diff --git a/.editorconfig b/.editorconfig index 65e690fff..114fbeb29 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,3 +3,10 @@ root = true [CMakeLists.txt] indent_style = tab indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{rcss,rml}] +indent_style = tab +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/Backends/RmlUi_Backend.h b/Backends/RmlUi_Backend.h index 49a67d688..7015c91e5 100644 --- a/Backends/RmlUi_Backend.h +++ b/Backends/RmlUi_Backend.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Backend_GLFW_GL2.cpp b/Backends/RmlUi_Backend_GLFW_GL2.cpp index 3b2b888eb..327f6786e 100644 --- a/Backends/RmlUi_Backend_GLFW_GL2.cpp +++ b/Backends/RmlUi_Backend_GLFW_GL2.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -148,9 +148,10 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call data->context = context; data->key_down_callback = key_down_callback; - if(power_save) + if (power_save) glfwWaitEventsTimeout(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)); - else glfwPollEvents(); + else + glfwPollEvents(); data->context = nullptr; data->key_down_callback = nullptr; @@ -220,9 +221,7 @@ static void SetupCallbacks(GLFWwindow* window) break; } break; - case GLFW_RELEASE: - RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods); - break; + case GLFW_RELEASE: RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods); break; } }); diff --git a/Backends/RmlUi_Backend_GLFW_GL3.cpp b/Backends/RmlUi_Backend_GLFW_GL3.cpp index a9b967069..9d6826317 100644 --- a/Backends/RmlUi_Backend_GLFW_GL3.cpp +++ b/Backends/RmlUi_Backend_GLFW_GL3.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -160,9 +160,10 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call data->context = context; data->key_down_callback = key_down_callback; - if(power_save) + if (power_save) glfwWaitEventsTimeout(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)); - else glfwPollEvents(); + else + glfwPollEvents(); data->context = nullptr; data->key_down_callback = nullptr; @@ -232,9 +233,7 @@ static void SetupCallbacks(GLFWwindow* window) break; } break; - case GLFW_RELEASE: - RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods); - break; + case GLFW_RELEASE: RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods); break; } }); diff --git a/Backends/RmlUi_Backend_GLFW_VK.cpp b/Backends/RmlUi_Backend_GLFW_VK.cpp index c1cf80f68..a2f704fed 100644 --- a/Backends/RmlUi_Backend_GLFW_VK.cpp +++ b/Backends/RmlUi_Backend_GLFW_VK.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -291,4 +291,4 @@ static void SetupCallbacks(GLFWwindow* window) glfwSetWindowContentScaleCallback(window, [](GLFWwindow* /*window*/, float xscale, float /*yscale*/) { RmlGLFW::ProcessContentScaleCallback(data->context, xscale); }); -} \ No newline at end of file +} diff --git a/Backends/RmlUi_Backend_SDL_GL2.cpp b/Backends/RmlUi_Backend_SDL_GL2.cpp index 5698e0e88..85204f6d7 100644 --- a/Backends/RmlUi_Backend_SDL_GL2.cpp +++ b/Backends/RmlUi_Backend_SDL_GL2.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -265,9 +265,10 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call SDL_Event ev; int has_event = 0; - if(power_save) - has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)*1000)); - else has_event = SDL_PollEvent(&ev); + if (power_save) + has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000)); + else + has_event = SDL_PollEvent(&ev); while (has_event) { switch (ev.type) diff --git a/Backends/RmlUi_Backend_SDL_GL3.cpp b/Backends/RmlUi_Backend_SDL_GL3.cpp index 372cb1ca8..0b615b4e9 100644 --- a/Backends/RmlUi_Backend_SDL_GL3.cpp +++ b/Backends/RmlUi_Backend_SDL_GL3.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -244,9 +244,10 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call SDL_Event ev; int has_event = 0; - if(power_save) - has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)*1000)); - else has_event = SDL_PollEvent(&ev); + if (power_save) + has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000)); + else + has_event = SDL_PollEvent(&ev); while (has_event) { switch (ev.type) diff --git a/Backends/RmlUi_Backend_SDL_SDLrenderer.cpp b/Backends/RmlUi_Backend_SDL_SDLrenderer.cpp index b74bc6da2..893ded18d 100644 --- a/Backends/RmlUi_Backend_SDL_SDLrenderer.cpp +++ b/Backends/RmlUi_Backend_SDL_SDLrenderer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -129,11 +129,12 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call bool result = data->running; SDL_Event ev; - + int has_event = 0; - if(power_save) - has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)*1000)); - else has_event = SDL_PollEvent(&ev); + if (power_save) + has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000)); + else + has_event = SDL_PollEvent(&ev); while (has_event) { switch (ev.type) diff --git a/Backends/RmlUi_Backend_SDL_VK.cpp b/Backends/RmlUi_Backend_SDL_VK.cpp index 1120a6c15..d90ae4d39 100644 --- a/Backends/RmlUi_Backend_SDL_VK.cpp +++ b/Backends/RmlUi_Backend_SDL_VK.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -79,14 +79,14 @@ bool Backend::Initialize(const char* window_name, int width, int height, bool al Rml::Vector extensions; { unsigned int count; - if(!SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr)) + if (!SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr)) { data.reset(); fprintf(stderr, "Could not get required vulkan extensions"); return false; } extensions.resize(count); - if(!SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data())) + if (!SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data())) { data.reset(); fprintf(stderr, "Could not get required vulkan extensions"); @@ -167,9 +167,10 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call SDL_Event ev; int has_event = 0; - if(power_save) - has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)*1000)); - else has_event = SDL_PollEvent(&ev); + if (power_save) + has_event = SDL_WaitEventTimeout(&ev, static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000)); + else + has_event = SDL_PollEvent(&ev); while (has_event) { switch (ev.type) diff --git a/Backends/RmlUi_Backend_SFML_GL2.cpp b/Backends/RmlUi_Backend_SFML_GL2.cpp index f15e2043d..08060370e 100644 --- a/Backends/RmlUi_Backend_SFML_GL2.cpp +++ b/Backends/RmlUi_Backend_SFML_GL2.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -205,9 +205,7 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call { switch (ev.type) { - case sf::Event::Resized: - UpdateWindowDimensions(data->window, data->render_interface, context); - break; + case sf::Event::Resized: UpdateWindowDimensions(data->window, data->render_interface, context); break; case sf::Event::KeyPressed: { const Rml::Input::KeyIdentifier key = RmlSFML::ConvertKey(ev.key.code); @@ -225,12 +223,8 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call break; } break; - case sf::Event::Closed: - result = false; - break; - default: - RmlSFML::InputHandler(context, ev); - break; + case sf::Event::Closed: result = false; break; + default: RmlSFML::InputHandler(context, ev); break; } } diff --git a/Backends/RmlUi_Backend_Win32_GL2.cpp b/Backends/RmlUi_Backend_Win32_GL2.cpp index 981525061..246dafee9 100644 --- a/Backends/RmlUi_Backend_Win32_GL2.cpp +++ b/Backends/RmlUi_Backend_Win32_GL2.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -191,12 +191,12 @@ Rml::RenderInterface* Backend::GetRenderInterface() static bool NextEvent(MSG& message, UINT timeout) { - if(timeout != 0) + if (timeout != 0) { UINT_PTR timer_id = SetTimer(NULL, NULL, timeout, NULL); BOOL res = GetMessage(&message, NULL, 0, 0); KillTimer(NULL, timer_id); - if(message.message != WM_TIMER || message.hwnd != nullptr || message.wParam != timer_id) + if (message.message != WM_TIMER || message.hwnd != nullptr || message.wParam != timer_id) return res; } return PeekMessage(&message, nullptr, 0, 0, PM_REMOVE); @@ -219,7 +219,7 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call data->key_down_callback = key_down_callback; MSG message; - bool has_message = NextEvent(message, power_save ? static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)*1000.0) : 0); + bool has_message = NextEvent(message, power_save ? static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000.0) : 0); while (has_message) { // Dispatch the message to our local event handler below. @@ -461,4 +461,4 @@ static void DetachFromNative(HWND window_handle, HDC device_context, HGLRC rende { ReleaseDC(window_handle, device_context); } -} \ No newline at end of file +} diff --git a/Backends/RmlUi_Backend_Win32_VK.cpp b/Backends/RmlUi_Backend_Win32_VK.cpp index 3cbbd7a6b..cdad95db7 100644 --- a/Backends/RmlUi_Backend_Win32_VK.cpp +++ b/Backends/RmlUi_Backend_Win32_VK.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -193,12 +193,12 @@ Rml::RenderInterface* Backend::GetRenderInterface() static bool NextEvent(MSG& message, UINT timeout) { - if(timeout != 0) + if (timeout != 0) { UINT_PTR timer_id = SetTimer(NULL, NULL, timeout, NULL); BOOL res = GetMessage(&message, NULL, 0, 0); KillTimer(NULL, timer_id); - if(message.message != WM_TIMER || message.hwnd != nullptr || message.wParam != timer_id) + if (message.message != WM_TIMER || message.hwnd != nullptr || message.wParam != timer_id) return res; } return PeekMessage(&message, nullptr, 0, 0, PM_REMOVE); @@ -222,10 +222,10 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call MSG message; // Process events. - bool has_message = NextEvent(message, power_save ? static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0)*1000.0) : 0); + bool has_message = NextEvent(message, power_save ? static_cast(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000.0) : 0); while (has_message || !data->render_interface.IsSwapchainValid()) { - if(has_message) + if (has_message) { // Dispatch the message to our local event handler below. TranslateMessage(&message); @@ -237,7 +237,7 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call // we trap the application inside this loop until we are able to recreate the swapchain and render again. if (!data->render_interface.IsSwapchainValid()) data->render_interface.RecreateSwapchain(); - + has_message = NextEvent(message, 0); } diff --git a/Backends/RmlUi_Backend_X11_GL2.cpp b/Backends/RmlUi_Backend_X11_GL2.cpp index ee570a0ca..bc4ebe72a 100644 --- a/Backends/RmlUi_Backend_X11_GL2.cpp +++ b/Backends/RmlUi_Backend_X11_GL2.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -48,7 +49,6 @@ #include #include #include -#include // Attach the OpenGL context to the window. static bool AttachToNative(GLXContext& out_gl_context, Display* display, Window window, XVisualInfo* visual_info) @@ -215,24 +215,26 @@ bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_call bool result = data->running; data->running = true; - if(power_save && XPending(display) == 0) { + if (power_save && XPending(display) == 0) + { int display_fd = ConnectionNumber(display); fd_set fds{}; FD_ZERO(&fds); - FD_SET(display_fd, &fds); + FD_SET(display_fd, &fds); double timeout = Rml::Math::Min(context->GetNextUpdateDelay(), 10.0); - struct timeval tv{}; + struct timeval tv {}; double seconds; - tv.tv_usec = std::modf(timeout, &seconds)*1000000.0; - tv.tv_sec = seconds; + tv.tv_usec = std::modf(timeout, &seconds) * 1000000.0; + tv.tv_sec = seconds; int ready_fd_count; - do { + do + { ready_fd_count = select(display_fd + 1, &fds, NULL, NULL, &tv); // We don't care about the return value as long as select didn't error out RMLUI_ASSERT(ready_fd_count >= 0); - } while(XPending(display) == 0 && ready_fd_count != 0); + } while (XPending(display) == 0 && ready_fd_count != 0); } while (XPending(display) > 0) diff --git a/Backends/RmlUi_Include_Windows.h b/Backends/RmlUi_Include_Windows.h index 90db37da2..3f781b867 100644 --- a/Backends/RmlUi_Include_Windows.h +++ b/Backends/RmlUi_Include_Windows.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Include_Xlib.h b/Backends/RmlUi_Include_Xlib.h index f308852bb..1e172f27f 100644 --- a/Backends/RmlUi_Include_Xlib.h +++ b/Backends/RmlUi_Include_Xlib.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Platform_GLFW.cpp b/Backends/RmlUi_Platform_GLFW.cpp index 07423c4c4..5b12cbc7c 100644 --- a/Backends/RmlUi_Platform_GLFW.cpp +++ b/Backends/RmlUi_Platform_GLFW.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -110,9 +110,7 @@ bool RmlGLFW::ProcessKeyCallback(Rml::Context* context, int key, int action, int if (key == GLFW_KEY_ENTER || key == GLFW_KEY_KP_ENTER) result &= context->ProcessTextInput('\n'); break; - case GLFW_RELEASE: - result = context->ProcessKeyUp(RmlGLFW::ConvertKey(key), RmlGLFW::ConvertKeyModifiers(mods)); - break; + case GLFW_RELEASE: result = context->ProcessKeyUp(RmlGLFW::ConvertKey(key), RmlGLFW::ConvertKeyModifiers(mods)); break; } return result; @@ -155,12 +153,8 @@ bool RmlGLFW::ProcessMouseButtonCallback(Rml::Context* context, int button, int switch (action) { - case GLFW_PRESS: - result = context->ProcessMouseButtonDown(button, RmlGLFW::ConvertKeyModifiers(mods)); - break; - case GLFW_RELEASE: - result = context->ProcessMouseButtonUp(button, RmlGLFW::ConvertKeyModifiers(mods)); - break; + case GLFW_PRESS: result = context->ProcessMouseButtonDown(button, RmlGLFW::ConvertKeyModifiers(mods)); break; + case GLFW_RELEASE: result = context->ProcessMouseButtonUp(button, RmlGLFW::ConvertKeyModifiers(mods)); break; } return result; } diff --git a/Backends/RmlUi_Platform_GLFW.h b/Backends/RmlUi_Platform_GLFW.h index f200d3700..fa6457938 100644 --- a/Backends/RmlUi_Platform_GLFW.h +++ b/Backends/RmlUi_Platform_GLFW.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Platform_SDL.cpp b/Backends/RmlUi_Platform_SDL.cpp index dbc904082..8269dc21d 100644 --- a/Backends/RmlUi_Platform_SDL.cpp +++ b/Backends/RmlUi_Platform_SDL.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -110,9 +110,7 @@ bool RmlSDL::InputEventHandler(Rml::Context* context, SDL_Event& ev) switch (ev.type) { - case SDL_MOUSEMOTION: - result = context->ProcessMouseMove(ev.motion.x, ev.motion.y, GetKeyModifierState()); - break; + case SDL_MOUSEMOTION: result = context->ProcessMouseMove(ev.motion.x, ev.motion.y, GetKeyModifierState()); break; case SDL_MOUSEBUTTONDOWN: result = context->ProcessMouseButtonDown(ConvertMouseButton(ev.button.button), GetKeyModifierState()); SDL_CaptureMouse(SDL_TRUE); @@ -121,20 +119,14 @@ bool RmlSDL::InputEventHandler(Rml::Context* context, SDL_Event& ev) SDL_CaptureMouse(SDL_FALSE); result = context->ProcessMouseButtonUp(ConvertMouseButton(ev.button.button), GetKeyModifierState()); break; - case SDL_MOUSEWHEEL: - result = context->ProcessMouseWheel(float(-ev.wheel.y), GetKeyModifierState()); - break; + case SDL_MOUSEWHEEL: result = context->ProcessMouseWheel(float(-ev.wheel.y), GetKeyModifierState()); break; case SDL_KEYDOWN: result = context->ProcessKeyDown(ConvertKey(ev.key.keysym.sym), GetKeyModifierState()); if (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_KP_ENTER) result &= context->ProcessTextInput('\n'); break; - case SDL_KEYUP: - result = context->ProcessKeyUp(ConvertKey(ev.key.keysym.sym), GetKeyModifierState()); - break; - case SDL_TEXTINPUT: - result = context->ProcessTextInput(Rml::String(&ev.text.text[0])); - break; + case SDL_KEYUP: result = context->ProcessKeyUp(ConvertKey(ev.key.keysym.sym), GetKeyModifierState()); break; + case SDL_TEXTINPUT: result = context->ProcessTextInput(Rml::String(&ev.text.text[0])); break; case SDL_WINDOWEVENT: { switch (ev.window.event) @@ -145,14 +137,11 @@ bool RmlSDL::InputEventHandler(Rml::Context* context, SDL_Event& ev) context->SetDimensions(dimensions); } break; - case SDL_WINDOWEVENT_LEAVE: - context->ProcessMouseLeave(); - break; + case SDL_WINDOWEVENT_LEAVE: context->ProcessMouseLeave(); break; } } break; - default: - break; + default: break; } return result; @@ -287,14 +276,10 @@ int RmlSDL::ConvertMouseButton(int button) { switch (button) { - case SDL_BUTTON_LEFT: - return 0; - case SDL_BUTTON_RIGHT: - return 1; - case SDL_BUTTON_MIDDLE: - return 2; - default: - return 3; + case SDL_BUTTON_LEFT: return 0; + case SDL_BUTTON_RIGHT: return 1; + case SDL_BUTTON_MIDDLE: return 2; + default: return 3; } } diff --git a/Backends/RmlUi_Platform_SDL.h b/Backends/RmlUi_Platform_SDL.h index c59480a98..937a6b08e 100644 --- a/Backends/RmlUi_Platform_SDL.h +++ b/Backends/RmlUi_Platform_SDL.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Platform_SFML.cpp b/Backends/RmlUi_Platform_SFML.cpp index de41a94bf..bdc6e13d0 100644 --- a/Backends/RmlUi_Platform_SFML.cpp +++ b/Backends/RmlUi_Platform_SFML.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -100,21 +100,11 @@ bool RmlSFML::InputHandler(Rml::Context* context, sf::Event& ev) switch (ev.type) { - case sf::Event::MouseMoved: - result = context->ProcessMouseMove(ev.mouseMove.x, ev.mouseMove.y, RmlSFML::GetKeyModifierState()); - break; - case sf::Event::MouseButtonPressed: - result = context->ProcessMouseButtonDown(ev.mouseButton.button, RmlSFML::GetKeyModifierState()); - break; - case sf::Event::MouseButtonReleased: - result = context->ProcessMouseButtonUp(ev.mouseButton.button, RmlSFML::GetKeyModifierState()); - break; - case sf::Event::MouseWheelMoved: - result = context->ProcessMouseWheel(float(-ev.mouseWheel.delta), RmlSFML::GetKeyModifierState()); - break; - case sf::Event::MouseLeft: - result = context->ProcessMouseLeave(); - break; + case sf::Event::MouseMoved: result = context->ProcessMouseMove(ev.mouseMove.x, ev.mouseMove.y, RmlSFML::GetKeyModifierState()); break; + case sf::Event::MouseButtonPressed: result = context->ProcessMouseButtonDown(ev.mouseButton.button, RmlSFML::GetKeyModifierState()); break; + case sf::Event::MouseButtonReleased: result = context->ProcessMouseButtonUp(ev.mouseButton.button, RmlSFML::GetKeyModifierState()); break; + case sf::Event::MouseWheelMoved: result = context->ProcessMouseWheel(float(-ev.mouseWheel.delta), RmlSFML::GetKeyModifierState()); break; + case sf::Event::MouseLeft: result = context->ProcessMouseLeave(); break; case sf::Event::TextEntered: { Rml::Character character = Rml::Character(ev.text.unicode); @@ -125,14 +115,9 @@ bool RmlSFML::InputHandler(Rml::Context* context, sf::Event& ev) result = context->ProcessTextInput(character); } break; - case sf::Event::KeyPressed: - result = context->ProcessKeyDown(RmlSFML::ConvertKey(ev.key.code), RmlSFML::GetKeyModifierState()); - break; - case sf::Event::KeyReleased: - result = context->ProcessKeyUp(RmlSFML::ConvertKey(ev.key.code), RmlSFML::GetKeyModifierState()); - break; - default: - break; + case sf::Event::KeyPressed: result = context->ProcessKeyDown(RmlSFML::ConvertKey(ev.key.code), RmlSFML::GetKeyModifierState()); break; + case sf::Event::KeyReleased: result = context->ProcessKeyUp(RmlSFML::ConvertKey(ev.key.code), RmlSFML::GetKeyModifierState()); break; + default: break; } return result; diff --git a/Backends/RmlUi_Platform_SFML.h b/Backends/RmlUi_Platform_SFML.h index 0baecf18a..8763cb671 100644 --- a/Backends/RmlUi_Platform_SFML.h +++ b/Backends/RmlUi_Platform_SFML.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -42,7 +42,7 @@ class SystemInterface_SFML : public Rml::SystemInterface { // Optionally, provide or change the window to be used for setting the mouse cursors. // @lifetime Any window provided here must be destroyed before the system interface. - // @lifetime The currently active window must stay alive until after the call to Rml::Shutdown. + // @lifetime The currently active window must stay alive until after the call to Rml::Shutdown. void SetWindow(sf::RenderWindow* window); // -- Inherited from Rml::SystemInterface -- diff --git a/Backends/RmlUi_Platform_Win32.cpp b/Backends/RmlUi_Platform_Win32.cpp index 8e7d038a0..489a4581a 100644 --- a/Backends/RmlUi_Platform_Win32.cpp +++ b/Backends/RmlUi_Platform_Win32.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -204,18 +204,10 @@ bool RmlWin32::WindowProcedure(Rml::Context* context, HWND window_handle, UINT m ReleaseCapture(); result = context->ProcessMouseButtonUp(0, RmlWin32::GetKeyModifierState()); break; - case WM_RBUTTONDOWN: - result = context->ProcessMouseButtonDown(1, RmlWin32::GetKeyModifierState()); - break; - case WM_RBUTTONUP: - result = context->ProcessMouseButtonUp(1, RmlWin32::GetKeyModifierState()); - break; - case WM_MBUTTONDOWN: - result = context->ProcessMouseButtonDown(2, RmlWin32::GetKeyModifierState()); - break; - case WM_MBUTTONUP: - result = context->ProcessMouseButtonUp(2, RmlWin32::GetKeyModifierState()); - break; + case WM_RBUTTONDOWN: result = context->ProcessMouseButtonDown(1, RmlWin32::GetKeyModifierState()); break; + case WM_RBUTTONUP: result = context->ProcessMouseButtonUp(1, RmlWin32::GetKeyModifierState()); break; + case WM_MBUTTONDOWN: result = context->ProcessMouseButtonDown(2, RmlWin32::GetKeyModifierState()); break; + case WM_MBUTTONUP: result = context->ProcessMouseButtonUp(2, RmlWin32::GetKeyModifierState()); break; case WM_MOUSEMOVE: result = context->ProcessMouseMove(static_cast((short)LOWORD(l_param)), static_cast((short)HIWORD(l_param)), RmlWin32::GetKeyModifierState()); @@ -237,12 +229,8 @@ bool RmlWin32::WindowProcedure(Rml::Context* context, HWND window_handle, UINT m result = context->ProcessMouseLeave(); tracking_mouse_leave = false; break; - case WM_KEYDOWN: - result = context->ProcessKeyDown(RmlWin32::ConvertKey((int)w_param), RmlWin32::GetKeyModifierState()); - break; - case WM_KEYUP: - result = context->ProcessKeyUp(RmlWin32::ConvertKey((int)w_param), RmlWin32::GetKeyModifierState()); - break; + case WM_KEYDOWN: result = context->ProcessKeyDown(RmlWin32::ConvertKey((int)w_param), RmlWin32::GetKeyModifierState()); break; + case WM_KEYUP: result = context->ProcessKeyUp(RmlWin32::ConvertKey((int)w_param), RmlWin32::GetKeyModifierState()); break; case WM_CHAR: { static wchar_t first_u16_code_unit = 0; @@ -278,8 +266,7 @@ bool RmlWin32::WindowProcedure(Rml::Context* context, HWND window_handle, UINT m } } break; - default: - break; + default: break; } return result; diff --git a/Backends/RmlUi_Platform_Win32.h b/Backends/RmlUi_Platform_Win32.h index 87538f686..b040c3501 100644 --- a/Backends/RmlUi_Platform_Win32.h +++ b/Backends/RmlUi_Platform_Win32.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Platform_X11.cpp b/Backends/RmlUi_Platform_X11.cpp index 59437db03..f82fcb22a 100644 --- a/Backends/RmlUi_Platform_X11.cpp +++ b/Backends/RmlUi_Platform_X11.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -247,14 +247,10 @@ bool RmlX11::HandleInputEvent(Rml::Context* context, Display* display, const XEv { case Button1: case Button2: - case Button3: - return context->ProcessMouseButtonDown(ConvertMouseButton(ev.xbutton.button), RmlX11::GetKeyModifierState(ev.xbutton.state)); - case Button4: - return context->ProcessMouseWheel(-1, RmlX11::GetKeyModifierState(ev.xbutton.state)); - case Button5: - return context->ProcessMouseWheel(1, RmlX11::GetKeyModifierState(ev.xbutton.state)); - default: - return true; + case Button3: return context->ProcessMouseButtonDown(ConvertMouseButton(ev.xbutton.button), RmlX11::GetKeyModifierState(ev.xbutton.state)); + case Button4: return context->ProcessMouseWheel(-1, RmlX11::GetKeyModifierState(ev.xbutton.state)); + case Button5: return context->ProcessMouseWheel(1, RmlX11::GetKeyModifierState(ev.xbutton.state)); + default: return true; } } break; @@ -264,10 +260,8 @@ bool RmlX11::HandleInputEvent(Rml::Context* context, Display* display, const XEv { case Button1: case Button2: - case Button3: - return context->ProcessMouseButtonUp(ConvertMouseButton(ev.xbutton.button), RmlX11::GetKeyModifierState(ev.xbutton.state)); - default: - return true; + case Button3: return context->ProcessMouseButtonUp(ConvertMouseButton(ev.xbutton.button), RmlX11::GetKeyModifierState(ev.xbutton.state)); + default: return true; } } break; @@ -311,8 +305,7 @@ bool RmlX11::HandleInputEvent(Rml::Context* context, Display* display, const XEv return propagates; } break; - default: - break; + default: break; } return true; @@ -391,7 +384,7 @@ Rml::Input::KeyIdentifier RmlX11::ConvertKey(Display* display, unsigned int x11_ { RMLUI_ASSERT(display); const XKeyData& key_data = GetXKeyData(display); - + const int group_index = 0; // this is always 0 for our limited example KeySym sym = {}; @@ -573,14 +566,10 @@ int RmlX11::ConvertMouseButton(unsigned int x11_mouse_button) { switch (x11_mouse_button) { - case Button1: - return 0; - case Button2: - return 2; - case Button3: - return 1; - default: - break; + case Button1: return 0; + case Button2: return 2; + case Button3: return 1; + default: break; } return 0; } diff --git a/Backends/RmlUi_Platform_X11.h b/Backends/RmlUi_Platform_X11.h index f07d428e2..e3e00c6cd 100644 --- a/Backends/RmlUi_Platform_X11.h +++ b/Backends/RmlUi_Platform_X11.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_GL2.cpp b/Backends/RmlUi_Renderer_GL2.cpp index e229273be..047b55a7d 100644 --- a/Backends/RmlUi_Renderer_GL2.cpp +++ b/Backends/RmlUi_Renderer_GL2.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_GL2.h b/Backends/RmlUi_Renderer_GL2.h index 543569511..08c403376 100644 --- a/Backends/RmlUi_Renderer_GL2.h +++ b/Backends/RmlUi_Renderer_GL2.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_GL3.cpp b/Backends/RmlUi_Renderer_GL3.cpp index 153cf4f20..8875aabd2 100644 --- a/Backends/RmlUi_Renderer_GL3.cpp +++ b/Backends/RmlUi_Renderer_GL3.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_GL3.h b/Backends/RmlUi_Renderer_GL3.h index 8bc8659d2..138f075a6 100644 --- a/Backends/RmlUi_Renderer_GL3.h +++ b/Backends/RmlUi_Renderer_GL3.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_SDL.cpp b/Backends/RmlUi_Renderer_SDL.cpp index 861926acf..742d6395e 100644 --- a/Backends/RmlUi_Renderer_SDL.cpp +++ b/Backends/RmlUi_Renderer_SDL.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_SDL.h b/Backends/RmlUi_Renderer_SDL.h index 6bfefa149..2f4031eb7 100644 --- a/Backends/RmlUi_Renderer_SDL.h +++ b/Backends/RmlUi_Renderer_SDL.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Backends/RmlUi_Renderer_VK.cpp b/Backends/RmlUi_Renderer_VK.cpp index 0f7ca6920..841a3c258 100644 --- a/Backends/RmlUi_Renderer_VK.cpp +++ b/Backends/RmlUi_Renderer_VK.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -85,10 +85,10 @@ static VKAPI_ATTR VkBool32 VKAPI_CALL MyDebugReportCallback(VkDebugReportFlagsEX #endif RenderInterface_VK::RenderInterface_VK() : - m_is_transform_enabled{false}, m_is_apply_to_regular_geometry_stencil{false}, m_is_use_scissor_specified{false}, - m_is_use_stencil_pipeline{false}, m_width{}, m_height{}, m_queue_index_present{}, m_queue_index_graphics{}, m_queue_index_compute{}, - m_semaphore_index{}, m_semaphore_index_previous{}, m_image_index{}, m_p_instance{}, m_p_device{}, m_p_physical_device{}, m_p_surface{}, - m_p_swapchain{}, m_p_allocator{}, m_p_current_command_buffer{}, m_p_descriptor_set_layout_vertex_transform{}, m_p_descriptor_set_layout_texture{}, + m_is_transform_enabled{false}, m_is_apply_to_regular_geometry_stencil{false}, m_is_use_scissor_specified{false}, m_is_use_stencil_pipeline{false}, + m_width{}, m_height{}, m_queue_index_present{}, m_queue_index_graphics{}, m_queue_index_compute{}, m_semaphore_index{}, + m_semaphore_index_previous{}, m_image_index{}, m_p_instance{}, m_p_device{}, m_p_physical_device{}, m_p_surface{}, m_p_swapchain{}, + m_p_allocator{}, m_p_current_command_buffer{}, m_p_descriptor_set_layout_vertex_transform{}, m_p_descriptor_set_layout_texture{}, m_p_pipeline_layout{}, m_p_pipeline_with_textures{}, m_p_pipeline_without_textures{}, m_p_pipeline_stencil_for_region_where_geometry_will_be_drawn{}, m_p_pipeline_stencil_for_regular_geometry_that_applied_to_region_with_textures{}, m_p_pipeline_stencil_for_regular_geometry_that_applied_to_region_without_textures{}, m_p_descriptor_set{}, m_p_render_pass{}, @@ -365,7 +365,8 @@ void RenderInterface_VK::SetScissorRegion(int x, int y, int width, int height) info_range.levelCount = 1; info_range.layerCount = 1; - vkCmdClearDepthStencilImage(m_p_current_command_buffer, m_texture_depthstencil.m_p_vk_image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, &info_clear_color, 1, &info_range); + vkCmdClearDepthStencilImage(m_p_current_command_buffer, m_texture_depthstencil.m_p_vk_image, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, &info_clear_color, 1, &info_range); RenderGeometry(vertices, 4, indices, 6, 0, Rml::Vector2f(0.0f, 0.0f)); @@ -1693,9 +1694,12 @@ VkSurfaceFormatKHR RenderInterface_VK::ChooseSwapchainFormat() noexcept RMLUI_VK_ASSERTMSG(status == VK_SUCCESS, "failed to vkGetPhysicalDeviceSurfaceFormatsKHR (filling vector of VkSurfaceFormatKHR)"); // Prefer UNORM formats - for(auto& format : formats) { - for(auto ufmt : UNORM_FORMATS) { - if(ufmt == format.format) return format; + for (auto& format : formats) + { + for (auto ufmt : UNORM_FORMATS) + { + if (ufmt == format.format) + return format; } } @@ -2799,8 +2803,8 @@ VkCommandBuffer RenderInterface_VK::CommandBufferRing::GetCommandBufferForActive } RenderInterface_VK::MemoryPool::MemoryPool() : - m_memory_total_size{}, m_device_min_uniform_alignment{}, m_p_data{}, m_p_buffer{}, m_p_buffer_alloc{}, m_p_device{}, - m_p_vk_allocator{}, m_p_block{} + m_memory_total_size{}, m_device_min_uniform_alignment{}, m_p_data{}, m_p_buffer{}, m_p_buffer_alloc{}, m_p_device{}, m_p_vk_allocator{}, + m_p_block{} {} RenderInterface_VK::MemoryPool::~MemoryPool() {} diff --git a/Backends/RmlUi_Renderer_VK.h b/Backends/RmlUi_Renderer_VK.h index 76ed50f5d..b32e8d1f8 100644 --- a/Backends/RmlUi_Renderer_VK.h +++ b/Backends/RmlUi_Renderer_VK.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -66,7 +66,7 @@ RMLUI_DISABLE_ALL_COMPILER_WARNINGS_PUSH #if defined(RMLUI_PLATFORM_UNIX) -#define VK_USE_PLATFORM_XCB_KHR 1 + #define VK_USE_PLATFORM_XCB_KHR 1 #endif #include "RmlUi_Vulkan/vulkan.h" @@ -80,7 +80,7 @@ RMLUI_DISABLE_ALL_COMPILER_WARNINGS_POP #define RMLUI_VK_ASSERTMSG(statement, msg) RMLUI_ASSERTMSG(statement, msg) // Uncomment the following line to enable additional Vulkan debugging. - //#define RMLUI_VK_DEBUG + // #define RMLUI_VK_DEBUG #else #define RMLUI_VK_ASSERTMSG(statement, msg) static_cast(statement) #endif diff --git a/Backends/RmlUi_Vulkan/.clang-format b/Backends/RmlUi_Vulkan/.clang-format new file mode 100644 index 000000000..47a38a93f --- /dev/null +++ b/Backends/RmlUi_Vulkan/.clang-format @@ -0,0 +1,2 @@ +DisableFormat: true +SortIncludes: Never diff --git a/Backends/RmlUi_Vulkan/compile_shaders.py b/Backends/RmlUi_Vulkan/compile_shaders.py index 8ce9f6328..19af6e7ff 100644 --- a/Backends/RmlUi_Vulkan/compile_shaders.py +++ b/Backends/RmlUi_Vulkan/compile_shaders.py @@ -3,7 +3,7 @@ # For the latest information, see http://github.com/mikke89/RmlUi # # Copyright (c) 2008-2014 CodePoint Ltd, Shift Technology Ltd, and contributors -# Copyright (c) 2019 The RmlUi Team, and contributors +# Copyright (c) 2019-2023 The RmlUi Team, and contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/CMake/BackendFileList.cmake b/CMake/BackendFileList.cmake index 979a2cff8..50b45bb9a 100644 --- a/CMake/BackendFileList.cmake +++ b/CMake/BackendFileList.cmake @@ -27,7 +27,7 @@ set(Win32_VK_HDR_FILES set(X11_GL2_SRC_FILES ${PROJECT_SOURCE_DIR}/Backends/RmlUi_Platform_X11.cpp - ${PROJECT_SOURCE_DIR}/Backends/RmlUi_Renderer_GL2.cpp + ${PROJECT_SOURCE_DIR}/Backends/RmlUi_Renderer_GL2.cpp ${PROJECT_SOURCE_DIR}/Backends/RmlUi_Backend_X11_GL2.cpp ) set(X11_GL2_HDR_FILES @@ -118,4 +118,4 @@ set(GLFW_VK_SRC_FILES set(GLFW_VK_HDR_FILES ${PROJECT_SOURCE_DIR}/Backends/RmlUi_Platform_GLFW.h ${PROJECT_SOURCE_DIR}/Backends/RmlUi_Renderer_VK.h -) \ No newline at end of file +) diff --git a/CMake/FindLuaJIT.cmake b/CMake/Modules/FindLuaJIT.cmake similarity index 100% rename from CMake/FindLuaJIT.cmake rename to CMake/Modules/FindLuaJIT.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index d8dce149b..f4020f43a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,7 +5,7 @@ cmake_minimum_required(VERSION 3.1) if(APPLE) - # This has to be before most other options so CMake properly handles the + # This has to be before most other options so CMake properly handles the # compiler variables, it MUST bebefore the project() definition if(IOS_PLATFORM) set(CMAKE_TOOLCHAIN_FILE CMake/Platform/iOS.cmake) @@ -14,7 +14,7 @@ if(APPLE) option(BUILD_UNIVERSAL_BINARIES "Build universal binaries for all architectures supported" ON) if (NOT CMAKE_OSX_ARCHITECTURES AND BUILD_UNIVERSAL_BINARIES) if(IOS) - # set the architecture for iOS + # set the architecture for iOS if (${IOS_PLATFORM} STREQUAL "OS") set (IOS_ARCH armv6 armv7 armv7s arm64) set (CMAKE_OSX_ARCHITECTURES ${IOS_ARCH} CACHE STRING "Build architecture for iOS") @@ -35,12 +35,12 @@ if(COMMAND cmake_policy) cmake_policy(SET CMP0015 NEW) endif(COMMAND cmake_policy) -# Enable the use of MACOSX_RPATH by default for CMake v3.0+; this effectively -# allows plug 'n' play functionality, so to speak -- the resulting shared -# library files can simply be copied over into the end-user's application +# Enable the use of MACOSX_RPATH by default for CMake v3.0+; this effectively +# allows plug 'n' play functionality, so to speak -- the resulting shared +# library files can simply be copied over into the end-user's application # bundle or framework bundle. No mucking around with install_name_tool. # -# See also: +# See also: # cmake --help-policy cmp0042 # http://www.kitware.com/blog/home/post/510 if(POLICY CMP0042) @@ -70,7 +70,7 @@ list(APPEND CORE_PRIVATE_DEFS RMLUI_VERSION="${RMLUI_VERSION_SHORT}") if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) option(BUILD_TESTING "" OFF) include(CTest) - + if(BUILD_TESTING) set(RMLUI_TESTS_ENABLED ON) set(VISUAL_TESTS_RML_DIRECTORIES "" CACHE PATH "Specify additional directories containing *.rml test documents for VisualTests. Separate multiple directories by comma.") @@ -248,7 +248,7 @@ if( CUSTOM_CONFIGURATION ) mark_as_advanced( CLEAR CUSTOM_CONFIGURATION_FILE CUSTOM_INCLUDE_DIRS CUSTOM_LINK_LIBRARIES ) else() mark_as_advanced( FORCE CUSTOM_CONFIGURATION_FILE CUSTOM_INCLUDE_DIRS CUSTOM_LINK_LIBRARIES ) - + if( CUSTOM_CONFIGURATION_FILE OR CUSTOM_INCLUDE_DIRS OR CUSTOM_LINK_LIBRARIES ) message("-- CUSTOM_CONFIGURATION disabled, but custom configuration variables are set. They will have no effect.") endif() @@ -302,7 +302,7 @@ mark_as_advanced(WARNINGS_AS_ERRORS) macro(add_common_target_options NAME) # C++ language version if(CMAKE_VERSION VERSION_LESS 3.8.0) - set_target_properties(${NAME} PROPERTIES + set_target_properties(${NAME} PROPERTIES CXX_STANDARD 14 CXX_STANDARD_REQUIRED YES ) @@ -310,18 +310,18 @@ macro(add_common_target_options NAME) target_compile_features(${NAME} PUBLIC cxx_std_14) endif() set_target_properties(${NAME} PROPERTIES CXX_EXTENSIONS OFF) - + # Compiler warnings if(CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR CMAKE_CXX_COMPILER_ID MATCHES "GNU") target_compile_options(${NAME} PRIVATE -Wall -pedantic -Wextra) - + if(WARNINGS_AS_ERRORS) target_compile_options(${NAME} PRIVATE -Werror) endif() elseif(MSVC) target_compile_options(${NAME} PRIVATE /MP /W4 /w44062 /permissive-) target_compile_definitions(${NAME} PRIVATE _CRT_SECURE_NO_WARNINGS) - + if(WARNINGS_AS_ERRORS) target_compile_options(${NAME} PRIVATE /WX) endif() @@ -352,7 +352,7 @@ if(NOT NO_FONT_INTERFACE_DEFAULT) if(MSVC AND FREETYPE_VERSION_STRING STREQUAL "2.11.0") message(WARNING "You are using FreeType version 2.11.0 which introduced an issue that causes a crash on startup on some of the samples. Please avoid this version specifically.") endif() - + list(APPEND CORE_LINK_LIBS ${FREETYPE_LIBRARIES}) list(APPEND CORE_INCLUDE_DIRS ${FREETYPE_INCLUDE_DIRS}) endif() @@ -384,14 +384,14 @@ elseif( ENABLE_LOTTIE_PLUGIN ) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/rlottie/build) find_package(rlottie CONFIG) find_path(rlottie_INCLUDE_DIR rlottie.h HINTS ${rlottie_DIR} $ENV{rlottie_DIR} PATH_SUFFIXES inc rlottie/inc ) - + if(rlottie_FOUND AND rlottie_INCLUDE_DIR) message("-- Can Lottie plugin be added to RmlCore - yes - rlottie library found") - + list(APPEND CORE_LINK_LIBS rlottie::rlottie) list(APPEND CORE_INCLUDE_DIRS ${rlottie_INCLUDE_DIR}) list(APPEND CORE_PRIVATE_DEFS RMLUI_ENABLE_LOTTIE_PLUGIN) - + list(APPEND Core_HDR_FILES ${Lottie_HDR_FILES}) list(APPEND Core_PUB_HDR_FILES ${Lottie_PUB_HDR_FILES}) list(APPEND Core_SRC_FILES ${Lottie_SRC_FILES}) @@ -411,15 +411,15 @@ if( ENABLE_SVG_PLUGIN ) if(NOT DEFINED LUNASVG_DIR) set(LUNASVG_DIR $ENV{LUNASVG_DIR}) endif() - + message("-- Can SVG plugin be enabled - looking for lunasvg library") find_package(lunasvg REQUIRED) - + list(APPEND CORE_LINK_LIBS ${LUNASVG_LIBRARIES}) list(APPEND CORE_INCLUDE_DIRS ${LUNASVG_INCLUDE_DIR}) list(APPEND CORE_PRIVATE_DEFS RMLUI_ENABLE_SVG_PLUGIN) - + list(APPEND Core_HDR_FILES ${SVG_HDR_FILES}) list(APPEND Core_PUB_HDR_FILES ${SVG_PUB_HDR_FILES}) list(APPEND Core_SRC_FILES ${SVG_SRC_FILES}) @@ -447,10 +447,10 @@ foreach(library ${LIBRARIES}) add_library(RmlUi::${library} ALIAS ${NAME}) set_target_properties(${NAME} PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR} + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} ) - + add_common_target_options(${NAME}) install(TARGETS ${NAME} @@ -556,10 +556,10 @@ if(BUILD_LUA_BINDINGS) ) set_target_properties(${NAME} PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR} + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} ) - + add_common_target_options(${NAME}) install(TARGETS ${NAME} @@ -568,7 +568,7 @@ if(BUILD_LUA_BINDINGS) ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) - + set(RMLUI_EXPORTED_TARGETS ${RMLUI_EXPORTED_TARGETS} ${NAME}) endif() @@ -642,7 +642,7 @@ macro(bl_sample NAME) else() add_executable(${NAME} ${${NAME}_SRC_FILES} ${${NAME}_HDR_FILES} ) endif() - + add_common_target_options(${NAME}) target_link_libraries(${NAME} ${ARGN}) @@ -651,10 +651,10 @@ endmacro() # Build shell if(BUILD_SAMPLES OR BUILD_TESTING) message("-- Adding shell with '${SAMPLES_BACKEND}' backend.") - + include(SampleFileList) include(BackendFileList) - + if(NOT BUILD_FRAMEWORK) set(sample_LIBRARIES shell @@ -672,28 +672,28 @@ if(BUILD_SAMPLES OR BUILD_TESTING) if(WIN32) mark_as_advanced(SAMPLES_DIR) endif() - + set(BACKEND_SRC_FILES "${${SAMPLES_BACKEND}_SRC_FILES}") set(BACKEND_HDR_FILES "${${SAMPLES_BACKEND}_HDR_FILES}") - + if("${BACKEND_SRC_FILES}" STREQUAL "" OR "${BACKEND_HDR_FILES}" STREQUAL "") message(FATAL_ERROR "Unknown samples backend '${SAMPLES_BACKEND}'.") endif() - + list(APPEND shell_SRC_FILES ${BACKEND_SRC_FILES}) list(APPEND shell_HDR_FILES ${BACKEND_HDR_FILES} ${BACKEND_COMMON_HDR_FILES}) - + add_library(shell STATIC ${shell_SRC_FILES} ${shell_HDR_FILES}) - + target_include_directories(shell PUBLIC ${PROJECT_SOURCE_DIR}/Backends ${PROJECT_SOURCE_DIR}/Samples/shell/include ) - + add_common_target_options(shell) target_link_libraries(shell PUBLIC RmlCore RmlDebugger) - + # Add OS dependencies. if (WIN32) target_link_libraries(shell PRIVATE shlwapi imm32) @@ -711,49 +711,49 @@ if(BUILD_SAMPLES OR BUILD_TESTING) endif() endif() endif() - + # Add platform dependencies. - if(SAMPLES_BACKEND MATCHES "^X11") + if(SAMPLES_BACKEND MATCHES "^X11") if(NOT X11_FOUND) message(FATAL_ERROR "X11 not found or not supported on this platform, select a different sample backend.") endif() endif() - + if(SAMPLES_BACKEND MATCHES "^SDL") message("-- Looking for SDL2 library for samples backend.") if(EMSCRIPTEN) set(EMSCRIPTEN_FLAGS "${EMSCRIPTEN_FLAGS} -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sSDL2_IMAGE_FORMATS='[tga]'") else() find_package(SDL2 REQUIRED) - + if(NOT SDL2_FOUND) message(FATAL_ERROR "SDL2 not found") endif() - + if(SAMPLES_BACKEND STREQUAL "SDL_GL2") find_package(GLEW REQUIRED) if(NOT GLEW_FOUND) message(FATAL_ERROR "GLEW not found") endif() endif() - + # Check version requirement for the SDL renderer. if(SAMPLES_BACKEND STREQUAL "SDL_SDLrenderer" AND "${SDL2_VERSION}" VERSION_LESS "2.0.20") message(FATAL_ERROR "SDL2 native renderer backend (${SAMPLES_BACKEND}) requires SDL 2.0.20 (found ${SDL2_VERSION}).") endif() - + if(SAMPLES_BACKEND STREQUAL "SDL_GL2" OR SAMPLES_BACKEND STREQUAL "SDL_GL3" OR SAMPLES_BACKEND STREQUAL "SDL_SDLrenderer") find_package(SDL2_image REQUIRED) if(NOT SDL2_IMAGE_FOUND) message(FATAL_ERROR "SDL2_image not found") endif() endif() - + target_include_directories(shell PRIVATE ${SDL2_INCLUDE_DIR} ${SDL2_IMAGE_INCLUDE_DIR} ${GLEW_INCLUDE_DIR}) target_link_libraries(shell PRIVATE ${SDL2_LIBRARY} ${SDL2_IMAGE_LIBRARY} ${GLEW_LIBRARIES}) endif() endif() - + if(SAMPLES_BACKEND MATCHES "^SFML") message("-- Looking for SFML 2.x library for samples backend.") if (WIN32) @@ -764,14 +764,14 @@ if(BUILD_SAMPLES OR BUILD_TESTING) target_include_directories(shell PRIVATE ${SFML_INCLUDE_DIR}) target_link_libraries(shell PRIVATE ${SFML_LIBRARIES}) endif() - + if(SAMPLES_BACKEND MATCHES "^GLFW") message("-- Looking for GLFW3 library for samples backend.") find_package(glfw3 3.3 CONFIG REQUIRED) target_link_libraries(shell PRIVATE glfw) message("-- Found GLFW version ${glfw3_VERSION}.") endif() - + # Add renderer dependencies. if(SAMPLES_BACKEND MATCHES "GL2$") message("-- Adding OpenGL 2 renderer backend.") @@ -783,19 +783,19 @@ if(BUILD_SAMPLES OR BUILD_TESTING) target_compile_definitions(shell PRIVATE GL_SILENCE_DEPRECATION) endif() endif() - + if(SAMPLES_BACKEND MATCHES "VK$") message("-- Using Vulkan renderer backend.") - + option(RMLUI_VK_DEBUG "Enable debugging mode for Vulkan renderer." OFF) mark_as_advanced(RMLUI_VK_DEBUG) if(RMLUI_VK_DEBUG) - target_compile_definitions(shell PRIVATE RMLUI_VK_DEBUG) + target_compile_definitions(shell PRIVATE RMLUI_VK_DEBUG) endif() target_link_libraries(shell PRIVATE ${CMAKE_DL_LIBS}) endif() - + if(SAMPLES_BACKEND MATCHES "GL3$") message("-- Adding OpenGL 3 renderer backend.") if(EMSCRIPTEN) @@ -830,7 +830,7 @@ if(BUILD_SAMPLES) # The samples always set this as their current working directory install(DIRECTORY DESTINATION ${SAMPLES_DIR}/basic/${sample}) - install(TARGETS ${sample} + install(TARGETS ${sample} RUNTIME DESTINATION ${SAMPLES_DIR}/${sample} BUNDLE DESTINATION ${SAMPLES_DIR}) endforeach() @@ -839,7 +839,7 @@ if(BUILD_SAMPLES) foreach(tutorial ${tutorials}) set(tutorial_fullname tutorial_${tutorial}) bl_sample(${tutorial_fullname} ${sample_LIBRARIES}) - + # The tutorials always set this as their current working directory install(DIRECTORY DESTINATION ${SAMPLES_DIR}/tutorial/${tutorial}) install(TARGETS ${tutorial_fullname} @@ -850,22 +850,22 @@ if(BUILD_SAMPLES) # Build and install invaders sample bl_sample(invaders ${sample_LIBRARIES}) install(DIRECTORY DESTINATION ${SAMPLES_DIR}/invaders) - install(TARGETS invaders + install(TARGETS invaders RUNTIME DESTINATION ${SAMPLES_DIR}/invaders BUNDLE DESTINATION ${SAMPLES_DIR}) if(BUILD_LUA_BINDINGS) bl_sample(luainvaders RmlLua ${sample_LIBRARIES} ${LUA_BINDINGS_LINK_LIBS}) install(DIRECTORY DESTINATION ${SAMPLES_DIR}/luainvaders) - install(TARGETS luainvaders + install(TARGETS luainvaders RUNTIME DESTINATION ${SAMPLES_DIR}/luainvaders BUNDLE DESTINATION ${SAMPLES_DIR}) endif() - + # Add assets to emscripten binaries if(EMSCRIPTEN) message("-- Preloading emscipten sample assets") - + set(COMMON_ASSET_FOLDER "Samples/assets/") set(EMSCRIPTEN_EXE_FLAGS "${EMSCRIPTEN_EXE_FLAGS} --preload-file ${CMAKE_CURRENT_SOURCE_DIR}/${COMMON_ASSET_FOLDER}@/${COMMON_ASSET_FOLDER}") @@ -876,7 +876,7 @@ if(BUILD_SAMPLES) target_link_libraries(${sample} "--preload-file ${ABS_SAMPLE_DATA_FOLDER}@/${SAMPLE_DATA_FOLDER}") endif() endforeach() - + foreach(tutorial ${tutorials}) set(TUTORIAL_DATA_FOLDER "Samples/tutorial/${tutorial}/data/") set(ABS_TUTORIAL_DATA_FOLDER "${CMAKE_CURRENT_SOURCE_DIR}/${TUTORIAL_DATA_FOLDER}") @@ -884,7 +884,7 @@ if(BUILD_SAMPLES) target_link_libraries("tutorial_${tutorial}" "--preload-file ${ABS_TUTORIAL_DATA_FOLDER}@/${TUTORIAL_DATA_FOLDER}") endif() endforeach() - + set(INVADER_DATA_FOLDER "Samples/invaders/data/") target_link_libraries(invaders "-sALLOW_MEMORY_GROWTH --preload-file ${CMAKE_CURRENT_SOURCE_DIR}/${INVADER_DATA_FOLDER}@/${INVADER_DATA_FOLDER}") endif() @@ -906,7 +906,7 @@ if(EMSCRIPTEN) # Enables Asyncify which we only need since the backend doesn't control the main loop. This enables us to yield to the browser during the backend call to # Backend::ProcessEvents(). Asyncify results in larger and slower code, users are instead encouraged to use 'emscripten_set_main_loop()' and family. set(EMSCRIPTEN_EXE_FLAGS "${EMSCRIPTEN_EXE_FLAGS} -sASYNCIFY") - + message(STATUS "Compiling for Emscripten.\n\t- Flags:${EMSCRIPTEN_FLAGS}\n\t- ExeFlags:${EMSCRIPTEN_EXE_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EMSCRIPTEN_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EMSCRIPTEN_FLAGS}") @@ -975,7 +975,7 @@ if(BUILD_SAMPLES) install(DIRECTORY ${PROJECT_SOURCE_DIR}/Samples/invaders/data DESTINATION ${SAMPLES_DIR}/invaders ) - + if(TARGET lottie) install(DIRECTORY ${PROJECT_SOURCE_DIR}/Samples/basic/lottie/data DESTINATION ${SAMPLES_DIR}/basic/lottie @@ -988,10 +988,10 @@ if(BUILD_SAMPLES) endif() if(BUILD_LUA_BINDINGS) - install(DIRECTORY ${PROJECT_SOURCE_DIR}/Samples/luainvaders/data + install(DIRECTORY ${PROJECT_SOURCE_DIR}/Samples/luainvaders/data DESTINATION ${SAMPLES_DIR}/luainvaders ) - install(DIRECTORY ${PROJECT_SOURCE_DIR}/Samples/luainvaders/lua + install(DIRECTORY ${PROJECT_SOURCE_DIR}/Samples/luainvaders/lua DESTINATION ${SAMPLES_DIR}/luainvaders ) endif() @@ -1046,4 +1046,3 @@ else() " or write generators for RmlUiConfig.cmake by yourself.") endif() endif() - diff --git a/Include/RmlUi/Config/Config.h b/Include/RmlUi/Config/Config.h index 018ab3b15..d5c025826 100644 --- a/Include/RmlUi/Config/Config.h +++ b/Include/RmlUi/Config/Config.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -38,165 +38,172 @@ */ #ifdef RMLUI_CUSTOM_CONFIGURATION_FILE -#include RMLUI_CUSTOM_CONFIGURATION_FILE + #include RMLUI_CUSTOM_CONFIGURATION_FILE #else -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef RMLUI_NO_THIRDPARTY_CONTAINERS -#include -#include -#else -#include "../Core/Containers/itlib/flat_map.hpp" -#include "../Core/Containers/itlib/flat_set.hpp" -#include "../Core/Containers/robin_hood.h" -#endif // RMLUI_NO_THIRDPARTY_CONTAINERS + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #ifdef RMLUI_NO_THIRDPARTY_CONTAINERS + #include + #include + #else + #include "../Core/Containers/itlib/flat_map.hpp" + #include "../Core/Containers/itlib/flat_set.hpp" + #include "../Core/Containers/robin_hood.h" + #endif // RMLUI_NO_THIRDPARTY_CONTAINERS namespace Rml { -// Default matrix type to be used. This alias may be set to ColumnMajorMatrix4f or RowMajorMatrix4f. This alias can not -// be set here because matrix types are defined after this include in Core/Types.h. -#ifdef RMLUI_MATRIX_ROW_MAJOR -#define RMLUI_MATRIX4_TYPE RowMajorMatrix4f -#else -#define RMLUI_MATRIX4_TYPE ColumnMajorMatrix4f -#endif + // Default matrix type to be used. This alias may be set to ColumnMajorMatrix4f or RowMajorMatrix4f. This alias can not + // be set here because matrix types are defined after this include in Core/Types.h. + #ifdef RMLUI_MATRIX_ROW_MAJOR + #define RMLUI_MATRIX4_TYPE RowMajorMatrix4f + #else + #define RMLUI_MATRIX4_TYPE ColumnMajorMatrix4f + #endif -// A way to disable 'final' specified for Rml::Releaser class. It breaks EASTL. -#define RMLUI_RELEASER_FINAL final + // A way to disable 'final' specified for Rml::Releaser class. It breaks EASTL. + #define RMLUI_RELEASER_FINAL final // Containers types. -template +template using Vector = std::vector; -template +template using Array = std::array; -template +template using Stack = std::stack; -template +template using List = std::list; -template +template using Queue = std::queue; -template +template using Pair = std::pair; template -using UnorderedMultimap = std::unordered_multimap< Key, Value >; -#ifdef RMLUI_NO_THIRDPARTY_CONTAINERS +using UnorderedMultimap = std::unordered_multimap; + + #ifdef RMLUI_NO_THIRDPARTY_CONTAINERS template -using UnorderedMap = std::unordered_map< Key, Value >; +using UnorderedMap = std::unordered_map; template -using SmallUnorderedMap = UnorderedMap< Key, Value >; +using SmallUnorderedMap = UnorderedMap; template -using UnorderedSet = std::unordered_set< T >; +using UnorderedSet = std::unordered_set; template -using SmallUnorderedSet = std::unordered_set< T >; +using SmallUnorderedSet = std::unordered_set; template -using SmallOrderedSet = std::set< T >; -#else -template < typename Key, typename Value> -using UnorderedMap = robin_hood::unordered_flat_map< Key, Value >; +using SmallOrderedSet = std::set; + #else template -using SmallUnorderedMap = itlib::flat_map< Key, Value >; +using UnorderedMap = robin_hood::unordered_flat_map; +template +using SmallUnorderedMap = itlib::flat_map; template -using UnorderedSet = robin_hood::unordered_flat_set< T >; +using UnorderedSet = robin_hood::unordered_flat_set; template -using SmallUnorderedSet = itlib::flat_set< T >; +using SmallUnorderedSet = itlib::flat_set; template -using SmallOrderedSet = itlib::flat_set< T >; -#endif // RMLUI_NO_THIRDPARTY_CONTAINERS -template -inline std::move_iterator MakeMoveIterator(Iterator it) { return std::make_move_iterator(it); } +using SmallOrderedSet = itlib::flat_set; + #endif // RMLUI_NO_THIRDPARTY_CONTAINERS // Utilities. template using Hash = std::hash; -template +template using Function = std::function; +template +inline std::move_iterator MakeMoveIterator(Iterator it) +{ + return std::make_move_iterator(it); +} // Strings. using String = std::string; -using StringList = Vector< String >; +using StringList = Vector; // Smart pointer types. -template +template using UniquePtr = std::unique_ptr; -template +template class Releaser; -template +template using UniqueReleaserPtr = std::unique_ptr>; -template +template using SharedPtr = std::shared_ptr; -template +template using WeakPtr = std::weak_ptr; -template -inline SharedPtr MakeShared(Args&&... args) { return std::make_shared(std::forward(args)...); } -template -inline UniquePtr MakeUnique(Args&&... args) { return std::make_unique(std::forward(args)...); } - +template +inline SharedPtr MakeShared(Args&&... args) +{ + return std::make_shared(std::forward(args)...); +} +template +inline UniquePtr MakeUnique(Args&&... args) +{ + return std::make_unique(std::forward(args)...); } - -/*** -// The following defines should be used for inserting custom type cast operators for conversion of RmlUi types -// to user types. RmlUi uses template math types, therefore conversion operators to non-templated types -// should be done using SFINAE as in example below. - -// Extra code to be inserted into RmlUi::Color<> class body. Note: be mindful of colorspaces used by different -// color types. RmlUi assumes that float colors are interpreted in linear colorspace while byte colors are -// interpreted as sRGB. - -#define RMLUI_COLOUR_USER_EXTRA \ - template>* = nullptr> \ - operator MyColor() const { return MyColor( \ - (float)red / 255.0f, (float)green / 255.0f, (float)blue / 255.0f, (float)alpha / 255.0f); } \ - template>* = nullptr> \ - operator MyColor() const { return MyColor(red, green, blue, alpha); } \ - -// Extra code to be inserted into RmlUi::Vector2<> class body. -#define RMLUI_VECTOR2_USER_EXTRA \ - template>* = nullptr> \ - operator typename MyIntVector2() const { return MyIntVector2(x, y); } \ - template>* = nullptr> \ - operator MyVector2() const { return MyVector2(x, y); } \ - template>* = nullptr> \ - Vector2(MyIntVector2 value) : Vector2(value.x_, value.y_) { } \ - template>* = nullptr> \ - Vector2(MyVector2 value) : Vector2(value.x_, value.y_) { } \ - -// Extra code to be inserted into RmlUi::Vector3<> class body. -#define RMLUI_VECTOR3_USER_EXTRA \ - template>* = nullptr> \ - operator typename MyIntVector3() const { return MyIntVector3(x, y, z); } \ - template>* = nullptr> \ - operator MyVector3() const { return MyVector3(x, y, z); } \ - template>* = nullptr> \ - Vector3(MyIntVector3 value) : Vector3(value.x_, value.y_, value.z_) { } \ - template>* = nullptr> \ - Vector3(MyVector3 value) : Vector3(value.x_, value.y_, value.z_) { } \ - -// Extra code to be inserted into RmlUi::Vector4<> class body. -#define RMLUI_VECTOR4_USER_EXTRA \ - template>* = nullptr> \ - operator typename MyIntVector4() const { return MyIntVector4(x, y, z, w); } \ - template>* = nullptr> \ - operator MyVector4() const { return MyVector4(x, y, z, w); } \ - template>* = nullptr> \ - Vector4(MyIntVector4 value) : Vector4(value.x_, value.y_, value.z_, value.w_) { } \ - template>* = nullptr> \ - Vector4(MyVector4 value) : Vector4(value.x_, value.y_, value.z_, value.w_) { } \ - -// Extra code to be inserted into RmlUi::Matrix4<> class body. - #define RMLUI_MATRIX4_USER_EXTRA operator MyMatrix4() const { return MyMatrix4(data()); } -***/ - - -#endif // RMLUI_USER_CONFIG_FILE - -#endif // RMLUI_CONFIG_CONFIG_H +} // namespace Rml + + /*** + // The following defines should be used for inserting custom type cast operators for conversion of RmlUi types + // to user types. RmlUi uses template math types, therefore conversion operators to non-templated types + // should be done using SFINAE as in example below. + + // Extra code to be inserted into RmlUi::Color<> class body. Note: be mindful of colorspaces used by different + // color types. RmlUi assumes that float colors are interpreted in linear colorspace while byte colors are + // interpreted as sRGB. + #define RMLUI_COLOUR_USER_EXTRA \ + template>* = nullptr> \ + operator MyColor() const { return MyColor( \ + (float)red / 255.0f, (float)green / 255.0f, (float)blue / 255.0f, (float)alpha / 255.0f); } \ + template>* = nullptr> \ + operator MyColor() const { return MyColor(red, green, blue, alpha); } \ + + // Extra code to be inserted into RmlUi::Vector2<> class body. + #define RMLUI_VECTOR2_USER_EXTRA \ + template>* = nullptr> \ + operator typename MyIntVector2() const { return MyIntVector2(x, y); } \ + template>* = nullptr> \ + operator MyVector2() const { return MyVector2(x, y); } \ + template>* = nullptr> \ + Vector2(MyIntVector2 value) : Vector2(value.x_, value.y_) { } \ + template>* = nullptr> \ + Vector2(MyVector2 value) : Vector2(value.x_, value.y_) { } \ + + // Extra code to be inserted into RmlUi::Vector3<> class body. + #define RMLUI_VECTOR3_USER_EXTRA \ + template>* = nullptr> \ + operator typename MyIntVector3() const { return MyIntVector3(x, y, z); } \ + template>* = nullptr> \ + operator MyVector3() const { return MyVector3(x, y, z); } \ + template>* = nullptr> \ + Vector3(MyIntVector3 value) : Vector3(value.x_, value.y_, value.z_) { } \ + template>* = nullptr> \ + Vector3(MyVector3 value) : Vector3(value.x_, value.y_, value.z_) { } \ + + // Extra code to be inserted into RmlUi::Vector4<> class body. + #define RMLUI_VECTOR4_USER_EXTRA \ + template>* = nullptr> \ + operator typename MyIntVector4() const { return MyIntVector4(x, y, z, w); } \ + template>* = nullptr> \ + operator MyVector4() const { return MyVector4(x, y, z, w); } \ + template>* = nullptr> \ + Vector4(MyIntVector4 value) : Vector4(value.x_, value.y_, value.z_, value.w_) { } \ + template>* = nullptr> \ + Vector4(MyVector4 value) : Vector4(value.x_, value.y_, value.z_, value.w_) { } \ + + // Extra code to be inserted into RmlUi::Matrix4<> class body. + #define RMLUI_MATRIX4_USER_EXTRA operator MyMatrix4() const { return MyMatrix4(data()); } + ***/ + +#endif // RMLUI_USER_CONFIG_FILE + +#endif // RMLUI_CONFIG_CONFIG_H diff --git a/Include/RmlUi/Core.h b/Include/RmlUi/Core.h index 39545a049..af61d1e37 100644 --- a/Include/RmlUi/Core.h +++ b/Include/RmlUi/Core.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,17 +29,13 @@ #ifndef RMLUI_CORE_H #define RMLUI_CORE_H -#include "Core/Core.h" - -#include "Core/Types.h" -#include "Core/Math.h" -#include "Core/Header.h" #include "Core/Animation.h" #include "Core/Box.h" #include "Core/ComputedValues.h" #include "Core/Context.h" #include "Core/ContextInstancer.h" #include "Core/ConvolutionFilter.h" +#include "Core/Core.h" #include "Core/DataModelHandle.h" #include "Core/DataTypeRegister.h" #include "Core/DataTypes.h" @@ -64,9 +60,11 @@ #include "Core/FontGlyph.h" #include "Core/Geometry.h" #include "Core/GeometryUtilities.h" +#include "Core/Header.h" #include "Core/ID.h" #include "Core/Input.h" #include "Core/Log.h" +#include "Core/Math.h" #include "Core/Plugin.h" #include "Core/PropertiesIteratorView.h" #include "Core/Property.h" @@ -88,10 +86,12 @@ #include "Core/TransformPrimitive.h" #include "Core/Tween.h" #include "Core/TypeConverter.h" +#include "Core/Types.h" #include "Core/Vertex.h" #include "Core/XMLNodeHandler.h" #include "Core/XMLParser.h" +// Elements #include "Core/Elements/ElementForm.h" #include "Core/Elements/ElementFormControl.h" #include "Core/Elements/ElementFormControlInput.h" diff --git a/Include/RmlUi/Core/Animation.h b/Include/RmlUi/Core/Animation.h index 828f10fac..15e784899 100644 --- a/Include/RmlUi/Core/Animation.h +++ b/Include/RmlUi/Core/Animation.h @@ -28,9 +28,9 @@ #ifndef RMLUI_CORE_ANIMATION_H #define RMLUI_CORE_ANIMATION_H -#include "Types.h" -#include "Tween.h" #include "ID.h" +#include "Tween.h" +#include "Types.h" namespace Rml { @@ -60,16 +60,35 @@ struct TransitionList { Vector transitions; TransitionList() {} - TransitionList(bool none, bool all, Vector transitions) : - none(none), all(all), transitions(std::move(transitions)) {} + TransitionList(bool none, bool all, Vector transitions) : none(none), all(all), transitions(std::move(transitions)) {} }; -inline bool operator==(const Animation& a, const Animation& b) { return a.duration == b.duration && a.tween == b.tween && a.delay == b.delay && a.alternate == b.alternate && a.paused == b.paused && a.num_iterations == b.num_iterations && a.name == b.name; } -inline bool operator!=(const Animation& a, const Animation& b) { return !(a == b); } -inline bool operator==(const Transition& a, const Transition& b) { return a.id == b.id && a.tween == b.tween && a.duration == b.duration && a.delay == b.delay && a.reverse_adjustment_factor == b.reverse_adjustment_factor; } -inline bool operator!=(const Transition& a, const Transition& b) { return !(a == b); } -inline bool operator==(const TransitionList& a, const TransitionList& b) { return a.none == b.none && a.all == b.all && a.transitions == b.transitions; } -inline bool operator!=(const TransitionList& a, const TransitionList& b) { return !(a == b); } +inline bool operator==(const Animation& a, const Animation& b) +{ + return a.duration == b.duration && a.tween == b.tween && a.delay == b.delay && a.alternate == b.alternate && a.paused == b.paused && + a.num_iterations == b.num_iterations && a.name == b.name; +} +inline bool operator!=(const Animation& a, const Animation& b) +{ + return !(a == b); +} +inline bool operator==(const Transition& a, const Transition& b) +{ + return a.id == b.id && a.tween == b.tween && a.duration == b.duration && a.delay == b.delay && + a.reverse_adjustment_factor == b.reverse_adjustment_factor; +} +inline bool operator!=(const Transition& a, const Transition& b) +{ + return !(a == b); +} +inline bool operator==(const TransitionList& a, const TransitionList& b) +{ + return a.none == b.none && a.all == b.all && a.transitions == b.transitions; +} +inline bool operator!=(const TransitionList& a, const TransitionList& b) +{ + return !(a == b); +} } // namespace Rml #endif diff --git a/Include/RmlUi/Core/BaseXMLParser.h b/Include/RmlUi/Core/BaseXMLParser.h index 3238b3eb1..b206bf893 100644 --- a/Include/RmlUi/Core/BaseXMLParser.h +++ b/Include/RmlUi/Core/BaseXMLParser.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,9 +29,9 @@ #ifndef RMLUI_CORE_BASEXMLPARSER_H #define RMLUI_CORE_BASEXMLPARSER_H +#include "Dictionary.h" #include "Header.h" #include "Types.h" -#include "Dictionary.h" namespace Rml { @@ -42,97 +42,96 @@ using XMLAttributes = Dictionary; enum class XMLDataType { Text, CData, InnerXML }; /** - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API BaseXMLParser -{ - public: - BaseXMLParser(); - virtual ~BaseXMLParser(); - - /// Registers a tag as containing general character data. This will mean the contents of the tag will be parsed - /// similarly to a CDATA tag (ie, no other markup will be recognised until the section's closing tag is found). - /// @param[in] tag The tag to register as containing generic character data. - void RegisterCDATATag(const String& tag); - - /// When an XML attribute with the given name is encountered during parsing, then all content below the current - /// node is treated as data. - /// @note While children nodes are treated as data (text), it is assumed that the content represents valid XML. - /// The parsing proceeds as normal except that the Handle...() functions are not called until the - /// starting node is closed. Then, all its contents are submitted as Data (raw text string). - /// @note In particular, this behavior is useful for some data-binding views. - void RegisterInnerXMLAttribute(const String& attribute_name); - - /// Parses the given stream as an XML file, and calls the handlers when - /// interesting phenomena are encountered. - void Parse(Stream* stream); - - /// Get the line number in the stream. - /// @return The line currently being processed in the XML stream. - int GetLineNumber() const; - /// Get the line number of the last open tag in the stream. - int GetLineNumberOpenTag() const; - - /// Called when the parser finds the beginning of an element tag. - virtual void HandleElementStart(const String& name, const XMLAttributes& attributes); - /// Called when the parser finds the end of an element tag. - virtual void HandleElementEnd(const String& name); - /// Called when the parser encounters data. - virtual void HandleData(const String& data, XMLDataType type); - - protected: - const URL* GetSourceURLPtr() const; - - private: - const URL* source_url = nullptr; - String xml_source; - size_t xml_index = 0; - - void Next(); - bool AtEnd() const; - char Look() const; - - void HandleElementStartInternal(const String& name, const XMLAttributes& attributes); - void HandleElementEndInternal(const String& name); - void HandleDataInternal(const String& data, XMLDataType type); - - void ReadHeader(); - void ReadBody(); - bool ReadOpenTag(); - - bool ReadCloseTag(size_t xml_index_tag); - bool ReadAttributes(XMLAttributes& attributes, bool& parse_raw_xml_content); - bool ReadCDATA(const char* tag_terminator = nullptr); - - // Reads from the stream until a complete word is found. - // @param[out] word Word thats been found - // @param[in] terminators List of characters that terminate the search - bool FindWord(String& word, const char* terminators = nullptr); - // Reads from the stream until the given character set is found. All - // intervening characters will be returned in data. - bool FindString(const char* string, String& data, bool escape_brackets = false); - // Returns true if the next sequence of characters in the stream - // matches the given string. If consume is set and this returns true, - // the characters will be consumed. - bool PeekString(const char* string, bool consume = true); - - int line_number = 0; - int line_number_open_tag = 0; - int open_tag_depth = 0; - - // Enabled when an attribute for inner xml data is encountered (see description in Register...() above). - bool inner_xml_data = false; - int inner_xml_data_terminate_depth = 0; - size_t inner_xml_data_index_begin = 0; - - // The element attributes being read. - XMLAttributes attributes; - // The loose data being read. - String data; - - SmallUnorderedSet< String > cdata_tags; - SmallUnorderedSet< String > attributes_for_inner_xml_data; +class RMLUICORE_API BaseXMLParser { +public: + BaseXMLParser(); + virtual ~BaseXMLParser(); + + /// Registers a tag as containing general character data. This will mean the contents of the tag will be parsed + /// similarly to a CDATA tag (ie, no other markup will be recognised until the section's closing tag is found). + /// @param[in] tag The tag to register as containing generic character data. + void RegisterCDATATag(const String& tag); + + /// When an XML attribute with the given name is encountered during parsing, then all content below the current + /// node is treated as data. + /// @note While children nodes are treated as data (text), it is assumed that the content represents valid XML. + /// The parsing proceeds as normal except that the Handle...() functions are not called until the + /// starting node is closed. Then, all its contents are submitted as Data (raw text string). + /// @note In particular, this behavior is useful for some data-binding views. + void RegisterInnerXMLAttribute(const String& attribute_name); + + /// Parses the given stream as an XML file, and calls the handlers when + /// interesting phenomena are encountered. + void Parse(Stream* stream); + + /// Get the line number in the stream. + /// @return The line currently being processed in the XML stream. + int GetLineNumber() const; + /// Get the line number of the last open tag in the stream. + int GetLineNumberOpenTag() const; + + /// Called when the parser finds the beginning of an element tag. + virtual void HandleElementStart(const String& name, const XMLAttributes& attributes); + /// Called when the parser finds the end of an element tag. + virtual void HandleElementEnd(const String& name); + /// Called when the parser encounters data. + virtual void HandleData(const String& data, XMLDataType type); + +protected: + const URL* GetSourceURLPtr() const; + +private: + const URL* source_url = nullptr; + String xml_source; + size_t xml_index = 0; + + void Next(); + bool AtEnd() const; + char Look() const; + + void HandleElementStartInternal(const String& name, const XMLAttributes& attributes); + void HandleElementEndInternal(const String& name); + void HandleDataInternal(const String& data, XMLDataType type); + + void ReadHeader(); + void ReadBody(); + bool ReadOpenTag(); + + bool ReadCloseTag(size_t xml_index_tag); + bool ReadAttributes(XMLAttributes& attributes, bool& parse_raw_xml_content); + bool ReadCDATA(const char* tag_terminator = nullptr); + + // Reads from the stream until a complete word is found. + // @param[out] word Word thats been found + // @param[in] terminators List of characters that terminate the search + bool FindWord(String& word, const char* terminators = nullptr); + // Reads from the stream until the given character set is found. All + // intervening characters will be returned in data. + bool FindString(const char* string, String& data, bool escape_brackets = false); + // Returns true if the next sequence of characters in the stream + // matches the given string. If consume is set and this returns true, + // the characters will be consumed. + bool PeekString(const char* string, bool consume = true); + + int line_number = 0; + int line_number_open_tag = 0; + int open_tag_depth = 0; + + // Enabled when an attribute for inner xml data is encountered (see description in Register...() above). + bool inner_xml_data = false; + int inner_xml_data_terminate_depth = 0; + size_t inner_xml_data_index_begin = 0; + + // The element attributes being read. + XMLAttributes attributes; + // The loose data being read. + String data; + + SmallUnorderedSet cdata_tags; + SmallUnorderedSet attributes_for_inner_xml_data; }; } // namespace Rml diff --git a/Include/RmlUi/Core/Box.h b/Include/RmlUi/Core/Box.h index ab2b5f528..209fe7e9f 100644 --- a/Include/RmlUi/Core/Box.h +++ b/Include/RmlUi/Core/Box.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,38 +34,25 @@ namespace Rml { /** - Stores a box with four sized areas; content, padding, a border and margin. See - http://www.w3.org/TR/REC-CSS2/box.html#box-dimensions for a diagram. + Stores a box with four sized areas; content, padding, a border and margin. See + http://www.w3.org/TR/REC-CSS2/box.html#box-dimensions for a diagram. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API Box -{ +class RMLUICORE_API Box { public: - enum Area - { + enum Area { MARGIN = 0, BORDER = 1, PADDING = 2, CONTENT = 3, - NUM_AREAS = 3, // ignores CONTENT + NUM_AREAS = 3, // ignores CONTENT }; - enum Edge - { - TOP = 0, - RIGHT = 1, - BOTTOM = 2, - LEFT = 3, - NUM_EDGES = 4 - }; + enum Edge { TOP = 0, RIGHT = 1, BOTTOM = 2, LEFT = 3, NUM_EDGES = 4 }; - enum Direction - { - VERTICAL = 0, - HORIZONTAL = 1 - }; + enum Direction { VERTICAL = 0, HORIZONTAL = 1 }; /// Initialises a zero-sized box. Box(); @@ -101,7 +88,8 @@ class RMLUICORE_API Box /// @return The size of the requested area edge. float GetEdge(Area area, Edge edge) const; /// Returns the cumulative size of one edge up to one of the box's areas. - /// @param area[in] The area to measure up to (and including). So, MARGIN will return the width of the margin, and PADDING will be the sum of the margin, border and padding. + /// @param area[in] The area to measure up to (and including). So, MARGIN will return the width of the margin, and PADDING will be the sum of the + /// margin, border and padding. /// @param edge[in] The desired edge. /// @return The cumulative size of the edge. float GetCumulativeEdge(Area area, Edge edge) const; diff --git a/Include/RmlUi/Core/Colour.h b/Include/RmlUi/Core/Colour.h index 84070219c..9fabe43ff 100644 --- a/Include/RmlUi/Core/Colour.h +++ b/Include/RmlUi/Core/Colour.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,26 +33,25 @@ namespace Rml { -/** - Templated class for a four-component RGBA colour. +/** + Templated class for a four-component RGBA colour. - @author Peter Curry + @author Peter Curry */ -template < typename ColourType, int AlphaDefault > -class Colour -{ +template +class Colour { public: /// Initialising constructor. /// @param[in] rgb Initial red, green and blue value of the colour. /// @param[in] alpha Initial alpha value of the colour. - inline Colour(ColourType rgb = ColourType{ 0 }, ColourType alpha = ColourType{ AlphaDefault }); + inline Colour(ColourType rgb = ColourType{0}, ColourType alpha = ColourType{AlphaDefault}); /// Initialising constructor. /// @param[in] red Initial red value of the colour. /// @param[in] green Initial green value of the colour. /// @param[in] blue Initial blue value of the colour. /// @param[in] alpha Initial alpha value of the colour. - inline Colour(ColourType red, ColourType green, ColourType blue, ColourType alpha = ColourType{ AlphaDefault }); + inline Colour(ColourType red, ColourType green, ColourType blue, ColourType alpha = ColourType{AlphaDefault}); /// Returns the sum of this colour and another. This does not saturate the channels. /// @param[in] rhs The colour to add this to. @@ -111,8 +110,6 @@ class Colour } // namespace Rml - #include "Colour.inl" - #endif diff --git a/Include/RmlUi/Core/Colour.inl b/Include/RmlUi/Core/Colour.inl index cfc80c89e..473a6cf05 100644 --- a/Include/RmlUi/Core/Colour.inl +++ b/Include/RmlUi/Core/Colour.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,50 +29,47 @@ namespace Rml { // Lightweight, non-initialising constructor. -template < typename ColourType, int AlphaDefault > -Colour< ColourType, AlphaDefault >::Colour(ColourType rgb, ColourType alpha) - : red(rgb), green(rgb), blue(rgb), alpha(alpha) -{ -} +template +Colour::Colour(ColourType rgb, ColourType alpha) : red(rgb), green(rgb), blue(rgb), alpha(alpha) +{} // Initialising constructor. -template < typename ColourType, int AlphaDefault > -Colour< ColourType, AlphaDefault >::Colour(ColourType red, ColourType green, ColourType blue, ColourType alpha) - : red(red), green(green), blue(blue), alpha(alpha) -{ -} +template +Colour::Colour(ColourType red, ColourType green, ColourType blue, ColourType alpha) : + red(red), green(green), blue(blue), alpha(alpha) +{} // Returns the sum of this colour and another. This does not saturate the channels. -template < typename ColourType, int AlphaDefault > -Colour< ColourType, AlphaDefault > Colour< ColourType, AlphaDefault >::operator+(const Colour< ColourType, AlphaDefault > rhs) const +template +Colour Colour::operator+(const Colour rhs) const { - return Colour< ColourType, AlphaDefault >(red + rhs.red, green + rhs.green, blue + rhs.blue, alpha + rhs.alpha); + return Colour(red + rhs.red, green + rhs.green, blue + rhs.blue, alpha + rhs.alpha); } // Returns the result of subtracting another colour from this colour. -template < typename ColourType, int AlphaDefault > -Colour< ColourType, AlphaDefault > Colour< ColourType, AlphaDefault >::operator-(const Colour< ColourType, AlphaDefault > rhs) const +template +Colour Colour::operator-(const Colour rhs) const { - return Colour< ColourType, AlphaDefault >(red - rhs.red, green - rhs.green, blue - rhs.blue, alpha - rhs.alpha); + return Colour(red - rhs.red, green - rhs.green, blue - rhs.blue, alpha - rhs.alpha); } // Returns the result of multiplying this colour component-wise by a scalar. -template < typename ColourType, int AlphaDefault > -Colour< ColourType, AlphaDefault > Colour< ColourType, AlphaDefault >::operator*(float rhs) const +template +Colour Colour::operator*(float rhs) const { - return Colour((ColourType) (red * rhs), (ColourType) (green * rhs), (ColourType) (blue * rhs), (ColourType) (alpha * rhs)); + return Colour((ColourType)(red * rhs), (ColourType)(green * rhs), (ColourType)(blue * rhs), (ColourType)(alpha * rhs)); } // Returns the result of dividing this colour component-wise by a scalar. -template < typename ColourType, int AlphaDefault > -Colour< ColourType, AlphaDefault > Colour< ColourType, AlphaDefault >::operator/(float rhs) const +template +Colour Colour::operator/(float rhs) const { - return Colour((ColourType) (red / rhs), (ColourType) (green / rhs), (ColourType) (blue / rhs), (ColourType) (alpha / rhs)); + return Colour((ColourType)(red / rhs), (ColourType)(green / rhs), (ColourType)(blue / rhs), (ColourType)(alpha / rhs)); } // Adds another colour to this in-place. This does not saturate the channels. -template < typename ColourType, int AlphaDefault > -void Colour< ColourType, AlphaDefault >::operator+=(const Colour rhs) +template +void Colour::operator+=(const Colour rhs) { red += rhs.red; green += rhs.green; @@ -81,8 +78,8 @@ void Colour< ColourType, AlphaDefault >::operator+=(const Colour rhs) } // Subtracts another colour from this in-place. -template < typename ColourType, int AlphaDefault > -void Colour< ColourType, AlphaDefault >::operator-=(const Colour rhs) +template +void Colour::operator-=(const Colour rhs) { red -= rhs.red; green -= rhs.green; @@ -91,8 +88,8 @@ void Colour< ColourType, AlphaDefault >::operator-=(const Colour rhs) } // Scales this colour component-wise in-place. -template < typename ColourType, int AlphaDefault > -void Colour< ColourType, AlphaDefault >::operator*=(float rhs) +template +void Colour::operator*=(float rhs) { red = (ColourType)(red * rhs); green = (ColourType)(green * rhs); @@ -101,8 +98,8 @@ void Colour< ColourType, AlphaDefault >::operator*=(float rhs) } // Scales this colour component-wise in-place by the inverse of a value. -template < typename ColourType, int AlphaDefault > -void Colour< ColourType, AlphaDefault >::operator/=(float rhs) +template +void Colour::operator/=(float rhs) { *this *= (1.0f / rhs); } diff --git a/Include/RmlUi/Core/ComputedValues.h b/Include/RmlUi/Core/ComputedValues.h index 9e0cdbe93..9aebcd134 100644 --- a/Include/RmlUi/Core/ComputedValues.h +++ b/Include/RmlUi/Core/ComputedValues.h @@ -3,7 +3,7 @@ * * For the latest information, see http://github.com/mikke89/RmlUi * - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Include/RmlUi/Core/Context.h b/Include/RmlUi/Core/Context.h index b45c95fb5..003c3cf28 100644 --- a/Include/RmlUi/Core/Context.h +++ b/Include/RmlUi/Core/Context.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,11 +30,11 @@ #define RMLUI_CORE_CONTEXT_H #include "Header.h" -#include "Types.h" -#include "Traits.h" #include "Input.h" #include "ScriptInterface.h" #include "ScrollTypes.h" +#include "Traits.h" +#include "Types.h" namespace Rml { @@ -50,13 +50,12 @@ class ScrollController; enum class EventId : uint16_t; /** - A context for storing, rendering and processing RML documents. Multiple contexts can exist simultaneously. + A context for storing, rendering and processing RML documents. Multiple contexts can exist simultaneously. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API Context : public ScriptInterface -{ +class RMLUICORE_API Context : public ScriptInterface { public: /// Constructs a new, uninitialised context. This should not be called directly, use CreateContext() /// instead. @@ -83,7 +82,7 @@ class RMLUICORE_API Context : public ScriptInterface /// @return The current density-independent pixel ratio of the context. float GetDensityIndependentPixelRatio() const; - /// Updates all elements in the context's documents. + /// Updates all elements in the context's documents. /// This must be called before Context::Render, but after any elements have been changed, added or removed. bool Update(); /// Renders all visible elements in the context's documents. @@ -180,12 +179,14 @@ class RMLUICORE_API Context : public ScriptInterface /// Sends a key down event into this context. /// @param[in] key_identifier The key pressed. - /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together members of the Input::KeyModifier enumeration. + /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together + /// members of the Input::KeyModifier enumeration. /// @return True if the event was not consumed (ie, was prevented from propagating by an element), false if it was. bool ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifier_state); /// Sends a key up event into this context. /// @param[in] key_identifier The key released. - /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together members of the Input::KeyModifier enumeration. + /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together + /// members of the Input::KeyModifier enumeration. /// @return True if the event was not consumed (ie, was prevented from propagating by an element), false if it was. bool ProcessKeyUp(Input::KeyIdentifier key_identifier, int key_modifier_state); @@ -203,17 +204,20 @@ class RMLUICORE_API Context : public ScriptInterface /// Sends a mouse movement event into this context. /// @param[in] x The x-coordinate of the mouse cursor, in window-coordinates (ie, 0 should be the left of the client area). /// @param[in] y The y-coordinate of the mouse cursor, in window-coordinates (ie, 0 should be the top of the client area). - /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together members of the Input::KeyModifier enumeration. + /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together + /// members of the Input::KeyModifier enumeration. /// @return True if the mouse is not interacting with any elements in the context (see 'IsMouseInteracting'), otherwise false. bool ProcessMouseMove(int x, int y, int key_modifier_state); /// Sends a mouse-button down event into this context. /// @param[in] button_index The index of the button that was pressed; 0 for the left button, 1 for right, and 2 for middle button. - /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together members of the Input::KeyModifier enumeration. + /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together + /// members of the Input::KeyModifier enumeration. /// @return True if the mouse is not interacting with any elements in the context (see 'IsMouseInteracting'), otherwise false. bool ProcessMouseButtonDown(int button_index, int key_modifier_state); /// Sends a mouse-button up event into this context. /// @param[in] button_index The index of the button that was release; 0 for the left button, 1 for right, and 2 for middle button. - /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together members of the Input::KeyModifier enumeration. + /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together + /// members of the Input::KeyModifier enumeration. /// @return True if the mouse is not interacting with any elements in the context (see 'IsMouseInteracting'), otherwise false. bool ProcessMouseButtonUp(int button_index, int key_modifier_state); /// Sends a mousescroll event into this context. @@ -221,16 +225,20 @@ class RMLUICORE_API Context : public ScriptInterface bool ProcessMouseWheel(float wheel_delta, int key_modifier_state); /// Sends a mousescroll event into this context, and scrolls the document unless the event was stopped from propagating. /// @param[in] wheel_delta The mouse-wheel movement this frame, with positive values being directed right and down. - /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together members of the Input::KeyModifier enumeration. + /// @param[in] key_modifier_state The state of key modifiers (shift, control, caps-lock, etc) keys; this should be generated by ORing together + /// members of the Input::KeyModifier enumeration. /// @return True if the event was not consumed (ie, was prevented from propagating by an element), false if it was. bool ProcessMouseWheel(Vector2f wheel_delta, int key_modifier_state); - /// Tells the context the mouse has left the window. This removes any hover state from all elements and prevents 'Update()' from setting the hover state for elements under the mouse. + /// Tells the context the mouse has left the window. This removes any hover state from all elements and prevents 'Update()' from setting the hover + /// state for elements under the mouse. /// @return True if the mouse is not interacting with any elements in the context (see 'IsMouseInteracting'), otherwise false. /// @note The mouse is considered activate again after the next call to 'ProcessMouseMove()'. bool ProcessMouseLeave(); - /// Returns a hint on whether the mouse is currently interacting with any elements in this context, based on previously submitted 'ProcessMouse...()' commands. - /// @note Interaction is determined irrespective of background and opacity. See the RCSS property 'pointer-events' to disable interaction for specific elements. + /// Returns a hint on whether the mouse is currently interacting with any elements in this context, based on previously submitted + /// 'ProcessMouse...()' commands. + /// @note Interaction is determined irrespective of background and opacity. See the RCSS property 'pointer-events' to disable interaction for + /// specific elements. /// @return True if the mouse hovers over or has activated an element in this context, otherwise false. bool IsMouseInteracting() const; @@ -308,8 +316,8 @@ class RMLUICORE_API Context : public ScriptInterface ContextInstancer* instancer; - using ElementSet = SmallOrderedSet< Element* >; - using ElementList = Vector< Element* >; + using ElementSet = SmallOrderedSet; + using ElementList = Vector; // Set of elements that are currently in hover state. ElementSet hover_chain; // List of elements that are currently in active state. diff --git a/Include/RmlUi/Core/ContextInstancer.h b/Include/RmlUi/Core/ContextInstancer.h index 2b402128d..111475ad0 100644 --- a/Include/RmlUi/Core/ContextInstancer.h +++ b/Include/RmlUi/Core/ContextInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,13 +39,12 @@ class Context; class Event; /** - Abstract instancer interface for instancing contexts. + Abstract instancer interface for instancing contexts. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API ContextInstancer : public Releasable -{ +class RMLUICORE_API ContextInstancer : public Releasable { public: virtual ~ContextInstancer(); diff --git a/Include/RmlUi/Core/ConvolutionFilter.h b/Include/RmlUi/Core/ConvolutionFilter.h index 1ea54474f..327e92851 100644 --- a/Include/RmlUi/Core/ConvolutionFilter.h +++ b/Include/RmlUi/Core/ConvolutionFilter.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,14 +42,13 @@ enum class FilterOperation { }; /** - A programmable convolution filter, designed to aid in the generation of texture data by custom - FontEffect types. + A programmable convolution filter, designed to aid in the generation of texture data by custom + FontEffect types. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ConvolutionFilter -{ +class RMLUICORE_API ConvolutionFilter { public: ConvolutionFilter(); ~ConvolutionFilter(); @@ -58,7 +57,8 @@ class RMLUICORE_API ConvolutionFilter bool Initialise(int kernel_radius, FilterOperation operation); /// Initialises the filter. A filter must be initialised and populated with values before use. - /// @param[in] kernel_radii The size of the filter's kernel on each side of the origin along both axes. So, for example, a filter initialised with radii (1,1) will store 9 values. + /// @param[in] kernel_radii The size of the filter's kernel on each side of the origin along both axes. So, for example, a filter initialised with + /// radii (1,1) will store 9 values. /// @param[in] operation The operation the filter conducts to determine the result. bool Initialise(Vector2i kernel_radii, FilterOperation operation); @@ -73,7 +73,8 @@ class RMLUICORE_API ConvolutionFilter /// @param[in] destination The RGBA-encoded destination buffer. /// @param[in] destination_dimensions The size of the destination region (in pixels). /// @param[in] destination_stride The stride (in bytes) of the destination region. - /// @param[in] destination_color_format Determines the representation of the bytes in the destination texture, only the alpha channel will be written to. + /// @param[in] destination_color_format Determines the representation of the bytes in the destination texture, only the alpha channel will be + /// written to. /// @param[in] source The opacity information for the source buffer. /// @param[in] source_dimensions The size of the source region (in pixels). The stride is assumed to be equivalent to the horizontal width. /// @param[in] source_offset The offset of the source region from the destination region. This is usually the same as the kernel size. @@ -90,4 +91,3 @@ class RMLUICORE_API ConvolutionFilter } // namespace Rml #endif - diff --git a/Include/RmlUi/Core/Core.h b/Include/RmlUi/Core/Core.h index cd62451ff..f55879219 100644 --- a/Include/RmlUi/Core/Core.h +++ b/Include/RmlUi/Core/Core.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,10 +29,10 @@ #ifndef RMLUI_CORE_CORE_H #define RMLUI_CORE_CORE_H -#include "Header.h" -#include "Types.h" #include "Event.h" +#include "Header.h" #include "StyleTypes.h" +#include "Types.h" namespace Rml { @@ -44,11 +44,10 @@ class RenderInterface; class SystemInterface; enum class DefaultActionPhase; - /** - RmlUi library core API. + RmlUi library core API. - @author Peter Curry + @author Peter Curry */ /// Initialises RmlUi. @@ -91,7 +90,7 @@ RMLUICORE_API FileInterface* GetFileInterface(); RMLUICORE_API void SetFontEngineInterface(FontEngineInterface* font_interface); /// Returns RmlUi's font interface. RMLUICORE_API FontEngineInterface* GetFontEngineInterface(); - + /// Creates a new element context. /// @param[in] name The new name of the context. This must be unique. /// @param[in] dimensions The initial dimensions of the new context. @@ -149,7 +148,8 @@ RMLUICORE_API void UnregisterPlugin(Plugin* plugin); /// @param[in] bubbles Whether the event executes the bubble phase. If false, only capture and target phase is executed. /// @param[in] default_action_phase Defines during which phase(s) the 'Element::ProcessDefaultAction' method is called. /// @return The EventId of the newly created type, or existing type if 'type' is an internal type. -RMLUICORE_API EventId RegisterEventType(const String& type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase = DefaultActionPhase::None); +RMLUICORE_API EventId RegisterEventType(const String& type, bool interruptible, bool bubbles, + DefaultActionPhase default_action_phase = DefaultActionPhase::None); /// Returns a list of source URLs to textures in all loaded documents. RMLUICORE_API StringList GetTextureSourceList(); diff --git a/Include/RmlUi/Core/DataModelHandle.h b/Include/RmlUi/Core/DataModelHandle.h index decd6e76b..3829d70e0 100644 --- a/Include/RmlUi/Core/DataModelHandle.h +++ b/Include/RmlUi/Core/DataModelHandle.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,18 +29,17 @@ #ifndef RMLUI_CORE_DATAMODELHANDLE_H #define RMLUI_CORE_DATAMODELHANDLE_H +#include "DataStructHandle.h" +#include "DataTypeRegister.h" +#include "DataTypes.h" #include "Header.h" -#include "Types.h" #include "Traits.h" -#include "DataTypes.h" -#include "DataTypeRegister.h" -#include "DataStructHandle.h" +#include "Types.h" namespace Rml { class DataModel; - class RMLUICORE_API DataModelHandle { public: DataModelHandle(DataModel* model = nullptr); @@ -55,11 +54,10 @@ class RMLUICORE_API DataModelHandle { DataModel* model; }; - class RMLUICORE_API DataModelConstructor { public: - template - using DataEventMemberFunc = void(T::*)(DataModelHandle, Event&, const VariantList&); + template + using DataEventMemberFunc = void (T::*)(DataModelHandle, Event&, const VariantList&); DataModelConstructor(); explicit DataModelConstructor(DataModel* model); @@ -69,12 +67,13 @@ class RMLUICORE_API DataModelConstructor { // Bind a data variable. // @note For non-builtin types, make sure they first have been registered with the appropriate 'Register...()' functions. - template - bool Bind(const String& name, T* ptr) { + template + bool Bind(const String& name, T* ptr) + { RMLUI_ASSERTMSG(ptr, "Invalid pointer to data variable"); return BindVariable(name, DataVariable(type_register->GetDefinition(), static_cast(ptr))); } - + // Bind a get/set function pair. bool BindFunc(const String& name, DataGetFunc get_func, DataSetFunc set_func = {}); @@ -82,8 +81,9 @@ class RMLUICORE_API DataModelConstructor { bool BindEventCallback(const String& name, DataEventFunc event_func); // Convenience wrapper around BindEventCallback for member functions. - template - bool BindEventCallback(const String& name, DataEventMemberFunc member_func, T* object_pointer) { + template + bool BindEventCallback(const String& name, DataEventMemberFunc member_func, T* object_pointer) + { return BindEventCallback(name, [member_func, object_pointer](DataModelHandle handle, Event& event, const VariantList& arguments) { (object_pointer->*member_func)(handle, event, arguments); }); @@ -91,37 +91,39 @@ class RMLUICORE_API DataModelConstructor { // Bind a user-declared DataVariable. // For advanced use cases, for example for binding variables to a custom 'VariableDefinition'. - bool BindCustomDataVariable(const String& name, DataVariable data_variable) { - return BindVariable(name, data_variable); - } + bool BindCustomDataVariable(const String& name, DataVariable data_variable) { return BindVariable(name, data_variable); } // Register a scalar type with associated get and set functions. - // @note This registers a type which can later be used as a normal data variable, while 'BindFunc' registers a named data variable with a specific getter and setter. + // @note This registers a type which can later be used as a normal data variable, while 'BindFunc' registers a named data variable with a specific + // getter and setter. // @note The type applies to every data model associated with the current Context. - template + template bool RegisterScalar(DataTypeGetFunc get_func, DataTypeSetFunc set_func = {}); // Register a struct type. // @note The type applies to every data model associated with the current Context. // @return A handle which can be used to register struct members. - template + template StructHandle RegisterStruct(); // Register a user-declared VariableDefinition to describe a custom type behaviour. - template + template bool RegisterCustomDataVariableDefinition(UniquePtr definition); // Register an array type. // @note The type applies to every data model associated with the current Context. - // @note If 'Container::value_type' represents a non-scalar type, that type must already have been registered with the appropriate 'Register...()' functions. - // @note Container requires the following functions to be implemented: size() and begin(). This is satisfied by several containers including std::vector and std::array. - template + // @note If 'Container::value_type' represents a non-scalar type, that type must already have been registered with the appropriate 'Register...()' + // functions. + // @note Container requires the following functions to be implemented: size() and begin(). This is satisfied by several containers including + // std::vector and std::array. + template bool RegisterArray(); // Register a transform function. // A transform function modifies a variant with optional arguments. It can be called in data expressions using the pipe '|' operator. // @note The transform function applies to every data model associated with the current Context. - void RegisterTransformFunc(const String& name, DataTransformFunc transform_func) { + void RegisterTransformFunc(const String& name, DataTransformFunc transform_func) + { type_register->GetTransformFuncRegister()->Register(name, std::move(transform_func)); } @@ -138,11 +140,11 @@ class RMLUICORE_API DataModelConstructor { DataTypeRegister* type_register; }; - -template +template inline bool DataModelConstructor::RegisterScalar(DataTypeGetFunc get_func, DataTypeSetFunc set_func) { - static_assert(!is_builtin_data_scalar::value, "Cannot register scalar data type function. Arithmetic types and String are handled internally and does not need to be registered."); + static_assert(!is_builtin_data_scalar::value, + "Cannot register scalar data type function. Arithmetic types and String are handled internally and does not need to be registered."); const FamilyId id = Family::Id(); auto scalar_func_definition = Rml::MakeUnique>(get_func, set_func); @@ -157,7 +159,7 @@ inline bool DataModelConstructor::RegisterScalar(DataTypeGetFunc get_func, Da return true; } -template +template inline bool DataModelConstructor::RegisterCustomDataVariableDefinition(UniquePtr definition) { const FamilyId id = Family::Id(); @@ -172,7 +174,7 @@ inline bool DataModelConstructor::RegisterCustomDataVariableDefinition(UniquePtr return true; } -template +template inline StructHandle DataModelConstructor::RegisterStruct() { static_assert(std::is_class::value, "Type must be a struct or class type."); @@ -191,7 +193,7 @@ inline StructHandle DataModelConstructor::RegisterStruct() return StructHandle(type_register, struct_variable_raw); } -template +template inline bool DataModelConstructor::RegisterArray() { using value_type = typename Container::value_type; diff --git a/Include/RmlUi/Core/DataStructHandle.h b/Include/RmlUi/Core/DataStructHandle.h index d99fe335c..075196e3c 100644 --- a/Include/RmlUi/Core/DataStructHandle.h +++ b/Include/RmlUi/Core/DataStructHandle.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,19 +29,21 @@ #ifndef RMLUI_CORE_DATASTRUCTHANDLE_H #define RMLUI_CORE_DATASTRUCTHANDLE_H -#include "Header.h" -#include "Types.h" -#include "Traits.h" +#include "DataTypeRegister.h" #include "DataTypes.h" #include "DataVariable.h" - +#include "Header.h" +#include "Traits.h" +#include "Types.h" namespace Rml { -template +template class StructHandle { public: - StructHandle(DataTypeRegister* type_register, StructDefinition* struct_definition) : type_register(type_register), struct_definition(struct_definition) {} + StructHandle(DataTypeRegister* type_register, StructDefinition* struct_definition) : + type_register(type_register), struct_definition(struct_definition) + {} /// Register a member object. /// @note Underlying type must be registered before it is used as a member. @@ -53,7 +55,7 @@ class StructHandle { /// }; /// struct_handle.RegisterMember("health", &Invader::health); template - bool RegisterMember(const String& name, MemberType Object::* member_object_ptr) + bool RegisterMember(const String& name, MemberType Object::*member_object_ptr) { return CreateMemberObjectDefinition(name, member_object_ptr); } @@ -69,7 +71,7 @@ class StructHandle { /// }; /// struct_handle.RegisterMember("weapons", &Invader::GetWeapons); template - bool RegisterMember(const String& name, ReturnType(Object::* member_get_func_ptr)()) + bool RegisterMember(const String& name, ReturnType (Object::*member_get_func_ptr)()) { return RegisterMemberGetter(name, member_get_func_ptr); } @@ -85,80 +87,80 @@ class StructHandle { /// }; /// struct_handle.RegisterMember("color", &Invader::GetColor, &Invader::SetColor); template - bool RegisterMember(const String& name, ReturnType(Object::* member_get_func_ptr)(), void(Object::* member_set_func_ptr)(AssignType)) + bool RegisterMember(const String& name, ReturnType (Object::*member_get_func_ptr)(), void (Object::*member_set_func_ptr)(AssignType)) { using BasicReturnType = typename std::remove_reference::type; using BasicAssignType = typename std::remove_const::type>::type; using UnderlyingType = typename std::conditional::value, BasicAssignType, BasicReturnType>::type; - static_assert(IsVoidMemberFunc::value || IsVoidMemberFunc::value || std::is_same::value, "Provided getter and setter functions must get and set the same type."); + static_assert(IsVoidMemberFunc::value || IsVoidMemberFunc::value || + std::is_same::value, + "Provided getter and setter functions must get and set the same type."); return CreateMemberScalarGetSetFuncDefinition(name, member_get_func_ptr, member_set_func_ptr); } - explicit operator bool() const { - return type_register && struct_definition; - } + explicit operator bool() const { return type_register && struct_definition; } private: - // Member getter with reference return type. template - bool RegisterMemberGetter(const String& name, ReturnType& (Object::* member_get_func_ptr)()) { + bool RegisterMemberGetter(const String& name, ReturnType& (Object::*member_get_func_ptr)()) + { return CreateMemberGetFuncDefinition(name, member_get_func_ptr); } // Member getter with pointer return type. template - bool RegisterMemberGetter(const String& name, ReturnType* (Object::* member_get_func_ptr)()) { + bool RegisterMemberGetter(const String& name, ReturnType* (Object::*member_get_func_ptr)()) + { return CreateMemberGetFuncDefinition(name, member_get_func_ptr); } // Member getter with value return type, only valid for scalar return types. template - bool RegisterMemberGetter(const String& name, ReturnType (Object::* member_get_func_ptr)()) { + bool RegisterMemberGetter(const String& name, ReturnType (Object::*member_get_func_ptr)()) + { using SetType = VoidMemberFunc Object::*; return CreateMemberScalarGetSetFuncDefinition(name, member_get_func_ptr, SetType{}); } - template - bool CreateMemberObjectDefinition(const String& name, MemberType Object::* member_ptr); + template + bool CreateMemberObjectDefinition(const String& name, MemberType Object::*member_ptr); - template - bool CreateMemberGetFuncDefinition(const String& name, MemberType Object::* member_get_func_ptr); + template + bool CreateMemberGetFuncDefinition(const String& name, MemberType Object::*member_get_func_ptr); - template - bool CreateMemberScalarGetSetFuncDefinition(const String& name, MemberGetType Object::* member_get_func_ptr, MemberSetType Object::* member_set_func_ptr); + template + bool CreateMemberScalarGetSetFuncDefinition(const String& name, MemberGetType Object::*member_get_func_ptr, + MemberSetType Object::*member_set_func_ptr); DataTypeRegister* type_register; StructDefinition* struct_definition; }; - - -template -template -bool StructHandle::CreateMemberObjectDefinition(const String& name, MemberType Object::* member_ptr) +template +template +bool StructHandle::CreateMemberObjectDefinition(const String& name, MemberType Object::*member_ptr) { using MemberObjectPtr = MemberType Object::*; - // If the member function signature doesn't match the getter function signature, it will end up calling this function. Emit a compile error in that case. - static_assert(!std::is_member_function_pointer::value, "Illegal data member getter function signature. Make sure it takes no arguments and is not const qualified."); + // If the member function signature doesn't match the getter function signature, it will end up calling this function. Emit a compile error in + // that case. + static_assert(!std::is_member_function_pointer::value, + "Illegal data member getter function signature. Make sure it takes no arguments and is not const qualified."); static_assert(!std::is_const::value, "Data member objects cannot be const qualified."); VariableDefinition* underlying_definition = type_register->GetDefinition(); if (!underlying_definition) return false; - struct_definition->AddMember( - name, - Rml::MakeUnique>(underlying_definition, member_ptr) - ); + struct_definition->AddMember(name, Rml::MakeUnique>(underlying_definition, member_ptr)); return true; } -template -template -bool StructHandle::CreateMemberGetFuncDefinition(const String& name, MemberType Object::* member_get_func_ptr) +template +template +bool StructHandle::CreateMemberGetFuncDefinition(const String& name, MemberType Object::*member_get_func_ptr) { static_assert(!std::is_const::value, "Returned type from data member function cannot be const qualified."); @@ -166,18 +168,18 @@ bool StructHandle::CreateMemberGetFuncDefinition(const String& name, Mem if (!underlying_definition) return false; - struct_definition->AddMember( - name, - Rml::MakeUnique>(underlying_definition, member_get_func_ptr) - ); + struct_definition->AddMember(name, + Rml::MakeUnique>(underlying_definition, member_get_func_ptr)); return true; } -template -template -bool StructHandle::CreateMemberScalarGetSetFuncDefinition(const String& name, MemberGetType Object::* member_get_func_ptr, MemberSetType Object::* member_set_func_ptr) +template +template +bool StructHandle::CreateMemberScalarGetSetFuncDefinition(const String& name, MemberGetType Object::*member_get_func_ptr, + MemberSetType Object::*member_set_func_ptr) { - static_assert(std::is_default_constructible::value, "Struct member getter/setter functions must return/assign a type that is default constructible."); + static_assert(std::is_default_constructible::value, + "Struct member getter/setter functions must return/assign a type that is default constructible."); static_assert(!std::is_const::value, "Const qualified type illegal in data member getter functions."); if (!IsVoidMemberFunc::value) @@ -195,14 +197,15 @@ bool StructHandle::CreateMemberScalarGetSetFuncDefinition(const String& if (underlying_definition->Type() != DataVariableType::Scalar) { - RMLUI_LOG_TYPE_ERROR(UnderlyingType, "Only scalar data variables are allowed here. Data member functions require scalar types when returning by value, or using getter/setter function pairs."); + RMLUI_LOG_TYPE_ERROR(UnderlyingType, + "Only scalar data variables are allowed here. Data member functions require scalar types when returning by value, or using getter/setter " + "function pairs."); return false; } - struct_definition->AddMember( - name, - Rml::MakeUnique>(underlying_definition, member_get_func_ptr, member_set_func_ptr) - ); + struct_definition->AddMember(name, + Rml::MakeUnique>(underlying_definition, + member_get_func_ptr, member_set_func_ptr)); return true; } diff --git a/Include/RmlUi/Core/DataTypeRegister.h b/Include/RmlUi/Core/DataTypeRegister.h index eab02df96..77a3cfceb 100644 --- a/Include/RmlUi/Core/DataTypeRegister.h +++ b/Include/RmlUi/Core/DataTypeRegister.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,22 +29,19 @@ #ifndef RMLUI_CORE_DATATYPEREGISTER_H #define RMLUI_CORE_DATATYPEREGISTER_H -#include "Header.h" -#include "Types.h" -#include "Traits.h" #include "DataTypes.h" #include "DataVariable.h" - +#include "Header.h" +#include "Traits.h" +#include "Types.h" namespace Rml { -template +template struct is_builtin_data_scalar { - static constexpr bool value = std::is_arithmetic::value - || std::is_same::type, String>::value; + static constexpr bool value = std::is_arithmetic::value || std::is_same::type, String>::value; }; - class RMLUICORE_API TransformFuncRegister { public: void Register(const String& name, DataTransformFunc transform_func); @@ -54,7 +51,6 @@ class RMLUICORE_API TransformFuncRegister { UnorderedMap transform_functions; }; - class RMLUICORE_API DataTypeRegister final : NonCopyMoveable { public: DataTypeRegister(); @@ -66,20 +62,18 @@ class RMLUICORE_API DataTypeRegister final : NonCopyMoveable { return inserted; } - template + template VariableDefinition* GetDefinition() { return GetDefinitionDetail(); } - inline TransformFuncRegister* GetTransformFuncRegister() { - return &transform_register; - } + inline TransformFuncRegister* GetTransformFuncRegister() { return &transform_register; } private: // Get definition for scalar types that can be assigned to and from Rml::Variant. // We automatically register these when needed, so users don't have to register trivial types manually. - template::is_pointer::value && is_builtin_data_scalar::value, int>::type = 0> + template ::is_pointer::value && is_builtin_data_scalar::value, int>::type = 0> VariableDefinition* GetDefinitionDetail() { static_assert(!std::is_const::value, "Data binding variables cannot point to constant variables."); @@ -97,14 +91,16 @@ class RMLUICORE_API DataTypeRegister final : NonCopyMoveable { // Get definition for types that are not a built-in scalar. // These must already have been registered by the user. - template::is_pointer::value && !is_builtin_data_scalar::value, int>::type = 0> + template ::is_pointer::value && !is_builtin_data_scalar::value, int>::type = 0> VariableDefinition* GetDefinitionDetail() { FamilyId id = Family::Id(); auto it = type_register.find(id); if (it == type_register.end()) { - RMLUI_LOG_TYPE_ERROR(T, "Desired data type T not registered with the type register, please use the 'Register...()' functions before binding values, adding members, or registering arrays of non-scalar types."); + RMLUI_LOG_TYPE_ERROR(T, + "Desired data type T not registered with the type register, please use the 'Register...()' functions before binding values, adding " + "members, or registering arrays of non-scalar types."); return nullptr; } @@ -113,13 +109,14 @@ class RMLUICORE_API DataTypeRegister final : NonCopyMoveable { // Get definition for pointer types, or create one as needed. // This will create a wrapper definition that forwards the call to the definition of the underlying type. - template::is_pointer::value, int>::type = 0> + template ::is_pointer::value, int>::type = 0> VariableDefinition* GetDefinitionDetail() { static_assert(PointerTraits::is_pointer::value, "Invalid pointer type provided."); using UnderlyingType = typename PointerTraits::element_type; - static_assert(!PointerTraits::is_pointer::value, "Recursive pointer types (pointer to pointer) to data variables are disallowed."); + static_assert(!PointerTraits::is_pointer::value, + "Recursive pointer types (pointer to pointer) to data variables are disallowed."); static_assert(!std::is_const::value, "Pointer to a const data variable is not supported."); // Get the underlying definition. @@ -147,6 +144,5 @@ class RMLUICORE_API DataTypeRegister final : NonCopyMoveable { TransformFuncRegister transform_register; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/DataTypes.h b/Include/RmlUi/Core/DataTypes.h index 792b3c8ab..1cd2c8185 100644 --- a/Include/RmlUi/Core/DataTypes.h +++ b/Include/RmlUi/Core/DataTypes.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,65 +46,62 @@ using DataSetFunc = Function; using DataTransformFunc = Function; using DataEventFunc = Function; -template using MemberGetFunc = void(T::*)(Variant&); -template using MemberSetFunc = void(T::*)(const Variant&); +template +using MemberGetFunc = void (T::*)(Variant&); +template +using MemberSetFunc = void (T::*)(const Variant&); -template using DataTypeGetFunc = void(*)(const T&, Variant&); -template using DataTypeSetFunc = void(*)(T&, const Variant&); +template +using DataTypeGetFunc = void (*)(const T&, Variant&); +template +using DataTypeSetFunc = void (*)(T&, const Variant&); -template using MemberGetterFunc = ReturnType(Object::*)(); -template using MemberSetterFunc = void(Object::*)(AssignType); +template +using MemberGetterFunc = ReturnType (Object::*)(); +template +using MemberSetterFunc = void (Object::*)(AssignType); using DirtyVariables = SmallUnorderedSet; struct DataAddressEntry { - DataAddressEntry(String name) : name(std::move(name)), index(-1) { } - DataAddressEntry(int index) : index(index) { } + DataAddressEntry(String name) : name(std::move(name)), index(-1) {} + DataAddressEntry(int index) : index(index) {} String name; int index; }; using DataAddress = Vector; -template +template struct PointerTraits { using is_pointer = std::false_type; using element_type = T; - static void* Dereference(void* ptr) { - return ptr; - } + static void* Dereference(void* ptr) { return ptr; } }; -template +template struct PointerTraits { using is_pointer = std::true_type; using element_type = T; - static void* Dereference(void* ptr) { - return static_cast(*static_cast(ptr)); - } + static void* Dereference(void* ptr) { return static_cast(*static_cast(ptr)); } }; -template +template struct PointerTraits> { using is_pointer = std::true_type; using element_type = T; - static void* Dereference(void* ptr) { - return static_cast(static_cast*>(ptr)->get()); - } + static void* Dereference(void* ptr) { return static_cast(static_cast*>(ptr)->get()); } }; -template +template struct PointerTraits> { using is_pointer = std::true_type; using element_type = T; - static void* Dereference(void* ptr) { - return static_cast(static_cast*>(ptr)->get()); - } + static void* Dereference(void* ptr) { return static_cast(static_cast*>(ptr)->get()); } }; struct VoidMemberFunc {}; -template using IsVoidMemberFunc = std::is_same; - +template +using IsVoidMemberFunc = std::is_same; #define RMLUI_LOG_TYPE_ERROR(T, msg) RMLUI_ERRORMSG((String(msg) + String("\nT: ") + String(rmlui_type_name())).c_str()) #define RMLUI_LOG_TYPE_ERROR_ASSERT(T, val, msg) RMLUI_ASSERTMSG((val), (String(msg) + String("\nT: ") + String(rmlui_type_name())).c_str()) - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/DataVariable.h b/Include/RmlUi/Core/DataVariable.h index 0ff6de38c..cede5715c 100644 --- a/Include/RmlUi/Core/DataVariable.h +++ b/Include/RmlUi/Core/DataVariable.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,23 +29,22 @@ #ifndef RMLUI_CORE_DATAVARIABLE_H #define RMLUI_CORE_DATAVARIABLE_H +#include "DataTypes.h" #include "Header.h" -#include "Types.h" #include "Traits.h" +#include "Types.h" #include "Variant.h" -#include "DataTypes.h" #include namespace Rml { enum class DataVariableType { Scalar, Array, Struct }; - /* -* A 'DataVariable' wraps a user handle (pointer) and a VariableDefinition. -* -* Together they can be used to get and set variables between the user side and data model side. -*/ + * A 'DataVariable' wraps a user handle (pointer) and a VariableDefinition. + * + * Together they can be used to get and set variables between the user side and data model side. + */ class RMLUICORE_API DataVariable { public: @@ -65,12 +64,11 @@ class RMLUICORE_API DataVariable { void* ptr = nullptr; }; - /* -* A 'VariableDefinition' specifies how a user handle (pointer) is translated to and from a value in the data model. -* -* Generally, Scalar types can set and get values, while Array and Struct types can retrieve children based on data addresses. -*/ + * A 'VariableDefinition' specifies how a user handle (pointer) is translated to and from a value in the data model. + * + * Generally, Scalar types can set and get values, while Array and Struct types can retrieve children based on data addresses. + */ class RMLUICORE_API VariableDefinition : public NonCopyMoveable { public: @@ -93,8 +91,7 @@ class RMLUICORE_API VariableDefinition : public NonCopyMoveable { // Literal data variable constructor RMLUICORE_API DataVariable MakeLiteralIntVariable(int value); - -template +template class ScalarDefinition final : public VariableDefinition { public: ScalarDefinition() : VariableDefinition(DataVariableType::Scalar) {} @@ -104,13 +101,9 @@ class ScalarDefinition final : public VariableDefinition { variant = *static_cast(ptr); return true; } - bool Set(void* ptr, const Variant& variant) override - { - return variant.GetInto(*static_cast(ptr)); - } + bool Set(void* ptr, const Variant& variant) override { return variant.GetInto(*static_cast(ptr)); } }; - class RMLUICORE_API FuncDefinition final : public VariableDefinition { public: FuncDefinition(DataGetFunc get, DataSetFunc set); @@ -123,8 +116,7 @@ class RMLUICORE_API FuncDefinition final : public VariableDefinition { DataSetFunc set; }; - -template +template class ScalarFuncDefinition final : public VariableDefinition { public: ScalarFuncDefinition(DataTypeGetFunc get, DataTypeSetFunc set) : VariableDefinition(DataVariableType::Scalar), get(get), set(set) {} @@ -149,7 +141,6 @@ class ScalarFuncDefinition final : public VariableDefinition { DataTypeSetFunc set; }; - class RMLUICORE_API StructDefinition final : public VariableDefinition { public: StructDefinition(); @@ -162,15 +153,14 @@ class RMLUICORE_API StructDefinition final : public VariableDefinition { SmallUnorderedMap> members; }; - -template +template class ArrayDefinition final : public VariableDefinition { public: - ArrayDefinition(VariableDefinition* underlying_definition) : VariableDefinition(DataVariableType::Array) , underlying_definition(underlying_definition) {} + ArrayDefinition(VariableDefinition* underlying_definition) : + VariableDefinition(DataVariableType::Array), underlying_definition(underlying_definition) + {} - int Size(void* ptr) override { - return int(static_cast(ptr)->size()); - } + int Size(void* ptr) override { return int(static_cast(ptr)->size()); } protected: DataVariable Child(void* void_ptr, const DataAddressEntry& address) override @@ -199,7 +189,6 @@ class ArrayDefinition final : public VariableDefinition { VariableDefinition* underlying_definition; }; - class RMLUICORE_API BasePointerDefinition : public VariableDefinition { public: BasePointerDefinition(VariableDefinition* underlying_definition); @@ -216,79 +205,69 @@ class RMLUICORE_API BasePointerDefinition : public VariableDefinition { VariableDefinition* underlying_definition; }; -template +template class PointerDefinition final : public BasePointerDefinition { public: PointerDefinition(VariableDefinition* underlying_definition) : BasePointerDefinition(underlying_definition) {} protected: - void* DereferencePointer(void* ptr) override { - return PointerTraits::Dereference(ptr); - } + void* DereferencePointer(void* ptr) override { return PointerTraits::Dereference(ptr); } }; -template +template class MemberObjectDefinition final : public BasePointerDefinition { public: - MemberObjectDefinition(VariableDefinition* underlying_definition, MemberType Object::* member_ptr) : BasePointerDefinition(underlying_definition), member_ptr(member_ptr) {} + MemberObjectDefinition(VariableDefinition* underlying_definition, MemberType Object::*member_ptr) : + BasePointerDefinition(underlying_definition), member_ptr(member_ptr) + {} protected: - void* DereferencePointer(void* base_ptr) override { - return &(static_cast(base_ptr)->*member_ptr); - } + void* DereferencePointer(void* base_ptr) override { return &(static_cast(base_ptr)->*member_ptr); } private: - MemberType Object::* member_ptr; + MemberType Object::*member_ptr; }; - -template +template class MemberGetFuncDefinition final : public BasePointerDefinition { public: - - MemberGetFuncDefinition(VariableDefinition* underlying_definition, MemberType Object::* member_get_func_ptr) - : BasePointerDefinition(underlying_definition), member_get_func_ptr(member_get_func_ptr) + MemberGetFuncDefinition(VariableDefinition* underlying_definition, MemberType Object::*member_get_func_ptr) : + BasePointerDefinition(underlying_definition), member_get_func_ptr(member_get_func_ptr) {} protected: - void* DereferencePointer(void* base_ptr) override { + void* DereferencePointer(void* base_ptr) override + { return static_cast(Extract((static_cast(base_ptr)->*member_get_func_ptr)())); } private: - BasicReturnType* Extract(BasicReturnType* value) { - return value; - } - BasicReturnType* Extract(BasicReturnType& value) { - return &value; - } + BasicReturnType* Extract(BasicReturnType* value) { return value; } + BasicReturnType* Extract(BasicReturnType& value) { return &value; } - MemberType Object::* member_get_func_ptr; + MemberType Object::*member_get_func_ptr; }; - -template +template class MemberScalarGetSetFuncDefinition final : public VariableDefinition { public: - MemberScalarGetSetFuncDefinition(VariableDefinition* underlying_definition, MemberGetType Object::* member_get_func_ptr, MemberSetType Object::* member_set_func_ptr) - : VariableDefinition(underlying_definition->Type()), underlying_definition(underlying_definition), member_get_func_ptr(member_get_func_ptr), member_set_func_ptr(member_set_func_ptr) + MemberScalarGetSetFuncDefinition(VariableDefinition* underlying_definition, MemberGetType Object::*member_get_func_ptr, + MemberSetType Object::*member_set_func_ptr) : + VariableDefinition(underlying_definition->Type()), + underlying_definition(underlying_definition), member_get_func_ptr(member_get_func_ptr), member_set_func_ptr(member_set_func_ptr) {} - bool Get(void* ptr, Variant& variant) override { - return GetDetail(ptr, variant); - } - bool Set(void* ptr, const Variant& variant) override { - return SetDetail(ptr, variant); - } + bool Get(void* ptr, Variant& variant) override { return GetDetail(ptr, variant); } + bool Set(void* ptr, const Variant& variant) override { return SetDetail(ptr, variant); } private: - template::value, int>::type = 0> + template ::value, int>::type = 0> bool GetDetail(void* /*ptr*/, Variant& /*variant*/) { return false; } - template::value, int>::type = 0> + template ::value, int>::type = 0> bool GetDetail(void* ptr, Variant& variant) { RMLUI_ASSERT(member_get_func_ptr); @@ -298,13 +277,13 @@ class MemberScalarGetSetFuncDefinition final : public VariableDefinition { return result; } - template::value, int>::type = 0> + template ::value, int>::type = 0> bool SetDetail(void* /*ptr*/, const Variant& /*variant*/) { return false; } - template::value, int>::type = 0> + template ::value, int>::type = 0> bool SetDetail(void* ptr, const Variant& variant) { RMLUI_ASSERT(member_set_func_ptr); @@ -319,10 +298,9 @@ class MemberScalarGetSetFuncDefinition final : public VariableDefinition { } VariableDefinition* underlying_definition; - MemberGetType Object::* member_get_func_ptr; - MemberSetType Object::* member_set_func_ptr; + MemberGetType Object::*member_get_func_ptr; + MemberSetType Object::*member_set_func_ptr; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Debug.h b/Include/RmlUi/Core/Debug.h index 0e59079ef..a16a7b15b 100644 --- a/Include/RmlUi/Core/Debug.h +++ b/Include/RmlUi/Core/Debug.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,27 +32,38 @@ #include "Header.h" // Define for breakpointing. -#if defined (RMLUI_PLATFORM_WIN32) - #if defined (__MINGW32__) - #define RMLUI_BREAK {asm("int $0x03");} - #elif defined (_MSC_VER) - #define RMLUI_BREAK {__debugbreak();} +#if defined(RMLUI_PLATFORM_WIN32) + #if defined(__MINGW32__) + #define RMLUI_BREAK \ + { \ + asm("int $0x03"); \ + } + #elif defined(_MSC_VER) + #define RMLUI_BREAK \ + { \ + __debugbreak(); \ + } #else #define RMLUI_BREAK #endif -#elif defined (RMLUI_PLATFORM_LINUX) +#elif defined(RMLUI_PLATFORM_LINUX) #if defined __GNUC__ - #define RMLUI_BREAK {__builtin_trap();} + #define RMLUI_BREAK \ + { \ + __builtin_trap(); \ + } #else #define RMLUI_BREAK #endif -#elif defined (RMLUI_PLATFORM_MACOSX) - #define RMLUI_BREAK {__builtin_trap();} +#elif defined(RMLUI_PLATFORM_MACOSX) + #define RMLUI_BREAK \ + { \ + __builtin_trap(); \ + } #else #define RMLUI_BREAK #endif - namespace Rml { bool RMLUICORE_API Assert(const char* message, const char* file, int line); @@ -62,58 +73,57 @@ bool RMLUICORE_API Assert(const char* message, const char* file, int line); // Define the RmlUi assertion macros. #if !defined RMLUI_DEBUG -#define RMLUI_ASSERT(x) -#define RMLUI_ASSERTMSG(x, m) -#define RMLUI_ERROR -#define RMLUI_ERRORMSG(m) -#define RMLUI_VERIFY(x) x -#define RMLUI_ASSERT_NONRECURSIVE + #define RMLUI_ASSERT(x) + #define RMLUI_ASSERTMSG(x, m) + #define RMLUI_ERROR + #define RMLUI_ERRORMSG(m) + #define RMLUI_VERIFY(x) x + #define RMLUI_ASSERT_NONRECURSIVE #else -#define RMLUI_ASSERT(x) \ -if (!(x)) \ -{ \ - if (!(::Rml::Assert("RMLUI_ASSERT("#x")", __FILE__, __LINE__ ))) \ - { \ - RMLUI_BREAK; \ - } \ -} -#define RMLUI_ASSERTMSG(x, m) \ -if (!(x)) \ -{ \ - if (!(::Rml::Assert(m, __FILE__, __LINE__ ))) \ - { \ - RMLUI_BREAK; \ - } \ -} -#define RMLUI_ERROR \ -if (!(::Rml::Assert("RMLUI_ERROR", __FILE__, __LINE__))) \ -{ \ - RMLUI_BREAK; \ -} -#define RMLUI_ERRORMSG(m) \ -if (!(::Rml::Assert(m, __FILE__, __LINE__))) \ -{ \ - RMLUI_BREAK; \ -} -#define RMLUI_VERIFY(x) RMLUI_ASSERT(x) + #define RMLUI_ASSERT(x) \ + if (!(x)) \ + { \ + if (!(::Rml::Assert("RMLUI_ASSERT(" #x ")", __FILE__, __LINE__))) \ + { \ + RMLUI_BREAK; \ + } \ + } + #define RMLUI_ASSERTMSG(x, m) \ + if (!(x)) \ + { \ + if (!(::Rml::Assert(m, __FILE__, __LINE__))) \ + { \ + RMLUI_BREAK; \ + } \ + } + #define RMLUI_ERROR \ + if (!(::Rml::Assert("RMLUI_ERROR", __FILE__, __LINE__))) \ + { \ + RMLUI_BREAK; \ + } + #define RMLUI_ERRORMSG(m) \ + if (!(::Rml::Assert(m, __FILE__, __LINE__))) \ + { \ + RMLUI_BREAK; \ + } + #define RMLUI_VERIFY(x) RMLUI_ASSERT(x) struct RmlUiAssertNonrecursive { bool& entered; - RmlUiAssertNonrecursive(bool& entered) : entered(entered) { + RmlUiAssertNonrecursive(bool& entered) : entered(entered) + { RMLUI_ASSERTMSG(!entered, "A method defined as non-recursive was entered twice!"); entered = true; } - ~RmlUiAssertNonrecursive() { - entered = false; - } + ~RmlUiAssertNonrecursive() { entered = false; } }; -#define RMLUI_ASSERT_NONRECURSIVE \ -static bool rmlui_nonrecursive_entered = false; \ -RmlUiAssertNonrecursive rmlui_nonrecursive(rmlui_nonrecursive_entered) + #define RMLUI_ASSERT_NONRECURSIVE \ + static bool rmlui_nonrecursive_entered = false; \ + RmlUiAssertNonrecursive rmlui_nonrecursive(rmlui_nonrecursive_entered) -#endif // RMLUI_DEBUG +#endif // RMLUI_DEBUG -#endif // RMLUI_CORE_DEBUG_H +#endif // RMLUI_CORE_DEBUG_H diff --git a/Include/RmlUi/Core/Decorator.h b/Include/RmlUi/Core/Decorator.h index fa7878cbb..2e81bc9dd 100644 --- a/Include/RmlUi/Core/Decorator.h +++ b/Include/RmlUi/Core/Decorator.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,13 +42,12 @@ class Property; struct Texture; /** - The abstract base class for any visual object that can be attached to any element. + The abstract base class for any visual object that can be attached to any element. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API Decorator -{ +class RMLUICORE_API Decorator { public: Decorator(); virtual ~Decorator(); @@ -85,7 +84,7 @@ class RMLUICORE_API Decorator // Stores a list of textures in use by this decorator. // Optimized for the common case of a single texture. Texture first_texture; - Vector< Texture > additional_textures; + Vector additional_textures; }; } // namespace Rml diff --git a/Include/RmlUi/Core/DecoratorInstancer.h b/Include/RmlUi/Core/DecoratorInstancer.h index b51ea32a3..6db5121dc 100644 --- a/Include/RmlUi/Core/DecoratorInstancer.h +++ b/Include/RmlUi/Core/DecoratorInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -43,16 +43,15 @@ class DecoratorInstancerInterface; class PropertyDefinition; /** - An element instancer provides a method for allocating and deallocating decorators. + An element instancer provides a method for allocating and deallocating decorators. - It is important at the same instancer that allocated a decorator releases it. This ensures there are no issues with - memory from different DLLs getting mixed up. + It is important at the same instancer that allocated a decorator releases it. This ensures there are no issues with + memory from different DLLs getting mixed up. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API DecoratorInstancer -{ +class RMLUICORE_API DecoratorInstancer { public: DecoratorInstancer(); virtual ~DecoratorInstancer(); @@ -62,7 +61,8 @@ class RMLUICORE_API DecoratorInstancer /// @param[in] properties All RCSS properties associated with the decorator. /// @param[in] instancer_interface An interface for querying the active style sheet. /// @return A shared_ptr to the decorator if it was instanced successfully. - virtual SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) = 0; + virtual SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) = 0; /// Returns the property specification associated with the instancer. const PropertySpecification& GetPropertySpecification() const; @@ -75,7 +75,8 @@ class RMLUICORE_API DecoratorInstancer PropertyDefinition& RegisterProperty(const String& property_name, const String& default_value); /// Registers a shorthand property definition. Specify a shorthand name of 'decorator' to parse anonymous decorators. /// @param[in] shorthand_name The name to register the new shorthand property under. - /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is the order in which the values will be processed. + /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is + /// the order in which the values will be processed. /// @param[in] type The type of shorthand to declare. /// @param True if all the property names exist, false otherwise. ShorthandId RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type); @@ -84,10 +85,11 @@ class RMLUICORE_API DecoratorInstancer PropertySpecification properties; }; - class RMLUICORE_API DecoratorInstancerInterface { public: - DecoratorInstancerInterface(const StyleSheet& style_sheet, const PropertySource* property_source) : style_sheet(style_sheet), property_source(property_source) {} + DecoratorInstancerInterface(const StyleSheet& style_sheet, const PropertySource* property_source) : + style_sheet(style_sheet), property_source(property_source) + {} /// Get a sprite from any @spritesheet in the style sheet the decorator is being instanced on. const Sprite* GetSprite(const String& name) const; diff --git a/Include/RmlUi/Core/Dictionary.h b/Include/RmlUi/Core/Dictionary.h index d5c12407c..e0feb7214 100644 --- a/Include/RmlUi/Core/Dictionary.h +++ b/Include/RmlUi/Core/Dictionary.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -48,7 +48,7 @@ inline const Variant* GetIf(const Dictionary& dictionary, const String& key) return &(it->second); return nullptr; } -template +template inline T Get(const Dictionary& dictionary, const String& key, const T& default_value) { T result = default_value; diff --git a/Include/RmlUi/Core/Element.h b/Include/RmlUi/Core/Element.h index 12c064135..eb7b26866 100644 --- a/Include/RmlUi/Core/Element.h +++ b/Include/RmlUi/Core/Element.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -68,13 +68,12 @@ struct ElementMeta; struct StackingContextChild; /** - A generic element in the DOM tree. + A generic element in the DOM tree. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr -{ +class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr { public: RMLUI_RTTI_DefineWithParent(Element, ScriptInterface) @@ -207,16 +206,16 @@ class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr + template T GetProperty(const String& name); /// Returns one of this element's properties. If this element is not defined this property, nullptr will be /// returned. @@ -233,7 +232,7 @@ class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr + template void SetAttribute(const String& name, const T& value); /// Gets the specified attribute. /// @param[in] name Name of the attribute to retrieve. @@ -310,7 +310,7 @@ class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr + template T GetAttribute(const String& name, const T& default_value) const; /// Checks if the element has a certain attribute. /// @param[in] name The name of the attribute to check for. @@ -447,7 +447,8 @@ class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr; + using PositionedBoxList = Vector; Box main_box; PositionedBoxList additional_boxes; @@ -780,8 +782,8 @@ class RMLUICORE_API Element : public ScriptInterface, public EnableObserverPtr transform_state; + + UniquePtr transform_state; ElementAnimationList animations; diff --git a/Include/RmlUi/Core/Element.inl b/Include/RmlUi/Core/Element.inl index 832138e21..963625ec7 100644 --- a/Include/RmlUi/Core/Element.inl +++ b/Include/RmlUi/Core/Element.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,7 +29,7 @@ namespace Rml { // Returns the values of one of this element's properties. -template < typename T > +template T Element::GetProperty(const String& name) { const Property* property = GetProperty(name); @@ -38,22 +38,22 @@ T Element::GetProperty(const String& name) Log::Message(Log::LT_WARNING, "Invalid property name %s.", name.c_str()); return T{}; } - return property->Get< T >(); + return property->Get(); } // Sets an attribute on the element. -template< typename T > +template void Element::SetAttribute(const String& name, const T& value) { Variant variant(value); attributes[name] = variant; - ElementAttributes changed_attributes; - changed_attributes.emplace(name, std::move(variant)); + ElementAttributes changed_attributes; + changed_attributes.emplace(name, std::move(variant)); OnAttributeChange(changed_attributes); } // Gets the specified attribute, with default value. -template< typename T > +template T Element::GetAttribute(const String& name, const T& default_value) const { return Get(attributes, name, default_value); diff --git a/Include/RmlUi/Core/ElementDocument.h b/Include/RmlUi/Core/ElementDocument.h index 5c14890c7..95db9e198 100644 --- a/Include/RmlUi/Core/ElementDocument.h +++ b/Include/RmlUi/Core/ElementDocument.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -41,29 +41,27 @@ class StyleSheet; class StyleSheetContainer; /** - ModalFlag used for controlling the modal state of the document. - None: Remove modal state. - Modal: Set modal state, other documents cannot receive focus. - Keep: Modal state unchanged. - - FocusFlag used for displaying the document. - None: No focus. - Document: Focus the document. - Keep: Focus the element in the document which last had focus. - Auto: Focus the first tab element with the 'autofocus' attribute or else the document. + ModalFlag used for controlling the modal state of the document. + None: Remove modal state. + Modal: Set modal state, other documents cannot receive focus. + Keep: Modal state unchanged. + + FocusFlag used for displaying the document. + None: No focus. + Document: Focus the document. + Keep: Focus the element in the document which last had focus. + Auto: Focus the first tab element with the 'autofocus' attribute or else the document. */ enum class ModalFlag { None, Modal, Keep }; enum class FocusFlag { None, Document, Keep, Auto }; - /** - Represents a document in the dom tree. + Represents a document in the dom tree. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API ElementDocument : public Element -{ +class RMLUICORE_API ElementDocument : public Element { public: RMLUI_RTTI_DefineWithParent(ElementDocument, Element) @@ -135,11 +133,11 @@ class RMLUICORE_API ElementDocument : public Element /// @param[in] source_path The script file path. virtual void LoadExternalScript(const String& source_path); - /// Updates the document, including its layout. Users must call this manually before requesting information such as + /// Updates the document, including its layout. Users must call this manually before requesting information such as /// size or position of an element if any element in the document was recently changed, unless Context::Update has /// already been called after the change. This has a perfomance penalty, only call when necessary. void UpdateDocument(); - + protected: /// Repositions the document if necessary. void OnPropertyChange(const PropertyIdSet& changed_properties) override; @@ -196,7 +194,6 @@ class RMLUICORE_API ElementDocument : public Element friend class Rml::Context; friend class Rml::Factory; - }; } // namespace Rml diff --git a/Include/RmlUi/Core/ElementInstancer.h b/Include/RmlUi/Core/ElementInstancer.h index 2ebba6509..36c91b6a3 100644 --- a/Include/RmlUi/Core/ElementInstancer.h +++ b/Include/RmlUi/Core/ElementInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,33 +29,32 @@ #ifndef RMLUI_CORE_ELEMENTINSTANCER_H #define RMLUI_CORE_ELEMENTINSTANCER_H -#include "Traits.h" -#include "Types.h" -#include "Header.h" #include "Element.h" +#include "Header.h" #include "Profiling.h" +#include "Traits.h" +#include "Types.h" namespace Rml { class Element; /** - An element instancer provides a method for allocating - and deallocating elements. + An element instancer provides a method for allocating + and deallocating elements. - It is important at the same instancer that allocated - the element releases it. This ensures there are no - issues with memory from different DLLs getting mixed up. + It is important at the same instancer that allocated + the element releases it. This ensures there are no + issues with memory from different DLLs getting mixed up. - The returned element is a unique pointer. When this is - destroyed, it will call ReleaseElement on the instancer - in which it was instanced. + The returned element is a unique pointer. When this is + destroyed, it will call ReleaseElement on the instancer + in which it was instanced. - @author Lloyd Weehuizen - */ + @author Lloyd Weehuizen + */ -class RMLUICORE_API ElementInstancer : public NonCopyMoveable -{ +class RMLUICORE_API ElementInstancer : public NonCopyMoveable { public: virtual ~ElementInstancer(); @@ -70,16 +69,13 @@ class RMLUICORE_API ElementInstancer : public NonCopyMoveable virtual void ReleaseElement(Element* element) = 0; }; - - /** - The element instancer constructs a plain Element, and is used for most elements. - This is a slightly faster version of the generic instancer, making use of a memory - pool for allocations. + The element instancer constructs a plain Element, and is used for most elements. + This is a slightly faster version of the generic instancer, making use of a memory + pool for allocations. */ -class RMLUICORE_API ElementInstancerElement : public ElementInstancer -{ +class RMLUICORE_API ElementInstancerElement : public ElementInstancer { public: ElementPtr InstanceElement(Element* parent, const String& tag, const XMLAttributes& attributes) override; void ReleaseElement(Element* element) override; @@ -87,34 +83,29 @@ class RMLUICORE_API ElementInstancerElement : public ElementInstancer }; /** - The element text instancer constructs ElementText. - This is a slightly faster version of the generic instancer, making use of a memory - pool for allocations. + The element text instancer constructs ElementText. + This is a slightly faster version of the generic instancer, making use of a memory + pool for allocations. */ -class RMLUICORE_API ElementInstancerText : public ElementInstancer -{ +class RMLUICORE_API ElementInstancerText : public ElementInstancer { public: ElementPtr InstanceElement(Element* parent, const String& tag, const XMLAttributes& attributes) override; void ReleaseElement(Element* element) override; }; - /** - Generic Instancer that creates the provided element type using new and delete. This instancer - is typically used for specialized element types. + Generic Instancer that creates the provided element type using new and delete. This instancer + is typically used for specialized element types. */ template -class ElementInstancerGeneric : public ElementInstancer -{ +class ElementInstancerGeneric : public ElementInstancer { public: virtual ~ElementInstancerGeneric() {} - ElementPtr InstanceElement(Element* RMLUI_UNUSED_PARAMETER(parent), const String& tag, const XMLAttributes& RMLUI_UNUSED_PARAMETER(attributes)) override + ElementPtr InstanceElement(Element* /*parent*/, const String& tag, const XMLAttributes& /*attributes*/) override { - RMLUI_UNUSED(parent); - RMLUI_UNUSED(attributes); RMLUI_ZoneScopedN("ElementGenericInstance"); return ElementPtr(new T(tag)); } diff --git a/Include/RmlUi/Core/ElementScroll.h b/Include/RmlUi/Core/ElementScroll.h index a20532018..9f428ffdb 100644 --- a/Include/RmlUi/Core/ElementScroll.h +++ b/Include/RmlUi/Core/ElementScroll.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,19 +38,14 @@ class Element; class WidgetScroll; /** - Manages an element's scrollbars and scrolling state. + Manages an element's scrollbars and scrolling state. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementScroll -{ +class RMLUICORE_API ElementScroll { public: - enum Orientation - { - VERTICAL = 0, - HORIZONTAL = 1 - }; + enum Orientation { VERTICAL = 0, HORIZONTAL = 1 }; ElementScroll(Element* element); ~ElementScroll(); @@ -83,8 +78,7 @@ class RMLUICORE_API ElementScroll void FormatScrollbars(); private: - struct Scrollbar - { + struct Scrollbar { Scrollbar(); ~Scrollbar(); diff --git a/Include/RmlUi/Core/ElementText.h b/Include/RmlUi/Core/ElementText.h index efa960dd7..2fd97c257 100644 --- a/Include/RmlUi/Core/ElementText.h +++ b/Include/RmlUi/Core/ElementText.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,18 +29,17 @@ #ifndef RMLUI_CORE_ELEMENTTEXT_H #define RMLUI_CORE_ELEMENTTEXT_H -#include "Header.h" #include "Element.h" #include "Geometry.h" +#include "Header.h" namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementText final : public Element -{ +class RMLUICORE_API ElementText final : public Element { public: RMLUI_RTTI_DefineWithParent(ElementText, Element) @@ -54,12 +53,15 @@ class RMLUICORE_API ElementText final : public Element /// Generates a line of text rendered from this element. /// @param[out] line The characters making up the line, with white-space characters collapsed and endlines processed appropriately. - /// @param[out] line_length The number of characters from the source string consumed making up this string; this may very well be different from line.size()! + /// @param[out] line_length The number of characters from the source string consumed making up this string; this may very well be different from + /// line.size()! /// @param[out] line_width The width (in pixels) of the generated line. /// @param[in] line_begin The index of the first character to be rendered in the line. /// @param[in] maximum_line_width The width (in pixels) of space allowed for the line, or -1 for unlimited space. - /// @param[in] right_spacing_width The width (in pixels) of the spacing (consisting of margins, padding, etc) that must be remaining on the right of the line if the last of the text is rendered onto this line. - /// @param[in] trim_whitespace_prefix If we're collapsing whitespace, whether or not to remove all prefixing whitespace or collapse it down to a single space. + /// @param[in] right_spacing_width The width (in pixels) of the spacing (consisting of margins, padding, etc) that must be remaining on the right + /// of the line if the last of the text is rendered onto this line. + /// @param[in] trim_whitespace_prefix If we're collapsing whitespace, whether or not to remove all prefixing whitespace or collapse it down to a + /// single space. /// @param[in] decode_escape_characters Decode escaped characters such as & into &. /// @param[in] allow_empty Allow no tokens to be consumed from the line. /// @return True if the line reached the end of the element's text, false if not. @@ -88,8 +90,7 @@ class RMLUICORE_API ElementText final : public Element bool UpdateFontEffects(); // Used to store the position and length of each line we have geometry for. - struct Line - { + struct Line { Line(String text, Vector2f position) : text(std::move(text)), position(position), width(0) {} String text; Vector2f position; @@ -105,7 +106,7 @@ class RMLUICORE_API ElementText final : public Element String text; - using LineList = Vector< Line >; + using LineList = Vector; LineList lines; GeometryList geometry; @@ -121,7 +122,7 @@ class RMLUICORE_API ElementText final : public Element bool geometry_dirty : 1; bool dirty_layout_on_change : 1; - + // What the decoration type is that we have generated. Style::TextDecoration generated_decoration; // What the element's actual text-decoration property is; this may be different from the generated decoration diff --git a/Include/RmlUi/Core/ElementUtilities.h b/Include/RmlUi/Core/ElementUtilities.h index 2b01f6bd1..b9274af1b 100644 --- a/Include/RmlUi/Core/ElementUtilities.h +++ b/Include/RmlUi/Core/ElementUtilities.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,19 +37,19 @@ namespace Rml { class Box; class Context; class RenderInterface; -namespace Style { class ComputedValues; } +namespace Style { + class ComputedValues; +} /** - Utility functions for dealing with elements. + Utility functions for dealing with elements. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API ElementUtilities -{ +class RMLUICORE_API ElementUtilities { public: - enum PositionAnchor - { + enum PositionAnchor { TOP = 1 << 0, BOTTOM = 1 << 1, LEFT = 1 << 2, diff --git a/Include/RmlUi/Core/Elements/ElementForm.h b/Include/RmlUi/Core/Elements/ElementForm.h index 57fa214e6..4a7c655e2 100644 --- a/Include/RmlUi/Core/Elements/ElementForm.h +++ b/Include/RmlUi/Core/Elements/ElementForm.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - A specialisation of the generic Element representing a form element. + A specialisation of the generic Element representing a form element. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementForm : public Element -{ +class RMLUICORE_API ElementForm : public Element { public: RMLUI_RTTI_DefineWithParent(ElementForm, Element) diff --git a/Include/RmlUi/Core/Elements/ElementFormControl.h b/Include/RmlUi/Core/Elements/ElementFormControl.h index 07c6ef93f..a5c5c0494 100644 --- a/Include/RmlUi/Core/Elements/ElementFormControl.h +++ b/Include/RmlUi/Core/Elements/ElementFormControl.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - A generic specialisation of the generic Element for all input controls. + A generic specialisation of the generic Element for all input controls. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementFormControl : public Element -{ +class RMLUICORE_API ElementFormControl : public Element { public: RMLUI_RTTI_DefineWithParent(ElementFormControl, Element) diff --git a/Include/RmlUi/Core/Elements/ElementFormControlInput.h b/Include/RmlUi/Core/Elements/ElementFormControlInput.h index e42ba7a0b..ea7c3223d 100644 --- a/Include/RmlUi/Core/Elements/ElementFormControlInput.h +++ b/Include/RmlUi/Core/Elements/ElementFormControlInput.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ namespace Rml { class InputType; /** - A form control for the generic input element. All functionality is handled through an input type interface. + A form control for the generic input element. All functionality is handled through an input type interface. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementFormControlInput : public ElementFormControl -{ +class RMLUICORE_API ElementFormControlInput : public ElementFormControl { public: RMLUI_RTTI_DefineWithParent(ElementFormControlInput, ElementFormControl) diff --git a/Include/RmlUi/Core/Elements/ElementFormControlSelect.h b/Include/RmlUi/Core/Elements/ElementFormControlSelect.h index 6b139a554..7488b317c 100644 --- a/Include/RmlUi/Core/Elements/ElementFormControlSelect.h +++ b/Include/RmlUi/Core/Elements/ElementFormControlSelect.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ namespace Rml { class WidgetDropDown; /** - A drop-down select form control. + A drop-down select form control. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementFormControlSelect : public ElementFormControl -{ +class RMLUICORE_API ElementFormControlSelect : public ElementFormControl { public: RMLUI_RTTI_DefineWithParent(ElementFormControlSelect, ElementFormControl) @@ -78,7 +77,8 @@ class RMLUICORE_API ElementFormControlSelect : public ElementFormControl /// Adds a new option to the select control. /// @param[in] rml The RML content used to represent the option. This is usually a simple string, but can include RML tags. /// @param[in] value The value of the option. This is used to identify the option, but does not necessarily need to be unique. - /// @param[in] before The index of the element to insert the new option before. If out of bounds of the control's option list (the default) the new option will be added at the end of the list. + /// @param[in] before The index of the element to insert the new option before. If out of bounds of the control's option list (the default) the + /// new option will be added at the end of the list. /// @param[in] selectable If true this option can be selected. If false, this option is not selectable. /// @return The index of the new option. int Add(const String& rml, const String& value, int before = -1, bool selectable = true); @@ -104,11 +104,12 @@ class RMLUICORE_API ElementFormControlSelect : public ElementFormControl void OnLayout() override; void OnChildAdd(Element* child) override; - + void OnChildRemove(Element* child) override; /// Returns true to mark this element as replaced. - /// @param[out] intrinsic_dimensions Set to the arbitrary dimensions of 128 x 16 just to give this element a size. Resize with the 'width' and 'height' properties. + /// @param[out] intrinsic_dimensions Set to the arbitrary dimensions of 128 x 16 just to give this element a size. Resize with the 'width' and + /// 'height' properties. /// @param[out] intrinsic_ratio Ignored. /// @return True. bool GetIntrinsicDimensions(Vector2f& intrinsic_dimensions, float& intrinsic_ratio) override; diff --git a/Include/RmlUi/Core/Elements/ElementFormControlTextArea.h b/Include/RmlUi/Core/Elements/ElementFormControlTextArea.h index 511924324..fd3d8bb8a 100644 --- a/Include/RmlUi/Core/Elements/ElementFormControlTextArea.h +++ b/Include/RmlUi/Core/Elements/ElementFormControlTextArea.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ namespace Rml { class WidgetTextInputMultiLine; /** - Default RmlUi implemention of a text area. + Default RmlUi implemention of a text area. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementFormControlTextArea : public ElementFormControl -{ +class RMLUICORE_API ElementFormControlTextArea : public ElementFormControl { public: RMLUI_RTTI_DefineWithParent(ElementFormControlTextArea, ElementFormControl) diff --git a/Include/RmlUi/Core/Elements/ElementProgress.h b/Include/RmlUi/Core/Elements/ElementProgress.h index 3d0672abf..d8a1fd1bb 100644 --- a/Include/RmlUi/Core/Elements/ElementProgress.h +++ b/Include/RmlUi/Core/Elements/ElementProgress.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,36 +29,35 @@ #ifndef RMLUI_CORE_ELEMENTS_ELEMENTPROGRESS_H #define RMLUI_CORE_ELEMENTS_ELEMENTPROGRESS_H -#include "../Header.h" #include "../Element.h" #include "../Geometry.h" -#include "../Texture.h" +#include "../Header.h" #include "../Spritesheet.h" +#include "../Texture.h" namespace Rml { /** - The 'progress' element. + The 'progress' element. - The 'value' attribute should be a number [0, 1] where 1 means completely filled. + The 'value' attribute should be a number [0, 1] where 1 means completely filled. - The 'direction' attribute should be one of: - top | right (default) | bottom | left | clockwise | counter-clockwise + The 'direction' attribute should be one of: + top | right (default) | bottom | left | clockwise | counter-clockwise - The 'start-edge' attribute should be one of: - top (default) | right | bottom | left - Only applies to 'clockwise' or 'counter-clockwise' directions. Defines which edge the - circle should start expanding from. + The 'start-edge' attribute should be one of: + top (default) | right | bottom | left + Only applies to 'clockwise' or 'counter-clockwise' directions. Defines which edge the + circle should start expanding from. - The progress element generates a non-dom 'fill' element beneath it which can be used to - style the filled part of the bar. The 'fill' element can use the 'fill-image'-property - to set an image which will be clipped according to the progress value. This property is - the only way to style a 'clockwise' or 'counter-clockwise' progress element. + The progress element generates a non-dom 'fill' element beneath it which can be used to + style the filled part of the bar. The 'fill' element can use the 'fill-image'-property + to set an image which will be clipped according to the progress value. This property is + the only way to style a 'clockwise' or 'counter-clockwise' progress element. */ -class RMLUICORE_API ElementProgress : public Element -{ +class RMLUICORE_API ElementProgress : public Element { public: RMLUI_RTTI_DefineWithParent(ElementProgress, Element) diff --git a/Include/RmlUi/Core/Elements/ElementTabSet.h b/Include/RmlUi/Core/Elements/ElementTabSet.h index 0d68e20f6..9e7dcc230 100644 --- a/Include/RmlUi/Core/Elements/ElementTabSet.h +++ b/Include/RmlUi/Core/Elements/ElementTabSet.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - A tabulated set of panels. + A tabulated set of panels. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API ElementTabSet : public Element -{ +class RMLUICORE_API ElementTabSet : public Element { public: RMLUI_RTTI_DefineWithParent(ElementTabSet, Element) diff --git a/Include/RmlUi/Core/Event.h b/Include/RmlUi/Core/Event.h index dc4304980..2d97afc37 100644 --- a/Include/RmlUi/Core/Event.h +++ b/Include/RmlUi/Core/Event.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,10 +29,10 @@ #ifndef RMLUI_CORE_EVENT_H #define RMLUI_CORE_EVENT_H -#include "Header.h" #include "Dictionary.h" -#include "ScriptInterface.h" +#include "Header.h" #include "ID.h" +#include "ScriptInterface.h" namespace Rml { @@ -45,14 +45,13 @@ enum class EventPhase { None, Capture = 1, Target = 2, Bubble = 4 }; enum class DefaultActionPhase { None, Target = (int)EventPhase::Target, TargetAndBubble = ((int)Target | (int)EventPhase::Bubble) }; /** - An event that propogates through the element hierarchy. Events follow the DOM3 event specification. See - http://www.w3.org/TR/DOM-Level-3-Events/events.html. + An event that propogates through the element hierarchy. Events follow the DOM3 event specification. See + http://www.w3.org/TR/DOM-Level-3-Events/events.html. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API Event : public ScriptInterface -{ +class RMLUICORE_API Event : public ScriptInterface { public: /// Constructor Event(); @@ -104,7 +103,7 @@ class RMLUICORE_API Event : public ScriptInterface /// Returns the value of one of the event's parameters. /// @param key[in] The name of the desired parameter. /// @return The value of the requested parameter. - template < typename T > + template T GetParameter(const String& key, const T& default_value) const { return Get(parameters, key, default_value); @@ -134,7 +133,7 @@ class RMLUICORE_API Event : public ScriptInterface String type; EventId id = EventId::Invalid; bool interruptible = false; - + bool interrupted = false; bool interrupted_immediate = false; @@ -148,6 +147,5 @@ class RMLUICORE_API Event : public ScriptInterface friend class Rml::Factory; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/EventInstancer.h b/Include/RmlUi/Core/EventInstancer.h index 0d19d8fba..3bc1caf40 100644 --- a/Include/RmlUi/Core/EventInstancer.h +++ b/Include/RmlUi/Core/EventInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_EVENTINSTANCER_H #define RMLUI_CORE_EVENTINSTANCER_H -#include "Traits.h" #include "Header.h" +#include "Traits.h" #include "Types.h" namespace Rml { @@ -39,13 +39,12 @@ class Element; class Event; /** - Abstract instancer interface for instancing events. This is required to be overridden for scripting systems. + Abstract instancer interface for instancing events. This is required to be overridden for scripting systems. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API EventInstancer : public Releasable -{ +class RMLUICORE_API EventInstancer : public Releasable { public: virtual ~EventInstancer(); diff --git a/Include/RmlUi/Core/EventListener.h b/Include/RmlUi/Core/EventListener.h index c2afe3191..201ddfb89 100644 --- a/Include/RmlUi/Core/EventListener.h +++ b/Include/RmlUi/Core/EventListener.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_EVENTLISTENER_H #define RMLUI_CORE_EVENTLISTENER_H -#include "Header.h" #include "Event.h" +#include "Header.h" #include "ObserverPtr.h" namespace Rml { @@ -39,13 +39,12 @@ class Event; class Element; /** - Abstract interface class for handling events. + Abstract interface class for handling events. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API EventListener : public EnableObserverPtr -{ +class RMLUICORE_API EventListener : public EnableObserverPtr { public: virtual ~EventListener() {} @@ -53,16 +52,10 @@ class RMLUICORE_API EventListener : public EnableObserverPtr virtual void ProcessEvent(Event& event) = 0; /// Called when the listener has been attached to a new Element - virtual void OnAttach(Element* RMLUI_UNUSED_PARAMETER(element)) - { - RMLUI_UNUSED(element); - } + virtual void OnAttach(Element* /*element*/) {} /// Called when the listener has been detached from an Element - virtual void OnDetach(Element* RMLUI_UNUSED_PARAMETER(element)) - { - RMLUI_UNUSED(element); - } + virtual void OnDetach(Element* /*element*/) {} }; } // namespace Rml diff --git a/Include/RmlUi/Core/EventListenerInstancer.h b/Include/RmlUi/Core/EventListenerInstancer.h index fa7528de3..5f2694c7c 100644 --- a/Include/RmlUi/Core/EventListenerInstancer.h +++ b/Include/RmlUi/Core/EventListenerInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,24 +29,23 @@ #ifndef RMLUI_CORE_EVENTLISTENERINSTANCER_H #define RMLUI_CORE_EVENTLISTENERINSTANCER_H +#include "Element.h" +#include "Header.h" #include "Traits.h" #include "Types.h" -#include "Header.h" -#include "Element.h" namespace Rml { class EventListener; /** - Abstract instancer interface for instancing event listeners. This is required to be overridden for scripting - systems. + Abstract instancer interface for instancing event listeners. This is required to be overridden for scripting + systems. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API EventListenerInstancer -{ +class RMLUICORE_API EventListenerInstancer { public: virtual ~EventListenerInstancer(); diff --git a/Include/RmlUi/Core/Factory.h b/Include/RmlUi/Core/Factory.h index 24d0dc886..7e39e8c57 100644 --- a/Include/RmlUi/Core/Factory.h +++ b/Include/RmlUi/Core/Factory.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_FACTORY_H #define RMLUI_CORE_FACTORY_H -#include "XMLParser.h" #include "Header.h" +#include "XMLParser.h" namespace Rml { @@ -56,16 +56,15 @@ class DecoratorInstancerInterface; enum class EventId : uint16_t; /** - The Factory contains a registry of instancers for different types. + The Factory contains a registry of instancers for different types. - All instantiation of these rmlui types should go through the factory - so that scripting API's can bind in new types. + All instantiation of these rmlui types should go through the factory + so that scripting API's can bind in new types. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API Factory -{ +class RMLUICORE_API Factory { public: /// Initialise the element factory static bool Initialise(); diff --git a/Include/RmlUi/Core/FileInterface.h b/Include/RmlUi/Core/FileInterface.h index 3c3aee347..41daa6e88 100644 --- a/Include/RmlUi/Core/FileInterface.h +++ b/Include/RmlUi/Core/FileInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,23 +30,22 @@ #define RMLUI_CORE_FILEINTERFACE_H #include "Header.h" -#include "Types.h" #include "Traits.h" +#include "Types.h" namespace Rml { /** - The abstract base class for application-specific file I/O. + The abstract base class for application-specific file I/O. - By default, RmlUi will use a file interface implementing the standard C file functions. If this is not sufficient, - or your application wants more control over file I/O, this class should be derived, instanced, and installed - through Rml::SetFileInterface() before you initialise RmlUi. + By default, RmlUi will use a file interface implementing the standard C file functions. If this is not sufficient, + or your application wants more control over file I/O, this class should be derived, instanced, and installed + through Rml::SetFileInterface() before you initialise RmlUi. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API FileInterface : public NonCopyMoveable -{ +class RMLUICORE_API FileInterface : public NonCopyMoveable { public: FileInterface(); virtual ~FileInterface(); @@ -68,7 +67,8 @@ class RMLUICORE_API FileInterface : public NonCopyMoveable /// Seeks to a point in a previously opened file. /// @param file The handle of the file to seek. /// @param offset The number of bytes to seek. - /// @param origin One of either SEEK_SET (seek from the beginning of the file), SEEK_END (seek from the end of the file) or SEEK_CUR (seek from the current file position). + /// @param origin One of either SEEK_SET (seek from the beginning of the file), SEEK_END (seek from the end of the file) or SEEK_CUR (seek from + /// the current file position). /// @return True if the operation completed successfully, false otherwise. virtual bool Seek(FileHandle file, long offset, int origin) = 0; /// Returns the current position of the file pointer. diff --git a/Include/RmlUi/Core/FontEffect.h b/Include/RmlUi/Core/FontEffect.h index 501c90bbc..3d3aa947e 100644 --- a/Include/RmlUi/Core/FontEffect.h +++ b/Include/RmlUi/Core/FontEffect.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API FontEffect -{ +class RMLUICORE_API FontEffect { public: // Behind or in front of the main text. enum class Layer { Back, Front }; @@ -53,13 +52,15 @@ class RMLUICORE_API FontEffect /// Requests the effect for a size and position of a single glyph's bitmap. /// @param[out] origin The desired origin of the effect's glyph bitmap, as a pixel offset from its original origin. This defaults to (0, 0). - /// @param[out] dimensions The desired dimensions of the effect's glyph bitmap, in pixels. This defaults to the dimensions of the glyph's original bitmap. If the font effect is not generating a unique texture, this will be ignored. + /// @param[out] dimensions The desired dimensions of the effect's glyph bitmap, in pixels. This defaults to the dimensions of the glyph's original + /// bitmap. If the font effect is not generating a unique texture, this will be ignored. /// @param[in] glyph The glyph the effect is being asked to size. /// @return False if the effect is not providing support for the glyph, true otherwise. virtual bool GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& glyph) const; /// Requests the effect to generate the texture data for a single glyph's bitmap. The default implementation does nothing. - /// @param[out] destination_data The top-left corner of the glyph's 32-bit, RGBA-ordered, destination texture. Note that the glyph shares its texture with other glyphs. + /// @param[out] destination_data The top-left corner of the glyph's 32-bit, RGBA-ordered, destination texture. Note that the glyph shares its + /// texture with other glyphs. /// @param[in] destination_dimensions The dimensions of the glyph's area on its texture. /// @param[in] destination_stride The stride of the glyph's texture. /// @param[in] glyph The glyph the effect is being asked to generate an effect texture for. diff --git a/Include/RmlUi/Core/FontEffectInstancer.h b/Include/RmlUi/Core/FontEffectInstancer.h index 51ba7864b..678453d73 100644 --- a/Include/RmlUi/Core/FontEffectInstancer.h +++ b/Include/RmlUi/Core/FontEffectInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,10 +29,10 @@ #ifndef RMLUI_CORE_FONTEFFECTINSTANCER_H #define RMLUI_CORE_FONTEFFECTINSTANCER_H -#include "Traits.h" #include "Header.h" #include "PropertyDictionary.h" #include "PropertySpecification.h" +#include "Traits.h" namespace Rml { @@ -40,16 +40,15 @@ class Factory; class FontEffect; /** - A font effect instancer provides a method for allocating and deallocating font effects. + A font effect instancer provides a method for allocating and deallocating font effects. - It is important that the same instancer that allocated a font effect releases it. This ensures there are no issues - with memory from different DLLs getting mixed up. + It is important that the same instancer that allocated a font effect releases it. This ensures there are no issues + with memory from different DLLs getting mixed up. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API FontEffectInstancer -{ +class RMLUICORE_API FontEffectInstancer { public: FontEffectInstancer(); virtual ~FontEffectInstancer(); @@ -73,7 +72,8 @@ class RMLUICORE_API FontEffectInstancer PropertyDefinition& RegisterProperty(const String& property_name, const String& default_value, bool affects_generation = true); /// Registers a shorthand property definition. /// @param[in] shorthand_name The name to register the new shorthand property under. - /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is the order in which the values will be processed. + /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is + /// the order in which the values will be processed. /// @param[in] type The type of shorthand to declare. /// @param True if all the property names exist, false otherwise. ShorthandId RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type); @@ -82,7 +82,7 @@ class RMLUICORE_API FontEffectInstancer PropertySpecification properties; // Properties that define the geometry. - SmallUnorderedSet< PropertyId > volatile_properties; + SmallUnorderedSet volatile_properties; friend class Rml::Factory; }; diff --git a/Include/RmlUi/Core/FontEngineInterface.h b/Include/RmlUi/Core/FontEngineInterface.h index 50ad225a3..bfefca97e 100644 --- a/Include/RmlUi/Core/FontEngineInterface.h +++ b/Include/RmlUi/Core/FontEngineInterface.h @@ -14,7 +14,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,15 +37,13 @@ namespace Rml { /** - The abstract base class for an application-specific font engine implementation. - - By default, RmlUi will use its own font engine with characters rendered through FreeType. To use your own engine, - provide a concrete implementation of this class and install it through Rml::SetFontEngineInterface(). - */ + The abstract base class for an application-specific font engine implementation. + By default, RmlUi will use its own font engine with characters rendered through FreeType. To use your own engine, + provide a concrete implementation of this class and install it through Rml::SetFontEngineInterface(). + */ -class RMLUICORE_API FontEngineInterface -{ +class RMLUICORE_API FontEngineInterface { public: FontEngineInterface(); virtual ~FontEngineInterface(); @@ -66,9 +64,10 @@ class RMLUICORE_API FontEngineInterface /// @param[in] fallback_face True to use this font face for unknown characters in other font faces. /// @return True if the face was loaded successfully, false otherwise. /// Note: The debugger plugin will load its embedded font faces through this method using the family name 'rmlui-debugger-font'. - virtual bool LoadFontFace(const byte* data, int data_size, const String& family, Style::FontStyle style, Style::FontWeight weight, bool fallback_face); + virtual bool LoadFontFace(const byte* data, int data_size, const String& family, Style::FontStyle style, Style::FontWeight weight, + bool fallback_face); - /// Called by RmlUi when a font configuration is resolved for an element. Should return a handle that + /// Called by RmlUi when a font configuration is resolved for an element. Should return a handle that /// can later be used to resolve properties of the face, and generate string geometry to be rendered. /// @param[in] family The family of the desired font handle. /// @param[in] style The style of the desired font handle. @@ -81,7 +80,7 @@ class RMLUICORE_API FontEngineInterface /// @param[in] handle The font handle. /// @param[in] font_effects The list of font effects to generate the configuration for. /// @return A handle to the prepared font effects which will be used when generating geometry for a string. - virtual FontEffectsHandle PrepareFontEffects(FontFaceHandle handle, const FontEffectList &font_effects); + virtual FontEffectsHandle PrepareFontEffects(FontFaceHandle handle, const FontEffectList& font_effects); /// Should return the font metrics of the given font face. /// @param[in] handle The font handle. @@ -92,7 +91,8 @@ class RMLUICORE_API FontEngineInterface /// @param[in] handle The font handle. /// @param[in] string The string to measure. /// @param[in] letter_spacing The letter spacing size in pixels. - /// @param[in] prior_character The optionally-specified character that immediately precedes the string. This may have an impact on the string width due to kerning. + /// @param[in] prior_character The optionally-specified character that immediately precedes the string. This may have an impact on the string + /// width due to kerning. /// @return The width, in pixels, this string will occupy if rendered with this handle. virtual int GetStringWidth(FontFaceHandle handle, const String& string, float letter_spacing, Character prior_character = Character::Null); diff --git a/Include/RmlUi/Core/FontGlyph.h b/Include/RmlUi/Core/FontGlyph.h index 95729b370..9915b670b 100644 --- a/Include/RmlUi/Core/FontGlyph.h +++ b/Include/RmlUi/Core/FontGlyph.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,9 +34,9 @@ namespace Rml { /** - Metrics and bitmap data for a single glyph within a font face. + Metrics and bitmap data for a single glyph within a font face. - @author Peter Curry + @author Peter Curry */ class RMLUICORE_API FontGlyph { @@ -62,7 +62,7 @@ class RMLUICORE_API FontGlyph { UniquePtr bitmap_owned_data; // Create a copy with its bitmap data owned by another glyph. - FontGlyph WeakCopy() const + FontGlyph WeakCopy() const { FontGlyph glyph; glyph.dimensions = dimensions; diff --git a/Include/RmlUi/Core/FontMetrics.h b/Include/RmlUi/Core/FontMetrics.h index 42f8105a2..22ebd4d9c 100644 --- a/Include/RmlUi/Core/FontMetrics.h +++ b/Include/RmlUi/Core/FontMetrics.h @@ -33,13 +33,13 @@ namespace Rml { struct FontMetrics { - int size; // Specified font size [px]. + int size; // Specified font size [px]. - float ascent; // Distance above the baseline to the upper grid coordinate [px, positive above baseline]. - float descent; // Distance below the baseline to the lower grid coordinate [px, positive below baseline]. - float line_spacing; // Font-specified distance between two consecutive baselines [px]. + float ascent; // Distance above the baseline to the upper grid coordinate [px, positive above baseline]. + float descent; // Distance below the baseline to the lower grid coordinate [px, positive below baseline]. + float line_spacing; // Font-specified distance between two consecutive baselines [px]. - float x_height; // Height of the lowercase 'x' character [px]. + float x_height; // Height of the lowercase 'x' character [px]. float underline_position; // Position of the underline relative to the baseline [px, positive below baseline]. float underline_thickness; // Width of underline [px]. diff --git a/Include/RmlUi/Core/Geometry.h b/Include/RmlUi/Core/Geometry.h index 04e54c02d..9d0e38c88 100644 --- a/Include/RmlUi/Core/Geometry.h +++ b/Include/RmlUi/Core/Geometry.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,13 +42,12 @@ struct Texture; using GeometryDatabaseHandle = uint32_t; /** - A helper object for holding an array of vertices and indices, and compiling it as necessary when rendered. + A helper object for holding an array of vertices and indices, and compiling it as necessary when rendered. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API Geometry -{ +class RMLUICORE_API Geometry { public: Geometry(Element* host_element = nullptr); Geometry(Context* host_context); @@ -71,10 +70,10 @@ class RMLUICORE_API Geometry /// Returns the geometry's vertices. If these are written to, Release() should be called to force a recompile. /// @return The geometry's vertex array. - Vector< Vertex >& GetVertices(); + Vector& GetVertices(); /// Returns the geometry's indices. If these are written to, Release() should be called to force a recompile. /// @return The geometry's index array. - Vector< int >& GetIndices(); + Vector& GetIndices(); /// Gets the geometry's texture. /// @return The geometry's texture. @@ -99,8 +98,8 @@ class RMLUICORE_API Geometry Context* host_context = nullptr; Element* host_element = nullptr; - Vector< Vertex > vertices; - Vector< int > indices; + Vector vertices; + Vector indices; const Texture* texture = nullptr; CompiledGeometryHandle compiled_geometry = 0; @@ -109,7 +108,7 @@ class RMLUICORE_API Geometry GeometryDatabaseHandle database_handle; }; -using GeometryList = Vector< Geometry >; +using GeometryList = Vector; } // namespace Rml #endif diff --git a/Include/RmlUi/Core/GeometryUtilities.h b/Include/RmlUi/Core/GeometryUtilities.h index 8d944406d..f5eb43e12 100644 --- a/Include/RmlUi/Core/GeometryUtilities.h +++ b/Include/RmlUi/Core/GeometryUtilities.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,9 +30,9 @@ #define RMLUI_CORE_GEOMETRYUTILITIES_H #include "Header.h" +#include "StyleTypes.h" #include "Types.h" #include "Vertex.h" -#include "StyleTypes.h" namespace Rml { @@ -40,13 +40,12 @@ class Box; class Geometry; /** - A class containing helper functions for rendering geometry. + A class containing helper functions for rendering geometry. - @author Robert Curry + @author Robert Curry */ -class RMLUICORE_API GeometryUtilities -{ +class RMLUICORE_API GeometryUtilities { public: /// Generates a quad from a position, size and colour. /// @param[out] vertices An array of at least four vertices that the generated vertex data will be written into. @@ -65,7 +64,8 @@ class RMLUICORE_API GeometryUtilities /// @param[in] top_left_texcoord The texture coordinates at the top-left of the quad. /// @param[in] bottom_right_texcoord The texture coordinates at the bottom-right of the quad. /// @param[in] index_offset The offset to be added to the generated indices; this should be the number of vertices already in the array. - static void GenerateQuad(Vertex* vertices, int* indices, Vector2f origin, Vector2f dimensions, Colourb colour, Vector2f top_left_texcoord, Vector2f bottom_right_texcoord, int index_offset = 0); + static void GenerateQuad(Vertex* vertices, int* indices, Vector2f origin, Vector2f dimensions, Colourb colour, Vector2f top_left_texcoord, + Vector2f bottom_right_texcoord, int index_offset = 0); /// Generates the geometry required to render a line. /// @param[out] geometry The geometry to append the newly created geometry into. @@ -82,7 +82,8 @@ class RMLUICORE_API GeometryUtilities /// @param[in] border_radius The border radius in pixel units in the following order: top-left, top-right, bottom-right, bottom-left. /// @param[in] background_colour The colour applied to the background, set alpha to zero to not generate the background. /// @param[in] border_colours Pointer to a four-element array of border colors in top-right-bottom-left order, or nullptr to not generate borders. - static void GenerateBackgroundBorder(Geometry* geometry, const Box& box, Vector2f offset, Vector4f border_radius, Colourb background_colour, const Colourb* border_colours = nullptr); + static void GenerateBackgroundBorder(Geometry* geometry, const Box& box, Vector2f offset, Vector4f border_radius, Colourb background_colour, + const Colourb* border_colours = nullptr); private: GeometryUtilities(); diff --git a/Include/RmlUi/Core/Header.h b/Include/RmlUi/Core/Header.h index 68089330a..31516e46e 100644 --- a/Include/RmlUi/Core/Header.h +++ b/Include/RmlUi/Core/Header.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,7 +40,7 @@ #define RMLUICORE_API __declspec(dllexport) // Note: Changing a RMLUICORE_API_INLINE method // breaks ABI compatibility!! - + // This results in an exported method from the DLL // that may be inlined in DLL clients, or if not // possible the client may choose to import the copy diff --git a/Include/RmlUi/Core/ID.h b/Include/RmlUi/Core/ID.h index 889e22eb8..4af9d8aa8 100644 --- a/Include/RmlUi/Core/ID.h +++ b/Include/RmlUi/Core/ID.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,7 +26,6 @@ * */ - #ifndef RMLUI_CORE_ID_H #define RMLUI_CORE_ID_H @@ -34,8 +33,7 @@ namespace Rml { -enum class ShorthandId : uint8_t -{ +enum class ShorthandId : uint8_t { Invalid, /* @@ -69,9 +67,7 @@ enum class ShorthandId : uint8_t MaxNumIds = 0xff }; - -enum class PropertyId : uint8_t -{ +enum class PropertyId : uint8_t { Invalid, /* @@ -180,9 +176,8 @@ enum class PropertyId : uint8_t MaxNumIds = 128 }; -enum class MediaQueryId : uint8_t -{ - Invalid, +enum class MediaQueryId : uint8_t { + Invalid, Width, MinWidth, @@ -202,8 +197,7 @@ enum class MediaQueryId : uint8_t NumDefinedIds }; -enum class EventId : uint16_t -{ +enum class EventId : uint16_t { Invalid, // Core events diff --git a/Include/RmlUi/Core/Input.h b/Include/RmlUi/Core/Input.h index 093aedde1..35b743b17 100644 --- a/Include/RmlUi/Core/Input.h +++ b/Include/RmlUi/Core/Input.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,15 +32,13 @@ namespace Rml { /* - Enumerants for sending input events into RmlUi. + Enumerants for sending input events into RmlUi. - @author Peter Curry + @author Peter Curry */ -namespace Input -{ - enum KeyIdentifier : unsigned char - { +namespace Input { + enum KeyIdentifier : unsigned char { KI_UNKNOWN = 0, KI_SPACE = 1, @@ -83,21 +81,21 @@ namespace Input KI_Y = 36, KI_Z = 37, - KI_OEM_1 = 38, // US standard keyboard; the ';:' key. - KI_OEM_PLUS = 39, // Any region; the '=+' key. - KI_OEM_COMMA = 40, // Any region; the ',<' key. - KI_OEM_MINUS = 41, // Any region; the '-_' key. - KI_OEM_PERIOD = 42, // Any region; the '.>' key. - KI_OEM_2 = 43, // Any region; the '/?' key. - KI_OEM_3 = 44, // Any region; the '`~' key. - - KI_OEM_4 = 45, // US standard keyboard; the '[{' key. - KI_OEM_5 = 46, // US standard keyboard; the '\|' key. - KI_OEM_6 = 47, // US standard keyboard; the ']}' key. - KI_OEM_7 = 48, // US standard keyboard; the ''"' key. + KI_OEM_1 = 38, // US standard keyboard; the ';:' key. + KI_OEM_PLUS = 39, // Any region; the '=+' key. + KI_OEM_COMMA = 40, // Any region; the ',<' key. + KI_OEM_MINUS = 41, // Any region; the '-_' key. + KI_OEM_PERIOD = 42, // Any region; the '.>' key. + KI_OEM_2 = 43, // Any region; the '/?' key. + KI_OEM_3 = 44, // Any region; the '`~' key. + + KI_OEM_4 = 45, // US standard keyboard; the '[{' key. + KI_OEM_5 = 46, // US standard keyboard; the '\|' key. + KI_OEM_6 = 47, // US standard keyboard; the ']}' key. + KI_OEM_7 = 48, // US standard keyboard; the ''"' key. KI_OEM_8 = 49, - KI_OEM_102 = 50, // RT 102-key keyboard; the '<>' or '\|' key. + KI_OEM_102 = 50, // RT 102-key keyboard; the '<>' or '\|' key. KI_NUMPAD0 = 51, KI_NUMPAD1 = 52, @@ -110,60 +108,60 @@ namespace Input KI_NUMPAD8 = 59, KI_NUMPAD9 = 60, KI_NUMPADENTER = 61, - KI_MULTIPLY = 62, // Asterisk on the numeric keypad. - KI_ADD = 63, // Plus on the numeric keypad. + KI_MULTIPLY = 62, // Asterisk on the numeric keypad. + KI_ADD = 63, // Plus on the numeric keypad. KI_SEPARATOR = 64, - KI_SUBTRACT = 65, // Minus on the numeric keypad. - KI_DECIMAL = 66, // Period on the numeric keypad. - KI_DIVIDE = 67, // Forward Slash on the numeric keypad. + KI_SUBTRACT = 65, // Minus on the numeric keypad. + KI_DECIMAL = 66, // Period on the numeric keypad. + KI_DIVIDE = 67, // Forward Slash on the numeric keypad. /* * NEC PC-9800 kbd definitions */ - KI_OEM_NEC_EQUAL = 68, // Equals key on the numeric keypad. + KI_OEM_NEC_EQUAL = 68, // Equals key on the numeric keypad. - KI_BACK = 69, // Backspace key. - KI_TAB = 70, // Tab key. + KI_BACK = 69, // Backspace key. + KI_TAB = 70, // Tab key. KI_CLEAR = 71, KI_RETURN = 72, KI_PAUSE = 73, - KI_CAPITAL = 74, // Capslock key. + KI_CAPITAL = 74, // Capslock key. - KI_KANA = 75, // IME Kana mode. - KI_HANGUL = 76, // IME Hangul mode. - KI_JUNJA = 77, // IME Junja mode. - KI_FINAL = 78, // IME final mode. - KI_HANJA = 79, // IME Hanja mode. - KI_KANJI = 80, // IME Kanji mode. + KI_KANA = 75, // IME Kana mode. + KI_HANGUL = 76, // IME Hangul mode. + KI_JUNJA = 77, // IME Junja mode. + KI_FINAL = 78, // IME final mode. + KI_HANJA = 79, // IME Hanja mode. + KI_KANJI = 80, // IME Kanji mode. - KI_ESCAPE = 81, // Escape key. + KI_ESCAPE = 81, // Escape key. - KI_CONVERT = 82, // IME convert. - KI_NONCONVERT = 83, // IME nonconvert. - KI_ACCEPT = 84, // IME accept. - KI_MODECHANGE = 85, // IME mode change request. + KI_CONVERT = 82, // IME convert. + KI_NONCONVERT = 83, // IME nonconvert. + KI_ACCEPT = 84, // IME accept. + KI_MODECHANGE = 85, // IME mode change request. - KI_PRIOR = 86, // Page Up key. - KI_NEXT = 87, // Page Down key. + KI_PRIOR = 86, // Page Up key. + KI_NEXT = 87, // Page Down key. KI_END = 88, KI_HOME = 89, - KI_LEFT = 90, // Left Arrow key. - KI_UP = 91, // Up Arrow key. - KI_RIGHT = 92, // Right Arrow key. - KI_DOWN = 93, // Down Arrow key. + KI_LEFT = 90, // Left Arrow key. + KI_UP = 91, // Up Arrow key. + KI_RIGHT = 92, // Right Arrow key. + KI_DOWN = 93, // Down Arrow key. KI_SELECT = 94, KI_PRINT = 95, KI_EXECUTE = 96, - KI_SNAPSHOT = 97, // Print Screen key. + KI_SNAPSHOT = 97, // Print Screen key. KI_INSERT = 98, KI_DELETE = 99, KI_HELP = 100, - KI_LWIN = 101, // Left Windows key. - KI_RWIN = 102, // Right Windows key. - KI_APPS = 103, // Applications key. + KI_LWIN = 101, // Left Windows key. + KI_RWIN = 102, // Right Windows key. + KI_APPS = 103, // Applications key. KI_POWER = 104, KI_SLEEP = 105, @@ -194,17 +192,17 @@ namespace Input KI_F23 = 129, KI_F24 = 130, - KI_NUMLOCK = 131, // Numlock key. - KI_SCROLL = 132, // Scroll Lock key. + KI_NUMLOCK = 131, // Numlock key. + KI_SCROLL = 132, // Scroll Lock key. /* * Fujitsu/OASYS kbd definitions */ - KI_OEM_FJ_JISHO = 133, // 'Dictionary' key. - KI_OEM_FJ_MASSHOU = 134, // 'Unregister word' key. - KI_OEM_FJ_TOUROKU = 135, // 'Register word' key. - KI_OEM_FJ_LOYA = 136, // 'Left OYAYUBI' key. - KI_OEM_FJ_ROYA = 137, // 'Right OYAYUBI' key. + KI_OEM_FJ_JISHO = 133, // 'Dictionary' key. + KI_OEM_FJ_MASSHOU = 134, // 'Unregister word' key. + KI_OEM_FJ_TOUROKU = 135, // 'Register word' key. + KI_OEM_FJ_LOYA = 136, // 'Left OYAYUBI' key. + KI_OEM_FJ_ROYA = 137, // 'Right OYAYUBI' key. KI_LSHIFT = 138, KI_RSHIFT = 139, @@ -240,7 +238,7 @@ namespace Input KI_ICO_HELP = 163, KI_ICO_00 = 164, - KI_PROCESSKEY = 165, // IME Process key. + KI_PROCESSKEY = 165, // IME Process key. KI_ICO_CLEAR = 166, @@ -257,17 +255,16 @@ namespace Input KI_RMETA = 176 }; - enum KeyModifier : unsigned char - { - KM_CTRL = 1 << 0, // Set if at least one Ctrl key is depressed. - KM_SHIFT = 1 << 1, // Set if at least one Shift key is depressed. - KM_ALT = 1 << 2, // Set if at least one Alt key is depressed. - KM_META = 1 << 3, // Set if at least one Meta key (the command key) is depressed. - KM_CAPSLOCK = 1 << 4, // Set if caps lock is enabled. - KM_NUMLOCK = 1 << 5, // Set if num lock is enabled. - KM_SCROLLLOCK = 1 << 6 // Set if scroll lock is enabled. + enum KeyModifier : unsigned char { + KM_CTRL = 1 << 0, // Set if at least one Ctrl key is depressed. + KM_SHIFT = 1 << 1, // Set if at least one Shift key is depressed. + KM_ALT = 1 << 2, // Set if at least one Alt key is depressed. + KM_META = 1 << 3, // Set if at least one Meta key (the command key) is depressed. + KM_CAPSLOCK = 1 << 4, // Set if caps lock is enabled. + KM_NUMLOCK = 1 << 5, // Set if num lock is enabled. + KM_SCROLLLOCK = 1 << 6 // Set if scroll lock is enabled. }; -} +} // namespace Input } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Log.h b/Include/RmlUi/Core/Log.h index dc77f2e50..d1d0cd2b8 100644 --- a/Include/RmlUi/Core/Log.h +++ b/Include/RmlUi/Core/Log.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,25 +35,23 @@ namespace Rml { /** - RmlUi logging API. + RmlUi logging API. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API Log -{ +class RMLUICORE_API Log { public: - enum Type - { + enum Type { LT_ALWAYS = 0, LT_ERROR, LT_ASSERT, LT_WARNING, LT_INFO, LT_DEBUG, - LT_MAX + LT_MAX, }; - + public: /// Initialises the logging interface. /// @return True if the logging interface was successful, false if not. diff --git a/Include/RmlUi/Core/Math.h b/Include/RmlUi/Core/Math.h index 0cd59cae6..4eb29e646 100644 --- a/Include/RmlUi/Core/Math.h +++ b/Include/RmlUi/Core/Math.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,223 +35,224 @@ namespace Rml { using byte = unsigned char; -template class Colour; -using Colourb = Colour< byte, 255 >; -template class Vector2; -using Vector2f = Vector2< float >; -using Vector2i = Vector2< int >; +template +class Colour; +using Colourb = Colour; +template +class Vector2; +using Vector2f = Vector2; +using Vector2i = Vector2; namespace Math { -constexpr float RMLUI_PI = 3.141592653f; - -template < typename Type > -Type Max(Type a, Type b) -{ - return (a > b) ? a : b; -} + constexpr float RMLUI_PI = 3.141592653f; -template< typename Type > -Type Min(Type a, Type b) -{ - return (a < b) ? a : b; -} + template + Type Max(Type a, Type b) + { + return (a > b) ? a : b; + } -template < typename Type > -Type ClampLower(Type value, Type min) -{ - return (value < min) ? min : value; -} + template + Type Min(Type a, Type b) + { + return (a < b) ? a : b; + } -template < typename Type > -Type ClampUpper(Type value, Type max) -{ - return (value > max) ? max: value; -} + template + Type ClampLower(Type value, Type min) + { + return (value < min) ? min : value; + } -template< typename Type > -Type Clamp(Type value, Type min, Type max) -{ - return (value < min) ? min : (value > max) ? max : value; -} + template + Type ClampUpper(Type value, Type max) + { + return (value > max) ? max : value; + } -template< typename Type > -Type Lerp(float t, Type v0, Type v1) -{ - static_assert(!std::is_same::value, "Lerp currently cannot be used with Colourb. Use RoundedLerp instead."); - return v0 * (1.0f - t) + v1 * t; -} + template + Type Clamp(Type value, Type min, Type max) + { + return (value < min) ? min : (value > max) ? max : value; + } -/// Element-wise maximum. -template <> -RMLUICORE_API Vector2f Max(Vector2f a, Vector2f b); -template <> -RMLUICORE_API Vector2i Max(Vector2i a, Vector2i b); -/// Element-wise minimum. -template <> -RMLUICORE_API Vector2f Min(Vector2f a, Vector2f b); -template <> -RMLUICORE_API Vector2i Min(Vector2i a, Vector2i b); -/// Element-wise clamp. -template <> -RMLUICORE_API Vector2f Clamp(Vector2f value, Vector2f min, Vector2f max); -template <> -RMLUICORE_API Vector2i Clamp(Vector2i value, Vector2i min, Vector2i max); + template + Type Lerp(float t, Type v0, Type v1) + { + static_assert(!std::is_same::value, "Lerp currently cannot be used with Colourb. Use RoundedLerp instead."); + return v0 * (1.0f - t) + v1 * t; + } + /// Element-wise maximum. + template <> + RMLUICORE_API Vector2f Max(Vector2f a, Vector2f b); + template <> + RMLUICORE_API Vector2i Max(Vector2i a, Vector2i b); + /// Element-wise minimum. + template <> + RMLUICORE_API Vector2f Min(Vector2f a, Vector2f b); + template <> + RMLUICORE_API Vector2i Min(Vector2i a, Vector2i b); + /// Element-wise clamp. + template <> + RMLUICORE_API Vector2f Clamp(Vector2f value, Vector2f min, Vector2f max); + template <> + RMLUICORE_API Vector2i Clamp(Vector2i value, Vector2i min, Vector2i max); -/// Color interpolation. -RMLUICORE_API Colourb RoundedLerp(float t, Colourb c0, Colourb c1); + /// Color interpolation. + RMLUICORE_API Colourb RoundedLerp(float t, Colourb c0, Colourb c1); -/// Evaluates if a number is, or close to, zero. -/// @param[in] value The number to compare to zero. -/// @return True if the number if zero or close to it, false otherwise. -RMLUICORE_API bool IsZero(float value); -/// Evaluates if two floating-point numbers are equal, or so similar that they could be considered -/// so. -/// @param[in] value_0 The first number to compare. -/// @param[in] value_1 The second number to compare. -/// @return True if the numbers are similar or equal. -RMLUICORE_API bool AreEqual(float value_0, float value_1); + /// Evaluates if a number is, or close to, zero. + /// @param[in] value The number to compare to zero. + /// @return True if the number if zero or close to it, false otherwise. + RMLUICORE_API bool IsZero(float value); + /// Evaluates if two floating-point numbers are equal, or so similar that they could be considered + /// so. + /// @param[in] value_0 The first number to compare. + /// @param[in] value_1 The second number to compare. + /// @return True if the numbers are similar or equal. + RMLUICORE_API bool AreEqual(float value_0, float value_1); -/// Calculates the absolute value of a number. -/// @param[in] value The number of get the absolute value of. -/// @return The absolute value of the number. -RMLUICORE_API float AbsoluteValue(float value); -/// Calculates the absolute value of a number. -/// @param[in] value The number of get the absolute value of. -/// @return The absolute value of the number. -RMLUICORE_API int AbsoluteValue(int value); -/// Calculates the component-wise absolute value of a vector. -/// @param[in] value The vector of get the absolute value of. -/// @return The absolute value of the vector. -RMLUICORE_API Vector2f AbsoluteValue(Vector2f value); + /// Calculates the absolute value of a number. + /// @param[in] value The number of get the absolute value of. + /// @return The absolute value of the number. + RMLUICORE_API float AbsoluteValue(float value); + /// Calculates the absolute value of a number. + /// @param[in] value The number of get the absolute value of. + /// @return The absolute value of the number. + RMLUICORE_API int AbsoluteValue(int value); + /// Calculates the component-wise absolute value of a vector. + /// @param[in] value The vector of get the absolute value of. + /// @return The absolute value of the vector. + RMLUICORE_API Vector2f AbsoluteValue(Vector2f value); -/// Calculates the cosine of an angle. -/// @param[in] angle The angle to calculate the cosine of, in radians. -/// @return The cosine of the angle. -RMLUICORE_API float Cos(float angle); -/// Calculates the arc-cosine of an value. -/// @param[in] angle The value to calculate the arc-cosine of. -/// @return The angle, in radians. -RMLUICORE_API float ACos(float value); -/// Calculates the sine of an angle. -/// @param[in] angle The angle to calculate the sine of, in radians. -/// @return The sine of the angle. -RMLUICORE_API float Sin(float angle); -/// Calculates the arc-sine of an value. -/// @param[in] angle The value to calculate the arc-sine of. -/// @return The angle, in radians. -RMLUICORE_API float ASin(float angle); -/// Calculates the tangent of an angle. -/// @param[in] angle The angle to calculate the tangent of, in radians. -/// @return The tanget of the angle. -RMLUICORE_API float Tan(float angle); -/// Calculates the angle of a two-dimensional line. -/// @param[in] y The y-component of the line. -/// @param[in] x The x-component of the line. -/// @return The angle of the line in radians. -RMLUICORE_API float ATan2(float y, float x); -/// Evaluates the natural exponential function on a value. -/// @param[in] value The value -/// @return e^(value) -RMLUICORE_API float Exp(float value); -/// Evaluates the base-2 logarithm of an integer. -/// @param[in] value The value -/// @return log2(value) -RMLUICORE_API int Log2(int value); + /// Calculates the cosine of an angle. + /// @param[in] angle The angle to calculate the cosine of, in radians. + /// @return The cosine of the angle. + RMLUICORE_API float Cos(float angle); + /// Calculates the arc-cosine of an value. + /// @param[in] angle The value to calculate the arc-cosine of. + /// @return The angle, in radians. + RMLUICORE_API float ACos(float value); + /// Calculates the sine of an angle. + /// @param[in] angle The angle to calculate the sine of, in radians. + /// @return The sine of the angle. + RMLUICORE_API float Sin(float angle); + /// Calculates the arc-sine of an value. + /// @param[in] angle The value to calculate the arc-sine of. + /// @return The angle, in radians. + RMLUICORE_API float ASin(float angle); + /// Calculates the tangent of an angle. + /// @param[in] angle The angle to calculate the tangent of, in radians. + /// @return The tanget of the angle. + RMLUICORE_API float Tan(float angle); + /// Calculates the angle of a two-dimensional line. + /// @param[in] y The y-component of the line. + /// @param[in] x The x-component of the line. + /// @return The angle of the line in radians. + RMLUICORE_API float ATan2(float y, float x); + /// Evaluates the natural exponential function on a value. + /// @param[in] value The value + /// @return e^(value) + RMLUICORE_API float Exp(float value); + /// Evaluates the base-2 logarithm of an integer. + /// @param[in] value The value + /// @return log2(value) + RMLUICORE_API int Log2(int value); -/// Converts an angle from radians to degrees. -/// @param[in] The angle, in radians. -/// @return The angle converted to degrees. -RMLUICORE_API float RadiansToDegrees(float angle); -/// Converts an angle from degrees to radians. -/// @param[in] The angle, in degrees. -/// @return The angle converted to radians. -RMLUICORE_API float DegreesToRadians(float angle); -/// Normalises and angle in radians -/// @param[in] The angle, in randians -/// @return The normalised angle -RMLUICORE_API float NormaliseAngle(float angle); + /// Converts an angle from radians to degrees. + /// @param[in] The angle, in radians. + /// @return The angle converted to degrees. + RMLUICORE_API float RadiansToDegrees(float angle); + /// Converts an angle from degrees to radians. + /// @param[in] The angle, in degrees. + /// @return The angle converted to radians. + RMLUICORE_API float DegreesToRadians(float angle); + /// Normalises and angle in radians + /// @param[in] The angle, in randians + /// @return The normalised angle + RMLUICORE_API float NormaliseAngle(float angle); -/// Calculates the square root of a value. -/// @param[in] value The value to calculate the square root of. This must be above zero. -/// @return The square root of the value. -RMLUICORE_API float SquareRoot(float value); + /// Calculates the square root of a value. + /// @param[in] value The value to calculate the square root of. This must be above zero. + /// @return The square root of the value. + RMLUICORE_API float SquareRoot(float value); -/// Rounds a floating-point value to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer as float. -RMLUICORE_API float RoundFloat(float value); -/// Rounds a floating-point value to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer as double. -RMLUICORE_API double RoundFloat(double value); -/// Rounds a floating-point value up to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer as float. -RMLUICORE_API float RoundUpFloat(float value); -/// Rounds a floating-point value down to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer as float. -RMLUICORE_API float RoundDownFloat(float value); -/// Rounds a floating-point value to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer. -RMLUICORE_API int RoundToInteger(float value); -/// Rounds a floating-point value up to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer. -RMLUICORE_API int RoundUpToInteger(float value); -/// Rounds a floating-point value down to the nearest integer. -/// @param[in] value The value to round. -/// @return The rounded integer. -RMLUICORE_API int RoundDownToInteger(float value); + /// Rounds a floating-point value to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer as float. + RMLUICORE_API float RoundFloat(float value); + /// Rounds a floating-point value to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer as double. + RMLUICORE_API double RoundFloat(double value); + /// Rounds a floating-point value up to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer as float. + RMLUICORE_API float RoundUpFloat(float value); + /// Rounds a floating-point value down to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer as float. + RMLUICORE_API float RoundDownFloat(float value); + /// Rounds a floating-point value to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer. + RMLUICORE_API int RoundToInteger(float value); + /// Rounds a floating-point value up to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer. + RMLUICORE_API int RoundUpToInteger(float value); + /// Rounds a floating-point value down to the nearest integer. + /// @param[in] value The value to round. + /// @return The rounded integer. + RMLUICORE_API int RoundDownToInteger(float value); -/// Decompose floating-point value to its fractional and integral parts. -/// @param[in] value The value to decompose. -/// @param[out] integral The integral part of the value. -/// @return The fractional part of the value. -RMLUICORE_API float DecomposeFractionalIntegral(float value, float* integral); -/// Efficiently truncates a floating-point value into an integer. -/// @param[in] value The value to truncate. -/// @return The truncated value as a signed integer. -RMLUICORE_API int RealToInteger(float value); + /// Decompose floating-point value to its fractional and integral parts. + /// @param[in] value The value to decompose. + /// @param[out] integral The integral part of the value. + /// @return The fractional part of the value. + RMLUICORE_API float DecomposeFractionalIntegral(float value, float* integral); + /// Efficiently truncates a floating-point value into an integer. + /// @param[in] value The value to truncate. + /// @return The truncated value as a signed integer. + RMLUICORE_API int RealToInteger(float value); -/// Round the position and width of a line segment to the pixel grid while minimizing movement of the edges. -/// @param[inout] x The position, which will use normal rounding. -/// @param[inout] width The width, which is rounded such that movement of the right edge is minimized. -RMLUICORE_API void SnapToPixelGrid(float& x, float& width); -/// Round the position and size of a rectangle to the pixel grid while minimizing movement of the edges. -/// @param[inout] position The position, which will use normal rounding. -/// @param[inout] size The size, which is rounded such that movement of the right and bottom edges is minimized. -RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size); -/// Round the position and size of a rectangle to the pixel grid such that it fully covers the original rectangle. -/// @param[inout] position The position, which will be rounded down. -/// @param[inout] size The size, which is rounded such that the right and bottom edges are rounded up. -RMLUICORE_API void ExpandToPixelGrid(Vector2f& position, Vector2f& size); + /// Round the position and width of a line segment to the pixel grid while minimizing movement of the edges. + /// @param[inout] x The position, which will use normal rounding. + /// @param[inout] width The width, which is rounded such that movement of the right edge is minimized. + RMLUICORE_API void SnapToPixelGrid(float& x, float& width); + /// Round the position and size of a rectangle to the pixel grid while minimizing movement of the edges. + /// @param[inout] position The position, which will use normal rounding. + /// @param[inout] size The size, which is rounded such that movement of the right and bottom edges is minimized. + RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size); + /// Round the position and size of a rectangle to the pixel grid such that it fully covers the original rectangle. + /// @param[inout] position The position, which will be rounded down. + /// @param[inout] size The size, which is rounded such that the right and bottom edges are rounded up. + RMLUICORE_API void ExpandToPixelGrid(Vector2f& position, Vector2f& size); -/// Converts a number to the nearest power of two, rounding up if necessary. -/// @param[in] value The value to convert to a power-of-two. -/// @return The smallest power of two that is as least as big as the input value. -RMLUICORE_API int ToPowerOfTwo(int value); + /// Converts a number to the nearest power of two, rounding up if necessary. + /// @param[in] value The value to convert to a power-of-two. + /// @return The smallest power of two that is as least as big as the input value. + RMLUICORE_API int ToPowerOfTwo(int value); -/// Converts from the ASCII-representation of a hexadecimal digit to decimal. -/// @param[in] hex_digit The hexadecimal digit to convert to decimal. -/// @return The digit in decimal. -RMLUICORE_API int HexToDecimal(char hex_digit); + /// Converts from the ASCII-representation of a hexadecimal digit to decimal. + /// @param[in] hex_digit The hexadecimal digit to convert to decimal. + /// @return The digit in decimal. + RMLUICORE_API int HexToDecimal(char hex_digit); -/// Generates a random floating-point value between 0 and a user-specified value. -/// @param[in] max_value The limit to random value. The generated value will be guaranteed to be below this limit. -/// @return The random value. -RMLUICORE_API float RandomReal(float max_value); -/// Generates a random integer value between 0 and a user-specified value. -/// @param[in] max_value The limit to random value. The generated value will be guaranteed to be below this limit. -/// @return The random value. -RMLUICORE_API int RandomInteger(int max_value); -/// Generates a random boolean value, with equal chance of true or false. -/// @return The random value. -RMLUICORE_API bool RandomBool(); + /// Generates a random floating-point value between 0 and a user-specified value. + /// @param[in] max_value The limit to random value. The generated value will be guaranteed to be below this limit. + /// @return The random value. + RMLUICORE_API float RandomReal(float max_value); + /// Generates a random integer value between 0 and a user-specified value. + /// @param[in] max_value The limit to random value. The generated value will be guaranteed to be below this limit. + /// @return The random value. + RMLUICORE_API int RandomInteger(int max_value); + /// Generates a random boolean value, with equal chance of true or false. + /// @return The random value. + RMLUICORE_API bool RandomBool(); -} +} // namespace Math } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Matrix4.h b/Include/RmlUi/Core/Matrix4.h index 6cba94f64..7361e8eea 100644 --- a/Include/RmlUi/Core/Matrix4.h +++ b/Include/RmlUi/Core/Matrix4.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,468 +36,457 @@ namespace Rml { /** - Templated class that acts as base strategy for vectors access patterns of matrices. - @author Markus Schöngart + Templated class that acts as base strategy for vectors access patterns of matrices. + @author Markus Schöngart */ -template< typename Component > -struct MatrixStorageBase -{ - typedef Component ComponentType; - typedef Vector4< ComponentType > VectorType; - typedef VectorType VectorsType[4]; - - class StrideVector - { - VectorsType& vectors; - int idx; - - public: - inline StrideVector(VectorsType& vectors, int idx) noexcept - : vectors(vectors), idx(idx) { } - inline ComponentType& operator[](int i) noexcept - { return vectors[i][idx]; } - inline StrideVector& operator=(const VectorType& vec) noexcept - { - (*this)[0] = vec[0]; - (*this)[1] = vec[1]; - (*this)[2] = vec[2]; - (*this)[3] = vec[3]; - return *this; - } - operator const VectorType() const noexcept - { - return VectorType( - (*this)[0], - (*this)[1], - (*this)[2], - (*this)[3] - ); - } - }; - class StrideAccess - { - VectorsType& vectors; - public: - inline StrideAccess(VectorsType& vectors) noexcept - : vectors(vectors) { } - inline StrideVector operator[](int i) noexcept - { return StrideVector(vectors, i); } - }; - class ConstStrideVector - { - const VectorsType& vectors; - int idx; - public: - inline ConstStrideVector(const VectorsType& vectors, int idx) noexcept - : vectors(vectors), idx(idx) { } - inline const ComponentType& operator[](int i) const noexcept - { return vectors[i][idx]; } - inline operator const VectorType() const noexcept - { - return VectorType( - (*this)[0], - (*this)[1], - (*this)[2], - (*this)[3] - ); - } - }; - class ConstStrideAccess - { - const VectorsType& vectors; - public: - inline ConstStrideAccess(const VectorsType& vectors) noexcept - : vectors(vectors) { } - inline ConstStrideVector operator[](int i) noexcept - { return ConstStrideVector(vectors, i); } - }; - - class PackedVector +template +struct MatrixStorageBase { + typedef Component ComponentType; + typedef Vector4 VectorType; + typedef VectorType VectorsType[4]; + + class StrideVector { + VectorsType& vectors; + int idx; + + public: + inline StrideVector(VectorsType& vectors, int idx) noexcept : vectors(vectors), idx(idx) {} + inline ComponentType& operator[](int i) noexcept { return vectors[i][idx]; } + inline StrideVector& operator=(const VectorType& vec) noexcept { - VectorType& vector; - public: - inline PackedVector(VectorType& vector) noexcept - : vector(vector) { } - inline ComponentType& operator[](int i) noexcept - { return vector[i]; } - inline PackedVector& operator=(const VectorType& vec) noexcept - { - vector = vec; - return *this; - } - inline PackedVector& operator=(StrideVector& vec) noexcept - { - vector[0] = vec[0]; - vector[1] = vec[1]; - vector[2] = vec[2]; - vector[3] = vec[3]; - return *this; - } - inline PackedVector& operator=(ConstStrideVector& vec) noexcept - { - vector[0] = vec[0]; - vector[1] = vec[1]; - vector[2] = vec[2]; - vector[3] = vec[3]; - return *this; - } - inline operator VectorType&() noexcept { return vector; } - }; - class PackedAccess + (*this)[0] = vec[0]; + (*this)[1] = vec[1]; + (*this)[2] = vec[2]; + (*this)[3] = vec[3]; + return *this; + } + operator const VectorType() const noexcept { return VectorType((*this)[0], (*this)[1], (*this)[2], (*this)[3]); } + }; + class StrideAccess { + VectorsType& vectors; + + public: + inline StrideAccess(VectorsType& vectors) noexcept : vectors(vectors) {} + inline StrideVector operator[](int i) noexcept { return StrideVector(vectors, i); } + }; + class ConstStrideVector { + const VectorsType& vectors; + int idx; + + public: + inline ConstStrideVector(const VectorsType& vectors, int idx) noexcept : vectors(vectors), idx(idx) {} + inline const ComponentType& operator[](int i) const noexcept { return vectors[i][idx]; } + inline operator const VectorType() const noexcept { return VectorType((*this)[0], (*this)[1], (*this)[2], (*this)[3]); } + }; + class ConstStrideAccess { + const VectorsType& vectors; + + public: + inline ConstStrideAccess(const VectorsType& vectors) noexcept : vectors(vectors) {} + inline ConstStrideVector operator[](int i) noexcept { return ConstStrideVector(vectors, i); } + }; + + class PackedVector { + VectorType& vector; + + public: + inline PackedVector(VectorType& vector) noexcept : vector(vector) {} + inline ComponentType& operator[](int i) noexcept { return vector[i]; } + inline PackedVector& operator=(const VectorType& vec) noexcept { - VectorsType& vectors; - public: - inline PackedAccess(VectorsType& vectors) noexcept - : vectors(vectors) { } - inline PackedVector operator[](int i) noexcept - { return PackedVector(vectors[i]); } - }; - #if 0 - class ConstPackedVector + vector = vec; + return *this; + } + inline PackedVector& operator=(StrideVector& vec) noexcept { - const VectorType& vectors; - public: - inline ConstPackedVector(const VectorType& vectors) noexcept - : vectors(vectors) { } - inline const ComponentType& operator[](int i) const noexcept - { return vectors[i]; } - inline operator const VectorType&() noexcept { return vectors; } - }; - #endif - class ConstPackedAccess + vector[0] = vec[0]; + vector[1] = vec[1]; + vector[2] = vec[2]; + vector[3] = vec[3]; + return *this; + } + inline PackedVector& operator=(ConstStrideVector& vec) noexcept { - const VectorsType& vectors; - public: - inline ConstPackedAccess(const VectorsType& vectors) noexcept - : vectors(vectors) { } - inline const VectorType& operator[](int i) noexcept - { return vectors[i]; } - }; + vector[0] = vec[0]; + vector[1] = vec[1]; + vector[2] = vec[2]; + vector[3] = vec[3]; + return *this; + } + inline operator VectorType&() noexcept { return vector; } + }; + class PackedAccess { + VectorsType& vectors; + + public: + inline PackedAccess(VectorsType& vectors) noexcept : vectors(vectors) {} + inline PackedVector operator[](int i) noexcept { return PackedVector(vectors[i]); } + }; + + class ConstPackedAccess { + const VectorsType& vectors; + + public: + inline ConstPackedAccess(const VectorsType& vectors) noexcept : vectors(vectors) {} + inline const VectorType& operator[](int i) noexcept { return vectors[i]; } + }; }; -template< typename Component > +template struct RowMajorStorage; -template< typename Component > +template struct ColumnMajorStorage; /** - Templated class that defines the vectors access pattern for row-major matrices. - @author Markus Schöngart + Templated class that defines the vectors access pattern for row-major matrices. + @author Markus Schöngart */ -template< typename Component > -struct RowMajorStorage : public MatrixStorageBase< Component > -{ - typedef Component ComponentType; - typedef Vector4< ComponentType > VectorType; - typedef RowMajorStorage< ComponentType > ThisType; - typedef ColumnMajorStorage< ComponentType > TransposeType; - - typedef typename MatrixStorageBase< Component >::PackedVector Row; - typedef typename MatrixStorageBase< Component >::PackedAccess Rows; - typedef const typename MatrixStorageBase< Component >::VectorType& ConstRow; - typedef typename MatrixStorageBase< Component >::ConstPackedAccess ConstRows; - typedef typename MatrixStorageBase< Component >::StrideVector Column; - typedef typename MatrixStorageBase< Component >::StrideAccess Columns; - typedef typename MatrixStorageBase< Component >::ConstStrideVector ConstColumn; - typedef typename MatrixStorageBase< Component >::ConstStrideAccess ConstColumns; +template +struct RowMajorStorage : public MatrixStorageBase { + typedef Component ComponentType; + typedef Vector4 VectorType; + typedef RowMajorStorage ThisType; + typedef ColumnMajorStorage TransposeType; + + typedef typename MatrixStorageBase::PackedVector Row; + typedef typename MatrixStorageBase::PackedAccess Rows; + typedef const typename MatrixStorageBase::VectorType& ConstRow; + typedef typename MatrixStorageBase::ConstPackedAccess ConstRows; + typedef typename MatrixStorageBase::StrideVector Column; + typedef typename MatrixStorageBase::StrideAccess Columns; + typedef typename MatrixStorageBase::ConstStrideVector ConstColumn; + typedef typename MatrixStorageBase::ConstStrideAccess ConstColumns; }; /** - Templated class that defines the vectors access pattern for column-major matrices. - @author Markus Schöngart + Templated class that defines the vectors access pattern for column-major matrices. + @author Markus Schöngart */ -template< typename Component > -struct ColumnMajorStorage -{ - typedef Component ComponentType; - typedef Vector4< ComponentType > VectorType; - typedef ColumnMajorStorage< ComponentType > ThisType; - typedef RowMajorStorage< ComponentType > TransposeType; - - typedef typename MatrixStorageBase< Component >::PackedVector Column; - typedef typename MatrixStorageBase< Component >::PackedAccess Columns; - typedef const typename MatrixStorageBase< Component >::VectorType& ConstColumn; - typedef typename MatrixStorageBase< Component >::ConstPackedAccess ConstColumns; - typedef typename MatrixStorageBase< Component >::StrideVector Row; - typedef typename MatrixStorageBase< Component >::StrideAccess Rows; - typedef typename MatrixStorageBase< Component >::ConstStrideVector ConstRow; - typedef typename MatrixStorageBase< Component >::ConstStrideAccess ConstRows; +template +struct ColumnMajorStorage { + typedef Component ComponentType; + typedef Vector4 VectorType; + typedef ColumnMajorStorage ThisType; + typedef RowMajorStorage TransposeType; + + typedef typename MatrixStorageBase::PackedVector Column; + typedef typename MatrixStorageBase::PackedAccess Columns; + typedef const typename MatrixStorageBase::VectorType& ConstColumn; + typedef typename MatrixStorageBase::ConstPackedAccess ConstColumns; + typedef typename MatrixStorageBase::StrideVector Row; + typedef typename MatrixStorageBase::StrideAccess Rows; + typedef typename MatrixStorageBase::ConstStrideVector ConstRow; + typedef typename MatrixStorageBase::ConstStrideAccess ConstRows; }; /** - Templated class for a generic 4x4 matrix. - @author Markus Schöngart + Templated class for a generic 4x4 matrix. + @author Markus Schöngart */ -template< typename Component, class Storage = ColumnMajorStorage< Component > > -class Matrix4 -{ - public: - typedef Component ComponentType; - typedef Vector4< ComponentType > VectorType; - typedef Matrix4< ComponentType, Storage > ThisType; - - typedef Storage StorageType; - typedef typename StorageType::Row Row; - typedef typename StorageType::Rows Rows; - typedef typename StorageType::ConstRow ConstRow; - typedef typename StorageType::ConstRows ConstRows; - typedef typename StorageType::Column Column; - typedef typename StorageType::Columns Columns; - typedef typename StorageType::ConstColumn ConstColumn; - typedef typename StorageType::ConstColumns ConstColumns; - - typedef typename StorageType::TransposeType TransposeStorageType; - typedef Matrix4< ComponentType, TransposeStorageType > TransposeType; - friend class Rml::Matrix4< ComponentType, TransposeStorageType >; - - private: - // The components of the matrix. - VectorType vectors[4]; - - /// Initialising constructor. - Matrix4(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; - - template< typename _Component, class _StorageA > - struct VectorMultiplier - { - typedef _Component ComponentType; - typedef _StorageA StorageAType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Vector4< ComponentType > VectorType; - - static const VectorType Multiply( - const MatrixAType& lhs, - const VectorType& rhs - ) noexcept; - }; - - template< typename _Component, class _StorageA, class _StorageB > - struct MatrixMultiplier - { - typedef _Component ComponentType; - typedef _StorageA StorageAType; - typedef _StorageB StorageBType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Matrix4< ComponentType, StorageBType > MatrixBType; - - static const VectorType Multiply( - const MatrixAType& lhs, - const VectorType& rhs - ); - - static const MatrixAType Multiply( - const MatrixAType& lhs, - const MatrixBType& rhs - ) noexcept; - }; - - public: - /// Zero-initialising default constructor. - inline Matrix4() noexcept; - - /// Copy constructor. - inline Matrix4(const ThisType& other) noexcept; - Matrix4(const TransposeType& other) noexcept; - - /// Assignment operator - const ThisType& operator=(const ThisType& other) noexcept; - const ThisType& operator=(const TransposeType& other) noexcept; - - /// Construct from row vectors. - static const ThisType FromRows(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; - - /// Construct from column vectors. - static const ThisType FromColumns(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; - - /// Construct from components. - static const ThisType FromRowMajor(const ComponentType* components) noexcept; - static const ThisType FromColumnMajor(const ComponentType* components) noexcept; - - // Convert to raw values; keep the storage mode in mind. - inline Component* data() noexcept - { return &vectors[0][0]; } - inline const Component* data() const noexcept - { return &vectors[0][0]; } - - /// Get the i-th row - inline Row GetRow(int i) noexcept - { Rows rows(vectors); return rows[i]; } - /// Get the i-th row - inline ConstRow GetRow(int i) const noexcept - { ConstRows rows(vectors); return rows[i]; } - /// Set the i-th row - inline void SetRow(int i, const VectorType& vec) noexcept - { Rows rows(vectors); rows[i] = vec; } - /// Set all rows - void SetRows(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; - - /// Get the i-th column - inline Column GetColumn(int i) noexcept - { Columns columns(vectors); return columns[i]; } - /// Get the i-th column - inline ConstColumn GetColumn(int i) const noexcept - { ConstColumns columns(vectors); return columns[i]; } - /// Set the i-th column - inline void SetColumn(int i, const VectorType& vec) noexcept - { Columns columns(vectors); columns[i] = vec; } - /// Set all columns - void SetColumns(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; - - /// Returns the transpose of this matrix. - /// @return The transpose matrix. - inline const TransposeType& Transpose() const noexcept - { return reinterpret_cast(*this); } - - /// Inverts this matrix in place, if possible. - /// @return true, if the inversion succeeded. - bool Invert() noexcept; - - /// Inverts this matrix in place, if possible. - /// @return true, if the inversion succeeded. - float Determinant() const noexcept; - - /// Returns the negation of this matrix. - /// @return The negation of this matrix. - ThisType operator-() const noexcept; - - /// Adds another matrix to this in-place. - /// @param[in] other The matrix to add. - /// @return This matrix, post-operation. - const ThisType& operator+=(const ThisType& other) noexcept; - const ThisType& operator+=(const TransposeType& other) noexcept; - /// Subtracts another matrix from this in-place. - /// @param[in] other The matrix to subtract. - /// @return This matrix, post-operation. - const ThisType& operator-=(const ThisType& other) noexcept; - const ThisType& operator-=(const TransposeType& other) noexcept; - /// Scales this matrix in-place. - /// @param[in] other The value to scale this matrix's components by. - /// @return This matrix, post-operation. - const ThisType& operator*=(Component other) noexcept; - /// Scales this matrix in-place by the inverse of a value. - /// @param[in] other The value to divide this matrix's components by. - /// @return This matrix, post-operation. - const ThisType& operator/=(Component other) noexcept; - - inline const VectorType& operator[](size_t i) const noexcept { return vectors[i]; } - inline VectorType& operator[](size_t i) noexcept { return vectors[i]; } - - /// Returns the sum of this matrix and another. - /// @param[in] other The matrix to add this to. - /// @return The sum of the two matrices. - inline const ThisType operator+(const ThisType& other) const noexcept - { ThisType result(*this); result += other; return result; } - inline const ThisType operator+(const TransposeType& other) const noexcept - { ThisType result(*this); result += other; return result; } - /// Returns the result of subtracting another matrix from this matrix. - /// @param[in] other The matrix to subtract from this matrix. - /// @return The result of the subtraction. - inline const ThisType operator-(const ThisType& other) const noexcept - { ThisType result(*this); result -= other; return result; } - inline const ThisType operator-(const TransposeType& other) const noexcept - { ThisType result(*this); result -= other; return result; } - /// Returns the result of multiplying this matrix by a scalar. - /// @param[in] other The scalar value to multiply by. - /// @return The result of the scale. - inline const ThisType operator*(Component other) const noexcept - { ThisType result(*this); result *= other; return result; } - /// Returns the result of dividing this matrix by a scalar. - /// @param[in] other The scalar value to divide by. - /// @return The result of the scale. - inline const ThisType operator/(Component other) const noexcept - { ThisType result(*this); result *= other; return result; } - - /// Returns the result of multiplying this matrix by a vector. - /// @param[in] other The scalar value to multiply by. - /// @return The result of the scale. - const VectorType operator*(const VectorType& other) const noexcept - { return VectorMultiplier< Component, Storage >::Multiply(*this, other); } - - /// Returns the result of multiplying this matrix by another matrix. - /// @param[in] other The matrix value to multiply by. - /// @return The result of the multiplication. - template< class Storage2 > - const ThisType operator*(const Matrix4< Component, Storage2 >& other) const noexcept - { return MatrixMultiplier< Component, Storage, Storage2 >::Multiply(*this, other); } - - /// Multiplies this matrix by another matrix in place. - /// @return The result of the multiplication. - inline const ThisType& operator*=(const ThisType& other) noexcept - { *this = *this * other; return *this; } - inline const ThisType& operator*=(const TransposeType& other) noexcept - { *this = *this * other; return *this; } - - /// Equality operator. - /// @param[in] other The matrix to compare this against. - /// @return True if the two matrices are equal, false otherwise. - bool operator==(const ThisType& other) const noexcept; - bool operator==(const TransposeType& other) const noexcept; - /// Inequality operator. - /// @param[in] other The matrix to compare this against. - /// @return True if the two matrices are not equal, false otherwise. - bool operator!=(const ThisType& other) const noexcept; - bool operator!=(const TransposeType& other) const noexcept; - - /// Return the identity matrix. - /// @return The identity matrix. - inline static const ThisType& Identity() noexcept; - /// Return a diagonal matrix. - /// @return A diagonal matrix. - static ThisType Diag(Component a, Component b, Component c, Component d = 1) noexcept; - - /// Create an orthographic projection matrix - /// @param l The horizontal coordinate of the left clipping plane - /// @param r The horizontal coordinate of the right clipping plane - /// @param b The vertical coordinate of the bottom clipping plane - /// @param t The vertical coordinate of the top clipping plane - /// @param n The depth coordinate of the near clipping plane - /// @param f The depth coordinate of the far clipping plane - /// @return The specified orthographic projection matrix. - static ThisType ProjectOrtho(Component l, Component r, Component b, Component t, Component n, Component f) noexcept; - /// Create a perspective projection matrix - /// @param l The horizontal coordinate of the left clipping plane - /// @param r The horizontal coordinate of the right clipping plane - /// @param b The vertical coordinate of the bottom clipping plane - /// @param t The vertical coordinate of the top clipping plane - /// @param n The depth coordinate of the near clipping plane - /// @param f The depth coordinate of the far clipping plane - /// @return The specified perspective projection matrix. - static ThisType ProjectPerspective(Component l, Component r, Component b, Component t, Component n, Component f) noexcept; - /// Create a perspective projection matrix - /// @param d The distance to the z-plane - static ThisType Perspective(Component d) noexcept; - - /// Return a translation matrix. - /// @return A translation matrix. - static ThisType Translate (const Vector3< Component >& v) noexcept; - static ThisType Translate (Component x, Component y, Component z) noexcept; - static ThisType TranslateX (Component x) noexcept; - static ThisType TranslateY (Component y) noexcept; - static ThisType TranslateZ (Component z) noexcept; - - /// Return a scaling matrix. - /// @return A scaling matrix. - static ThisType Scale (Component x, Component y, Component z) noexcept; - static ThisType ScaleX (Component x) noexcept; - static ThisType ScaleY (Component y) noexcept; - static ThisType ScaleZ (Component z) noexcept; - - /// Return a rotation matrix. - /// @return A rotation matrix. - static ThisType Rotate (const Vector3< Component >& v, Component angle) noexcept; - static ThisType RotateX (Component angle) noexcept; - static ThisType RotateY (Component angle) noexcept; - static ThisType RotateZ (Component angle) noexcept; - - /// Return a skew/shearing matrix. - /// @return A skew matrix. - static ThisType Skew (Component angle_x, Component angle_y) noexcept; - static ThisType SkewX (Component angle) noexcept; - static ThisType SkewY (Component angle) noexcept; - - static ThisType Compose(const Vector3< Component >& translation, const Vector3< Component >& scale, - const Vector3< Component >& skew, const Vector4< Component >& perspective, const Vector4< Component >& quaternion) noexcept; +template > +class Matrix4 { +public: + typedef Component ComponentType; + typedef Vector4 VectorType; + typedef Matrix4 ThisType; + + typedef Storage StorageType; + typedef typename StorageType::Row Row; + typedef typename StorageType::Rows Rows; + typedef typename StorageType::ConstRow ConstRow; + typedef typename StorageType::ConstRows ConstRows; + typedef typename StorageType::Column Column; + typedef typename StorageType::Columns Columns; + typedef typename StorageType::ConstColumn ConstColumn; + typedef typename StorageType::ConstColumns ConstColumns; + + typedef typename StorageType::TransposeType TransposeStorageType; + typedef Matrix4 TransposeType; + friend class Rml::Matrix4; + +private: + // The components of the matrix. + VectorType vectors[4]; + + /// Initialising constructor. + Matrix4(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; + + template + struct VectorMultiplier { + typedef _Component ComponentType; + typedef _StorageA StorageAType; + typedef Matrix4 MatrixAType; + typedef Vector4 VectorType; + + static const VectorType Multiply(const MatrixAType& lhs, const VectorType& rhs) noexcept; + }; + + template + struct MatrixMultiplier { + typedef _Component ComponentType; + typedef _StorageA StorageAType; + typedef _StorageB StorageBType; + typedef Matrix4 MatrixAType; + typedef Matrix4 MatrixBType; + + static const VectorType Multiply(const MatrixAType& lhs, const VectorType& rhs); + + static const MatrixAType Multiply(const MatrixAType& lhs, const MatrixBType& rhs) noexcept; + }; + +public: + /// Zero-initialising default constructor. + inline Matrix4() noexcept; + + /// Copy constructor. + inline Matrix4(const ThisType& other) noexcept; + Matrix4(const TransposeType& other) noexcept; + + /// Assignment operator + const ThisType& operator=(const ThisType& other) noexcept; + const ThisType& operator=(const TransposeType& other) noexcept; + + /// Construct from row vectors. + static const ThisType FromRows(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; + + /// Construct from column vectors. + static const ThisType FromColumns(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; + + /// Construct from components. + static const ThisType FromRowMajor(const ComponentType* components) noexcept; + static const ThisType FromColumnMajor(const ComponentType* components) noexcept; + + // Convert to raw values; keep the storage mode in mind. + inline Component* data() noexcept { return &vectors[0][0]; } + inline const Component* data() const noexcept { return &vectors[0][0]; } + + /// Get the i-th row + inline Row GetRow(int i) noexcept + { + Rows rows(vectors); + return rows[i]; + } + /// Get the i-th row + inline ConstRow GetRow(int i) const noexcept + { + ConstRows rows(vectors); + return rows[i]; + } + /// Set the i-th row + inline void SetRow(int i, const VectorType& vec) noexcept + { + Rows rows(vectors); + rows[i] = vec; + } + /// Set all rows + void SetRows(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; + + /// Get the i-th column + inline Column GetColumn(int i) noexcept + { + Columns columns(vectors); + return columns[i]; + } + /// Get the i-th column + inline ConstColumn GetColumn(int i) const noexcept + { + ConstColumns columns(vectors); + return columns[i]; + } + /// Set the i-th column + inline void SetColumn(int i, const VectorType& vec) noexcept + { + Columns columns(vectors); + columns[i] = vec; + } + /// Set all columns + void SetColumns(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept; + + /// Returns the transpose of this matrix. + /// @return The transpose matrix. + inline const TransposeType& Transpose() const noexcept { return reinterpret_cast(*this); } + + /// Inverts this matrix in place, if possible. + /// @return true, if the inversion succeeded. + bool Invert() noexcept; + + /// Inverts this matrix in place, if possible. + /// @return true, if the inversion succeeded. + float Determinant() const noexcept; + + /// Returns the negation of this matrix. + /// @return The negation of this matrix. + ThisType operator-() const noexcept; + + /// Adds another matrix to this in-place. + /// @param[in] other The matrix to add. + /// @return This matrix, post-operation. + const ThisType& operator+=(const ThisType& other) noexcept; + const ThisType& operator+=(const TransposeType& other) noexcept; + /// Subtracts another matrix from this in-place. + /// @param[in] other The matrix to subtract. + /// @return This matrix, post-operation. + const ThisType& operator-=(const ThisType& other) noexcept; + const ThisType& operator-=(const TransposeType& other) noexcept; + /// Scales this matrix in-place. + /// @param[in] other The value to scale this matrix's components by. + /// @return This matrix, post-operation. + const ThisType& operator*=(Component other) noexcept; + /// Scales this matrix in-place by the inverse of a value. + /// @param[in] other The value to divide this matrix's components by. + /// @return This matrix, post-operation. + const ThisType& operator/=(Component other) noexcept; + + inline const VectorType& operator[](size_t i) const noexcept { return vectors[i]; } + inline VectorType& operator[](size_t i) noexcept { return vectors[i]; } + + /// Returns the sum of this matrix and another. + /// @param[in] other The matrix to add this to. + /// @return The sum of the two matrices. + inline const ThisType operator+(const ThisType& other) const noexcept + { + ThisType result(*this); + result += other; + return result; + } + inline const ThisType operator+(const TransposeType& other) const noexcept + { + ThisType result(*this); + result += other; + return result; + } + /// Returns the result of subtracting another matrix from this matrix. + /// @param[in] other The matrix to subtract from this matrix. + /// @return The result of the subtraction. + inline const ThisType operator-(const ThisType& other) const noexcept + { + ThisType result(*this); + result -= other; + return result; + } + inline const ThisType operator-(const TransposeType& other) const noexcept + { + ThisType result(*this); + result -= other; + return result; + } + /// Returns the result of multiplying this matrix by a scalar. + /// @param[in] other The scalar value to multiply by. + /// @return The result of the scale. + inline const ThisType operator*(Component other) const noexcept + { + ThisType result(*this); + result *= other; + return result; + } + /// Returns the result of dividing this matrix by a scalar. + /// @param[in] other The scalar value to divide by. + /// @return The result of the scale. + inline const ThisType operator/(Component other) const noexcept + { + ThisType result(*this); + result *= other; + return result; + } + + /// Returns the result of multiplying this matrix by a vector. + /// @param[in] other The scalar value to multiply by. + /// @return The result of the scale. + const VectorType operator*(const VectorType& other) const noexcept { return VectorMultiplier::Multiply(*this, other); } + + /// Returns the result of multiplying this matrix by another matrix. + /// @param[in] other The matrix value to multiply by. + /// @return The result of the multiplication. + template + const ThisType operator*(const Matrix4& other) const noexcept + { + return MatrixMultiplier::Multiply(*this, other); + } + + /// Multiplies this matrix by another matrix in place. + /// @return The result of the multiplication. + inline const ThisType& operator*=(const ThisType& other) noexcept + { + *this = *this * other; + return *this; + } + inline const ThisType& operator*=(const TransposeType& other) noexcept + { + *this = *this * other; + return *this; + } + + /// Equality operator. + /// @param[in] other The matrix to compare this against. + /// @return True if the two matrices are equal, false otherwise. + bool operator==(const ThisType& other) const noexcept; + bool operator==(const TransposeType& other) const noexcept; + /// Inequality operator. + /// @param[in] other The matrix to compare this against. + /// @return True if the two matrices are not equal, false otherwise. + bool operator!=(const ThisType& other) const noexcept; + bool operator!=(const TransposeType& other) const noexcept; + + /// Return the identity matrix. + /// @return The identity matrix. + inline static const ThisType& Identity() noexcept; + /// Return a diagonal matrix. + /// @return A diagonal matrix. + static ThisType Diag(Component a, Component b, Component c, Component d = 1) noexcept; + + /// Create an orthographic projection matrix + /// @param l The horizontal coordinate of the left clipping plane + /// @param r The horizontal coordinate of the right clipping plane + /// @param b The vertical coordinate of the bottom clipping plane + /// @param t The vertical coordinate of the top clipping plane + /// @param n The depth coordinate of the near clipping plane + /// @param f The depth coordinate of the far clipping plane + /// @return The specified orthographic projection matrix. + static ThisType ProjectOrtho(Component l, Component r, Component b, Component t, Component n, Component f) noexcept; + /// Create a perspective projection matrix + /// @param l The horizontal coordinate of the left clipping plane + /// @param r The horizontal coordinate of the right clipping plane + /// @param b The vertical coordinate of the bottom clipping plane + /// @param t The vertical coordinate of the top clipping plane + /// @param n The depth coordinate of the near clipping plane + /// @param f The depth coordinate of the far clipping plane + /// @return The specified perspective projection matrix. + static ThisType ProjectPerspective(Component l, Component r, Component b, Component t, Component n, Component f) noexcept; + /// Create a perspective projection matrix + /// @param d The distance to the z-plane + static ThisType Perspective(Component d) noexcept; + + /// Return a translation matrix. + /// @return A translation matrix. + static ThisType Translate(const Vector3& v) noexcept; + static ThisType Translate(Component x, Component y, Component z) noexcept; + static ThisType TranslateX(Component x) noexcept; + static ThisType TranslateY(Component y) noexcept; + static ThisType TranslateZ(Component z) noexcept; + + /// Return a scaling matrix. + /// @return A scaling matrix. + static ThisType Scale(Component x, Component y, Component z) noexcept; + static ThisType ScaleX(Component x) noexcept; + static ThisType ScaleY(Component y) noexcept; + static ThisType ScaleZ(Component z) noexcept; + + /// Return a rotation matrix. + /// @return A rotation matrix. + static ThisType Rotate(const Vector3& v, Component angle) noexcept; + static ThisType RotateX(Component angle) noexcept; + static ThisType RotateY(Component angle) noexcept; + static ThisType RotateZ(Component angle) noexcept; + + /// Return a skew/shearing matrix. + /// @return A skew matrix. + static ThisType Skew(Component angle_x, Component angle_y) noexcept; + static ThisType SkewX(Component angle) noexcept; + static ThisType SkewY(Component angle) noexcept; + + static ThisType Compose(const Vector3& translation, const Vector3& scale, const Vector3& skew, + const Vector4& perspective, const Vector4& quaternion) noexcept; #if defined(RMLUI_MATRIX4_USER_EXTRA) RMLUI_MATRIX4_USER_EXTRA diff --git a/Include/RmlUi/Core/Matrix4.inl b/Include/RmlUi/Core/Matrix4.inl index 010301e5b..6fd215c0d 100644 --- a/Include/RmlUi/Core/Matrix4.inl +++ b/Include/RmlUi/Core/Matrix4.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,13 +29,10 @@ namespace Rml { // Initialising constructor. -template< typename Component, class Storage > -Matrix4< Component, Storage >::Matrix4( - const typename Matrix4< Component, Storage >::VectorType& vec0, - const typename Matrix4< Component, Storage >::VectorType& vec1, - const typename Matrix4< Component, Storage >::VectorType& vec2, - const typename Matrix4< Component, Storage >::VectorType& vec3 -) noexcept +template +Matrix4::Matrix4(const typename Matrix4::VectorType& vec0, + const typename Matrix4::VectorType& vec1, const typename Matrix4::VectorType& vec2, + const typename Matrix4::VectorType& vec3) noexcept { vectors[0] = vec0; vectors[1] = vec1; @@ -44,15 +41,13 @@ Matrix4< Component, Storage >::Matrix4( } // Default constructor. -template< typename Component, class Storage > -Matrix4< Component, Storage >::Matrix4() noexcept - : vectors{ VectorType{0}, VectorType{0}, VectorType{0}, VectorType{0} } -{ -} +template +Matrix4::Matrix4() noexcept : vectors{VectorType{0}, VectorType{0}, VectorType{0}, VectorType{0}} +{} // Initialising, copy constructor. -template< typename Component, class Storage > -Matrix4< Component, Storage >::Matrix4(const typename Matrix4< Component, Storage >::ThisType& other) noexcept +template +Matrix4::Matrix4(const typename Matrix4::ThisType& other) noexcept { for (int i = 0; i < 4; ++i) { @@ -60,11 +55,11 @@ Matrix4< Component, Storage >::Matrix4(const typename Matrix4< Component, Storag } } -template< typename Component, class Storage > -Matrix4< Component, Storage >::Matrix4(const typename Matrix4< Component, Storage >::TransposeType& other) noexcept +template +Matrix4::Matrix4(const typename Matrix4::TransposeType& other) noexcept { Rows rows(vectors); - typename Matrix4< Component, Storage >::TransposeType::ConstRows other_rows(other.vectors); + typename Matrix4::TransposeType::ConstRows other_rows(other.vectors); for (int i = 0; i < 4; ++i) { rows[i] = other_rows[i]; @@ -72,8 +67,9 @@ Matrix4< Component, Storage >::Matrix4(const typename Matrix4< Component, Storag } // Assignment operator -template< typename Component, class Storage > -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator=(const typename Matrix4< Component, Storage >::ThisType& other) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator=( + const typename Matrix4::ThisType& other) noexcept { for (int i = 0; i < 4; ++i) { @@ -82,11 +78,12 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor return *this; } -template< typename Component, class Storage > -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator=(const typename Matrix4< Component, Storage >::TransposeType& other) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator=( + const typename Matrix4::TransposeType& other) noexcept { Rows rows(vectors); - typename Matrix4< Component, Storage >::TransposeType::Rows other_rows(other.vectors); + typename Matrix4::TransposeType::Rows other_rows(other.vectors); for (int i = 0; i < 4; ++i) { rows[i] = other_rows[i]; @@ -95,66 +92,60 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } // Construct from row vectors. -template< typename Component, class Storage > -const typename Matrix4< Component, Storage >::ThisType Matrix4< Component, Storage >::FromRows( - const typename Matrix4< Component, Storage >::VectorType& vec0, - const typename Matrix4< Component, Storage >::VectorType& vec1, - const typename Matrix4< Component, Storage >::VectorType& vec2, - const typename Matrix4< Component, Storage >::VectorType& vec3 -) noexcept -{ - typename Matrix4< Component, Storage >::ThisType result; +template +const typename Matrix4::ThisType Matrix4::FromRows( + const typename Matrix4::VectorType& vec0, const typename Matrix4::VectorType& vec1, + const typename Matrix4::VectorType& vec2, const typename Matrix4::VectorType& vec3) noexcept +{ + typename Matrix4::ThisType result; result.SetRows(vec0, vec1, vec2, vec3); return result; } // Construct from column vectors. -template< typename Component, class Storage > -const typename Matrix4< Component, Storage >::ThisType Matrix4< Component, Storage >::FromColumns( - const typename Matrix4< Component, Storage >::VectorType& vec0, - const typename Matrix4< Component, Storage >::VectorType& vec1, - const typename Matrix4< Component, Storage >::VectorType& vec2, - const typename Matrix4< Component, Storage >::VectorType& vec3 -) noexcept -{ - typename Matrix4< Component, Storage >::ThisType result; +template +const typename Matrix4::ThisType Matrix4::FromColumns( + const typename Matrix4::VectorType& vec0, const typename Matrix4::VectorType& vec1, + const typename Matrix4::VectorType& vec2, const typename Matrix4::VectorType& vec3) noexcept +{ + typename Matrix4::ThisType result; result.SetColumns(vec0, vec1, vec2, vec3); return result; } // Construct from components -template< typename Component, class Storage > -const typename Matrix4< Component, Storage >::ThisType Matrix4< Component, Storage >::FromRowMajor(const Component* components) noexcept +template +const typename Matrix4::ThisType Matrix4::FromRowMajor(const Component* components) noexcept { - Matrix4< Component, Storage >::ThisType result; - Matrix4< Component, Storage >::Rows rows(result.vectors); + Matrix4::ThisType result; + Matrix4::Rows rows(result.vectors); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { - rows[i][j] = components[i*4 + j]; + rows[i][j] = components[i * 4 + j]; } } return result; } -template< typename Component, class Storage > -const typename Matrix4< Component, Storage >::ThisType Matrix4< Component, Storage >::FromColumnMajor(const Component* components) noexcept +template +const typename Matrix4::ThisType Matrix4::FromColumnMajor(const Component* components) noexcept { - Matrix4< Component, Storage >::ThisType result; - Matrix4< Component, Storage >::Columns columns(result.vectors); + Matrix4::ThisType result; + Matrix4::Columns columns(result.vectors); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { - columns[i][j] = components[i*4 + j]; + columns[i][j] = components[i * 4 + j]; } } return result; } // Set all rows -template< typename Component, class Storage > -void Matrix4< Component, Storage >::SetRows(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept +template +void Matrix4::SetRows(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept { Rows rows(vectors); rows[0] = vec0; @@ -164,8 +155,8 @@ void Matrix4< Component, Storage >::SetRows(const VectorType& vec0, const Vector } // Set all columns -template< typename Component, class Storage > -void Matrix4< Component, Storage >::SetColumns(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept +template +void Matrix4::SetColumns(const VectorType& vec0, const VectorType& vec1, const VectorType& vec2, const VectorType& vec3) noexcept { Columns columns(vectors); columns[0] = vec0; @@ -176,129 +167,62 @@ void Matrix4< Component, Storage >::SetColumns(const VectorType& vec0, const Vec // Inverts this matrix in place. // This is from the MESA implementation of the GLU library. -template< typename Component, class Storage > -bool Matrix4< Component, Storage >::Invert() noexcept -{ - Matrix4< Component, Storage >::ThisType result; - Component *dst = result.data(); - const Component *src = data(); - - dst[0] = src[5] * src[10] * src[15] - - src[5] * src[11] * src[14] - - src[9] * src[6] * src[15] + - src[9] * src[7] * src[14] + - src[13] * src[6] * src[11] - - src[13] * src[7] * src[10]; - - dst[4] = -src[4] * src[10] * src[15] + - src[4] * src[11] * src[14] + - src[8] * src[6] * src[15] - - src[8] * src[7] * src[14] - - src[12] * src[6] * src[11] + - src[12] * src[7] * src[10]; - - dst[8] = src[4] * src[9] * src[15] - - src[4] * src[11] * src[13] - - src[8] * src[5] * src[15] + - src[8] * src[7] * src[13] + - src[12] * src[5] * src[11] - - src[12] * src[7] * src[9]; - - dst[12] = -src[4] * src[9] * src[14] + - src[4] * src[10] * src[13] + - src[8] * src[5] * src[14] - - src[8] * src[6] * src[13] - - src[12] * src[5] * src[10] + - src[12] * src[6] * src[9]; - - dst[1] = -src[1] * src[10] * src[15] + - src[1] * src[11] * src[14] + - src[9] * src[2] * src[15] - - src[9] * src[3] * src[14] - - src[13] * src[2] * src[11] + - src[13] * src[3] * src[10]; - - dst[5] = src[0] * src[10] * src[15] - - src[0] * src[11] * src[14] - - src[8] * src[2] * src[15] + - src[8] * src[3] * src[14] + - src[12] * src[2] * src[11] - - src[12] * src[3] * src[10]; - - dst[9] = -src[0] * src[9] * src[15] + - src[0] * src[11] * src[13] + - src[8] * src[1] * src[15] - - src[8] * src[3] * src[13] - - src[12] * src[1] * src[11] + - src[12] * src[3] * src[9]; - - dst[13] = src[0] * src[9] * src[14] - - src[0] * src[10] * src[13] - - src[8] * src[1] * src[14] + - src[8] * src[2] * src[13] + - src[12] * src[1] * src[10] - - src[12] * src[2] * src[9]; - - dst[2] = src[1] * src[6] * src[15] - - src[1] * src[7] * src[14] - - src[5] * src[2] * src[15] + - src[5] * src[3] * src[14] + - src[13] * src[2] * src[7] - - src[13] * src[3] * src[6]; - - dst[6] = -src[0] * src[6] * src[15] + - src[0] * src[7] * src[14] + - src[4] * src[2] * src[15] - - src[4] * src[3] * src[14] - - src[12] * src[2] * src[7] + - src[12] * src[3] * src[6]; - - dst[10] = src[0] * src[5] * src[15] - - src[0] * src[7] * src[13] - - src[4] * src[1] * src[15] + - src[4] * src[3] * src[13] + - src[12] * src[1] * src[7] - - src[12] * src[3] * src[5]; - - dst[14] = -src[0] * src[5] * src[14] + - src[0] * src[6] * src[13] + - src[4] * src[1] * src[14] - - src[4] * src[2] * src[13] - - src[12] * src[1] * src[6] + - src[12] * src[2] * src[5]; - - dst[3] = -src[1] * src[6] * src[11] + - src[1] * src[7] * src[10] + - src[5] * src[2] * src[11] - - src[5] * src[3] * src[10] - - src[9] * src[2] * src[7] + - src[9] * src[3] * src[6]; - - dst[7] = src[0] * src[6] * src[11] - - src[0] * src[7] * src[10] - - src[4] * src[2] * src[11] + - src[4] * src[3] * src[10] + - src[8] * src[2] * src[7] - - src[8] * src[3] * src[6]; - - dst[11] = -src[0] * src[5] * src[11] + - src[0] * src[7] * src[9] + - src[4] * src[1] * src[11] - - src[4] * src[3] * src[9] - - src[8] * src[1] * src[7] + - src[8] * src[3] * src[5]; - - dst[15] = src[0] * src[5] * src[10] - - src[0] * src[6] * src[9] - - src[4] * src[1] * src[10] + - src[4] * src[2] * src[9] + - src[8] * src[1] * src[6] - +template +bool Matrix4::Invert() noexcept +{ + Matrix4::ThisType result; + Component* dst = result.data(); + const Component* src = data(); + + dst[0] = src[5] * src[10] * src[15] - src[5] * src[11] * src[14] - src[9] * src[6] * src[15] + src[9] * src[7] * src[14] + + src[13] * src[6] * src[11] - src[13] * src[7] * src[10]; + + dst[4] = -src[4] * src[10] * src[15] + src[4] * src[11] * src[14] + src[8] * src[6] * src[15] - src[8] * src[7] * src[14] - + src[12] * src[6] * src[11] + src[12] * src[7] * src[10]; + + dst[8] = src[4] * src[9] * src[15] - src[4] * src[11] * src[13] - src[8] * src[5] * src[15] + src[8] * src[7] * src[13] + + src[12] * src[5] * src[11] - src[12] * src[7] * src[9]; + + dst[12] = -src[4] * src[9] * src[14] + src[4] * src[10] * src[13] + src[8] * src[5] * src[14] - src[8] * src[6] * src[13] - + src[12] * src[5] * src[10] + src[12] * src[6] * src[9]; + + dst[1] = -src[1] * src[10] * src[15] + src[1] * src[11] * src[14] + src[9] * src[2] * src[15] - src[9] * src[3] * src[14] - + src[13] * src[2] * src[11] + src[13] * src[3] * src[10]; + + dst[5] = src[0] * src[10] * src[15] - src[0] * src[11] * src[14] - src[8] * src[2] * src[15] + src[8] * src[3] * src[14] + + src[12] * src[2] * src[11] - src[12] * src[3] * src[10]; + + dst[9] = -src[0] * src[9] * src[15] + src[0] * src[11] * src[13] + src[8] * src[1] * src[15] - src[8] * src[3] * src[13] - + src[12] * src[1] * src[11] + src[12] * src[3] * src[9]; + + dst[13] = src[0] * src[9] * src[14] - src[0] * src[10] * src[13] - src[8] * src[1] * src[14] + src[8] * src[2] * src[13] + + src[12] * src[1] * src[10] - src[12] * src[2] * src[9]; + + dst[2] = src[1] * src[6] * src[15] - src[1] * src[7] * src[14] - src[5] * src[2] * src[15] + src[5] * src[3] * src[14] + + src[13] * src[2] * src[7] - src[13] * src[3] * src[6]; + + dst[6] = -src[0] * src[6] * src[15] + src[0] * src[7] * src[14] + src[4] * src[2] * src[15] - src[4] * src[3] * src[14] - + src[12] * src[2] * src[7] + src[12] * src[3] * src[6]; + + dst[10] = src[0] * src[5] * src[15] - src[0] * src[7] * src[13] - src[4] * src[1] * src[15] + src[4] * src[3] * src[13] + + src[12] * src[1] * src[7] - src[12] * src[3] * src[5]; + + dst[14] = -src[0] * src[5] * src[14] + src[0] * src[6] * src[13] + src[4] * src[1] * src[14] - src[4] * src[2] * src[13] - + src[12] * src[1] * src[6] + src[12] * src[2] * src[5]; + + dst[3] = -src[1] * src[6] * src[11] + src[1] * src[7] * src[10] + src[5] * src[2] * src[11] - src[5] * src[3] * src[10] - + src[9] * src[2] * src[7] + src[9] * src[3] * src[6]; + + dst[7] = src[0] * src[6] * src[11] - src[0] * src[7] * src[10] - src[4] * src[2] * src[11] + src[4] * src[3] * src[10] + + src[8] * src[2] * src[7] - src[8] * src[3] * src[6]; + + dst[11] = -src[0] * src[5] * src[11] + src[0] * src[7] * src[9] + src[4] * src[1] * src[11] - src[4] * src[3] * src[9] - + src[8] * src[1] * src[7] + src[8] * src[3] * src[5]; + + dst[15] = src[0] * src[5] * src[10] - src[0] * src[6] * src[9] - src[4] * src[1] * src[10] + src[4] * src[2] * src[9] + src[8] * src[1] * src[6] - src[8] * src[2] * src[5]; - float det = src[0] * dst[0] + \ - src[1] * dst[4] + \ - src[2] * dst[8] + \ - src[3] * dst[12]; + float det = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8] + src[3] * dst[12]; if (det == 0) { @@ -309,66 +233,40 @@ bool Matrix4< Component, Storage >::Invert() noexcept return true; } - - - -template +template inline float Matrix4::Determinant() const noexcept { - const Component *src = data(); + const Component* src = data(); float diag[4]; // Diagonal elements of the matrix inverse (see Invert) - diag[0] = src[5] * src[10] * src[15] - - src[5] * src[11] * src[14] - - src[9] * src[6] * src[15] + - src[9] * src[7] * src[14] + - src[13] * src[6] * src[11] - - src[13] * src[7] * src[10]; - - diag[1] = -src[4] * src[10] * src[15] + - src[4] * src[11] * src[14] + - src[8] * src[6] * src[15] - - src[8] * src[7] * src[14] - - src[12] * src[6] * src[11] + - src[12] * src[7] * src[10]; - - diag[2] = src[4] * src[9] * src[15] - - src[4] * src[11] * src[13] - - src[8] * src[5] * src[15] + - src[8] * src[7] * src[13] + - src[12] * src[5] * src[11] - - src[12] * src[7] * src[9]; - - diag[3] = -src[4] * src[9] * src[14] + - src[4] * src[10] * src[13] + - src[8] * src[5] * src[14] - - src[8] * src[6] * src[13] - - src[12] * src[5] * src[10] + - src[12] * src[6] * src[9]; - - float det = src[0] * diag[0] + \ - src[1] * diag[1] + \ - src[2] * diag[2] + \ - src[3] * diag[3]; + diag[0] = src[5] * src[10] * src[15] - src[5] * src[11] * src[14] - src[9] * src[6] * src[15] + src[9] * src[7] * src[14] + + src[13] * src[6] * src[11] - src[13] * src[7] * src[10]; + + diag[1] = -src[4] * src[10] * src[15] + src[4] * src[11] * src[14] + src[8] * src[6] * src[15] - src[8] * src[7] * src[14] - + src[12] * src[6] * src[11] + src[12] * src[7] * src[10]; + + diag[2] = src[4] * src[9] * src[15] - src[4] * src[11] * src[13] - src[8] * src[5] * src[15] + src[8] * src[7] * src[13] + + src[12] * src[5] * src[11] - src[12] * src[7] * src[9]; + + diag[3] = -src[4] * src[9] * src[14] + src[4] * src[10] * src[13] + src[8] * src[5] * src[14] - src[8] * src[6] * src[13] - + src[12] * src[5] * src[10] + src[12] * src[6] * src[9]; + + float det = src[0] * diag[0] + src[1] * diag[1] + src[2] * diag[2] + src[3] * diag[3]; return det; } // Returns the negation of this matrix. -template< typename Component, class Storage > -typename Matrix4< Component, Storage >::ThisType Matrix4< Component, Storage >::operator-() const noexcept +template +typename Matrix4::ThisType Matrix4::operator-() const noexcept { - return typename Matrix4< Component, Storage >::ThisType( - -vectors[0], - -vectors[1], - -vectors[2], - -vectors[3] - ); + return typename Matrix4::ThisType(-vectors[0], -vectors[1], -vectors[2], -vectors[3]); } // Adds another matrix to this in-place. -template< typename Component, class Storage> -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator+=(const typename Matrix4< Component, Storage >::ThisType& other) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator+=( + const typename Matrix4::ThisType& other) noexcept { for (int i = 0; i < 4; ++i) { @@ -376,11 +274,12 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } return *this; } -template< typename Component, class Storage> -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator+=(const typename Matrix4< Component, Storage >::TransposeType& other) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator+=( + const typename Matrix4::TransposeType& other) noexcept { Rows rows(vectors); - typename Matrix4< Component, Storage >::TransposeType::ConstRows other_rows(other); + typename Matrix4::TransposeType::ConstRows other_rows(other); for (int i = 0; i < 4; ++i) { rows[i] += other_rows[i]; @@ -389,8 +288,9 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } // Subtracts another matrix from this in-place. -template< typename Component, class Storage> -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator-=(const typename Matrix4< Component, Storage >::ThisType& other) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator-=( + const typename Matrix4::ThisType& other) noexcept { for (int i = 0; i < 4; ++i) { @@ -398,11 +298,12 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } return *this; } -template< typename Component, class Storage> -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator-=(const typename Matrix4< Component, Storage >::TransposeType& other) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator-=( + const typename Matrix4::TransposeType& other) noexcept { Rows rows(vectors); - typename Matrix4< Component, Storage >::TransposeType::ConstRows other_rows(other); + typename Matrix4::TransposeType::ConstRows other_rows(other); for (int i = 0; i < 4; ++i) { rows[i] -= other_rows[i]; @@ -411,8 +312,8 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } // Scales this matrix in-place. -template< typename Component, class Storage> -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator*=(Component s) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator*=(Component s) noexcept { for (int i = 0; i < 4; ++i) { @@ -422,8 +323,8 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } // Scales this matrix in-place by the inverse of a value. -template< typename Component, class Storage> -const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Storage >::operator/=(Component s) noexcept +template +const typename Matrix4::ThisType& Matrix4::operator/=(Component s) noexcept { for (int i = 0; i < 4; ++i) { @@ -433,263 +334,210 @@ const typename Matrix4< Component, Storage >::ThisType& Matrix4< Component, Stor } // Equality operator. -template< typename Component, class Storage> -bool Matrix4< Component, Storage >::operator==(const typename Matrix4< Component, Storage >::ThisType& other) const noexcept +template +bool Matrix4::operator==(const typename Matrix4::ThisType& other) const noexcept { - typename Matrix4< Component, Storage >::ConstRows rows(vectors); - typename Matrix4< Component, Storage >::ConstRows other_rows(other.vectors); - return vectors[0] == other.vectors[0] - && vectors[1] == other.vectors[1] - && vectors[2] == other.vectors[2] - && vectors[3] == other.vectors[3]; + typename Matrix4::ConstRows rows(vectors); + typename Matrix4::ConstRows other_rows(other.vectors); + return vectors[0] == other.vectors[0] && vectors[1] == other.vectors[1] && vectors[2] == other.vectors[2] && vectors[3] == other.vectors[3]; } -template< typename Component, class Storage> -bool Matrix4< Component, Storage >::operator==(const typename Matrix4< Component, Storage >::TransposeType& other) const noexcept +template +bool Matrix4::operator==(const typename Matrix4::TransposeType& other) const noexcept { - typename Matrix4< Component, Storage >::ConstRows rows(vectors); - typename Matrix4< Component, Storage >::ConstRows other_rows(other.vectors); - return rows[0] == other_rows[0] - && rows[1] == other_rows[1] - && rows[2] == other_rows[2] - && rows[3] == other_rows[3]; + typename Matrix4::ConstRows rows(vectors); + typename Matrix4::ConstRows other_rows(other.vectors); + return rows[0] == other_rows[0] && rows[1] == other_rows[1] && rows[2] == other_rows[2] && rows[3] == other_rows[3]; } // Inequality operator. -template< typename Component, class Storage> -bool Matrix4< Component, Storage >::operator!=(const typename Matrix4< Component, Storage >::ThisType& other) const noexcept +template +bool Matrix4::operator!=(const typename Matrix4::ThisType& other) const noexcept { - return vectors[0] != other.vectors[0] - || vectors[1] != other.vectors[1] - || vectors[2] != other.vectors[2] - || vectors[3] != other.vectors[3]; + return vectors[0] != other.vectors[0] || vectors[1] != other.vectors[1] || vectors[2] != other.vectors[2] || vectors[3] != other.vectors[3]; } -template< typename Component, class Storage> -bool Matrix4< Component, Storage >::operator!=(const typename Matrix4< Component, Storage >::TransposeType& other) const noexcept +template +bool Matrix4::operator!=(const typename Matrix4::TransposeType& other) const noexcept { - typename Matrix4< Component, Storage >::ConstRows rows(vectors); - typename Matrix4< Component, Storage >::ConstRows other_rows(other.vectors); - return rows[0] != other_rows[0] - || rows[1] != other_rows[1] - || rows[2] != other_rows[2] - || rows[3] != other_rows[3]; + typename Matrix4::ConstRows rows(vectors); + typename Matrix4::ConstRows other_rows(other.vectors); + return rows[0] != other_rows[0] || rows[1] != other_rows[1] || rows[2] != other_rows[2] || rows[3] != other_rows[3]; } // Return the identity matrix. -template< typename Component, class Storage> -const Matrix4< Component, Storage >& Matrix4< Component, Storage >::Identity() noexcept +template +const Matrix4& Matrix4::Identity() noexcept { - static Matrix4< Component, Storage > identity(Diag(1, 1, 1, 1)); + static Matrix4 identity(Diag(1, 1, 1, 1)); return identity; } // Return a diagonal matrix. -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Diag(Component a, Component b, Component c, Component d) noexcept +template +Matrix4 Matrix4::Diag(Component a, Component b, Component c, Component d) noexcept { - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(a, 0, 0, 0), - Matrix4< Component, Storage >::VectorType(0, b, 0, 0), - Matrix4< Component, Storage >::VectorType(0, 0, c, 0), - Matrix4< Component, Storage >::VectorType(0, 0, 0, d) - ); + return Matrix4::FromRows(Matrix4::VectorType(a, 0, 0, 0), + Matrix4::VectorType(0, b, 0, 0), Matrix4::VectorType(0, 0, c, 0), + Matrix4::VectorType(0, 0, 0, d)); } // Create an orthographic projection matrix -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::ProjectOrtho(Component l, Component r, Component b, Component t, Component n, Component f) noexcept +template +Matrix4 Matrix4::ProjectOrtho(Component l, Component r, Component b, Component t, Component n, + Component f) noexcept { - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(2 / (r - l), 0, 0, -(r + l)/(r - l)), - Matrix4< Component, Storage >::VectorType(0, 2 / (t - b), 0, -(t + b)/(t - b)), - Matrix4< Component, Storage >::VectorType(0, 0, 2 / (f - n), -(f + n)/(f - n)), - Matrix4< Component, Storage >::VectorType(0, 0, 0, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(2 / (r - l), 0, 0, -(r + l) / (r - l)), + Matrix4::VectorType(0, 2 / (t - b), 0, -(t + b) / (t - b)), + Matrix4::VectorType(0, 0, 2 / (f - n), -(f + n) / (f - n)), Matrix4::VectorType(0, 0, 0, 1)); } // Create a perspective projection matrix -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::ProjectPerspective(Component l, Component r, Component b, Component t, Component n, Component f) noexcept +template +Matrix4 Matrix4::ProjectPerspective(Component l, Component r, Component b, Component t, Component n, + Component f) noexcept { - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(2 * n / (r - l), 0, (r + l)/(r - l), 0), - Matrix4< Component, Storage >::VectorType(0, 2 * n / (t - b), (t + b)/(t - b), 0), - Matrix4< Component, Storage >::VectorType(0, 0, -(f + n)/(f - n), -(2 * f * n)/(f - n)), - Matrix4< Component, Storage >::VectorType(0, 0, -1, 0) - ); + return Matrix4::FromRows(Matrix4::VectorType(2 * n / (r - l), 0, (r + l) / (r - l), 0), + Matrix4::VectorType(0, 2 * n / (t - b), (t + b) / (t - b), 0), + Matrix4::VectorType(0, 0, -(f + n) / (f - n), -(2 * f * n) / (f - n)), + Matrix4::VectorType(0, 0, -1, 0)); } // Create a perspective projection matrix -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Perspective(Component d) noexcept +template +Matrix4 Matrix4::Perspective(Component d) noexcept { - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(1, 0, 0, 0), - Matrix4< Component, Storage >::VectorType(0, 1, 0, 0), - Matrix4< Component, Storage >::VectorType(0, 0, 1, 0), - Matrix4< Component, Storage >::VectorType(0, 0, -static_cast(1)/d, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(1, 0, 0, 0), + Matrix4::VectorType(0, 1, 0, 0), Matrix4::VectorType(0, 0, 1, 0), + Matrix4::VectorType(0, 0, -static_cast(1) / d, 1)); } // Return a translation matrix. -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Translate(const Vector3< Component >& v) noexcept +template +Matrix4 Matrix4::Translate(const Vector3& v) noexcept { return Translate(v.x, v.y, v.z); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Translate(Component x, Component y, Component z) noexcept +template +Matrix4 Matrix4::Translate(Component x, Component y, Component z) noexcept { - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(1, 0, 0, x), - Matrix4< Component, Storage >::VectorType(0, 1, 0, y), - Matrix4< Component, Storage >::VectorType(0, 0, 1, z), - Matrix4< Component, Storage >::VectorType(0, 0, 0, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(1, 0, 0, x), + Matrix4::VectorType(0, 1, 0, y), Matrix4::VectorType(0, 0, 1, z), + Matrix4::VectorType(0, 0, 0, 1)); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::TranslateX(Component x) noexcept +template +Matrix4 Matrix4::TranslateX(Component x) noexcept { - return Translate(Vector3< Component >(x, 0, 0)); + return Translate(Vector3(x, 0, 0)); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::TranslateY(Component y) noexcept +template +Matrix4 Matrix4::TranslateY(Component y) noexcept { - return Translate(Vector3< Component >(0, y, 0)); + return Translate(Vector3(0, y, 0)); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::TranslateZ(Component z) noexcept +template +Matrix4 Matrix4::TranslateZ(Component z) noexcept { - return Translate(Vector3< Component >(0, 0, z)); + return Translate(Vector3(0, 0, z)); } // Return a scaling matrix. -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Scale(Component x, Component y, Component z) noexcept +template +Matrix4 Matrix4::Scale(Component x, Component y, Component z) noexcept { return Matrix4::Diag(x, y, z, 1); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::ScaleX(Component x) noexcept +template +Matrix4 Matrix4::ScaleX(Component x) noexcept { return Scale(x, 1, 1); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::ScaleY(Component y) noexcept +template +Matrix4 Matrix4::ScaleY(Component y) noexcept { return Scale(1, y, 1); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::ScaleZ(Component z) noexcept +template +Matrix4 Matrix4::ScaleZ(Component z) noexcept { return Scale(1, 1, z); } // Return a rotation matrix. -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Rotate(const Vector3< Component >& v, Component angle) noexcept +template +Matrix4 Matrix4::Rotate(const Vector3& v, Component angle) noexcept { - Vector3< Component > n = v.Normalise(); + Vector3 n = v.Normalise(); Component Sin = Math::Sin(angle); Component Cos = Math::Cos(angle); - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType( - n.x * n.x * (1 - Cos) + Cos, - n.x * n.y * (1 - Cos) - n.z * Sin, - n.x * n.z * (1 - Cos) + n.y * Sin, - 0 - ), - Matrix4< Component, Storage >::VectorType( - n.y * n.x * (1 - Cos) + n.z * Sin, - n.y * n.y * (1 - Cos) + Cos, - n.y * n.z * (1 - Cos) - n.x * Sin, - 0 - ), - Matrix4< Component, Storage >::VectorType( - n.z * n.x * (1 - Cos) - n.y * Sin, - n.z * n.y * (1 - Cos) + n.x * Sin, - n.z * n.z * (1 - Cos) + Cos, - 0 - ), - Matrix4< Component, Storage >::VectorType(0, 0, 0, 1) - ); -} - -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::RotateX(Component angle) noexcept + return Matrix4::FromRows( + Matrix4::VectorType(n.x * n.x * (1 - Cos) + Cos, n.x * n.y * (1 - Cos) - n.z * Sin, n.x * n.z * (1 - Cos) + n.y * Sin, 0), + Matrix4::VectorType(n.y * n.x * (1 - Cos) + n.z * Sin, n.y * n.y * (1 - Cos) + Cos, n.y * n.z * (1 - Cos) - n.x * Sin, 0), + Matrix4::VectorType(n.z * n.x * (1 - Cos) - n.y * Sin, n.z * n.y * (1 - Cos) + n.x * Sin, n.z * n.z * (1 - Cos) + Cos, 0), + Matrix4::VectorType(0, 0, 0, 1)); +} + +template +Matrix4 Matrix4::RotateX(Component angle) noexcept { Component Sin = Math::Sin(angle); Component Cos = Math::Cos(angle); - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(1, 0, 0, 0), - Matrix4< Component, Storage >::VectorType(0, Cos, -Sin, 0), - Matrix4< Component, Storage >::VectorType(0, Sin, Cos, 0), - Matrix4< Component, Storage >::VectorType(0, 0, 0, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(1, 0, 0, 0), + Matrix4::VectorType(0, Cos, -Sin, 0), Matrix4::VectorType(0, Sin, Cos, 0), + Matrix4::VectorType(0, 0, 0, 1)); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::RotateY(Component angle) noexcept +template +Matrix4 Matrix4::RotateY(Component angle) noexcept { Component Sin = Math::Sin(angle); Component Cos = Math::Cos(angle); - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType( Cos, 0, Sin, 0), - Matrix4< Component, Storage >::VectorType( 0, 1, 0, 0), - Matrix4< Component, Storage >::VectorType(-Sin, 0, Cos, 0), - Matrix4< Component, Storage >::VectorType( 0, 0, 0, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(Cos, 0, Sin, 0), + Matrix4::VectorType(0, 1, 0, 0), Matrix4::VectorType(-Sin, 0, Cos, 0), + Matrix4::VectorType(0, 0, 0, 1)); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::RotateZ(Component angle) noexcept +template +Matrix4 Matrix4::RotateZ(Component angle) noexcept { Component Sin = Math::Sin(angle); Component Cos = Math::Cos(angle); - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(Cos, -Sin, 0, 0), - Matrix4< Component, Storage >::VectorType(Sin, Cos, 0, 0), - Matrix4< Component, Storage >::VectorType( 0, 0, 1, 0), - Matrix4< Component, Storage >::VectorType( 0, 0, 0, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(Cos, -Sin, 0, 0), + Matrix4::VectorType(Sin, Cos, 0, 0), Matrix4::VectorType(0, 0, 1, 0), + Matrix4::VectorType(0, 0, 0, 1)); } // Return a skew/shearing matrix. // @return A skew matrix. -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::Skew(Component angle_x, Component angle_y) noexcept +template +Matrix4 Matrix4::Skew(Component angle_x, Component angle_y) noexcept { Component SkewX = Math::Tan(angle_x); Component SkewY = Math::Tan(angle_y); - return Matrix4< Component, Storage >::FromRows( - Matrix4< Component, Storage >::VectorType(1, SkewX, 0, 0), - Matrix4< Component, Storage >::VectorType(SkewY, 1, 0, 0), - Matrix4< Component, Storage >::VectorType( 0, 0, 1, 0), - Matrix4< Component, Storage >::VectorType( 0, 0, 0, 1) - ); + return Matrix4::FromRows(Matrix4::VectorType(1, SkewX, 0, 0), + Matrix4::VectorType(SkewY, 1, 0, 0), Matrix4::VectorType(0, 0, 1, 0), + Matrix4::VectorType(0, 0, 0, 1)); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::SkewX(Component angle) noexcept +template +Matrix4 Matrix4::SkewX(Component angle) noexcept { return Skew(angle, 0); } -template< typename Component, class Storage> -Matrix4< Component, Storage > Matrix4< Component, Storage >::SkewY(Component angle) noexcept +template +Matrix4 Matrix4::SkewY(Component angle) noexcept { return Skew(0, angle); } -template -Matrix4< Component, Storage > Matrix4::Compose(const Vector3& translation, - const Vector3& scale, const Vector3& skew, const Vector4& perspective, - const Vector4& quaternion) noexcept +template +Matrix4 Matrix4::Compose(const Vector3& translation, const Vector3& scale, + const Vector3& skew, const Vector4& perspective, const Vector4& quaternion) noexcept { ThisType matrix = ThisType::Identity(); @@ -699,23 +547,21 @@ Matrix4< Component, Storage > Matrix4::Compose(const Vector3 for (int i = 0; i < 4; i++) for (int j = 0; j < 3; j++) matrix[3][i] += translation[j] * matrix[j][i]; - + float x = quaternion.x; float y = quaternion.y; float z = quaternion.z; float w = quaternion.w; - ThisType rotation = Matrix4< Component, Storage >::FromRows( - VectorType(1.f - 2.f * (y*y + z * z), 2.f*(x*y - z * w), 2.f*(x*z + y * w), 0.f), - VectorType(2.f * (x * y + z * w), 1.f - 2.f * (x * x + z * z), 2.f * (y * z - x * w), 0.f), - VectorType(2.f * (x * z - y * w), 2.f * (y * z + x * w), 1.f - 2.f * (x * x + y * y), 0.f), - VectorType(0, 0, 0, 1) - ); + ThisType rotation = + Matrix4::FromRows(VectorType(1.f - 2.f * (y * y + z * z), 2.f * (x * y - z * w), 2.f * (x * z + y * w), 0.f), + VectorType(2.f * (x * y + z * w), 1.f - 2.f * (x * x + z * z), 2.f * (y * z - x * w), 0.f), + VectorType(2.f * (x * z - y * w), 2.f * (y * z + x * w), 1.f - 2.f * (x * x + y * y), 0.f), VectorType(0, 0, 0, 1)); matrix *= rotation; ThisType temp = ThisType::Identity(); - if(skew[2]) + if (skew[2]) { temp[2][1] = skew[2]; matrix *= temp; @@ -740,57 +586,44 @@ Matrix4< Component, Storage > Matrix4::Compose(const Vector3 return matrix; } -template< typename Component, class Storage > -template< typename _Component > -struct Matrix4< Component, Storage >::VectorMultiplier< _Component, RowMajorStorage< _Component > > -{ +template +template +struct Matrix4::VectorMultiplier<_Component, RowMajorStorage<_Component>> { typedef _Component ComponentType; - typedef RowMajorStorage< ComponentType > StorageAType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Vector4< ComponentType > VectorType; + typedef RowMajorStorage StorageAType; + typedef Matrix4 MatrixAType; + typedef Vector4 VectorType; static const VectorType Multiply(const MatrixAType& lhs, const VectorType& rhs) noexcept { typename MatrixAType::ConstRows rows(lhs.vectors); - return VectorType( - rhs.DotProduct(rows[0]), - rhs.DotProduct(rows[1]), - rhs.DotProduct(rows[2]), - rhs.DotProduct(rows[3]) - ); + return VectorType(rhs.DotProduct(rows[0]), rhs.DotProduct(rows[1]), rhs.DotProduct(rows[2]), rhs.DotProduct(rows[3])); } }; -template< typename Component, class Storage > -template< typename _Component > -struct Matrix4< Component, Storage >::VectorMultiplier< _Component, ColumnMajorStorage< _Component > > -{ +template +template +struct Matrix4::VectorMultiplier<_Component, ColumnMajorStorage<_Component>> { typedef _Component ComponentType; - typedef ColumnMajorStorage< ComponentType > StorageAType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Vector4< ComponentType > VectorType; + typedef ColumnMajorStorage StorageAType; + typedef Matrix4 MatrixAType; + typedef Vector4 VectorType; static const VectorType Multiply(const MatrixAType& lhs, const VectorType& rhs) noexcept { typename MatrixAType::ConstRows rows(lhs.vectors); - return VectorType( - rhs.DotProduct(rows[0]), - rhs.DotProduct(rows[1]), - rhs.DotProduct(rows[2]), - rhs.DotProduct(rows[3]) - ); + return VectorType(rhs.DotProduct(rows[0]), rhs.DotProduct(rows[1]), rhs.DotProduct(rows[2]), rhs.DotProduct(rows[3])); } }; -template< typename Component, class Storage > -template< typename _Component, class _StorageB > -struct Matrix4< Component, Storage >::MatrixMultiplier< _Component, RowMajorStorage< _Component >, _StorageB > -{ +template +template +struct Matrix4::MatrixMultiplier<_Component, RowMajorStorage<_Component>, _StorageB> { typedef _Component ComponentType; - typedef RowMajorStorage< ComponentType > StorageAType; + typedef RowMajorStorage StorageAType; typedef _StorageB StorageBType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Matrix4< ComponentType, StorageBType > MatrixBType; + typedef Matrix4 MatrixAType; + typedef Matrix4 MatrixBType; static const MatrixAType Multiply(const MatrixAType& lhs, const MatrixBType& rhs) noexcept { @@ -809,15 +642,14 @@ struct Matrix4< Component, Storage >::MatrixMultiplier< _Component, RowMajorStor } }; -template< typename Component, class Storage > -template< typename _Component > -struct Matrix4< Component, Storage >::MatrixMultiplier< _Component, ColumnMajorStorage< _Component >, ColumnMajorStorage< _Component > > -{ +template +template +struct Matrix4::MatrixMultiplier<_Component, ColumnMajorStorage<_Component>, ColumnMajorStorage<_Component>> { typedef _Component ComponentType; - typedef ColumnMajorStorage< ComponentType > StorageAType; - typedef ColumnMajorStorage< ComponentType > StorageBType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Matrix4< ComponentType, StorageBType > MatrixBType; + typedef ColumnMajorStorage StorageAType; + typedef ColumnMajorStorage StorageBType; + typedef Matrix4 MatrixAType; + typedef Matrix4 MatrixBType; static const MatrixAType Multiply(const MatrixAType& lhs, const MatrixBType& rhs) noexcept { @@ -836,20 +668,16 @@ struct Matrix4< Component, Storage >::MatrixMultiplier< _Component, ColumnMajorS } }; -template< typename Component, class Storage > -template< typename _Component > -struct Matrix4< Component, Storage >::MatrixMultiplier< _Component, ColumnMajorStorage< _Component >, RowMajorStorage< _Component > > -{ +template +template +struct Matrix4::MatrixMultiplier<_Component, ColumnMajorStorage<_Component>, RowMajorStorage<_Component>> { typedef _Component ComponentType; - typedef ColumnMajorStorage< ComponentType > StorageAType; - typedef RowMajorStorage< ComponentType > StorageBType; - typedef Matrix4< ComponentType, StorageAType > MatrixAType; - typedef Matrix4< ComponentType, StorageBType > MatrixBType; + typedef ColumnMajorStorage StorageAType; + typedef RowMajorStorage StorageBType; + typedef Matrix4 MatrixAType; + typedef Matrix4 MatrixBType; - static const MatrixAType Multiply(const MatrixAType& lhs, const MatrixBType& rhs) noexcept - { - return lhs * MatrixAType(rhs); - } + static const MatrixAType Multiply(const MatrixAType& lhs, const MatrixBType& rhs) noexcept { return lhs * MatrixAType(rhs); } }; } // namespace Rml diff --git a/Include/RmlUi/Core/ObserverPtr.h b/Include/RmlUi/Core/ObserverPtr.h index 906fdacf0..4e7a3aff9 100644 --- a/Include/RmlUi/Core/ObserverPtr.h +++ b/Include/RmlUi/Core/ObserverPtr.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,9 +29,9 @@ #ifndef RMLUIOBSERVERPTR_H #define RMLUIOBSERVERPTR_H -#include -#include #include "Header.h" +#include +#include namespace Rml { @@ -42,44 +42,43 @@ struct RMLUICORE_API ObserverPtrBlock { RMLUICORE_API ObserverPtrBlock* AllocateObserverPtrBlock(); RMLUICORE_API void DeallocateObserverPtrBlockIfEmpty(ObserverPtrBlock* block); -template +template class EnableObserverPtr; - /** - Observer pointer. + Observer pointer. - Holds a weak reference to an object owned by someone else. Can tell whether or not the pointed to object has been destroyed. + Holds a weak reference to an object owned by someone else. Can tell whether or not the pointed to object has been destroyed. - Usage: Given a class T, derive from EnableObserverPtr. Then, we can use the observer pointer as follows: + Usage: Given a class T, derive from EnableObserverPtr. Then, we can use the observer pointer as follows: - auto object = MakeUnique(); - ObserverPtr observer_ptr = object->GetObserverPtr(); - // ... - if(obserer_ptr) { - // Will only enter if object is still alive. - observer_ptr->do_a_thing(); - } + auto object = MakeUnique(); + ObserverPtr observer_ptr = object->GetObserverPtr(); + // ... + if(obserer_ptr) { + // Will only enter if object is still alive. + observer_ptr->do_a_thing(); + } - Note: Not thread safe. + Note: Not thread safe. */ -template +template class RMLUICORE_API ObserverPtr { public: ObserverPtr() noexcept : block(nullptr) {} ObserverPtr(std::nullptr_t) noexcept : block(nullptr) {} - ~ObserverPtr() noexcept { - reset(); - } + ~ObserverPtr() noexcept { reset(); } // Copy - ObserverPtr(const ObserverPtr& other) noexcept : block(other.block) { + ObserverPtr(const ObserverPtr& other) noexcept : block(other.block) + { if (block) block->num_observers += 1; } - ObserverPtr& operator=(const ObserverPtr& other) noexcept { - if(this == &other) + ObserverPtr& operator=(const ObserverPtr& other) noexcept + { + if (this == &other) return *this; reset(); block = other.block; @@ -90,8 +89,9 @@ class RMLUICORE_API ObserverPtr { // Move ObserverPtr(ObserverPtr&& other) noexcept : block(std::exchange(other.block, nullptr)) {} - ObserverPtr& operator=(ObserverPtr&& other) noexcept { - if(this == &other) + ObserverPtr& operator=(ObserverPtr&& other) noexcept + { + if (this == &other) return *this; reset(); block = std::exchange(other.block, nullptr); @@ -106,17 +106,14 @@ class RMLUICORE_API ObserverPtr { bool operator==(const ObserverPtr& other) const noexcept { return get() == other.get(); } // Retrieve the pointer to the observed object if we have one and it's still alive. - T* get() const noexcept { - return block ? static_cast(block->pointed_to_object) : nullptr; - } + T* get() const noexcept { return block ? static_cast(block->pointed_to_object) : nullptr; } // Dereference the pointed to object. - T* operator->() const noexcept { - return static_cast(block->pointed_to_object); - } + T* operator->() const noexcept { return static_cast(block->pointed_to_object); } // Reset the pointer so that it does not point to anything. // When the pointed to object and all observer pointers to it have been destroyed, it will deallocate the block. - void reset() noexcept { + void reset() noexcept + { if (block) { block->num_observers -= 1; @@ -128,7 +125,8 @@ class RMLUICORE_API ObserverPtr { private: friend class Rml::EnableObserverPtr; - explicit ObserverPtr(ObserverPtrBlock* block) noexcept : block(block) { + explicit ObserverPtr(ObserverPtrBlock* block) noexcept : block(block) + { if (block) block->num_observers += 1; } @@ -136,23 +134,20 @@ class RMLUICORE_API ObserverPtr { ObserverPtrBlock* block; }; - - -template +template class RMLUICORE_API EnableObserverPtr { public: - - ObserverPtr GetObserverPtr() { + ObserverPtr GetObserverPtr() + { InitializeBlock(); return ObserverPtr(block); } protected: - EnableObserverPtr() noexcept { - static_assert(std::is_base_of, T>::value, "T must derive from EnableObserverPtr."); - } + EnableObserverPtr() noexcept { static_assert(std::is_base_of, T>::value, "T must derive from EnableObserverPtr."); } - ~EnableObserverPtr() noexcept { + ~EnableObserverPtr() noexcept + { if (block) { block->pointed_to_object = nullptr; @@ -160,24 +155,27 @@ class RMLUICORE_API EnableObserverPtr { } } - EnableObserverPtr(const EnableObserverPtr&) noexcept { + EnableObserverPtr(const EnableObserverPtr&) noexcept + { // Do not copy or modify the block, it should always point to the same object. } - EnableObserverPtr& operator=(const EnableObserverPtr&) noexcept { + EnableObserverPtr& operator=(const EnableObserverPtr&) noexcept + { // Assignment should not do anything, the block must point to the initially constructed object. - return *this; + return *this; } - EnableObserverPtr(EnableObserverPtr&&) noexcept { + EnableObserverPtr(EnableObserverPtr&&) noexcept + { // Do not move or modify the block, it should always point to the same object. } - EnableObserverPtr& operator=(EnableObserverPtr&&) noexcept { + EnableObserverPtr& operator=(EnableObserverPtr&&) noexcept + { // Assignment should not do anything, the block must point to the initially constructed object. return *this; } private: - inline void InitializeBlock() { if (!block) @@ -191,6 +189,5 @@ class RMLUICORE_API EnableObserverPtr { ObserverPtrBlock* block = nullptr; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Platform.h b/Include/RmlUi/Core/Platform.h index d5dc107d2..4c7e19465 100644 --- a/Include/RmlUi/Core/Platform.h +++ b/Include/RmlUi/Core/Platform.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -51,12 +51,11 @@ #endif #if defined __LP64__ || defined _M_X64 || defined _WIN64 || defined __MINGW64__ || defined _LP64 - #define RMLUI_ARCH_64 + #define RMLUI_ARCH_64 #else - #define RMLUI_ARCH_32 + #define RMLUI_ARCH_32 #endif - #if defined(RMLUI_PLATFORM_WIN32) && !defined(__MINGW32__) // declaration of 'identifier' hides class member #pragma warning(disable : 4458) @@ -68,75 +67,13 @@ #pragma warning(disable : 4996) #endif -// Wraps unused variables in methods or functions to avoid compiler warnings. This should -// be wrapped around the name of all parameters that are wrapped with RMLUI_UNUSED_PARAMETER -// to cover warnings generated by non-llvm/gcc style compilers that can't be covered with -// RMLUI_UNUSED_PARAMETER -#if defined __llvm__ -//# define RMLUI_UNUSED(x) UNUSED_ ## x __unused -# define RMLUI_UNUSED(x) -#elif defined __GNUC__ -//# define RMLUI_UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) -# define RMLUI_UNUSED(x) -#else -# define RMLUI_UNUSED(x) (void)(UNUSED_ ## x) -#endif - -// Wraps unused parameter names in method or function declarations. When used, the first lines -// of the function should contain a matching RMLUI_UNUSED call with the name of the function -// as well to cover compilers with no-op RMLUI_UNUSED_PARAMETER macros. -#if defined __llvm__ -# define RMLUI_UNUSED_PARAMETER(x) UNUSED_ ## x __attribute__((unused)) -#elif defined __GNUC__ -# define RMLUI_UNUSED_PARAMETER(x) UNUSED_ ## x __attribute__((__unused__)) -#else -# define RMLUI_UNUSED_PARAMETER(x) UNUSED_ ## x -#endif - -// RMLUI_UNUSED_ASSERT_PARAMETERS wraps method parameters which are not used in the method other than -// by a RMLUI_ASSERT check. This safely deals with debug versus release mode configurations -// and will warn if the parameter starts being used when compiled with GCC -#ifdef RMLUI_DEBUG - // In this case, the parameter is used by a RMLUI_ASSERT test, so we just pass through as is -# define RMLUI_UNUSED_ASSERT_PARAMETER(x) x -# define RMLUI_UNUSED_ASSERT(x) -#else - // If not in DEBUG builds, this parameter is unused, mark it as such -# if defined __llvm__ -# define RMLUI_UNUSED_ASSERT_PARAMETER(x) UNUSED_ ## x __attribute__((unused)) -# define RMLUI_UNUSED_ASSERT(x) -# elif defined __GNUC__ -# define RMLUI_UNUSED_ASSERT_PARAMETER(x) UNUSED_ ## x __attribute__((__unused__)) -# define RMLUI_UNUSED_ASSERT(x) -# else -# define RMLUI_UNUSED_ASSERT_PARAMETER(x) UNUSED_ ## x -# define RMLUI_UNUSED_ASSERT(x) (void)(UNUSED_ ## x) -# endif -#endif - -// Wraps functions which are not referenced or exported to avoid compiler warnings -#if defined __llvm__ -# define RMLUI_UNUSED_FUNCTION(x) __attribute__((unused)) UNUSED_ ## x -#elif defined __GNUC__ -# define RMLUI_UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x -#else -# define RMLUI_UNUSED_FUNCTION(x) UNUSED_ ## x -#endif - -// Squelchs warnings for unused enums in switch statements, this should only be used for special values -// that are known to NEVER be used. -#define RMLUI_UNUSED_SWITCH_ENUM(x) \ - case x: \ - RMLUI_ERRORMSG("Switch case for unhandled ENUM has been hit! This shouldn't happen! ENUM Name: " # x); \ - break; - // Tell the compiler of printf-like functions, warns on incorrect usage. #if defined __MINGW32__ -# define RMLUI_ATTRIBUTE_FORMAT_PRINTF(i, f) __attribute__((format (__MINGW_PRINTF_FORMAT, i, f))) + #define RMLUI_ATTRIBUTE_FORMAT_PRINTF(i, f) __attribute__((format(__MINGW_PRINTF_FORMAT, i, f))) #elif defined __GNUC__ || defined __clang__ -# define RMLUI_ATTRIBUTE_FORMAT_PRINTF(i, f) __attribute__((format (printf, i, f))) + #define RMLUI_ATTRIBUTE_FORMAT_PRINTF(i, f) __attribute__((format(printf, i, f))) #else -# define RMLUI_ATTRIBUTE_FORMAT_PRINTF(i, f) + #define RMLUI_ATTRIBUTE_FORMAT_PRINTF(i, f) #endif #endif diff --git a/Include/RmlUi/Core/Plugin.h b/Include/RmlUi/Core/Plugin.h index ccbc4cdbd..0cb21b673 100644 --- a/Include/RmlUi/Core/Plugin.h +++ b/Include/RmlUi/Core/Plugin.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,30 +39,27 @@ class ElementDocument; class Context; /** - Generic Interface for plugins to RmlUi. + Generic Interface for plugins to RmlUi. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API Plugin -{ +class RMLUICORE_API Plugin { public: virtual ~Plugin(); - enum EventClasses - { - EVT_BASIC = (1 << 0), // Initialise, Shutdown, ContextCreate, ContextDestroy - EVT_DOCUMENT = (1 << 1), // DocumentOpen, DocumentLoad, DocumentUnload - EVT_ELEMENT = (1 << 2), // ElementCreate, ElementDestroy + enum EventClasses { + EVT_BASIC = (1 << 0), // Initialise, Shutdown, ContextCreate, ContextDestroy + EVT_DOCUMENT = (1 << 1), // DocumentOpen, DocumentLoad, DocumentUnload + EVT_ELEMENT = (1 << 2), // ElementCreate, ElementDestroy - EVT_ALL = EVT_BASIC | EVT_DOCUMENT | EVT_ELEMENT + EVT_ALL = EVT_BASIC | EVT_DOCUMENT | EVT_ELEMENT }; - /// Called when the plugin is registered to determine - /// which of the above event types the plugin is interested in + /// Called when the plugin is registered to determine which of the above event types the plugin is interested in. virtual int GetEventClasses(); - /// Called when RmlUi is initialised, or immediately when the plugin registers itself if - /// RmlUi has already been initialised. + /// Called when RmlUi is initialised, or immediately when the plugin registers itself if RmlUi has already been + /// initialised. virtual void OnInitialise(); /// Called when RmlUi shuts down. virtual void OnShutdown(); diff --git a/Include/RmlUi/Core/Profiling.h b/Include/RmlUi/Core/Profiling.h index 6d46382b3..b589ad14c 100644 --- a/Include/RmlUi/Core/Profiling.h +++ b/Include/RmlUi/Core/Profiling.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,55 +29,53 @@ #ifndef RMLUI_CORE_PROFILING_H #define RMLUI_CORE_PROFILING_H - #ifdef RMLUI_ENABLE_PROFILING -#define TRACY_ENABLE -#include + #define TRACY_ENABLE + #include -#define RMLUI_ZoneNamed(varname, active) ZoneNamed(varname, active) -#define RMLUI_ZoneNamedN(varname, name, active) ZoneNamedN(varname, name, active) -#define RMLUI_ZoneNamedC(varname, color, active) ZoneNamedC(varname, color, active) -#define RMLUI_ZoneNamedNC(varname, name, color, active) ZoneNamedNC(varname, name, color, active) + #define RMLUI_ZoneNamed(varname, active) ZoneNamed(varname, active) + #define RMLUI_ZoneNamedN(varname, name, active) ZoneNamedN(varname, name, active) + #define RMLUI_ZoneNamedC(varname, color, active) ZoneNamedC(varname, color, active) + #define RMLUI_ZoneNamedNC(varname, name, color, active) ZoneNamedNC(varname, name, color, active) -#define RMLUI_ZoneScoped ZoneScoped -#define RMLUI_ZoneScopedN(name) ZoneScopedN(name) -#define RMLUI_ZoneScopedC(color) ZoneScopedC(color) -#define RMLUI_ZoneScopedNC(name, color) ZoneScopedNC(name, color) + #define RMLUI_ZoneScoped ZoneScoped + #define RMLUI_ZoneScopedN(name) ZoneScopedN(name) + #define RMLUI_ZoneScopedC(color) ZoneScopedC(color) + #define RMLUI_ZoneScopedNC(name, color) ZoneScopedNC(name, color) -#define RMLUI_ZoneText(txt, size) ZoneText(txt, size) -#define RMLUI_ZoneName(txt, size) ZoneName(txt, size) + #define RMLUI_ZoneText(txt, size) ZoneText(txt, size) + #define RMLUI_ZoneName(txt, size) ZoneName(txt, size) -#define RMLUI_TracyPlot(name,val) TracyPlot(name, val) + #define RMLUI_TracyPlot(name, val) TracyPlot(name, val) -#define RMLUI_FrameMark FrameMark -#define RMLUI_FrameMarkNamed(name) FrameMarkNamed(name) -#define RMLUI_FrameMarkStart(name) FrameMarkStart(name) -#define RMLUI_FrameMarkEnd(name) FrameMarkEnd(name) + #define RMLUI_FrameMark FrameMark + #define RMLUI_FrameMarkNamed(name) FrameMarkNamed(name) + #define RMLUI_FrameMarkStart(name) FrameMarkStart(name) + #define RMLUI_FrameMarkEnd(name) FrameMarkEnd(name) #else -#define RMLUI_ZoneNamed(varname, active) -#define RMLUI_ZoneNamedN(varname, name, active) -#define RMLUI_ZoneNamedC(varname, color, active) -#define RMLUI_ZoneNamedNC(varname, name, color, active) + #define RMLUI_ZoneNamed(varname, active) + #define RMLUI_ZoneNamedN(varname, name, active) + #define RMLUI_ZoneNamedC(varname, color, active) + #define RMLUI_ZoneNamedNC(varname, name, color, active) -#define RMLUI_ZoneScoped -#define RMLUI_ZoneScopedN(name) -#define RMLUI_ZoneScopedC(color) -#define RMLUI_ZoneScopedNC(name, color) + #define RMLUI_ZoneScoped + #define RMLUI_ZoneScopedN(name) + #define RMLUI_ZoneScopedC(color) + #define RMLUI_ZoneScopedNC(name, color) -#define RMLUI_ZoneText(txt, size) -#define RMLUI_ZoneName(txt, size) + #define RMLUI_ZoneText(txt, size) + #define RMLUI_ZoneName(txt, size) -#define RMLUI_TracyPlot(name,val) + #define RMLUI_TracyPlot(name, val) -#define RMLUI_FrameMark -#define RMLUI_FrameMarkNamed(name) -#define RMLUI_FrameMarkStart(name) -#define RMLUI_FrameMarkEnd(name) + #define RMLUI_FrameMark + #define RMLUI_FrameMarkNamed(name) + #define RMLUI_FrameMarkStart(name) + #define RMLUI_FrameMarkEnd(name) #endif - #endif diff --git a/Include/RmlUi/Core/PropertiesIteratorView.h b/Include/RmlUi/Core/PropertiesIteratorView.h index 7e413080a..f79acae36 100644 --- a/Include/RmlUi/Core/PropertiesIteratorView.h +++ b/Include/RmlUi/Core/PropertiesIteratorView.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,25 +28,25 @@ #ifndef RMLUI_CORE_PROPERTIESITERATORVIEW_H #define RMLUI_CORE_PROPERTIESITERATORVIEW_H -#include "Types.h" #include "Property.h" +#include "Types.h" namespace Rml { class PropertiesIterator; /** - Provides an iterator for properties defined in the element's style or definition. - Construct it through the desired Element. - Warning: Modifying the underlying style invalidates the iterator. + Provides an iterator for properties defined in the element's style or definition. + Construct it through the desired Element. + Warning: Modifying the underlying style invalidates the iterator. - Usage: - for(auto it = element.IterateLocalProperties(); !it.AtEnd(); ++it) { ... } + Usage: + for(auto it = element.IterateLocalProperties(); !it.AtEnd(); ++it) { ... } - Note: Not an std-style iterator. Implemented as a wrapper over the internal - iterator to avoid exposing internal headers to the user. + Note: Not an std-style iterator. Implemented as a wrapper over the internal + iterator to avoid exposing internal headers to the user. - @author Michael R. P. Ragazzon + @author Michael R. P. Ragazzon */ class RMLUICORE_API PropertiesIteratorView { @@ -73,4 +73,4 @@ class RMLUICORE_API PropertiesIteratorView { }; } // namespace Rml -#endif \ No newline at end of file +#endif diff --git a/Include/RmlUi/Core/Property.h b/Include/RmlUi/Core/Property.h index 8b9eaad93..12ebaa355 100644 --- a/Include/RmlUi/Core/Property.h +++ b/Include/RmlUi/Core/Property.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_PROPERTY_H #define RMLUI_CORE_PROPERTY_H -#include "Variant.h" #include "Header.h" +#include "Variant.h" #include namespace Rml { @@ -38,61 +38,58 @@ namespace Rml { class PropertyDefinition; struct RMLUICORE_API PropertySource { - PropertySource(String path, int line_number, String rule_name) - : path(std::move(path)), line_number(line_number), rule_name(std::move(rule_name)) {} + PropertySource(String path, int line_number, String rule_name) : path(std::move(path)), line_number(line_number), rule_name(std::move(rule_name)) + {} String path; int line_number; String rule_name; }; - /** - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API Property -{ +class RMLUICORE_API Property { public: - enum Unit - { + enum Unit { UNKNOWN = 1 << 0, - KEYWORD = 1 << 1, // generic keyword; fetch as < int > + KEYWORD = 1 << 1, // generic keyword; fetch as < int > - STRING = 1 << 2, // generic string; fetch as < String > + STRING = 1 << 2, // generic string; fetch as < String > // Absolute values. - NUMBER = 1 << 3, // number unsuffixed; fetch as < float > - PX = 1 << 4, // number suffixed by 'px'; fetch as < float > - DEG = 1 << 5, // number suffixed by 'deg'; fetch as < float > - RAD = 1 << 6, // number suffixed by 'rad'; fetch as < float > - COLOUR = 1 << 7, // colour; fetch as < Colourb > - DP = 1 << 8, // density-independent pixel; number suffixed by 'dp'; fetch as < float > - X = 1 << 9, // dots per px unit; number suffixed by 'x'; fetch as < float > - VW = 1 << 10, // viewport-width percentage; number suffixed by 'vw'; fetch as < float > - VH = 1 << 11, // viewport-height percentage; number suffixed by 'vh'; fetch as < float > + NUMBER = 1 << 3, // number unsuffixed; fetch as < float > + PX = 1 << 4, // number suffixed by 'px'; fetch as < float > + DEG = 1 << 5, // number suffixed by 'deg'; fetch as < float > + RAD = 1 << 6, // number suffixed by 'rad'; fetch as < float > + COLOUR = 1 << 7, // colour; fetch as < Colourb > + DP = 1 << 8, // density-independent pixel; number suffixed by 'dp'; fetch as < float > + X = 1 << 9, // dots per px unit; number suffixed by 'x'; fetch as < float > + VW = 1 << 10, // viewport-width percentage; number suffixed by 'vw'; fetch as < float > + VH = 1 << 11, // viewport-height percentage; number suffixed by 'vh'; fetch as < float > ABSOLUTE_UNIT = NUMBER | PX | DP | X | DEG | RAD | COLOUR | VW | VH, // Relative values. - EM = 1 << 12, // number suffixed by 'em'; fetch as < float > - PERCENT = 1 << 13, // number suffixed by '%'; fetch as < float > - REM = 1 << 14, // number suffixed by 'rem'; fetch as < float > + EM = 1 << 12, // number suffixed by 'em'; fetch as < float > + PERCENT = 1 << 13, // number suffixed by '%'; fetch as < float > + REM = 1 << 14, // number suffixed by 'rem'; fetch as < float > RELATIVE_UNIT = EM | REM | PERCENT, // Values based on pixels-per-inch. - INCH = 1 << 15, // number suffixed by 'in'; fetch as < float > - CM = 1 << 16, // number suffixed by 'cm'; fetch as < float > - MM = 1 << 17, // number suffixed by 'mm'; fetch as < float > - PT = 1 << 18, // number suffixed by 'pt'; fetch as < float > - PC = 1 << 19, // number suffixed by 'pc'; fetch as < float > + INCH = 1 << 15, // number suffixed by 'in'; fetch as < float > + CM = 1 << 16, // number suffixed by 'cm'; fetch as < float > + MM = 1 << 17, // number suffixed by 'mm'; fetch as < float > + PT = 1 << 18, // number suffixed by 'pt'; fetch as < float > + PC = 1 << 19, // number suffixed by 'pc'; fetch as < float > PPI_UNIT = INCH | CM | MM | PT | PC, - TRANSFORM = 1 << 20, // transform; fetch as < TransformPtr >, may be empty - TRANSITION = 1 << 21, // transition; fetch as < TransitionList > - ANIMATION = 1 << 22, // animation; fetch as < AnimationList > - DECORATOR = 1 << 23, // decorator; fetch as < DecoratorsPtr > - FONTEFFECT = 1 << 24, // font-effect; fetch as < FontEffectsPtr > - RATIO = 1 << 25, // ratio defined as x/y; fetch as < Vector2f > + TRANSFORM = 1 << 20, // transform; fetch as < TransformPtr >, may be empty + TRANSITION = 1 << 21, // transition; fetch as < TransitionList > + ANIMATION = 1 << 22, // animation; fetch as < AnimationList > + DECORATOR = 1 << 23, // decorator; fetch as < DecoratorsPtr > + FONTEFFECT = 1 << 24, // font-effect; fetch as < FontEffectsPtr > + RATIO = 1 << 25, // ratio defined as x/y; fetch as < Vector2f > LENGTH = PX | DP | PPI_UNIT | EM | REM | VW | VH | X, LENGTH_PERCENT = LENGTH | PERCENT, @@ -102,14 +99,15 @@ class RMLUICORE_API Property }; Property(); - template < typename PropertyType > + template Property(PropertyType value, Unit unit, int specificity = -1) : value(value), unit(unit), specificity(specificity) { definition = nullptr; parser_index = -1; } - template::value, EnumType >::type> - Property(EnumType value) : value(static_cast(value)), unit(KEYWORD), specificity(-1) {} + template ::value, EnumType>::type> + Property(EnumType value) : value(static_cast(value)), unit(KEYWORD), specificity(-1) + {} /// Get the value of the property as a string. String ToString() const; diff --git a/Include/RmlUi/Core/PropertyDefinition.h b/Include/RmlUi/Core/PropertyDefinition.h index 3bfb0e324..d5cb3c685 100644 --- a/Include/RmlUi/Core/PropertyDefinition.h +++ b/Include/RmlUi/Core/PropertyDefinition.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,12 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ enum class RelativeTarget { None, ContainingBlockWidth, ContainingBlockHeight, FontSize, ParentFontSize, LineHeight }; -class RMLUICORE_API PropertyDefinition final : public NonCopyMoveable -{ +class RMLUICORE_API PropertyDefinition final : public NonCopyMoveable { public: PropertyDefinition(PropertyId id, const String& default_value, bool inherited, bool forces_layout); ~PropertyDefinition(); @@ -89,13 +88,12 @@ class RMLUICORE_API PropertyDefinition final : public NonCopyMoveable bool inherited; bool forces_layout; - struct ParserState - { + struct ParserState { PropertyParser* parser; ParameterMap parameters; }; - Vector< ParserState > parsers; + Vector parsers; RelativeTarget relative_target; }; diff --git a/Include/RmlUi/Core/PropertyDictionary.h b/Include/RmlUi/Core/PropertyDictionary.h index 350c46df3..60dbe29bc 100644 --- a/Include/RmlUi/Core/PropertyDictionary.h +++ b/Include/RmlUi/Core/PropertyDictionary.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - A dictionary to property names to values. + A dictionary to property names to values. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API PropertyDictionary -{ +class RMLUICORE_API PropertyDictionary { public: PropertyDictionary(); @@ -62,7 +61,8 @@ class RMLUICORE_API PropertyDictionary /// overwrite the existing properties if their specificity (or their forced specificity) /// are at least equal. /// @param[in] property_dictionary The properties to import. - /// @param[in] specificity The specificity for all incoming properties. If this is not specified, the properties will keep their original specificity. + /// @param[in] specificity The specificity for all incoming properties. If this is not specified, the properties will keep their original + /// specificity. void Import(const PropertyDictionary& property_dictionary, int specificity = -1); /// Merges the contents of another fully-specified property dictionary with this one. diff --git a/Include/RmlUi/Core/PropertyIdSet.h b/Include/RmlUi/Core/PropertyIdSet.h index a33167c86..0ca6f5064 100644 --- a/Include/RmlUi/Core/PropertyIdSet.h +++ b/Include/RmlUi/Core/PropertyIdSet.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,21 +28,20 @@ #ifndef RMLUI_CORE_PROPERTYIDSET_H #define RMLUI_CORE_PROPERTYIDSET_H -#include "Types.h" #include "ID.h" +#include "Types.h" #include namespace Rml { class PropertyIdSetIterator; - /* - PropertyIdSet is a 'set'-like container for PropertyIds. - - Implemented as a wrapper around bitset. It is cheap to construct and use, requiring no dynamic allocation. + PropertyIdSet is a 'set'-like container for PropertyIds. - Supports union and intersection operations between two sets, as well as iteration through the IDs that are inserted. + Implemented as a wrapper around bitset. It is cheap to construct and use, requiring no dynamic allocation. + + Supports union and intersection operations between two sets, as well as iteration through the IDs that are inserted. */ class RMLUICORE_API PropertyIdSet { @@ -51,51 +50,47 @@ class RMLUICORE_API PropertyIdSet { std::bitset defined_ids; public: - PropertyIdSet() { - static_assert((size_t)PropertyId::Invalid == 0, "PropertyIdSet makes an assumption that PropertyId::Invalid is zero."); - } + PropertyIdSet() { static_assert((size_t)PropertyId::Invalid == 0, "PropertyIdSet makes an assumption that PropertyId::Invalid is zero."); } - void Insert(PropertyId id) { + void Insert(PropertyId id) + { RMLUI_ASSERT(size_t(id) < N); defined_ids.set((size_t)id); } - void Clear() { - defined_ids.reset(); - } - void Erase(PropertyId id) { + void Clear() { defined_ids.reset(); } + void Erase(PropertyId id) + { RMLUI_ASSERT(size_t(id) < N); defined_ids.reset((size_t)id); } - bool Empty() const { - return defined_ids.none(); - } - bool Contains(PropertyId id) const { - return defined_ids.test((size_t)id); - } + bool Empty() const { return defined_ids.none(); } + bool Contains(PropertyId id) const { return defined_ids.test((size_t)id); } - size_t Size() const { - return defined_ids.count(); - } + size_t Size() const { return defined_ids.count(); } // Union with another set - PropertyIdSet& operator|=(const PropertyIdSet& other) { + PropertyIdSet& operator|=(const PropertyIdSet& other) + { defined_ids |= other.defined_ids; return *this; } - PropertyIdSet operator|(const PropertyIdSet& other) const { + PropertyIdSet operator|(const PropertyIdSet& other) const + { PropertyIdSet result = *this; result |= other; return result; } // Intersection with another set - PropertyIdSet& operator&=(const PropertyIdSet& other) { + PropertyIdSet& operator&=(const PropertyIdSet& other) + { defined_ids &= other.defined_ids; return *this; } - PropertyIdSet operator&(const PropertyIdSet& other) const { + PropertyIdSet operator&(const PropertyIdSet& other) const + { PropertyIdSet result; result.defined_ids = (defined_ids & other.defined_ids); return result; @@ -111,40 +106,28 @@ class RMLUICORE_API PropertyIdSet { inline PropertyIdSetIterator Erase(PropertyIdSetIterator it); }; - - -class RMLUICORE_API PropertyIdSetIterator -{ +class RMLUICORE_API PropertyIdSetIterator { public: PropertyIdSetIterator() = default; - PropertyIdSetIterator(const PropertyIdSet* container, size_t id_index) : container(container), id_index(id_index) + PropertyIdSetIterator(const PropertyIdSet* container, size_t id_index) : container(container), id_index(id_index) { ProceedToNextValid(); } + + PropertyIdSetIterator& operator++() { - ProceedToNextValid(); - } - - PropertyIdSetIterator& operator++() { ++id_index; ProceedToNextValid(); return *this; } - bool operator==(const PropertyIdSetIterator& other) const { - return container == other.container && id_index == other.id_index; - } - bool operator!=(const PropertyIdSetIterator& other) const { - return !(*this == other); - } - PropertyId operator*() const { - return static_cast(id_index); - } + bool operator==(const PropertyIdSetIterator& other) const { return container == other.container && id_index == other.id_index; } + bool operator!=(const PropertyIdSetIterator& other) const { return !(*this == other); } + PropertyId operator*() const { return static_cast(id_index); } private: - inline void ProceedToNextValid() { for (; id_index < size_t(PropertyId::MaxNumIds); ++id_index) { - if (container->Contains( static_cast(id_index) )) + if (container->Contains(static_cast(id_index))) return; } } @@ -155,19 +138,20 @@ class RMLUICORE_API PropertyIdSetIterator friend PropertyIdSetIterator PropertyIdSet::Erase(PropertyIdSetIterator); }; - - -PropertyIdSetIterator PropertyIdSet::begin() const { +PropertyIdSetIterator PropertyIdSet::begin() const +{ if (Empty()) return end(); return PropertyIdSetIterator(this, 1); } -PropertyIdSetIterator PropertyIdSet::end() const { +PropertyIdSetIterator PropertyIdSet::end() const +{ return PropertyIdSetIterator(this, N); } -PropertyIdSetIterator PropertyIdSet::Erase(PropertyIdSetIterator it) { +PropertyIdSetIterator PropertyIdSet::Erase(PropertyIdSetIterator it) +{ RMLUI_ASSERT(it.container == this && it.id_index < N); defined_ids.reset(it.id_index); ++it; @@ -175,4 +159,4 @@ PropertyIdSetIterator PropertyIdSet::Erase(PropertyIdSetIterator it) { } } // namespace Rml -#endif \ No newline at end of file +#endif diff --git a/Include/RmlUi/Core/PropertyParser.h b/Include/RmlUi/Core/PropertyParser.h index d9e721e66..41bbdde3f 100644 --- a/Include/RmlUi/Core/PropertyParser.h +++ b/Include/RmlUi/Core/PropertyParser.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,16 +34,15 @@ namespace Rml { -using ParameterMap = UnorderedMap< String, int >; +using ParameterMap = UnorderedMap; /** - A property parser takes a property declaration in string form, validates it, and converts it to a Property. + A property parser takes a property declaration in string form, validates it, and converts it to a Property. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API PropertyParser -{ +class RMLUICORE_API PropertyParser { public: virtual ~PropertyParser() {} diff --git a/Include/RmlUi/Core/PropertySpecification.h b/Include/RmlUi/Core/PropertySpecification.h index 175967453..d0ef42cf0 100644 --- a/Include/RmlUi/Core/PropertySpecification.h +++ b/Include/RmlUi/Core/PropertySpecification.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,9 +30,9 @@ #define RMLUI_CORE_PROPERTYSPECIFICATION_H #include "Header.h" -#include "Types.h" -#include "PropertyIdSet.h" #include "ID.h" +#include "PropertyIdSet.h" +#include "Types.h" namespace Rml { @@ -43,8 +43,7 @@ class PropertyIdNameMap; class ShorthandIdNameMap; struct ShorthandDefinition; -enum class ShorthandType -{ +enum class ShorthandType { // Normal; properties that fail to parse fall-through to the next until they parse correctly, and any // undeclared are not set. FallThrough, @@ -60,15 +59,13 @@ enum class ShorthandType Flex }; - /** - A property specification stores a group of property definitions. + A property specification stores a group of property definitions. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API PropertySpecification -{ +class RMLUICORE_API PropertySpecification { public: PropertySpecification(size_t reserve_num_properties, size_t reserve_num_shorthands); ~PropertySpecification(); @@ -80,7 +77,8 @@ class RMLUICORE_API PropertySpecification /// @param[in] forces_layout True if this property requires its parent to be reformatted if changed. /// @param[in] id If 'Invalid' then automatically assigns a new id, otherwise assigns the given id. /// @return The new property definition, ready to have parsers attached. - PropertyDefinition& RegisterProperty(const String& property_name, const String& default_value, bool inherited, bool forces_layout, PropertyId id = PropertyId::Invalid); + PropertyDefinition& RegisterProperty(const String& property_name, const String& default_value, bool inherited, bool forces_layout, + PropertyId id = PropertyId::Invalid); /// Returns a property definition. /// @param[in] id The id of the desired property. /// @return The appropriate property definition if it could be found, nullptr otherwise. @@ -96,11 +94,13 @@ class RMLUICORE_API PropertySpecification /// Registers a shorthand property definition. /// @param[in] shorthand_name The name to register the new shorthand property under. - /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is the order in which the values will be processed. + /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is + /// the order in which the values will be processed. /// @param[in] type The type of shorthand to declare. /// @param[in] id If 'Invalid' then automatically assigns a new id, otherwise assigns the given id. /// @param True if all the property names exist, false otherwise. - ShorthandId RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type, ShorthandId id = ShorthandId::Invalid); + ShorthandId RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type, + ShorthandId id = ShorthandId::Invalid); /// Returns a shorthand definition. /// @param[in] shorthand_name The name of the desired shorthand. /// @return The appropriate shorthand definition if it could be found, nullptr otherwise. @@ -123,8 +123,8 @@ class RMLUICORE_API PropertySpecification String PropertiesToString(const PropertyDictionary& dictionary, bool include_name, char delimiter) const; private: - using Properties = Vector< UniquePtr >; - using Shorthands = Vector< UniquePtr >; + using Properties = Vector>; + using Shorthands = Vector>; Properties properties; Shorthands shorthands; diff --git a/Include/RmlUi/Core/Rectangle.h b/Include/RmlUi/Core/Rectangle.h index b0939868c..d6c0a1862 100644 --- a/Include/RmlUi/Core/Rectangle.h +++ b/Include/RmlUi/Core/Rectangle.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Include/RmlUi/Core/RenderInterface.h b/Include/RmlUi/Core/RenderInterface.h index 7718465fe..4c3b821f9 100644 --- a/Include/RmlUi/Core/RenderInterface.h +++ b/Include/RmlUi/Core/RenderInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,25 +29,24 @@ #ifndef RMLUI_CORE_RENDERINTERFACE_H #define RMLUI_CORE_RENDERINTERFACE_H -#include "Traits.h" #include "Header.h" #include "Texture.h" -#include "Vertex.h" +#include "Traits.h" #include "Types.h" +#include "Vertex.h" namespace Rml { class Context; /** - The abstract base class for application-specific rendering implementation. Your application must provide a concrete - implementation of this class and install it through Rml::SetRenderInterface() in order for anything to be rendered. + The abstract base class for application-specific rendering implementation. Your application must provide a concrete + implementation of this class and install it through Rml::SetRenderInterface() in order for anything to be rendered. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API RenderInterface : public NonCopyMoveable -{ +class RMLUICORE_API RenderInterface : public NonCopyMoveable { public: RenderInterface(); virtual ~RenderInterface(); @@ -60,7 +59,8 @@ class RMLUICORE_API RenderInterface : public NonCopyMoveable /// @param[in] num_indices The number of indices passed to the function. This will always be a multiple of three. /// @param[in] texture The texture to be applied to the geometry. This may be nullptr, in which case the geometry is untextured. /// @param[in] translation The translation to apply to the geometry. - virtual void RenderGeometry(Vertex* vertices, int num_vertices, int* indices, int num_indices, TextureHandle texture, const Vector2f& translation) = 0; + virtual void RenderGeometry(Vertex* vertices, int num_vertices, int* indices, int num_indices, TextureHandle texture, + const Vector2f& translation) = 0; /// Called by RmlUi when it wants to compile geometry it believes will be static for the forseeable future. /// If supported, this should return a handle to an optimised, application-specific version of the data. If @@ -70,7 +70,8 @@ class RMLUICORE_API RenderInterface : public NonCopyMoveable /// @param[in] indices The geometry's index data. /// @param[in] num_indices The number of indices passed to the function. This will always be a multiple of three. /// @param[in] texture The texture to be applied to the geometry. This may be nullptr, in which case the geometry is untextured. - /// @return The application-specific compiled geometry. Compiled geometry will be stored and rendered using RenderCompiledGeometry() in future calls, and released with ReleaseCompiledGeometry() when it is no longer needed. + /// @return The application-specific compiled geometry. Compiled geometry will be stored and rendered using RenderCompiledGeometry() in future + /// calls, and released with ReleaseCompiledGeometry() when it is no longer needed. virtual CompiledGeometryHandle CompileGeometry(Vertex* vertices, int num_vertices, int* indices, int num_indices, TextureHandle texture); /// Called by RmlUi when it wants to render application-compiled geometry. /// @param[in] geometry The application-specific compiled geometry to render. diff --git a/Include/RmlUi/Core/ScriptInterface.h b/Include/RmlUi/Core/ScriptInterface.h index 371ef6c89..fc7d37c8c 100644 --- a/Include/RmlUi/Core/ScriptInterface.h +++ b/Include/RmlUi/Core/ScriptInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,20 +36,17 @@ namespace Rml { /** - Base class for all objects that hold a scriptable object. - @author Peter Curry + Base class for all objects that hold a scriptable object. + @author Peter Curry */ class RMLUICORE_API ScriptInterface : public Releasable { public: RMLUI_RTTI_Define(ScriptInterface) - virtual ~ScriptInterface() { } + virtual ~ScriptInterface() {} - virtual ScriptObject GetScriptObject() const - { - return nullptr; - } + virtual ScriptObject GetScriptObject() const { return nullptr; } }; } // namespace Rml diff --git a/Include/RmlUi/Core/ScrollTypes.h b/Include/RmlUi/Core/ScrollTypes.h index c1dcdf1a8..7ce560768 100644 --- a/Include/RmlUi/Core/ScrollTypes.h +++ b/Include/RmlUi/Core/ScrollTypes.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Include/RmlUi/Core/Spritesheet.h b/Include/RmlUi/Core/Spritesheet.h index e651fc70a..8d705e2bd 100644 --- a/Include/RmlUi/Core/Spritesheet.h +++ b/Include/RmlUi/Core/Spritesheet.h @@ -3,7 +3,7 @@ * * For the latest information, see http://github.com/mikke89/RmlUi * - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -14,7 +14,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,8 +28,8 @@ #ifndef RMLUISPRITESHEET_H #define RMLUISPRITESHEET_H -#include "Types.h" #include "Texture.h" +#include "Types.h" namespace Rml { @@ -41,9 +41,8 @@ struct Sprite { }; using SpriteMap = UnorderedMap; // key: sprite name (as given in @spritesheet) - /** - Spritesheet holds a list of sprite names given in the @spritesheet at-rule in RCSS. + Spritesheet holds a list of sprite names given in the @spritesheet at-rule in RCSS. */ struct Spritesheet { String name; @@ -53,20 +52,20 @@ struct Spritesheet { float display_scale; // The inverse of the 'resolution' spritesheet property. Texture texture; - Spritesheet(const String& name, const String& image_source, const String& definition_source, - int definition_line_number, float display_scale, const Texture& texture); + Spritesheet(const String& name, const String& image_source, const String& definition_source, int definition_line_number, float display_scale, + const Texture& texture); }; using SpriteDefinitionList = Vector>; // Sprite name and rectangle - /** - SpritesheetList holds all the spritesheets and sprites given in a style sheet. + SpritesheetList holds all the spritesheets and sprites given in a style sheet. */ class SpritesheetList { public: /// Adds a new sprite sheet to the list and inserts all sprites with unique names into the global list. - bool AddSpriteSheet(const String& name, const String& image_source, const String& definition_source, int definition_line_number, float display_scale, const SpriteDefinitionList& sprite_definitions); + bool AddSpriteSheet(const String& name, const String& image_source, const String& definition_source, int definition_line_number, + float display_scale, const SpriteDefinitionList& sprite_definitions); /// Get a sprite from its name if it exists. /// Note: The pointer is invalidated whenever another sprite is added. Do not store it around. @@ -79,7 +78,6 @@ class SpritesheetList { size_t NumSpriteSheets() const; size_t NumSprites() const; - private: using Spritesheets = Vector>; @@ -87,6 +85,5 @@ class SpritesheetList { SpriteMap sprite_map; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Stream.h b/Include/RmlUi/Core/Stream.h index cef020e21..7af8fdb8d 100644 --- a/Include/RmlUi/Core/Stream.h +++ b/Include/RmlUi/Core/Stream.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,16 +39,14 @@ namespace Rml { class StreamListener; /** - Abstract class for a media-independent byte stream. - @author Lloyd Weehuizen + Abstract class for a media-independent byte stream. + @author Lloyd Weehuizen */ -class RMLUICORE_API Stream : public NonCopyMoveable -{ +class RMLUICORE_API Stream : public NonCopyMoveable { public: // Stream modes. - enum StreamMode - { + enum StreamMode { MODE_WRITE = 1 << 0, MODE_APPEND = 1 << 1, MODE_READ = 1 << 2, @@ -122,7 +120,7 @@ class RMLUICORE_API Stream : public NonCopyMoveable protected: /// Sets the mode on the stream; should be called by a stream when it is opened. - void SetStreamDetails(const URL& url, int stream_mode); + void SetStreamDetails(const URL& url, int stream_mode); private: URL url; diff --git a/Include/RmlUi/Core/StreamMemory.h b/Include/RmlUi/Core/StreamMemory.h index dd3b54902..579603e47 100644 --- a/Include/RmlUi/Core/StreamMemory.h +++ b/Include/RmlUi/Core/StreamMemory.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,12 +35,11 @@ namespace Rml { /** - Memory Byte Stream Class - @author Lloyd Weehuizen + Memory Byte Stream Class + @author Lloyd Weehuizen */ -class RMLUICORE_API StreamMemory final : public Stream -{ +class RMLUICORE_API StreamMemory final : public Stream { public: /// Empty memory stream with default size buffer StreamMemory(); @@ -51,7 +50,7 @@ class RMLUICORE_API StreamMemory final : public Stream virtual ~StreamMemory(); /// Close the stream - void Close() override; + void Close() override; /// Are we at the end of the stream bool IsEOS() const override; @@ -70,7 +69,7 @@ class RMLUICORE_API StreamMemory final : public Stream size_t Read(void* buffer, size_t bytes) const override; /// Peek into the stream - size_t Peek(void *buffer, size_t bytes) const override; + size_t Peek(void* buffer, size_t bytes) const override; /// Write to the stream using Stream::Write; @@ -102,13 +101,12 @@ class RMLUICORE_API StreamMemory final : public Stream void SetSourceURL(const URL& url); private: - byte* buffer; mutable byte* buffer_ptr; size_t buffer_size; size_t buffer_used; bool owns_buffer; - + bool Reallocate(size_t size); }; diff --git a/Include/RmlUi/Core/StringUtilities.h b/Include/RmlUi/Core/StringUtilities.h index 6fb5c5815..70f6305b3 100644 --- a/Include/RmlUi/Core/StringUtilities.h +++ b/Include/RmlUi/Core/StringUtilities.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,21 +35,19 @@ namespace Rml { /** - Helper functions for string manipulation. - @author Lloyd Weehuizen + Helper functions for string manipulation. + @author Lloyd Weehuizen */ class StringView; /// Construct a string using sprintf-style syntax. -RMLUICORE_API String CreateString(size_t max_size, const char* format, ...) RMLUI_ATTRIBUTE_FORMAT_PRINTF(2,3); +RMLUICORE_API String CreateString(size_t max_size, const char* format, ...) RMLUI_ATTRIBUTE_FORMAT_PRINTF(2, 3); /// Format to a string using sprintf-style syntax. -RMLUICORE_API int FormatString(String& string, size_t max_size, const char* format, ...) RMLUI_ATTRIBUTE_FORMAT_PRINTF(3,4); - +RMLUICORE_API int FormatString(String& string, size_t max_size, const char* format, ...) RMLUI_ATTRIBUTE_FORMAT_PRINTF(3, 4); -namespace StringUtilities -{ +namespace StringUtilities { /// Expands character-delimited list of values in a single string to a whitespace-trimmed list /// of values. /// @param[out] string_list Resulting list of values. @@ -63,7 +61,8 @@ namespace StringUtilities /// @param[in] quote_character Begin quote /// @param[in] unquote_character End quote /// @param[in] ignore_repeated_delimiters If true, repeated values of the delimiter will not add additional entries to the list. - RMLUICORE_API void ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, bool ignore_repeated_delimiters = false); + RMLUICORE_API void ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, + bool ignore_repeated_delimiters = false); /// Joins a list of string values into a single string separated by a character delimiter. /// @param[out] string Resulting concatenated string. /// @param[in] string_list Input list of string values. @@ -134,13 +133,12 @@ namespace StringUtilities --p; return p; } -} - +} // namespace StringUtilities /* - A poor man's string view. - - The string view is agnostic to the underlying encoding, any operation will strictly operate on bytes. + A poor man's string view. + + The string view is agnostic to the underlying encoding, any operation will strictly operate on bytes. */ class RMLUICORE_API StringView { @@ -167,21 +165,18 @@ class RMLUICORE_API StringView { inline size_t size() const { return size_t(p_end - p_begin); } - explicit inline operator String() const { - return String(p_begin, p_end); - } + explicit inline operator String() const { return String(p_begin, p_end); } private: const char* p_begin; const char* p_end; }; - /* - An iterator for UTF-8 strings. + An iterator for UTF-8 strings. - The increment and decrement operations will move to the beginning of the next or the previous - UTF-8 character, respectively. The dereference operator will resolve the current code point. + The increment and decrement operations will move to the beginning of the next or the previous + UTF-8 character, respectively. The dereference operator will resolve the current code point. */ @@ -221,8 +216,5 @@ class RMLUICORE_API StringIteratorU8 { inline void SeekBack(); }; - - - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/StyleSheet.h b/Include/RmlUi/Core/StyleSheet.h index daf04e091..6525bd016 100644 --- a/Include/RmlUi/Core/StyleSheet.h +++ b/Include/RmlUi/Core/StyleSheet.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -49,14 +49,13 @@ struct Sprite; using DecoratorPtrList = Vector>; /** - StyleSheet maintains a single stylesheet definition. A stylesheet can be combined with another stylesheet to create - a new, merged stylesheet. + StyleSheet maintains a single stylesheet definition. A stylesheet can be combined with another stylesheet to create + a new, merged stylesheet. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API StyleSheet final : public NonCopyMoveable -{ +class RMLUICORE_API StyleSheet final : public NonCopyMoveable { public: ~StyleSheet(); @@ -72,11 +71,13 @@ class RMLUICORE_API StyleSheet final : public NonCopyMoveable const DecoratorSpecification* GetDecoratorSpecification(const String& name) const; /// Returns the Keyframes of the given name, or null if it does not exist. - /// @lifetime The returned pointer becomes invalidated whenever the style sheet is re-generated. Do not store this pointer or references to subobjects around. + /// @lifetime The returned pointer becomes invalidated whenever the style sheet is re-generated. Do not store this pointer or references to + /// subobjects around. const Keyframes* GetKeyframes(const String& name) const; /// Get sprite located in any spritesheet within this stylesheet. - /// @lifetime The returned pointer becomes invalidated whenever the style sheet is re-generated. Do not store this pointer or references to subobjects around. + /// @lifetime The returned pointer becomes invalidated whenever the style sheet is re-generated. Do not store this pointer or references to + /// subobjects around. const Sprite* GetSprite(const String& name) const; /// Returns the compiled element definition for a given element and its hierarchy. diff --git a/Include/RmlUi/Core/StyleSheetContainer.h b/Include/RmlUi/Core/StyleSheetContainer.h index 20155a49c..a47734f22 100644 --- a/Include/RmlUi/Core/StyleSheetContainer.h +++ b/Include/RmlUi/Core/StyleSheetContainer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_STYLESHEETCONTAINER_H #define RMLUI_CORE_STYLESHEETCONTAINER_H -#include "Traits.h" #include "StyleSheetTypes.h" +#include "Traits.h" namespace Rml { @@ -38,14 +38,13 @@ class Stream; class StyleSheet; /** - StyleSheetContainer contains a list of media blocks and creates a combined style sheet when getting - properties of the current context regarding the available media features. + StyleSheetContainer contains a list of media blocks and creates a combined style sheet when getting + properties of the current context regarding the available media features. - @author Maximilian Stark + @author Maximilian Stark */ -class RMLUICORE_API StyleSheetContainer : public NonCopyMoveable -{ +class RMLUICORE_API StyleSheetContainer : public NonCopyMoveable { public: StyleSheetContainer(); virtual ~StyleSheetContainer(); @@ -59,7 +58,7 @@ class RMLUICORE_API StyleSheetContainer : public NonCopyMoveable /// @warning This operation invalidates all references to the previously compiled style sheet. bool UpdateCompiledStyleSheet(const Context* context); - /// Returns the previously compiled style sheet. + /// Returns the previously compiled style sheet. StyleSheet* GetCompiledStyleSheet(); /// Combines this style sheet container with another one, producing a new sheet container. diff --git a/Include/RmlUi/Core/StyleSheetSpecification.h b/Include/RmlUi/Core/StyleSheetSpecification.h index 543624bf2..a948d55a0 100644 --- a/Include/RmlUi/Core/StyleSheetSpecification.h +++ b/Include/RmlUi/Core/StyleSheetSpecification.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,11 +39,10 @@ class PropertyParser; struct DefaultStyleSheetParsers; /** - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API StyleSheetSpecification -{ +class RMLUICORE_API StyleSheetSpecification { public: /// Starts up the specification structure and registers default properties and type parsers. /// @return True if the specification started up successfully, false if not. @@ -84,7 +83,8 @@ class RMLUICORE_API StyleSheetSpecification /// Registers a custom shorthand property definition. /// @param[in] shorthand_name The name to register the new shorthand property under. - /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is the order in which the values will be processed. + /// @param[in] properties A comma-separated list of the properties this definition is shorthand for. The order in which they are specified here is + /// the order in which the values will be processed. /// @param[in] type The type of shorthand to declare. /// @param True if all the property names exist, false otherwise. static ShorthandId RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type); @@ -98,7 +98,8 @@ class RMLUICORE_API StyleSheetSpecification /// @param[in] dictionary The property dictionary which will hold all declared properties. /// @param[in] property_name The name of the declared property. /// @param[in] property_value The values the property is being set to. - /// @param[in] source_file The file where this property was declared. Used for error reporting, debugging and relative paths for referenced assets. + /// @param[in] source_file The file where this property was declared. Used for error reporting, debugging and relative paths for referenced + /// assets. /// @param[in] line_number The location of the source file where this property was declared. Used for error reporting and debugging. /// @return True if all properties were parsed successfully, false otherwise. static bool ParsePropertyDeclaration(PropertyDictionary& dictionary, const String& property_name, const String& property_value); @@ -117,7 +118,8 @@ class RMLUICORE_API StyleSheetSpecification StyleSheetSpecification(); ~StyleSheetSpecification(); - PropertyDefinition& RegisterProperty(PropertyId id, const String& property_name, const String& default_value, bool inherited, bool forces_layout = false); + PropertyDefinition& RegisterProperty(PropertyId id, const String& property_name, const String& default_value, bool inherited, + bool forces_layout = false); ShorthandId RegisterShorthand(ShorthandId id, const String& shorthand_name, const String& property_names, ShorthandType type); // Registers RmlUi's default parsers. @@ -126,7 +128,7 @@ class RMLUICORE_API StyleSheetSpecification void RegisterDefaultProperties(); // Parsers used by all property definitions. - typedef UnorderedMap< String, PropertyParser* > ParserMap; + typedef UnorderedMap ParserMap; ParserMap parsers; // The properties defined in the style sheet specification. diff --git a/Include/RmlUi/Core/StyleSheetTypes.h b/Include/RmlUi/Core/StyleSheetTypes.h index e3701056d..3145c7c67 100644 --- a/Include/RmlUi/Core/StyleSheetTypes.h +++ b/Include/RmlUi/Core/StyleSheetTypes.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_STYLESHEETTYPES_H #define RMLUI_CORE_STYLESHEETTYPES_H -#include "PropertyDictionary.h" #include "Factory.h" +#include "PropertyDictionary.h" #include "Types.h" #include "Utilities.h" @@ -66,8 +66,13 @@ struct DecoratorDeclaration { }; struct DecoratorDeclarationView { - DecoratorDeclarationView(const DecoratorDeclaration& declaration) : type(declaration.type), instancer(declaration.instancer), properties(declaration.properties) {} - DecoratorDeclarationView(const DecoratorSpecification* specification) : type(specification->decorator_type), instancer(Factory::GetDecoratorInstancer(specification->decorator_type)), properties(specification->properties) {} + DecoratorDeclarationView(const DecoratorDeclaration& declaration) : + type(declaration.type), instancer(declaration.instancer), properties(declaration.properties) + {} + DecoratorDeclarationView(const DecoratorSpecification* specification) : + type(specification->decorator_type), instancer(Factory::GetDecoratorInstancer(specification->decorator_type)), + properties(specification->properties) + {} const String& type; DecoratorInstancer* instancer; diff --git a/Include/RmlUi/Core/StyleTypes.h b/Include/RmlUi/Core/StyleTypes.h index d8f0013de..9b0b31895 100644 --- a/Include/RmlUi/Core/StyleTypes.h +++ b/Include/RmlUi/Core/StyleTypes.h @@ -3,7 +3,7 @@ * * For the latest information, see http://github.com/mikke89/RmlUi * - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Include/RmlUi/Core/SystemInterface.h b/Include/RmlUi/Core/SystemInterface.h index 06f7dc702..1e94ee6d5 100644 --- a/Include/RmlUi/Core/SystemInterface.h +++ b/Include/RmlUi/Core/SystemInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,30 +29,29 @@ #ifndef RMLUI_CORE_SYSTEMINTERFACE_H #define RMLUI_CORE_SYSTEMINTERFACE_H -#include "Types.h" +#include "Header.h" #include "Log.h" #include "Traits.h" -#include "Header.h" +#include "Types.h" namespace Rml { /** - RmlUi's System Interface. + RmlUi's System Interface. - This class provides interfaces for Time, Translation and Logging. + This class provides interfaces for Time, Translation and Logging. - Time is the only required implementation. + Time is the only required implementation. - The default implemention of Translation doesn't translate anything + The default implemention of Translation doesn't translate anything - The default implementation of logging logs Windows Debug Console, - or Standard Error, depending on what platform you're using. + The default implementation of logging logs Windows Debug Console, + or Standard Error, depending on what platform you're using. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API SystemInterface : public NonCopyMoveable -{ +class RMLUICORE_API SystemInterface : public NonCopyMoveable { public: SystemInterface(); virtual ~SystemInterface(); @@ -95,7 +94,7 @@ class RMLUICORE_API SystemInterface : public NonCopyMoveable /// @param[in] caret_position Position of the caret in absolute window coordinates. /// @param[in] line_height Height of the current line being edited. virtual void ActivateKeyboard(Rml::Vector2f caret_position, float line_height); - + /// Deactivate keyboard (for touchscreen devices). virtual void DeactivateKeyboard(); }; diff --git a/Include/RmlUi/Core/Texture.h b/Include/RmlUi/Core/Texture.h index fd7b0cd7d..730c592ec 100644 --- a/Include/RmlUi/Core/Texture.h +++ b/Include/RmlUi/Core/Texture.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,24 +38,22 @@ class TextureResource; class RenderInterface; /* - Callback function for generating textures. - /// @param[in] render_interface The render interface to use for generating the texture. - /// @param[in] name The name used to set the texture. - /// @param[out] handle The texture handle obtained through the render interface. - /// @param[out] dimensions The width and height of the generated texture. - /// @return True on success. + Callback function for generating textures. + /// @param[in] render_interface The render interface to use for generating the texture. + /// @param[in] name The name used to set the texture. + /// @param[out] handle The texture handle obtained through the render interface. + /// @param[out] dimensions The width and height of the generated texture. + /// @return True on success. */ using TextureCallback = Function; - /** - Abstraction of a two-dimensional texture image, with an application-specific texture handle. + Abstraction of a two-dimensional texture image, with an application-specific texture handle. - @author Peter Curry + @author Peter Curry */ -struct RMLUICORE_API Texture -{ +struct RMLUICORE_API Texture { public: /// Set the texture source and path. The texture is added to the global cache and only loaded on first use. /// @param[in] source The source of the texture. diff --git a/Include/RmlUi/Core/Traits.h b/Include/RmlUi/Core/Traits.h index 1c936b654..2558a7daf 100644 --- a/Include/RmlUi/Core/Traits.h +++ b/Include/RmlUi/Core/Traits.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_TRAITS_H #define RMLUI_CORE_TRAITS_H -#include "Header.h" #include "../Config/Config.h" +#include "Header.h" #include namespace Rml { @@ -45,7 +45,6 @@ class RMLUICORE_API NonCopyMoveable { NonCopyMoveable& operator=(NonCopyMoveable&&) = delete; }; - class ReleaserBase; class RMLUICORE_API Releasable : public NonCopyMoveable { @@ -57,37 +56,37 @@ class RMLUICORE_API Releasable : public NonCopyMoveable { class RMLUICORE_API ReleaserBase { protected: - void Release(Releasable* target) const { - target->Release(); - } + void Release(Releasable* target) const { target->Release(); } }; -template +template class RMLUICORE_API Releaser : public ReleaserBase { public: - void operator()(T* target) const { + void operator()(T* target) const + { static_assert(std::is_base_of::value, "Rml::Releaser can only operate with classes derived from ::Rml::Releasable."); Release(static_cast(target)); } }; - enum class FamilyId : int {}; class RMLUICORE_API FamilyBase { protected: - static int GetNewId() { + static int GetNewId() + { static int id = 0; return id++; } }; -template +template class Family : FamilyBase { public: // Get a unique ID for a given type. // Note: IDs will be unique across DLL-boundaries even for the same type. - static FamilyId Id() { + static FamilyId Id() + { static int id = GetNewId(); return static_cast(id); } @@ -95,24 +94,35 @@ class Family : FamilyBase { } // namespace Rml - - #ifdef RMLUI_USE_CUSTOM_RTTI -#define RMLUI_RTTI_Define( _NAME_ ) \ - using RttiClassType = _NAME_; \ - static void* GetStaticClassIdentifier() { static int dummy; return &dummy; } \ - virtual bool IsClass(void * type_identifier) const { return type_identifier == GetStaticClassIdentifier(); } - -#define RMLUI_RTTI_DefineWithParent( _NAME_, _PARENT_ ) \ - using RttiClassType = _NAME_; \ - static void* GetStaticClassIdentifier() { static int dummy; return &dummy; } \ - bool IsClass(void * type_identifier) const override { \ - static_assert(std::is_same::value, "Parent does not implement RMLUI_RTTI_Define or RMLUI_RTTI_DefineWithParent");\ - return type_identifier == GetStaticClassIdentifier() || _PARENT_::IsClass(type_identifier);\ - } - -template + #define RMLUI_RTTI_Define(_NAME_) \ + using RttiClassType = _NAME_; \ + static void* GetStaticClassIdentifier() \ + { \ + static int dummy; \ + return &dummy; \ + } \ + virtual bool IsClass(void* type_identifier) const \ + { \ + return type_identifier == GetStaticClassIdentifier(); \ + } + + #define RMLUI_RTTI_DefineWithParent(_NAME_, _PARENT_) \ + using RttiClassType = _NAME_; \ + static void* GetStaticClassIdentifier() \ + { \ + static int dummy; \ + return &dummy; \ + } \ + bool IsClass(void* type_identifier) const override \ + { \ + static_assert(std::is_same::value, \ + "Parent does not implement RMLUI_RTTI_Define or RMLUI_RTTI_DefineWithParent"); \ + return type_identifier == GetStaticClassIdentifier() || _PARENT_::IsClass(type_identifier); \ + } + +template Derived rmlui_dynamic_cast(Base base_instance) { static_assert(std::is_pointer::value && std::is_pointer::value, "rmlui_dynamic_cast can only cast pointer types"); @@ -126,13 +136,13 @@ Derived rmlui_dynamic_cast(Base base_instance) return nullptr; } -template +template const char* rmlui_type_name(const T& /*var*/) { return "(type name unavailable)"; } -template +template const char* rmlui_type_name() { return "(type name unavailable)"; @@ -140,30 +150,30 @@ const char* rmlui_type_name() #else -#include + #include -#define RMLUI_RTTI_Define(_NAME_) -#define RMLUI_RTTI_DefineWithParent(_NAME_, _PARENT_) + #define RMLUI_RTTI_Define(_NAME_) + #define RMLUI_RTTI_DefineWithParent(_NAME_, _PARENT_) -template +template Derived rmlui_dynamic_cast(Base base_instance) { static_assert(std::is_pointer::value && std::is_pointer::value, "rmlui_dynamic_cast can only cast pointer types"); return dynamic_cast(base_instance); } -template +template const char* rmlui_type_name(const T& var) { return typeid(var).name(); } -template +template const char* rmlui_type_name() { return typeid(T).name(); } -#endif // RMLUI_USE_CUSTOM_RTTI +#endif // RMLUI_USE_CUSTOM_RTTI -#endif // RMLUI_CORE_TRAITS_H +#endif // RMLUI_CORE_TRAITS_H diff --git a/Include/RmlUi/Core/Transform.h b/Include/RmlUi/Core/Transform.h index b2f3a9c0f..718e53135 100644 --- a/Include/RmlUi/Core/Transform.h +++ b/Include/RmlUi/Core/Transform.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,29 +30,28 @@ #define RMLUI_CORE_TRANSFORM_H #include "Header.h" -#include "Types.h" #include "TransformPrimitive.h" +#include "Types.h" namespace Rml { class Property; /** - The Transform class holds the information parsed from an element's `transform' property. - - The class holds a list of transform primitives making up a complete transformation specification - of an element. Each transform instance is relative to the element's parent coordinate system. - During the Context::Render call the transforms of the current element and its ancestors will be - used to find the final transformation matrix for the global coordinate system. - - @author Markus Schöngart - @see Rml::Variant + The Transform class holds the information parsed from an element's `transform' property. + + The class holds a list of transform primitives making up a complete transformation specification + of an element. Each transform instance is relative to the element's parent coordinate system. + During the Context::Render call the transforms of the current element and its ancestors will be + used to find the final transformation matrix for the global coordinate system. + + @author Markus Schöngart + @see Rml::Variant */ -class RMLUICORE_API Transform -{ +class RMLUICORE_API Transform { public: - using PrimitiveList = Vector< TransformPrimitive >; + using PrimitiveList = Vector; /// Default constructor, initializes an identity transform Transform(); @@ -82,7 +81,5 @@ class RMLUICORE_API Transform PrimitiveList primitives; }; - - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/TransformPrimitive.h b/Include/RmlUi/Core/TransformPrimitive.h index c594a4cea..de261f187 100644 --- a/Include/RmlUi/Core/TransformPrimitive.h +++ b/Include/RmlUi/Core/TransformPrimitive.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,224 +30,214 @@ #define RMLUI_CORE_TRANSFORMPRIMITIVE_H #include "Header.h" -#include "Types.h" #include "Property.h" +#include "Types.h" namespace Rml { namespace Transforms { -struct RMLUICORE_API NumericValue { - NumericValue() noexcept : number(0.f), unit(Property::UNKNOWN) {} - NumericValue(float number, Property::Unit unit) noexcept : number(number), unit(unit) {} + struct RMLUICORE_API NumericValue { + NumericValue() noexcept : number(0.f), unit(Property::UNKNOWN) {} + NumericValue(float number, Property::Unit unit) noexcept : number(number), unit(unit) {} - float number; - Property::Unit unit; -}; + float number; + Property::Unit unit; + }; -// A resolved primitive has values that are always independent of an element's properties or layout. -template< size_t N > -struct RMLUICORE_API ResolvedPrimitive -{ - Array values; - -protected: - ResolvedPrimitive(const float* values) noexcept; - ResolvedPrimitive(const NumericValue* values) noexcept; - ResolvedPrimitive(const NumericValue* values, Array base_units) noexcept; - ResolvedPrimitive(Array values, Array base_units) noexcept; - ResolvedPrimitive(Array values) noexcept; -}; + // A resolved primitive has values that are always independent of an element's properties or layout. + template + struct RMLUICORE_API ResolvedPrimitive { + Array values; + + protected: + ResolvedPrimitive(const float* values) noexcept; + ResolvedPrimitive(const NumericValue* values) noexcept; + ResolvedPrimitive(const NumericValue* values, Array base_units) noexcept; + ResolvedPrimitive(Array values, Array base_units) noexcept; + ResolvedPrimitive(Array values) noexcept; + }; -// An unresolved primitive may have values that depend on the final layout of a given element, such as its width. -template< size_t N > -struct RMLUICORE_API UnresolvedPrimitive -{ - Array values; - -protected: - UnresolvedPrimitive(const NumericValue* values) noexcept; - UnresolvedPrimitive(Array values) noexcept; -}; + // An unresolved primitive may have values that depend on the final layout of a given element, such as its width. + template + struct RMLUICORE_API UnresolvedPrimitive { + Array values; + protected: + UnresolvedPrimitive(const NumericValue* values) noexcept; + UnresolvedPrimitive(Array values) noexcept; + }; -struct RMLUICORE_API Matrix2D : public ResolvedPrimitive< 6 > -{ - Matrix2D(const NumericValue* values) noexcept; -}; + struct RMLUICORE_API Matrix2D : public ResolvedPrimitive<6> { + Matrix2D(const NumericValue* values) noexcept; + }; -struct RMLUICORE_API Matrix3D : public ResolvedPrimitive< 16 > -{ - Matrix3D(const NumericValue* values) noexcept; - Matrix3D(const Matrix4f& matrix) noexcept; -}; + struct RMLUICORE_API Matrix3D : public ResolvedPrimitive<16> { + Matrix3D(const NumericValue* values) noexcept; + Matrix3D(const Matrix4f& matrix) noexcept; + }; -struct RMLUICORE_API TranslateX : public UnresolvedPrimitive< 1 > -{ - TranslateX(const NumericValue* values) noexcept; - TranslateX(float x, Property::Unit unit = Property::PX) noexcept; -}; + struct RMLUICORE_API TranslateX : public UnresolvedPrimitive<1> { + TranslateX(const NumericValue* values) noexcept; + TranslateX(float x, Property::Unit unit = Property::PX) noexcept; + }; -struct RMLUICORE_API TranslateY : public UnresolvedPrimitive< 1 > -{ - TranslateY(const NumericValue* values) noexcept; - TranslateY(float y, Property::Unit unit = Property::PX) noexcept; -}; + struct RMLUICORE_API TranslateY : public UnresolvedPrimitive<1> { + TranslateY(const NumericValue* values) noexcept; + TranslateY(float y, Property::Unit unit = Property::PX) noexcept; + }; -struct RMLUICORE_API TranslateZ : public UnresolvedPrimitive< 1 > -{ - TranslateZ(const NumericValue* values) noexcept; - TranslateZ(float z, Property::Unit unit = Property::PX) noexcept; -}; + struct RMLUICORE_API TranslateZ : public UnresolvedPrimitive<1> { + TranslateZ(const NumericValue* values) noexcept; + TranslateZ(float z, Property::Unit unit = Property::PX) noexcept; + }; -struct RMLUICORE_API Translate2D : public UnresolvedPrimitive< 2 > -{ - Translate2D(const NumericValue* values) noexcept; - Translate2D(float x, float y, Property::Unit units = Property::PX) noexcept; -}; + struct RMLUICORE_API Translate2D : public UnresolvedPrimitive<2> { + Translate2D(const NumericValue* values) noexcept; + Translate2D(float x, float y, Property::Unit units = Property::PX) noexcept; + }; -struct RMLUICORE_API Translate3D : public UnresolvedPrimitive< 3 > -{ - Translate3D(const NumericValue* values) noexcept; - Translate3D(NumericValue x, NumericValue y, NumericValue z) noexcept; - Translate3D(float x, float y, float z, Property::Unit units = Property::PX) noexcept; -}; + struct RMLUICORE_API Translate3D : public UnresolvedPrimitive<3> { + Translate3D(const NumericValue* values) noexcept; + Translate3D(NumericValue x, NumericValue y, NumericValue z) noexcept; + Translate3D(float x, float y, float z, Property::Unit units = Property::PX) noexcept; + }; -struct RMLUICORE_API ScaleX : public ResolvedPrimitive< 1 > -{ - ScaleX(const NumericValue* values) noexcept; - ScaleX(float value) noexcept; -}; + struct RMLUICORE_API ScaleX : public ResolvedPrimitive<1> { + ScaleX(const NumericValue* values) noexcept; + ScaleX(float value) noexcept; + }; -struct RMLUICORE_API ScaleY : public ResolvedPrimitive< 1 > -{ - ScaleY(const NumericValue* values) noexcept; - ScaleY(float value) noexcept; -}; + struct RMLUICORE_API ScaleY : public ResolvedPrimitive<1> { + ScaleY(const NumericValue* values) noexcept; + ScaleY(float value) noexcept; + }; -struct RMLUICORE_API ScaleZ : public ResolvedPrimitive< 1 > -{ - ScaleZ(const NumericValue* values) noexcept; - ScaleZ(float value) noexcept; -}; + struct RMLUICORE_API ScaleZ : public ResolvedPrimitive<1> { + ScaleZ(const NumericValue* values) noexcept; + ScaleZ(float value) noexcept; + }; -struct RMLUICORE_API Scale2D : public ResolvedPrimitive< 2 > -{ - Scale2D(const NumericValue* values) noexcept; - Scale2D(float xy) noexcept; - Scale2D(float x, float y) noexcept; -}; + struct RMLUICORE_API Scale2D : public ResolvedPrimitive<2> { + Scale2D(const NumericValue* values) noexcept; + Scale2D(float xy) noexcept; + Scale2D(float x, float y) noexcept; + }; -struct RMLUICORE_API Scale3D : public ResolvedPrimitive< 3 > -{ - Scale3D(const NumericValue* values) noexcept; - Scale3D(float xyz) noexcept; - Scale3D(float x, float y, float z) noexcept; -}; + struct RMLUICORE_API Scale3D : public ResolvedPrimitive<3> { + Scale3D(const NumericValue* values) noexcept; + Scale3D(float xyz) noexcept; + Scale3D(float x, float y, float z) noexcept; + }; -struct RMLUICORE_API RotateX : public ResolvedPrimitive< 1 > -{ - RotateX(const NumericValue* values) noexcept; - RotateX(float angle, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API RotateX : public ResolvedPrimitive<1> { + RotateX(const NumericValue* values) noexcept; + RotateX(float angle, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API RotateY : public ResolvedPrimitive< 1 > -{ - RotateY(const NumericValue* values) noexcept; - RotateY(float angle, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API RotateY : public ResolvedPrimitive<1> { + RotateY(const NumericValue* values) noexcept; + RotateY(float angle, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API RotateZ : public ResolvedPrimitive< 1 > -{ - RotateZ(const NumericValue* values) noexcept; - RotateZ(float angle, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API RotateZ : public ResolvedPrimitive<1> { + RotateZ(const NumericValue* values) noexcept; + RotateZ(float angle, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API Rotate2D : public ResolvedPrimitive< 1 > -{ - Rotate2D(const NumericValue* values) noexcept; - Rotate2D(float angle, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API Rotate2D : public ResolvedPrimitive<1> { + Rotate2D(const NumericValue* values) noexcept; + Rotate2D(float angle, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API Rotate3D : public ResolvedPrimitive< 4 > -{ - Rotate3D(const NumericValue* values) noexcept; - Rotate3D(float x, float y, float z, float angle, Property::Unit angle_unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API Rotate3D : public ResolvedPrimitive<4> { + Rotate3D(const NumericValue* values) noexcept; + Rotate3D(float x, float y, float z, float angle, Property::Unit angle_unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API SkewX : public ResolvedPrimitive< 1 > -{ - SkewX(const NumericValue* values) noexcept; - SkewX(float angle, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API SkewX : public ResolvedPrimitive<1> { + SkewX(const NumericValue* values) noexcept; + SkewX(float angle, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API SkewY : public ResolvedPrimitive< 1 > -{ - SkewY(const NumericValue* values) noexcept; - SkewY(float angle, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API SkewY : public ResolvedPrimitive<1> { + SkewY(const NumericValue* values) noexcept; + SkewY(float angle, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API Skew2D : public ResolvedPrimitive< 2 > -{ - Skew2D(const NumericValue* values) noexcept; - Skew2D(float x, float y, Property::Unit unit = Property::DEG) noexcept; -}; + struct RMLUICORE_API Skew2D : public ResolvedPrimitive<2> { + Skew2D(const NumericValue* values) noexcept; + Skew2D(float x, float y, Property::Unit unit = Property::DEG) noexcept; + }; -struct RMLUICORE_API Perspective : public UnresolvedPrimitive< 1 > -{ - Perspective(const NumericValue* values) noexcept; -}; + struct RMLUICORE_API Perspective : public UnresolvedPrimitive<1> { + Perspective(const NumericValue* values) noexcept; + }; -struct RMLUICORE_API DecomposedMatrix4 { - Vector4f perspective; - Vector4f quaternion; - Vector3f translation; - Vector3f scale; - Vector3f skew; -}; + struct RMLUICORE_API DecomposedMatrix4 { + Vector4f perspective; + Vector4f quaternion; + Vector3f translation; + Vector3f scale; + Vector3f skew; + }; } // namespace Transforms - /** - The TransformPrimitive struct is the base struct of geometric transforms such as rotations, scalings and translations. - Instances of this struct are added to Rml::Transform during parsing of the 'transform' property. + The TransformPrimitive struct is the base struct of geometric transforms such as rotations, scalings and translations. + Instances of this struct are added to Rml::Transform during parsing of the 'transform' property. - @author Markus Schöngart - @see Rml::Transform - @see Rml::PropertyParserTransform + @author Markus Schöngart + @see Rml::Transform + @see Rml::PropertyParserTransform */ struct RMLUICORE_API TransformPrimitive { - enum Type { - MATRIX2D, MATRIX3D, - TRANSLATEX, TRANSLATEY, TRANSLATEZ, TRANSLATE2D, TRANSLATE3D, - SCALEX, SCALEY, SCALEZ, SCALE2D, SCALE3D, - ROTATEX, ROTATEY, ROTATEZ, ROTATE2D, ROTATE3D, - SKEWX, SKEWY, SKEW2D, - PERSPECTIVE, DECOMPOSEDMATRIX4 + MATRIX2D, + MATRIX3D, + TRANSLATEX, + TRANSLATEY, + TRANSLATEZ, + TRANSLATE2D, + TRANSLATE3D, + SCALEX, + SCALEY, + SCALEZ, + SCALE2D, + SCALE3D, + ROTATEX, + ROTATEY, + ROTATEZ, + ROTATE2D, + ROTATE3D, + SKEWX, + SKEWY, + SKEW2D, + PERSPECTIVE, + DECOMPOSEDMATRIX4 }; - TransformPrimitive(Transforms::Matrix2D p) : type(MATRIX2D) { matrix_2d = p; } - TransformPrimitive(Transforms::Matrix3D p) : type(MATRIX3D) { matrix_3d = p; } - TransformPrimitive(Transforms::TranslateX p) : type(TRANSLATEX) { translate_x = p; } - TransformPrimitive(Transforms::TranslateY p) : type(TRANSLATEY) { translate_y = p; } - TransformPrimitive(Transforms::TranslateZ p) : type(TRANSLATEZ) { translate_z = p; } - TransformPrimitive(Transforms::Translate2D p) : type(TRANSLATE2D) { translate_2d = p; } - TransformPrimitive(Transforms::Translate3D p) : type(TRANSLATE3D) { translate_3d = p; } - TransformPrimitive(Transforms::ScaleX p) : type(SCALEX) { scale_x = p; } - TransformPrimitive(Transforms::ScaleY p) : type(SCALEY) { scale_y = p; } - TransformPrimitive(Transforms::ScaleZ p) : type(SCALEZ) { scale_z = p; } - TransformPrimitive(Transforms::Scale2D p) : type(SCALE2D) { scale_2d = p; } - TransformPrimitive(Transforms::Scale3D p) : type(SCALE3D) { scale_3d = p; } - TransformPrimitive(Transforms::RotateX p) : type(ROTATEX) { rotate_x = p; } - TransformPrimitive(Transforms::RotateY p) : type(ROTATEY) { rotate_y = p; } - TransformPrimitive(Transforms::RotateZ p) : type(ROTATEZ) { rotate_z = p; } - TransformPrimitive(Transforms::Rotate2D p) : type(ROTATE2D) { rotate_2d = p; } - TransformPrimitive(Transforms::Rotate3D p) : type(ROTATE3D) { rotate_3d = p; } - TransformPrimitive(Transforms::SkewX p) : type(SKEWX) { skew_x = p; } - TransformPrimitive(Transforms::SkewY p) : type(SKEWY) { skew_y = p; } - TransformPrimitive(Transforms::Skew2D p) : type(SKEW2D) { skew_2d = p; } - TransformPrimitive(Transforms::Perspective p) : type(PERSPECTIVE) { perspective = p; } + TransformPrimitive(Transforms::Matrix2D p) : type(MATRIX2D) { matrix_2d = p; } + TransformPrimitive(Transforms::Matrix3D p) : type(MATRIX3D) { matrix_3d = p; } + TransformPrimitive(Transforms::TranslateX p) : type(TRANSLATEX) { translate_x = p; } + TransformPrimitive(Transforms::TranslateY p) : type(TRANSLATEY) { translate_y = p; } + TransformPrimitive(Transforms::TranslateZ p) : type(TRANSLATEZ) { translate_z = p; } + TransformPrimitive(Transforms::Translate2D p) : type(TRANSLATE2D) { translate_2d = p; } + TransformPrimitive(Transforms::Translate3D p) : type(TRANSLATE3D) { translate_3d = p; } + TransformPrimitive(Transforms::ScaleX p) : type(SCALEX) { scale_x = p; } + TransformPrimitive(Transforms::ScaleY p) : type(SCALEY) { scale_y = p; } + TransformPrimitive(Transforms::ScaleZ p) : type(SCALEZ) { scale_z = p; } + TransformPrimitive(Transforms::Scale2D p) : type(SCALE2D) { scale_2d = p; } + TransformPrimitive(Transforms::Scale3D p) : type(SCALE3D) { scale_3d = p; } + TransformPrimitive(Transforms::RotateX p) : type(ROTATEX) { rotate_x = p; } + TransformPrimitive(Transforms::RotateY p) : type(ROTATEY) { rotate_y = p; } + TransformPrimitive(Transforms::RotateZ p) : type(ROTATEZ) { rotate_z = p; } + TransformPrimitive(Transforms::Rotate2D p) : type(ROTATE2D) { rotate_2d = p; } + TransformPrimitive(Transforms::Rotate3D p) : type(ROTATE3D) { rotate_3d = p; } + TransformPrimitive(Transforms::SkewX p) : type(SKEWX) { skew_x = p; } + TransformPrimitive(Transforms::SkewY p) : type(SKEWY) { skew_y = p; } + TransformPrimitive(Transforms::Skew2D p) : type(SKEW2D) { skew_2d = p; } + TransformPrimitive(Transforms::Perspective p) : type(PERSPECTIVE) { perspective = p; } TransformPrimitive(Transforms::DecomposedMatrix4 p) : type(DECOMPOSEDMATRIX4) { decomposed_matrix_4 = p; } Type type; @@ -278,6 +268,5 @@ struct RMLUICORE_API TransformPrimitive { }; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Tween.h b/Include/RmlUi/Core/Tween.h index 087c37ba1..6d4731dda 100644 --- a/Include/RmlUi/Core/Tween.h +++ b/Include/RmlUi/Core/Tween.h @@ -3,7 +3,7 @@ * * For the latest information, see http://github.com/mikke89/RmlUi * - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,12 +24,12 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_CORE_TWEEN_H #define RMLUI_CORE_TWEEN_H -#include "Types.h" #include "Header.h" +#include "Types.h" namespace Rml { @@ -37,7 +37,7 @@ class RMLUICORE_API Tween { public: enum Type { None, Back, Bounce, Circular, Cubic, Elastic, Exponential, Linear, Quadratic, Quartic, Quintic, Sine, Callback, Count }; enum Direction { In = 1, Out = 2, InOut = 3 }; - using CallbackFnc = float(*)(float); + using CallbackFnc = float (*)(float); Tween(Type type = Linear, Direction direction = Out); Tween(Type type_in, Type type_out); @@ -50,7 +50,7 @@ class RMLUICORE_API Tween { void reverse(); bool operator==(const Tween& other) const; - bool operator!=(const Tween& other) const; + bool operator!=(const Tween& other) const; String to_string() const; @@ -65,6 +65,5 @@ class RMLUICORE_API Tween { CallbackFnc callback = nullptr; }; - } // namespace Rml #endif diff --git a/Include/RmlUi/Core/TypeConverter.h b/Include/RmlUi/Core/TypeConverter.h index 24f82356a..6792aaad6 100644 --- a/Include/RmlUi/Core/TypeConverter.h +++ b/Include/RmlUi/Core/TypeConverter.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,90 +29,100 @@ #ifndef RMLUI_CORE_TYPECONVERTER_H #define RMLUI_CORE_TYPECONVERTER_H -#include "Platform.h" -#include "Types.h" #include "Log.h" +#include "Platform.h" #include "StringUtilities.h" -#include +#include "Types.h" #include +#include namespace Rml { /** - Templatised TypeConverters with Template Specialisation. + Templatised TypeConverters with Template Specialisation. - These converters convert from source types to destination types. - They're mainly useful in things like dictionaries and serialisers. + These converters convert from source types to destination types. + They're mainly useful in things like dictionaries and serialisers. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ template -class TypeConverter -{ +class TypeConverter { public: static bool Convert(const SourceType& src, DestType& dest); }; -template -inline String ToString(const T& value, String default_value = String()) { +template +inline String ToString(const T& value, String default_value = String()) +{ String result = default_value; TypeConverter::Convert(value, result); return result; } -template -inline T FromString(const String& string, T default_value = T()) { +template +inline T FromString(const String& string, T default_value = T()) +{ T result = default_value; TypeConverter::Convert(string, result); return result; } - // Some more complex types are defined in cpp-file -template<> class TypeConverter< TransformPtr, TransformPtr > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const TransformPtr& src, TransformPtr& dest); }; -template<> class TypeConverter< TransformPtr, String > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const TransformPtr& src, String& dest); }; -template<> class TypeConverter< TransitionList, TransitionList > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const TransitionList& src, TransitionList& dest); }; -template<> class TypeConverter< TransitionList, String > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const TransitionList& src, String& dest); }; -template<> class TypeConverter< AnimationList, AnimationList > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const AnimationList& src, AnimationList& dest); }; -template<> class TypeConverter< AnimationList, String > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const AnimationList& src, String& dest); }; -template<> class TypeConverter< DecoratorsPtr, DecoratorsPtr > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const DecoratorsPtr& src, DecoratorsPtr& dest); }; -template<> class TypeConverter< DecoratorsPtr, String > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const DecoratorsPtr& src, String& dest); }; -template<> class TypeConverter< FontEffectsPtr, FontEffectsPtr> { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const FontEffectsPtr& src, FontEffectsPtr& dest); }; -template<> class TypeConverter< FontEffectsPtr, String > { +template <> +class TypeConverter { public: RMLUICORE_API static bool Convert(const FontEffectsPtr& src, String& dest); }; diff --git a/Include/RmlUi/Core/TypeConverter.inl b/Include/RmlUi/Core/TypeConverter.inl index 7c791c594..53349265c 100644 --- a/Include/RmlUi/Core/TypeConverter.inl +++ b/Include/RmlUi/Core/TypeConverter.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,44 +36,42 @@ bool TypeConverter::Convert(const SourceType& /*src*/, Des } #if defined(RMLUI_PLATFORM_WIN32) && defined(__MINGW32__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wformat" -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wformat-extra-args" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wformat" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wformat-extra-args" #endif /// /// Full Specialisations /// -#define BASIC_CONVERTER(s, d) \ -template<> \ -class TypeConverter< s, d > \ -{ \ -public: \ - static bool Convert(const s& src, d& dest) \ - { \ - dest = (d)src; \ - return true; \ - } \ -} +#define BASIC_CONVERTER(s, d) \ + template <> \ + class TypeConverter { \ + public: \ + static bool Convert(const s& src, d& dest) \ + { \ + dest = (d)src; \ + return true; \ + } \ + } -#define BASIC_CONVERTER_BOOL(s, d) \ -template<> \ -class TypeConverter< s, d > \ -{ \ -public: \ - static bool Convert(const s& src, d& dest) \ - { \ - dest = src != 0; \ - return true; \ - } \ -} +#define BASIC_CONVERTER_BOOL(s, d) \ + template <> \ + class TypeConverter { \ + public: \ + static bool Convert(const s& src, d& dest) \ + { \ + dest = src != 0; \ + return true; \ + } \ + } -#define PASS_THROUGH(t) BASIC_CONVERTER(t, t) +#define PASS_THROUGH(t) BASIC_CONVERTER(t, t) ///////////////////////////////////////////////// -// Simple pass through definitions for converting +// Simple pass through definitions for converting // to the same type (direct copy) ///////////////////////////////////////////////// PASS_THROUGH(int); @@ -194,17 +192,16 @@ BASIC_CONVERTER(char, Character); // From string converters ///////////////////////////////////////////////// -#define STRING_FLOAT_CONVERTER(type) \ -template<> \ -class TypeConverter< String, type > \ -{ \ -public: \ - static bool Convert(const String& src, type& dest) \ - { \ - dest = (type) atof(src.c_str()); \ - return true; \ - } \ -} +#define STRING_FLOAT_CONVERTER(type) \ + template <> \ + class TypeConverter { \ + public: \ + static bool Convert(const String& src, type& dest) \ + { \ + dest = (type)atof(src.c_str()); \ + return true; \ + } \ + } STRING_FLOAT_CONVERTER(float); STRING_FLOAT_CONVERTER(double); @@ -270,9 +267,8 @@ public: } }; -template< typename DestType, typename InternalType, int count > -class TypeConverterStringVector -{ +template +class TypeConverterStringVector { public: static bool Convert(const String& src, DestType& dest) { @@ -282,23 +278,22 @@ public: return false; for (int i = 0; i < count; i++) { - if (!TypeConverter< String, InternalType >::Convert(string_list[i], dest[i])) + if (!TypeConverter::Convert(string_list[i], dest[i])) return false; } return true; } }; -#define STRING_VECTOR_CONVERTER(type, internal_type, count) \ -template<> \ -class TypeConverter< String, type > \ -{ \ -public: \ - static bool Convert(const String& src, type& dest) \ - { \ - return TypeConverterStringVector< type, internal_type, count >::Convert(src, dest); \ - } \ -} +#define STRING_VECTOR_CONVERTER(type, internal_type, count) \ + template <> \ + class TypeConverter { \ + public: \ + static bool Convert(const String& src, type& dest) \ + { \ + return TypeConverterStringVector::Convert(src, dest); \ + } \ + } STRING_VECTOR_CONVERTER(Vector2i, int, 2); STRING_VECTOR_CONVERTER(Vector2f, float, 2); @@ -313,19 +308,18 @@ STRING_VECTOR_CONVERTER(Colourb, byte, 4); // To String Converters ///////////////////////////////////////////////// -#define FLOAT_STRING_CONVERTER(type) \ -template<> \ -class TypeConverter< type, String > \ -{ \ -public: \ - static bool Convert(const type& src, String& dest) \ - { \ - if(FormatString(dest, 32, "%.3f", src) == 0) \ - return false; \ - StringUtilities::TrimTrailingDotZeros(dest); \ - return true; \ - } \ -} +#define FLOAT_STRING_CONVERTER(type) \ + template <> \ + class TypeConverter { \ + public: \ + static bool Convert(const type& src, String& dest) \ + { \ + if (FormatString(dest, 32, "%.3f", src) == 0) \ + return false; \ + StringUtilities::TrimTrailingDotZeros(dest); \ + return true; \ + } \ + } FLOAT_STRING_CONVERTER(float); FLOAT_STRING_CONVERTER(double); @@ -391,9 +385,8 @@ public: } }; -template< typename SourceType, typename InternalType, int count > -class TypeConverterVectorString -{ +template +class TypeConverterVectorString { public: static bool Convert(const SourceType& src, String& dest) { @@ -401,9 +394,9 @@ public: for (int i = 0; i < count; i++) { String value; - if (!TypeConverter< InternalType, String >::Convert(src[i], value)) + if (!TypeConverter::Convert(src[i], value)) return false; - + dest += value; if (i < count - 1) dest += ", "; @@ -412,16 +405,15 @@ public: } }; -#define VECTOR_STRING_CONVERTER(type, internal_type, count) \ -template<> \ -class TypeConverter< type, String > \ -{ \ -public: \ - static bool Convert(const type& src, String& dest) \ - { \ - return TypeConverterVectorString< type, internal_type, count >::Convert(src, dest); \ - } \ -} +#define VECTOR_STRING_CONVERTER(type, internal_type, count) \ + template <> \ + class TypeConverter { \ + public: \ + static bool Convert(const type& src, String& dest) \ + { \ + return TypeConverterVectorString::Convert(src, dest); \ + } \ + } VECTOR_STRING_CONVERTER(Vector2i, int, 2); VECTOR_STRING_CONVERTER(Vector2f, float, 2); @@ -440,8 +432,8 @@ VECTOR_STRING_CONVERTER(Colourb, byte, 4); #undef VECTOR_STRING_CONVERTER #if defined(RMLUI_PLATFORM_WIN32) && defined(__MINGW32__) -#pragma GCC diagnostic pop -#pragma GCC diagnostic pop + #pragma GCC diagnostic pop + #pragma GCC diagnostic pop #endif } // namespace Rml diff --git a/Include/RmlUi/Core/Types.h b/Include/RmlUi/Core/Types.h index 2724b279e..c9176598c 100644 --- a/Include/RmlUi/Core/Types.h +++ b/Include/RmlUi/Core/Types.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,12 +30,10 @@ #define RMLUI_CORE_TYPES_H #include "../Config/Config.h" - +#include "Traits.h" #include #include -#include "Traits.h" - namespace Rml { // Commonly used basic types @@ -46,32 +44,32 @@ using std::size_t; // Unicode code point enum class Character : char32_t { Null, Replacement = 0xfffd }; -} +} // namespace Rml #include "Colour.h" +#include "Matrix4.h" +#include "ObserverPtr.h" +#include "Rectangle.h" #include "Vector2.h" #include "Vector3.h" #include "Vector4.h" -#include "Rectangle.h" -#include "Matrix4.h" -#include "ObserverPtr.h" namespace Rml { // Color and linear algebra enum class ColorFormat { RGBA8, A8 }; -using Colourf = Colour< float, 1 >; -using Colourb = Colour< byte, 255 >; -using Vector2i = Vector2< int >; -using Vector2f = Vector2< float >; -using Vector3i = Vector3< int >; -using Vector3f = Vector3< float >; -using Vector4i = Vector4< int >; -using Vector4f = Vector4< float >; -using Rectanglei = Rectangle< int >; -using Rectanglef = Rectangle< float >; -using ColumnMajorMatrix4f = Matrix4< float, ColumnMajorStorage< float > >; -using RowMajorMatrix4f = Matrix4< float, RowMajorStorage< float > >; +using Colourf = Colour; +using Colourb = Colour; +using Vector2i = Vector2; +using Vector2f = Vector2; +using Vector3i = Vector3; +using Vector3f = Vector3; +using Vector4i = Vector4; +using Vector4f = Vector4; +using Rectanglei = Rectangle; +using Rectanglef = Rectangle; +using ColumnMajorMatrix4f = Matrix4>; +using RowMajorMatrix4f = Matrix4>; using Matrix4f = RMLUI_MATRIX4_TYPE; // Common classes @@ -108,15 +106,15 @@ using ContextPtr = UniqueReleaserPtr; using EventPtr = UniqueReleaserPtr; // Container types for common classes -using ElementList = Vector< Element* >; -using OwnedElementList = Vector< ElementPtr >; -using VariantList = Vector< Variant >; -using ElementAnimationList = Vector< ElementAnimation >; +using ElementList = Vector; +using OwnedElementList = Vector; +using VariantList = Vector; +using ElementAnimationList = Vector; -using AttributeNameList = SmallUnorderedSet< String >; -using PropertyMap = UnorderedMap< PropertyId, Property >; +using AttributeNameList = SmallUnorderedSet; +using PropertyMap = UnorderedMap; -using Dictionary = SmallUnorderedMap< String, Variant >; +using Dictionary = SmallUnorderedMap; using ElementAttributes = Dictionary; using XMLAttributes = Dictionary; @@ -128,7 +126,7 @@ struct FontEffects { }; // Additional smart pointers -using TransformPtr = SharedPtr< Transform >; +using TransformPtr = SharedPtr; using DecoratorsPtr = SharedPtr; using FontEffectsPtr = SharedPtr; @@ -140,21 +138,35 @@ using DataControllerPtr = UniqueReleaserPtr; } // namespace Rml - namespace std { // Hash specialization for enum class types (required on some older compilers) -template <> struct hash<::Rml::PropertyId> { +template <> +struct hash<::Rml::PropertyId> { using utype = ::std::underlying_type_t<::Rml::PropertyId>; - size_t operator() (const ::Rml::PropertyId& t) const noexcept { ::std::hash h; return h(static_cast(t)); } + size_t operator()(const ::Rml::PropertyId& t) const noexcept + { + ::std::hash h; + return h(static_cast(t)); + } }; -template <> struct hash<::Rml::Character> { +template <> +struct hash<::Rml::Character> { using utype = ::std::underlying_type_t<::Rml::Character>; - size_t operator() (const ::Rml::Character& t) const noexcept { ::std::hash h; return h(static_cast(t)); } + size_t operator()(const ::Rml::Character& t) const noexcept + { + ::std::hash h; + return h(static_cast(t)); + } }; -template <> struct hash<::Rml::FamilyId> { +template <> +struct hash<::Rml::FamilyId> { using utype = ::std::underlying_type_t<::Rml::FamilyId>; - size_t operator() (const ::Rml::FamilyId& t) const noexcept { ::std::hash h; return h(static_cast(t)); } + size_t operator()(const ::Rml::FamilyId& t) const noexcept + { + ::std::hash h; + return h(static_cast(t)); + } }; -} +} // namespace std #endif diff --git a/Include/RmlUi/Core/URL.h b/Include/RmlUi/Core/URL.h index fa49a6aa6..422bb602e 100644 --- a/Include/RmlUi/Core/URL.h +++ b/Include/RmlUi/Core/URL.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,11 +35,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API URL -{ +class RMLUICORE_API URL { public: /// Constructs an empty URL. URL(); @@ -63,12 +62,12 @@ class RMLUICORE_API URL const String& GetProtocol() const; /// Sets the URL's login - bool SetLogin( const String& login ); + bool SetLogin(const String& login); /// Returns the URL's login const String& GetLogin() const; /// Sets the URL's password - bool SetPassword( const String& password ); + bool SetPassword(const String& password); /// Returns the URL's password const String& GetPassword() const; @@ -98,26 +97,26 @@ class RMLUICORE_API URL bool SetExtension(const String& extension); /// Returns the URL's file extension. const String& GetExtension() const; - + /// Access the url parameters - typedef UnorderedMap< String, String > Parameters; + typedef UnorderedMap Parameters; const Parameters& GetParameters() const; void SetParameter(const String& name, const String& value); - void SetParameters( const Parameters& parameters ); + void SetParameters(const Parameters& parameters); void ClearParameters(); - + /// Returns the URL's path, file name and extension. String GetPathedFileName() const; - /// Builds and returns a url query string ( key=value&key2=value2 ) + /// Builds and returns a url query string ( key=value&key2=value2 ) String GetQueryString() const; /// Less-than operator for use as a key in STL containers. bool operator<(const URL& rhs) const; - /// Since URLs often contain characters outside the ASCII set, + /// Since URLs often contain characters outside the ASCII set, /// the URL has to be converted into a valid ASCII format and back. - static String UrlEncode(const String &value); - static String UrlDecode(const String &value); + static String UrlEncode(const String& value); + static String UrlDecode(const String& value); private: void ConstructURL() const; @@ -132,7 +131,7 @@ class RMLUICORE_API URL String protocol; String login; String password; - String host; + String host; String path; String file_name; String extension; diff --git a/Include/RmlUi/Core/Utilities.h b/Include/RmlUi/Core/Utilities.h index fcfd6d053..a419e747f 100644 --- a/Include/RmlUi/Core/Utilities.h +++ b/Include/RmlUi/Core/Utilities.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,13 @@ namespace Rml { namespace Utilities { -template -inline void HashCombine(std::size_t& seed, const T& v) -{ - Hash hasher; - seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); -} + template + inline void HashCombine(std::size_t& seed, const T& v) + { + Hash hasher; + seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + } -} +} // namespace Utilities } // namespace Rml #endif diff --git a/Include/RmlUi/Core/Variant.h b/Include/RmlUi/Core/Variant.h index d243a10d8..3481c077b 100644 --- a/Include/RmlUi/Core/Variant.h +++ b/Include/RmlUi/Core/Variant.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,28 +29,26 @@ #ifndef RMLUIVARIANT_H #define RMLUIVARIANT_H +#include "Animation.h" #include "Header.h" -#include "Types.h" #include "TypeConverter.h" -#include "Animation.h" +#include "Types.h" namespace Rml { /** - Variant is a container that can store a selection of basic types. The variant will store the - value in the native form corresponding to the version of Set that was called. + Variant is a container that can store a selection of basic types. The variant will store the + value in the native form corresponding to the version of Set that was called. - Get is templated to convert from the stored form to the requested form by using a TypeConverter. + Get is templated to convert from the stored form to the requested form by using a TypeConverter. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API Variant -{ +class RMLUICORE_API Variant { public: /// Type of data stored in the variant. We use size_t as base to avoid 'padding due to alignment specifier' warning. - enum Type : size_t - { + enum Type : size_t { NONE = '-', BOOL = 'B', BYTE = 'b', @@ -99,26 +97,25 @@ class RMLUICORE_API Variant /// internal representation to the requested representation. /// @param[in] default_value The value returned if the conversion failed. /// @return Data in the requested type. - template< typename T > + template T Get(T default_value = T()) const; /// Templatised data accessor. TypeConverters will be used to attempt to convert from the /// internal representation to the requested representation. /// @param[out] value Data in the requested type. /// @return True if the value was converted and returned, false if no data was stored in the variant. - template< typename T > + template bool GetInto(T& value) const; /// Returns a reference to the variant's underlying type. /// @warning: Undefined behavior if T does not represent the underlying type of the variant. - template< typename T> + template const T& GetReference() const; bool operator==(const Variant& other) const; bool operator!=(const Variant& other) const { return !(*this == other); } private: - /// Copy another variant's data to this variant. /// @warning Does not clear existing data. void Set(const Variant& copy); @@ -154,7 +151,7 @@ class RMLUICORE_API Variant void Set(DecoratorsPtr&& value); void Set(const FontEffectsPtr& value); void Set(FontEffectsPtr&& value); - + static constexpr size_t LOCAL_DATA_SIZE = (sizeof(TransitionList) > sizeof(String) ? sizeof(TransitionList) : sizeof(String)); Type type = NONE; diff --git a/Include/RmlUi/Core/Variant.inl b/Include/RmlUi/Core/Variant.inl index eb1a6e968..bb168f38f 100644 --- a/Include/RmlUi/Core/Variant.inl +++ b/Include/RmlUi/Core/Variant.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -48,7 +48,7 @@ Variant& Variant::operator=(T&& t) } // Templatised data accessor. -template< typename T > +template bool Variant::GetInto(T& value) const { switch (type) @@ -81,14 +81,14 @@ bool Variant::GetInto(T& value) const return false; } -template< typename T > +template T Variant::Get(T default_value) const { GetInto(default_value); return default_value; } -template +template const T& Variant::GetReference() const { return *reinterpret_cast(&data); diff --git a/Include/RmlUi/Core/Vector2.h b/Include/RmlUi/Core/Vector2.h index bdcc07f0e..e727b6498 100644 --- a/Include/RmlUi/Core/Vector2.h +++ b/Include/RmlUi/Core/Vector2.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,125 +35,124 @@ namespace Rml { /** - Templated class for a generic two-component vector. - @author Peter Curry + Templated class for a generic two-component vector. + @author Peter Curry */ -template < typename Type > -class Vector2 -{ - public: - /// Default constructor. - inline Vector2(); - /// Initialising constructor. - /// @param[in] v Initial value of each element in the vector. - explicit inline Vector2(Type v); - /// Initialising constructor. - /// @param[in] x Initial x-value of the vector. - /// @param[in] y Initial y-value of the vector. - inline Vector2(Type x, Type y); - - /// Returns the magnitude of the vector. - /// @return The computed magnitude. - inline float Magnitude() const; - /// Returns the squared magnitude of the vector. - /// @return The computed squared magnitude. - inline Type SquaredMagnitude() const; - /// Generates a normalised vector from this vector. - /// @return The normalised vector. - inline Vector2 Normalise() const; - /// Generates a vector with values rounded to their nearest integer. - /// @return The rounded vector - inline Vector2 Round() const; - - /// Computes the dot-product between this vector and another. - /// @param[in] rhs The other vector to use in the dot-product. - /// @return The computed dot-product between the two vectors. - inline Type DotProduct(Vector2 rhs) const; - - /// Returns this vector rotated around the origin. - /// @param[in] theta The angle to rotate by, in radians. - /// @return The rotated vector. - inline Vector2 Rotate(float theta) const; - - /// Returns the negation of this vector. - /// @return The negation of this vector. - inline Vector2 operator-() const; - - /// Returns the sum of this vector and another. - /// @param[in] rhs The vector to add this to. - /// @return The sum of the two vectors. - inline Vector2 operator+(Vector2 rhs) const; - /// Returns the result of subtracting another vector from this vector. - /// @param[in] rhs The vector to subtract from this vector. - /// @return The result of the subtraction. - inline Vector2 operator-(Vector2 rhs) const; - /// Returns the result of multiplying this vector by a scalar. - /// @param[in] rhs The scalar value to multiply by. - /// @return The result of the scale. - inline Vector2 operator*(Type rhs) const; - /// Returns the result of element-wise multiplication. - /// @param[in] rhs The vector to multiply by. - /// @return The result of the multiplication. - inline Vector2 operator*(Vector2 rhs) const; - /// Returns the result of dividing this vector by a scalar. - /// @param[in] rhs The scalar value to divide by. - /// @return The result of the scale. - inline Vector2 operator/(Type rhs) const; - /// Returns the result of element-wise division. - /// @param[in] rhs The vector to divide by. - /// @return The result of the division. - inline Vector2 operator/(Vector2 rhs) const; - - /// Adds another vector to this in-place. - /// @param[in] rhs The vector to add. - /// @return This vector, post-operation. - inline Vector2& operator+=(Vector2 rhs); - /// Subtracts another vector from this in-place. - /// @param[in] rhs The vector to subtract. - /// @return This vector, post-operation. - inline Vector2& operator-=(Vector2 rhs); - /// Scales this vector in-place. - /// @param[in] rhs The value to scale this vector's components by. - /// @return This vector, post-operation. - inline Vector2& operator*=(Type rhs); - /// Element-wise multiplication in-place. - /// @param[in] rhs The vector to multiply. - /// @return This vector, post-operation. - inline Vector2& operator*=(Vector2 rhs); - /// Scales this vector in-place by the inverse of a value. - /// @param[in] rhs The value to divide this vector's components by. - /// @return This vector, post-operation. - inline Vector2& operator/=(Type rhs); - /// Element-wise division in-place. - /// @param[in] rhs The vector to divide by. - /// @return This vector, post-operation. - inline Vector2& operator/=(Vector2 rhs); - - /// Equality operator. - /// @param[in] rhs The vector to compare this against. - /// @return True if the two vectors are equal, false otherwise. - inline bool operator==(Vector2 rhs) const; - /// Inequality operator. - /// @param[in] rhs The vector to compare this against. - /// @return True if the two vectors are not equal, false otherwise. - inline bool operator!=(Vector2 rhs) const; - - /// Auto-cast operator. - /// @return A pointer to the first value. - inline operator const Type*() const; - /// Constant auto-cast operator. - /// @return A constant pointer to the first value. - inline operator Type*(); - - /// Underlying type-cast operator. - /// @return A copy of the vector with another underlying type. - template < typename U > - explicit inline operator Vector2() const; - - // The components of the vector. - Type x; - Type y; +template +class Vector2 { +public: + /// Default constructor. + inline Vector2(); + /// Initialising constructor. + /// @param[in] v Initial value of each element in the vector. + explicit inline Vector2(Type v); + /// Initialising constructor. + /// @param[in] x Initial x-value of the vector. + /// @param[in] y Initial y-value of the vector. + inline Vector2(Type x, Type y); + + /// Returns the magnitude of the vector. + /// @return The computed magnitude. + inline float Magnitude() const; + /// Returns the squared magnitude of the vector. + /// @return The computed squared magnitude. + inline Type SquaredMagnitude() const; + /// Generates a normalised vector from this vector. + /// @return The normalised vector. + inline Vector2 Normalise() const; + /// Generates a vector with values rounded to their nearest integer. + /// @return The rounded vector + inline Vector2 Round() const; + + /// Computes the dot-product between this vector and another. + /// @param[in] rhs The other vector to use in the dot-product. + /// @return The computed dot-product between the two vectors. + inline Type DotProduct(Vector2 rhs) const; + + /// Returns this vector rotated around the origin. + /// @param[in] theta The angle to rotate by, in radians. + /// @return The rotated vector. + inline Vector2 Rotate(float theta) const; + + /// Returns the negation of this vector. + /// @return The negation of this vector. + inline Vector2 operator-() const; + + /// Returns the sum of this vector and another. + /// @param[in] rhs The vector to add this to. + /// @return The sum of the two vectors. + inline Vector2 operator+(Vector2 rhs) const; + /// Returns the result of subtracting another vector from this vector. + /// @param[in] rhs The vector to subtract from this vector. + /// @return The result of the subtraction. + inline Vector2 operator-(Vector2 rhs) const; + /// Returns the result of multiplying this vector by a scalar. + /// @param[in] rhs The scalar value to multiply by. + /// @return The result of the scale. + inline Vector2 operator*(Type rhs) const; + /// Returns the result of element-wise multiplication. + /// @param[in] rhs The vector to multiply by. + /// @return The result of the multiplication. + inline Vector2 operator*(Vector2 rhs) const; + /// Returns the result of dividing this vector by a scalar. + /// @param[in] rhs The scalar value to divide by. + /// @return The result of the scale. + inline Vector2 operator/(Type rhs) const; + /// Returns the result of element-wise division. + /// @param[in] rhs The vector to divide by. + /// @return The result of the division. + inline Vector2 operator/(Vector2 rhs) const; + + /// Adds another vector to this in-place. + /// @param[in] rhs The vector to add. + /// @return This vector, post-operation. + inline Vector2& operator+=(Vector2 rhs); + /// Subtracts another vector from this in-place. + /// @param[in] rhs The vector to subtract. + /// @return This vector, post-operation. + inline Vector2& operator-=(Vector2 rhs); + /// Scales this vector in-place. + /// @param[in] rhs The value to scale this vector's components by. + /// @return This vector, post-operation. + inline Vector2& operator*=(Type rhs); + /// Element-wise multiplication in-place. + /// @param[in] rhs The vector to multiply. + /// @return This vector, post-operation. + inline Vector2& operator*=(Vector2 rhs); + /// Scales this vector in-place by the inverse of a value. + /// @param[in] rhs The value to divide this vector's components by. + /// @return This vector, post-operation. + inline Vector2& operator/=(Type rhs); + /// Element-wise division in-place. + /// @param[in] rhs The vector to divide by. + /// @return This vector, post-operation. + inline Vector2& operator/=(Vector2 rhs); + + /// Equality operator. + /// @param[in] rhs The vector to compare this against. + /// @return True if the two vectors are equal, false otherwise. + inline bool operator==(Vector2 rhs) const; + /// Inequality operator. + /// @param[in] rhs The vector to compare this against. + /// @return True if the two vectors are not equal, false otherwise. + inline bool operator!=(Vector2 rhs) const; + + /// Auto-cast operator. + /// @return A pointer to the first value. + inline operator const Type*() const; + /// Constant auto-cast operator. + /// @return A constant pointer to the first value. + inline operator Type*(); + + /// Underlying type-cast operator. + /// @return A copy of the vector with another underlying type. + template + explicit inline operator Vector2() const; + + // The components of the vector. + Type x; + Type y; #if defined(RMLUI_VECTOR2_USER_EXTRA) RMLUI_VECTOR2_USER_EXTRA diff --git a/Include/RmlUi/Core/Vector2.inl b/Include/RmlUi/Core/Vector2.inl index e6b50a051..1c9f67fd5 100644 --- a/Include/RmlUi/Core/Vector2.inl +++ b/Include/RmlUi/Core/Vector2.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,20 +34,18 @@ Vector2::Vector2() : x{}, y{} {} // Initialising constructor. -template < typename Type > -Vector2< Type >::Vector2(Type v) : x(v), y(v) -{ -} +template +Vector2::Vector2(Type v) : x(v), y(v) +{} // Initialising constructor. -template < typename Type > -Vector2< Type >::Vector2(Type x, Type y) : x(x), y(y) -{ -} +template +Vector2::Vector2(Type x, Type y) : x(x), y(y) +{} // Returns the magnitude of the vector. -template < typename Type > -float Vector2< Type >::Magnitude() const +template +float Vector2::Magnitude() const { float squared_magnitude = (float)SquaredMagnitude(); if (Math::IsZero(squared_magnitude)) @@ -57,23 +55,22 @@ float Vector2< Type >::Magnitude() const } // Returns the squared magnitude of the vector. -template < typename Type > -Type Vector2< Type >::SquaredMagnitude() const +template +Type Vector2::SquaredMagnitude() const { - return x * x + - y * y; + return x * x + y * y; } // Generates a normalised vector from this vector. -template < typename Type > -inline Vector2< Type > Vector2< Type >::Normalise() const +template +inline Vector2 Vector2::Normalise() const { static_assert(std::is_same::value, "Normalise only implemented for Vector."); return *this; } -template < > -inline Vector2< float > Vector2< float >::Normalise() const +template <> +inline Vector2 Vector2::Normalise() const { float magnitude = Magnitude(); if (Math::IsZero(magnitude)) @@ -83,91 +80,89 @@ inline Vector2< float > Vector2< float >::Normalise() const } // Generates a rounded vector from this vector. -template < > -inline Vector2< float > Vector2< float >::Round() const +template <> +inline Vector2 Vector2::Round() const { - Vector2 < float > result; + Vector2 result; result.x = Math::RoundFloat(x); result.y = Math::RoundFloat(y); return result; } // Generates a rounded vector from this vector. -template < > -inline Vector2< int > Vector2< int >::Round() const +template <> +inline Vector2 Vector2::Round() const { return *this; } // Computes the dot-product between this vector and another. -template < typename Type > -Type Vector2< Type >::DotProduct(Vector2 rhs) const +template +Type Vector2::DotProduct(Vector2 rhs) const { - return x * rhs.x + - y * rhs.y; + return x * rhs.x + y * rhs.y; } // Returns this vector rotated around the origin. -template < typename Type > -Vector2< Type > Vector2< Type >::Rotate(float theta) const +template +Vector2 Vector2::Rotate(float theta) const { float cos_theta = Math::Cos(theta); float sin_theta = Math::Sin(theta); - return Vector2< Type >(((Type)(cos_theta * x - sin_theta * y)), - ((Type)(sin_theta * x + cos_theta * y))); + return Vector2(((Type)(cos_theta * x - sin_theta * y)), ((Type)(sin_theta * x + cos_theta * y))); } // Returns the negation of this vector. -template < typename Type > -Vector2< Type > Vector2< Type >::operator-() const +template +Vector2 Vector2::operator-() const { return Vector2(-x, -y); } // Returns the sum of this vector and another. -template < typename Type > -Vector2< Type > Vector2< Type >::operator+(Vector2 rhs) const +template +Vector2 Vector2::operator+(Vector2 rhs) const { - return Vector2< Type >(x + rhs.x, y + rhs.y); + return Vector2(x + rhs.x, y + rhs.y); } // Returns the result of subtracting another vector from this vector. -template < typename Type > -Vector2< Type > Vector2< Type >::operator-(Vector2 rhs) const +template +Vector2 Vector2::operator-(Vector2 rhs) const { return Vector2(x - rhs.x, y - rhs.y); } // Returns the result of multiplying this vector by a scalar. -template < typename Type > -Vector2< Type > Vector2< Type >::operator*(Type rhs) const +template +Vector2 Vector2::operator*(Type rhs) const { return Vector2(x * rhs, y * rhs); } -template -Vector2< Type > Vector2::operator*(Vector2 rhs) const +template +Vector2 Vector2::operator*(Vector2 rhs) const { return Vector2(x * rhs.x, y * rhs.y); } // Returns the result of dividing this vector by a scalar. -template < typename Type > -Vector2< Type > Vector2< Type >::operator/(Type rhs) const +template +Vector2 Vector2::operator/(Type rhs) const { return Vector2(x / rhs, y / rhs); } -template -Vector2< Type > Vector2::operator/(Vector2 rhs) const +template +Vector2 Vector2::operator/(Vector2 rhs) const { return Vector2(x / rhs.x, y / rhs.y); } // Adds another vector to this in-place. -template < typename Type > -Vector2< Type >& Vector2< Type >::operator+=(Vector2 rhs) +template +Vector2& Vector2::operator+=(Vector2 rhs) { x += rhs.x; y += rhs.y; @@ -176,8 +171,8 @@ Vector2< Type >& Vector2< Type >::operator+=(Vector2 rhs) } // Subtracts another vector from this in-place. -template < typename Type > -Vector2< Type >& Vector2< Type >::operator-=(Vector2 rhs) +template +Vector2& Vector2::operator-=(Vector2 rhs) { x -= rhs.x; y -= rhs.y; @@ -186,8 +181,8 @@ Vector2< Type >& Vector2< Type >::operator-=(Vector2 rhs) } // Scales this vector in-place. -template < typename Type > -Vector2< Type >& Vector2< Type >::operator*=(Type rhs) +template +Vector2& Vector2::operator*=(Type rhs) { x *= rhs; y *= rhs; @@ -195,8 +190,8 @@ Vector2< Type >& Vector2< Type >::operator*=(Type rhs) return *this; } -template -Vector2< Type >& Vector2::operator*=(Vector2 rhs) +template +Vector2& Vector2::operator*=(Vector2 rhs) { x *= rhs.x; y *= rhs.y; @@ -205,8 +200,8 @@ Vector2< Type >& Vector2::operator*=(Vector2 rhs) } // Scales this vector in-place by the inverse of a value. -template < typename Type > -Vector2< Type >& Vector2< Type >::operator/=(Type rhs) +template +Vector2& Vector2::operator/=(Type rhs) { x /= rhs; y /= rhs; @@ -214,8 +209,8 @@ Vector2< Type >& Vector2< Type >::operator/=(Type rhs) return *this; } -template -Vector2< Type >& Vector2::operator/=(Vector2 rhs) +template +Vector2& Vector2::operator/=(Vector2 rhs) { x /= rhs.x; y /= rhs.y; @@ -223,44 +218,44 @@ Vector2< Type >& Vector2::operator/=(Vector2 rhs) } // Equality operator. -template < typename Type > -bool Vector2< Type >::operator==(Vector2 rhs) const +template +bool Vector2::operator==(Vector2 rhs) const { return (x == rhs.x && y == rhs.y); } // Inequality operator. -template < typename Type > -bool Vector2< Type >::operator!=(Vector2 rhs) const +template +bool Vector2::operator!=(Vector2 rhs) const { return (x != rhs.x || y != rhs.y); } // Auto-cast operator. -template < typename Type > -Vector2< Type >::operator const Type* () const +template +Vector2::operator const Type*() const { return &x; } // Constant auto-cast operator. -template < typename Type > -Vector2< Type >::operator Type* () +template +Vector2::operator Type*() { return &x; } // Underlying type-cast operator. -template < typename Type > -template < typename U > -inline Vector2< Type >::operator Vector2() const +template +template +inline Vector2::operator Vector2() const { return Vector2(static_cast(x), static_cast(y)); } // Multiply by scalar operator. -template < typename Type > -inline Vector2< Type > operator*(Type lhs, Vector2< Type> rhs) +template +inline Vector2 operator*(Type lhs, Vector2 rhs) { return rhs * lhs; } diff --git a/Include/RmlUi/Core/Vector3.h b/Include/RmlUi/Core/Vector3.h index 7ee210ce7..c8fe967cd 100644 --- a/Include/RmlUi/Core/Vector3.h +++ b/Include/RmlUi/Core/Vector3.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,111 +35,110 @@ namespace Rml { /** - Templated class for a generic three-component vector. - @author Markus Schöngart + Templated class for a generic three-component vector. + @author Markus Schöngart */ -template < typename Type > -class Vector3 -{ - public: - /// Default constructor. - inline Vector3(); - /// Initialising constructor. - /// @param[in] v Initial value of each element in the vector. - explicit inline Vector3(Type v); - /// Initialising constructor. - /// @param[in] x Initial x-value of the vector. - /// @param[in] y Initial y-value of the vector. - /// @param[in] z Initial z-value of the vector. - inline Vector3(Type x, Type y, Type z); - - /// Returns the magnitude of the vector. - /// @return The computed magnitude. - inline float Magnitude() const; - /// Returns the squared magnitude of the vector. - /// @return The computed squared magnitude. - inline Type SquaredMagnitude() const; - /// Generates a normalised vector from this vector. - /// @return The normalised vector. - inline Vector3 Normalise() const; - - /// Computes the dot-product between this vector and another. - /// @param[in] rhs The other vector to use in the dot-product. - /// @return The computed dot-product between the two vectors. - inline Type DotProduct(const Vector3& rhs) const; - - /// Computes the cross-product between this vector and another. - /// @param[in] rhs The other vector to use in the dot-product. - /// @return The computed cross-product between the two vectors. - inline Vector3 CrossProduct(const Vector3& rhs) const; - - /// Returns the negation of this vector. - /// @return The negation of this vector. - inline Vector3 operator-() const; - - /// Returns the sum of this vector and another. - /// @param[in] rhs The vector to add this to. - /// @return The sum of the two vectors. - inline Vector3 operator+(const Vector3& rhs) const; - /// Returns the result of subtracting another vector from this vector. - /// @param[in] rhs The vector to subtract from this vector. - /// @return The result of the subtraction. - inline Vector3 operator-(const Vector3& rhs) const; - /// Returns the result of multiplying this vector by a scalar. - /// @param[in] rhs The scalar value to multiply by. - /// @return The result of the scale. - inline Vector3 operator*(Type rhs) const; - /// Returns the result of dividing this vector by a scalar. - /// @param[in] rhs The scalar value to divide by. - /// @return The result of the scale. - inline Vector3 operator/(Type rhs) const; - - /// Adds another vector to this in-place. - /// @param[in] rhs The vector to add. - /// @return This vector, post-operation. - inline Vector3& operator+=(const Vector3& rhs); - /// Subtracts another vector from this in-place. - /// @param[in] rhs The vector to subtract. - /// @return This vector, post-operation. - inline Vector3& operator-=(const Vector3& rhs); - /// Scales this vector in-place. - /// @param[in] rhs The value to scale this vector's components by. - /// @return This vector, post-operation. - inline Vector3& operator*=(const Type& rhs); - /// Scales this vector in-place by the inverse of a value. - /// @param[in] rhs The value to divide this vector's components by. - /// @return This vector, post-operation. - inline Vector3& operator/=(const Type& rhs); - - /// Equality operator. - /// @param[in] rhs The vector to compare this against. - /// @return True if the two vectors are equal, false otherwise. - inline bool operator==(const Vector3& rhs) const; - /// Inequality operator. - /// @param[in] rhs The vector to compare this against. - /// @return True if the two vectors are not equal, false otherwise. - inline bool operator!=(const Vector3& rhs) const; - - /// Constant auto-cast operator. - /// @return A pointer to the first value. - inline operator const Type*() const; - /// Auto-cast operator. - /// @return A constant pointer to the first value. - inline operator Type*(); - - /// Underlying type-cast operator. - /// @return A copy of the vector with another underlying type. - template < typename U > - explicit inline operator Vector3() const; - - // Cast to Vector2 - explicit inline operator Vector2< Type >() const; - - // The components of the vector. - Type x; - Type y; - Type z; +template +class Vector3 { +public: + /// Default constructor. + inline Vector3(); + /// Initialising constructor. + /// @param[in] v Initial value of each element in the vector. + explicit inline Vector3(Type v); + /// Initialising constructor. + /// @param[in] x Initial x-value of the vector. + /// @param[in] y Initial y-value of the vector. + /// @param[in] z Initial z-value of the vector. + inline Vector3(Type x, Type y, Type z); + + /// Returns the magnitude of the vector. + /// @return The computed magnitude. + inline float Magnitude() const; + /// Returns the squared magnitude of the vector. + /// @return The computed squared magnitude. + inline Type SquaredMagnitude() const; + /// Generates a normalised vector from this vector. + /// @return The normalised vector. + inline Vector3 Normalise() const; + + /// Computes the dot-product between this vector and another. + /// @param[in] rhs The other vector to use in the dot-product. + /// @return The computed dot-product between the two vectors. + inline Type DotProduct(const Vector3& rhs) const; + + /// Computes the cross-product between this vector and another. + /// @param[in] rhs The other vector to use in the dot-product. + /// @return The computed cross-product between the two vectors. + inline Vector3 CrossProduct(const Vector3& rhs) const; + + /// Returns the negation of this vector. + /// @return The negation of this vector. + inline Vector3 operator-() const; + + /// Returns the sum of this vector and another. + /// @param[in] rhs The vector to add this to. + /// @return The sum of the two vectors. + inline Vector3 operator+(const Vector3& rhs) const; + /// Returns the result of subtracting another vector from this vector. + /// @param[in] rhs The vector to subtract from this vector. + /// @return The result of the subtraction. + inline Vector3 operator-(const Vector3& rhs) const; + /// Returns the result of multiplying this vector by a scalar. + /// @param[in] rhs The scalar value to multiply by. + /// @return The result of the scale. + inline Vector3 operator*(Type rhs) const; + /// Returns the result of dividing this vector by a scalar. + /// @param[in] rhs The scalar value to divide by. + /// @return The result of the scale. + inline Vector3 operator/(Type rhs) const; + + /// Adds another vector to this in-place. + /// @param[in] rhs The vector to add. + /// @return This vector, post-operation. + inline Vector3& operator+=(const Vector3& rhs); + /// Subtracts another vector from this in-place. + /// @param[in] rhs The vector to subtract. + /// @return This vector, post-operation. + inline Vector3& operator-=(const Vector3& rhs); + /// Scales this vector in-place. + /// @param[in] rhs The value to scale this vector's components by. + /// @return This vector, post-operation. + inline Vector3& operator*=(const Type& rhs); + /// Scales this vector in-place by the inverse of a value. + /// @param[in] rhs The value to divide this vector's components by. + /// @return This vector, post-operation. + inline Vector3& operator/=(const Type& rhs); + + /// Equality operator. + /// @param[in] rhs The vector to compare this against. + /// @return True if the two vectors are equal, false otherwise. + inline bool operator==(const Vector3& rhs) const; + /// Inequality operator. + /// @param[in] rhs The vector to compare this against. + /// @return True if the two vectors are not equal, false otherwise. + inline bool operator!=(const Vector3& rhs) const; + + /// Constant auto-cast operator. + /// @return A pointer to the first value. + inline operator const Type*() const; + /// Auto-cast operator. + /// @return A constant pointer to the first value. + inline operator Type*(); + + /// Underlying type-cast operator. + /// @return A copy of the vector with another underlying type. + template + explicit inline operator Vector3() const; + + // Cast to Vector2 + explicit inline operator Vector2() const; + + // The components of the vector. + Type x; + Type y; + Type z; #if defined(RMLUI_VECTOR3_USER_EXTRA) RMLUI_VECTOR3_USER_EXTRA diff --git a/Include/RmlUi/Core/Vector3.inl b/Include/RmlUi/Core/Vector3.inl index 52d5ad4ae..d0edee5ec 100644 --- a/Include/RmlUi/Core/Vector3.inl +++ b/Include/RmlUi/Core/Vector3.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,20 +36,18 @@ Vector3::Vector3() : x{}, y{}, z{} {} // Initialising constructor. -template < typename Type > -Vector3< Type >::Vector3(Type v) : x(v), y(v), z(v) -{ -} +template +Vector3::Vector3(Type v) : x(v), y(v), z(v) +{} // Initialising constructor. -template < typename Type > -Vector3< Type >::Vector3(Type x, Type y, Type z) : x(x), y(y), z(z) -{ -} +template +Vector3::Vector3(Type x, Type y, Type z) : x(x), y(y), z(z) +{} // Returns the magnitude of the vector. -template < typename Type > -float Vector3< Type >::Magnitude() const +template +float Vector3::Magnitude() const { float squared_magnitude = (float)SquaredMagnitude(); if (Math::IsZero(squared_magnitude)) @@ -59,22 +57,22 @@ float Vector3< Type >::Magnitude() const } // Returns the squared magnitude of the vector. -template < typename Type > -Type Vector3< Type >::SquaredMagnitude() const +template +Type Vector3::SquaredMagnitude() const { return x * x + y * y + z * z; } // Generates a normalised vector from this vector. -template < typename Type > -inline Vector3< Type > Vector3< Type >::Normalise() const +template +inline Vector3 Vector3::Normalise() const { static_assert(std::is_same::value, "Normalise only implemented for Vector."); return *this; } template <> -inline Vector3< float > Vector3< float >::Normalise() const +inline Vector3 Vector3::Normalise() const { const float magnitude = Magnitude(); if (Math::IsZero(magnitude)) @@ -84,61 +82,57 @@ inline Vector3< float > Vector3< float >::Normalise() const } // Computes the dot-product between this vector and another. -template < typename Type > -Type Vector3< Type >::DotProduct(const Vector3< Type >& rhs) const +template +Type Vector3::DotProduct(const Vector3& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; } // Computes the cross-product between this vector and another. -template < typename Type > -Vector3< Type> Vector3< Type >::CrossProduct(const Vector3< Type >& rhs) const +template +Vector3 Vector3::CrossProduct(const Vector3& rhs) const { - return Vector3< Type >( - y * rhs.z - z * rhs.y, - z * rhs.x - x * rhs.z, - x * rhs.y - y * rhs.x - ); + return Vector3(y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x); } // Returns the negation of this vector. -template < typename Type > -Vector3< Type > Vector3< Type >::operator-() const +template +Vector3 Vector3::operator-() const { return Vector3(-x, -y, -z); } // Returns the sum of this vector and another. -template < typename Type > -Vector3< Type > Vector3< Type >::operator+(const Vector3< Type > & rhs) const +template +Vector3 Vector3::operator+(const Vector3& rhs) const { - return Vector3< Type >(x + rhs.x, y + rhs.y, z + rhs.z); + return Vector3(x + rhs.x, y + rhs.y, z + rhs.z); } // Returns the result of subtracting another vector from this vector. -template < typename Type > -Vector3< Type > Vector3< Type >::operator-(const Vector3< Type > & rhs) const +template +Vector3 Vector3::operator-(const Vector3& rhs) const { return Vector3(x - rhs.x, y - rhs.y, z - rhs.z); } // Returns the result of multiplying this vector by a scalar. -template < typename Type > -Vector3< Type > Vector3< Type >::operator*(Type rhs) const +template +Vector3 Vector3::operator*(Type rhs) const { return Vector3(x * rhs, y * rhs, z * rhs); } // Returns the result of dividing this vector by a scalar. -template < typename Type > -Vector3< Type > Vector3< Type >::operator/(Type rhs) const +template +Vector3 Vector3::operator/(Type rhs) const { return Vector3(x / rhs, y / rhs, z / rhs); } // Adds another vector to this in-place. -template < typename Type > -Vector3< Type >& Vector3< Type >::operator+=(const Vector3 & rhs) +template +Vector3& Vector3::operator+=(const Vector3& rhs) { x += rhs.x; y += rhs.y; @@ -148,8 +142,8 @@ Vector3< Type >& Vector3< Type >::operator+=(const Vector3 & rhs) } // Subtracts another vector from this in-place. -template < typename Type > -Vector3< Type >& Vector3< Type >::operator-=(const Vector3 & rhs) +template +Vector3& Vector3::operator-=(const Vector3& rhs) { x -= rhs.x; y -= rhs.y; @@ -159,8 +153,8 @@ Vector3< Type >& Vector3< Type >::operator-=(const Vector3 & rhs) } // Scales this vector in-place. -template < typename Type > -Vector3< Type >& Vector3< Type >::operator*=(const Type & rhs) +template +Vector3& Vector3::operator*=(const Type& rhs) { x *= rhs; y *= rhs; @@ -170,8 +164,8 @@ Vector3< Type >& Vector3< Type >::operator*=(const Type & rhs) } // Scales this vector in-place by the inverse of a value. -template < typename Type > -Vector3< Type >& Vector3< Type >::operator/=(const Type & rhs) +template +Vector3& Vector3::operator/=(const Type& rhs) { x /= rhs; y /= rhs; @@ -181,50 +175,50 @@ Vector3< Type >& Vector3< Type >::operator/=(const Type & rhs) } // Equality operator. -template < typename Type > -bool Vector3< Type >::operator==(const Vector3 & rhs) const +template +bool Vector3::operator==(const Vector3& rhs) const { return (x == rhs.x && y == rhs.y && z == rhs.z); } // Inequality operator. -template < typename Type > -bool Vector3< Type >::operator!=(const Vector3 & rhs) const +template +bool Vector3::operator!=(const Vector3& rhs) const { return (x != rhs.x || y != rhs.y || z != rhs.z); } // Constant auto-cast operator. -template < typename Type > -Vector3< Type >::operator const Type* () const +template +Vector3::operator const Type*() const { return &x; } // Auto-cast operator. -template < typename Type > -Vector3< Type >::operator Type* () +template +Vector3::operator Type*() { return &x; } // Underlying type-cast operator. -template < typename Type > -template < typename U > -inline Vector3< Type >::operator Vector3() const +template +template +inline Vector3::operator Vector3() const { return Vector3(static_cast(x), static_cast(y), static_cast(z)); } -template < typename Type > -Vector3< Type >::operator Vector2< Type >() const +template +Vector3::operator Vector2() const { - return Vector2< Type >(x, y); + return Vector2(x, y); } // Multiply by scalar operator. -template < typename Type > -inline Vector3< Type > operator*(Type lhs, Vector3< Type > rhs) +template +inline Vector3 operator*(Type lhs, Vector3 rhs) { return rhs * lhs; } diff --git a/Include/RmlUi/Core/Vector4.h b/Include/RmlUi/Core/Vector4.h index 6688bc4f0..1e8f3bd86 100644 --- a/Include/RmlUi/Core/Vector4.h +++ b/Include/RmlUi/Core/Vector4.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,115 +36,114 @@ namespace Rml { /** - Templated class for a generic four-component vector. - @author Markus Schöngart + Templated class for a generic four-component vector. + @author Markus Schöngart */ -template < typename Type > -class Vector4 -{ - public: - /// Default constructor. - inline Vector4(); - /// Initialising constructor. - /// @param[in] v Initial value of each element in the vector. - explicit inline Vector4(Type v); - /// Initialising constructor. - /// @param[in] x Initial x-value of the vector. - /// @param[in] y Initial y-value of the vector. - /// @param[in] z Initial z-value of the vector. - /// @param[in] w Initial omega-value of the vector. - inline Vector4(Type x, Type y, Type z, Type w); - /// Implicit conversion from a 3D Vector. - inline Vector4(Vector3< Type > const &v, Type w); - - /// Returns the magnitude of the vector. - /// @return The computed magnitude. - inline float Magnitude() const; - /// Returns the squared magnitude of the vector. - /// @return The computed squared magnitude. - inline Type SquaredMagnitude() const; - /// Generates a normalised vector from this vector. - /// @return The normalised vector. - inline Vector4 Normalise() const; - - /// Computes the dot-product between this vector and another. - /// @param[in] rhs The other vector to use in the dot-product. - /// @return The computed dot-product between the two vectors. - inline Type DotProduct(const Vector4& rhs) const; - - /// Return a Vector3 after perspective divide - inline Vector3< Type > PerspectiveDivide() const; - - /// Returns the negation of this vector. - /// @return The negation of this vector. - inline Vector4 operator-() const; - - /// Returns the sum of this vector and another. - /// @param[in] rhs The vector to add this to. - /// @return The sum of the two vectors. - inline Vector4 operator+(const Vector4& rhs) const; - /// Returns the result of subtracting another vector from this vector. - /// @param[in] rhs The vector to subtract from this vector. - /// @return The result of the subtraction. - inline Vector4 operator-(const Vector4& rhs) const; - /// Returns the result of multiplying this vector by a scalar. - /// @param[in] rhs The scalar value to multiply by. - /// @return The result of the scale. - inline Vector4 operator*(Type rhs) const; - /// Returns the result of dividing this vector by a scalar. - /// @param[in] rhs The scalar value to divide by. - /// @return The result of the scale. - inline Vector4 operator/(Type rhs) const; - - /// Adds another vector to this in-place. - /// @param[in] rhs The vector to add. - /// @return This vector, post-operation. - inline Vector4& operator+=(const Vector4& rhs); - /// Subtracts another vector from this in-place. - /// @param[in] rhs The vector to subtract. - /// @return This vector, post-operation. - inline Vector4& operator-=(const Vector4& rhs); - /// Scales this vector in-place. - /// @param[in] rhs The value to scale this vector's components by. - /// @return This vector, post-operation. - inline Vector4& operator*=(const Type& rhs); - /// Scales this vector in-place by the inverse of a value. - /// @param[in] rhs The value to divide this vector's components by. - /// @return This vector, post-operation. - inline Vector4& operator/=(const Type& rhs); - - /// Equality operator. - /// @param[in] rhs The vector to compare this against. - /// @return True if the two vectors are equal, false otherwise. - inline bool operator==(const Vector4& rhs) const; - /// Inequality operator. - /// @param[in] rhs The vector to compare this against. - /// @return True if the two vectors are not equal, false otherwise. - inline bool operator!=(const Vector4& rhs) const; - - /// Auto-cast operator to array of components. - /// @return A pointer to the first value. - inline operator const Type*() const; - /// Constant auto-cast operator to array of components. - /// @return A constant pointer to the first value. - inline operator Type*(); - - /// Underlying type-cast operator. - /// @return A copy of the vector with another underlying type. - template < typename U > - explicit inline operator Vector4() const; - - /// Cast to Vector3 - explicit inline operator Vector3< Type >() const; - /// Cast to Vector2 - explicit inline operator Vector2< Type >() const; - - // The components of the vector. - Type x; - Type y; - Type z; - Type w; +template +class Vector4 { +public: + /// Default constructor. + inline Vector4(); + /// Initialising constructor. + /// @param[in] v Initial value of each element in the vector. + explicit inline Vector4(Type v); + /// Initialising constructor. + /// @param[in] x Initial x-value of the vector. + /// @param[in] y Initial y-value of the vector. + /// @param[in] z Initial z-value of the vector. + /// @param[in] w Initial omega-value of the vector. + inline Vector4(Type x, Type y, Type z, Type w); + /// Implicit conversion from a 3D Vector. + inline Vector4(Vector3 const& v, Type w); + + /// Returns the magnitude of the vector. + /// @return The computed magnitude. + inline float Magnitude() const; + /// Returns the squared magnitude of the vector. + /// @return The computed squared magnitude. + inline Type SquaredMagnitude() const; + /// Generates a normalised vector from this vector. + /// @return The normalised vector. + inline Vector4 Normalise() const; + + /// Computes the dot-product between this vector and another. + /// @param[in] rhs The other vector to use in the dot-product. + /// @return The computed dot-product between the two vectors. + inline Type DotProduct(const Vector4& rhs) const; + + /// Return a Vector3 after perspective divide + inline Vector3 PerspectiveDivide() const; + + /// Returns the negation of this vector. + /// @return The negation of this vector. + inline Vector4 operator-() const; + + /// Returns the sum of this vector and another. + /// @param[in] rhs The vector to add this to. + /// @return The sum of the two vectors. + inline Vector4 operator+(const Vector4& rhs) const; + /// Returns the result of subtracting another vector from this vector. + /// @param[in] rhs The vector to subtract from this vector. + /// @return The result of the subtraction. + inline Vector4 operator-(const Vector4& rhs) const; + /// Returns the result of multiplying this vector by a scalar. + /// @param[in] rhs The scalar value to multiply by. + /// @return The result of the scale. + inline Vector4 operator*(Type rhs) const; + /// Returns the result of dividing this vector by a scalar. + /// @param[in] rhs The scalar value to divide by. + /// @return The result of the scale. + inline Vector4 operator/(Type rhs) const; + + /// Adds another vector to this in-place. + /// @param[in] rhs The vector to add. + /// @return This vector, post-operation. + inline Vector4& operator+=(const Vector4& rhs); + /// Subtracts another vector from this in-place. + /// @param[in] rhs The vector to subtract. + /// @return This vector, post-operation. + inline Vector4& operator-=(const Vector4& rhs); + /// Scales this vector in-place. + /// @param[in] rhs The value to scale this vector's components by. + /// @return This vector, post-operation. + inline Vector4& operator*=(const Type& rhs); + /// Scales this vector in-place by the inverse of a value. + /// @param[in] rhs The value to divide this vector's components by. + /// @return This vector, post-operation. + inline Vector4& operator/=(const Type& rhs); + + /// Equality operator. + /// @param[in] rhs The vector to compare this against. + /// @return True if the two vectors are equal, false otherwise. + inline bool operator==(const Vector4& rhs) const; + /// Inequality operator. + /// @param[in] rhs The vector to compare this against. + /// @return True if the two vectors are not equal, false otherwise. + inline bool operator!=(const Vector4& rhs) const; + + /// Auto-cast operator to array of components. + /// @return A pointer to the first value. + inline operator const Type*() const; + /// Constant auto-cast operator to array of components. + /// @return A constant pointer to the first value. + inline operator Type*(); + + /// Underlying type-cast operator. + /// @return A copy of the vector with another underlying type. + template + explicit inline operator Vector4() const; + + /// Cast to Vector3 + explicit inline operator Vector3() const; + /// Cast to Vector2 + explicit inline operator Vector2() const; + + // The components of the vector. + Type x; + Type y; + Type z; + Type w; #if defined(RMLUI_VECTOR4_USER_EXTRA) RMLUI_VECTOR4_USER_EXTRA diff --git a/Include/RmlUi/Core/Vector4.inl b/Include/RmlUi/Core/Vector4.inl index 6ec522a43..1d89c0d30 100644 --- a/Include/RmlUi/Core/Vector4.inl +++ b/Include/RmlUi/Core/Vector4.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,29 +36,23 @@ Vector4::Vector4() : x{}, y{}, z{}, w{} {} // Initialising constructor. -template < typename Type > -Vector4< Type >::Vector4(Type v) - : x(v), y(v), z(v), w(v) -{ -} +template +Vector4::Vector4(Type v) : x(v), y(v), z(v), w(v) +{} // Initialising constructor. -template < typename Type > -Vector4< Type >::Vector4(Type x, Type y, Type z, Type w) - : x(x), y(y), z(z), w(w) -{ -} +template +Vector4::Vector4(Type x, Type y, Type z, Type w) : x(x), y(y), z(z), w(w) +{} // Implicit conversion from a 3D Vector. -template < typename Type > -Vector4< Type >::Vector4(Vector3< Type > const& v, Type w) - : x(v.x), y(v.y), z(v.z), w(w) -{ -} +template +Vector4::Vector4(Vector3 const& v, Type w) : x(v.x), y(v.y), z(v.z), w(w) +{} // Returns the magnitude of the vector. -template < typename Type > -float Vector4< Type >::Magnitude() const +template +float Vector4::Magnitude() const { float squared_magnitude = (float)SquaredMagnitude(); if (Math::IsZero(squared_magnitude)) @@ -68,22 +62,22 @@ float Vector4< Type >::Magnitude() const } // Returns the squared magnitude of the vector. -template < typename Type > -Type Vector4< Type >::SquaredMagnitude() const +template +Type Vector4::SquaredMagnitude() const { return x * x + y * y + z * z + w * w; } // Generates a normalised vector from this vector. -template < typename Type > -inline Vector4< Type > Vector4< Type >::Normalise() const +template +inline Vector4 Vector4::Normalise() const { static_assert(std::is_same::value, "Normalise only implemented for Vector."); return *this; } template <> -inline Vector4< float > Vector4< float >::Normalise() const +inline Vector4 Vector4::Normalise() const { const float magnitude = Magnitude(); if (Math::IsZero(magnitude)) @@ -93,56 +87,56 @@ inline Vector4< float > Vector4< float >::Normalise() const } // Computes the dot-product between this vector and another. -template < typename Type > -Type Vector4< Type >::DotProduct(const Vector4< Type >& rhs) const +template +Type Vector4::DotProduct(const Vector4& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w; } -template < typename Type > -Vector3< Type > Vector4< Type >::PerspectiveDivide() const +template +Vector3 Vector4::PerspectiveDivide() const { - return Vector3< Type >(x / w, y / w, z / w); + return Vector3(x / w, y / w, z / w); } // Returns the negation of this vector. -template < typename Type > -Vector4< Type > Vector4< Type >::operator-() const +template +Vector4 Vector4::operator-() const { return Vector4(-x, -y, -z, -w); } // Returns the sum of this vector and another. -template < typename Type > -Vector4< Type > Vector4< Type >::operator+(const Vector4< Type > & rhs) const +template +Vector4 Vector4::operator+(const Vector4& rhs) const { - return Vector4< Type >(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); + return Vector4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); } // Returns the result of subtracting another vector from this vector. -template < typename Type > -Vector4< Type > Vector4< Type >::operator-(const Vector4< Type > & rhs) const +template +Vector4 Vector4::operator-(const Vector4& rhs) const { return Vector4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); } // Returns the result of multiplying this vector by a scalar. -template < typename Type > -Vector4< Type > Vector4< Type >::operator*(Type rhs) const +template +Vector4 Vector4::operator*(Type rhs) const { return Vector4(x * rhs, y * rhs, z * rhs, w * rhs); } // Returns the result of dividing this vector by a scalar. -template < typename Type > -Vector4< Type > Vector4< Type >::operator/(Type rhs) const +template +Vector4 Vector4::operator/(Type rhs) const { return Vector4(x / rhs, y / rhs, z / rhs, w / rhs); } // Adds another vector to this in-place. -template < typename Type > -Vector4< Type >& Vector4< Type >::operator+=(const Vector4 & rhs) +template +Vector4& Vector4::operator+=(const Vector4& rhs) { x += rhs.x; y += rhs.y; @@ -153,8 +147,8 @@ Vector4< Type >& Vector4< Type >::operator+=(const Vector4 & rhs) } // Subtracts another vector from this in-place. -template < typename Type > -Vector4< Type >& Vector4< Type >::operator-=(const Vector4 & rhs) +template +Vector4& Vector4::operator-=(const Vector4& rhs) { x -= rhs.x; y -= rhs.y; @@ -165,8 +159,8 @@ Vector4< Type >& Vector4< Type >::operator-=(const Vector4 & rhs) } // Scales this vector in-place. -template < typename Type > -Vector4< Type >& Vector4< Type >::operator*=(const Type & rhs) +template +Vector4& Vector4::operator*=(const Type& rhs) { x *= rhs; y *= rhs; @@ -177,8 +171,8 @@ Vector4< Type >& Vector4< Type >::operator*=(const Type & rhs) } // Scales this vector in-place by the inverse of a value. -template < typename Type > -Vector4< Type >& Vector4< Type >::operator/=(const Type & rhs) +template +Vector4& Vector4::operator/=(const Type& rhs) { x /= rhs; y /= rhs; @@ -189,57 +183,56 @@ Vector4< Type >& Vector4< Type >::operator/=(const Type & rhs) } // Equality operator. -template < typename Type > -bool Vector4< Type >::operator==(const Vector4 & rhs) const +template +bool Vector4::operator==(const Vector4& rhs) const { return (x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w); } // Inequality operator. -template < typename Type > -bool Vector4< Type >::operator!=(const Vector4 & rhs) const +template +bool Vector4::operator!=(const Vector4& rhs) const { return (x != rhs.x || y != rhs.y || z != rhs.z || w != rhs.w); } // Auto-cast operator. -template < typename Type > -Vector4< Type >::operator const Type* () const +template +Vector4::operator const Type*() const { return &x; } // Constant auto-cast operator. -template < typename Type > -Vector4< Type >::operator Type* () +template +Vector4::operator Type*() { return &x; } // Underlying type-cast operator. -template < typename Type > -template < typename U > -inline Vector4< Type >::operator Vector4() const +template +template +inline Vector4::operator Vector4() const { return Vector4(static_cast(x), static_cast(y), static_cast(z), static_cast(w)); } - -template < typename Type > -Vector4< Type >::operator Vector3< Type >() const +template +Vector4::operator Vector3() const { - return Vector3< Type >(x, y, z); + return Vector3(x, y, z); } -template < typename Type > -Vector4< Type >::operator Vector2< Type >() const +template +Vector4::operator Vector2() const { - return Vector2< Type >(x, y); + return Vector2(x, y); } // Multiply by scalar operator. -template < typename Type > -inline Vector4< Type > operator*(Type lhs, Vector4< Type > rhs) +template +inline Vector4 operator*(Type lhs, Vector4 rhs) { return rhs * lhs; } diff --git a/Include/RmlUi/Core/Vertex.h b/Include/RmlUi/Core/Vertex.h index 7f8e70a5e..a056fdd51 100644 --- a/Include/RmlUi/Core/Vertex.h +++ b/Include/RmlUi/Core/Vertex.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - The element that makes up all geometry sent to the renderer. + The element that makes up all geometry sent to the renderer. - @author Peter Curry + @author Peter Curry */ -struct RMLUICORE_API Vertex -{ +struct RMLUICORE_API Vertex { /// Two-dimensional position of the vertex (usually in pixels). Vector2f position; /// RGBA-ordered 8-bit / channel colour. diff --git a/Include/RmlUi/Core/XMLNodeHandler.h b/Include/RmlUi/Core/XMLNodeHandler.h index 33a8e68a2..c23a3327e 100644 --- a/Include/RmlUi/Core/XMLNodeHandler.h +++ b/Include/RmlUi/Core/XMLNodeHandler.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,13 +40,12 @@ class XMLParser; enum class XMLDataType; /** - A handler gets ElementStart, ElementEnd and ElementData called by the XMLParser. + A handler gets ElementStart, ElementEnd and ElementData called by the XMLParser. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API XMLNodeHandler : public NonCopyMoveable -{ +class RMLUICORE_API XMLNodeHandler : public NonCopyMoveable { public: virtual ~XMLNodeHandler(); diff --git a/Include/RmlUi/Core/XMLParser.h b/Include/RmlUi/Core/XMLParser.h index 95d8149e6..ad788b29d 100644 --- a/Include/RmlUi/Core/XMLParser.h +++ b/Include/RmlUi/Core/XMLParser.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,9 +29,9 @@ #ifndef RMLUI_CORE_XMLPARSER_H #define RMLUI_CORE_XMLPARSER_H -#include -#include "Header.h" #include "BaseXMLParser.h" +#include "Header.h" +#include namespace Rml { @@ -41,13 +41,12 @@ class XMLNodeHandler; class URL; /** - RmlUi's XML parsing engine. The factory creates an instance of this class for each RML parse. + RmlUi's XML parsing engine. The factory creates an instance of this class for each RML parse. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class RMLUICORE_API XMLParser : public BaseXMLParser -{ +class RMLUICORE_API XMLParser : public BaseXMLParser { public: XMLParser(Element* root); ~XMLParser(); @@ -69,8 +68,7 @@ class RMLUICORE_API XMLParser : public BaseXMLParser DocumentHeader* GetDocumentHeader(); // The parse stack. - struct ParseFrame - { + struct ParseFrame { // Tag being parsed. String tag; @@ -113,7 +111,7 @@ class RMLUICORE_API XMLParser : public BaseXMLParser XMLNodeHandler* active_handler; // The parser stack. - using ParserStack = Stack< ParseFrame >; + using ParserStack = Stack; ParserStack stack; }; diff --git a/Include/RmlUi/Debugger.h b/Include/RmlUi/Debugger.h index 0c18e37d4..fc18382fb 100644 --- a/Include/RmlUi/Debugger.h +++ b/Include/RmlUi/Debugger.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Include/RmlUi/Debugger/Debugger.h b/Include/RmlUi/Debugger/Debugger.h index 569832584..ae880277b 100644 --- a/Include/RmlUi/Debugger/Debugger.h +++ b/Include/RmlUi/Debugger/Debugger.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,30 +37,30 @@ class Context; namespace Debugger { -/// Initialises the debug plugin. The debugger will be loaded into the given context. -/// @param[in] host_context RmlUi context to load the debugger into. The debugging tools will be displayed on this context. If this context is -/// destroyed, the debugger will be released. -/// @return True if the debugger was successfully initialised -RMLUIDEBUGGER_API bool Initialise(Context* host_context); + /// Initialises the debug plugin. The debugger will be loaded into the given context. + /// @param[in] host_context RmlUi context to load the debugger into. The debugging tools will be displayed on this context. If this context is + /// destroyed, the debugger will be released. + /// @return True if the debugger was successfully initialised + RMLUIDEBUGGER_API bool Initialise(Context* host_context); -/// Shuts down the debugger. -/// @note The debugger is automatically shutdown during the call to Rml::Shutdown(), calling this is only necessary to shutdown the debugger early -/// or to re-initialize the debugger on another host context. -RMLUIDEBUGGER_API void Shutdown(); + /// Shuts down the debugger. + /// @note The debugger is automatically shutdown during the call to Rml::Shutdown(), calling this is only necessary to shutdown the debugger early + /// or to re-initialize the debugger on another host context. + RMLUIDEBUGGER_API void Shutdown(); -/// Sets the context to be debugged. -/// @param[in] context The context to be debugged. -/// @return True if the debugger is initialised and the context was switched, false otherwise. -RMLUIDEBUGGER_API bool SetContext(Context* context); + /// Sets the context to be debugged. + /// @param[in] context The context to be debugged. + /// @return True if the debugger is initialised and the context was switched, false otherwise. + RMLUIDEBUGGER_API bool SetContext(Context* context); -/// Sets the visibility of the debugger. -/// @param[in] visibility True to show the debugger, false to hide it. -RMLUIDEBUGGER_API void SetVisible(bool visibility); -/// Returns the visibility of the debugger. -/// @return True if the debugger is visible, false if not. -RMLUIDEBUGGER_API bool IsVisible(); + /// Sets the visibility of the debugger. + /// @param[in] visibility True to show the debugger, false to hide it. + RMLUIDEBUGGER_API void SetVisible(bool visibility); + /// Returns the visibility of the debugger. + /// @return True if the debugger is visible, false if not. + RMLUIDEBUGGER_API bool IsVisible(); -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Include/RmlUi/Debugger/Header.h b/Include/RmlUi/Debugger/Header.h index 7d404fff7..09a24ffde 100644 --- a/Include/RmlUi/Debugger/Header.h +++ b/Include/RmlUi/Debugger/Header.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Include/RmlUi/Lottie/ElementLottie.h b/Include/RmlUi/Lottie/ElementLottie.h index f5f7f2fd0..f8db06cac 100644 --- a/Include/RmlUi/Lottie/ElementLottie.h +++ b/Include/RmlUi/Lottie/ElementLottie.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,17 +29,18 @@ #ifndef RMLUI_LOTTIE_ELEMENT_LOTTIE_H #define RMLUI_LOTTIE_ELEMENT_LOTTIE_H -#include "../Core/Header.h" #include "../Core/Element.h" #include "../Core/Geometry.h" +#include "../Core/Header.h" #include "../Core/Texture.h" -namespace rlottie { class Animation; } +namespace rlottie { +class Animation; +} namespace Rml { -class RMLUICORE_API ElementLottie : public Element -{ +class RMLUICORE_API ElementLottie : public Element { public: RMLUI_RTTI_DefineWithParent(ElementLottie, Element) diff --git a/Include/RmlUi/Lua.h b/Include/RmlUi/Lua.h index 8b4b04578..8d5b8fc31 100644 --- a/Include/RmlUi/Lua.h +++ b/Include/RmlUi/Lua.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,8 +31,9 @@ #include "Lua/Lua.h" +// Helper utilities #include "Lua/IncludeLua.h" -#include "Lua/LuaType.h" #include "Lua/Interpreter.h" +#include "Lua/LuaType.h" #endif diff --git a/Include/RmlUi/Lua/Header.h b/Include/RmlUi/Lua/Header.h index 1aa6966f3..643d16bb4 100644 --- a/Include/RmlUi/Lua/Header.h +++ b/Include/RmlUi/Lua/Header.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,19 +25,19 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_HEADER_H #define RMLUI_LUA_HEADER_H #include #ifdef RMLUILUA_API -#undef RMLUILUA_API + #undef RMLUILUA_API #endif #if !defined RMLUI_STATIC_LIB #ifdef RMLUI_PLATFORM_WIN32 - #if defined RmlLua_EXPORTS + #if defined RmlLua_EXPORTS #define RMLUILUA_API __declspec(dllexport) #else #define RMLUILUA_API __declspec(dllimport) diff --git a/Include/RmlUi/Lua/IncludeLua.h b/Include/RmlUi/Lua/IncludeLua.h index a2eb1723a..9a40deee0 100644 --- a/Include/RmlUi/Lua/IncludeLua.h +++ b/Include/RmlUi/Lua/IncludeLua.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,14 +25,14 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_INCLUDELUA_H -#define RMLUI_LUA_INCLUDELUA_H +#define RMLUI_LUA_INCLUDELUA_H -//The standard Lua headers +// The standard Lua headers extern "C" { -#include #include +#include #include } diff --git a/Include/RmlUi/Lua/Interpreter.h b/Include/RmlUi/Lua/Interpreter.h index 2e3f17feb..b33e8c317 100644 --- a/Include/RmlUi/Lua/Interpreter.h +++ b/Include/RmlUi/Lua/Interpreter.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,9 +25,9 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_INTERPRETER_H -#define RMLUI_LUA_INTERPRETER_H +#define RMLUI_LUA_INTERPRETER_H #include "Header.h" #include @@ -37,47 +37,46 @@ typedef struct lua_State lua_State; namespace Rml { namespace Lua { + namespace Interpreter { + /** + @return The lua_State that the Interpreter created in Interpreter::Startup() + @remark This class lacks a SetLuaState for a reason. If you have to use a seperate Lua binding and want to keep the types + from RmlUi, then use this lua_State; it will already have all of the libraries loaded, and all of the types defined. + Alternatively, you can initialise the plugin with your own Lua state if you need them defined in it. */ + RMLUILUA_API lua_State* GetLuaState(); -namespace Interpreter { - /** - @return The lua_State that the Interpreter created in Interpreter::Startup() - @remark This class lacks a SetLuaState for a reason. If you have to use a seperate Lua binding and want to keep the types - from RmlUi, then use this lua_State; it will already have all of the libraries loaded, and all of the types defined. - Alternatively, you can initialise the plugin with your own Lua state if you need them defined in it. */ - RMLUILUA_API lua_State* GetLuaState(); - - /** This function calls luaL_loadfile and then lua_pcall, reporting the errors (if any) - @param[in] file Fully qualified file name to execute. - @remark Somewhat misleading name if you are used to the Lua meaning of "load file". It behaves - exactly as luaL_dofile does. */ - RMLUILUA_API bool LoadFile(const String& file); - /** Calls lua_dostring and reports the errors. - @param[in] code String to execute - @param[in] name Name for the code that will show up in the Log */ - RMLUILUA_API bool DoString(const String& code, const String& name = ""); - /** Same as DoString, except does NOT call pcall on it. It will leave the compiled (but not executed) string - on top of the stack. It behaves exactly like luaL_loadstring, but you get to specify the name - @param[in] code String to compile - @param[in] name Name for the code that will show up in the Log */ - RMLUILUA_API bool LoadString(const String& code, const String& name = ""); + /** This function calls luaL_loadfile and then lua_pcall, reporting the errors (if any) + @param[in] file Fully qualified file name to execute. + @remark Somewhat misleading name if you are used to the Lua meaning of "load file". It behaves + exactly as luaL_dofile does. */ + RMLUILUA_API bool LoadFile(const String& file); + /** Calls lua_dostring and reports the errors. + @param[in] code String to execute + @param[in] name Name for the code that will show up in the Log */ + RMLUILUA_API bool DoString(const String& code, const String& name = ""); + /** Same as DoString, except does NOT call pcall on it. It will leave the compiled (but not executed) string + on top of the stack. It behaves exactly like luaL_loadstring, but you get to specify the name + @param[in] code String to compile + @param[in] name Name for the code that will show up in the Log */ + RMLUILUA_API bool LoadString(const String& code, const String& name = ""); - /** Clears all of the items on the stack, and pushes the function from funRef on top of the stack. Only use - this if you used lua_ref instead of luaL_ref - @param[in] funRef Lua reference that you would recieve from calling lua_ref */ - RMLUILUA_API void BeginCall(int funRef); - /** Uses lua_pcall on a function, which executes the function with params number of parameters and pushes - res number of return values on to the stack. - @pre Before you call this, your stack should look like: - [1] function to call; - [2...top] parameters to pass to the function (if any). - Or, in words, make sure to push the function on the stack before the parameters. - @post After this function, the params and function will be popped off, and 'res' - number of items will be pushed. */ - RMLUILUA_API bool ExecuteCall(int params = 0, int res = 0); - /** removes 'res' number of items from the stack - @param[in] res Number of results to remove from the stack. */ - RMLUILUA_API void EndCall(int res = 0); -} + /** Clears all of the items on the stack, and pushes the function from funRef on top of the stack. Only use + this if you used lua_ref instead of luaL_ref + @param[in] funRef Lua reference that you would recieve from calling lua_ref */ + RMLUILUA_API void BeginCall(int funRef); + /** Uses lua_pcall on a function, which executes the function with params number of parameters and pushes + res number of return values on to the stack. + @pre Before you call this, your stack should look like: + [1] function to call; + [2...top] parameters to pass to the function (if any). + Or, in words, make sure to push the function on the stack before the parameters. + @post After this function, the params and function will be popped off, and 'res' + number of items will be pushed. */ + RMLUILUA_API bool ExecuteCall(int params = 0, int res = 0); + /** removes 'res' number of items from the stack + @param[in] res Number of results to remove from the stack. */ + RMLUILUA_API void EndCall(int res = 0); + } // namespace Interpreter } // namespace Lua } // namespace Rml diff --git a/Include/RmlUi/Lua/Lua.h b/Include/RmlUi/Lua/Lua.h index cc7d675f1..0449b4ea0 100644 --- a/Include/RmlUi/Lua/Lua.h +++ b/Include/RmlUi/Lua/Lua.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,9 +25,9 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUA_H -#define RMLUI_LUA_LUA_H +#define RMLUI_LUA_LUA_H #include "Header.h" @@ -36,17 +36,16 @@ typedef struct lua_State lua_State; namespace Rml { namespace Lua { -/** Initialise the Lua plugin. - @remark This is equivalent to calling Initialise(nullptr). */ -RMLUILUA_API void Initialise(); - -/** Initialise the Lua plugin and add RmlUi to an existing Lua state if one is provided. - @remark If nullptr is passed as an argument, the plugin will automatically create the lua state during initialisation - and close the state during the call to Rml::Shutdown(). Otherwise, if a Lua state is provided, the user is - responsible for closing the provided Lua state. The state must then be closed after the call to Rml::Shutdown(). - @remark The plugin registers the "body" tag to generate a LuaDocument rather than a ElementDocument. */ -RMLUILUA_API void Initialise(lua_State* L); + /** Initialise the Lua plugin. + @remark This is equivalent to calling Initialise(nullptr). */ + RMLUILUA_API void Initialise(); + /** Initialise the Lua plugin and add RmlUi to an existing Lua state if one is provided. + @remark If nullptr is passed as an argument, the plugin will automatically create the lua state during initialisation + and close the state during the call to Rml::Shutdown(). Otherwise, if a Lua state is provided, the user is + responsible for closing the provided Lua state. The state must then be closed after the call to Rml::Shutdown(). + @remark The plugin registers the "body" tag to generate a LuaDocument rather than a ElementDocument. */ + RMLUILUA_API void Initialise(lua_State* L); } // namespace Lua } // namespace Rml diff --git a/Include/RmlUi/Lua/LuaType.h b/Include/RmlUi/Lua/LuaType.h index b620c6a8a..692be2740 100644 --- a/Include/RmlUi/Lua/LuaType.h +++ b/Include/RmlUi/Lua/LuaType.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,150 +25,189 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUATYPE_H #define RMLUI_LUA_LUATYPE_H #include "Header.h" #include "IncludeLua.h" -//As an example, if you used this macro like -//RMLUI_LUAMETHOD(Unit,GetId) -//it would result in code that looks like +// As an example, if you used this macro like +// RMLUI_LUAMETHOD(Unit,GetId) +// it would result in code that looks like //{ "GetId", UnitGetId }, -//Which would force you to create a global function named UnitGetId in C with the correct function signature, usually int(*)(lua_State*,type*); -#define RMLUI_LUAMETHOD(type,name) { #name, type##name }, - -//See above, but the method must match the function signature int(*)(lua_State*) and as example: -//RMLUI_LUAGETTER(Unit,Id) would mean you need a function named UnitGetAttrId -//The first stack position will be the userdata -#define RMLUI_LUAGETTER(type,varname) { #varname, type##GetAttr##varname }, - -//Same method signature as above, but as example: -//RMLUI_LUASETTER(Unit,Id) would mean you need a function named UnitSetAttrId -//The first stack position will be the userdata, and the second will be value on the other side of the equal sign -#define RMLUI_LUASETTER(type,varname) { #varname, type##SetAttr##varname }, - -#define RMLUI_CHECK_BOOL(L,narg) (lua_toboolean((L),(narg)) > 0 ? true : false ) -#define RMLUI_CHECK_OBJ(obj) if((obj) == nullptr) { lua_pushnil(L); return 1; } - - /** Used to remove repetitive typing at the cost of flexibility. When you use this, you @em must have - functions with the same name as defined in the macro. For example, if you used @c Element as type, you would - have to have functions named @c ElementMethods, @c ElementGetters, @c ElementSetters that return the appropriate - types.*/ -#define RMLUI_LUATYPE_DEFINE(type) \ - template<> const char* GetTClassName() { return #type; } \ - template<> RegType* GetMethodTable() { return type##Methods; } \ - template<> luaL_Reg* GetAttrTable() { return type##Getters; } \ - template<> luaL_Reg* SetAttrTable() { return type##Setters; } \ +// Which would force you to create a global function named UnitGetId in C with the correct function signature, usually int(*)(lua_State*,type*); +#define RMLUI_LUAMETHOD(type, name) \ + { \ + #name, type##name \ + } + +// See above, but the method must match the function signature int(*)(lua_State*) and as example: +// RMLUI_LUAGETTER(Unit,Id), would mean you need a function named UnitGetAttrId +// The first stack position will be the userdata +#define RMLUI_LUAGETTER(type, varname) \ + { \ + #varname, type##GetAttr##varname \ + } + +// Same method signature as above, but as example: +// RMLUI_LUASETTER(Unit,Id) would mean you need a function named UnitSetAttrId +// The first stack position will be the userdata, and the second will be value on the other side of the equal sign +#define RMLUI_LUASETTER(type, varname) \ + { \ + #varname, type##SetAttr##varname \ + } + +#define RMLUI_CHECK_BOOL(L, narg) (lua_toboolean((L), (narg)) > 0 ? true : false) +#define RMLUI_CHECK_OBJ(obj) \ + if ((obj) == nullptr) \ + { \ + lua_pushnil(L); \ + return 1; \ + } + +/** Used to remove repetitive typing at the cost of flexibility. When you use this, you @em must have +functions with the same name as defined in the macro. For example, if you used @c Element as type, you would +have to have functions named @c ElementMethods, @c ElementGetters, @c ElementSetters that return the appropriate +types.*/ +#define RMLUI_LUATYPE_DEFINE(type) \ + template <> \ + const char* GetTClassName() \ + { \ + return #type; \ + } \ + template <> \ + RegType* GetMethodTable() \ + { \ + return type##Methods; \ + } \ + template <> \ + luaL_Reg* GetAttrTable() \ + { \ + return type##Getters; \ + } \ + template <> \ + luaL_Reg* SetAttrTable() \ + { \ + return type##Setters; \ + } /** Used to remove repetitive typing at the cost of flexibility. It creates function prototypes for getting the name of the type, method tables, and if it is reference counted. When you use this, you either must also use the RMLUI_LUATYPE_DEFINE macro, or make sure that the function signatures are @em exact.*/ -#define RMLUI_LUATYPE_DECLARE(type) \ - template<> RMLUILUA_API const char* GetTClassName(); \ - template<> RMLUILUA_API RegType* GetMethodTable(); \ - template<> RMLUILUA_API luaL_Reg* GetAttrTable(); \ - template<> RMLUILUA_API luaL_Reg* SetAttrTable(); \ - +#define RMLUI_LUATYPE_DECLARE(type) \ + template <> \ + RMLUILUA_API const char* GetTClassName(); \ + template <> \ + RMLUILUA_API RegType* GetMethodTable(); \ + template <> \ + RMLUILUA_API luaL_Reg* GetAttrTable(); \ + template <> \ + RMLUILUA_API luaL_Reg* SetAttrTable(); namespace Rml { namespace Lua { -//replacement for luaL_Reg that uses a different function pointer signature, but similar syntax -template -struct RMLUILUA_API RegType -{ - const char* name; - int (*ftnptr)(lua_State*,T*); -}; - -/** For all of the methods available from Lua that call to the C functions. */ -template RMLUILUA_API RegType* GetMethodTable(); -/** For all of the function that 'get' an attribute/property */ -template RMLUILUA_API luaL_Reg* GetAttrTable(); -/** For all of the functions that 'set' an attribute/property */ -template RMLUILUA_API luaL_Reg* SetAttrTable(); -/** String representation of the class */ -template RMLUILUA_API const char* GetTClassName(); - -/** gets called from the LuaType::Register function, right before @c _regfunctions. -If you want to inherit from another class, in the function you would want -to call @c _regfunctions, where method is metatable_index - 1. Anything -that has the same name in the subclass will be overwrite whatever had the -same name in the superclass. */ -template RMLUILUA_API void ExtraInit(lua_State* L, int metatable_index); - -/** - This is mostly the definition of the Lua userdata that C++ gives to the user, plus - some helper functions. - - @author Nathan Starkey -*/ -template -class RMLUILUA_API LuaType -{ -public: - typedef int (*ftnptr)(lua_State* L, T* ptr); - /** replacement for luaL_Reg that uses a different function pointer signature, but similar syntax */ - typedef struct { const char* name; ftnptr func; } RegType; - - /** Registers the type T as a type in the Lua global namespace by creating a - metatable with the same name as the class, setting the metatmethods, and adding the - functions from _regfunctions */ - static inline void Register(lua_State *L); - /** Pushes on to the Lua stack a userdata representing a pointer of T - @param obj[in] The object to push to the stack - @param gc[in] If the obj should be deleted or decrease reference count upon the garbage collection - metamethod being called from the object in Lua - @return Position on the stack where the userdata resides */ - static inline int push(lua_State *L, T* obj, bool gc=false); - /** Statically casts the item at the position on the Lua stack - @param narg[in] Position of the item to cast on the Lua stack - @return A pointer to an object of type T or @c nullptr */ - static inline T* check(lua_State* L, int narg); - - /** For calling a C closure with upvalues. Used by the functions defined by RegType - @return The value that RegType.func returns */ - static inline int thunk(lua_State* L); - /** String representation of the pointer. Called by the __tostring metamethod */ - static inline void tostring(char* buff, size_t buff_size, void* obj); - //these are metamethods - /** The __gc metamethod. If the object was pushed by push(lua_State*,T*,bool) with the third - argument as true, it will either decrease the reference count or call delete depending on if - the type is reference counted. If the third argument to push was false, then this does nothing. - @return 0, since it pushes nothing on to the stack*/ - static inline int gc_T(lua_State* L); - /** The __tostring metamethod. - @return 1, because it pushes a string representation of the userdata on to the stack */ - static inline int tostring_T(lua_State* L); - /** The __eq metamethod. Facilitates equality tests with C++-side pointers */ - static inline int eq_T(lua_State* L); - /** The __index metamethod. Called whenever the user attempts to access a variable that is - not in the immediate table. This handles the method calls and calls tofunctions in __getters */ - static inline int index(lua_State* L); - /** The __newindex metamethod. Called when the user attempts to set a variable that is not - int the immediate table. This handles the calls to functions in __setters */ - static inline int newindex(lua_State* L); - - /** Registers methods,getters,and setters to the type. In Lua, the methods exist in the Type name's - metatable, and the getters exist in __getters and setters in __setters. The reason for __getters and __setters - is to have the objects use a 'dot' syntax for properties and a 'colon' syntax for methods.*/ - static inline void _regfunctions(lua_State* L, int meta, int method); - -private: - static constexpr size_t max_pointer_string_size = 32; - - LuaType(); //hide constructor -}; - -namespace LuaTypeImpl { -RMLUILUA_API int index(lua_State* L, const char* class_name); -RMLUILUA_API int newindex(lua_State* L, const char* class_name); -} + // replacement for luaL_Reg that uses a different function pointer signature, but similar syntax + template + struct RMLUILUA_API RegType { + const char* name; + int (*ftnptr)(lua_State*, T*); + }; + + /** For all of the methods available from Lua that call to the C functions. */ + template + RMLUILUA_API RegType* GetMethodTable(); + /** For all of the function that 'get' an attribute/property */ + template + RMLUILUA_API luaL_Reg* GetAttrTable(); + /** For all of the functions that 'set' an attribute/property */ + template + RMLUILUA_API luaL_Reg* SetAttrTable(); + /** String representation of the class */ + template + RMLUILUA_API const char* GetTClassName(); + + /** gets called from the LuaType::Register function, right before @c _regfunctions. + If you want to inherit from another class, in the function you would want + to call @c _regfunctions, where method is metatable_index - 1. Anything + that has the same name in the subclass will be overwrite whatever had the + same name in the superclass. */ + template + RMLUILUA_API void ExtraInit(lua_State* L, int metatable_index); + + /** + This is mostly the definition of the Lua userdata that C++ gives to the user, plus + some helper functions. + + @author Nathan Starkey + */ + template + class RMLUILUA_API LuaType { + public: + typedef int (*ftnptr)(lua_State* L, T* ptr); + /** replacement for luaL_Reg that uses a different function pointer signature, but similar syntax */ + typedef struct { + const char* name; + ftnptr func; + } RegType; + + /** Registers the type T as a type in the Lua global namespace by creating a + metatable with the same name as the class, setting the metatmethods, and adding the + functions from _regfunctions */ + static inline void Register(lua_State* L); + /** Pushes on to the Lua stack a userdata representing a pointer of T + @param obj[in] The object to push to the stack + @param gc[in] If the obj should be deleted or decrease reference count upon the garbage collection + metamethod being called from the object in Lua + @return Position on the stack where the userdata resides */ + static inline int push(lua_State* L, T* obj, bool gc = false); + /** Statically casts the item at the position on the Lua stack + @param narg[in] Position of the item to cast on the Lua stack + @return A pointer to an object of type T or @c nullptr */ + static inline T* check(lua_State* L, int narg); + + /** For calling a C closure with upvalues. Used by the functions defined by RegType + @return The value that RegType.func returns */ + static inline int thunk(lua_State* L); + /** String representation of the pointer. Called by the __tostring metamethod */ + static inline void tostring(char* buff, size_t buff_size, void* obj); + // these are metamethods + /** The __gc metamethod. If the object was pushed by push(lua_State*,T*,bool) with the third + argument as true, it will either decrease the reference count or call delete depending on if + the type is reference counted. If the third argument to push was false, then this does nothing. + @return 0, since it pushes nothing on to the stack*/ + static inline int gc_T(lua_State* L); + /** The __tostring metamethod. + @return 1, because it pushes a string representation of the userdata on to the stack */ + static inline int tostring_T(lua_State* L); + /** The __eq metamethod. Facilitates equality tests with C++-side pointers */ + static inline int eq_T(lua_State* L); + /** The __index metamethod. Called whenever the user attempts to access a variable that is + not in the immediate table. This handles the method calls and calls tofunctions in __getters */ + static inline int index(lua_State* L); + /** The __newindex metamethod. Called when the user attempts to set a variable that is not + int the immediate table. This handles the calls to functions in __setters */ + static inline int newindex(lua_State* L); + + /** Registers methods,getters,and setters to the type. In Lua, the methods exist in the Type name's + metatable, and the getters exist in __getters and setters in __setters. The reason for __getters and __setters + is to have the objects use a 'dot' syntax for properties and a 'colon' syntax for methods.*/ + static inline void _regfunctions(lua_State* L, int meta, int method); + + private: + static constexpr size_t max_pointer_string_size = 32; + + LuaType(); // hide constructor + }; + + namespace LuaTypeImpl { + RMLUILUA_API int index(lua_State* L, const char* class_name); + RMLUILUA_API int newindex(lua_State* L, const char* class_name); + } // namespace LuaTypeImpl } // namespace Lua } // namespace Rml -#include "LuaType.inl" -#endif \ No newline at end of file +#include "LuaType.inl" +#endif diff --git a/Include/RmlUi/Lua/LuaType.inl b/Include/RmlUi/Lua/LuaType.inl index 46a9489db..ec1816804 100644 --- a/Include/RmlUi/Lua/LuaType.inl +++ b/Include/RmlUi/Lua/LuaType.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,254 +29,247 @@ namespace Rml { namespace Lua { -template -void LuaType::Register(lua_State* L) -{ - //for annotations, starting at 1, but it is a relative value, not always 1 - lua_newtable(L); //[1] = table - int methods = lua_gettop(L); //methods = 1 - - luaL_newmetatable(L, GetTClassName()); //[2] = metatable named , referred in here by ClassMT - int metatable = lua_gettop(L); //metatable = 2 - - luaL_newmetatable(L, "DO NOT TRASH"); //[3] = metatable named "DO NOT TRASH" - lua_pop(L,1); //remove the above metatable -> [-1 = 2] - - //store method table in globals so that scripts can add functions written in Lua - lua_pushvalue(L, methods); //[methods = 1] -> [3] = copy (reference) of methods table - lua_setglobal(L, GetTClassName()); // -> = [3 = 1], pop top [3] - - //hide metatable from Lua getmetatable() - lua_pushvalue(L, methods); //[methods = 1] -> [3] = copy of methods table, including modifications above - lua_setfield(L, metatable, "__metatable"); //[metatable = 2] -> t[k] = v; t = [2 = ClassMT], k = "__metatable", v = [3 = 1]; pop [3] - - lua_pushcfunction(L, index); //index = cfunction -> [3] = cfunction - lua_setfield(L, metatable, "__index"); //[metatable = 2] -> t[k] = v; t = [2], k = "__index", v = cfunc; pop [3] - - lua_pushcfunction(L, newindex); - lua_setfield(L, metatable, "__newindex"); - - lua_pushcfunction(L, gc_T); - lua_setfield(L, metatable, "__gc"); - - lua_pushcfunction(L, tostring_T); - lua_setfield(L, metatable, "__tostring"); - - lua_pushcfunction(L, eq_T); - lua_setfield(L, metatable, "__eq"); - - ExtraInit(L,metatable); //optionally implemented by individual types - - lua_newtable(L); //for method table -> [3] = this table - lua_setmetatable(L, methods); //[methods = 1] -> metatable for [1] is [3]; [3] is popped off, top = [2] - - _regfunctions(L,metatable,methods); - - lua_pop(L, 2); //remove the two items from the stack, [1 = methods] and [2 = metatable] -} - - -template -int LuaType::push(lua_State *L, T* obj, bool gc) -{ - //for annotations, starting at index 1, but it is a relative number, not always 1 - if (!obj) { lua_pushnil(L); return lua_gettop(L); } - luaL_getmetatable(L, GetTClassName()); // lookup metatable in Lua registry ->[1] = metatable of - if (lua_isnil(L, -1)) luaL_error(L, "%s missing metatable", GetTClassName()); - int mt = lua_gettop(L); //mt = 1 - T** ptrHold = (T**)lua_newuserdata(L,sizeof(T**)); //->[2] = empty userdata - int ud = lua_gettop(L); //ud = 2 - if(ptrHold != nullptr) - { - *ptrHold = obj; - lua_pushvalue(L, mt); // ->[3] = copy of [1] - lua_setmetatable(L, -2); //[-2 = 2] -> [2]'s metatable = [3]; pop [3] - char name[max_pointer_string_size]; - tostring(name, max_pointer_string_size, ptrHold); - lua_getfield(L,LUA_REGISTRYINDEX,"DO NOT TRASH"); //->[3] = value returned from function - if(lua_isnil(L,-1) ) //if [3] hasn't been created yet, then create it - { - luaL_newmetatable(L,"DO NOT TRASH"); //[4] = the new metatable - lua_pop(L,1); //pop [4] - } - lua_pop(L,1); //pop [3] - lua_getfield(L,LUA_REGISTRYINDEX,"DO NOT TRASH"); //->[3] = value returned from function - if(gc == false) //if we shouldn't garbage collect it, then put the name in to [3] - { - lua_pushboolean(L,1);// ->[4] = true - lua_setfield(L,-2,name); //represents t[k] = v, [-2 = 3] = t -> v = [4], k = ; pop [4] - } - else - { - //In case this is an address that has been pushed - //to lua before, we need to set it to nil - lua_pushnil(L); // ->[4] = nil - lua_setfield(L,-2,name); //represents t[k] = v, [-2 = 3] = t -> v = [4], k = ; pop [4] - } - - lua_pop(L,1); // -> pop [3] - } - lua_settop(L,ud); //[ud = 2] -> remove everything that is above 2, top = [2] - lua_replace(L, mt); //[mt = 1] -> move [2] to pos [1], and pop previous [1] - lua_settop(L, mt); //remove everything above [1] - return mt; // index of userdata containing pointer to T object -} - - -template -T* LuaType::check(lua_State* L, int narg) -{ - T** ptrHold = static_cast(lua_touserdata(L,narg)); - if(ptrHold == nullptr) - return nullptr; - return (*ptrHold); -} - - -//private members - -template -int LuaType::thunk(lua_State* L) -{ - // stack has userdata, followed by method args - T *obj = check(L, 1); // get 'self', or if you prefer, 'this' - lua_remove(L, 1); // remove self so member function args start at index 1 - // get member function from upvalue - RegType *l = static_cast(lua_touserdata(L, lua_upvalueindex(1))); - //at the moment, there isn't a case where nullptr is acceptable to be used in the function, so check - //for it here, rather than individually for each function - if(obj == nullptr) - { - lua_pushnil(L); - return 1; - } - else - return l->func(L,obj); // call member function -} - - - -template -void LuaType::tostring(char* buff, size_t buff_size, void* obj) -{ - snprintf(buff, buff_size, "%p", obj); -} - - -template -int LuaType::gc_T(lua_State* L) -{ - T * obj = check(L,1); //[1] = this userdata - if(obj == nullptr) - return 0; - - lua_getfield(L,LUA_REGISTRYINDEX,"DO NOT TRASH"); //->[2] = return value from this - if(lua_istable(L,-1) ) //[-1 = 2], if it is a table - { - char name[max_pointer_string_size]; - void* ptrHold = lua_touserdata(L,1); - tostring(name, max_pointer_string_size, ptrHold); - lua_getfield(L,-1,name); //[-1 = 2] -> [3] = the value returned from if exists in the table to not gc - if(lua_isnoneornil(L,-1) ) //[-1 = 3] if it doesn't exist, then we are free to garbage collect c++ side + template + void LuaType::Register(lua_State* L) + { + // for annotations, starting at 1, but it is a relative value, not always 1 + lua_newtable(L); //[1] = table + int methods = lua_gettop(L); // methods = 1 + + luaL_newmetatable(L, GetTClassName()); //[2] = metatable named , referred in here by ClassMT + int metatable = lua_gettop(L); // metatable = 2 + + luaL_newmetatable(L, "DO NOT TRASH"); //[3] = metatable named "DO NOT TRASH" + lua_pop(L, 1); // remove the above metatable -> [-1 = 2] + + // store method table in globals so that scripts can add functions written in Lua + lua_pushvalue(L, methods); //[methods = 1] -> [3] = copy (reference) of methods table + lua_setglobal(L, GetTClassName()); // -> = [3 = 1], pop top [3] + + // hide metatable from Lua getmetatable() + lua_pushvalue(L, methods); //[methods = 1] -> [3] = copy of methods table, including modifications above + lua_setfield(L, metatable, "__metatable"); //[metatable = 2] -> t[k] = v; t = [2 = ClassMT], k = "__metatable", v = [3 = 1]; pop [3] + + lua_pushcfunction(L, index); // index = cfunction -> [3] = cfunction + lua_setfield(L, metatable, "__index"); //[metatable = 2] -> t[k] = v; t = [2], k = "__index", v = cfunc; pop [3] + + lua_pushcfunction(L, newindex); + lua_setfield(L, metatable, "__newindex"); + + lua_pushcfunction(L, gc_T); + lua_setfield(L, metatable, "__gc"); + + lua_pushcfunction(L, tostring_T); + lua_setfield(L, metatable, "__tostring"); + + lua_pushcfunction(L, eq_T); + lua_setfield(L, metatable, "__eq"); + + ExtraInit(L, metatable); // optionally implemented by individual types + + lua_newtable(L); // for method table -> [3] = this table + lua_setmetatable(L, methods); //[methods = 1] -> metatable for [1] is [3]; [3] is popped off, top = [2] + + _regfunctions(L, metatable, methods); + + lua_pop(L, 2); // remove the two items from the stack, [1 = methods] and [2 = metatable] + } + + template + int LuaType::push(lua_State* L, T* obj, bool gc) + { + // for annotations, starting at index 1, but it is a relative number, not always 1 + if (!obj) + { + lua_pushnil(L); + return lua_gettop(L); + } + luaL_getmetatable(L, GetTClassName()); // lookup metatable in Lua registry ->[1] = metatable of + if (lua_isnil(L, -1)) + luaL_error(L, "%s missing metatable", GetTClassName()); + int mt = lua_gettop(L); // mt = 1 + T** ptrHold = (T**)lua_newuserdata(L, sizeof(T**)); //->[2] = empty userdata + int ud = lua_gettop(L); // ud = 2 + if (ptrHold != nullptr) + { + *ptrHold = obj; + lua_pushvalue(L, mt); // ->[3] = copy of [1] + lua_setmetatable(L, -2); //[-2 = 2] -> [2]'s metatable = [3]; pop [3] + char name[max_pointer_string_size]; + tostring(name, max_pointer_string_size, ptrHold); + lua_getfield(L, LUA_REGISTRYINDEX, "DO NOT TRASH"); //->[3] = value returned from function + if (lua_isnil(L, -1)) // if [3] hasn't been created yet, then create it + { + luaL_newmetatable(L, "DO NOT TRASH"); //[4] = the new metatable + lua_pop(L, 1); // pop [4] + } + lua_pop(L, 1); // pop [3] + lua_getfield(L, LUA_REGISTRYINDEX, "DO NOT TRASH"); //->[3] = value returned from function + if (gc == false) // if we shouldn't garbage collect it, then put the name in to [3] + { + lua_pushboolean(L, 1); // ->[4] = true + lua_setfield(L, -2, name); // represents t[k] = v, [-2 = 3] = t -> v = [4], k = ; pop [4] + } + else + { + // In case this is an address that has been pushed + // to lua before, we need to set it to nil + lua_pushnil(L); // ->[4] = nil + lua_setfield(L, -2, name); // represents t[k] = v, [-2 = 3] = t -> v = [4], k = ; pop [4] + } + + lua_pop(L, 1); // -> pop [3] + } + lua_settop(L, ud); //[ud = 2] -> remove everything that is above 2, top = [2] + lua_replace(L, mt); //[mt = 1] -> move [2] to pos [1], and pop previous [1] + lua_settop(L, mt); // remove everything above [1] + return mt; // index of userdata containing pointer to T object + } + + template + T* LuaType::check(lua_State* L, int narg) + { + T** ptrHold = static_cast(lua_touserdata(L, narg)); + if (ptrHold == nullptr) + return nullptr; + return (*ptrHold); + } + + // private members + + template + int LuaType::thunk(lua_State* L) + { + // stack has userdata, followed by method args + T* obj = check(L, 1); // get 'self', or if you prefer, 'this' + lua_remove(L, 1); // remove self so member function args start at index 1 + // get member function from upvalue + RegType* l = static_cast(lua_touserdata(L, lua_upvalueindex(1))); + // at the moment, there isn't a case where nullptr is acceptable to be used in the function, so check + // for it here, rather than individually for each function + if (obj == nullptr) + { + lua_pushnil(L); + return 1; + } + else + return l->func(L, obj); // call member function + } + + template + void LuaType::tostring(char* buff, size_t buff_size, void* obj) + { + snprintf(buff, buff_size, "%p", obj); + } + + template + int LuaType::gc_T(lua_State* L) + { + T* obj = check(L, 1); //[1] = this userdata + if (obj == nullptr) + return 0; + + lua_getfield(L, LUA_REGISTRYINDEX, "DO NOT TRASH"); //->[2] = return value from this + if (lua_istable(L, -1)) //[-1 = 2], if it is a table + { + char name[max_pointer_string_size]; + void* ptrHold = lua_touserdata(L, 1); + tostring(name, max_pointer_string_size, ptrHold); + lua_getfield(L, -1, name); //[-1 = 2] -> [3] = the value returned from if exists in the table to not gc + if (lua_isnoneornil(L, -1)) //[-1 = 3] if it doesn't exist, then we are free to garbage collect c++ side + { + delete obj; + obj = nullptr; + + // Change the field to not gc the next time we encounter this pointer. This may be necessary in case the + // just deleted object shared an address with a previously deleted (non-GCed) object, the latter which + // this function will be called upon later. + lua_pushboolean(L, 1); // ->[4] = true + lua_setfield(L, -3, name); // represents t[k] = v, [-3 = 2] = t -> v = [4], k = ; pop [4] + } + } + lua_pop(L, 3); // balance function + return 0; + } + + template + int LuaType::tostring_T(lua_State* L) + { + char buff[max_pointer_string_size]; + T** ptrHold = (T**)lua_touserdata(L, 1); + void* obj = static_cast(*ptrHold); + snprintf(buff, max_pointer_string_size, "%p", obj); + lua_pushfstring(L, "%s (%s)", GetTClassName(), buff); + return 1; + } + + template + int LuaType::eq_T(lua_State* L) + { + T* o1 = check(L, 1); + RMLUI_CHECK_OBJ(o1); + T* o2 = check(L, 2); + RMLUI_CHECK_OBJ(o2); + lua_pushboolean(L, o1 == o2); + return 1; + } + + template + int LuaType::index(lua_State* L) + { + const char* class_name = GetTClassName(); + return LuaTypeImpl::index(L, class_name); + } + + template + int LuaType::newindex(lua_State* L) + { + const char* class_name = GetTClassName(); + return LuaTypeImpl::newindex(L, class_name); + } + + template + void LuaType::_regfunctions(lua_State* L, int /*meta*/, int methods) + { + // fill method table with methods. + for (RegType* m = (RegType*)GetMethodTable(); m->name; m++) + { + lua_pushstring(L, m->name); // ->[1] = name of function Lua side + lua_pushlightuserdata(L, (void*)m); // ->[2] = pointer to the object containing the name and the function pointer as light userdata + lua_pushcclosure(L, thunk, 1); // thunk = function pointer -> pop 1 item from stack, [2] = closure + lua_settable(L, methods); // represents t[k] = v, t = [methods] -> pop [2 = closure] to be v, pop [1 = name] to be k + } + + lua_getfield(L, methods, "__getters"); // -> table[1] + if (lua_isnoneornil(L, -1)) + { + lua_pop(L, 1); // pop unsuccessful get + lua_newtable(L); // -> table [1] + lua_setfield(L, methods, "__getters"); // pop [1] + lua_getfield(L, methods, "__getters"); // -> table [1] + } + for (luaL_Reg* m = (luaL_Reg*)GetAttrTable(); m->name; m++) { - delete obj; - obj = nullptr; - - // Change the field to not gc the next time we encounter this pointer. This may be necessary in case the - // just deleted object shared an address with a previously deleted (non-GCed) object, the latter which - // this function will be called upon later. - lua_pushboolean(L, 1); // ->[4] = true - lua_setfield(L, -3, name); // represents t[k] = v, [-3 = 2] = t -> v = [4], k = ; pop [4] + lua_pushcfunction(L, m->func); // -> [2] is this function + lua_setfield(L, -2, m->name); //[-2 = 1] -> __getters.name = function } - } - lua_pop(L,3); //balance function - return 0; -} - - -template -int LuaType::tostring_T(lua_State* L) -{ - char buff[max_pointer_string_size]; - T** ptrHold = (T**)lua_touserdata(L,1); - void* obj = static_cast(*ptrHold); - snprintf(buff, max_pointer_string_size, "%p", obj); - lua_pushfstring(L, "%s (%s)", GetTClassName(), buff); - return 1; -} - -template -int LuaType::eq_T(lua_State* L) -{ - T* o1 = check(L,1); - RMLUI_CHECK_OBJ(o1); - T* o2 = check(L,2); - RMLUI_CHECK_OBJ(o2); - lua_pushboolean(L, o1 == o2); - return 1; -} - - -template -int LuaType::index(lua_State* L) -{ - const char* class_name = GetTClassName(); - return LuaTypeImpl::index(L, class_name); -} - -template -int LuaType::newindex(lua_State* L) -{ - const char* class_name = GetTClassName(); - return LuaTypeImpl::newindex(L, class_name); -} - - -template -void LuaType::_regfunctions(lua_State* L, int /*meta*/, int methods) -{ - //fill method table with methods. - for(RegType* m = (RegType*)GetMethodTable(); m->name; m++) - { - lua_pushstring(L, m->name); // ->[1] = name of function Lua side - lua_pushlightuserdata(L, (void*)m); // ->[2] = pointer to the object containing the name and the function pointer as light userdata - lua_pushcclosure(L, thunk, 1); //thunk = function pointer -> pop 1 item from stack, [2] = closure - lua_settable(L, methods); // represents t[k] = v, t = [methods] -> pop [2 = closure] to be v, pop [1 = name] to be k - } - - - lua_getfield(L,methods, "__getters"); // -> table[1] - if(lua_isnoneornil(L,-1)) - { - lua_pop(L,1); //pop unsuccessful get - lua_newtable(L); // -> table [1] - lua_setfield(L,methods,"__getters"); // pop [1] - lua_getfield(L,methods,"__getters"); // -> table [1] - } - for(luaL_Reg* m = (luaL_Reg*)GetAttrTable(); m->name; m++) - { - lua_pushcfunction(L,m->func); // -> [2] is this function - lua_setfield(L,-2,m->name); //[-2 = 1] -> __getters.name = function - } - lua_pop(L,1); //pop __getters - - - lua_getfield(L,methods, "__setters"); // -> table[1] - if(lua_isnoneornil(L,-1)) - { - lua_pop(L,1); //pop unsuccessful get - lua_newtable(L); // -> table [1] - lua_setfield(L,methods,"__setters"); // pop [1] - lua_getfield(L,methods,"__setters"); // -> table [1] - } - for(luaL_Reg* m = (luaL_Reg*)SetAttrTable(); m->name; m++) - { - lua_pushcfunction(L,m->func); // -> [2] is this function - lua_setfield(L,-2,m->name); //[-2 = 1] -> __setters.name = function - } - lua_pop(L,1); //pop __setters -} + lua_pop(L, 1); // pop __getters + lua_getfield(L, methods, "__setters"); // -> table[1] + if (lua_isnoneornil(L, -1)) + { + lua_pop(L, 1); // pop unsuccessful get + lua_newtable(L); // -> table [1] + lua_setfield(L, methods, "__setters"); // pop [1] + lua_getfield(L, methods, "__setters"); // -> table [1] + } + for (luaL_Reg* m = (luaL_Reg*)SetAttrTable(); m->name; m++) + { + lua_pushcfunction(L, m->func); // -> [2] is this function + lua_setfield(L, -2, m->name); //[-2 = 1] -> __setters.name = function + } + lua_pop(L, 1); // pop __setters + } } // namespace Lua } // namespace Rml diff --git a/Include/RmlUi/Lua/Utilities.h b/Include/RmlUi/Lua/Utilities.h index 808f1ec43..a85738704 100644 --- a/Include/RmlUi/Lua/Utilities.h +++ b/Include/RmlUi/Lua/Utilities.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_UTILITIES_H #define RMLUI_LUA_UTILITIES_H /* @@ -40,61 +40,60 @@ namespace Rml { namespace Lua { #if LUA_VERSION_NUM < 502 -#define lua_setuservalue(L, i) \ - (luaL_checktype((L), -1, LUA_TTABLE), lua_setfenv((L), (i))) - -inline int lua_absindex(lua_State* L, int idx) -{ - if (idx > LUA_REGISTRYINDEX && idx < 0) - return lua_gettop(L) + idx + 1; - else - return idx; -} + #define lua_setuservalue(L, i) (luaL_checktype((L), -1, LUA_TTABLE), lua_setfenv((L), (i))) + + inline int lua_absindex(lua_State* L, int idx) + { + if (idx > LUA_REGISTRYINDEX && idx < 0) + return lua_gettop(L) + idx + 1; + else + return idx; + } -void lua_len (lua_State *L, int i); -lua_Integer luaL_len(lua_State *L, int i); + void lua_len(lua_State* L, int i); + lua_Integer luaL_len(lua_State* L, int i); #endif -/** casts the variant to its specific type before pushing it to the stack -@relates LuaType */ -void RMLUILUA_API PushVariant(lua_State* L, const Variant* var); + /** casts the variant to its specific type before pushing it to the stack + @relates LuaType */ + void RMLUILUA_API PushVariant(lua_State* L, const Variant* var); -/** Populate the variant based on the Lua value at the given index */ -void RMLUILUA_API GetVariant(lua_State* L, int index, Variant* variant); + /** Populate the variant based on the Lua value at the given index */ + void RMLUILUA_API GetVariant(lua_State* L, int index, Variant* variant); -// Converts index from 0-based to 1-based before pushing it to the stack -void RMLUILUA_API PushIndex(lua_State* L, int index); + // Converts index from 0-based to 1-based before pushing it to the stack + void RMLUILUA_API PushIndex(lua_State* L, int index); -// Returns 0-based index after retrieving from stack and converting from 1-based -// The index parameter refers to the position on the stack and is not affected -// by the conversion -int RMLUILUA_API GetIndex(lua_State* L, int index); + // Returns 0-based index after retrieving from stack and converting from 1-based + // The index parameter refers to the position on the stack and is not affected + // by the conversion + int RMLUILUA_API GetIndex(lua_State* L, int index); -//Helper function, so that the types don't have to define individual functions themselves -// to fill the Elements.As table -template -int CastFromElementTo(lua_State* L) -{ - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - LuaType::push(L,(ToType*)ele,false); - return 1; -} + // Helper function, so that the types don't have to define individual functions themselves + // to fill the Elements.As table + template + int CastFromElementTo(lua_State* L) + { + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + LuaType::push(L, (ToType*)ele, false); + return 1; + } -//Adds to the Element.As table the name of the type, and the function to use to cast -template -void AddTypeToElementAsTable(lua_State* L) -{ - int top = lua_gettop(L); - lua_getglobal(L,"Element"); - lua_getfield(L,-1,"As"); - if(!lua_isnoneornil(L,-1)) - { - lua_pushcfunction(L,CastFromElementTo); - lua_setfield(L,-2,GetTClassName()); - } - lua_settop(L,top); //pop "As" and "Element" -} + // Adds to the Element.As table the name of the type, and the function to use to cast + template + void AddTypeToElementAsTable(lua_State* L) + { + int top = lua_gettop(L); + lua_getglobal(L, "Element"); + lua_getfield(L, -1, "As"); + if (!lua_isnoneornil(L, -1)) + { + lua_pushcfunction(L, CastFromElementTo); + lua_setfield(L, -2, GetTClassName()); + } + lua_settop(L, top); // pop "As" and "Element" + } } // namespace Lua } // namespace Rml #endif diff --git a/Include/RmlUi/SVG/ElementSVG.h b/Include/RmlUi/SVG/ElementSVG.h index 43ca617f2..67614ac4d 100644 --- a/Include/RmlUi/SVG/ElementSVG.h +++ b/Include/RmlUi/SVG/ElementSVG.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,17 +29,18 @@ #ifndef RMLUI_SVG_ELEMENT_SVG_H #define RMLUI_SVG_ELEMENT_SVG_H -#include "../Core/Header.h" #include "../Core/Element.h" #include "../Core/Geometry.h" +#include "../Core/Header.h" #include "../Core/Texture.h" -namespace lunasvg { class Document; } +namespace lunasvg { +class Document; +} namespace Rml { -class RMLUICORE_API ElementSVG : public Element -{ +class RMLUICORE_API ElementSVG : public Element { public: RMLUI_RTTI_DefineWithParent(ElementSVG, Element) diff --git a/LICENSE.txt b/LICENSE.txt index 3e3102738..c5ce978ec 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,7 +1,7 @@ MIT License Copyright (c) 2008-2014 CodePoint Ltd, Shift Technology Ltd, and contributors -Copyright (c) 2019-2021 The RmlUi Team, and contributors +Copyright (c) 2019-2023 The RmlUi Team, and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/assets/LICENSE.txt b/Samples/assets/LICENSE.txt index dd4a9e2be..63ef813fa 100644 --- a/Samples/assets/LICENSE.txt +++ b/Samples/assets/LICENSE.txt @@ -34,7 +34,7 @@ with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, +fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The diff --git a/Samples/assets/demo.rml b/Samples/assets/demo.rml index f136db9bf..82f2e6ffb 100644 --- a/Samples/assets/demo.rml +++ b/Samples/assets/demo.rml @@ -7,15 +7,15 @@ { width: 300dp; height: 225dp; - + margin: auto; } - + div#title_bar div#icon { display: none; } - + div#content { text-align: left; diff --git a/Samples/assets/invader.rcss b/Samples/assets/invader.rcss index 4b1958d12..c2e237841 100644 --- a/Samples/assets/invader.rcss +++ b/Samples/assets/invader.rcss @@ -1,24 +1,24 @@ -@spritesheet theme +@spritesheet theme { src: invader.tga; - + /* For high dpi screens, designates the scaling it is intended to be shown at. */ - resolution: 1x; - + resolution: 1x; + /** - The following specifies a list of sprite names and associated rectangles into the image given above. - Any sprite given here can be specified in a decorator. Their names must be globally unique. - Rectangles are specified as: x y width height. With the origin assumed to be at the top left corner. + The following specifies a list of sprite names and associated rectangles into the image given above. + Any sprite given here can be specified in a decorator. Their names must be globally unique. + Rectangles are specified as: x y width height. With the origin assumed to be at the top left corner. */ title-bar-l: 147px 0px 82px 85px; title-bar-c: 229px 0px 1px 85px; title-bar-r: 231px 0px 15px 85px; - + /* huditems are vertically flipped titlebars */ huditem-l: 147px 55px 82px -55px; huditem-c: 229px 55px 1px -55px; huditem-r: 231px 55px 15px -55px; - + icon-help: 128px 152px 51px 39px; icon-invader: 179px 152px 51px 39px; icon-game: 230px 152px 51px 39px; @@ -27,7 +27,7 @@ icon-flag: 336px 191px 51px 39px; icon-lives: 383px 152px 51px 39px; icon-score: 434px 152px 51px 39px; - + window-tl: 0px 0px 133px 140px; window-t: 134px 0px 1px 140px; window-tr: 136px 0px 10px 140px; @@ -37,20 +37,20 @@ window-bl: 0px 140px 11px 11px; window-b: 11px 140px 1px 11px; window-br: 136px 140px 10px 11px; - + button: 247px 0px 159px 45px; button-hover: 247px 45px 159px 45px; button-active: 247px 90px 159px 45px; - + button-inner: 259px 19px 135px 1px; button-inner-hover: 259px 64px 135px 1px; button-inner-active: 259px 109px 135px 1px; - + text-l: 162px 192px 14px 31px; text-c: 176px 192px 1px 31px; textarea: 162px 193px 145px 31px; textarea-inner: 173px 206px 127px 10px; - + selectbox-tl: 281px 275px 11px 9px; selectbox-t: 292px 275px 1px 9px; selectbox-tr: 294px 275px 11px 9px; @@ -59,42 +59,42 @@ selectbox-bl: 281px 285px 11px 11px; selectbox-b: 292px 285px 1px 11px; selectbox-br: 294px 285px 11px 11px; - + selectvalue: 162px 192px 145px 37px; selectvalue-hover: 162px 230px 145px 37px; selectarrow: 307px 192px 30px 37px; selectarrow-hover: 307px 230px 30px 37px; selectarrow-active: 307px 268px 30px 37px; - + radio: 407px 0px 30px 30px; radio-hover: 437px 0px 30px 30px; radio-active: 467px 0px 30px 30px; radio-checked: 407px 30px 30px 30px; radio-checked-hover: 437px 30px 30px 30px; radio-checked-active: 467px 30px 30px 30px; - + checkbox: 407px 60px 30px 30px; checkbox-hover: 437px 60px 30px 30px; checkbox-active: 467px 60px 30px 30px; checkbox-checked: 407px 90px 30px 30px; checkbox-checked-hover: 437px 90px 30px 30px; checkbox-checked-active: 467px 90px 30px 30px; - + tableheader-l: 127px 192px 16px 31px; tableheader-c: 143px 192px 2px 31px; tableheader-r: 145px 192px 15px 31px; - + expand: 3px 232px 17px 17px; expand-hover: 21px 232px 17px 17px; expand-active: 39px 232px 17px 17px; expand-collapsed: 3px 250px 17px 17px; expand-collapsed-hover: 21px 250px 17px 17px; expand-collapsed-active: 39px 250px 17px 17px; - + slidertrack-t: 70px 199px 27px 2px; slidertrack-c: 70px 201px 27px 1px; slidertrack-b: 70px 202px 27px 2px; - + sliderbar-t: 56px 152px 23px 23px; sliderbar-c: 56px 175px 23px 1px; sliderbar-b: 56px 176px 23px 22px; @@ -104,15 +104,15 @@ sliderbar-active-t: 104px 152px 23px 23px; sliderbar-active-c: 104px 175px 23px 1px; sliderbar-active-b: 104px 176px 23px 22px; - + sliderarrowdec: 0px 152px 27px 24px; sliderarrowdec-hover: 0px 177px 27px 24px; sliderarrowdec-active: 0px 202px 27px 24px; - + sliderarrowinc: 28px 152px 27px 24px; sliderarrowinc-hover: 28px 177px 27px 24px; sliderarrowinc-active: 28px 202px 27px 24px; - + range-track: 219px 194px 3px 32px; range-track-inner: 220px 204px 1px 14px; range-bar: 127px 191px 34px 32px; @@ -122,7 +122,7 @@ range-inc: 3px 250px 17px 17px; range-inc-hover: 21px 250px 17px 17px; range-inc-active: 39px 250px 17px 17px; - + progress-l: 103px 267px 13px 34px; progress-c: 116px 267px 54px 34px; progress-r: 170px 267px 13px 34px; @@ -146,10 +146,10 @@ body.window { padding-top: 43dp; padding-bottom: 20dp; - + min-width: 250dp; max-width: 800dp; - + min-height: 135dp; max-height: 700dp; } @@ -161,7 +161,7 @@ div#title_bar position: absolute; top: 7dp; left: 0; - + text-align: left; vertical-align: bottom; } @@ -171,7 +171,7 @@ div#title_bar div#icon position: absolute; left: 15dp; top: -4dp; - + width: 51dp; height: 39dp; } @@ -183,13 +183,13 @@ div#title_bar span padding-right: 25dp; padding-top: 18dp; padding-bottom: 43dp; - + vertical-align: top; - + line-height: 24dp; font-size: 20dp; font-weight: bold; - + font-effect: glow(1dp black); decorator: tiled-horizontal( title-bar-l, title-bar-c, title-bar-r ); } @@ -199,9 +199,9 @@ div#window width: auto; height: 100%; padding: 10dp 15dp; - + decorator: tiled-box( - window-tl, window-t, window-tr, + window-tl, window-t, window-tr, window-l, window-c, window-r, window-bl, window-b, window-br ); @@ -334,7 +334,7 @@ table input.text background-color: white; font-size: 15dp; - + decorator: none; } @@ -350,7 +350,7 @@ select selectvalue { width: auto; margin-right: 30dp; - + height: 25dp; padding: 12dp 10dp 0dp 10dp; @@ -361,7 +361,7 @@ select selectarrow { width: 30dp; height: 37dp; - + decorator: image( selectarrow ); } @@ -389,7 +389,7 @@ select selectbox, tbody { decorator: tiled-box( - selectbox-tl, selectbox-t, selectbox-tr, + selectbox-tl, selectbox-t, selectbox-tr, selectbox-l, selectbox-c, auto, /* auto mirrors left */ selectbox-bl, selectbox-b, selectbox-br ); @@ -550,11 +550,11 @@ tbody tr { expand { display: block; - + margin: 1dp 0 1dp 5dp; height: 17dp; width: 17dp; - + decorator: image( expand ); } @@ -662,9 +662,9 @@ textarea scrollbarvertical margin: 10dp 0 4dp 0; width: 12dp; } -textarea scrollbarvertical slidertrack -{ - decorator: none; +textarea scrollbarvertical slidertrack +{ + decorator: none; } textarea scrollbarvertical sliderbar { diff --git a/Samples/basic/animation/data/animation.rml b/Samples/basic/animation/data/animation.rml index 9d5d58493..d47765822 100644 --- a/Samples/basic/animation/data/animation.rml +++ b/Samples/basic/animation/data/animation.rml @@ -39,8 +39,8 @@ display: inline-block; width: 25dp; } - - #start_game + + #start_game { opacity: 0.8; transform: rotate(370deg) translateX(100dp) scale(1.2); @@ -62,7 +62,7 @@ #high_scores { margin-left: -100dp; } - + @keyframes fadeout { from { opacity: 1; @@ -98,12 +98,12 @@ .textalign { animation: 1.4s textalign; } - + #exit { transform: rotate(45deg); transform-origin: 50% 50% 0; } - + div.container { margin-top: 15dp; @@ -121,8 +121,8 @@ background-color: #c66; } div.plain:hover { background-color: #ddb700; } - - + + /* -- TRANSFORM TESTS */ #generic { /* Note the translateX vs translateY in animation target, and rotateZ vs rotate3d, scaleX vs scaleY. @@ -134,11 +134,11 @@ transform: rotate(45deg); } #decomposition { - /* To interpolate the rotate3d transforms, we need to decompose the matrix, + /* To interpolate the rotate3d transforms, we need to decompose the matrix, see the element info in the debugger for the resulting matrix. */ transform: translateX(100dp) rotate3d(1.0, 0, 1.0, 0deg); } - + /* -- MIXED UNITS TESTS */ #abs_rel { margin: 0; @@ -161,7 +161,7 @@ /*transition: padding-left background-color transform 0.8s quadratic-out 1.0;*/ padding-left: 60dp; transform: scale(1.5); - } + } #transition_class { margin-left: 50dp; transition: all 0.5s cubic-out; @@ -171,9 +171,9 @@ margin-left: -50dp; background-color: #dd3; } - + /* -- KEYFRAMES TESTS */ - @keyframes hello-world + @keyframes hello-world { 25% { transform: rotate(180deg); @@ -205,7 +205,7 @@ 50% { background-color: #9d9; } - to { + to { background-color: #f9f; width: 100%; } @@ -225,11 +225,11 @@ top: 110dp; left: 0; height: 55dp; } - #performance + #performance { position: absolute; - bottom: 0; - height: 30%; + bottom: 0; + height: 30%; width: 20%; left: -100dp; transform: scale(0.5) rotate(-90deg); diff --git a/Samples/basic/animation/src/main.cpp b/Samples/basic/animation/src/main.cpp index fa705859b..6ca3f2cae 100644 --- a/Samples/basic/animation/src/main.cpp +++ b/Samples/basic/animation/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,7 +35,7 @@ class DemoWindow { public: - DemoWindow(const Rml::String &title, Rml::Context *context) + DemoWindow(const Rml::String& title, Rml::Context* context) { using namespace Rml; document = context->LoadDocument("basic/animation/data/animation.rml"); @@ -46,15 +46,15 @@ class DemoWindow { // Button fun { auto el = document->GetElementById("start_game"); - auto p1 = Transform::MakeProperty({ Transforms::Rotate2D{10.f}, Transforms::TranslateX{100.f} }); - auto p2 = Transform::MakeProperty({ Transforms::Scale2D{3.f} }); - el->Animate("transform", p1, 1.8f, Tween{ Tween::Elastic, Tween::InOut }, -1, true); - el->AddAnimationKey("transform", p2, 1.3f, Tween{ Tween::Elastic, Tween::InOut }); + auto p1 = Transform::MakeProperty({Transforms::Rotate2D{10.f}, Transforms::TranslateX{100.f}}); + auto p2 = Transform::MakeProperty({Transforms::Scale2D{3.f}}); + el->Animate("transform", p1, 1.8f, Tween{Tween::Elastic, Tween::InOut}, -1, true); + el->AddAnimationKey("transform", p2, 1.3f, Tween{Tween::Elastic, Tween::InOut}); } { auto el = document->GetElementById("high_scores"); - el->Animate("margin-left", Property(0.f, Property::PX), 0.3f, Tween{ Tween::Sine, Tween::In }, 10, true, 1.f); - el->AddAnimationKey("margin-left", Property(100.f, Property::PX), 3.0f, Tween{ Tween::Circular, Tween::Out }); + el->Animate("margin-left", Property(0.f, Property::PX), 0.3f, Tween{Tween::Sine, Tween::In}, 10, true, 1.f); + el->AddAnimationKey("margin-left", Property(100.f, Property::PX), 3.0f, Tween{Tween::Circular, Tween::Out}); } { auto el = document->GetElementById("options"); @@ -68,24 +68,25 @@ class DemoWindow { auto el = document->GetElementById("exit"); PropertyDictionary pd; StyleSheetSpecification::ParsePropertyDeclaration(pd, "transform", "translate(200px, 200px) rotate(1215deg)"); - el->Animate("transform", *pd.GetProperty(PropertyId::Transform), 3.f, Tween{ Tween::Bounce, Tween::Out }, -1); + el->Animate("transform", *pd.GetProperty(PropertyId::Transform), 3.f, Tween{Tween::Bounce, Tween::Out}, -1); } // Transform tests { auto el = document->GetElementById("generic"); - auto p = Transform::MakeProperty({ Transforms::TranslateY{50, Property::PX}, Transforms::Rotate3D{0, 0, 1, -90, Property::DEG}, Transforms::ScaleY{0.8f} }); + auto p = Transform::MakeProperty( + {Transforms::TranslateY{50, Property::PX}, Transforms::Rotate3D{0, 0, 1, -90, Property::DEG}, Transforms::ScaleY{0.8f}}); el->Animate("transform", p, 1.5f, Tween{Tween::Sine, Tween::InOut}, -1, true); } { auto el = document->GetElementById("combine"); - auto p = Transform::MakeProperty({ Transforms::Translate2D{50, 50, Property::PX}, Transforms::Rotate2D(1215) }); + auto p = Transform::MakeProperty({Transforms::Translate2D{50, 50, Property::PX}, Transforms::Rotate2D(1215)}); el->Animate("transform", p, 8.0f, Tween{}, -1, true); } { auto el = document->GetElementById("decomposition"); - auto p = Transform::MakeProperty({ Transforms::TranslateY{50, Property::PX}, Transforms::Rotate3D{0.8f, 0, 1, 110, Property::DEG} }); - el->Animate("transform", p, 1.3f, Tween{ Tween::Quadratic, Tween::InOut }, -1, true); + auto p = Transform::MakeProperty({Transforms::TranslateY{50, Property::PX}, Transforms::Rotate3D{0.8f, 0, 1, 110, Property::DEG}}); + el->Animate("transform", p, 1.3f, Tween{Tween::Quadratic, Tween::InOut}, -1, true); } // Mixed units tests @@ -95,13 +96,13 @@ class DemoWindow { } { auto el = document->GetElementById("abs_rel_transform"); - auto p = Transform::MakeProperty({ Transforms::TranslateX{0, Property::PX} }); + auto p = Transform::MakeProperty({Transforms::TranslateX{0, Property::PX}}); el->Animate("transform", p, 1.5f, Tween{}, -1, true); } { auto el = document->GetElementById("animation_event"); - el->Animate("top", Property(Math::RandomReal(250.f), Property::PX), 1.5f, Tween{ Tween::Cubic, Tween::InOut }); - el->Animate("left", Property(Math::RandomReal(250.f), Property::PX), 1.5f, Tween{ Tween::Cubic, Tween::InOut }); + el->Animate("top", Property(Math::RandomReal(250.f), Property::PX), 1.5f, Tween{Tween::Cubic, Tween::InOut}); + el->Animate("left", Property(Math::RandomReal(250.f), Property::PX), 1.5f, Tween{Tween::Cubic, Tween::InOut}); } document->Show(); @@ -144,12 +145,10 @@ class DemoWindow { } } - Rml::ElementDocument * GetDocument() { - return document; - } + Rml::ElementDocument* GetDocument() { return document; } private: - Rml::ElementDocument *document; + Rml::ElementDocument* document; double t_prev_fade = 0; }; @@ -158,8 +157,7 @@ bool run_loop = true; bool single_loop = false; int nudge = 0; -class Event : public Rml::EventListener -{ +class Event : public Rml::EventListener { public: Event(const Rml::String& value) : value(value) {} @@ -174,7 +172,7 @@ class Event : public Rml::EventListener { case EventId::Keydown: { - Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); + Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter("key_identifier", 0); if (key_identifier == Rml::Input::KI_SPACE) { @@ -200,23 +198,27 @@ class Event : public Rml::EventListener else if (key_identifier == Rml::Input::KI_LEFT) { auto el = context->GetRootElement()->GetElementById("keyevent_response"); - if (el) el->Animate("left", Property{ -200.f, Property::DP }, 0.5, Tween{ Tween::Cubic }); + if (el) + el->Animate("left", Property{-200.f, Property::DP}, 0.5, Tween{Tween::Cubic}); } else if (key_identifier == Rml::Input::KI_RIGHT) { auto el = context->GetRootElement()->GetElementById("keyevent_response"); - if (el) el->Animate("left", Property{ 200.f, Property::DP }, 0.5, Tween{ Tween::Cubic }); + if (el) + el->Animate("left", Property{200.f, Property::DP}, 0.5, Tween{Tween::Cubic}); } else if (key_identifier == Rml::Input::KI_UP) { auto el = context->GetRootElement()->GetElementById("keyevent_response"); - auto offset_right = Property{ 200.f, Property::DP }; - if (el) el->Animate("left", Property{ 0.f, Property::PX }, 0.5, Tween{ Tween::Cubic }, 1, true, 0, &offset_right); + auto offset_right = Property{200.f, Property::DP}; + if (el) + el->Animate("left", Property{0.f, Property::PX}, 0.5, Tween{Tween::Cubic}, 1, true, 0, &offset_right); } else if (key_identifier == Rml::Input::KI_DOWN) { auto el = context->GetRootElement()->GetElementById("keyevent_response"); - if (el) el->Animate("left", Property{ 0.f, Property::PX }, 0.5, Tween{ Tween::Cubic }); + if (el) + el->Animate("left", Property{0.f, Property::PX}, 0.5, Tween{Tween::Cubic}); } } break; @@ -236,14 +238,13 @@ class Event : public Rml::EventListener auto el = event.GetTargetElement(); if (el->GetId() == "animation_event") { - el->Animate("top", Property(Math::RandomReal(200.f), Property::PX), 1.2f, Tween{ Tween::Cubic, Tween::InOut }); - el->Animate("left", Property(Math::RandomReal(100.f), Property::PERCENT), 0.8f, Tween{ Tween::Cubic, Tween::InOut }); + el->Animate("top", Property(Math::RandomReal(200.f), Property::PX), 1.2f, Tween{Tween::Cubic, Tween::InOut}); + el->Animate("left", Property(Math::RandomReal(100.f), Property::PERCENT), 0.8f, Tween{Tween::Cubic, Tween::InOut}); } } break; - default: - break; + default: break; } } diff --git a/Samples/basic/benchmark/data/benchmark.rml b/Samples/basic/benchmark/data/benchmark.rml index 3bdd48f7e..31a2922a9 100644 --- a/Samples/basic/benchmark/data/benchmark.rml +++ b/Samples/basic/benchmark/data/benchmark.rml @@ -12,7 +12,7 @@ max-width: 2000dp; max-height: 2000dp; } - #fps + #fps { position: absolute; top: 55dp; @@ -20,7 +20,7 @@ font-size: 0.85em; text-align: left; } - #performance + #performance { width: 800dp; height: 300dp; diff --git a/Samples/basic/benchmark/src/main.cpp b/Samples/basic/benchmark/src/main.cpp index c451dd8fc..6a5ef0cb3 100644 --- a/Samples/basic/benchmark/src/main.cpp +++ b/Samples/basic/benchmark/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,10 +31,9 @@ #include #include -class DemoWindow -{ +class DemoWindow { public: - DemoWindow(const Rml::String &title, Rml::Context *context) + DemoWindow(const Rml::String& title, Rml::Context* context) { using namespace Rml; document = context->LoadDocument("basic/benchmark/data/benchmark.rml"); @@ -78,11 +77,7 @@ class DemoWindow )", - index, - route, - max, - value - ); + index, route, max, value); rml += rml_row; } @@ -92,7 +87,8 @@ class DemoWindow class SimpleEventListener : public Rml::EventListener { public: - void ProcessEvent(Rml::Event& event) override { + void ProcessEvent(Rml::Event& event) override + { static int i = 0; event.GetTargetElement()->SetProperty("background-color", i++ % 2 == 0 ? "green" : "orange"); } @@ -106,12 +102,10 @@ class DemoWindow } } - Rml::ElementDocument * GetDocument() { - return document; - } + Rml::ElementDocument* GetDocument() { return document; } private: - Rml::ElementDocument *document; + Rml::ElementDocument* document; }; bool run_loop = true; @@ -119,8 +113,7 @@ bool single_loop = true; bool run_update = true; bool single_update = true; -class Event : public Rml::EventListener -{ +class Event : public Rml::EventListener { public: Event(const Rml::String& value) : value(value) {} @@ -128,12 +121,12 @@ class Event : public Rml::EventListener { using namespace Rml; - if(value == "exit") + if (value == "exit") Backend::RequestExit(); if (event == "keydown") { - auto key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter< int >("key_identifier", 0); + auto key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter("key_identifier", 0); if (key_identifier == Rml::Input::KI_SPACE) { @@ -166,15 +159,10 @@ class Event : public Rml::EventListener Rml::String value; }; -class EventInstancer : public Rml::EventListenerInstancer -{ +class EventInstancer : public Rml::EventListenerInstancer { public: - /// Instances a new event handle for Invaders. - Rml::EventListener* InstanceEventListener(const Rml::String& value, Rml::Element* /*element*/) override - { - return new Event(value); - } + Rml::EventListener* InstanceEventListener(const Rml::String& value, Rml::Element* /*element*/) override { return new Event(value); } }; #if defined RMLUI_PLATFORM_WIN32 diff --git a/Samples/basic/bitmapfont/data/LICENSE.txt b/Samples/basic/bitmapfont/data/LICENSE.txt index 8c96c298e..91ec6bd95 100644 --- a/Samples/basic/bitmapfont/data/LICENSE.txt +++ b/Samples/basic/bitmapfont/data/LICENSE.txt @@ -46,4 +46,4 @@ TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/Samples/basic/bitmapfont/src/FontEngineBitmap.cpp b/Samples/basic/bitmapfont/src/FontEngineBitmap.cpp index 053fe5f4f..8637ee798 100644 --- a/Samples/basic/bitmapfont/src/FontEngineBitmap.cpp +++ b/Samples/basic/bitmapfont/src/FontEngineBitmap.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,109 +26,104 @@ * */ -#include -#include -#include #include "FontEngineBitmap.h" +#include +#include +#include +#include +#include -namespace FontProviderBitmap -{ - static Rml::Vector> fonts; +namespace FontProviderBitmap { +static Rml::Vector> fonts; +void Initialise() {} - void Initialise() - { - } +void Shutdown() +{ + fonts.clear(); +} - void Shutdown() - { - fonts.clear(); - } +bool LoadFontFace(const String& file_name) +{ + // Load the xml meta file into memory + Rml::UniquePtr data; + size_t length = 0; - bool LoadFontFace(const String& file_name) { - // Load the xml meta file into memory - Rml::UniquePtr data; - size_t length = 0; + auto file_interface = Rml::GetFileInterface(); + auto handle = file_interface->Open(file_name); + if (!handle) + return false; - { - auto file_interface = Rml::GetFileInterface(); - auto handle = file_interface->Open(file_name); - if (!handle) - return false; + length = file_interface->Length(handle); - length = file_interface->Length(handle); - - data.reset(new byte[length]); + data.reset(new byte[length]); - size_t read_length = file_interface->Read(data.get(), length, handle); + size_t read_length = file_interface->Read(data.get(), length, handle); - file_interface->Close(handle); + file_interface->Close(handle); - if (read_length != length || !data) - return false; - } + if (read_length != length || !data) + return false; + } - // Parse the xml font description - FontParserBitmap parser; + // Parse the xml font description + FontParserBitmap parser; - { - auto stream = Rml::MakeUnique(data.get(), length); - stream->SetSourceURL(file_name); + { + auto stream = Rml::MakeUnique(data.get(), length); + stream->SetSourceURL(file_name); - parser.Parse(stream.get()); + parser.Parse(stream.get()); - if (parser.family.empty() || parser.glyphs.empty() || parser.texture_name.empty() || parser.metrics.size == 0) - return false; + if (parser.family.empty() || parser.glyphs.empty() || parser.texture_name.empty() || parser.metrics.size == 0) + return false; - // Fill the remaining metrics - parser.metrics.underline_position = 3.f; - parser.metrics.underline_thickness = 1.f; - } + // Fill the remaining metrics + parser.metrics.underline_position = 3.f; + parser.metrics.underline_thickness = 1.f; + } - Texture texture; - texture.Set(parser.texture_name, file_name); + Texture texture; + texture.Set(parser.texture_name, file_name); - // Construct and add the font face - fonts.push_back( - Rml::MakeUnique( - parser.family, parser.style, parser.weight, parser.metrics, texture, parser.texture_dimensions, std::move(parser.glyphs), std::move(parser.kerning) - )); + // Construct and add the font face + fonts.push_back(Rml::MakeUnique(parser.family, parser.style, parser.weight, parser.metrics, texture, parser.texture_dimensions, + std::move(parser.glyphs), std::move(parser.kerning))); - return true; - } + return true; +} - FontFaceBitmap* GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size) +FontFaceBitmap* GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size) +{ + FontFaceBitmap* best_match = nullptr; + int best_score = 0; + + // Normally, we'd want to only match the font family exactly, but for this demo we create a very lenient heuristic. + for (const auto& font : fonts) { - FontFaceBitmap* best_match = nullptr; - int best_score = 0; + int score = 1; + if (font->GetFamily() == family) + score += 100; + + score += 10 - std::min(10, std::abs(font->GetMetrics().size - size)); - // Normally, we'd want to only match the font family exactly, but for this demo we create a very lenient heuristic. - for (const auto& font : fonts) + if (font->GetStyle() == style) + score += 2; + if (font->GetWeight() == weight) + score += 1; + + if (score > best_score) { - int score = 1; - if (font->GetFamily() == family) - score += 100; - - score += 10 - std::min(10, std::abs(font->GetMetrics().size - size)); - - if (font->GetStyle() == style) - score += 2; - if (font->GetWeight() == weight) - score += 1; - - if (score > best_score) - { - best_match = font.get(); - best_score = score; - } + best_match = font.get(); + best_score = score; } - - return best_match; } + return best_match; } +} // namespace FontProviderBitmap FontFaceBitmap::FontFaceBitmap(String family, FontStyle style, FontWeight weight, FontMetrics metrics, Texture texture, Vector2f texture_dimensions, FontGlyphs&& glyphs, FontKerning&& kerning) : @@ -200,16 +195,8 @@ int FontFaceBitmap::GenerateString(const String& string, const Vector2f& string_ Vector2f uv_top_left = glyph.position / texture_dimensions; Vector2f uv_bottom_right = (glyph.position + glyph.dimension) / texture_dimensions; - Rml::GeometryUtilities::GenerateQuad( - &vertices[0] + (vertices.size() - 4), - &indices[0] + (indices.size() - 6), - Vector2f(position + glyph.offset).Round(), - glyph.dimension, - colour, - uv_top_left, - uv_bottom_right, - (int)vertices.size() - 4 - ); + Rml::GeometryUtilities::GenerateQuad(&vertices[0] + (vertices.size() - 4), &indices[0] + (indices.size() - 6), + Vector2f(position + glyph.offset).Round(), glyph.dimension, colour, uv_top_left, uv_bottom_right, (int)vertices.size() - 4); width += glyph.advance; position.x += glyph.advance; @@ -231,20 +218,13 @@ int FontFaceBitmap::GetKerning(Character left, Character right) const return 0; } +FontParserBitmap::~FontParserBitmap() {} - - - -FontParserBitmap::~FontParserBitmap() -{ -} - -// Called when the parser finds the beginning of an element tag. void FontParserBitmap::HandleElementStart(const String& name, const Rml::XMLAttributes& attributes) { if (name == "info") { - family = Rml::StringUtilities::ToLower( Get(attributes, "face", String()) ); + family = Rml::StringUtilities::ToLower(Get(attributes, "face", String())); metrics.size = Get(attributes, "size", 0); style = Get(attributes, "italic", 0) == 1 ? FontStyle::Italic : FontStyle::Normal; @@ -262,7 +242,7 @@ void FontParserBitmap::HandleElementStart(const String& name, const Rml::XMLAttr else if (name == "page") { int id = Get(attributes, "id", -1); - if(id != 0) + if (id != 0) { Rml::Log::Message(Rml::Log::LT_WARNING, "Only single font textures are supported in Bitmap Font Engine"); return; @@ -303,15 +283,6 @@ void FontParserBitmap::HandleElementStart(const String& name, const Rml::XMLAttr } } -// Called when the parser finds the end of an element tag. -void FontParserBitmap::HandleElementEnd(const String& RMLUI_UNUSED_PARAMETER(name)) -{ - RMLUI_UNUSED(name); -} +void FontParserBitmap::HandleElementEnd(const String& /*name*/) {} -// Called when the parser encounters data. -void FontParserBitmap::HandleData(const String& RMLUI_UNUSED_PARAMETER(data), Rml::XMLDataType RMLUI_UNUSED_PARAMETER(type)) -{ - RMLUI_UNUSED(data); - RMLUI_UNUSED(type); -} +void FontParserBitmap::HandleData(const String& /*data*/, Rml::XMLDataType /*type*/) {} diff --git a/Samples/basic/bitmapfont/src/FontEngineBitmap.h b/Samples/basic/bitmapfont/src/FontEngineBitmap.h index 2f9683175..6de35e8d8 100644 --- a/Samples/basic/bitmapfont/src/FontEngineBitmap.h +++ b/Samples/basic/bitmapfont/src/FontEngineBitmap.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,26 +29,26 @@ #ifndef FONTENGINEBITMAP_H #define FONTENGINEBITMAP_H -#include -#include #include "FontEngineInterfaceBitmap.h" +#include +#include +#include +#include class FontFaceBitmap; -namespace FontProviderBitmap -{ - void Initialise(); - void Shutdown(); - bool LoadFontFace(const String& file_name); - FontFaceBitmap* GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size); -} - +namespace FontProviderBitmap { +void Initialise(); +void Shutdown(); +bool LoadFontFace(const String& file_name); +FontFaceBitmap* GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size); +} // namespace FontProviderBitmap struct BitmapGlyph { int advance = 0; - Vector2f offset = { 0, 0 }; - Vector2f position = { 0, 0 }; - Vector2f dimension = { 0, 0 }; + Vector2f offset = {0, 0}; + Vector2f position = {0, 0}; + Vector2f dimension = {0, 0}; }; // A mapping of characters to their glyphs. @@ -57,7 +57,6 @@ using FontGlyphs = Rml::UnorderedMap; // Mapping of combined (left, right) character to kerning in pixels. using FontKerning = Rml::UnorderedMap; - class FontFaceBitmap { public: FontFaceBitmap(String family, FontStyle style, FontWeight weight, FontMetrics metrics, Texture texture, Vector2f texture_dimensions, @@ -69,9 +68,8 @@ class FontFaceBitmap { // Generate the string geometry, returning its width. int GenerateString(const String& string, const Vector2f& position, const Colourb& colour, GeometryList& geometry); - const FontMetrics& GetMetrics() const { return metrics; } - + const String& GetFamily() const { return family; } FontStyle GetStyle() const { return style; } FontWeight GetWeight() const { return weight; } @@ -92,13 +90,11 @@ class FontFaceBitmap { FontKerning kerning; }; - /* - Parses the font meta data from an xml file. + Parses the font meta data from an xml file. */ -class FontParserBitmap : public Rml::BaseXMLParser -{ +class FontParserBitmap : public Rml::BaseXMLParser { public: FontParserBitmap() {} virtual ~FontParserBitmap(); @@ -115,12 +111,11 @@ class FontParserBitmap : public Rml::BaseXMLParser FontWeight weight = FontWeight::Normal; String texture_name; - Vector2f texture_dimensions = { 0, 0 }; + Vector2f texture_dimensions = {0, 0}; FontMetrics metrics = {}; FontGlyphs glyphs; FontKerning kerning; }; - #endif diff --git a/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.cpp b/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.cpp index 14805f91b..0e7a8d535 100644 --- a/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.cpp +++ b/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,9 +26,9 @@ * */ -#include #include "FontEngineInterfaceBitmap.h" #include "FontEngineBitmap.h" +#include FontEngineInterfaceBitmap::FontEngineInterfaceBitmap() { @@ -45,7 +45,8 @@ bool FontEngineInterfaceBitmap::LoadFontFace(const String& file_name, bool /*fal return FontProviderBitmap::LoadFontFace(file_name); } -bool FontEngineInterfaceBitmap::LoadFontFace(const byte* /*data*/, int /*data_size*/, const String& font_family, FontStyle /*style*/, FontWeight /*weight*/, bool /*fallback_face*/) +bool FontEngineInterfaceBitmap::LoadFontFace(const byte* /*data*/, int /*data_size*/, const String& font_family, FontStyle /*style*/, + FontWeight /*weight*/, bool /*fallback_face*/) { // We return 'true' here to allow the debugger to continue loading, but we will use our own fonts when it asks for a handle. // The debugger might look a bit off with our own fonts, but hey it works. diff --git a/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.h b/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.h index eda8677a6..d06fa9ee3 100644 --- a/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.h +++ b/Samples/basic/bitmapfont/src/FontEngineInterfaceBitmap.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,30 +29,28 @@ #ifndef FONTENGINEINTERFACEBITMAP_H #define FONTENGINEINTERFACEBITMAP_H -#include #include #include +#include -using Rml::FontFaceHandle; using Rml::FontEffectsHandle; +using Rml::FontFaceHandle; -using Rml::Vector2i; -using Rml::Vector2f; +using Rml::byte; +using Rml::Character; using Rml::Colourb; -using Rml::Texture; using Rml::String; -using Rml::Character; +using Rml::Texture; +using Rml::Vector2f; +using Rml::Vector2i; using Rml::Style::FontStyle; using Rml::Style::FontWeight; -using Rml::byte; using Rml::FontEffectList; -using Rml::GeometryList; using Rml::FontMetrics; +using Rml::GeometryList; - -class FontEngineInterfaceBitmap : public Rml::FontEngineInterface -{ +class FontEngineInterfaceBitmap : public Rml::FontEngineInterface { public: FontEngineInterfaceBitmap(); virtual ~FontEngineInterfaceBitmap(); @@ -64,7 +62,7 @@ class FontEngineInterfaceBitmap : public Rml::FontEngineInterface /// @param[in] data A pointer to the data. bool LoadFontFace(const byte* data, int data_size, const String& family, FontStyle style, FontWeight weight, bool fallback_face) override; - /// Called by RmlUi when a font configuration is resolved for an element. Should return a handle that + /// Called by RmlUi when a font configuration is resolved for an element. Should return a handle that /// can later be used to resolve properties of the face, and generate string geometry to be rendered. FontFaceHandle GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size) override; @@ -85,6 +83,4 @@ class FontEngineInterfaceBitmap : public Rml::FontEngineInterface int GetVersion(FontFaceHandle handle) override; }; - - #endif diff --git a/Samples/basic/bitmapfont/src/main.cpp b/Samples/basic/bitmapfont/src/main.cpp index 8cebf277a..ecf2967c6 100644 --- a/Samples/basic/bitmapfont/src/main.cpp +++ b/Samples/basic/bitmapfont/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,10 +34,10 @@ /* - This demo shows how to create a custom bitmap font engine implementation. - - It should work even when RmlUi is compiled without the default font engine (see CMake flag 'NO_FONT_INTERFACE_DEFAULT'). - See the interface in 'FontEngineInterfaceBitmap.h' and the implementation in 'FontEngineBitmap.h'. + This demo shows how to create a custom bitmap font engine implementation. + + It should work even when RmlUi is compiled without the default font engine (see CMake flag 'NO_FONT_INTERFACE_DEFAULT'). + See the interface in 'FontEngineInterfaceBitmap.h' and the implementation in 'FontEngineBitmap.h'. */ @@ -48,7 +48,7 @@ int APIENTRY WinMain(HINSTANCE /*instance_handle*/, HINSTANCE /*previous_instanc int main(int /*argc*/, char** /*argv*/) #endif { - int window_width = 1024; + int window_width = 1024; int window_height = 768; // Initializes the shell which provides common functionality used by the included samples. @@ -85,7 +85,7 @@ int main(int /*argc*/, char** /*argv*/) Rml::Debugger::Initialise(context); - // Load bitmap font + // Load bitmap font if (!Rml::LoadFontFace("basic/bitmapfont/data/Comfortaa_Regular_22.fnt")) { Rml::Shutdown(); @@ -95,7 +95,7 @@ int main(int /*argc*/, char** /*argv*/) } // Load and show the demo document. - if (Rml::ElementDocument * document = context->LoadDocument("basic/bitmapfont/data/bitmapfont.rml")) + if (Rml::ElementDocument* document = context->LoadDocument("basic/bitmapfont/data/bitmapfont.rml")) { if (auto el = document->GetElementById("title")) el->SetInnerRML("Bitmap font"); diff --git a/Samples/basic/customlog/src/SystemInterface.cpp b/Samples/basic/customlog/src/SystemInterface.cpp index 205500d6c..904659b7c 100644 --- a/Samples/basic/customlog/src/SystemInterface.cpp +++ b/Samples/basic/customlog/src/SystemInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,7 +33,7 @@ #include #include #ifdef RMLUI_PLATFORM_WIN32 -#include + #include #endif SystemInterface::SystemInterface() @@ -47,7 +47,6 @@ SystemInterface::~SystemInterface() fclose(fp); } -// Get the number of seconds elapsed since the start of the application. double SystemInterface::GetElapsedTime() { static const auto start = std::chrono::steady_clock::now(); @@ -64,18 +63,12 @@ bool SystemInterface::LogMessage(Rml::Log::Type type, const Rml::String& message const char* prefix; switch (type) { - case Rml::Log::LT_ERROR: - case Rml::Log::LT_ASSERT: - prefix = "-!-"; - break; + case Rml::Log::LT_ERROR: + case Rml::Log::LT_ASSERT: prefix = "-!-"; break; - case Rml::Log::LT_WARNING: - prefix = "-*-"; - break; + case Rml::Log::LT_WARNING: prefix = "-*-"; break; - default: - prefix = "---"; - break; + default: prefix = "---"; break; } // Print the message and timestamp to file, and force a write in case of a crash. diff --git a/Samples/basic/customlog/src/SystemInterface.h b/Samples/basic/customlog/src/SystemInterface.h index 68486fd04..7acabdba8 100644 --- a/Samples/basic/customlog/src/SystemInterface.h +++ b/Samples/basic/customlog/src/SystemInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,12 +32,11 @@ #include /** - Sample custom RmlUi system interface for writing log messages to file. - @author Lloyd Weehuizen + Sample custom RmlUi system interface for writing log messages to file. + @author Lloyd Weehuizen */ -class SystemInterface : public Rml::SystemInterface -{ +class SystemInterface : public Rml::SystemInterface { public: SystemInterface(); virtual ~SystemInterface(); diff --git a/Samples/basic/customlog/src/main.cpp b/Samples/basic/customlog/src/main.cpp index 5b03f743a..c30c65eb0 100644 --- a/Samples/basic/customlog/src/main.cpp +++ b/Samples/basic/customlog/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -57,7 +57,6 @@ int main(int /*argc*/, char** /*argv*/) Rml::SetSystemInterface(Backend::GetSystemInterface()); Rml::SetRenderInterface(Backend::GetRenderInterface()); - // Initialize our custom system interface to write the log messages to file. SystemInterface system_interface; Rml::SetSystemInterface(&system_interface); diff --git a/Samples/basic/databinding/data/databinding.rml b/Samples/basic/databinding/data/databinding.rml index b183edd22..f96226982 100644 --- a/Samples/basic/databinding/data/databinding.rml +++ b/Samples/basic/databinding/data/databinding.rml @@ -19,8 +19,8 @@ div#title_bar div#icon display: none; } div#content -{ - position: relative; +{ + position: relative; } tabset { @@ -42,11 +42,11 @@ tab width: 100dp; padding: 0 20dp; line-height: 40dp; - + font-size: 16dp; color: #ddd; text-align: center; - + decorator: tiled-horizontal( tableheader-l, tableheader-c, tableheader-r ); image-color: #cffc; } @@ -87,7 +87,7 @@ p.title text-align: center; } .clickable -{ +{ cursor: pointer; } .red { @@ -379,8 +379,8 @@ select selectbox option.disabled {

Subject

+ +

Select subject by index
diff --git a/Samples/basic/databinding/src/main.cpp b/Samples/basic/databinding/src/main.cpp index f0757b1e5..bcde2b5e2 100644 --- a/Samples/basic/databinding/src/main.cpp +++ b/Samples/basic/databinding/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,6 +32,7 @@ #include #include +namespace { namespace BasicExample { Rml::DataModelHandle model_handle; @@ -56,8 +57,7 @@ namespace BasicExample { return true; } -} - +} // namespace BasicExample namespace EventsExample { @@ -68,7 +68,7 @@ namespace EventsExample { Rml::String mouse_detector = "Mouse-move Detector."; int rating = 99; - Rml::Vector list = { 1, 2, 3, 4, 5 }; + Rml::Vector list = {1, 2, 3, 4, 5}; Rml::Vector positions; @@ -80,7 +80,6 @@ namespace EventsExample { } my_data; - void ClearPositions(Rml::DataModelHandle model, Rml::Event& /*ev*/, const Rml::VariantList& /*arguments*/) { my_data.positions.clear(); @@ -92,7 +91,6 @@ namespace EventsExample { variant = int(my_data.rating > 50); } - bool Initialize(Rml::Context* context) { using namespace Rml; @@ -115,9 +113,7 @@ namespace EventsExample { constructor.Bind("mouse_detector", &my_data.mouse_detector); constructor.Bind("rating", &my_data.rating); constructor.BindFunc("good_rating", &HasGoodRating); - constructor.BindFunc("great_rating", [](Variant& variant) { - variant = int(my_data.rating > 80); - }); + constructor.BindFunc("great_rating", [](Variant& variant) { variant = int(my_data.rating > 80); }); constructor.Bind("list", &my_data.list); @@ -126,7 +122,6 @@ namespace EventsExample { constructor.BindEventCallback("clear_positions", &ClearPositions); constructor.BindEventCallback("add_mouse_pos", &MyData::AddMousePos, &my_data); - model_handle = constructor.GetModelHandle(); return true; @@ -148,9 +143,7 @@ namespace EventsExample { } } } -} - - +} // namespace EventsExample namespace InvadersExample { @@ -162,7 +155,7 @@ namespace InvadersExample { struct Invader { Rml::String name; Rml::String sprite; - Rml::Colourb color{ 255, 255, 255 }; + Rml::Colourb color{255, 255, 255}; float max_health = 0; float charge_rate = 0; float health = 0; @@ -173,7 +166,7 @@ namespace InvadersExample { float health = 0; float charge = 0; int score = 0; - + double elapsed_time = 0; double next_invader_spawn_time = 0; @@ -237,10 +230,7 @@ namespace InvadersExample { // Register a custom getter for the Colourb type. constructor.RegisterScalar( - [](const Rml::Colourb& color, Rml::Variant& variant) { - variant = "rgba(" + Rml::ToString(color) + ')'; - } - ); + [](const Rml::Colourb& color, Rml::Variant& variant) { variant = "rgba(" + Rml::ToString(color) + ')'; }); // Register a transform function for formatting time constructor.RegisterTransformFunc("format_time", [](const Rml::VariantList& arguments) -> Rml::Variant { if (arguments.empty()) @@ -288,7 +278,7 @@ namespace InvadersExample { void Update(const double dt) { using namespace Rml; - + if (data.health == 0) return; @@ -303,9 +293,9 @@ namespace InvadersExample { if (data.elapsed_time >= data.next_invader_spawn_time) { constexpr int num_items = 4; - static Array names = { "Angry invader", "Harmless invader", "Deceitful invader", "Cute invader" }; - static Array sprites = { "icon-invader", "icon-flag", "icon-game", "icon-waves" }; - static Array colors = { { { 255, 40, 30 }, {20, 40, 255}, {255, 255, 30}, {230, 230, 230} } }; + static Array names = {"Angry invader", "Harmless invader", "Deceitful invader", "Cute invader"}; + static Array sprites = {"icon-invader", "icon-flag", "icon-game", "icon-waves"}; + static Array colors = {{{255, 40, 30}, {20, 40, 255}, {255, 255, 30}, {230, 230, 230}}}; Invader new_invader; new_invader.name = names[Math::RandomInteger(num_items)]; @@ -346,7 +336,7 @@ namespace InvadersExample { data.health = Math::Max(data.health - float(10.0 * dt), 0.0f); model_handle.DirtyVariable("health"); } - + if (invader.charge >= 120) invader.charge = 0; @@ -354,7 +344,7 @@ namespace InvadersExample { } } } -} +} // namespace InvadersExample namespace FormsExample { @@ -366,7 +356,7 @@ namespace FormsExample { bool pasta = false; bool lasagne = false; Rml::String animal = "dog"; - Rml::Vector subjects = { "Choose your subject", "Feature request", "Bug report", "Praise", "Criticism" }; + Rml::Vector subjects = {"Choose your subject", "Feature request", "Bug report", "Praise", "Criticism"}; int selected_subject = 0; Rml::String new_subject = "New subject"; } my_data; @@ -390,7 +380,8 @@ namespace FormsExample { constructor.BindEventCallback("add_subject", [](Rml::DataModelHandle model, Rml::Event& /*ev*/, const Rml::VariantList& arguments) { Rml::String name = (arguments.size() == 1 ? arguments[0].Get() : ""); - if (!name.empty()) { + if (!name.empty()) + { my_data.subjects.push_back(std::move(name)); model.DirtyVariable("subjects"); } @@ -410,8 +401,8 @@ namespace FormsExample { return true; } -} - +} // namespace FormsExample +} // namespace class DemoWindow : public Rml::EventListener { public: @@ -446,8 +437,7 @@ class DemoWindow : public Rml::EventListener { Backend::RequestExit(); } break; - default: - break; + default: break; } } @@ -488,12 +478,12 @@ int main(int /*argc*/, char** /*argv*/) // Create the main RmlUi context. Rml::Context* context = Rml::CreateContext("main", Rml::Vector2i(width, height)); - if (!context - || !BasicExample::Initialize(context) - || !EventsExample::Initialize(context) - || !InvadersExample::Initialize(context) - || !FormsExample::Initialize(context) - ) + if (!context // + || !BasicExample::Initialize(context) // + || !EventsExample::Initialize(context) // + || !InvadersExample::Initialize(context) // + || !FormsExample::Initialize(context) // + ) { Rml::Shutdown(); Backend::Shutdown(); diff --git a/Samples/basic/demo/data/demo.rml b/Samples/basic/demo/data/demo.rml index 2bbd6ecf5..3c6749613 100644 --- a/Samples/basic/demo/data/demo.rml +++ b/Samples/basic/demo/data/demo.rml @@ -6,33 +6,33 @@ @spritesheet demo-sheet { src: /assets/invader.tga; - + window-outer: 0px 0px 144px 151px; - + demo-radio-t: 407px 0px 30px 14px; demo-radio-c: 407px 14px 30px 2px; demo-radio-b: 407px 16px 30px 14px; - + demo-radio-l: 407px 0px 14px 30px; demo-radio-m: 421px 0px 2px 30px; demo-radio-r: 423px 0px 14px 30px; - + demo-checkbox-t: 407px 60px 30px 14px; demo-checkbox-c: 407px 74px 30px 2px; demo-checkbox-b: 407px 76px 30px 14px; - + demo-checkbox-l: 407px 60px 14px 30px; demo-checkbox-m: 421px 60px 2px 30px; demo-checkbox-r: 423px 60px 14px 30px; - + demo-checked-t: 407px 90px 30px 8px; demo-checked-c: 407px 98px 30px 14px; demo-checked-b: 407px 112px 30px 8px; - + demo-help-t: 128px 152px 51px 6px; demo-help-c: 128px 158px 51px 21px; demo-help-b: 128px 179px 51px 12px; - + demo-title-bar: 147px 0px 96px 85px; } @@ -52,8 +52,8 @@ div#title_bar div#icon display: none; } div#content -{ - position: relative; +{ + position: relative; /* background-color: #bbb; */ } tabset @@ -62,7 +62,7 @@ tabset } tabs { - display: block; + display: block; position: fixed; clip: none; text-align: right; @@ -76,11 +76,11 @@ tab padding: 0 20dp; line-height: 40dp; display: inline-block; - + font-size: 15dp; color: #ddd; text-align: center; - + decorator: tiled-horizontal( tableheader-l, tableheader-c, tableheader-r ); image-color: #cffc; } @@ -96,11 +96,11 @@ tab:active, tab:selected } panels { - display: block; + display: block; } panel { - display: block; + display: block; padding: 30dp; margin-left: auto; margin-right: auto; @@ -125,7 +125,7 @@ p.title text-align: center; } .clickable -{ +{ cursor: pointer; } @@ -178,7 +178,7 @@ p.title { height: 200dp; decorator: tiled-box( - window-tl, window-t, window-tr, + window-tl, window-t, window-tr, window-l, window-c, window-r, window-bl, window-b, window-br ); @@ -230,7 +230,7 @@ p.title /*** Font effects ***/ -#font_effects div +#font_effects div { display: inline-block; width: 180dp; @@ -239,7 +239,7 @@ p.title font-size: 35dp; color: #b33; } -#font_effects h1 +#font_effects h1 { margin: 15dp 0 10dp 0; } @@ -338,14 +338,14 @@ p.title #transition:hover .alien1 { left: 30%; top: 75dp; } #transition:hover .alien3 { left: 70%; top: 75dp; } #transition .defender -{ +{ transition: image-color 0.3s 0.0s quadratic-out; position: absolute; left: -44dp; - top: 150dp; opacity: 1; + top: 150dp; opacity: 1; } #transition:hover .defender { image-color: #acf; } -#transition .ray { +#transition .ray { transition: top 0.4s back-out, opacity 0.4s cubic-in; position: absolute; top: -130dp; @@ -448,7 +448,7 @@ form h2 { width: 40dp; padding-left: 1em; } -#rating_emoji { +#rating_emoji { color: #ffd40f; font-size: 1.7em; } @@ -457,13 +457,13 @@ progress { display: inline-block; vertical-align: middle; } -#gauge { +#gauge { decorator: image( gauge ); width: 100dp; height: 86dp; fill-image: gauge-fill; } -#progress_horizontal { +#progress_horizontal { decorator: tiled-horizontal( progress-l, progress-c, progress-r ); width: 150dp; height: 34dp; @@ -489,13 +489,13 @@ progress { #gauge_value { margin: 34dp 0 0 18dp; } -#progress_value { +#progress_value { margin-left: -20dp; display: inline-block; } -#form_output +#form_output { border: 1dp #666; font-size: 0.9em; @@ -508,7 +508,7 @@ progress { overflow: hidden auto; } -#controls textarea +#controls textarea { font-size: 18dp; font-effect: outline(2dp #060); @@ -552,7 +552,7 @@ progress { width: 100%; height: 100%; } -#sandbox_target +#sandbox_target { box-sizing: border-box; background-color: #fff; @@ -587,7 +587,7 @@ progress { background: #dda; } #vertical_slider -{ +{ width: 12dp; margin-left: 3dp; padding-top: 5dp; @@ -617,7 +617,7 @@ progress {

- +

Image decorator

The 'image' decorator applies an image to the background of an element. By default it stretches the image to the size of the element, but this behavior can be controlled as seen later on.

@@ -631,7 +631,7 @@ progress {
- +

Tiled-horizontal decorator

The 'tiled-horizontal' decorator separates an image into three parts, with the edges displayed at their native size while the middle part is stretched to cover the remaining width of the element. In each of the following examples an image is displayed at its native size first, and then the decorator is applied to it with its element stretched horizontally.

@@ -647,7 +647,7 @@ progress {

In the third example we show the same title bar that is used to style the sample windows.

- +

Tiled-vertical decorator

The 'tiled-vertical' decorator behaves like tiled-horizontal, but this time it is stretched vertically.

@@ -668,31 +668,31 @@ progress {

Clearly, not all images are designed to stretch like this. However, one can certainly envision a usage for the first two examples.

- +

Tiled-box decorator

The 'tiled-box' decorator lays out a 3x3 grid within the element, each of the nine parts being filled with a separate sprite or image. The corners stay fixed in size, while the center and edges are stretched to fill the remaining size of the element.

The following image displays the region used to define the background of the window in this sample.

The decorator's element can then gracefully be sized in any direction, keeping the corners and edges at a proper size.

- +

Ninepatch decorator

The 'ninepatch' decorator is similar to the tiled-box decorator in that it splits the image into nine parts. However, only two sprites are used to define all nine tiles, an outer sprite and an inner sprite.

- +

Let us define the outer sprite by the following image, and the inner sprite as the part within the displayed border.

- +

When the ninepatch decorator is applied and the element is stretched, the following is rendered.

Notice that the corners stay fixed, and the inner sprite is stretched. We can also control the rendered size of the edges, here the left edge is displayed at its native size and the others at half their size.

- +

If we instead compare this to the image decorator, we see the following.

With the image decorator it looks blurry and its borders are stretched.

- +

Image decorator fit modes

@@ -735,7 +735,7 @@ progress {

The 'img' elements are separate from decorators, but we describe them here for completeness. They can be declared as in html. Additionally, a 'rect' attribute can be used to crop the image. The element can also display sprites declared in a sprite sheet.

- +

Sprite sheets

Sprite sheets are defined by an image source and a collection of sprites, and can be declared in RCSS. Sprites are essentially rectangles into the given image. For example, the following image

@@ -762,7 +762,7 @@ progress { Animations - +

Transitions

Hover over the following to see an animation performed by the transition property in RCSS.

@@ -772,7 +772,7 @@ progress {
- +

Tweening functions

Set animation parameters below and click on the background or the flag.

@@ -799,10 +799,10 @@ progress {
- + Duration 0.50 s
- +

Cube

The cube is transformed and animated entirely in RCSS using the @keyframes at-rule.

diff --git a/Samples/basic/demo/src/main.cpp b/Samples/basic/demo/src/main.cpp index a4be6ceb0..5a2a713fd 100644 --- a/Samples/basic/demo/src/main.cpp +++ b/Samples/basic/demo/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -49,10 +49,9 @@ scrollbarhorizontal sliderbar:hover { background: #888; } scrollbarhorizontal sliderbar:active { background: #666; } )"; -class DemoWindow : public Rml::EventListener -{ +class DemoWindow : public Rml::EventListener { public: - DemoWindow(const Rml::String &title, Rml::Context *context) + DemoWindow(const Rml::String& title, Rml::Context* context) { using namespace Rml; document = context->LoadDocument("basic/demo/data/demo.rml"); @@ -84,7 +83,7 @@ class DemoWindow : public Rml::EventListener // Load file into string auto file_interface = Rml::GetFileInterface(); Rml::FileHandle handle = file_interface->Open("assets/rml.rcss"); - + size_t length = file_interface->Length(handle); style_sheet_content.resize(length); file_interface->Read((void*)style_sheet_content.data(), length, handle); @@ -110,12 +109,13 @@ class DemoWindow : public Rml::EventListener gauge = document->GetElementById("gauge"); progress_horizontal = document->GetElementById("progress_horizontal"); - + document->Show(); } } - void Update() { + void Update() + { if (iframe) { iframe->UpdateDocument(); @@ -169,7 +169,8 @@ class DemoWindow : public Rml::EventListener } } - void Shutdown() { + void Shutdown() + { if (document) { document->Close(); @@ -185,23 +186,20 @@ class DemoWindow : public Rml::EventListener { case EventId::Keydown: { - Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); + Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter("key_identifier", 0); if (key_identifier == Rml::Input::KI_ESCAPE) Backend::RequestExit(); } break; - default: - break; + default: break; } } - Rml::ElementDocument * GetDocument() { - return document; - } + Rml::ElementDocument* GetDocument() { return document; } - void SubmitForm(Rml::String in_submit_message) + void SubmitForm(Rml::String in_submit_message) { submitting = true; submitting_start_time = Rml::GetSystemInterface()->GetElapsedTime(); @@ -235,8 +233,8 @@ class DemoWindow : public Rml::EventListener } private: - Rml::ElementDocument *document = nullptr; - Rml::ElementDocument *iframe = nullptr; + Rml::ElementDocument* document = nullptr; + Rml::ElementDocument* iframe = nullptr; Rml::Element *gauge = nullptr, *progress_horizontal = nullptr; Rml::SharedPtr rml_basic_style_sheet; @@ -245,7 +243,6 @@ class DemoWindow : public Rml::EventListener Rml::String submit_message; }; - Rml::UniquePtr demo_window; struct TweeningParameters { @@ -254,8 +251,7 @@ struct TweeningParameters { float duration = 0.5f; } tweening_parameters; -class DemoEventListener : public Rml::EventListener -{ +class DemoEventListener : public Rml::EventListener { public: DemoEventListener(const Rml::String& value, Rml::Element* element) : value(value), element(element) {} @@ -279,38 +275,37 @@ class DemoEventListener : public Rml::EventListener } else if (value == "cancel_exit") { - if(Element* parent = element->GetParentNode()) + if (Element* parent = element->GetParentNode()) parent->SetInnerRML(""); } else if (value == "change_color") { Colourb color((byte)Math::RandomInteger(255), (byte)Math::RandomInteger(255), (byte)Math::RandomInteger(255)); - element->Animate("image-color", Property(color, Property::COLOUR), tweening_parameters.duration, Tween(tweening_parameters.type, tweening_parameters.direction)); + element->Animate("image-color", Property(color, Property::COLOUR), tweening_parameters.duration, + Tween(tweening_parameters.type, tweening_parameters.direction)); event.StopPropagation(); } else if (value == "move_child") { - Vector2f mouse_pos( event.GetParameter("mouse_x", 0.0f), event.GetParameter("mouse_y", 0.0f) ); + Vector2f mouse_pos(event.GetParameter("mouse_x", 0.0f), event.GetParameter("mouse_y", 0.0f)); if (Element* child = element->GetFirstChild()) { - Vector2f new_pos = mouse_pos - element->GetAbsoluteOffset() - Vector2f(0.35f * child->GetClientWidth(), 0.9f * child->GetClientHeight()); - Property destination = Transform::MakeProperty({ Transforms::Translate2D(new_pos.x, new_pos.y) }); - if(tweening_parameters.duration <= 0) + Vector2f new_pos = + mouse_pos - element->GetAbsoluteOffset() - Vector2f(0.35f * child->GetClientWidth(), 0.9f * child->GetClientHeight()); + Property destination = Transform::MakeProperty({Transforms::Translate2D(new_pos.x, new_pos.y)}); + if (tweening_parameters.duration <= 0) child->SetProperty(PropertyId::Transform, destination); else - child->Animate("transform", destination, tweening_parameters.duration, Tween(tweening_parameters.type, tweening_parameters.direction)); + child->Animate("transform", destination, tweening_parameters.duration, + Tween(tweening_parameters.type, tweening_parameters.direction)); } } else if (value == "tween_function") { - static const SmallUnorderedMap tweening_functions = { - {"back", Tween::Back}, {"bounce", Tween::Bounce}, - {"circular", Tween::Circular}, {"cubic", Tween::Cubic}, - {"elastic", Tween::Elastic}, {"exponential", Tween::Exponential}, - {"linear", Tween::Linear}, {"quadratic", Tween::Quadratic}, - {"quartic", Tween::Quartic}, {"quintic", Tween::Quintic}, - {"sine", Tween::Sine} - }; + static const SmallUnorderedMap tweening_functions = {{"back", Tween::Back}, {"bounce", Tween::Bounce}, + {"circular", Tween::Circular}, {"cubic", Tween::Cubic}, {"elastic", Tween::Elastic}, {"exponential", Tween::Exponential}, + {"linear", Tween::Linear}, {"quadratic", Tween::Quadratic}, {"quartic", Tween::Quartic}, {"quintic", Tween::Quintic}, + {"sine", Tween::Sine}}; String value = event.GetParameter("value", String()); auto it = tweening_functions.find(value); @@ -326,9 +321,9 @@ class DemoEventListener : public Rml::EventListener String value = event.GetParameter("value", String()); if (value == "in") tweening_parameters.direction = Tween::In; - else if(value == "out") + else if (value == "out") tweening_parameters.direction = Tween::Out; - else if(value == "in-out") + else if (value == "in-out") tweening_parameters.direction = Tween::InOut; else { @@ -349,16 +344,14 @@ class DemoEventListener : public Rml::EventListener if (el_rating && el_rating_emoji) { enum { Sad, Mediocre, Exciting, Celebrate, Champion, CountEmojis }; - static const Rml::String emojis[CountEmojis] = { - (const char*)u8"😢", (const char*)u8"😐", (const char*)u8"😮", - (const char*)u8"😎", (const char*)u8"🏆" - }; + static const Rml::String emojis[CountEmojis] = {(const char*)u8"😢", (const char*)u8"😐", (const char*)u8"😮", (const char*)u8"😎", + (const char*)u8"🏆"}; int value = event.GetParameter("value", 50); - + Rml::String emoji; if (value <= 0) emoji = emojis[Sad]; - else if(value < 50) + else if (value < 50) emoji = emojis[Mediocre]; else if (value < 75) emoji = emojis[Exciting]; @@ -411,10 +404,7 @@ class DemoEventListener : public Rml::EventListener Rml::Element* element; }; - - -class DemoEventListenerInstancer : public Rml::EventListenerInstancer -{ +class DemoEventListenerInstancer : public Rml::EventListenerInstancer { public: Rml::EventListener* InstanceEventListener(const Rml::String& value, Rml::Element* element) override { @@ -422,7 +412,6 @@ class DemoEventListenerInstancer : public Rml::EventListenerInstancer } }; - #if defined RMLUI_PLATFORM_WIN32 #include int APIENTRY WinMain(HINSTANCE /*instance_handle*/, HINSTANCE /*previous_instance_handle*/, char* /*command_line*/, int /*command_show*/) diff --git a/Samples/basic/drag/data/icon.rcss b/Samples/basic/drag/data/icon.rcss index 204e1780e..c8bbbb489 100644 --- a/Samples/basic/drag/data/icon.rcss +++ b/Samples/basic/drag/data/icon.rcss @@ -1,22 +1,22 @@ icon { - /* The icons are floated left so they appear left-to-right. */ - float: left; - - /* The padding is added to push the text down to the bottom of the element. */ + /* The icons are floated left so they appear left-to-right. */ + float: left; + + /* The padding is added to push the text down to the bottom of the element. */ box-sizing: border-box; - width: 100dp; - height: 100dp; - padding: 60dp 10dp 0 10dp; - margin: 10dp; - - decorator: image( ../../../assets/present.tga ); - - font-size: 12dp; - text-align: center; - font-effect: shadow(1dp 1dp black); - + width: 100dp; + height: 100dp; + padding: 60dp 10dp 0 10dp; + margin: 10dp; + + decorator: image( ../../../assets/present.tga ); + + font-size: 12dp; + text-align: center; + font-effect: shadow(1dp 1dp black); + cursor: move; - - drag: clone; + + drag: clone; } diff --git a/Samples/basic/drag/data/inventory.rml b/Samples/basic/drag/data/inventory.rml index fa3cec2ee..3f4aa3f52 100644 --- a/Samples/basic/drag/data/inventory.rml +++ b/Samples/basic/drag/data/inventory.rml @@ -9,12 +9,12 @@ width: 400dp; height: 300dp; } - + /* Hide the window icon. */ - div#title_bar div#icon - { - display: none; - } + div#title_bar div#icon + { + display: none; + } diff --git a/Samples/basic/drag/src/DragListener.cpp b/Samples/basic/drag/src/DragListener.cpp index 3dcef7d3b..1f202de75 100644 --- a/Samples/basic/drag/src/DragListener.cpp +++ b/Samples/basic/drag/src/DragListener.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,7 +31,6 @@ static DragListener drag_listener; -// Registers an element as being a container of draggable elements. void DragListener::RegisterDraggableContainer(Rml::Element* element) { element->AddEventListener(Rml::EventId::Dragdrop, &drag_listener); @@ -43,7 +42,7 @@ void DragListener::ProcessEvent(Rml::Event& event) { Rml::Element* dest_container = event.GetCurrentElement(); Rml::Element* dest_element = event.GetTargetElement(); - Rml::Element* drag_element = static_cast< Rml::Element* >(event.GetParameter< void* >("drag_element", nullptr)); + Rml::Element* drag_element = static_cast(event.GetParameter("drag_element", nullptr)); if (dest_container == dest_element) { diff --git a/Samples/basic/drag/src/DragListener.h b/Samples/basic/drag/src/DragListener.h index 06a8176f3..7247b5094 100644 --- a/Samples/basic/drag/src/DragListener.h +++ b/Samples/basic/drag/src/DragListener.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,11 +33,10 @@ #include /** - @author Pete + @author Pete */ -class DragListener : public Rml::EventListener -{ +class DragListener : public Rml::EventListener { public: /// Registers an elemenet as being a container of draggable elements. static void RegisterDraggableContainer(Rml::Element* element); diff --git a/Samples/basic/drag/src/Inventory.cpp b/Samples/basic/drag/src/Inventory.cpp index e393f109d..897223a17 100644 --- a/Samples/basic/drag/src/Inventory.cpp +++ b/Samples/basic/drag/src/Inventory.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,10 +27,9 @@ */ #include "Inventory.h" -#include #include "DragListener.h" +#include -// Constructs a new inventory and opens its window. Inventory::Inventory(const Rml::String& title, const Rml::Vector2f& position, Rml::Context* context) { document = context->LoadDocument("basic/drag/data/inventory.rml"); @@ -46,7 +45,6 @@ Inventory::Inventory(const Rml::String& title, const Rml::Vector2f& position, Rm DragListener::RegisterDraggableContainer(document->GetElementById("content")); } -// Destroys the inventory and closes its window. Inventory::~Inventory() { if (document != nullptr) @@ -55,7 +53,6 @@ Inventory::~Inventory() } } -// Adds a brand-new item into this inventory. void Inventory::AddItem(const Rml::String& name) { if (document == nullptr) diff --git a/Samples/basic/drag/src/Inventory.h b/Samples/basic/drag/src/Inventory.h index d16a71ab5..e910f2ee4 100644 --- a/Samples/basic/drag/src/Inventory.h +++ b/Samples/basic/drag/src/Inventory.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,16 +29,15 @@ #ifndef INVENTORY_H #define INVENTORY_H -#include #include #include +#include /** - @author Peter Curry + @author Peter Curry */ -class Inventory -{ +class Inventory { public: /// Constructs a new inventory and opens its window. /// @param[in] title The title of the new inventory. diff --git a/Samples/basic/drag/src/main.cpp b/Samples/basic/drag/src/main.cpp index f185bcfd9..6a6238d82 100644 --- a/Samples/basic/drag/src/main.cpp +++ b/Samples/basic/drag/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/basic/loaddocument/src/main.cpp b/Samples/basic/loaddocument/src/main.cpp index bfdc2bba9..e8399f9fe 100644 --- a/Samples/basic/loaddocument/src/main.cpp +++ b/Samples/basic/loaddocument/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/basic/lottie/data/lottie.rml b/Samples/basic/lottie/data/lottie.rml index 2d578d56f..300e444d2 100644 --- a/Samples/basic/lottie/data/lottie.rml +++ b/Samples/basic/lottie/data/lottie.rml @@ -7,15 +7,15 @@ { width: 300dp; height: 225dp; - + margin: auto; } - + div#title_bar div#icon { display: none; } - + div#content { text-align: left; diff --git a/Samples/basic/lottie/src/main.cpp b/Samples/basic/lottie/src/main.cpp index f91c0f96f..db0621fc2 100644 --- a/Samples/basic/lottie/src/main.cpp +++ b/Samples/basic/lottie/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/basic/svg/data/svg.rml b/Samples/basic/svg/data/svg.rml index 53abd6593..76e74a8f1 100644 --- a/Samples/basic/svg/data/svg.rml +++ b/Samples/basic/svg/data/svg.rml @@ -7,10 +7,10 @@ { width: 300px; height: 225px; - + margin: auto; } - + svg { display: block; max-width: 80%; diff --git a/Samples/basic/svg/src/main.cpp b/Samples/basic/svg/src/main.cpp index c7e4f29fe..aef0b5040 100644 --- a/Samples/basic/svg/src/main.cpp +++ b/Samples/basic/svg/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/basic/transform/data/transform.rml b/Samples/basic/transform/data/transform.rml index a54f4f4a0..83dff156d 100644 --- a/Samples/basic/transform/data/transform.rml +++ b/Samples/basic/transform/data/transform.rml @@ -34,7 +34,7 @@ scrollbarvertical sliderbar:hover,scrollbarvertical sliderbar:active /* Perspective cubes based on: - https://developer.mozilla.org/en-US/docs/Web/CSS/perspective */ + https://developer.mozilla.org/en-US/docs/Web/CSS/perspective */ .pers250 { perspective: 250dp; diff --git a/Samples/basic/transform/src/main.cpp b/Samples/basic/transform/src/main.cpp index 1098b8956..cc355c0d3 100644 --- a/Samples/basic/transform/src/main.cpp +++ b/Samples/basic/transform/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,10 +35,9 @@ static bool run_rotate = true; -class DemoWindow : public Rml::EventListener -{ +class DemoWindow : public Rml::EventListener { public: - DemoWindow(const Rml::String &title, const Rml::Vector2f &position, Rml::Context *context) + DemoWindow(const Rml::String& title, const Rml::Vector2f& position, Rml::Context* context) { document = context->LoadDocument("basic/transform/data/transform.rml"); if (document) @@ -70,7 +69,7 @@ class DemoWindow : public Rml::EventListener void SetRotation(float degrees) { - if(document) + if (document) { std::stringstream s; if (perspective > 0) @@ -84,7 +83,7 @@ class DemoWindow : public Rml::EventListener { if (ev == Rml::EventId::Keydown) { - Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier) ev.GetParameter< int >("key_identifier", 0); + Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)ev.GetParameter("key_identifier", 0); if (key_identifier == Rml::Input::KI_SPACE) { @@ -99,7 +98,7 @@ class DemoWindow : public Rml::EventListener private: float perspective = 0; - Rml::ElementDocument *document; + Rml::ElementDocument* document; }; #if defined RMLUI_PLATFORM_WIN32 @@ -186,7 +185,7 @@ int main(int /*argc*/, char** /*argv*/) // Shutdown RmlUi. Rml::Shutdown(); - + Backend::Shutdown(); Shell::Shutdown(); diff --git a/Samples/basic/treeview/data/treeview.rml b/Samples/basic/treeview/data/treeview.rml index 113229a08..660098180 100644 --- a/Samples/basic/treeview/data/treeview.rml +++ b/Samples/basic/treeview/data/treeview.rml @@ -8,12 +8,12 @@ height: 400dp; margin: auto; } - + /* Hide the window icon. */ div#title_bar div#icon { display: none; } - + spacer { display: inline-block; } diff --git a/Samples/basic/treeview/src/FileBrowser.cpp b/Samples/basic/treeview/src/FileBrowser.cpp index 441f863ee..46b4b9702 100644 --- a/Samples/basic/treeview/src/FileBrowser.cpp +++ b/Samples/basic/treeview/src/FileBrowser.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,14 +29,15 @@ #include "FileBrowser.h" #include #include -#include #include +#include namespace FileBrowser { struct File { - File(bool directory, int depth, Rml::String name) - : visible(depth == 0), directory(directory), collapsed(true), depth(depth), name(std::move(name)) {} + File(bool directory, int depth, Rml::String name) : + visible(depth == 0), directory(directory), collapsed(true), depth(depth), name(std::move(name)) + {} bool visible; bool directory; @@ -95,7 +96,6 @@ static void ToggleExpand(Rml::DataModelHandle handle, Rml::Event& /*ev*/, const handle.DirtyVariable("files"); } - bool Initialise(Rml::Context* context, const Rml::String& root_dir) { BuildTree(root_dir, 0); diff --git a/Samples/basic/treeview/src/FileBrowser.h b/Samples/basic/treeview/src/FileBrowser.h index 280a18505..69b1e96b7 100644 --- a/Samples/basic/treeview/src/FileBrowser.h +++ b/Samples/basic/treeview/src/FileBrowser.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,7 +31,6 @@ #include - namespace FileBrowser { bool Initialise(Rml::Context* context, const Rml::String& root_dir); diff --git a/Samples/basic/treeview/src/main.cpp b/Samples/basic/treeview/src/main.cpp index 64c03d2da..e6ca66510 100644 --- a/Samples/basic/treeview/src/main.cpp +++ b/Samples/basic/treeview/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Samples/invaders/data/background.rml b/Samples/invaders/data/background.rml index b0b8bec31..0ed7aaf0d 100644 --- a/Samples/invaders/data/background.rml +++ b/Samples/invaders/data/background.rml @@ -7,7 +7,7 @@ height: 100%; z-index: -1; } - + @decorator stars : starfield { num-layers: 5; top-colour: #fffc; @@ -25,7 +25,7 @@ top: 0; left: 0; } - + starfield { decorator: stars; diff --git a/Samples/invaders/data/game.rml b/Samples/invaders/data/game.rml index eb598ea93..7776973d5 100644 --- a/Samples/invaders/data/game.rml +++ b/Samples/invaders/data/game.rml @@ -13,14 +13,14 @@ z-index: -1; } - + game { display: block; width: 100%; height: 100%; } - + div { position: relative; @@ -56,7 +56,7 @@ float: right; width: 80dp; } - + icon { display: block; diff --git a/Samples/invaders/data/help.rml b/Samples/invaders/data/help.rml index 9398fc1cf..79bd5f86d 100644 --- a/Samples/invaders/data/help.rml +++ b/Samples/invaders/data/help.rml @@ -9,12 +9,12 @@ height: 70%; margin: auto; } - + div#content { overflow-y: scroll; } - + div#title_bar div#icon { decorator: image( icon-help ); diff --git a/Samples/invaders/data/high_score.rml b/Samples/invaders/data/high_score.rml index 317ecf7c8..21b95f578 100644 --- a/Samples/invaders/data/high_score.rml +++ b/Samples/invaders/data/high_score.rml @@ -9,7 +9,7 @@ height: 440dp; margin: auto; } - + div#title_bar div#icon { decorator: image( icon-hiscore ); diff --git a/Samples/invaders/data/logo.rml b/Samples/invaders/data/logo.rml index de8e14c09..6ab86604f 100644 --- a/Samples/invaders/data/logo.rml +++ b/Samples/invaders/data/logo.rml @@ -8,7 +8,7 @@ z-index: -1; } - + #rifm_logo { position: absolute; diff --git a/Samples/invaders/data/main_menu.rml b/Samples/invaders/data/main_menu.rml index 01d874aca..46c8d3d41 100644 --- a/Samples/invaders/data/main_menu.rml +++ b/Samples/invaders/data/main_menu.rml @@ -10,7 +10,7 @@ margin: auto; } - + div#title_bar div#icon { decorator: image( icon-invader ); diff --git a/Samples/invaders/data/options.rml b/Samples/invaders/data/options.rml index 3b73e75b3..d4f2843f3 100644 --- a/Samples/invaders/data/options.rml +++ b/Samples/invaders/data/options.rml @@ -7,7 +7,7 @@ { width: 350dp; height: 330dp; - + margin: auto; } diff --git a/Samples/invaders/data/pause.rml b/Samples/invaders/data/pause.rml index 6a63a0f23..b898a9286 100644 --- a/Samples/invaders/data/pause.rml +++ b/Samples/invaders/data/pause.rml @@ -7,10 +7,10 @@ { width: 350dp; height: 135dp; - + margin: auto; } - + div#title_bar div#icon { decorator: image( icon-flag ); diff --git a/Samples/invaders/data/start_game.rml b/Samples/invaders/data/start_game.rml index 789be143b..6d4011991 100644 --- a/Samples/invaders/data/start_game.rml +++ b/Samples/invaders/data/start_game.rml @@ -7,15 +7,15 @@ { width: 300dp; height: 225dp; - + margin: auto; } - + div#title_bar div#icon { decorator: image( icon-game ); } - + form div { width: 200dp; diff --git a/Samples/invaders/src/DecoratorDefender.cpp b/Samples/invaders/src/DecoratorDefender.cpp index 5149b587f..e8bc0cb5f 100644 --- a/Samples/invaders/src/DecoratorDefender.cpp +++ b/Samples/invaders/src/DecoratorDefender.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,25 +46,15 @@ bool DecoratorDefender::Initialise(const Rml::Texture& texture) return true; } -/// Called on a decorator to generate any required per-element data for a newly decorated element. -Rml::DecoratorDataHandle DecoratorDefender::GenerateElementData(Rml::Element* RMLUI_UNUSED_PARAMETER(element)) const +Rml::DecoratorDataHandle DecoratorDefender::GenerateElementData(Rml::Element* /*element*/) const { - RMLUI_UNUSED(element); - return Rml::Decorator::INVALID_DECORATORDATAHANDLE; } -// Called to release element data generated by this decorator. -void DecoratorDefender::ReleaseElementData(Rml::DecoratorDataHandle RMLUI_UNUSED_PARAMETER(element_data)) const -{ - RMLUI_UNUSED(element_data); -} +void DecoratorDefender::ReleaseElementData(Rml::DecoratorDataHandle /*element_data*/) const {} -// Called to render the decorator on an element. -void DecoratorDefender::RenderElement(Rml::Element* element, Rml::DecoratorDataHandle RMLUI_UNUSED_PARAMETER(element_data)) const +void DecoratorDefender::RenderElement(Rml::Element* element, Rml::DecoratorDataHandle /*element_data*/) const { - RMLUI_UNUSED(element_data); - Rml::Vector2f position = element->GetAbsoluteOffset(Rml::Box::PADDING); Rml::Vector2f size = element->GetBox().GetSize(Rml::Box::PADDING); Rml::Math::SnapToPixelGrid(position, size); diff --git a/Samples/invaders/src/DecoratorDefender.h b/Samples/invaders/src/DecoratorDefender.h index 46875e594..d38e3b7e1 100644 --- a/Samples/invaders/src/DecoratorDefender.h +++ b/Samples/invaders/src/DecoratorDefender.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,8 +31,7 @@ #include -class DecoratorDefender : public Rml::Decorator -{ +class DecoratorDefender : public Rml::Decorator { public: virtual ~DecoratorDefender(); diff --git a/Samples/invaders/src/DecoratorInstancerDefender.cpp b/Samples/invaders/src/DecoratorInstancerDefender.cpp index 588d41453..f8ede7366 100644 --- a/Samples/invaders/src/DecoratorInstancerDefender.cpp +++ b/Samples/invaders/src/DecoratorInstancerDefender.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,10 +27,10 @@ */ #include "DecoratorInstancerDefender.h" +#include "DecoratorDefender.h" #include #include #include -#include "DecoratorDefender.h" DecoratorInstancerDefender::DecoratorInstancerDefender() { @@ -38,21 +38,18 @@ DecoratorInstancerDefender::DecoratorInstancerDefender() RegisterShorthand("decorator", "image-src", Rml::ShorthandType::FallThrough); } -DecoratorInstancerDefender::~DecoratorInstancerDefender() -{ -} +DecoratorInstancerDefender::~DecoratorInstancerDefender() {} -// Instances a decorator given the property tag and attributes from the RCSS file. -Rml::SharedPtr DecoratorInstancerDefender::InstanceDecorator(const Rml::String& /*name*/, - const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& instancer_interface) +Rml::SharedPtr DecoratorInstancerDefender::InstanceDecorator(const Rml::String& /*name*/, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& instancer_interface) { const Rml::Property* image_source_property = properties.GetProperty(id_image_src); - Rml::String image_source = image_source_property->Get< Rml::String >(); + Rml::String image_source = image_source_property->Get(); Rml::Texture texture = instancer_interface.GetTexture(image_source); auto decorator = Rml::MakeShared(); if (decorator->Initialise(texture)) return decorator; - + return nullptr; } diff --git a/Samples/invaders/src/DecoratorInstancerDefender.h b/Samples/invaders/src/DecoratorInstancerDefender.h index d70d33fc2..9962fae4c 100644 --- a/Samples/invaders/src/DecoratorInstancerDefender.h +++ b/Samples/invaders/src/DecoratorInstancerDefender.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,17 +32,17 @@ #include /** - @author Robert Curry + @author Robert Curry */ -class DecoratorInstancerDefender : public Rml::DecoratorInstancer -{ +class DecoratorInstancerDefender : public Rml::DecoratorInstancer { public: DecoratorInstancerDefender(); ~DecoratorInstancerDefender(); /// Instances a decorator given the property tag and attributes from the RCSS file. - Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& instancer_interface) override; + Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& instancer_interface) override; private: Rml::PropertyId id_image_src; diff --git a/Samples/invaders/src/DecoratorInstancerStarfield.cpp b/Samples/invaders/src/DecoratorInstancerStarfield.cpp index 3dc4eb1da..e57706ab7 100644 --- a/Samples/invaders/src/DecoratorInstancerStarfield.cpp +++ b/Samples/invaders/src/DecoratorInstancerStarfield.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,10 +26,10 @@ * */ +#include "DecoratorInstancerStarfield.h" #include "DecoratorStarfield.h" #include #include -#include "DecoratorInstancerStarfield.h" DecoratorInstancerStarfield::DecoratorInstancerStarfield() { @@ -42,21 +42,18 @@ DecoratorInstancerStarfield::DecoratorInstancerStarfield() id_bottom_density = RegisterProperty("bottom-density", "10").AddParser("number").GetId(); } -DecoratorInstancerStarfield::~DecoratorInstancerStarfield() -{ -} +DecoratorInstancerStarfield::~DecoratorInstancerStarfield() {} -// Instances a decorator given the property tag and attributes from the RCSS file. -Rml::SharedPtr DecoratorInstancerStarfield::InstanceDecorator(const Rml::String& /*name*/, - const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& /*instancer_interface*/) +Rml::SharedPtr DecoratorInstancerStarfield::InstanceDecorator(const Rml::String& /*name*/, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& /*instancer_interface*/) { - int num_layers = Rml::Math::RealToInteger(properties.GetProperty(id_num_layers)->Get< float >()); - Rml::Colourb top_colour = properties.GetProperty(id_top_colour)->Get< Rml::Colourb >(); - Rml::Colourb bottom_colour = properties.GetProperty(id_bottom_colour)->Get< Rml::Colourb >(); - float top_speed = properties.GetProperty(id_top_speed)->Get< float >(); - float bottom_speed = properties.GetProperty(id_bottom_speed)->Get< float >(); - int top_density = Rml::Math::RealToInteger(properties.GetProperty(id_top_density)->Get< float >()); - int bottom_density = Rml::Math::RealToInteger(properties.GetProperty(id_bottom_density)->Get< float >()); + int num_layers = Rml::Math::RealToInteger(properties.GetProperty(id_num_layers)->Get()); + Rml::Colourb top_colour = properties.GetProperty(id_top_colour)->Get(); + Rml::Colourb bottom_colour = properties.GetProperty(id_bottom_colour)->Get(); + float top_speed = properties.GetProperty(id_top_speed)->Get(); + float bottom_speed = properties.GetProperty(id_bottom_speed)->Get(); + int top_density = Rml::Math::RealToInteger(properties.GetProperty(id_top_density)->Get()); + int bottom_density = Rml::Math::RealToInteger(properties.GetProperty(id_bottom_density)->Get()); auto decorator = Rml::MakeShared(); if (decorator->Initialise(num_layers, top_colour, bottom_colour, top_speed, bottom_speed, top_density, bottom_density)) diff --git a/Samples/invaders/src/DecoratorInstancerStarfield.h b/Samples/invaders/src/DecoratorInstancerStarfield.h index 82c4b7a13..c3a6b669e 100644 --- a/Samples/invaders/src/DecoratorInstancerStarfield.h +++ b/Samples/invaders/src/DecoratorInstancerStarfield.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,21 +29,21 @@ #ifndef RMLUI_INVADERS_DECORATORINSTANCERSTARFIELD_H #define RMLUI_INVADERS_DECORATORINSTANCERSTARFIELD_H -#include #include "DecoratorStarfield.h" +#include /** - @author Robert Curry + @author Robert Curry */ -class DecoratorInstancerStarfield : public Rml::DecoratorInstancer -{ +class DecoratorInstancerStarfield : public Rml::DecoratorInstancer { public: DecoratorInstancerStarfield(); ~DecoratorInstancerStarfield(); /// Instances a decorator given the property tag and attributes from the RCSS file. - Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& instancer_interface) override; + Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& instancer_interface) override; private: Rml::PropertyId id_num_layers, id_top_colour, id_bottom_colour, id_top_speed, id_bottom_speed, id_top_density, id_bottom_density; diff --git a/Samples/invaders/src/DecoratorStarfield.cpp b/Samples/invaders/src/DecoratorStarfield.cpp index cec9c767a..55fcbdf84 100644 --- a/Samples/invaders/src/DecoratorStarfield.cpp +++ b/Samples/invaders/src/DecoratorStarfield.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,11 +38,10 @@ #include #include -DecoratorStarfield::~DecoratorStarfield() -{ -} +DecoratorStarfield::~DecoratorStarfield() {} -bool DecoratorStarfield::Initialise(int _num_layers, const Rml::Colourb& _top_colour, const Rml::Colourb& _bottom_colour, float _top_speed, float _bottom_speed, int _top_density, int _bottom_density) +bool DecoratorStarfield::Initialise(int _num_layers, const Rml::Colourb& _top_colour, const Rml::Colourb& _bottom_colour, float _top_speed, + float _bottom_speed, int _top_density, int _bottom_density) { num_layers = _num_layers; top_colour = _top_colour; @@ -55,7 +54,6 @@ bool DecoratorStarfield::Initialise(int _num_layers, const Rml::Colourb& _top_co return true; } -/// Called on a decorator to generate any required per-element data for a newly decorated element. Rml::DecoratorDataHandle DecoratorStarfield::GenerateElementData(Rml::Element* element) const { const double t = Rml::GetSystemInterface()->GetElapsedTime(); @@ -82,8 +80,8 @@ Rml::DecoratorDataHandle DecoratorStarfield::GenerateElementData(Rml::Element* e { for (int j = 0; j < density; j++) { - star_field->star_layers[i].stars[j].x = (float) Rml::Math::RandomReal(star_field->dimensions.x); - star_field->star_layers[i].stars[j].y = (float) Rml::Math::RandomReal(star_field->dimensions.y); + star_field->star_layers[i].stars[j].x = (float)Rml::Math::RandomReal(star_field->dimensions.x); + star_field->star_layers[i].stars[j].y = (float)Rml::Math::RandomReal(star_field->dimensions.y); } } @@ -93,14 +91,11 @@ Rml::DecoratorDataHandle DecoratorStarfield::GenerateElementData(Rml::Element* e return reinterpret_cast(star_field); } -// Called to release element data generated by this decorator. void DecoratorStarfield::ReleaseElementData(Rml::DecoratorDataHandle element_data) const { delete reinterpret_cast(element_data); } - -// Called to render the decorator on an element. void DecoratorStarfield::RenderElement(Rml::Element* element, Rml::DecoratorDataHandle element_data) const { const double t = Rml::GetSystemInterface()->GetElapsedTime(); diff --git a/Samples/invaders/src/DecoratorStarfield.h b/Samples/invaders/src/DecoratorStarfield.h index 8e7137cdf..a2bd2adff 100644 --- a/Samples/invaders/src/DecoratorStarfield.h +++ b/Samples/invaders/src/DecoratorStarfield.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,15 +29,15 @@ #ifndef RMLUI_INVADERS_DECORATORSTARFIELD_H #define RMLUI_INVADERS_DECORATORSTARFIELD_H -#include #include +#include -class DecoratorStarfield : public Rml::Decorator -{ +class DecoratorStarfield : public Rml::Decorator { public: virtual ~DecoratorStarfield(); - bool Initialise(int num_layers, const Rml::Colourb& top_colour, const Rml::Colourb& bottom_colour, float top_speed, float bottom_speed, int top_density, int bottom_density); + bool Initialise(int num_layers, const Rml::Colourb& top_colour, const Rml::Colourb& bottom_colour, float top_speed, float bottom_speed, + int top_density, int bottom_density); /// Called on a decorator to generate any required per-element data for a newly decorated element. /// @param[in] element The newly decorated element. @@ -61,21 +61,19 @@ class DecoratorStarfield : public Rml::Decorator int top_density; int bottom_density; - struct StarLayer - { - typedef Rml::Vector< Rml::Vector2f > StarList; + struct StarLayer { + typedef Rml::Vector StarList; StarList stars; Rml::Colourb colour; float speed; }; - struct StarField - { + struct StarField { void Update(double t); double last_update; Rml::Vector2f dimensions; - typedef Rml::Vector< StarLayer > StarLayerList; + typedef Rml::Vector StarLayerList; StarLayerList star_layers; }; }; diff --git a/Samples/invaders/src/Defender.cpp b/Samples/invaders/src/Defender.cpp index 845a80766..b75a9512a 100644 --- a/Samples/invaders/src/Defender.cpp +++ b/Samples/invaders/src/Defender.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,13 +27,13 @@ */ #include "Defender.h" -#include #include "Game.h" #include "GameDetails.h" #include "Invader.h" #include "Mothership.h" #include "Shield.h" #include "Sprite.h" +#include const float UPDATE_FREQ = 0.01f; const float MOVEMENT_SPEED = 300; @@ -57,20 +57,18 @@ Defender::Defender(Game* _game) state = ALIVE; render = true; } - -Defender::~Defender() -{ -} + +Defender::~Defender() {} void Defender::Update(double t) { float dt = float(t - defender_frame_start); if (dt < UPDATE_FREQ) return; - + dt = Rml::Math::Min(dt, 0.1f); - defender_frame_start = t; + defender_frame_start = t; position.x += (move_direction * dt * MOVEMENT_SPEED); @@ -82,7 +80,7 @@ void Defender::Update(double t) UpdateBullet(t); if (state == RESPAWN) - { + { // Switch the render flag so the defender "flickers" render = !render; @@ -91,7 +89,7 @@ void Defender::Update(double t) { state = ALIVE; render = true; - } + } } } @@ -124,30 +122,27 @@ void Defender::Fire() { if (!bullet_in_flight) { - bullet_position = position + Rml::Vector2f((SPRITE_WIDTH/2) - 4, 0); + bullet_position = position + Rml::Vector2f((SPRITE_WIDTH / 2) - 4, 0); bullet_in_flight = true; } } bool Defender::CheckHit(double t, const Rml::Vector2f& check_position) -{ +{ float sprite_width = defender_sprite.dimensions.x; float sprite_height = defender_sprite.dimensions.y; // If the position is within our bounds, set ourselves // as exploding and return a valid hit. - if (state == ALIVE - && check_position.x >= position.x - && check_position.x <= position.x + sprite_width - && check_position.y >= position.y - && check_position.y <= position.y + sprite_height) + if (state == ALIVE && check_position.x >= position.x && check_position.x <= position.x + sprite_width && check_position.y >= position.y && + check_position.y <= position.y + sprite_height) { game->RemoveLife(); state = RESPAWN; respawn_start = t; return true; - } + } return false; } diff --git a/Samples/invaders/src/Defender.h b/Samples/invaders/src/Defender.h index 05b31971f..9bb84ded8 100644 --- a/Samples/invaders/src/Defender.h +++ b/Samples/invaders/src/Defender.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,12 +35,11 @@ class Game; class Sprite; /** - Represents the Earth defender. Stores position and performs the update of the bullet position and collision detection. - @author Lloyd Weehuizen + Represents the Earth defender. Stores position and performs the update of the bullet position and collision detection. + @author Lloyd Weehuizen */ -class Defender -{ +class Defender { public: Defender(Game* game); ~Defender(); @@ -51,7 +50,7 @@ class Defender void Render(float dp_ratio, Rml::TextureHandle texture); /// Move the defender left. - void StartMove(float direction); + void StartMove(float direction); /// Stop the movement. void StopMove(float direction); /// Fire a bullet (if one isn't already in flight). @@ -65,10 +64,10 @@ class Defender void UpdateBullet(double t); Game* game; - Rml::Vector2f position; - + Rml::Vector2f position; + float move_direction; - + bool bullet_in_flight; Rml::Vector2f bullet_position; @@ -81,5 +80,4 @@ class Defender State state; }; - #endif diff --git a/Samples/invaders/src/ElementGame.cpp b/Samples/invaders/src/ElementGame.cpp index 154037d0a..a03345630 100644 --- a/Samples/invaders/src/ElementGame.cpp +++ b/Samples/invaders/src/ElementGame.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,21 +42,18 @@ ElementGame::ElementGame(const Rml::String& tag) : Rml::Element(tag) } ElementGame::~ElementGame() -{ +{ delete game; } -// Intercepts and handles key events. void ElementGame::ProcessEvent(Rml::Event& event) { - if (event == Rml::EventId::Keydown || - event == Rml::EventId::Keyup) + if (event == Rml::EventId::Keydown || event == Rml::EventId::Keyup) { bool key_down = (event == Rml::EventId::Keydown); - Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); + Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter("key_identifier", 0); - if (key_identifier == Rml::Input::KI_ESCAPE && - !key_down) + if (key_identifier == Rml::Input::KI_ESCAPE && !key_down) { EventManager::LoadWindow("pause"); } @@ -70,13 +67,13 @@ void ElementGame::ProcessEvent(Rml::Event& event) game->GetDefender()->StartMove(1.0f); if (key_identifier == Rml::Input::KI_SPACE) game->GetDefender()->Fire(); - } + } else if (!key_down) { if (key_identifier == Rml::Input::KI_LEFT) game->GetDefender()->StopMove(-1.0f); if (key_identifier == Rml::Input::KI_RIGHT) - game->GetDefender()->StopMove(1.0f); + game->GetDefender()->StopMove(1.0f); } } @@ -86,13 +83,11 @@ void ElementGame::ProcessEvent(Rml::Event& event) } } -// Updates the game. void ElementGame::OnUpdate() { game->Update(Rml::GetSystemInterface()->GetElapsedTime()); } -// Renders the game. void ElementGame::OnRender() { game->Render(GetContext()->GetDensityIndependentPixelRatio()); diff --git a/Samples/invaders/src/ElementGame.h b/Samples/invaders/src/ElementGame.h index 8e0432d75..98d6fe21e 100644 --- a/Samples/invaders/src/ElementGame.h +++ b/Samples/invaders/src/ElementGame.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,11 +35,10 @@ class Game; /** - @author Peter Curry + @author Peter Curry */ -class ElementGame : public Rml::Element, public Rml::EventListener -{ +class ElementGame : public Rml::Element, public Rml::EventListener { public: ElementGame(const Rml::String& tag); virtual ~ElementGame(); diff --git a/Samples/invaders/src/EventHandler.cpp b/Samples/invaders/src/EventHandler.cpp index 7ac158c2d..fc5017f39 100644 --- a/Samples/invaders/src/EventHandler.cpp +++ b/Samples/invaders/src/EventHandler.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,6 +28,4 @@ #include "EventHandler.h" -EventHandler::~EventHandler() -{ -} +EventHandler::~EventHandler() {} diff --git a/Samples/invaders/src/EventHandler.h b/Samples/invaders/src/EventHandler.h index 92add3d84..9b7500c1d 100644 --- a/Samples/invaders/src/EventHandler.h +++ b/Samples/invaders/src/EventHandler.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,15 +32,13 @@ #include /** - @author Peter Curry + @author Peter Curry */ -class EventHandler -{ +class EventHandler { public: virtual ~EventHandler(); virtual void ProcessEvent(Rml::Event& event, const Rml::String& value) = 0; }; - #endif diff --git a/Samples/invaders/src/EventHandlerHighScore.cpp b/Samples/invaders/src/EventHandlerHighScore.cpp index accae987e..f65e98c0c 100644 --- a/Samples/invaders/src/EventHandlerHighScore.cpp +++ b/Samples/invaders/src/EventHandlerHighScore.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,20 +27,16 @@ */ #include "EventHandlerHighScore.h" -#include -#include -#include #include "EventManager.h" #include "GameDetails.h" #include "HighScores.h" +#include +#include +#include -EventHandlerHighScore::EventHandlerHighScore() -{ -} +EventHandlerHighScore::EventHandlerHighScore() {} -EventHandlerHighScore::~EventHandlerHighScore() -{ -} +EventHandlerHighScore::~EventHandlerHighScore() {} void EventHandlerHighScore::ProcessEvent(Rml::Event& event, const Rml::String& value) { @@ -57,18 +53,18 @@ void EventHandlerHighScore::ProcessEvent(Rml::Event& event, const Rml::String& v } else if (value == "enter_name") { - if (event.GetParameter< int >("key_identifier", Rml::Input::KI_UNKNOWN) == Rml::Input::KI_RETURN) + if (event.GetParameter("key_identifier", Rml::Input::KI_UNKNOWN) == Rml::Input::KI_RETURN) { - Rml::String name = event.GetCurrentElement()->GetAttribute< Rml::String >("value", "Anon."); + Rml::String name = event.GetCurrentElement()->GetAttribute("value", "Anon."); HighScores::SubmitName(name); } } else if (value == "check_name") { Rml::String name = "Anon."; - + // Submit the name the user started typing - if(auto element = event.GetCurrentElement()->GetOwnerDocument()->GetElementById("player_input")) + if (auto element = event.GetCurrentElement()->GetOwnerDocument()->GetElementById("player_input")) name = element->GetAttribute("value", name); HighScores::SubmitName(name); diff --git a/Samples/invaders/src/EventHandlerHighScore.h b/Samples/invaders/src/EventHandlerHighScore.h index 643b763af..ee2349620 100644 --- a/Samples/invaders/src/EventHandlerHighScore.h +++ b/Samples/invaders/src/EventHandlerHighScore.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,8 +34,7 @@ /** */ -class EventHandlerHighScore : public EventHandler -{ +class EventHandlerHighScore : public EventHandler { public: EventHandlerHighScore(); virtual ~EventHandlerHighScore(); diff --git a/Samples/invaders/src/EventHandlerOptions.cpp b/Samples/invaders/src/EventHandlerOptions.cpp index 94afe38c4..e83a7601b 100644 --- a/Samples/invaders/src/EventHandlerOptions.cpp +++ b/Samples/invaders/src/EventHandlerOptions.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,20 +27,16 @@ */ #include "EventHandlerOptions.h" +#include "EventManager.h" +#include "GameDetails.h" #include #include -#include #include -#include "EventManager.h" -#include "GameDetails.h" +#include -EventHandlerOptions::EventHandlerOptions() -{ -} +EventHandlerOptions::EventHandlerOptions() {} -EventHandlerOptions::~EventHandlerOptions() -{ -} +EventHandlerOptions::~EventHandlerOptions() {} void EventHandlerOptions::ProcessEvent(Rml::Event& event, const Rml::String& value) { @@ -58,21 +54,22 @@ void EventHandlerOptions::ProcessEvent(Rml::Event& event, const Rml::String& val Rml::String graphics_option_id; switch (GameDetails::GetGraphicsQuality()) { - case GameDetails::GOOD: graphics_option_id = "good"; break; - case GameDetails::OK: graphics_option_id = "ok"; break; - case GameDetails::BAD: graphics_option_id = "bad"; break; - default: break; + case GameDetails::GOOD: graphics_option_id = "good"; break; + case GameDetails::OK: graphics_option_id = "ok"; break; + case GameDetails::BAD: graphics_option_id = "bad"; break; + default: break; } // Fetch the radio button from the document by ID, cast it to a radio button interface and set it as checked. // This will automatically pop the other radio buttons in the set. Note that we could have not cast and called // the 'Click()' function instead, but this method will avoid event overhead. - Rml::ElementFormControlInput* graphics_option = rmlui_dynamic_cast< Rml::ElementFormControlInput* >(options_body->GetElementById(graphics_option_id)); + Rml::ElementFormControlInput* graphics_option = + rmlui_dynamic_cast(options_body->GetElementById(graphics_option_id)); if (graphics_option != nullptr) graphics_option->SetAttribute("checked", ""); // Fetch the reverb option by ID and set its checked status from the game options. - Rml::ElementFormControlInput* reverb_option = rmlui_dynamic_cast< Rml::ElementFormControlInput* >(options_body->GetElementById("reverb")); + Rml::ElementFormControlInput* reverb_option = rmlui_dynamic_cast(options_body->GetElementById("reverb")); if (reverb_option != nullptr) { if (GameDetails::GetReverb()) @@ -82,7 +79,7 @@ void EventHandlerOptions::ProcessEvent(Rml::Event& event, const Rml::String& val } // Similarly, fetch the 3D spatialisation option by ID and set its checked status. - Rml::ElementFormControlInput* spatialisation_option = rmlui_dynamic_cast< Rml::ElementFormControlInput* >(options_body->GetElementById("3d")); + Rml::ElementFormControlInput* spatialisation_option = rmlui_dynamic_cast(options_body->GetElementById("3d")); if (spatialisation_option != nullptr) { if (GameDetails::Get3DSpatialisation()) @@ -105,15 +102,15 @@ void EventHandlerOptions::ProcessEvent(Rml::Event& event, const Rml::String& val { // First check which button was clicked to submit the form; if it was 'cancel', then we don't want to // propagate the changes. - if (event.GetParameter< Rml::String >("submit", "cancel") == "accept") + if (event.GetParameter("submit", "cancel") == "accept") { // Fetch the results of the form submission. These are stored as parameters directly on the event itself. // Like HTML form events, the name of the parameter is the 'name' attribute of the control, and the value // is whatever was put into the 'value' attribute. Checkbox values are only sent through if the box was // clicked. Radio buttons send through one value for the active button. - Rml::String graphics = event.GetParameter< Rml::String >("graphics", "ok"); - bool reverb = event.GetParameter< Rml::String >("reverb", "") == "true"; - bool spatialisation = event.GetParameter< Rml::String >("3d", "") == "true"; + Rml::String graphics = event.GetParameter("graphics", "ok"); + bool reverb = event.GetParameter("reverb", "") == "true"; + bool spatialisation = event.GetParameter("3d", "") == "true"; if (graphics == "good") GameDetails::SetGraphicsQuality(GameDetails::GOOD); @@ -141,7 +138,7 @@ void EventHandlerOptions::ProcessEvent(Rml::Event& event, const Rml::String& val { // The 'value' parameter of an onchange event is set to the value the control would send if it was // submitted; so, the empty string if it is clear or to the 'value' attribute of the control if it is set. - if (event.GetParameter< String >("value", "").empty()) + if (event.GetParameter("value", "").empty()) bad_warning->SetProperty(PropertyId::Display, Property(Style::Display::None)); else bad_warning->SetProperty(PropertyId::Display, Property(Style::Display::Block)); diff --git a/Samples/invaders/src/EventHandlerOptions.h b/Samples/invaders/src/EventHandlerOptions.h index 622f0f4ae..11993d090 100644 --- a/Samples/invaders/src/EventHandlerOptions.h +++ b/Samples/invaders/src/EventHandlerOptions.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,11 +32,10 @@ #include "EventHandler.h" /** - @author Peter Curry + @author Peter Curry */ -class EventHandlerOptions : public EventHandler -{ +class EventHandlerOptions : public EventHandler { public: EventHandlerOptions(); virtual ~EventHandlerOptions(); diff --git a/Samples/invaders/src/EventHandlerStartGame.cpp b/Samples/invaders/src/EventHandlerStartGame.cpp index d1fa7076a..b29cad399 100644 --- a/Samples/invaders/src/EventHandlerStartGame.cpp +++ b/Samples/invaders/src/EventHandlerStartGame.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,30 +27,26 @@ */ #include "EventHandlerStartGame.h" +#include "EventManager.h" +#include "GameDetails.h" #include #include #include #include -#include "EventManager.h" -#include "GameDetails.h" // The game's element context (declared in main.cpp). extern Rml::Context* context; -EventHandlerStartGame::EventHandlerStartGame() -{ -} +EventHandlerStartGame::EventHandlerStartGame() {} -EventHandlerStartGame::~EventHandlerStartGame() -{ -} +EventHandlerStartGame::~EventHandlerStartGame() {} void EventHandlerStartGame::ProcessEvent(Rml::Event& event, const Rml::String& value) { if (value == "start") { // Set the difficulty. - Rml::String difficulty = event.GetParameter< Rml::String >("difficulty", "easy"); + Rml::String difficulty = event.GetParameter("difficulty", "easy"); if (difficulty == "hard") GameDetails::SetDifficulty(GameDetails::HARD); else @@ -58,7 +54,7 @@ void EventHandlerStartGame::ProcessEvent(Rml::Event& event, const Rml::String& v // Set the defender colour. Rml::StringList colour_components; - Rml::StringUtilities::ExpandString(colour_components, event.GetParameter< Rml::String >("colour", "255,255,255")); + Rml::StringUtilities::ExpandString(colour_components, event.GetParameter("colour", "255,255,255")); Rml::Colourb colour(255, 255, 255); for (size_t i = 0; i < colour_components.size() && i < 3; ++i) @@ -69,7 +65,7 @@ void EventHandlerStartGame::ProcessEvent(Rml::Event& event, const Rml::String& v if (colour_component > 255) colour_component = 255; - colour[i] = (Rml::byte) colour_component; + colour[i] = (Rml::byte)colour_component; } GameDetails::SetDefenderColour(colour); diff --git a/Samples/invaders/src/EventHandlerStartGame.h b/Samples/invaders/src/EventHandlerStartGame.h index f6a5939ba..e9af7aa57 100644 --- a/Samples/invaders/src/EventHandlerStartGame.h +++ b/Samples/invaders/src/EventHandlerStartGame.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,11 +32,10 @@ #include "EventHandler.h" /** - @author Peter Curry + @author Peter Curry */ -class EventHandlerStartGame : public EventHandler -{ +class EventHandlerStartGame : public EventHandler { public: EventHandlerStartGame(); virtual ~EventHandlerStartGame(); diff --git a/Samples/invaders/src/EventListener.cpp b/Samples/invaders/src/EventListener.cpp index f456d1ef4..1d15fcd3d 100644 --- a/Samples/invaders/src/EventListener.cpp +++ b/Samples/invaders/src/EventListener.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,24 +29,18 @@ #include "EventListener.h" #include "EventManager.h" -EventListener::EventListener(const Rml::String& value) : value(value) -{ -} +EventListener::EventListener(const Rml::String& value) : value(value) {} -EventListener::~EventListener() -{ -} +EventListener::~EventListener() {} -// Sends the event value through to Invader's event processing system. void EventListener::ProcessEvent(Rml::Event& event) { + // Sends the event value through to Invader's event processing system. EventManager::ProcessEvent(event, value); } -// Destroys the event. -void EventListener::OnDetach(Rml::Element* RMLUI_UNUSED_PARAMETER(element)) +void EventListener::OnDetach(Rml::Element* /*element*/) { - RMLUI_UNUSED(element); - + // Destroys the event listener. delete this; } diff --git a/Samples/invaders/src/EventListener.h b/Samples/invaders/src/EventListener.h index 59d9d7939..8a19768ff 100644 --- a/Samples/invaders/src/EventListener.h +++ b/Samples/invaders/src/EventListener.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,11 +32,10 @@ #include /** - @author Peter Curry + @author Peter Curry */ -class EventListener : public Rml::EventListener -{ +class EventListener : public Rml::EventListener { public: EventListener(const Rml::String& value); virtual ~EventListener(); diff --git a/Samples/invaders/src/EventListenerInstancer.cpp b/Samples/invaders/src/EventListenerInstancer.cpp index d9cbb1fa2..1812a563e 100644 --- a/Samples/invaders/src/EventListenerInstancer.cpp +++ b/Samples/invaders/src/EventListenerInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,16 +29,12 @@ #include "EventListenerInstancer.h" #include "EventListener.h" -EventListenerInstancer::EventListenerInstancer() -{ -} +EventListenerInstancer::EventListenerInstancer() {} -EventListenerInstancer::~EventListenerInstancer() -{ -} +EventListenerInstancer::~EventListenerInstancer() {} -// Instances a new event handle for Invaders. Rml::EventListener* EventListenerInstancer::InstanceEventListener(const Rml::String& value, Rml::Element* /*element*/) { + // Instances a new event handler for Invaders. return new EventListener(value); } diff --git a/Samples/invaders/src/EventListenerInstancer.h b/Samples/invaders/src/EventListenerInstancer.h index c8435044e..6c2d88219 100644 --- a/Samples/invaders/src/EventListenerInstancer.h +++ b/Samples/invaders/src/EventListenerInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,18 +32,16 @@ #include /** - @author Peter Curry + @author Peter Curry */ -class EventListenerInstancer : public Rml::EventListenerInstancer -{ +class EventListenerInstancer : public Rml::EventListenerInstancer { public: EventListenerInstancer(); virtual ~EventListenerInstancer(); /// Instances a new event listener for Invaders. Rml::EventListener* InstanceEventListener(const Rml::String& value, Rml::Element* element) override; - }; #endif diff --git a/Samples/invaders/src/EventManager.cpp b/Samples/invaders/src/EventManager.cpp index 282f07401..0c12576cc 100644 --- a/Samples/invaders/src/EventManager.cpp +++ b/Samples/invaders/src/EventManager.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -45,29 +45,22 @@ static EventHandler* event_handler = nullptr; using EventHandlerMap = Rml::SmallUnorderedMap>; EventHandlerMap event_handlers; -EventManager::EventManager() -{ -} +EventManager::EventManager() {} -EventManager::~EventManager() -{ -} +EventManager::~EventManager() {} -// Releases all event handlers registered with the manager. void EventManager::Shutdown() { event_handlers.clear(); event_handler = nullptr; } -// Registers a new event handler with the manager. void EventManager::RegisterEventHandler(const Rml::String& handler_name, Rml::UniquePtr handler) { // Any handler bound under the same name will be released. event_handlers[handler_name] = std::move(handler); } -// Processes an event coming through from RmlUi. void EventManager::ProcessEvent(Rml::Event& event, const Rml::String& value) { Rml::StringList commands; @@ -81,15 +74,13 @@ void EventManager::ProcessEvent(Rml::Event& event, const Rml::String& value) if (values.empty()) return; - if (values[0] == "goto" && - values.size() > 1) + if (values[0] == "goto" && values.size() > 1) { // Load the window, and if successful close the old window. if (LoadWindow(values[1])) event.GetTargetElement()->GetOwnerDocument()->Close(); } - else if (values[0] == "load" && - values.size() > 1) + else if (values[0] == "load" && values.size() > 1) { // Load the window. LoadWindow(values[1]); @@ -126,7 +117,6 @@ void EventManager::ProcessEvent(Rml::Event& event, const Rml::String& value) } } -// Loads a window and binds the event handler for it. Rml::ElementDocument* EventManager::LoadWindow(const Rml::String& window_name) { // Set the event handler for the new screen, if one has been registered. diff --git a/Samples/invaders/src/EventManager.h b/Samples/invaders/src/EventManager.h index 863551353..08a0e6448 100644 --- a/Samples/invaders/src/EventManager.h +++ b/Samples/invaders/src/EventManager.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,11 +36,10 @@ class EventHandler; /** - @author Peter Curry + @author Peter Curry */ -class EventManager -{ +class EventManager { public: /// Releases all event handlers registered with the manager. static void Shutdown(); @@ -63,5 +62,4 @@ class EventManager ~EventManager(); }; - #endif diff --git a/Samples/invaders/src/Game.cpp b/Samples/invaders/src/Game.cpp index 55963e53a..24667bcf9 100644 --- a/Samples/invaders/src/Game.cpp +++ b/Samples/invaders/src/Game.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +27,6 @@ */ #include "Game.h" -#include -#include #include "Defender.h" #include "EventManager.h" #include "GameDetails.h" @@ -36,6 +34,8 @@ #include "Invader.h" #include "Mothership.h" #include "Shield.h" +#include +#include const int WINDOW_WIDTH = 1024; const int WINDOW_HEIGHT = 768; @@ -69,11 +69,11 @@ Game::Game() { initialized = false; invader_frame_start = 0; - defender_lives = 3; - current_invader_direction = 1.0f; + defender_lives = 3; + current_invader_direction = 1.0f; invaders = new Invader*[NUM_INVADERS + 1]; for (int i = 0; i < NUM_INVADERS + 1; i++) - invaders[i] = nullptr; + invaders[i] = nullptr; shields = new Shield*[NUM_SHIELDS]; for (int i = 0; i < NUM_SHIELDS; i++) @@ -91,12 +91,12 @@ Game::~Game() for (int i = 0; i < NUM_INVADERS + 1; i++) delete invaders[i]; - delete [] invaders; + delete[] invaders; for (int i = 0; i < NUM_SHIELDS; i++) delete shields[i]; - delete [] shields; + delete[] shields; } void Game::Initialise() @@ -126,21 +126,21 @@ void Game::Update(double t) // Determine if we should advance the invaders if (t - invader_frame_start >= invader_move_freq) { - MoveInvaders(); + MoveInvaders(); invader_frame_start = t; } // Update all invaders for (int i = 0; i < NUM_INVADERS + 1; i++) - invaders[i]->Update(t); + invaders[i]->Update(t); defender->Update(t); } } void Game::Render(float dp_ratio) -{ +{ if (defender_lives <= 0) return; @@ -192,25 +192,21 @@ bool Game::CanDropBomb(int index) return true; } -// Access the shields. Shield* Game::GetShield(int index) { return shields[index]; } -// Get the total number of shields int Game::GetNumShields() { return NUM_SHIELDS; } -// Adds a score onto the player's score. void Game::AddScore(int score) { SetScore(GameDetails::GetScore() + score); } -// Sets the player's score. void Game::SetScore(int score) { GameDetails::SetScore(score); @@ -224,7 +220,6 @@ void Game::SetScore(int score) SetHighScore(score); } -// Sets the player's high-score. void Game::SetHighScore(int score) { Rml::Element* high_score_element = context->GetDocument("game_window")->GetElementById("hiscore"); @@ -251,7 +246,7 @@ void Game::SetWave(int wave) } void Game::RemoveLife() -{ +{ if (defender_lives > 0) { SetLives(defender_lives - 1); @@ -265,7 +260,7 @@ void Game::RemoveLife() const Rml::Vector2f Game::GetWindowDimensions() { - return Rml::Vector2f((float) WINDOW_WIDTH, (float) WINDOW_HEIGHT); + return Rml::Vector2f((float)WINDOW_WIDTH, (float)WINDOW_HEIGHT); } void Game::MoveInvaders() @@ -299,7 +294,7 @@ void Game::MoveInvaders() } // Increase speed of invaders - invader_move_freq *= INVADER_UPDATE_MODIFIER; + invader_move_freq *= INVADER_UPDATE_MODIFIER; } } @@ -340,7 +335,7 @@ void Game::OnGameOver() void Game::InitialiseShields() { - Rml::Vector2f shield_array_start_position((float) SHIELD_START_X, (float) SHIELD_START_Y); + Rml::Vector2f shield_array_start_position((float)SHIELD_START_X, (float)SHIELD_START_Y); for (int x = 0; x < NUM_SHIELD_ARRAYS; x++) { @@ -356,13 +351,12 @@ void Game::InitialiseShields() } shields[(x * NUM_SHIELDS_PER_ARRAY) + i] = new Shield(this, type); - shields[(x * NUM_SHIELDS_PER_ARRAY) + i]->SetPosition(shield_array_start_position + Rml::Vector2f((float) SHIELD_SIZE * i, 0)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + i]->SetPosition(shield_array_start_position + Rml::Vector2f((float)SHIELD_SIZE * i, 0)); } // Middle row (row of 4) for (int i = 0; i < 4; i++) { - Shield::ShieldType type = Shield::REGULAR; if (i == 1) type = Shield::BOTTOM_RIGHT; @@ -372,15 +366,17 @@ void Game::InitialiseShields() } shields[(x * NUM_SHIELDS_PER_ARRAY) + 4 + i] = new Shield(this, type); - shields[(x * NUM_SHIELDS_PER_ARRAY) + 4 + i]->SetPosition(shield_array_start_position + Rml::Vector2f((float) SHIELD_SIZE * i, (float) SHIELD_SIZE)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + 4 + i]->SetPosition( + shield_array_start_position + Rml::Vector2f((float)SHIELD_SIZE * i, (float)SHIELD_SIZE)); } // Bottom row (2, one on each end) shields[(x * NUM_SHIELDS_PER_ARRAY) + 8] = new Shield(this, Shield::REGULAR); - shields[(x * NUM_SHIELDS_PER_ARRAY) + 8]->SetPosition(shield_array_start_position + Rml::Vector2f(0, (float) SHIELD_SIZE * 2)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + 8]->SetPosition(shield_array_start_position + Rml::Vector2f(0, (float)SHIELD_SIZE * 2)); shields[(x * NUM_SHIELDS_PER_ARRAY) + 9] = new Shield(this, Shield::REGULAR); - shields[(x * NUM_SHIELDS_PER_ARRAY) + 9]->SetPosition(shield_array_start_position + Rml::Vector2f((float) SHIELD_SIZE * 3, (float) SHIELD_SIZE * 2)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + 9]->SetPosition( + shield_array_start_position + Rml::Vector2f((float)SHIELD_SIZE * 3, (float)SHIELD_SIZE * 2)); shield_array_start_position.x += SHIELD_SPACING_X; } @@ -395,26 +391,24 @@ void Game::InitialiseWave() Invader::InvaderType type = Invader::UNKNOWN; switch (y) { - case 0: - type = Invader::RANK3; break; + case 0: type = Invader::RANK3; break; case 1: - case 2: - type = Invader::RANK2; break; - default: - type = Invader::RANK1; break; + case 2: type = Invader::RANK2; break; + default: type = Invader::RANK1; break; } // Determine position of top left invader - Rml::Vector2f invader_position((float) (WINDOW_WIDTH - (NUM_INVADERS_PER_ROW * INVADER_SPACING_X)) / 2, (float) (INVADER_START_Y + (y * INVADER_SPACING_Y))); - + Rml::Vector2f invader_position((float)(WINDOW_WIDTH - (NUM_INVADERS_PER_ROW * INVADER_SPACING_X)) / 2, + (float)(INVADER_START_Y + (y * INVADER_SPACING_Y))); + for (int x = 0; x < NUM_INVADERS_PER_ROW; x++) { // Determine invader type based on row position int index = (y * NUM_INVADERS_PER_ROW) + x; delete invaders[index]; - invaders[index] = new Invader(this, type, (y * NUM_INVADERS_PER_ROW) + x); - invaders[index]->SetPosition(invader_position); + invaders[index] = new Invader(this, type, (y * NUM_INVADERS_PER_ROW) + x); + invaders[index]->SetPosition(invader_position); // Increase invader position invader_position.x += INVADER_SPACING_X; @@ -425,7 +419,7 @@ void Game::InitialiseWave() delete invaders[MOTHERSHIP]; invaders[MOTHERSHIP] = new Mothership(this, MOTHERSHIP); - // Update the move frequency - invader_move_freq = ((((float)GameDetails::GetWave())-100.0f)/140.0f); + // Update the move frequency + invader_move_freq = ((((float)GameDetails::GetWave()) - 100.0f) / 140.0f); invader_move_freq *= invader_move_freq; } diff --git a/Samples/invaders/src/Game.h b/Samples/invaders/src/Game.h index 51bf84d43..936e9b18f 100644 --- a/Samples/invaders/src/Game.h +++ b/Samples/invaders/src/Game.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_INVADERS_GAME_H #define RMLUI_INVADERS_GAME_H -#include #include +#include class Shield; class Invader; @@ -38,15 +38,14 @@ class Defender; class Mothership; /** - Runs the game. - - Updates the Invader positions, animations and bombs. - - Updates the player position and bullets + Runs the game. + - Updates the Invader positions, animations and bombs. + - Updates the player position and bullets - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class Game -{ +class Game { public: Game(); ~Game(); @@ -92,7 +91,6 @@ class Game const Rml::Vector2f GetWindowDimensions(); private: - bool initialized; // The current invaders Invader** invaders; diff --git a/Samples/invaders/src/GameDetails.cpp b/Samples/invaders/src/GameDetails.cpp index 508ff081c..95da28be3 100644 --- a/Samples/invaders/src/GameDetails.cpp +++ b/Samples/invaders/src/GameDetails.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,111 +38,90 @@ static GameDetails::GraphicsQuality graphics_quality = GameDetails::OK; static bool reverb = true; static bool spatialisation = false; -GameDetails::GameDetails() -{ -} +GameDetails::GameDetails() {} -GameDetails::~GameDetails() -{ -} +GameDetails::~GameDetails() {} -// Sets the game difficulty. void GameDetails::SetDifficulty(Difficulty _difficulty) { difficulty = _difficulty; } -// Returns the game difficulty. GameDetails::Difficulty GameDetails::GetDifficulty() { return difficulty; } -// Sets the colour of the player's ship. void GameDetails::SetDefenderColour(const Rml::Colourb& _colour) { colour = _colour; } -// Returns the player's ship colour. const Rml::Colourb& GameDetails::GetDefenderColour() { return colour; } -// Sets the score the player achieved in the last game. void GameDetails::SetScore(int _score) { score = _score; } -// Resets the player's score. void GameDetails::ResetScore() { score = -1; } -// Returns the score the player achieved in the last game. int GameDetails::GetScore() { return score; } -// Set the current wave number void GameDetails::SetWave(int _wave) { wave = _wave; } -// Get the current wave number int GameDetails::GetWave() { return wave; } -// Sets the pauses state of the game void GameDetails::SetPaused(bool _paused) { paused = _paused; } -// Gets if the game is paused or not bool GameDetails::GetPaused() { return paused; } -// Sets the quality of the graphics used in-game. void GameDetails::SetGraphicsQuality(GraphicsQuality quality) { graphics_quality = quality; } -// Returns the quality of the graphics to use in-game. GameDetails::GraphicsQuality GameDetails::GetGraphicsQuality() { return graphics_quality; } -// Enables or disables reverb. void GameDetails::SetReverb(bool enabled) { reverb = enabled; } -// Returns the current state of reverb. bool GameDetails::GetReverb() { return reverb; } -// Enables or disables 3D spatialisation in the audio engine. void GameDetails::Set3DSpatialisation(bool enabled) { spatialisation = enabled; } -// Returns the current state of audio spatialisation. bool GameDetails::Get3DSpatialisation() { return spatialisation; diff --git a/Samples/invaders/src/GameDetails.h b/Samples/invaders/src/GameDetails.h index 13cf37f5c..d2e2aa822 100644 --- a/Samples/invaders/src/GameDetails.h +++ b/Samples/invaders/src/GameDetails.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,11 +32,10 @@ #include /** - @author Peter Curry + @author Peter Curry */ -class GameDetails -{ +class GameDetails { public: enum Difficulty { EASY, HARD }; diff --git a/Samples/invaders/src/HighScores.cpp b/Samples/invaders/src/HighScores.cpp index e1e7c81be..bf5e00e8b 100644 --- a/Samples/invaders/src/HighScores.cpp +++ b/Samples/invaders/src/HighScores.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,11 +27,11 @@ */ #include "HighScores.h" -#include #include #include -#include +#include #include +#include HighScores* HighScores::instance = nullptr; @@ -99,7 +99,6 @@ void HighScores::SubmitScore(const Rml::Colourb& colour, int wave, int score) instance->SubmitScore("", colour, wave, score, true); } -// Sets the name of the last player to submit their score. void HighScores::SubmitName(const Rml::String& name) { for (Score& score : instance->scores) @@ -139,7 +138,7 @@ void HighScores::LoadScores() { // Open and read the high score file. FILE* scores_file = fopen("scores.txt", "rt"); - + if (scores_file) { char buffer[1024]; @@ -153,9 +152,9 @@ void HighScores::LoadScores() int wave; int score; - if (Rml::TypeConverter< Rml::String , Rml::Colourb >::Convert(score_parts[1], colour) && - Rml::TypeConverter< Rml::String, int >::Convert(score_parts[2], wave) && - Rml::TypeConverter< Rml::String, int >::Convert(score_parts[3], score)) + if (Rml::TypeConverter::Convert(score_parts[1], colour) && + Rml::TypeConverter::Convert(score_parts[2], wave) && + Rml::TypeConverter::Convert(score_parts[3], score)) { SubmitScore(score_parts[0], colour, wave, score); } @@ -175,7 +174,7 @@ void HighScores::SaveScores() for (const Score& score : scores) { Rml::String colour_string; - Rml::TypeConverter< Rml::Colourb, Rml::String >::Convert(score.colour, colour_string); + Rml::TypeConverter::Convert(score.colour, colour_string); Rml::String score_str = Rml::CreateString(1024, "%s\t%s\t%d\t%d\n", score.name.c_str(), colour_string.c_str(), score.wave, score.score); fputs(score_str.c_str(), scores_file); diff --git a/Samples/invaders/src/HighScores.h b/Samples/invaders/src/HighScores.h index c202374f2..0ae5e8085 100644 --- a/Samples/invaders/src/HighScores.h +++ b/Samples/invaders/src/HighScores.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,11 +29,10 @@ #ifndef RMLUI_INVADERS_HIGHSCORES_H #define RMLUI_INVADERS_HIGHSCORES_H -#include #include +#include -class HighScores -{ +class HighScores { public: static void Initialise(Rml::Context* context); static void Shutdown(); @@ -58,19 +57,16 @@ class HighScores void LoadScores(); void SaveScores(); - struct Score - { + struct Score { Rml::String name; bool name_required; Rml::Colourb colour; int score; int wave; - Rml::String GetColour() { - return "rgba(" + Rml::ToString(colour) + ')'; - } + Rml::String GetColour() { return "rgba(" + Rml::ToString(colour) + ')'; } }; - using ScoreList = Rml::Vector< Score >; + using ScoreList = Rml::Vector; ScoreList scores; Rml::DataModelHandle model_handle; diff --git a/Samples/invaders/src/Invader.cpp b/Samples/invaders/src/Invader.cpp index 56be3712a..328610d11 100644 --- a/Samples/invaders/src/Invader.cpp +++ b/Samples/invaders/src/Invader.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,13 +27,13 @@ */ #include "Invader.h" -#include -#include #include "Defender.h" #include "Game.h" #include "GameDetails.h" #include "Shield.h" #include "Sprite.h" +#include +#include const float BOMB_UPDATE_FREQ = 0.04f; const float BOMB_RAY_SPEED = 10; @@ -43,8 +43,7 @@ const float BOMB_PROBABILITY_HARD = 0.005f; const float EXPLOSION_TIME = 0.25f; const Rml::Colourb MOTHERSHIP_COLOUR = Rml::Colourb(255, 0, 0, 255); -Sprite invader_sprites[] = -{ +Sprite invader_sprites[] = { // Rank 1 Sprite(Rml::Vector2f(48, 32), Rml::Vector2f(0.609375f, 0), Rml::Vector2f(0.796875f, 0.5f)), Sprite(Rml::Vector2f(48, 32), Rml::Vector2f(0.80078125f, 0), Rml::Vector2f(0.98828125f, 0.5f)), @@ -57,21 +56,18 @@ Sprite invader_sprites[] = // Mothership Sprite(Rml::Vector2f(64, 28), Rml::Vector2f(0.23828125f, 0.515625f), Rml::Vector2f(0.48828125f, 0.953125f)), // Explosion - Sprite(Rml::Vector2f(52, 28), Rml::Vector2f(0.71484375f, 0.51562500f), Rml::Vector2f(0.91796875f, 0.95312500f)) -}; + Sprite(Rml::Vector2f(52, 28), Rml::Vector2f(0.71484375f, 0.51562500f), Rml::Vector2f(0.91796875f, 0.95312500f))}; -Sprite bomb_sprites[] = -{ +Sprite bomb_sprites[] = { // Ray Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.51171875f, 0.51562500f), Rml::Vector2f(0.55859375f, 0.82812500f)), Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.56250000, 0.51562500), Rml::Vector2f(0.60937500, 0.82812500)), Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.61328125, 0.51562500), Rml::Vector2f(0.66015625, 0.82812500)), Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.66406250, 0.51562500), Rml::Vector2f(0.71093750, 0.82812500)), // Missile - Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.92578125, 0.51562500), Rml::Vector2f(0.97265625, 0.82812500)) -}; + Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.92578125, 0.51562500), Rml::Vector2f(0.97265625, 0.82812500))}; -Invader::Invader(Game* _game, InvaderType _type, int _index) : position(0,0) +Invader::Invader(Game* _game, InvaderType _type, int _index) : position(0, 0) { type = UNKNOWN; animation_frame = 0; @@ -89,9 +85,7 @@ Invader::Invader(Game* _game, InvaderType _type, int _index) : position(0,0) bomb_probability *= float(type); } -Invader::~Invader() -{ -} +Invader::~Invader() {} void Invader::SetPosition(const Rml::Vector2f& _position) { @@ -107,8 +101,7 @@ void Invader::Update(double t) { // Update the bombs if (float(t - bomb_frame_start) > BOMB_UPDATE_FREQ) - { - + { // Update the bomb position if its in flight, or check if we should drop one if (bomb != NONE) { @@ -124,7 +117,7 @@ void Invader::Update(double t) { bomb_position.y += BOMB_MISSILE_SPEED; } - + if (bomb_position.y > game->GetWindowDimensions().y) bomb = NONE; @@ -145,9 +138,7 @@ void Invader::Update(double t) bomb = NONE; } } - else if ( state == ALIVE - && Rml::Math::RandomReal(1.0f) < bomb_probability - && game->CanDropBomb(invader_index)) + else if (state == ALIVE && Rml::Math::RandomReal(1.0f) < bomb_probability && game->CanDropBomb(invader_index)) { bomb = Rml::Math::RandomInteger(2) == 0 ? RAY : MISSILE; bomb_position = position; @@ -157,7 +148,7 @@ void Invader::Update(double t) bomb_animation_frame = 0; else bomb_animation_frame = 4; - } + } bomb_frame_start = t; } @@ -176,8 +167,7 @@ void Invader::UpdateAnimation() animation_frame = 0; break; - default: - break; + default: break; } } @@ -193,7 +183,7 @@ void Invader::Render(float dp_ratio, Rml::TextureHandle texture) if (state != DEAD) invader_sprites[sprite_index].Render(Rml::Vector2f(position.x - sprite_offset, position.y), dp_ratio, color, texture); - + if (bomb != NONE) bomb_sprites[bomb_animation_frame].Render(bomb_position, dp_ratio, color, texture); } @@ -213,20 +203,17 @@ bool Invader::CheckHit(double t, const Rml::Vector2f& check_position) // If we're alive and the position is within our bounds, set ourselves // as exploding and return a valid hit - if (state == ALIVE - && check_position.x >= position.x - sprite_offset - && check_position.x <= position.x - sprite_offset + sprite_width - && check_position.y >= position.y - && check_position.y <= position.y + sprite_height) + if (state == ALIVE && check_position.x >= position.x - sprite_offset && check_position.x <= position.x - sprite_offset + sprite_width && + check_position.y >= position.y && check_position.y <= position.y + sprite_height) { int score = 0; switch (type) { - RMLUI_UNUSED_SWITCH_ENUM(UNKNOWN); - case MOTHERSHIP: score = (Rml::Math::RandomInteger(6) + 1) * 50; break; // 50 -> 300 - case RANK3: score = 40; break; - case RANK2: score = 20; break; - case RANK1: score = 10; break; + case MOTHERSHIP: score = (Rml::Math::RandomInteger(6) + 1) * 50; break; // 50 -> 300 + case RANK3: score = 40; break; + case RANK2: score = 20; break; + case RANK1: score = 10; break; + case UNKNOWN: break; } // Add the number of points @@ -234,7 +221,7 @@ bool Invader::CheckHit(double t, const Rml::Vector2f& check_position) // Set our state to exploding and start the timer to our doom state = EXPLODING; - death_time = t + EXPLOSION_TIME; + death_time = t + EXPLOSION_TIME; return true; } @@ -248,11 +235,11 @@ int Invader::GetSpriteIndex() const int index = animation_frame; switch (type) { - RMLUI_UNUSED_SWITCH_ENUM(UNKNOWN); - case RANK1: break; // animation_frame is the right index already - case RANK2: index += 2; break; - case RANK3: index += 4; break; - case MOTHERSHIP: index = 6; break; + case RANK1: break; // animation_frame is the right index already + case RANK2: index += 2; break; + case RANK3: index += 4; break; + case MOTHERSHIP: index = 6; break; + case UNKNOWN: break; } // If we're in exploding state, use the exploding sprite diff --git a/Samples/invaders/src/Invader.h b/Samples/invaders/src/Invader.h index 49c94fcba..bc6fc68b6 100644 --- a/Samples/invaders/src/Invader.h +++ b/Samples/invaders/src/Invader.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ class Game; /** - An alien invader. + An alien invader. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class Invader -{ +class Invader { public: enum InvaderType { UNKNOWN, RANK1, RANK2, RANK3, MOTHERSHIP }; enum BombType { NONE, RAY, MISSILE }; diff --git a/Samples/invaders/src/Mothership.cpp b/Samples/invaders/src/Mothership.cpp index bb8516224..4aac25e92 100644 --- a/Samples/invaders/src/Mothership.cpp +++ b/Samples/invaders/src/Mothership.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,10 +27,10 @@ */ #include "Mothership.h" -#include -#include "Shell.h" #include "Game.h" +#include "Shell.h" #include "Sprite.h" +#include const int SPRITE_WIDTH = 64; @@ -47,9 +47,7 @@ Mothership::Mothership(Game* game, int index) : Invader(game, Invader::MOTHERSHI position = Rml::Vector2f(-SPRITE_WIDTH, 64.0f); } -Mothership::~Mothership() -{ -} +Mothership::~Mothership() {} void Mothership::Update(double t) { @@ -64,8 +62,7 @@ void Mothership::Update(double t) { position.x += (direction * MOVEMENT_SPEED); - if ((direction < 0.0f && position.x < -SPRITE_WIDTH) - || (direction > 0.0f && position.x > game->GetWindowDimensions().x)) + if ((direction < 0.0f && position.x < -SPRITE_WIDTH) || (direction > 0.0f && position.x > game->GetWindowDimensions().x)) state = DEAD; update_frame_start = t; diff --git a/Samples/invaders/src/Mothership.h b/Samples/invaders/src/Mothership.h index 0c0155f83..c4431f0ec 100644 --- a/Samples/invaders/src/Mothership.h +++ b/Samples/invaders/src/Mothership.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,8 +34,7 @@ /** */ -class Mothership : public Invader -{ +class Mothership : public Invader { public: Mothership(Game* game, int index); ~Mothership(); diff --git a/Samples/invaders/src/Shield.cpp b/Samples/invaders/src/Shield.cpp index 8d4745e18..741e2637e 100644 --- a/Samples/invaders/src/Shield.cpp +++ b/Samples/invaders/src/Shield.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,14 +27,14 @@ */ #include "Shield.h" -#include #include "Game.h" #include "GameDetails.h" #include "Sprite.h" +#include const int MAX_HEALTH = 4; -Shield::Shield(Game* _game, ShieldType _type) : position(0,0) +Shield::Shield(Game* _game, ShieldType _type) : position(0, 0) { game = _game; type = _type; @@ -43,9 +43,7 @@ Shield::Shield(Game* _game, ShieldType _type) : position(0,0) InitialiseCells(); } -Shield::~Shield() -{ -} +Shield::~Shield() {} void Shield::InitialiseCells() { @@ -151,11 +149,8 @@ bool Shield::CheckHit(const Rml::Vector2f& check_position) // If we're alive and the position is within our bounds, set ourselves // as exploding and return a valid hit - if (health > 0 - && check_position.x >= position.x - && check_position.x <= position.x + sprite_size - && check_position.y >= position.y - && check_position.y <= position.y + sprite_size) + if (health > 0 && check_position.x >= position.x && check_position.x <= position.x + sprite_size && check_position.y >= position.y && + check_position.y <= position.y + sprite_size) { // Take damage. SustainDamage(); diff --git a/Samples/invaders/src/Shield.h b/Samples/invaders/src/Shield.h index d917fed9f..1e2daf404 100644 --- a/Samples/invaders/src/Shield.h +++ b/Samples/invaders/src/Shield.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ const int NUM_SHIELD_CELLS = 6; const int PIXEL_SIZE = 4; /** - A shield, protecting the player. + A shield, protecting the player. - @author Robert Curry + @author Robert Curry */ -class Shield -{ +class Shield { public: enum ShieldType { REGULAR, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; diff --git a/Samples/invaders/src/Sprite.cpp b/Samples/invaders/src/Sprite.cpp index a1d2ffa5a..e5545ae00 100644 --- a/Samples/invaders/src/Sprite.cpp +++ b/Samples/invaders/src/Sprite.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/invaders/src/Sprite.h b/Samples/invaders/src/Sprite.h index 9fdfa43e4..9b43d94cd 100644 --- a/Samples/invaders/src/Sprite.h +++ b/Samples/invaders/src/Sprite.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,7 +32,7 @@ #include /** - @author Peter Curry + @author Peter Curry */ class Sprite { diff --git a/Samples/invaders/src/main.cpp b/Samples/invaders/src/main.cpp index 6be980268..121208d8e 100644 --- a/Samples/invaders/src/main.cpp +++ b/Samples/invaders/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/luainvaders/data/background.rml b/Samples/luainvaders/data/background.rml index b0b8bec31..0ed7aaf0d 100644 --- a/Samples/luainvaders/data/background.rml +++ b/Samples/luainvaders/data/background.rml @@ -7,7 +7,7 @@ height: 100%; z-index: -1; } - + @decorator stars : starfield { num-layers: 5; top-colour: #fffc; @@ -25,7 +25,7 @@ top: 0; left: 0; } - + starfield { decorator: stars; diff --git a/Samples/luainvaders/data/game.rml b/Samples/luainvaders/data/game.rml index f8798572e..40b2d365d 100644 --- a/Samples/luainvaders/data/game.rml +++ b/Samples/luainvaders/data/game.rml @@ -12,7 +12,7 @@ z-index: -1; } - + game { display: block; @@ -93,7 +93,7 @@ Game = Game or {} --namespace for functions function Game.OnKeyDown(event, document) if event.parameters['key_identifier'] == rmlui.key_identifier.ESCAPE then document.context:LoadDocument('luainvaders/data/pause.rml'):Show() - end + end end diff --git a/Samples/luainvaders/data/help.rml b/Samples/luainvaders/data/help.rml index 163d4ceb7..3114ad332 100644 --- a/Samples/luainvaders/data/help.rml +++ b/Samples/luainvaders/data/help.rml @@ -9,12 +9,12 @@ height: 70%; margin: auto; } - + div#content { overflow-y: scroll; } - + div#title_bar div#icon { decorator: image( icon-help ); diff --git a/Samples/luainvaders/data/high_score.rml b/Samples/luainvaders/data/high_score.rml index bf34a87d8..7bb5b43e3 100644 --- a/Samples/luainvaders/data/high_score.rml +++ b/Samples/luainvaders/data/high_score.rml @@ -9,7 +9,7 @@ height: 440dp; margin: auto; } - + div#title_bar div#icon { decorator: image( icon-hiscore ); diff --git a/Samples/luainvaders/data/logo.rml b/Samples/luainvaders/data/logo.rml index de8e14c09..6ab86604f 100644 --- a/Samples/luainvaders/data/logo.rml +++ b/Samples/luainvaders/data/logo.rml @@ -8,7 +8,7 @@ z-index: -1; } - + #rifm_logo { position: absolute; diff --git a/Samples/luainvaders/data/main_menu.rml b/Samples/luainvaders/data/main_menu.rml index e4630dd2c..07ac71128 100644 --- a/Samples/luainvaders/data/main_menu.rml +++ b/Samples/luainvaders/data/main_menu.rml @@ -10,7 +10,7 @@ margin: auto; } - + div#title_bar div#icon { decorator: image( icon-invader ); @@ -21,9 +21,9 @@ MainMenu = MainMenu or {} function MainMenu.CloseLogo(document) if document.context then - local logo = document.context.documents['logo'] - if logo then logo:Close() end - end + local logo = document.context.documents['logo'] + if logo then logo:Close() end + end end diff --git a/Samples/luainvaders/data/options.rml b/Samples/luainvaders/data/options.rml index 9d2489322..2048235a6 100644 --- a/Samples/luainvaders/data/options.rml +++ b/Samples/luainvaders/data/options.rml @@ -7,7 +7,7 @@ { width: 350dp; height: 350dp; - + margin: auto; } @@ -39,61 +39,61 @@ if Options.datamodel == nil then end function Options.Serialize(filename,options) - local file,message = io.open(filename,'w+') --w+ will erase the previous data - if file == nil then Log.Message(Log.logtype.error, "Error saving options in options.rml: " .. message) return end - --cache the function - local format = string.format - - for key,value in pairs(options) do - file:write(tostring(key)..'='..tostring(value)..'\n') - end - file:close() + local file,message = io.open(filename,'w+') --w+ will erase the previous data + if file == nil then Log.Message(Log.logtype.error, "Error saving options in options.rml: " .. message) return end + --cache the function + local format = string.format + + for key,value in pairs(options) do + file:write(tostring(key)..'='..tostring(value)..'\n') + end + file:close() end function Options.Deserialize(filename) - local ret = {} --table to return - --cache functions that are used a lot for faster lookup - local gmatch = string.gmatch - - local f = io.open(filename) - if f then - for line in f:lines() do - for k,v in gmatch(line, '(%w+)=(%w+)') do ret[k] = v end - end - f:close() - else - return nil - end - - return ret + local ret = {} --table to return + --cache functions that are used a lot for faster lookup + local gmatch = string.gmatch + + local f = io.open(filename) + if f then + for line in f:lines() do + for k,v in gmatch(line, '(%w+)=(%w+)') do ret[k] = v end + end + f:close() + else + return nil + end + + return ret end function Options.LoadOptions(document) - local options = Options.Deserialize('options.dat') - if options == nil then return end --short circuit if the file doesn't exist - - --because everything is loaded as a string, we have to fool around with the boolean variables + local options = Options.Deserialize('options.dat') + if options == nil then return end --short circuit if the file doesn't exist + + --because everything is loaded as a string, we have to fool around with the boolean variables Options.datamodel.audios[1].checked = (options['reverb'] == 'true') Options.datamodel.audios[2].checked = (options['3d'] == 'true') - + Options.datamodel.graphics = options['graphics'] Options.datamodel.options_changed = false end function Options.SaveOptions(event) - if event.parameters['button'] == 'cancel' then - return - end - - local options = {} - local params = event.parameters - options['graphics'] = params['graphics'] - --because of how checkboxes won't be in the event params if they aren't checked, - --we return false if they don't exist. This is Lua's ternary operator. - options['reverb'] = params['reverb'] and true or false - options['3d'] = params['3d'] and true or false - - Options.Serialize('options.dat',options) + if event.parameters['button'] == 'cancel' then + return + end + + local options = {} + local params = event.parameters + options['graphics'] = params['graphics'] + --because of how checkboxes won't be in the event params if they aren't checked, + --we return false if they don't exist. This is Lua's ternary operator. + options['reverb'] = params['reverb'] and true or false + options['3d'] = params['3d'] and true or false + + Options.Serialize('options.dat',options) end diff --git a/Samples/luainvaders/data/pause.rml b/Samples/luainvaders/data/pause.rml index 99e32bbb9..311e9dfbb 100644 --- a/Samples/luainvaders/data/pause.rml +++ b/Samples/luainvaders/data/pause.rml @@ -7,10 +7,10 @@ { width: 350dp; height: 135dp; - + margin: auto; } - + div#title_bar div#icon { decorator: image( icon-flag ); diff --git a/Samples/luainvaders/data/start_game.rml b/Samples/luainvaders/data/start_game.rml index 43ded28b4..5540b42c5 100644 --- a/Samples/luainvaders/data/start_game.rml +++ b/Samples/luainvaders/data/start_game.rml @@ -7,15 +7,15 @@ { width: 300dp; height: 225dp; - + margin: auto; } - + div#title_bar div#icon { decorator: image( icon-game ); } - + form div { width: 200dp; @@ -38,14 +38,14 @@ function StartGame.SetupGame(event,document) Game.SetDifficulty(Game.difficulty.HARD) else Game.SetDifficulty(Game.difficulty.EASY) - end - - --some lua trickery coming up. Compiling a string at runtime that will return the values, - --because they are comma separated. For example, if the user chose "Denim", then the - --compiled string would look like "return 21,96,189" - local red,green,blue = load('return '..event.parameters['colour']) () + end + + --some lua trickery coming up. Compiling a string at runtime that will return the values, + --because they are comma separated. For example, if the user chose "Denim", then the + --compiled string would look like "return 21,96,189" + local red,green,blue = load('return '..event.parameters['colour']) () Game.SetDefenderColour(Colourb.new(red,green,blue,255)) - + local elem = Window.LoadMenu('game',document):GetElementById('game') elem:Focus() end diff --git a/Samples/luainvaders/data/window.rml b/Samples/luainvaders/data/window.rml index f11f45d94..d7292e9cd 100644 --- a/Samples/luainvaders/data/window.rml +++ b/Samples/luainvaders/data/window.rml @@ -7,14 +7,14 @@ Window = Window or {} --namespace function Window.OnWindowLoad(document) document:GetElementById('title').inner_rml = document.title end - + function Window.LoadMenu(name,document) local doc = document.context:LoadDocument('luainvaders/data/' .. name .. '.rml') if doc then doc:Show() document:Close() - end - + end + return doc end diff --git a/Samples/luainvaders/src/DecoratorDefender.cpp b/Samples/luainvaders/src/DecoratorDefender.cpp index 5149b587f..e8bc0cb5f 100644 --- a/Samples/luainvaders/src/DecoratorDefender.cpp +++ b/Samples/luainvaders/src/DecoratorDefender.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,25 +46,15 @@ bool DecoratorDefender::Initialise(const Rml::Texture& texture) return true; } -/// Called on a decorator to generate any required per-element data for a newly decorated element. -Rml::DecoratorDataHandle DecoratorDefender::GenerateElementData(Rml::Element* RMLUI_UNUSED_PARAMETER(element)) const +Rml::DecoratorDataHandle DecoratorDefender::GenerateElementData(Rml::Element* /*element*/) const { - RMLUI_UNUSED(element); - return Rml::Decorator::INVALID_DECORATORDATAHANDLE; } -// Called to release element data generated by this decorator. -void DecoratorDefender::ReleaseElementData(Rml::DecoratorDataHandle RMLUI_UNUSED_PARAMETER(element_data)) const -{ - RMLUI_UNUSED(element_data); -} +void DecoratorDefender::ReleaseElementData(Rml::DecoratorDataHandle /*element_data*/) const {} -// Called to render the decorator on an element. -void DecoratorDefender::RenderElement(Rml::Element* element, Rml::DecoratorDataHandle RMLUI_UNUSED_PARAMETER(element_data)) const +void DecoratorDefender::RenderElement(Rml::Element* element, Rml::DecoratorDataHandle /*element_data*/) const { - RMLUI_UNUSED(element_data); - Rml::Vector2f position = element->GetAbsoluteOffset(Rml::Box::PADDING); Rml::Vector2f size = element->GetBox().GetSize(Rml::Box::PADDING); Rml::Math::SnapToPixelGrid(position, size); diff --git a/Samples/luainvaders/src/DecoratorDefender.h b/Samples/luainvaders/src/DecoratorDefender.h index 0abfb0116..9f0e6e1f8 100644 --- a/Samples/luainvaders/src/DecoratorDefender.h +++ b/Samples/luainvaders/src/DecoratorDefender.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,8 +31,7 @@ #include -class DecoratorDefender : public Rml::Decorator -{ +class DecoratorDefender : public Rml::Decorator { public: virtual ~DecoratorDefender(); diff --git a/Samples/luainvaders/src/DecoratorInstancerDefender.cpp b/Samples/luainvaders/src/DecoratorInstancerDefender.cpp index 11ecc3b42..f8ede7366 100644 --- a/Samples/luainvaders/src/DecoratorInstancerDefender.cpp +++ b/Samples/luainvaders/src/DecoratorInstancerDefender.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,10 +27,10 @@ */ #include "DecoratorInstancerDefender.h" +#include "DecoratorDefender.h" #include #include #include -#include "DecoratorDefender.h" DecoratorInstancerDefender::DecoratorInstancerDefender() { @@ -38,16 +38,13 @@ DecoratorInstancerDefender::DecoratorInstancerDefender() RegisterShorthand("decorator", "image-src", Rml::ShorthandType::FallThrough); } -DecoratorInstancerDefender::~DecoratorInstancerDefender() -{ -} +DecoratorInstancerDefender::~DecoratorInstancerDefender() {} -// Instances a decorator given the property tag and attributes from the RCSS file. -Rml::SharedPtr DecoratorInstancerDefender::InstanceDecorator(const Rml::String& /*name*/, - const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& instancer_interface) +Rml::SharedPtr DecoratorInstancerDefender::InstanceDecorator(const Rml::String& /*name*/, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& instancer_interface) { const Rml::Property* image_source_property = properties.GetProperty(id_image_src); - Rml::String image_source = image_source_property->Get< Rml::String >(); + Rml::String image_source = image_source_property->Get(); Rml::Texture texture = instancer_interface.GetTexture(image_source); auto decorator = Rml::MakeShared(); diff --git a/Samples/luainvaders/src/DecoratorInstancerDefender.h b/Samples/luainvaders/src/DecoratorInstancerDefender.h index b99ddbd7f..3123f80d7 100644 --- a/Samples/luainvaders/src/DecoratorInstancerDefender.h +++ b/Samples/luainvaders/src/DecoratorInstancerDefender.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,17 +32,17 @@ #include /** - @author Robert Curry + @author Robert Curry */ -class DecoratorInstancerDefender : public Rml::DecoratorInstancer -{ +class DecoratorInstancerDefender : public Rml::DecoratorInstancer { public: DecoratorInstancerDefender(); ~DecoratorInstancerDefender(); /// Instances a decorator given the property tag and attributes from the RCSS file. - Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& instancer_interface) override; + Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& instancer_interface) override; private: Rml::PropertyId id_image_src; diff --git a/Samples/luainvaders/src/DecoratorInstancerStarfield.cpp b/Samples/luainvaders/src/DecoratorInstancerStarfield.cpp index 3dc4eb1da..e57706ab7 100644 --- a/Samples/luainvaders/src/DecoratorInstancerStarfield.cpp +++ b/Samples/luainvaders/src/DecoratorInstancerStarfield.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,10 +26,10 @@ * */ +#include "DecoratorInstancerStarfield.h" #include "DecoratorStarfield.h" #include #include -#include "DecoratorInstancerStarfield.h" DecoratorInstancerStarfield::DecoratorInstancerStarfield() { @@ -42,21 +42,18 @@ DecoratorInstancerStarfield::DecoratorInstancerStarfield() id_bottom_density = RegisterProperty("bottom-density", "10").AddParser("number").GetId(); } -DecoratorInstancerStarfield::~DecoratorInstancerStarfield() -{ -} +DecoratorInstancerStarfield::~DecoratorInstancerStarfield() {} -// Instances a decorator given the property tag and attributes from the RCSS file. -Rml::SharedPtr DecoratorInstancerStarfield::InstanceDecorator(const Rml::String& /*name*/, - const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& /*instancer_interface*/) +Rml::SharedPtr DecoratorInstancerStarfield::InstanceDecorator(const Rml::String& /*name*/, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& /*instancer_interface*/) { - int num_layers = Rml::Math::RealToInteger(properties.GetProperty(id_num_layers)->Get< float >()); - Rml::Colourb top_colour = properties.GetProperty(id_top_colour)->Get< Rml::Colourb >(); - Rml::Colourb bottom_colour = properties.GetProperty(id_bottom_colour)->Get< Rml::Colourb >(); - float top_speed = properties.GetProperty(id_top_speed)->Get< float >(); - float bottom_speed = properties.GetProperty(id_bottom_speed)->Get< float >(); - int top_density = Rml::Math::RealToInteger(properties.GetProperty(id_top_density)->Get< float >()); - int bottom_density = Rml::Math::RealToInteger(properties.GetProperty(id_bottom_density)->Get< float >()); + int num_layers = Rml::Math::RealToInteger(properties.GetProperty(id_num_layers)->Get()); + Rml::Colourb top_colour = properties.GetProperty(id_top_colour)->Get(); + Rml::Colourb bottom_colour = properties.GetProperty(id_bottom_colour)->Get(); + float top_speed = properties.GetProperty(id_top_speed)->Get(); + float bottom_speed = properties.GetProperty(id_bottom_speed)->Get(); + int top_density = Rml::Math::RealToInteger(properties.GetProperty(id_top_density)->Get()); + int bottom_density = Rml::Math::RealToInteger(properties.GetProperty(id_bottom_density)->Get()); auto decorator = Rml::MakeShared(); if (decorator->Initialise(num_layers, top_colour, bottom_colour, top_speed, bottom_speed, top_density, bottom_density)) diff --git a/Samples/luainvaders/src/DecoratorInstancerStarfield.h b/Samples/luainvaders/src/DecoratorInstancerStarfield.h index 7b3acb973..bd2873988 100644 --- a/Samples/luainvaders/src/DecoratorInstancerStarfield.h +++ b/Samples/luainvaders/src/DecoratorInstancerStarfield.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,21 +29,21 @@ #ifndef RMLUI_LUAINVADERS_DECORATORINSTANCERSTARFIELD_H #define RMLUI_LUAINVADERS_DECORATORINSTANCERSTARFIELD_H -#include #include "DecoratorStarfield.h" +#include /** - @author Robert Curry + @author Robert Curry */ -class DecoratorInstancerStarfield : public Rml::DecoratorInstancer -{ +class DecoratorInstancerStarfield : public Rml::DecoratorInstancer { public: DecoratorInstancerStarfield(); ~DecoratorInstancerStarfield(); /// Instances a decorator given the property tag and attributes from the RCSS file. - Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, const Rml::DecoratorInstancerInterface& instancer_interface) override; + Rml::SharedPtr InstanceDecorator(const Rml::String& name, const Rml::PropertyDictionary& properties, + const Rml::DecoratorInstancerInterface& instancer_interface) override; private: Rml::PropertyId id_num_layers, id_top_colour, id_bottom_colour, id_top_speed, id_bottom_speed, id_top_density, id_bottom_density; diff --git a/Samples/luainvaders/src/DecoratorStarfield.cpp b/Samples/luainvaders/src/DecoratorStarfield.cpp index cec9c767a..55fcbdf84 100644 --- a/Samples/luainvaders/src/DecoratorStarfield.cpp +++ b/Samples/luainvaders/src/DecoratorStarfield.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,11 +38,10 @@ #include #include -DecoratorStarfield::~DecoratorStarfield() -{ -} +DecoratorStarfield::~DecoratorStarfield() {} -bool DecoratorStarfield::Initialise(int _num_layers, const Rml::Colourb& _top_colour, const Rml::Colourb& _bottom_colour, float _top_speed, float _bottom_speed, int _top_density, int _bottom_density) +bool DecoratorStarfield::Initialise(int _num_layers, const Rml::Colourb& _top_colour, const Rml::Colourb& _bottom_colour, float _top_speed, + float _bottom_speed, int _top_density, int _bottom_density) { num_layers = _num_layers; top_colour = _top_colour; @@ -55,7 +54,6 @@ bool DecoratorStarfield::Initialise(int _num_layers, const Rml::Colourb& _top_co return true; } -/// Called on a decorator to generate any required per-element data for a newly decorated element. Rml::DecoratorDataHandle DecoratorStarfield::GenerateElementData(Rml::Element* element) const { const double t = Rml::GetSystemInterface()->GetElapsedTime(); @@ -82,8 +80,8 @@ Rml::DecoratorDataHandle DecoratorStarfield::GenerateElementData(Rml::Element* e { for (int j = 0; j < density; j++) { - star_field->star_layers[i].stars[j].x = (float) Rml::Math::RandomReal(star_field->dimensions.x); - star_field->star_layers[i].stars[j].y = (float) Rml::Math::RandomReal(star_field->dimensions.y); + star_field->star_layers[i].stars[j].x = (float)Rml::Math::RandomReal(star_field->dimensions.x); + star_field->star_layers[i].stars[j].y = (float)Rml::Math::RandomReal(star_field->dimensions.y); } } @@ -93,14 +91,11 @@ Rml::DecoratorDataHandle DecoratorStarfield::GenerateElementData(Rml::Element* e return reinterpret_cast(star_field); } -// Called to release element data generated by this decorator. void DecoratorStarfield::ReleaseElementData(Rml::DecoratorDataHandle element_data) const { delete reinterpret_cast(element_data); } - -// Called to render the decorator on an element. void DecoratorStarfield::RenderElement(Rml::Element* element, Rml::DecoratorDataHandle element_data) const { const double t = Rml::GetSystemInterface()->GetElapsedTime(); diff --git a/Samples/luainvaders/src/DecoratorStarfield.h b/Samples/luainvaders/src/DecoratorStarfield.h index 229357145..cc40e111f 100644 --- a/Samples/luainvaders/src/DecoratorStarfield.h +++ b/Samples/luainvaders/src/DecoratorStarfield.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,15 +29,15 @@ #ifndef RMLUI_LUAINVADERS_DECORATORSTARFIELD_H #define RMLUI_LUAINVADERS_DECORATORSTARFIELD_H -#include #include +#include -class DecoratorStarfield : public Rml::Decorator -{ +class DecoratorStarfield : public Rml::Decorator { public: virtual ~DecoratorStarfield(); - bool Initialise(int num_layers, const Rml::Colourb& top_colour, const Rml::Colourb& bottom_colour, float top_speed, float bottom_speed, int top_density, int bottom_density); + bool Initialise(int num_layers, const Rml::Colourb& top_colour, const Rml::Colourb& bottom_colour, float top_speed, float bottom_speed, + int top_density, int bottom_density); /// Called on a decorator to generate any required per-element data for a newly decorated element. /// @param[in] element The newly decorated element. @@ -61,21 +61,19 @@ class DecoratorStarfield : public Rml::Decorator int top_density; int bottom_density; - struct StarLayer - { - typedef Rml::Vector< Rml::Vector2f > StarList; + struct StarLayer { + typedef Rml::Vector StarList; StarList stars; Rml::Colourb colour; float speed; }; - struct StarField - { + struct StarField { void Update(double t); double last_update; Rml::Vector2f dimensions; - typedef Rml::Vector< StarLayer > StarLayerList; + typedef Rml::Vector StarLayerList; StarLayerList star_layers; }; }; diff --git a/Samples/luainvaders/src/Defender.cpp b/Samples/luainvaders/src/Defender.cpp index 845a80766..b75a9512a 100644 --- a/Samples/luainvaders/src/Defender.cpp +++ b/Samples/luainvaders/src/Defender.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,13 +27,13 @@ */ #include "Defender.h" -#include #include "Game.h" #include "GameDetails.h" #include "Invader.h" #include "Mothership.h" #include "Shield.h" #include "Sprite.h" +#include const float UPDATE_FREQ = 0.01f; const float MOVEMENT_SPEED = 300; @@ -57,20 +57,18 @@ Defender::Defender(Game* _game) state = ALIVE; render = true; } - -Defender::~Defender() -{ -} + +Defender::~Defender() {} void Defender::Update(double t) { float dt = float(t - defender_frame_start); if (dt < UPDATE_FREQ) return; - + dt = Rml::Math::Min(dt, 0.1f); - defender_frame_start = t; + defender_frame_start = t; position.x += (move_direction * dt * MOVEMENT_SPEED); @@ -82,7 +80,7 @@ void Defender::Update(double t) UpdateBullet(t); if (state == RESPAWN) - { + { // Switch the render flag so the defender "flickers" render = !render; @@ -91,7 +89,7 @@ void Defender::Update(double t) { state = ALIVE; render = true; - } + } } } @@ -124,30 +122,27 @@ void Defender::Fire() { if (!bullet_in_flight) { - bullet_position = position + Rml::Vector2f((SPRITE_WIDTH/2) - 4, 0); + bullet_position = position + Rml::Vector2f((SPRITE_WIDTH / 2) - 4, 0); bullet_in_flight = true; } } bool Defender::CheckHit(double t, const Rml::Vector2f& check_position) -{ +{ float sprite_width = defender_sprite.dimensions.x; float sprite_height = defender_sprite.dimensions.y; // If the position is within our bounds, set ourselves // as exploding and return a valid hit. - if (state == ALIVE - && check_position.x >= position.x - && check_position.x <= position.x + sprite_width - && check_position.y >= position.y - && check_position.y <= position.y + sprite_height) + if (state == ALIVE && check_position.x >= position.x && check_position.x <= position.x + sprite_width && check_position.y >= position.y && + check_position.y <= position.y + sprite_height) { game->RemoveLife(); state = RESPAWN; respawn_start = t; return true; - } + } return false; } diff --git a/Samples/luainvaders/src/Defender.h b/Samples/luainvaders/src/Defender.h index 8b32ae033..106df1eb9 100644 --- a/Samples/luainvaders/src/Defender.h +++ b/Samples/luainvaders/src/Defender.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,12 +35,11 @@ class Game; class Sprite; /** - Represents the Earth defender. Stores position and performs the update of the bullet position and collision detection. - @author Lloyd Weehuizen + Represents the Earth defender. Stores position and performs the update of the bullet position and collision detection. + @author Lloyd Weehuizen */ -class Defender -{ +class Defender { public: Defender(Game* game); ~Defender(); @@ -51,7 +50,7 @@ class Defender void Render(float dp_ratio, Rml::TextureHandle texture); /// Move the defender left. - void StartMove(float direction); + void StartMove(float direction); /// Stop the movement. void StopMove(float direction); /// Fire a bullet (if one isn't already in flight). @@ -65,10 +64,10 @@ class Defender void UpdateBullet(double t); Game* game; - Rml::Vector2f position; - + Rml::Vector2f position; + float move_direction; - + bool bullet_in_flight; Rml::Vector2f bullet_position; @@ -81,5 +80,4 @@ class Defender State state; }; - #endif diff --git a/Samples/luainvaders/src/ElementGame.cpp b/Samples/luainvaders/src/ElementGame.cpp index e16d87000..0e0d7eadb 100644 --- a/Samples/luainvaders/src/ElementGame.cpp +++ b/Samples/luainvaders/src/ElementGame.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,18 +42,16 @@ ElementGame::ElementGame(const Rml::String& tag) : Rml::Element(tag) } ElementGame::~ElementGame() -{ +{ delete game; } -// Intercepts and handles key events. void ElementGame::ProcessEvent(Rml::Event& event) { - if (event == Rml::EventId::Keydown || - event == Rml::EventId::Keyup) + if (event == Rml::EventId::Keydown || event == Rml::EventId::Keyup) { bool key_down = (event == Rml::EventId::Keydown); - Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); + Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter("key_identifier", 0); // Process left and right keys if (key_down) @@ -64,13 +62,13 @@ void ElementGame::ProcessEvent(Rml::Event& event) game->GetDefender()->StartMove(1.0f); if (key_identifier == Rml::Input::KI_SPACE) game->GetDefender()->Fire(); - } + } else if (!key_down) { if (key_identifier == Rml::Input::KI_LEFT) game->GetDefender()->StopMove(-1.0f); if (key_identifier == Rml::Input::KI_RIGHT) - game->GetDefender()->StopMove(1.0f); + game->GetDefender()->StopMove(1.0f); } } @@ -80,7 +78,6 @@ void ElementGame::ProcessEvent(Rml::Event& event) } } -// Updates the game. void ElementGame::OnUpdate() { game->Update(Rml::GetSystemInterface()->GetElapsedTime()); @@ -89,7 +86,6 @@ void ElementGame::OnUpdate() DispatchEvent("gameover", Rml::Dictionary()); } -// Renders the game. void ElementGame::OnRender() { game->Render(GetContext()->GetDensityIndependentPixelRatio()); diff --git a/Samples/luainvaders/src/ElementGame.h b/Samples/luainvaders/src/ElementGame.h index 98603a1aa..33dd029d4 100644 --- a/Samples/luainvaders/src/ElementGame.h +++ b/Samples/luainvaders/src/ElementGame.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,11 +35,10 @@ class Game; /** - @author Peter Curry + @author Peter Curry */ -class ElementGame : public Rml::Element, public Rml::EventListener -{ +class ElementGame : public Rml::Element, public Rml::EventListener { public: ElementGame(const Rml::String& tag); virtual ~ElementGame(); diff --git a/Samples/luainvaders/src/ElementGameInstancer.cpp b/Samples/luainvaders/src/ElementGameInstancer.cpp index e82111998..f7101d536 100644 --- a/Samples/luainvaders/src/ElementGameInstancer.cpp +++ b/Samples/luainvaders/src/ElementGameInstancer.cpp @@ -1,22 +1,14 @@ #include "ElementGameInstancer.h" #include "ElementGame.h" -ElementGameInstancer::~ElementGameInstancer() -{ -} - -// Instances an element given the tag name and attributes +ElementGameInstancer::~ElementGameInstancer() {} + Rml::ElementPtr ElementGameInstancer::InstanceElement(Rml::Element* /*parent*/, const Rml::String& tag, const Rml::XMLAttributes& /*attributes*/) { return Rml::ElementPtr(new ElementGame(tag)); } - - -// Releases the given element void ElementGameInstancer::ReleaseElement(Rml::Element* element) { delete element; } - - diff --git a/Samples/luainvaders/src/ElementGameInstancer.h b/Samples/luainvaders/src/ElementGameInstancer.h index 7021bd837..234a2713b 100644 --- a/Samples/luainvaders/src/ElementGameInstancer.h +++ b/Samples/luainvaders/src/ElementGameInstancer.h @@ -3,15 +3,14 @@ #include -class ElementGameInstancer : public Rml::ElementInstancer -{ +class ElementGameInstancer : public Rml::ElementInstancer { public: virtual ~ElementGameInstancer(); - + /// Instances an element given the tag name and attributes /// @param tag Name of the element to instance /// @param attributes vector of name value pairs - Rml::ElementPtr InstanceElement(Rml::Element* parent, const Rml::String& tag, const Rml::XMLAttributes& attributes) override; + Rml::ElementPtr InstanceElement(Rml::Element* parent, const Rml::String& tag, const Rml::XMLAttributes& attributes) override; /// Releases the given element /// @param element to release diff --git a/Samples/luainvaders/src/Game.cpp b/Samples/luainvaders/src/Game.cpp index 943ffdb36..27bfb8c03 100644 --- a/Samples/luainvaders/src/Game.cpp +++ b/Samples/luainvaders/src/Game.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,14 +27,14 @@ */ #include "Game.h" -#include -#include #include "Defender.h" #include "GameDetails.h" #include "HighScores.h" #include "Invader.h" #include "Mothership.h" #include "Shield.h" +#include +#include const int WINDOW_WIDTH = 1024; const int WINDOW_HEIGHT = 768; @@ -67,13 +67,13 @@ extern Rml::Context* context; Game::Game() { invader_frame_start = 0; - defender_lives = 3; + defender_lives = 3; invader_move_freq = 0; game_over = false; - current_invader_direction = 1.0f; + current_invader_direction = 1.0f; invaders = new Invader*[NUM_INVADERS + 1]; for (int i = 0; i < NUM_INVADERS + 1; i++) - invaders[i] = nullptr; + invaders[i] = nullptr; shields = new Shield*[NUM_SHIELDS]; for (int i = 0; i < NUM_SHIELDS; i++) @@ -91,12 +91,12 @@ Game::~Game() for (int i = 0; i < NUM_INVADERS + 1; i++) delete invaders[i]; - delete [] invaders; + delete[] invaders; for (int i = 0; i < NUM_SHIELDS; i++) delete shields[i]; - delete [] shields; + delete[] shields; } void Game::Initialise() @@ -124,21 +124,21 @@ void Game::Update(double t) // Determine if we should advance the invaders if (t - invader_frame_start >= invader_move_freq) { - MoveInvaders(); + MoveInvaders(); invader_frame_start = t; } // Update all invaders for (int i = 0; i < NUM_INVADERS + 1; i++) - invaders[i]->Update(t); + invaders[i]->Update(t); defender->Update(t); } } void Game::Render(float dp_ratio) -{ +{ if (defender_lives <= 0) return; @@ -190,25 +190,21 @@ bool Game::CanDropBomb(int index) return true; } -// Access the shields. Shield* Game::GetShield(int index) { return shields[index]; } -// Get the total number of shields int Game::GetNumShields() { return NUM_SHIELDS; } -// Adds a score onto the player's score. void Game::AddScore(int score) { SetScore(GameDetails::GetScore() + score); } -// Sets the player's score. void Game::SetScore(int score) { GameDetails::SetScore(score); @@ -222,7 +218,6 @@ void Game::SetScore(int score) SetHighScore(score); } -// Sets the player's high-score. void Game::SetHighScore(int score) { Rml::Element* high_score_element = context->GetDocument("game_window")->GetElementById("hiscore"); @@ -249,7 +244,7 @@ void Game::SetWave(int wave) } void Game::RemoveLife() -{ +{ if (defender_lives > 0) { SetLives(defender_lives - 1); @@ -268,7 +263,7 @@ bool Game::IsGameOver() const const Rml::Vector2f Game::GetWindowDimensions() { - return Rml::Vector2f((float) WINDOW_WIDTH, (float) WINDOW_HEIGHT); + return Rml::Vector2f((float)WINDOW_WIDTH, (float)WINDOW_HEIGHT); } void Game::MoveInvaders() @@ -302,7 +297,7 @@ void Game::MoveInvaders() } // Increase speed of invaders - invader_move_freq *= INVADER_UPDATE_MODIFIER; + invader_move_freq *= INVADER_UPDATE_MODIFIER; } } @@ -343,7 +338,7 @@ void Game::OnGameOver() void Game::InitialiseShields() { - Rml::Vector2f shield_array_start_position((float) SHIELD_START_X, (float) SHIELD_START_Y); + Rml::Vector2f shield_array_start_position((float)SHIELD_START_X, (float)SHIELD_START_Y); for (int x = 0; x < NUM_SHIELD_ARRAYS; x++) { @@ -359,13 +354,12 @@ void Game::InitialiseShields() } shields[(x * NUM_SHIELDS_PER_ARRAY) + i] = new Shield(this, type); - shields[(x * NUM_SHIELDS_PER_ARRAY) + i]->SetPosition(shield_array_start_position + Rml::Vector2f((float) SHIELD_SIZE * i, 0)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + i]->SetPosition(shield_array_start_position + Rml::Vector2f((float)SHIELD_SIZE * i, 0)); } // Middle row (row of 4) for (int i = 0; i < 4; i++) { - Shield::ShieldType type = Shield::REGULAR; if (i == 1) type = Shield::BOTTOM_RIGHT; @@ -375,15 +369,17 @@ void Game::InitialiseShields() } shields[(x * NUM_SHIELDS_PER_ARRAY) + 4 + i] = new Shield(this, type); - shields[(x * NUM_SHIELDS_PER_ARRAY) + 4 + i]->SetPosition(shield_array_start_position + Rml::Vector2f((float) SHIELD_SIZE * i, (float) SHIELD_SIZE)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + 4 + i]->SetPosition( + shield_array_start_position + Rml::Vector2f((float)SHIELD_SIZE * i, (float)SHIELD_SIZE)); } // Bottom row (2, one on each end) shields[(x * NUM_SHIELDS_PER_ARRAY) + 8] = new Shield(this, Shield::REGULAR); - shields[(x * NUM_SHIELDS_PER_ARRAY) + 8]->SetPosition(shield_array_start_position + Rml::Vector2f(0, (float) SHIELD_SIZE * 2)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + 8]->SetPosition(shield_array_start_position + Rml::Vector2f(0, (float)SHIELD_SIZE * 2)); shields[(x * NUM_SHIELDS_PER_ARRAY) + 9] = new Shield(this, Shield::REGULAR); - shields[(x * NUM_SHIELDS_PER_ARRAY) + 9]->SetPosition(shield_array_start_position + Rml::Vector2f((float) SHIELD_SIZE * 3, (float) SHIELD_SIZE * 2)); + shields[(x * NUM_SHIELDS_PER_ARRAY) + 9]->SetPosition( + shield_array_start_position + Rml::Vector2f((float)SHIELD_SIZE * 3, (float)SHIELD_SIZE * 2)); shield_array_start_position.x += SHIELD_SPACING_X; } @@ -398,26 +394,24 @@ void Game::InitialiseWave() Invader::InvaderType type = Invader::UNKNOWN; switch (y) { - case 0: - type = Invader::RANK3; break; + case 0: type = Invader::RANK3; break; case 1: - case 2: - type = Invader::RANK2; break; - default: - type = Invader::RANK1; break; + case 2: type = Invader::RANK2; break; + default: type = Invader::RANK1; break; } // Determine position of top left invader - Rml::Vector2f invader_position((float) (WINDOW_WIDTH - (NUM_INVADERS_PER_ROW * INVADER_SPACING_X)) / 2, (float) (INVADER_START_Y + (y * INVADER_SPACING_Y))); - + Rml::Vector2f invader_position((float)(WINDOW_WIDTH - (NUM_INVADERS_PER_ROW * INVADER_SPACING_X)) / 2, + (float)(INVADER_START_Y + (y * INVADER_SPACING_Y))); + for (int x = 0; x < NUM_INVADERS_PER_ROW; x++) { // Determine invader type based on row position int index = (y * NUM_INVADERS_PER_ROW) + x; delete invaders[index]; - invaders[index] = new Invader(this, type, (y * NUM_INVADERS_PER_ROW) + x); - invaders[index]->SetPosition(invader_position); + invaders[index] = new Invader(this, type, (y * NUM_INVADERS_PER_ROW) + x); + invaders[index]->SetPosition(invader_position); // Increase invader position invader_position.x += INVADER_SPACING_X; @@ -428,7 +422,7 @@ void Game::InitialiseWave() delete invaders[MOTHERSHIP]; invaders[MOTHERSHIP] = new Mothership(this, MOTHERSHIP); - // Update the move frequency - invader_move_freq = ((float)GameDetails::GetWave()-100.0f)/140.0f; + // Update the move frequency + invader_move_freq = ((float)GameDetails::GetWave() - 100.0f) / 140.0f; invader_move_freq *= invader_move_freq; } diff --git a/Samples/luainvaders/src/Game.h b/Samples/luainvaders/src/Game.h index 7d8c17553..1acd060e2 100644 --- a/Samples/luainvaders/src/Game.h +++ b/Samples/luainvaders/src/Game.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_LUAINVADERS_GAME_H #define RMLUI_LUAINVADERS_GAME_H -#include #include +#include class Shield; class Invader; @@ -38,15 +38,14 @@ class Defender; class Mothership; /** - Runs the game. - - Updates the Invader positions, animations and bombs. - - Updates the player position and bullets + Runs the game. + - Updates the Invader positions, animations and bombs. + - Updates the player position and bullets - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class Game -{ +class Game { public: Game(); ~Game(); @@ -94,7 +93,6 @@ class Game const Rml::Vector2f GetWindowDimensions(); private: - // The current invaders Invader** invaders; // The direction they're moving diff --git a/Samples/luainvaders/src/GameDetails.cpp b/Samples/luainvaders/src/GameDetails.cpp index 508ff081c..95da28be3 100644 --- a/Samples/luainvaders/src/GameDetails.cpp +++ b/Samples/luainvaders/src/GameDetails.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,111 +38,90 @@ static GameDetails::GraphicsQuality graphics_quality = GameDetails::OK; static bool reverb = true; static bool spatialisation = false; -GameDetails::GameDetails() -{ -} +GameDetails::GameDetails() {} -GameDetails::~GameDetails() -{ -} +GameDetails::~GameDetails() {} -// Sets the game difficulty. void GameDetails::SetDifficulty(Difficulty _difficulty) { difficulty = _difficulty; } -// Returns the game difficulty. GameDetails::Difficulty GameDetails::GetDifficulty() { return difficulty; } -// Sets the colour of the player's ship. void GameDetails::SetDefenderColour(const Rml::Colourb& _colour) { colour = _colour; } -// Returns the player's ship colour. const Rml::Colourb& GameDetails::GetDefenderColour() { return colour; } -// Sets the score the player achieved in the last game. void GameDetails::SetScore(int _score) { score = _score; } -// Resets the player's score. void GameDetails::ResetScore() { score = -1; } -// Returns the score the player achieved in the last game. int GameDetails::GetScore() { return score; } -// Set the current wave number void GameDetails::SetWave(int _wave) { wave = _wave; } -// Get the current wave number int GameDetails::GetWave() { return wave; } -// Sets the pauses state of the game void GameDetails::SetPaused(bool _paused) { paused = _paused; } -// Gets if the game is paused or not bool GameDetails::GetPaused() { return paused; } -// Sets the quality of the graphics used in-game. void GameDetails::SetGraphicsQuality(GraphicsQuality quality) { graphics_quality = quality; } -// Returns the quality of the graphics to use in-game. GameDetails::GraphicsQuality GameDetails::GetGraphicsQuality() { return graphics_quality; } -// Enables or disables reverb. void GameDetails::SetReverb(bool enabled) { reverb = enabled; } -// Returns the current state of reverb. bool GameDetails::GetReverb() { return reverb; } -// Enables or disables 3D spatialisation in the audio engine. void GameDetails::Set3DSpatialisation(bool enabled) { spatialisation = enabled; } -// Returns the current state of audio spatialisation. bool GameDetails::Get3DSpatialisation() { return spatialisation; diff --git a/Samples/luainvaders/src/GameDetails.h b/Samples/luainvaders/src/GameDetails.h index 806a8eea4..d226b480a 100644 --- a/Samples/luainvaders/src/GameDetails.h +++ b/Samples/luainvaders/src/GameDetails.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,11 +32,10 @@ #include /** - @author Peter Curry + @author Peter Curry */ -class GameDetails -{ +class GameDetails { public: enum Difficulty { EASY, HARD }; diff --git a/Samples/luainvaders/src/HighScores.cpp b/Samples/luainvaders/src/HighScores.cpp index 302605068..bf5e00e8b 100644 --- a/Samples/luainvaders/src/HighScores.cpp +++ b/Samples/luainvaders/src/HighScores.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,11 +27,11 @@ */ #include "HighScores.h" -#include #include #include -#include +#include #include +#include HighScores* HighScores::instance = nullptr; @@ -99,7 +99,6 @@ void HighScores::SubmitScore(const Rml::Colourb& colour, int wave, int score) instance->SubmitScore("", colour, wave, score, true); } -// Sets the name of the last player to submit their score. void HighScores::SubmitName(const Rml::String& name) { for (Score& score : instance->scores) @@ -153,9 +152,9 @@ void HighScores::LoadScores() int wave; int score; - if (Rml::TypeConverter< Rml::String, Rml::Colourb >::Convert(score_parts[1], colour) && - Rml::TypeConverter< Rml::String, int >::Convert(score_parts[2], wave) && - Rml::TypeConverter< Rml::String, int >::Convert(score_parts[3], score)) + if (Rml::TypeConverter::Convert(score_parts[1], colour) && + Rml::TypeConverter::Convert(score_parts[2], wave) && + Rml::TypeConverter::Convert(score_parts[3], score)) { SubmitScore(score_parts[0], colour, wave, score); } @@ -175,7 +174,7 @@ void HighScores::SaveScores() for (const Score& score : scores) { Rml::String colour_string; - Rml::TypeConverter< Rml::Colourb, Rml::String >::Convert(score.colour, colour_string); + Rml::TypeConverter::Convert(score.colour, colour_string); Rml::String score_str = Rml::CreateString(1024, "%s\t%s\t%d\t%d\n", score.name.c_str(), colour_string.c_str(), score.wave, score.score); fputs(score_str.c_str(), scores_file); diff --git a/Samples/luainvaders/src/HighScores.h b/Samples/luainvaders/src/HighScores.h index e0dc7cfed..42fb56561 100644 --- a/Samples/luainvaders/src/HighScores.h +++ b/Samples/luainvaders/src/HighScores.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,11 +29,10 @@ #ifndef RMLUI_LUAINVADERS_HIGHSCORES_H #define RMLUI_LUAINVADERS_HIGHSCORES_H -#include #include +#include -class HighScores -{ +class HighScores { public: static void Initialise(Rml::Context* context); static void Shutdown(); @@ -58,19 +57,16 @@ class HighScores void LoadScores(); void SaveScores(); - struct Score - { + struct Score { Rml::String name; bool name_required; Rml::Colourb colour; int score; int wave; - Rml::String GetColour() { - return "rgba(" + Rml::ToString(colour) + ')'; - } + Rml::String GetColour() { return "rgba(" + Rml::ToString(colour) + ')'; } }; - using ScoreList = Rml::Vector< Score >; + using ScoreList = Rml::Vector; ScoreList scores; Rml::DataModelHandle model_handle; diff --git a/Samples/luainvaders/src/Invader.cpp b/Samples/luainvaders/src/Invader.cpp index 56be3712a..328610d11 100644 --- a/Samples/luainvaders/src/Invader.cpp +++ b/Samples/luainvaders/src/Invader.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,13 +27,13 @@ */ #include "Invader.h" -#include -#include #include "Defender.h" #include "Game.h" #include "GameDetails.h" #include "Shield.h" #include "Sprite.h" +#include +#include const float BOMB_UPDATE_FREQ = 0.04f; const float BOMB_RAY_SPEED = 10; @@ -43,8 +43,7 @@ const float BOMB_PROBABILITY_HARD = 0.005f; const float EXPLOSION_TIME = 0.25f; const Rml::Colourb MOTHERSHIP_COLOUR = Rml::Colourb(255, 0, 0, 255); -Sprite invader_sprites[] = -{ +Sprite invader_sprites[] = { // Rank 1 Sprite(Rml::Vector2f(48, 32), Rml::Vector2f(0.609375f, 0), Rml::Vector2f(0.796875f, 0.5f)), Sprite(Rml::Vector2f(48, 32), Rml::Vector2f(0.80078125f, 0), Rml::Vector2f(0.98828125f, 0.5f)), @@ -57,21 +56,18 @@ Sprite invader_sprites[] = // Mothership Sprite(Rml::Vector2f(64, 28), Rml::Vector2f(0.23828125f, 0.515625f), Rml::Vector2f(0.48828125f, 0.953125f)), // Explosion - Sprite(Rml::Vector2f(52, 28), Rml::Vector2f(0.71484375f, 0.51562500f), Rml::Vector2f(0.91796875f, 0.95312500f)) -}; + Sprite(Rml::Vector2f(52, 28), Rml::Vector2f(0.71484375f, 0.51562500f), Rml::Vector2f(0.91796875f, 0.95312500f))}; -Sprite bomb_sprites[] = -{ +Sprite bomb_sprites[] = { // Ray Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.51171875f, 0.51562500f), Rml::Vector2f(0.55859375f, 0.82812500f)), Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.56250000, 0.51562500), Rml::Vector2f(0.60937500, 0.82812500)), Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.61328125, 0.51562500), Rml::Vector2f(0.66015625, 0.82812500)), Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.66406250, 0.51562500), Rml::Vector2f(0.71093750, 0.82812500)), // Missile - Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.92578125, 0.51562500), Rml::Vector2f(0.97265625, 0.82812500)) -}; + Sprite(Rml::Vector2f(12, 20), Rml::Vector2f(0.92578125, 0.51562500), Rml::Vector2f(0.97265625, 0.82812500))}; -Invader::Invader(Game* _game, InvaderType _type, int _index) : position(0,0) +Invader::Invader(Game* _game, InvaderType _type, int _index) : position(0, 0) { type = UNKNOWN; animation_frame = 0; @@ -89,9 +85,7 @@ Invader::Invader(Game* _game, InvaderType _type, int _index) : position(0,0) bomb_probability *= float(type); } -Invader::~Invader() -{ -} +Invader::~Invader() {} void Invader::SetPosition(const Rml::Vector2f& _position) { @@ -107,8 +101,7 @@ void Invader::Update(double t) { // Update the bombs if (float(t - bomb_frame_start) > BOMB_UPDATE_FREQ) - { - + { // Update the bomb position if its in flight, or check if we should drop one if (bomb != NONE) { @@ -124,7 +117,7 @@ void Invader::Update(double t) { bomb_position.y += BOMB_MISSILE_SPEED; } - + if (bomb_position.y > game->GetWindowDimensions().y) bomb = NONE; @@ -145,9 +138,7 @@ void Invader::Update(double t) bomb = NONE; } } - else if ( state == ALIVE - && Rml::Math::RandomReal(1.0f) < bomb_probability - && game->CanDropBomb(invader_index)) + else if (state == ALIVE && Rml::Math::RandomReal(1.0f) < bomb_probability && game->CanDropBomb(invader_index)) { bomb = Rml::Math::RandomInteger(2) == 0 ? RAY : MISSILE; bomb_position = position; @@ -157,7 +148,7 @@ void Invader::Update(double t) bomb_animation_frame = 0; else bomb_animation_frame = 4; - } + } bomb_frame_start = t; } @@ -176,8 +167,7 @@ void Invader::UpdateAnimation() animation_frame = 0; break; - default: - break; + default: break; } } @@ -193,7 +183,7 @@ void Invader::Render(float dp_ratio, Rml::TextureHandle texture) if (state != DEAD) invader_sprites[sprite_index].Render(Rml::Vector2f(position.x - sprite_offset, position.y), dp_ratio, color, texture); - + if (bomb != NONE) bomb_sprites[bomb_animation_frame].Render(bomb_position, dp_ratio, color, texture); } @@ -213,20 +203,17 @@ bool Invader::CheckHit(double t, const Rml::Vector2f& check_position) // If we're alive and the position is within our bounds, set ourselves // as exploding and return a valid hit - if (state == ALIVE - && check_position.x >= position.x - sprite_offset - && check_position.x <= position.x - sprite_offset + sprite_width - && check_position.y >= position.y - && check_position.y <= position.y + sprite_height) + if (state == ALIVE && check_position.x >= position.x - sprite_offset && check_position.x <= position.x - sprite_offset + sprite_width && + check_position.y >= position.y && check_position.y <= position.y + sprite_height) { int score = 0; switch (type) { - RMLUI_UNUSED_SWITCH_ENUM(UNKNOWN); - case MOTHERSHIP: score = (Rml::Math::RandomInteger(6) + 1) * 50; break; // 50 -> 300 - case RANK3: score = 40; break; - case RANK2: score = 20; break; - case RANK1: score = 10; break; + case MOTHERSHIP: score = (Rml::Math::RandomInteger(6) + 1) * 50; break; // 50 -> 300 + case RANK3: score = 40; break; + case RANK2: score = 20; break; + case RANK1: score = 10; break; + case UNKNOWN: break; } // Add the number of points @@ -234,7 +221,7 @@ bool Invader::CheckHit(double t, const Rml::Vector2f& check_position) // Set our state to exploding and start the timer to our doom state = EXPLODING; - death_time = t + EXPLOSION_TIME; + death_time = t + EXPLOSION_TIME; return true; } @@ -248,11 +235,11 @@ int Invader::GetSpriteIndex() const int index = animation_frame; switch (type) { - RMLUI_UNUSED_SWITCH_ENUM(UNKNOWN); - case RANK1: break; // animation_frame is the right index already - case RANK2: index += 2; break; - case RANK3: index += 4; break; - case MOTHERSHIP: index = 6; break; + case RANK1: break; // animation_frame is the right index already + case RANK2: index += 2; break; + case RANK3: index += 4; break; + case MOTHERSHIP: index = 6; break; + case UNKNOWN: break; } // If we're in exploding state, use the exploding sprite diff --git a/Samples/luainvaders/src/Invader.h b/Samples/luainvaders/src/Invader.h index 9b866bba8..780d6eafe 100644 --- a/Samples/luainvaders/src/Invader.h +++ b/Samples/luainvaders/src/Invader.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ class Game; /** - An alien invader. + An alien invader. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class Invader -{ +class Invader { public: enum InvaderType { UNKNOWN, RANK1, RANK2, RANK3, MOTHERSHIP }; enum BombType { NONE, RAY, MISSILE }; diff --git a/Samples/luainvaders/src/LuaInterface.cpp b/Samples/luainvaders/src/LuaInterface.cpp index 0f1e4d02e..1c48b65d7 100644 --- a/Samples/luainvaders/src/LuaInterface.cpp +++ b/Samples/luainvaders/src/LuaInterface.cpp @@ -11,8 +11,10 @@ #include #include -//we have to create the binding ourselves, and these are the functions that will be -//called. It has to match the function signature of int (*ftnptr)(lua_State*) +/* + * We have to create the binding ourselves, and these are the functions that will be + * called. It has to match the function signature of int (*ftnptr)(lua_State*). + */ int GameShutdown(lua_State* L); int GameSetPaused(lua_State* L); int GameSetDifficulty(lua_State* L); @@ -24,97 +26,97 @@ static ElementGameInstancer game_instancer; void LuaInterface::Initialise(lua_State* L) { - InitGame(L); - Rml::Factory::RegisterElementInstancer("game", &game_instancer); + InitGame(L); + Rml::Factory::RegisterElementInstancer("game", &game_instancer); } -void LuaInterface::InitGame(lua_State *L) +void LuaInterface::InitGame(lua_State* L) { - luaL_dostring(L,"Game = Game or {}"); //doing this in Lua because it would be 10+ lines in C++ - lua_getglobal(L,"Game"); - int game = lua_gettop(L); + luaL_dostring(L, "Game = Game or {}"); // doing this in Lua because it would be 10+ lines in C++ + lua_getglobal(L, "Game"); + int game = lua_gettop(L); - if(lua_isnil(L,game)) - { - Rml::Log::Message(Rml::Log::LT_ERROR, "Error creating the Game table from C++ in LuaInterface::InitGame"); - return; - } - - //this can be done in a loop similar to the implementation of LuaType::_regfunctions, but I am - //defining them explicitly so that there is no black magic - lua_pushcfunction(L,GameShutdown); - lua_setfield(L, game, "Shutdown"); + if (lua_isnil(L, game)) + { + Rml::Log::Message(Rml::Log::LT_ERROR, "Error creating the Game table from C++ in LuaInterface::InitGame"); + return; + } - lua_pushcfunction(L,GameSetPaused); - lua_setfield(L,game,"SetPaused"); + // this can be done in a loop similar to the implementation of LuaType::_regfunctions, but I am + // defining them explicitly so that there is no black magic + lua_pushcfunction(L, GameShutdown); + lua_setfield(L, game, "Shutdown"); - lua_pushcfunction(L,GameSetDifficulty); - lua_setfield(L,game,"SetDifficulty"); + lua_pushcfunction(L, GameSetPaused); + lua_setfield(L, game, "SetPaused"); - lua_pushcfunction(L,GameSetDefenderColour); - lua_setfield(L,game,"SetDefenderColour"); + lua_pushcfunction(L, GameSetDifficulty); + lua_setfield(L, game, "SetDifficulty"); - lua_pushcfunction(L,GameSubmitHighScore); - lua_setfield(L,game,"SubmitHighScore"); + lua_pushcfunction(L, GameSetDefenderColour); + lua_setfield(L, game, "SetDefenderColour"); - lua_pushcfunction(L,GameSetHighScoreName); - lua_setfield(L,game,"SetHighScoreName"); + lua_pushcfunction(L, GameSubmitHighScore); + lua_setfield(L, game, "SubmitHighScore"); - lua_newtable(L); //table, Game - lua_pushinteger(L,GameDetails::HARD); //int,table,Game - lua_setfield(L,-2,"HARD");//table,Game + lua_pushcfunction(L, GameSetHighScoreName); + lua_setfield(L, game, "SetHighScoreName"); - lua_pushinteger(L,GameDetails::EASY); //int,table,Game - lua_setfield(L,-2,"EASY"); //table,Game + lua_newtable(L); // table, Game + lua_pushinteger(L, GameDetails::HARD); // int,table,Game + lua_setfield(L, -2, "HARD"); // table,Game - lua_setfield(L,game,"difficulty"); //Game + lua_pushinteger(L, GameDetails::EASY); // int,table,Game + lua_setfield(L, -2, "EASY"); // table,Game - lua_pop(L,1); //pop Game + lua_setfield(L, game, "difficulty"); // Game + + lua_pop(L, 1); // pop Game } int GameShutdown(lua_State* /*L*/) { - Backend::RequestExit(); - return 0; + Backend::RequestExit(); + return 0; } int GameSetPaused(lua_State* L) { - bool paused = RMLUI_CHECK_BOOL(L,1); //RMLUI_CHECK_BOOL defined in LuaType.h - GameDetails::SetPaused(paused); - return 0; + bool paused = RMLUI_CHECK_BOOL(L, 1); // RMLUI_CHECK_BOOL defined in LuaType.h + GameDetails::SetPaused(paused); + return 0; } int GameSetDifficulty(lua_State* L) { - int difficulty = (int)luaL_checkinteger(L,1); - GameDetails::SetDifficulty((GameDetails::Difficulty)difficulty); - return 0; + int difficulty = (int)luaL_checkinteger(L, 1); + GameDetails::SetDifficulty((GameDetails::Difficulty)difficulty); + return 0; } int GameSetDefenderColour(lua_State* L) { - Rml::Colourb* colour = Rml::Lua::LuaType::check(L,1); - GameDetails::SetDefenderColour(*colour); - return 0; + Rml::Colourb* colour = Rml::Lua::LuaType::check(L, 1); + GameDetails::SetDefenderColour(*colour); + return 0; } int GameSubmitHighScore(lua_State* /*L*/) { - int score = GameDetails::GetScore(); - if(score > 0) - { - // Submit the score the player just got to the high scores chart. - HighScores::SubmitScore(GameDetails::GetDefenderColour(),GameDetails::GetWave(), GameDetails::GetScore()); - // Reset the score so the chart won't get confused next time we enter. - GameDetails::ResetScore(); - } - return 0; + int score = GameDetails::GetScore(); + if (score > 0) + { + // Submit the score the player just got to the high scores chart. + HighScores::SubmitScore(GameDetails::GetDefenderColour(), GameDetails::GetWave(), GameDetails::GetScore()); + // Reset the score so the chart won't get confused next time we enter. + GameDetails::ResetScore(); + } + return 0; } int GameSetHighScoreName(lua_State* L) { - const char* name = luaL_checkstring(L,1); - HighScores::SubmitName(name); - return 0; + const char* name = luaL_checkstring(L, 1); + HighScores::SubmitName(name); + return 0; } diff --git a/Samples/luainvaders/src/LuaInterface.h b/Samples/luainvaders/src/LuaInterface.h index f9cb66955..30317214f 100644 --- a/Samples/luainvaders/src/LuaInterface.h +++ b/Samples/luainvaders/src/LuaInterface.h @@ -1,5 +1,5 @@ #ifndef RMLUI_LUAINVADERS_LUAINTERFACE_H -#define RMLUI_LUAINVADERS_LUAINTERFACE_H +#define RMLUI_LUAINVADERS_LUAINTERFACE_H /* This will define the "Game" global table in Lua and some functions with it. @@ -17,11 +17,10 @@ struct lua_State; class Game; -class LuaInterface -{ +class LuaInterface { public: - static void Initialise(lua_State* L); - static void InitGame(lua_State* L); + static void Initialise(lua_State* L); + static void InitGame(lua_State* L); }; -#endif \ No newline at end of file +#endif diff --git a/Samples/luainvaders/src/Mothership.cpp b/Samples/luainvaders/src/Mothership.cpp index bb8516224..4aac25e92 100644 --- a/Samples/luainvaders/src/Mothership.cpp +++ b/Samples/luainvaders/src/Mothership.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,10 +27,10 @@ */ #include "Mothership.h" -#include -#include "Shell.h" #include "Game.h" +#include "Shell.h" #include "Sprite.h" +#include const int SPRITE_WIDTH = 64; @@ -47,9 +47,7 @@ Mothership::Mothership(Game* game, int index) : Invader(game, Invader::MOTHERSHI position = Rml::Vector2f(-SPRITE_WIDTH, 64.0f); } -Mothership::~Mothership() -{ -} +Mothership::~Mothership() {} void Mothership::Update(double t) { @@ -64,8 +62,7 @@ void Mothership::Update(double t) { position.x += (direction * MOVEMENT_SPEED); - if ((direction < 0.0f && position.x < -SPRITE_WIDTH) - || (direction > 0.0f && position.x > game->GetWindowDimensions().x)) + if ((direction < 0.0f && position.x < -SPRITE_WIDTH) || (direction > 0.0f && position.x > game->GetWindowDimensions().x)) state = DEAD; update_frame_start = t; diff --git a/Samples/luainvaders/src/Mothership.h b/Samples/luainvaders/src/Mothership.h index 207c0e16e..0d8c19e95 100644 --- a/Samples/luainvaders/src/Mothership.h +++ b/Samples/luainvaders/src/Mothership.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,8 +34,7 @@ /** */ -class Mothership : public Invader -{ +class Mothership : public Invader { public: Mothership(Game* game, int index); ~Mothership(); diff --git a/Samples/luainvaders/src/Shield.cpp b/Samples/luainvaders/src/Shield.cpp index 8d4745e18..741e2637e 100644 --- a/Samples/luainvaders/src/Shield.cpp +++ b/Samples/luainvaders/src/Shield.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,14 +27,14 @@ */ #include "Shield.h" -#include #include "Game.h" #include "GameDetails.h" #include "Sprite.h" +#include const int MAX_HEALTH = 4; -Shield::Shield(Game* _game, ShieldType _type) : position(0,0) +Shield::Shield(Game* _game, ShieldType _type) : position(0, 0) { game = _game; type = _type; @@ -43,9 +43,7 @@ Shield::Shield(Game* _game, ShieldType _type) : position(0,0) InitialiseCells(); } -Shield::~Shield() -{ -} +Shield::~Shield() {} void Shield::InitialiseCells() { @@ -151,11 +149,8 @@ bool Shield::CheckHit(const Rml::Vector2f& check_position) // If we're alive and the position is within our bounds, set ourselves // as exploding and return a valid hit - if (health > 0 - && check_position.x >= position.x - && check_position.x <= position.x + sprite_size - && check_position.y >= position.y - && check_position.y <= position.y + sprite_size) + if (health > 0 && check_position.x >= position.x && check_position.x <= position.x + sprite_size && check_position.y >= position.y && + check_position.y <= position.y + sprite_size) { // Take damage. SustainDamage(); diff --git a/Samples/luainvaders/src/Shield.h b/Samples/luainvaders/src/Shield.h index 0ca928188..ebe8d128f 100644 --- a/Samples/luainvaders/src/Shield.h +++ b/Samples/luainvaders/src/Shield.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ const int NUM_SHIELD_CELLS = 6; const int PIXEL_SIZE = 4; /** - A shield, protecting the player. + A shield, protecting the player. - @author Robert Curry + @author Robert Curry */ -class Shield -{ +class Shield { public: enum ShieldType { REGULAR, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; diff --git a/Samples/luainvaders/src/Sprite.cpp b/Samples/luainvaders/src/Sprite.cpp index a1d2ffa5a..e5545ae00 100644 --- a/Samples/luainvaders/src/Sprite.cpp +++ b/Samples/luainvaders/src/Sprite.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/luainvaders/src/Sprite.h b/Samples/luainvaders/src/Sprite.h index 1251b4695..ae2c7f740 100644 --- a/Samples/luainvaders/src/Sprite.h +++ b/Samples/luainvaders/src/Sprite.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,7 +32,7 @@ #include /** - @author Peter Curry + @author Peter Curry */ class Sprite { diff --git a/Samples/luainvaders/src/main.cpp b/Samples/luainvaders/src/main.cpp index e771dee6a..191e1689f 100644 --- a/Samples/luainvaders/src/main.cpp +++ b/Samples/luainvaders/src/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -96,8 +96,8 @@ int main(int /*argc*/, char** /*argv*/) HighScores::Initialise(context); // Fire off the startup script. - LuaInterface::Initialise(Rml::Lua::Interpreter::GetLuaState()); //the tables/functions defined in the samples - Rml::Lua::Interpreter::LoadFile(Rml::String("luainvaders/lua/start.lua")); + LuaInterface::Initialise(Rml::Lua::Interpreter::GetLuaState()); // the tables/functions defined in the samples + Rml::Lua::Interpreter::LoadFile(Rml::String("luainvaders/lua/start.lua")); bool running = true; while (running) diff --git a/Samples/shell/include/PlatformExtensions.h b/Samples/shell/include/PlatformExtensions.h index be0f96782..328c0f7c2 100644 --- a/Samples/shell/include/PlatformExtensions.h +++ b/Samples/shell/include/PlatformExtensions.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/shell/include/RendererExtensions.h b/Samples/shell/include/RendererExtensions.h index 2e1fe2824..a5ad181f2 100644 --- a/Samples/shell/include/RendererExtensions.h +++ b/Samples/shell/include/RendererExtensions.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/shell/include/Shell.h b/Samples/shell/include/Shell.h index e358e7083..a4749a7fc 100644 --- a/Samples/shell/include/Shell.h +++ b/Samples/shell/include/Shell.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/shell/include/ShellFileInterface.h b/Samples/shell/include/ShellFileInterface.h index 6b98a3948..0a08b57d0 100644 --- a/Samples/shell/include/ShellFileInterface.h +++ b/Samples/shell/include/ShellFileInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,33 +29,32 @@ #ifndef RMLUI_SHELL_SHELLFILEINTERFACE_H #define RMLUI_SHELL_SHELLFILEINTERFACE_H -#include #include +#include /** - RmlUi file interface for the shell examples. - @author Lloyd Weehuizen + RmlUi file interface for the shell examples. + @author Lloyd Weehuizen */ -class ShellFileInterface : public Rml::FileInterface -{ +class ShellFileInterface : public Rml::FileInterface { public: ShellFileInterface(const Rml::String& root); virtual ~ShellFileInterface(); - /// Opens a file. + /// Opens a file. Rml::FileHandle Open(const Rml::String& path) override; - /// Closes a previously opened file. + /// Closes a previously opened file. void Close(Rml::FileHandle file) override; - /// Reads data from a previously opened file. + /// Reads data from a previously opened file. size_t Read(void* buffer, size_t size, Rml::FileHandle file) override; - /// Seeks to a point in a previously opened file. + /// Seeks to a point in a previously opened file. bool Seek(Rml::FileHandle file, long offset, int origin) override; - /// Returns the current position of the file pointer. + /// Returns the current position of the file pointer. size_t Tell(Rml::FileHandle file) override; private: diff --git a/Samples/shell/src/PlatformExtensions.cpp b/Samples/shell/src/PlatformExtensions.cpp index 85db4f8c8..320ba1fc1 100644 --- a/Samples/shell/src/PlatformExtensions.cpp +++ b/Samples/shell/src/PlatformExtensions.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/shell/src/RendererExtensions.cpp b/Samples/shell/src/RendererExtensions.cpp index d61ba0831..b5c495c8b 100644 --- a/Samples/shell/src/RendererExtensions.cpp +++ b/Samples/shell/src/RendererExtensions.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/shell/src/Shell.cpp b/Samples/shell/src/Shell.cpp index 02765f6ce..0b52ad64a 100644 --- a/Samples/shell/src/Shell.cpp +++ b/Samples/shell/src/Shell.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Samples/shell/src/ShellFileInterface.cpp b/Samples/shell/src/ShellFileInterface.cpp index d97826d52..54fc390fc 100644 --- a/Samples/shell/src/ShellFileInterface.cpp +++ b/Samples/shell/src/ShellFileInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -33,7 +33,6 @@ ShellFileInterface::ShellFileInterface(const Rml::String& root) : root(root) {} ShellFileInterface::~ShellFileInterface() {} -// Opens a file. Rml::FileHandle ShellFileInterface::Open(const Rml::String& path) { // Attempt to open the file relative to the application's root. @@ -46,25 +45,21 @@ Rml::FileHandle ShellFileInterface::Open(const Rml::String& path) return (Rml::FileHandle)fp; } -// Closes a previously opened file. void ShellFileInterface::Close(Rml::FileHandle file) { fclose((FILE*)file); } -// Reads data from a previously opened file. size_t ShellFileInterface::Read(void* buffer, size_t size, Rml::FileHandle file) { return fread(buffer, 1, size, (FILE*)file); } -// Seeks to a point in a previously opened file. bool ShellFileInterface::Seek(Rml::FileHandle file, long offset, int origin) { return fseek((FILE*)file, offset, origin) == 0; } -// Returns the current position of the file pointer. size_t ShellFileInterface::Tell(Rml::FileHandle file) { return ftell((FILE*)file); diff --git a/Samples/tutorial/drag/data/tutorial.rcss b/Samples/tutorial/drag/data/tutorial.rcss index 7ec088d95..8d9d7938d 100644 --- a/Samples/tutorial/drag/data/tutorial.rcss +++ b/Samples/tutorial/drag/data/tutorial.rcss @@ -1,24 +1,24 @@ /* Hide the window icon. */ div#title_bar div#icon { - display: none; + display: none; } icon { - /* The icons are floated left so they appear left-to-right. */ - float: left; - - /* The padding is added to push the text down to the bottom of the element. */ + /* The icons are floated left so they appear left-to-right. */ + float: left; + + /* The padding is added to push the text down to the bottom of the element. */ box-sizing: border-box; - width: 100dp; - height: 100dp; - padding: 60dp 10dp 0dp 10dp; - margin: 10dp; - - decorator: image( /assets/present.tga ); - - font-size: 12dp; - text-align: center; - font-effect: shadow(1dp 1dp black); + width: 100dp; + height: 100dp; + padding: 60dp 10dp 0dp 10dp; + margin: 10dp; + + decorator: image( /assets/present.tga ); + + font-size: 12dp; + text-align: center; + font-effect: shadow(1dp 1dp black); } diff --git a/Samples/tutorial/drag/src/Inventory.cpp b/Samples/tutorial/drag/src/Inventory.cpp index 47beb48ae..95edabc91 100644 --- a/Samples/tutorial/drag/src/Inventory.cpp +++ b/Samples/tutorial/drag/src/Inventory.cpp @@ -1,7 +1,6 @@ #include "Inventory.h" #include -// Constructs a new inventory and opens its window. Inventory::Inventory(const Rml::String& title, const Rml::Vector2f& position, Rml::Context* context) { document = context->LoadDocument("tutorial/drag/data/inventory.rml"); @@ -14,14 +13,12 @@ Inventory::Inventory(const Rml::String& title, const Rml::Vector2f& position, Rm } } -// Destroys the inventory and closes its window. Inventory::~Inventory() { if (document) document->Close(); } -// Adds a brand-new item into this inventory. void Inventory::AddItem(const Rml::String& name) { if (!document) diff --git a/Samples/tutorial/drag/src/Inventory.h b/Samples/tutorial/drag/src/Inventory.h index 901260eea..f7404a55b 100644 --- a/Samples/tutorial/drag/src/Inventory.h +++ b/Samples/tutorial/drag/src/Inventory.h @@ -1,16 +1,15 @@ #ifndef INVENTORY_H #define INVENTORY_H -#include #include #include +#include /** - @author Peter Curry + @author Peter Curry */ -class Inventory -{ +class Inventory { public: /// Constructs a new inventory and opens its window. /// @param[in] title The title of the new inventory. diff --git a/Samples/tutorial/template/data/tutorial.rcss b/Samples/tutorial/template/data/tutorial.rcss index 1ff7ae156..36ac7e36e 100644 --- a/Samples/tutorial/template/data/tutorial.rcss +++ b/Samples/tutorial/template/data/tutorial.rcss @@ -1,4 +1,4 @@ -@spritesheet theme +@spritesheet theme { src: /assets/invader.tga; @@ -25,7 +25,7 @@ body body.window { decorator: tiled-box( - window-tl, window-t, window-tr, + window-tl, window-t, window-tr, window-l, window-c, window-r, window-bl, window-b, window-br ); @@ -33,5 +33,5 @@ body.window div { - display: block; + display: block; } diff --git a/Source/Core/BaseXMLParser.cpp b/Source/Core/BaseXMLParser.cpp index 5e5286627..7faad953f 100644 --- a/Source/Core/BaseXMLParser.cpp +++ b/Source/Core/BaseXMLParser.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,10 @@ namespace Rml { -BaseXMLParser::BaseXMLParser() -{} +BaseXMLParser::BaseXMLParser() {} -BaseXMLParser::~BaseXMLParser() -{} +BaseXMLParser::~BaseXMLParser() {} -// Registers a tag as containing general character data. void BaseXMLParser::RegisterCDATATag(const String& tag) { if (!tag.empty()) @@ -52,8 +49,6 @@ void BaseXMLParser::RegisterInnerXMLAttribute(const String& attribute_name) attributes_for_inner_xml_data.insert(attribute_name); } -// Parses the given stream as an XML file, and calls the handlers when -// interesting phenomenon are encountered. void BaseXMLParser::Parse(Stream* stream) { source_url = &stream->GetSourceURL(); @@ -84,7 +79,6 @@ void BaseXMLParser::Parse(Stream* stream) source_url = nullptr; } -// Get the current file line number int BaseXMLParser::GetLineNumber() const { return line_number; @@ -95,42 +89,29 @@ int BaseXMLParser::GetLineNumberOpenTag() const return line_number_open_tag; } -// Called when the parser finds the beginning of an element tag. -void BaseXMLParser::HandleElementStart(const String& RMLUI_UNUSED_PARAMETER(name), const XMLAttributes& RMLUI_UNUSED_PARAMETER(attributes)) -{ - RMLUI_UNUSED(name); - RMLUI_UNUSED(attributes); -} - -// Called when the parser finds the end of an element tag. -void BaseXMLParser::HandleElementEnd(const String& RMLUI_UNUSED_PARAMETER(name)) -{ - RMLUI_UNUSED(name); -} +void BaseXMLParser::HandleElementStart(const String& /*name*/, const XMLAttributes& /*attributes*/) {} -// Called when the parser encounters data. -void BaseXMLParser::HandleData(const String& RMLUI_UNUSED_PARAMETER(data), XMLDataType RMLUI_UNUSED_PARAMETER(type)) -{ - RMLUI_UNUSED(data); - RMLUI_UNUSED(type); -} +void BaseXMLParser::HandleElementEnd(const String& /*name*/) {} -/// Returns the source URL of this parse. Only valid during parsing. +void BaseXMLParser::HandleData(const String& /*data*/, XMLDataType /*type*/) {} const URL* BaseXMLParser::GetSourceURLPtr() const { return source_url; } -void BaseXMLParser::Next() { +void BaseXMLParser::Next() +{ xml_index += 1; } -bool BaseXMLParser::AtEnd() const { +bool BaseXMLParser::AtEnd() const +{ return xml_index >= xml_source.size(); } -char BaseXMLParser::Look() const { +char BaseXMLParser::Look() const +{ RMLUI_ASSERT(!AtEnd()); return xml_source[xml_index]; } @@ -170,7 +151,7 @@ void BaseXMLParser::ReadBody() open_tag_depth = 0; line_number_open_tag = 0; - for(;;) + for (;;) { // Find the next open tag. if (!FindString("<", data, true)) @@ -240,8 +221,7 @@ bool BaseXMLParser::ReadOpenTag() HandleElementStartInternal(tag_name, XMLAttributes()); section_opened = true; } - else if (PeekString("/") && - PeekString(">")) + else if (PeekString("/") && PeekString(">")) { // Empty open tag. HandleElementStartInternal(tag_name, XMLAttributes()); @@ -263,8 +243,7 @@ bool BaseXMLParser::ReadOpenTag() HandleElementStartInternal(tag_name, attributes); section_opened = true; } - else if (PeekString("/") && - PeekString(">")) + else if (PeekString("/") && PeekString(">")) { HandleElementStartInternal(tag_name, attributes); HandleElementEndInternal(tag_name); @@ -339,11 +318,9 @@ bool BaseXMLParser::ReadCloseTag(const size_t xml_index_tag) HandleElementEndInternal(StringUtilities::StripWhitespace(tag_name)); - // Tag closed, reduce count open_tag_depth--; - return true; } @@ -354,12 +331,12 @@ bool BaseXMLParser::ReadAttributes(XMLAttributes& attributes, bool& parse_raw_xm String attribute; String value; - // Get the attribute name + // Get the attribute name if (!FindWord(attribute, "=/>")) - { + { return false; } - + // Check if theres an assigned value if (PeekString("=")) { @@ -382,7 +359,7 @@ bool BaseXMLParser::ReadAttributes(XMLAttributes& attributes, bool& parse_raw_xm if (attributes_for_inner_xml_data.count(attribute) == 1) parse_raw_xml_content = true; - attributes[attribute] = StringUtilities::DecodeRml(value); + attributes[attribute] = StringUtilities::DecodeRml(value); // Check for the end of the tag. if (PeekString("/", false) || PeekString(">", false)) @@ -433,7 +410,6 @@ bool BaseXMLParser::ReadCDATA(const char* tag_terminator) } } -// Reads from the stream until a complete word is found. bool BaseXMLParser::FindWord(String& word, const char* terminators) { while (!AtEnd()) @@ -471,7 +447,6 @@ bool BaseXMLParser::FindWord(String& word, const char* terminators) return false; } -// Reads from the stream until the given character set is found. bool BaseXMLParser::FindString(const char* string, String& data, bool escape_brackets) { int index = 0; @@ -492,7 +467,7 @@ bool BaseXMLParser::FindString(const char* string, String& data, bool escape_bra line_number++; } - if(escape_brackets) + if (escape_brackets) { const char* error_str = XMLParseTools::ParseDataBrackets(in_brackets, in_string, c, previous); if (error_str) @@ -524,8 +499,6 @@ bool BaseXMLParser::FindString(const char* string, String& data, bool escape_bra return true; } -// Returns true if the next sequence of characters in the stream matches the -// given string. bool BaseXMLParser::PeekString(const char* string, bool consume) { const size_t start_index = xml_index; diff --git a/Source/Core/Box.cpp b/Source/Core/Box.cpp index b03c85b02..e960b7864 100644 --- a/Source/Core/Box.cpp +++ b/Source/Core/Box.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -36,7 +36,6 @@ Box::Box(Vector2f content) : content(content) {} Box::~Box() {} -// Returns the top-left position of one of the areas. Vector2f Box::GetPosition(Area area) const { Vector2f area_position(-area_edges[MARGIN][LEFT], -area_edges[MARGIN][TOP]); @@ -66,25 +65,21 @@ Vector2f Box::GetSize(Area area) const return area_size; } -// Sets the size of the content area. void Box::SetContent(Vector2f _content) { content = _content; } -// Sets the size of one of the segments of one of the box's outer areas. void Box::SetEdge(Area area, Edge edge, float size) { area_edges[area][edge] = size; } -// Returns the size of one of the area segments. float Box::GetEdge(Area area, Edge edge) const { return area_edges[area][edge]; } -// Returns the cumulative size of one edge up to one of the box's areas. float Box::GetCumulativeEdge(Area area, Edge edge) const { float size = 0; diff --git a/Source/Core/Clock.cpp b/Source/Core/Clock.cpp index 26027aeea..2c5186593 100644 --- a/Source/Core/Clock.cpp +++ b/Source/Core/Clock.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Source/Core/Clock.h b/Source/Core/Clock.h index 2223a4f46..bf0082c72 100644 --- a/Source/Core/Clock.h +++ b/Source/Core/Clock.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,12 +34,11 @@ namespace Rml { /** - RmlUi's Interface to Time. + RmlUi's Interface to Time. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class Clock -{ +class Clock { public: /// Get the elapsed time since application startup /// @return Seconds elapsed since application startup. diff --git a/Source/Core/ComputeProperty.cpp b/Source/Core/ComputeProperty.cpp index 9f01f6df9..37703735f 100644 --- a/Source/Core/ComputeProperty.cpp +++ b/Source/Core/ComputeProperty.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,31 +40,23 @@ static constexpr float PixelsPerInch = 96.0f; float ComputeLength(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions) { RMLUI_ASSERT(property); - + float value = property->value.Get(); switch (property->unit) { case Property::NUMBER: case Property::PX: - case Property::RAD: - return value; - - case Property::EM: - return value * font_size; - case Property::REM: - return value * document_font_size; - case Property::DP: - return value * dp_ratio; - case Property::VW: - return value * vp_dimensions.x * 0.01f; - case Property::VH: - return value * vp_dimensions.y * 0.01f; - - case Property::DEG: - return Math::DegreesToRadians(value); - default: - break; + case Property::RAD: return value; + + case Property::EM: return value * font_size; + case Property::REM: return value * document_font_size; + case Property::DP: return value * dp_ratio; + case Property::VW: return value * vp_dimensions.x * 0.01f; + case Property::VH: return value * vp_dimensions.y * 0.01f; + + case Property::DEG: return Math::DegreesToRadians(value); + default: break; } // Values based on pixels-per-inch. @@ -74,18 +66,12 @@ float ComputeLength(const Property* property, float font_size, float document_fo switch (property->unit) { - case Property::INCH: // inch - return inch; - case Property::CM: // centimeter - return inch * (1.0f / 2.54f); - case Property::MM: // millimeter - return inch * (1.0f / 25.4f); - case Property::PT: // point - return inch * (1.0f / 72.0f); - case Property::PC: // pica - return inch * (1.0f / 6.0f); - default: - break; + case Property::INCH: return inch; // inch + case Property::CM: return inch * (1.0f / 2.54f); // centimeter + case Property::MM: return inch * (1.0f / 25.4f); // millimeter + case Property::PT: return inch * (1.0f / 72.0f); // point + case Property::PC: return inch * (1.0f / 6.0f); // pica + default: break; } } @@ -99,34 +85,24 @@ float ComputeAbsoluteLength(const Property& property, float dp_ratio, Vector2f v switch (property.unit) { - case Property::PX: - return property.value.Get< float >(); - case Property::DP: - return property.value.Get< float >() * dp_ratio; - case Property::VW: - return property.value.Get< float >() * vp_dimensions.x * 0.01f; - case Property::VH: - return property.value.Get< float >() * vp_dimensions.y * 0.01f; + case Property::PX: return property.value.Get(); + case Property::DP: return property.value.Get() * dp_ratio; + case Property::VW: return property.value.Get() * vp_dimensions.x * 0.01f; + case Property::VH: return property.value.Get() * vp_dimensions.y * 0.01f; default: // Values based on pixels-per-inch. if (property.unit & Property::PPI_UNIT) { - float inch = property.value.Get< float >() * PixelsPerInch; + float inch = property.value.Get() * PixelsPerInch; switch (property.unit) { - case Property::INCH: // inch - return inch; - case Property::CM: // centimeter - return inch * (1.0f / 2.54f); - case Property::MM: // millimeter - return inch * (1.0f / 25.4f); - case Property::PT: // point - return inch * (1.0f / 72.0f); - case Property::PC: // pica - return inch * (1.0f / 6.0f); - default: - break; + case Property::INCH: return inch; // inch + case Property::CM: return inch * (1.0f / 2.54f); // centimeter + case Property::MM: return inch * (1.0f / 25.4f); // millimeter + case Property::PT: return inch * (1.0f / 72.0f); // point + case Property::PC: return inch * (1.0f / 6.0f); // pica + default: break; } } } @@ -142,13 +118,10 @@ float ComputeAngle(const Property& property) switch (property.unit) { case Property::NUMBER: - case Property::RAD: - return value; + case Property::RAD: return value; - case Property::DEG: - return Math::DegreesToRadians(value); - default: - break; + case Property::DEG: return Math::DegreesToRadians(value); + default: break; } return 0.0f; @@ -159,7 +132,8 @@ String ComputeFontFamily(String font_family) return StringUtilities::ToLower(std::move(font_family)); } -float ComputeFontsize(const Property& property, const Style::ComputedValues& values, const Style::ComputedValues* parent_values, const Style::ComputedValues* document_values, float dp_ratio, Vector2f vp_dimensions) +float ComputeFontsize(const Property& property, const Style::ComputedValues& values, const Style::ComputedValues* parent_values, + const Style::ComputedValues* document_values, float dp_ratio, Vector2f vp_dimensions) { // The calculated value of the font-size property is inherited, so we need to check if this // is an inherited property. If so, then we return our parent's font size instead. @@ -181,12 +155,11 @@ float ComputeFontsize(const Property& property, const Style::ComputedValues& val if (!document_values) return 0; // If the current element is a document, the rem unit is relative to the default size - if(&values == document_values) + if (&values == document_values) return property.value.Get() * DefaultComputedValues.font_size(); // Otherwise it is relative to the document font size return property.value.Get() * document_values->font_size(); - default: - RMLUI_ERRORMSG("A relative unit must be percentage, em or rem."); + default: RMLUI_ERRORMSG("A relative unit must be percentage, em or rem."); } } @@ -216,21 +189,17 @@ Style::LineHeight ComputeLineHeight(const Property* property, float font_size, f switch (property->unit) { - case Property::NUMBER: - scale_factor = property->value.Get< float >(); - break; - case Property::PERCENT: - scale_factor = property->value.Get< float >() * 0.01f; - break; - default: - RMLUI_ERRORMSG("Invalid unit for line-height"); + case Property::NUMBER: scale_factor = property->value.Get(); break; + case Property::PERCENT: scale_factor = property->value.Get() * 0.01f; break; + default: RMLUI_ERRORMSG("Invalid unit for line-height"); } float value = font_size * scale_factor; return Style::LineHeight(value, Style::LineHeight::Number, scale_factor); } -Style::VerticalAlign ComputeVerticalAlign(const Property* property, float line_height, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions) +Style::VerticalAlign ComputeVerticalAlign(const Property* property, float line_height, float font_size, float document_font_size, float dp_ratio, + Vector2f vp_dimensions) { if (property->unit & Property::LENGTH) { @@ -246,7 +215,8 @@ Style::VerticalAlign ComputeVerticalAlign(const Property* property, float line_h return Style::VerticalAlign((Style::VerticalAlign::Type)property->Get()); } -Style::LengthPercentage ComputeLengthPercentage(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions) +Style::LengthPercentage ComputeLengthPercentage(const Property* property, float font_size, float document_font_size, float dp_ratio, + Vector2f vp_dimensions) { using namespace Style; if (property->unit & Property::PERCENT) @@ -255,8 +225,8 @@ Style::LengthPercentage ComputeLengthPercentage(const Property* property, float return LengthPercentage(LengthPercentage::Length, ComputeLength(property, font_size, document_font_size, dp_ratio, vp_dimensions)); } - -Style::LengthPercentageAuto ComputeLengthPercentageAuto(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions) +Style::LengthPercentageAuto ComputeLengthPercentageAuto(const Property* property, float font_size, float document_font_size, float dp_ratio, + Vector2f vp_dimensions) { using namespace Style; // Assuming here that 'auto' is the only possible keyword @@ -271,7 +241,8 @@ Style::LengthPercentageAuto ComputeLengthPercentageAuto(const Property* property Style::LengthPercentage ComputeOrigin(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions) { using namespace Style; - static_assert((int)OriginX::Left == (int)OriginY::Top && (int)OriginX::Center == (int)OriginY::Center && (int)OriginX::Right == (int)OriginY::Bottom, ""); + static_assert( + (int)OriginX::Left == (int)OriginY::Top && (int)OriginX::Center == (int)OriginY::Center && (int)OriginX::Right == (int)OriginY::Bottom, ""); if (property->unit & Property::KEYWORD) { @@ -310,7 +281,7 @@ uint16_t ComputeBorderWidth(float computed_length) if (computed_length <= 1.f) return 1; - + return uint16_t(computed_length + 0.5f); } diff --git a/Source/Core/ComputeProperty.h b/Source/Core/ComputeProperty.h index 134d59377..7dc827d51 100644 --- a/Source/Core/ComputeProperty.h +++ b/Source/Core/ComputeProperty.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,17 +44,21 @@ float ComputeAngle(const Property& property); String ComputeFontFamily(String font_family); -float ComputeFontsize(const Property& property, const Style::ComputedValues& values, const Style::ComputedValues* parent_values, const Style::ComputedValues* document_values, float dp_ratio, Vector2f vp_dimensions); +float ComputeFontsize(const Property& property, const Style::ComputedValues& values, const Style::ComputedValues* parent_values, + const Style::ComputedValues* document_values, float dp_ratio, Vector2f vp_dimensions); Style::Clip ComputeClip(const Property* property); Style::LineHeight ComputeLineHeight(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions); -Style::VerticalAlign ComputeVerticalAlign(const Property* property, float line_height, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions); +Style::VerticalAlign ComputeVerticalAlign(const Property* property, float line_height, float font_size, float document_font_size, float dp_ratio, + Vector2f vp_dimensions); -Style::LengthPercentage ComputeLengthPercentage(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions); +Style::LengthPercentage ComputeLengthPercentage(const Property* property, float font_size, float document_font_size, float dp_ratio, + Vector2f vp_dimensions); -Style::LengthPercentageAuto ComputeLengthPercentageAuto(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions); +Style::LengthPercentageAuto ComputeLengthPercentageAuto(const Property* property, float font_size, float document_font_size, float dp_ratio, + Vector2f vp_dimensions); Style::LengthPercentage ComputeOrigin(const Property* property, float font_size, float document_font_size, float dp_ratio, Vector2f vp_dimensions); diff --git a/Source/Core/ComputedValues.cpp b/Source/Core/ComputedValues.cpp index 551014339..d9b247513 100644 --- a/Source/Core/ComputedValues.cpp +++ b/Source/Core/ComputedValues.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Context.cpp b/Source/Core/Context.cpp index 98b198a20..a87b9b8b1 100644 --- a/Source/Core/Context.cpp +++ b/Source/Core/Context.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -48,14 +48,15 @@ #include #include - namespace Rml { static constexpr float DOUBLE_CLICK_TIME = 0.5f; // [s] static constexpr float DOUBLE_CLICK_MAX_DIST = 3.f; // [dp] static constexpr float UNIT_SCROLL_LENGTH = 80.f; // [dp] -Context::Context(const String& name) : name(name), dimensions(0, 0), density_independent_pixel_ratio(1.0f), mouse_position(0, 0), clip_origin(-1, -1), clip_dimensions(-1, -1), next_update_timeout(0) +Context::Context(const String& name) : + name(name), dimensions(0, 0), density_independent_pixel_ratio(1.0f), mouse_position(0, 0), clip_origin(-1, -1), clip_dimensions(-1, -1), + next_update_timeout(0) { instancer = nullptr; @@ -68,7 +69,7 @@ Context::Context(const String& name) : name(name), dimensions(0, 0), density_ind root->SetProperty(PropertyId::ZIndex, Property(0, Property::NUMBER)); cursor_proxy = Factory::InstanceElement(nullptr, documents_base_tag, documents_base_tag, XMLAttributes()); - ElementDocument* cursor_proxy_document = rmlui_dynamic_cast< ElementDocument* >(cursor_proxy.get()); + ElementDocument* cursor_proxy_document = rmlui_dynamic_cast(cursor_proxy.get()); RMLUI_ASSERT(cursor_proxy_document); cursor_proxy_document->context = this; @@ -120,13 +121,11 @@ Context::~Context() render_interface = nullptr; } -// Returns the name of the context. const String& Context::GetName() const { return name; } -// Changes the dimensions of the screen. void Context::SetDimensions(const Vector2i _dimensions) { if (dimensions != _dimensions) @@ -147,12 +146,11 @@ void Context::SetDimensions(const Vector2i _dimensions) document->DispatchEvent(EventId::Resize, Dictionary()); } } - + clip_dimensions = dimensions; } } -// Returns the dimensions of the screen. Vector2i Context::GetDimensions() const { return dimensions; @@ -187,7 +185,7 @@ bool Context::Update() next_update_timeout = std::numeric_limits::infinity(); - if(scroll_controller->Update(mouse_position, density_independent_pixel_ratio)) + if (scroll_controller->Update(mouse_position, density_independent_pixel_ratio)) RequestNextUpdate(0); // Update the hover chain to detect any new or moved elements under the mouse. @@ -221,7 +219,6 @@ bool Context::Update() return true; } -// Renders all visible elements in the element tree. bool Context::Render() { RMLUI_ZoneScoped; @@ -241,9 +238,8 @@ bool Context::Render() if (drag_clone) { static_cast(*cursor_proxy).UpdateDocument(); - cursor_proxy->SetOffset(Vector2f((float)Math::Clamp(mouse_position.x, 0, dimensions.x), - (float)Math::Clamp(mouse_position.y, 0, dimensions.y)), - nullptr); + cursor_proxy->SetOffset( + Vector2f((float)Math::Clamp(mouse_position.x, 0, dimensions.x), (float)Math::Clamp(mouse_position.y, 0, dimensions.y)), nullptr); cursor_proxy->Render(); } @@ -252,7 +248,6 @@ bool Context::Render() return true; } -// Creates a new, empty document and places it into this context. ElementDocument* Context::CreateDocument(const String& instancer_name) { ElementPtr element = Factory::InstanceElement(nullptr, instancer_name, documents_base_tag, XMLAttributes()); @@ -262,10 +257,12 @@ ElementDocument* Context::CreateDocument(const String& instancer_name) return nullptr; } - ElementDocument* document = rmlui_dynamic_cast< ElementDocument* >(element.get()); + ElementDocument* document = rmlui_dynamic_cast(element.get()); if (!document) { - Log::Message(Log::LT_ERROR, "Failed to instance document on instancer_name '%s', Found type '%s', was expecting derivative of ElementDocument.", instancer_name.c_str(), rmlui_type_name(*element)); + Log::Message(Log::LT_ERROR, + "Failed to instance document on instancer_name '%s', Found type '%s', was expecting derivative of ElementDocument.", + instancer_name.c_str(), rmlui_type_name(*element)); return nullptr; } @@ -277,9 +274,8 @@ ElementDocument* Context::CreateDocument(const String& instancer_name) return document; } -// Load a document into the context. ElementDocument* Context::LoadDocument(const String& document_path) -{ +{ auto stream = MakeUnique(); if (!stream->Open(document_path)) @@ -290,7 +286,6 @@ ElementDocument* Context::LoadDocument(const String& document_path) return document; } -// Load a document into the context. ElementDocument* Context::LoadDocument(Stream* stream) { PluginRegistry::NotifyDocumentOpen(this, stream->GetSourceURL().GetURL()); @@ -300,7 +295,7 @@ ElementDocument* Context::LoadDocument(Stream* stream) return nullptr; ElementDocument* document = static_cast(element.get()); - + root->AppendChild(std::move(element)); // The 'load' event is fired before updating the document, because the user might @@ -321,13 +316,12 @@ ElementDocument* Context::LoadDocument(Stream* stream) return document; } -// Load a document into the context. ElementDocument* Context::LoadDocumentFromMemory(const String& string, const String& source_url) { // Open the stream based on the string contents. auto stream = MakeUnique(reinterpret_cast(string.c_str()), string.size()); - stream->SetSourceURL( source_url ); + stream->SetSourceURL(source_url); // Load the document from the stream. ElementDocument* document = LoadDocument(stream.get()); @@ -335,7 +329,6 @@ ElementDocument* Context::LoadDocumentFromMemory(const String& string, const Str return document; } -// Unload the given document void Context::UnloadDocument(ElementDocument* _document) { // Has this document already been unloaded? @@ -354,7 +347,7 @@ void Context::UnloadDocument(ElementDocument* _document) PluginRegistry::NotifyDocumentUnload(document); // Move document to a temporary location to be released later. - unloaded_documents.push_back( root->RemoveChild(document) ); + unloaded_documents.push_back(root->RemoveChild(document)); } // Remove the item from the focus history. @@ -391,7 +384,6 @@ void Context::UnloadDocument(ElementDocument* _document) UpdateHoverChain(mouse_position); } -// Unload all the currently loaded documents void Context::UnloadAllDocuments() { // Unload all children. @@ -404,7 +396,6 @@ void Context::UnloadAllDocuments() drag_hover_chain.clear(); } -// Enables or disables the mouse cursor. void Context::EnableMouseCursor(bool enable) { // The cursor is set to an invalid name so that it is forced to update in the next update loop. @@ -436,7 +427,6 @@ bool Context::IsThemeActive(const String& theme_name) const return active_themes.count(theme_name); } -// Returns the first document found in the root with the given id. ElementDocument* Context::GetDocument(const String& id) { for (int i = 0; i < root->GetNumChildren(); i++) @@ -452,7 +442,6 @@ ElementDocument* Context::GetDocument(const String& id) return nullptr; } -// Returns a document in the context by index. ElementDocument* Context::GetDocument(int index) { Element* element = root->GetChild(index); @@ -462,31 +451,26 @@ ElementDocument* Context::GetDocument(int index) return element->GetOwnerDocument(); } -// Returns the number of documents in the context. int Context::GetNumDocuments() const { return root->GetNumChildren(); } -// Returns the hover element. Element* Context::GetHoverElement() { return hover; } -// Returns the focus element. Element* Context::GetFocusElement() { return focus; } -// Returns the root element. Element* Context::GetRootElement() { return root.get(); } -// Brings the document to the front of the document stack. void Context::PullDocumentToFront(ElementDocument* document) { if (document != root->GetLastChild()) @@ -507,7 +491,6 @@ void Context::PullDocumentToFront(ElementDocument* document) } } -// Sends the document to the back of the document stack. void Context::PushDocumentToBack(ElementDocument* document) { if (document != root->GetFirstChild()) @@ -537,19 +520,16 @@ void Context::UnfocusDocument(ElementDocument* document) document_focus_history.back()->GetFocusLeafNode()->Focus(); } -// Adds an event listener to the root element. void Context::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase) { root->AddEventListener(event, listener, in_capture_phase); } -// Removes an event listener from the root element. void Context::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase) { root->RemoveEventListener(event, listener, in_capture_phase); } -// Sends a key down event into RmlUi. bool Context::ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifier_state) { // Generate the parameters for the key event. @@ -563,7 +543,6 @@ bool Context::ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifi return root->DispatchEvent(EventId::Keydown, parameters); } -// Sends a key up event into RmlUi. bool Context::ProcessKeyUp(Input::KeyIdentifier key_identifier, int key_modifier_state) { // Generate the parameters for the key event. @@ -585,7 +564,6 @@ bool Context::ProcessTextInput(char character) return ProcessTextInput(static_cast(character)); } -// Sends a single character of text as text input into RmlUi. bool Context::ProcessTextInput(Character character) { // Generate the parameters for the key event. @@ -593,7 +571,6 @@ bool Context::ProcessTextInput(Character character) return ProcessTextInput(text); } -// Sends a string of text as text input into RmlUi. bool Context::ProcessTextInput(const String& string) { Element* target = (focus ? focus : root.get()); @@ -606,7 +583,6 @@ bool Context::ProcessTextInput(const String& string) return consumed; } -// Sends a mouse movement event into RmlUi. bool Context::ProcessMouseMove(int x, int y, int key_modifier_state) { // Check whether the mouse moved since the last event came through. @@ -639,16 +615,15 @@ static Element* FindFocusElement(Element* element) ElementDocument* owner_document = element->GetOwnerDocument(); if (!owner_document || owner_document->GetComputedValues().focus() == Style::Focus::None) return nullptr; - + while (element && element->GetComputedValues().focus() == Style::Focus::None) { element = element->GetParentNode(); } - + return element; } -// Sends a mouse-button down event into RmlUi. bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state) { Dictionary parameters; @@ -660,7 +635,7 @@ bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state) if (button_index == 0) { Element* new_focus = hover; - + // Set the currently hovered element to focus if it isn't already the focus. if (hover) { @@ -688,8 +663,7 @@ bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state) double click_time = GetSystemInterface()->GetElapsedTime(); - if (active == last_click_element && - float(click_time - last_click_time) < DOUBLE_CLICK_TIME && + if (active == last_click_element && float(click_time - last_click_time) < DOUBLE_CLICK_TIME && mouse_distance_squared < max_mouse_distance * max_mouse_distance) { if (hover) @@ -719,8 +693,8 @@ bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state) Style::Drag drag_style = drag->GetComputedValues().drag(); switch (drag_style) { - case Style::Drag::None: drag = drag->GetParentNode(); continue; - case Style::Drag::Block: drag = nullptr; continue; + case Style::Drag::None: drag = drag->GetParentNode(); continue; + case Style::Drag::Block: drag = nullptr; continue; default: drag_verbose = (drag_style == Style::Drag::DragDrop || drag_style == Style::Drag::Clone); } @@ -754,14 +728,14 @@ bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state) return !IsMouseInteracting(); } -// Sends a mouse-button up event into RmlUi. bool Context::ProcessMouseButtonUp(int button_index, int key_modifier_state) { Dictionary parameters; GenerateMouseEventParameters(parameters, button_index); GenerateKeyModifierEventParameters(parameters, key_modifier_state); - // We want to return the interaction state before handling the mouse up events, so that any active element that is released is considered to capture the event. + // We want to return the interaction state before handling the mouse up events, so that any active element that is released is considered to + // capture the event. const bool result = !IsMouseInteracting(); // Process primary click. @@ -800,12 +774,12 @@ bool Context::ProcessMouseButtonUp(int button_index, int key_modifier_state) { drag_hover->DispatchEvent(EventId::Dragdrop, drag_parameters); // User may have removed the element, do an extra check. - if(drag_hover) + if (drag_hover) drag_hover->DispatchEvent(EventId::Dragout, drag_parameters); } } - if(drag) + if (drag) drag->DispatchEvent(EventId::Dragend, drag_parameters); ReleaseDragClone(); @@ -876,10 +850,10 @@ bool Context::ProcessMouseWheel(Vector2f wheel_delta, int key_modifier_state) bool Context::ProcessMouseLeave() { mouse_active = false; - + // Update the hover chain. Now that 'mouse_active' is disabled this will remove the hover state from all elements. UpdateHoverChain(mouse_position); - + return !IsMouseInteracting(); } @@ -893,32 +867,28 @@ void Context::SetDefaultScrollBehavior(ScrollBehavior scroll_behavior, float spe scroll_controller->SetDefaultScrollBehavior(scroll_behavior, speed_factor); } -// Gets the context's render interface. RenderInterface* Context::GetRenderInterface() const { return render_interface; } - -// Gets the current clipping region for the render traversal + bool Context::GetActiveClipRegion(Vector2i& origin, Vector2i& dimensions) const { if (clip_dimensions.x < 0 || clip_dimensions.y < 0) return false; - + origin = clip_origin; dimensions = clip_dimensions; - + return true; } - -// Sets the current clipping region for the render traversal + void Context::SetActiveClipRegion(const Vector2i origin, const Vector2i dimensions) { clip_origin = origin; clip_dimensions = dimensions; } -// Sets the instancer to use for releasing this object. void Context::SetInstancer(ContextInstancer* _instancer) { RMLUI_ASSERT(instancer == nullptr); @@ -969,7 +939,6 @@ bool Context::RemoveDataModel(const String& name) return true; } -// Internal callback for when an element is removed from the hierarchy. void Context::OnElementDetach(Element* element) { auto it_hover = hover_chain.find(element); @@ -1018,7 +987,7 @@ void Context::OnElementDetach(Element* element) } // Focus normally cleared and set by parent during Element::RemoveChild. - // However, there are some exceptions, such as when an there are multiple + // However, there are some exceptions, such as when an there are multiple // ElementDocuments in the hierarchy above the current element. if (element == focus) focus = nullptr; @@ -1035,7 +1004,6 @@ void Context::OnElementDetach(Element* element) scroll_controller->Reset(); } -// Internal callback for when a new element gains focus bool Context::OnFocusChange(Element* new_focus) { RMLUI_ASSERT(new_focus); @@ -1099,7 +1067,6 @@ bool Context::OnFocusChange(Element* new_focus) return true; } -// Generates an event for faking clicks on an element. void Context::GenerateClickEvent(Element* element) { Dictionary parameters; @@ -1108,7 +1075,6 @@ void Context::GenerateClickEvent(Element* element) element->DispatchEvent(EventId::Click, parameters); } -// Updates the current hover elements, sending required events. void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_state, Dictionary* out_parameters, Dictionary* out_drag_parameters) { const Vector2f position(mouse_position); @@ -1120,7 +1086,7 @@ void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_sta // Generate the parameters for the mouse events (there could be a few!). GenerateMouseEventParameters(parameters); GenerateKeyModifierEventParameters(parameters, key_modifier_state); - + GenerateMouseEventParameters(drag_parameters); GenerateDragEventParameters(drag_parameters); GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state); @@ -1151,18 +1117,18 @@ void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_sta hover = mouse_active ? GetElementAtPoint(position) : nullptr; - if(enable_cursor) + if (enable_cursor) { String new_cursor_name; if (scroll_controller->GetMode() == ScrollController::Mode::Autoscroll) new_cursor_name = scroll_controller->GetAutoscrollCursor(mouse_position, density_independent_pixel_ratio); - else if(drag) + else if (drag) new_cursor_name = drag->GetComputedValues().cursor(); else if (hover) new_cursor_name = hover->GetComputedValues().cursor(); - if(new_cursor_name != cursor_name) + if (new_cursor_name != cursor_name) { GetSystemInterface()->SetMouseCursor(new_cursor_name); cursor_name = new_cursor_name; @@ -1195,8 +1161,7 @@ void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_sta element = element->GetParentNode(); } - if (drag_started && - drag_verbose) + if (drag_started && drag_verbose) { // Send out ondragover and ondragout events as appropriate. SendEvents(drag_hover_chain, new_drag_hover_chain, EventId::Dragout, drag_parameters); @@ -1210,7 +1175,6 @@ void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_sta hover_chain.swap(new_hover_chain); } -// Returns the youngest descendent of the given element which is under the given point in screen coodinates. Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_element, Element* element) const { if (element == nullptr) @@ -1227,15 +1191,13 @@ Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_elemen if (focus) { ElementDocument* focus_document = focus->GetOwnerDocument(); - if (focus_document != nullptr && - focus_document->IsModal()) + if (focus_document != nullptr && focus_document->IsModal()) { element = focus_document; } } } - // Check any elements within our stacking context. We want to return the lowest-down element // that is under the cursor. if (element->local_stacking_context) @@ -1243,7 +1205,7 @@ Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_elemen if (element->stacking_context_dirty) element->BuildLocalStackingContext(); - for (int i = (int) element->stacking_context.size() - 1; i >= 0; --i) + for (int i = (int)element->stacking_context.size() - 1; i >= 0; --i) { if (ignore_element != nullptr) { @@ -1280,10 +1242,8 @@ Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_elemen Vector2i clip_origin, clip_dimensions; if (ElementUtilities::GetClippingRegion(clip_origin, clip_dimensions, element)) { - within_element = point.x >= clip_origin.x && - point.y >= clip_origin.y && - point.x <= (clip_origin.x + clip_dimensions.x) && - point.y <= (clip_origin.y + clip_dimensions.y); + within_element = point.x >= clip_origin.x && point.y >= clip_origin.y && point.x <= (clip_origin.x + clip_dimensions.x) && + point.y <= (clip_origin.y + clip_dimensions.y); } } @@ -1293,7 +1253,6 @@ Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_elemen return nullptr; } -// Creates the drag clone from the given element. void Context::CreateDragClone(Element* element) { RMLUI_ASSERTMSG(cursor_proxy, "Unable to create drag clone, no cursor proxy document."); @@ -1336,7 +1295,6 @@ void Context::CreateDragClone(Element* element) drag_clone->SetPseudoClass("drag", true); } -// Releases the drag clone, if one exists. void Context::ReleaseDragClone() { if (drag_clone) @@ -1360,13 +1318,11 @@ DataModel* Context::GetDataModelPtr(const String& name) const return nullptr; } -// Builds the parameters for a generic key event. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier) { parameters["key_identifier"] = (int)key_identifier; } -// Builds the parameters for a generic mouse event. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index) { parameters.reserve(3); @@ -1376,30 +1332,19 @@ void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_in parameters["button"] = button_index; } -// Builds the parameters for the key modifier state. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state) { - static const String property_names[] = { - "ctrl_key", - "shift_key", - "alt_key", - "meta_key", - "caps_lock_key", - "num_lock_key", - "scroll_lock_key" - }; + static const String property_names[] = {"ctrl_key", "shift_key", "alt_key", "meta_key", "caps_lock_key", "num_lock_key", "scroll_lock_key"}; for (int i = 0; i < 7; i++) parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0); } -// Builds the parameters for a drag event. void Context::GenerateDragEventParameters(Dictionary& parameters) -{ +{ parameters["drag_element"] = (void*)drag; } -// Releases all unloaded documents pending destruction. void Context::ReleaseUnloadedDocuments() { if (!unloaded_documents.empty()) @@ -1414,7 +1359,7 @@ void Context::ReleaseUnloadedDocuments() } } -using ElementObserverList = Vector< ObserverPtr >; +using ElementObserverList = Vector>; class ElementObserverListBackInserter { public: @@ -1426,7 +1371,8 @@ class ElementObserverListBackInserter { using container_type = ElementObserverList; ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {} - ElementObserverListBackInserter& operator=(Element* element) { + ElementObserverListBackInserter& operator=(Element* element) + { elements->push_back(element->GetObserverPtr()); return *this; } @@ -1438,7 +1384,6 @@ class ElementObserverListBackInserter { ElementObserverList* elements; }; -// Sends the specified event to all elements in new_items that don't appear in old_items. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters) { // We put our elements in observer pointers in case some of them are deleted during dispatch. @@ -1469,12 +1414,14 @@ const String& Context::GetDocumentsBaseTag() return documents_base_tag; } -void Context::RequestNextUpdate(double delay) { +void Context::RequestNextUpdate(double delay) +{ RMLUI_ASSERT(delay >= 0.0); next_update_timeout = Math::Min(next_update_timeout, delay); } -double Context::GetNextUpdateDelay() const { +double Context::GetNextUpdateDelay() const +{ return next_update_timeout; } diff --git a/Source/Core/ContextInstancer.cpp b/Source/Core/ContextInstancer.cpp index 472215251..91520b55d 100644 --- a/Source/Core/ContextInstancer.cpp +++ b/Source/Core/ContextInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,8 +30,6 @@ namespace Rml { -ContextInstancer::~ContextInstancer() -{ -} +ContextInstancer::~ContextInstancer() {} } // namespace Rml diff --git a/Source/Core/ContextInstancerDefault.cpp b/Source/Core/ContextInstancerDefault.cpp index 6d1f8949b..d2c1d8369 100644 --- a/Source/Core/ContextInstancerDefault.cpp +++ b/Source/Core/ContextInstancerDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,20 +31,15 @@ namespace Rml { -ContextInstancerDefault::ContextInstancerDefault() -{ -} +ContextInstancerDefault::ContextInstancerDefault() {} -ContextInstancerDefault::~ContextInstancerDefault() -{ -} +ContextInstancerDefault::~ContextInstancerDefault() {} ContextPtr ContextInstancerDefault::InstanceContext(const String& name) { return ContextPtr(new Context(name)); } -// Releases a context previously created by this context. void ContextInstancerDefault::ReleaseContext(Context* context) { delete context; diff --git a/Source/Core/ContextInstancerDefault.h b/Source/Core/ContextInstancerDefault.h index 034b8e36a..fd10ad54c 100644 --- a/Source/Core/ContextInstancerDefault.h +++ b/Source/Core/ContextInstancerDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - Default instancer for instancing contexts. + Default instancer for instancing contexts. - @author Peter Curry + @author Peter Curry */ -class ContextInstancerDefault : public ContextInstancer -{ +class ContextInstancerDefault : public ContextInstancer { public: ContextInstancerDefault(); virtual ~ContextInstancerDefault(); diff --git a/Source/Core/ConvolutionFilter.cpp b/Source/Core/ConvolutionFilter.cpp index 210397c99..3b4695e69 100644 --- a/Source/Core/ConvolutionFilter.cpp +++ b/Source/Core/ConvolutionFilter.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,11 +33,9 @@ namespace Rml { -ConvolutionFilter::ConvolutionFilter() -{} +ConvolutionFilter::ConvolutionFilter() {} -ConvolutionFilter::~ConvolutionFilter() -{} +ConvolutionFilter::~ConvolutionFilter() {} bool ConvolutionFilter::Initialise(int _kernel_radius, FilterOperation _operation) { @@ -95,8 +93,7 @@ void ConvolutionFilter::Run(byte* destination, const Vector2i destination_dimens for (int kernel_x = 0; kernel_x < kernel_size.x; ++kernel_x) { const int source_x = x - source_offset.x - kernel_radius.x + kernel_x; - if (source_y >= 0 && source_y < source_dimensions.y && - source_x >= 0 && source_x < source_dimensions.x) + if (source_y >= 0 && source_y < source_dimensions.y && source_x >= 0 && source_x < source_dimensions.x) { const int source_index = (source_y * source_dimensions.x + source_x) * source_bytes_per_pixel + source_alpha_offset; const float pixel_opacity = float(source[source_index]) * kernel[kernel_y * kernel_size.x + kernel_x]; diff --git a/Source/Core/Core.cpp b/Source/Core/Core.cpp index eb3c3c206..f47d4710e 100644 --- a/Source/Core/Core.cpp +++ b/Source/Core/Core.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,10 +34,9 @@ #include "../../Include/RmlUi/Core/FontEngineInterface.h" #include "../../Include/RmlUi/Core/Plugin.h" #include "../../Include/RmlUi/Core/RenderInterface.h" -#include "../../Include/RmlUi/Core/SystemInterface.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" +#include "../../Include/RmlUi/Core/SystemInterface.h" #include "../../Include/RmlUi/Core/Types.h" - #include "EventSpecification.h" #include "FileInterfaceDefault.h" #include "GeometryDatabase.h" @@ -46,23 +45,21 @@ #include "StyleSheetParser.h" #include "TemplateCache.h" #include "TextureDatabase.h" -#include "EventSpecification.h" #ifndef RMLUI_NO_FONT_INTERFACE_DEFAULT -#include "FontEngineDefault/FontEngineInterfaceDefault.h" + #include "FontEngineDefault/FontEngineInterfaceDefault.h" #endif #ifdef RMLUI_ENABLE_LOTTIE_PLUGIN -#include "../Lottie/LottiePlugin.h" + #include "../Lottie/LottiePlugin.h" #endif #ifdef RMLUI_ENABLE_SVG_PLUGIN -#include "../SVG/SVGPlugin.h" + #include "../SVG/SVGPlugin.h" #endif #include "Pool.h" - namespace Rml { // RmlUi's renderer interface. @@ -80,7 +77,7 @@ static UniquePtr default_font_interface; static bool initialised = false; -using ContextMap = UnorderedMap< String, ContextPtr >; +using ContextMap = UnorderedMap; static ContextMap contexts; // The ObserverPtrBlock pool @@ -90,7 +87,6 @@ extern Pool* observerPtrBlockPool; #define RMLUI_VERSION "custom" #endif - bool Initialise() { RMLUI_ASSERTMSG(!initialised, "Rml::Initialise() called, but RmlUi is already initialised!"); @@ -99,13 +95,13 @@ bool Initialise() // Check for valid interfaces, or install default interfaces as appropriate. if (!system_interface) - { + { Log::Message(Log::LT_ERROR, "No system interface set!"); return false; } if (!file_interface) - { + { #ifndef RMLUI_NO_FILE_INTERFACE_DEFAULT default_file_interface = MakeUnique(); file_interface = default_file_interface.get(); @@ -189,61 +185,51 @@ void Shutdown() ReleaseMemoryPools(); } -// Returns the version of this RmlUi library. String GetVersion() { return RMLUI_VERSION; } -// Sets the interface through which all RmlUi messages will be routed. void SetSystemInterface(SystemInterface* _system_interface) { system_interface = _system_interface; } -// Returns RmlUi's system interface. SystemInterface* GetSystemInterface() { return system_interface; } -// Sets the interface through which all rendering requests are made. void SetRenderInterface(RenderInterface* _render_interface) { render_interface = _render_interface; } -// Returns RmlUi's render interface. RenderInterface* GetRenderInterface() { return render_interface; } -// Sets the interface through which all file I/O requests are made. void SetFileInterface(FileInterface* _file_interface) { file_interface = _file_interface; } -// Returns RmlUi's file interface. FileInterface* GetFileInterface() { return file_interface; } -// Sets the interface through which all font requests are made. void SetFontEngineInterface(FontEngineInterface* _font_interface) { font_interface = _font_interface; } - -// Returns RmlUi's file interface. + FontEngineInterface* GetFontEngineInterface() { return font_interface; } -// Creates a new element context. Context* CreateContext(const String& name, const Vector2i dimensions, RenderInterface* custom_render_interface) { if (!initialised) @@ -251,7 +237,8 @@ Context* CreateContext(const String& name, const Vector2i dimensions, RenderInte if (!custom_render_interface && !render_interface) { - Log::Message(Log::LT_WARNING, "Failed to create context '%s', no render interface specified and no default render interface exists.", name.c_str()); + Log::Message(Log::LT_WARNING, "Failed to create context '%s', no render interface specified and no default render interface exists.", + name.c_str()); return nullptr; } @@ -295,7 +282,6 @@ bool RemoveContext(const String& name) return false; } -// Fetches a previously constructed context by name. Context* GetContext(const String& name) { ContextMap::iterator i = contexts.find(name); @@ -305,12 +291,11 @@ Context* GetContext(const String& name) return i->second.get(); } -// Fetches a context by index. Context* GetContext(int index) { ContextMap::iterator i = contexts.begin(); int count = 0; - + if (index < 0 || index >= GetNumContexts()) return nullptr; @@ -326,10 +311,9 @@ Context* GetContext(int index) return i->second.get(); } -// Returns the number of active contexts. int GetNumContexts() { - return (int) contexts.size(); + return (int)contexts.size(); } bool LoadFontFace(const String& file_path, bool fallback_face, Style::FontWeight weight) @@ -342,7 +326,6 @@ bool LoadFontFace(const byte* data, int data_size, const String& font_family, St return font_interface->LoadFontFace(data, data_size, font_family, style, weight, fallback_face); } -// Registers a generic rmlui plugin void RegisterPlugin(Plugin* plugin) { if (initialised) @@ -351,12 +334,11 @@ void RegisterPlugin(Plugin* plugin) PluginRegistry::RegisterPlugin(plugin); } -// Unregisters a generic rmlui plugin void UnregisterPlugin(Plugin* plugin) { PluginRegistry::UnregisterPlugin(plugin); - if(initialised) + if (initialised) plugin->OnShutdown(); } diff --git a/Source/Core/DataController.cpp b/Source/Core/DataController.cpp index 4186be04e..ff442664e 100644 --- a/Source/Core/DataController.cpp +++ b/Source/Core/DataController.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,28 +32,25 @@ namespace Rml { -DataController::DataController(Element* element) : attached_element(element->GetObserverPtr()) -{} +DataController::DataController(Element* element) : attached_element(element->GetObserverPtr()) {} -DataController::~DataController() -{} -Element* DataController::GetElement() const { +DataController::~DataController() {} +Element* DataController::GetElement() const +{ return attached_element.get(); } -bool DataController::IsValid() const { +bool DataController::IsValid() const +{ return static_cast(attached_element); } +DataControllers::DataControllers() {} +DataControllers::~DataControllers() {} -DataControllers::DataControllers() -{} - -DataControllers::~DataControllers() -{} - -void DataControllers::Add(DataControllerPtr controller) { +void DataControllers::Add(DataControllerPtr controller) +{ RMLUI_ASSERT(controller); Element* element = controller->GetElement(); @@ -69,5 +66,4 @@ void DataControllers::OnElementRemove(Element* element) controllers.erase(element); } - } // namespace Rml diff --git a/Source/Core/DataController.h b/Source/Core/DataController.h index 37fdb4e2a..8e989fcd8 100644 --- a/Source/Core/DataController.h +++ b/Source/Core/DataController.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -30,31 +30,27 @@ #define RMLUI_CORE_DATACONTROLLER_H #include "../../Include/RmlUi/Core/Header.h" -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/Traits.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { class Element; class DataModel; - class DataControllerInstancer : public NonCopyMoveable { public: - DataControllerInstancer() {} - virtual ~DataControllerInstancer() {} - virtual DataControllerPtr InstanceController(Element* element) = 0; + DataControllerInstancer() {} + virtual ~DataControllerInstancer() {} + virtual DataControllerPtr InstanceController(Element* element) = 0; }; -template +template class DataControllerInstancerDefault final : public DataControllerInstancer { public: - DataControllerPtr InstanceController(Element* element) override { - return DataControllerPtr(new T(element)); - } + DataControllerPtr InstanceController(Element* element) override { return DataControllerPtr(new T(element)); } }; - /** Data controller. @@ -78,19 +74,19 @@ class DataController : public Releasable { public: virtual ~DataController(); - // Initialize the data controller. - // @param[in] model The data model the controller will be attached to. - // @param[in] element The element which spawned the controller. - // @param[in] expression The value of the element's 'data-' attribute which spawned the controller (see above). - // @param[in] modifier The modifier for the given controller type (see above). - // @return True on success. - virtual bool Initialize(DataModel& model, Element* element, const String& expression, const String& modifier) = 0; + // Initialize the data controller. + // @param[in] model The data model the controller will be attached to. + // @param[in] element The element which spawned the controller. + // @param[in] expression The value of the element's 'data-' attribute which spawned the controller (see above). + // @param[in] modifier The modifier for the given controller type (see above). + // @return True on success. + virtual bool Initialize(DataModel& model, Element* element, const String& expression, const String& modifier) = 0; - // Returns the attached element if it still exists. - Element* GetElement() const; + // Returns the attached element if it still exists. + Element* GetElement() const; - // Returns true if the element still exists. - bool IsValid() const; + // Returns true if the element still exists. + bool IsValid() const; protected: DataController(Element* element); @@ -99,21 +95,19 @@ class DataController : public Releasable { ObserverPtr attached_element; }; - class DataControllers : NonCopyMoveable { public: - DataControllers(); - ~DataControllers(); + DataControllers(); + ~DataControllers(); void Add(DataControllerPtr controller); - void OnElementRemove(Element* element); + void OnElementRemove(Element* element); private: - using ElementControllersMap = UnorderedMultimap; - ElementControllersMap controllers; + using ElementControllersMap = UnorderedMultimap; + ElementControllersMap controllers; }; - } // namespace Rml #endif diff --git a/Source/Core/DataControllerDefault.cpp b/Source/Core/DataControllerDefault.cpp index 24ad1e443..03c146a34 100644 --- a/Source/Core/DataControllerDefault.cpp +++ b/Source/Core/DataControllerDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,9 +35,7 @@ namespace Rml { -DataControllerValue::DataControllerValue(Element* element) - : DataController(element) -{} +DataControllerValue::DataControllerValue(Element* element) : DataController(element) {} DataControllerValue::~DataControllerValue() { @@ -55,7 +53,7 @@ bool DataControllerValue::Initialize(DataModel& model, Element* element, const S if (model.GetVariable(variable_address)) address = std::move(variable_address); - + element->AddEventListener(EventId::Change, this); return true; @@ -74,7 +72,8 @@ void DataControllerValue::ProcessEvent(Event& event) else if (value_it != parameters.cend()) value_to_set = value_it->second; else - Log::Message(Log::LT_WARNING, "A 'change' event was received, but it did not contain the attribute 'value' when processing a data binding in %s", + Log::Message(Log::LT_WARNING, + "A 'change' event was received, but it did not contain the attribute 'value' when processing a data binding in %s", element->GetAddress().c_str()); DataModel* model = element->GetDataModel(); @@ -92,9 +91,7 @@ void DataControllerValue::Release() delete this; } - -DataControllerEvent::DataControllerEvent(Element* element) : DataController(element) -{} +DataControllerEvent::DataControllerEvent(Element* element) : DataController(element) {} DataControllerEvent::~DataControllerEvent() { @@ -118,7 +115,8 @@ bool DataControllerEvent::Initialize(DataModel& model, Element* element, const S id = EventSpecificationInterface::GetIdOrInsert(modifier); if (id == EventId::Invalid) { - Log::Message(Log::LT_WARNING, "Event type '%s' could not be recognized, while adding 'data-event' to %s", modifier.c_str(), element->GetAddress().c_str()); + Log::Message(Log::LT_WARNING, "Event type '%s' could not be recognized, while adding 'data-event' to %s", modifier.c_str(), + element->GetAddress().c_str()); return false; } diff --git a/Source/Core/DataControllerDefault.h b/Source/Core/DataControllerDefault.h index caac0c084..51b274f47 100644 --- a/Source/Core/DataControllerDefault.h +++ b/Source/Core/DataControllerDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,10 +29,10 @@ #ifndef RMLUI_CORE_DATACONTROLLERDEFAULT_H #define RMLUI_CORE_DATACONTROLLERDEFAULT_H +#include "../../Include/RmlUi/Core/DataVariable.h" +#include "../../Include/RmlUi/Core/EventListener.h" #include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Types.h" -#include "../../Include/RmlUi/Core/EventListener.h" -#include "../../Include/RmlUi/Core/DataVariable.h" #include "DataController.h" namespace Rml { @@ -44,39 +44,38 @@ using DataExpressionPtr = UniquePtr; class DataControllerValue : public DataController, private EventListener { public: - DataControllerValue(Element* element); - ~DataControllerValue(); + DataControllerValue(Element* element); + ~DataControllerValue(); - bool Initialize(DataModel& model, Element* element, const String& expression, const String& modifier) override; + bool Initialize(DataModel& model, Element* element, const String& expression, const String& modifier) override; private: - // Responds to 'Change' events. - void ProcessEvent(Event& event) override; - - // Delete this. - void Release() override; + // Responds to 'Change' events. + void ProcessEvent(Event& event) override; - DataAddress address; -}; + // Delete this. + void Release() override; + DataAddress address; +}; class DataControllerEvent final : public DataController, private EventListener { public: - DataControllerEvent(Element* element); - ~DataControllerEvent(); + DataControllerEvent(Element* element); + ~DataControllerEvent(); - bool Initialize(DataModel& model, Element* element, const String& expression, const String& modifier) override; + bool Initialize(DataModel& model, Element* element, const String& expression, const String& modifier) override; protected: - // Responds to the event type specified in the attribute modifier. - void ProcessEvent(Event& event) override; + // Responds to the event type specified in the attribute modifier. + void ProcessEvent(Event& event) override; - // Delete this. - void Release() override; + // Delete this. + void Release() override; private: - EventId id = EventId::Invalid; - DataExpressionPtr expression; + EventId id = EventId::Invalid; + DataExpressionPtr expression; }; } // namespace Rml diff --git a/Source/Core/DataExpression.cpp b/Source/Core/DataExpression.cpp index e175e0819..3609e7656 100644 --- a/Source/Core/DataExpression.cpp +++ b/Source/Core/DataExpression.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,8 +34,8 @@ #include #ifdef _MSC_VER -#pragma warning(default : 4061) -#pragma warning(default : 4062) + #pragma warning(default : 4061) + #pragma warning(default : 4062) #endif namespace Rml { @@ -43,27 +43,28 @@ namespace Rml { class DataParser; /* - The abstract machine for RmlUi data expressions. + The abstract machine for RmlUi data expressions. - The machine can execute a program which contains a list of instructions listed below. + The machine can execute a program which contains a list of instructions listed below. - The abstract machine has three registers: - R Typically results and right-hand side arguments. - L Typically left-hand side arguments. - C Typically center arguments (eg. in ternary operator). + The abstract machine has three registers: + R Typically results and right-hand side arguments. + L Typically left-hand side arguments. + C Typically center arguments (eg. in ternary operator). - And a stack: - S The program stack. + And a stack: + S The program stack. - In addition, each instruction has an optional payload: - D Instruction data (payload). + In addition, each instruction has an optional payload: + D Instruction data (payload). - Notation used in the instruction list below: - S+ Push to stack S. - S- Pop stack S (returns the popped value). + Notation used in the instruction list below: + S+ Push to stack S. + S- Pop stack S (returns the popped value). */ -enum class Instruction { - // Assignment (register/stack) = Read (register R/L/C, instruction data D, or stack) +enum class Instruction { + // clang-format off + // Assignment (register/stack) = Read (register R/L/C, instruction data D, or stack) Push = 'P', // S+ = R Pop = 'o', // = S- (D determines R/L/C) Literal = 'D', // R = D @@ -86,12 +87,13 @@ enum class Instruction { TransformFnc = 'T', // R = DataModel.Execute(D, A) where A = S[TOP - R, TOP]; S -= R; (D determines function name, input R the num. arguments, A the arguments) EventFnc = 'E', // DataModel.EventCallback(D, A); S -= R; Assign = 'A', // DataModel.SetVariable(D, R) + // clang-format on }; enum class Register { R, L, - C + C, }; struct InstructionData { @@ -102,21 +104,25 @@ struct InstructionData { namespace Parse { static void Assignment(DataParser& parser); static void Expression(DataParser& parser); -} - +} // namespace Parse class DataParser { public: - DataParser(String expression, DataExpressionInterface expression_interface) : expression(std::move(expression)), expression_interface(expression_interface) {} + DataParser(String expression, DataExpressionInterface expression_interface) : + expression(std::move(expression)), expression_interface(expression_interface) + {} - char Look() { + char Look() + { if (reached_end) return '\0'; return expression[index]; } - bool Match(char c, bool skip_whitespace = true) { - if (c == Look()) { + bool Match(char c, bool skip_whitespace = true) + { + if (c == Look()) + { Next(); if (skip_whitespace) SkipWhitespace(); @@ -126,14 +132,16 @@ class DataParser { return false; } - char Next() { + char Next() + { ++index; if (index >= expression.size()) reached_end = true; return Look(); } - void SkipWhitespace() { + void SkipWhitespace() + { char c = Look(); while (StringUtilities::IsWhitespace(c)) c = Next(); @@ -144,21 +152,20 @@ class DataParser { parse_error = true; Log::Message(Log::LT_WARNING, "Error in data expression at %zu. %s", index, message.c_str()); Log::Message(Log::LT_WARNING, " \"%s\"", expression.c_str()); - + const size_t cursor_offset = size_t(index) + 3; const String cursor_string = String(cursor_offset, ' ') + '^'; Log::Message(Log::LT_WARNING, "%s", cursor_string.c_str()); } - void Expected(const String& expected_symbols) { + void Expected(const String& expected_symbols) + { const char c = Look(); if (c == '\0') Error(CreateString(expected_symbols.size() + 50, "Expected %s but found end of string.", expected_symbols.c_str())); else Error(CreateString(expected_symbols.size() + 50, "Expected %s but found character '%c'.", expected_symbols.c_str(), c)); } - void Expected(char expected) { - Expected(String(1, '\'') + expected + '\''); - } + void Expected(char expected) { Expected(String(1, '\'') + expected + '\''); } bool Parse(bool is_assignment_expression) { @@ -176,12 +183,14 @@ class DataParser { Parse::Assignment(*this); else Parse::Expression(*this); - - if (!reached_end) { + + if (!reached_end) + { parse_error = true; Error(CreateString(50, "Unexpected character '%c' encountered.", Look())); } - if (!parse_error && program_stack_size != 0) { + if (!parse_error && program_stack_size != 0) + { parse_error = true; Error(CreateString(120, "Internal parser error, inconsistent stack operations. Stack size is %d at parse end.", program_stack_size)); } @@ -189,11 +198,13 @@ class DataParser { return !parse_error; } - Program ReleaseProgram() { + Program ReleaseProgram() + { RMLUI_ASSERT(!parse_error); return std::move(program); } - AddressList ReleaseAddresses() { + AddressList ReleaseAddresses() + { RMLUI_ASSERT(!parse_error); return std::move(variable_addresses); } @@ -242,13 +253,14 @@ class DataParser { void VariableGetSet(const String& name, bool is_assignment) { DataAddress address = expression_interface.ParseAddress(name); - if (address.empty()) { + if (address.empty()) + { Error(CreateString(name.size() + 50, "Could not find data variable with name '%s'.", name.c_str())); return; } int index = int(variable_addresses.size()); variable_addresses.push_back(std::move(address)); - program.push_back(InstructionData{ is_assignment ? Instruction::Assign : Instruction::Variable, Variant(int(index)) }); + program.push_back(InstructionData{is_assignment ? Instruction::Assign : Instruction::Variable, Variant(int(index))}); } const String expression; @@ -260,11 +272,10 @@ class DataParser { int program_stack_size = 0; Program program; - + AddressList variable_addresses; }; - namespace Parse { // Forward declare all parse functions. @@ -356,7 +367,8 @@ namespace Parse { if (parser.Look() != '\0') { String variable_name = VariableOrFunctionName(parser, nullptr); - if (variable_name.empty()) { + if (variable_name.empty()) + { parser.Error("Expected a variable for assignment but got an empty name."); return; } @@ -428,8 +440,7 @@ namespace Parse { } break; case '?': Ternary(parser); break; - default: - looping = false; + default: looping = false; } } } @@ -447,12 +458,11 @@ namespace Parse { case '!': NotEqual(parser); break; case '<': Less(parser); break; case '>': Greater(parser); break; - default: - looping = false; + default: looping = false; } } } - + static void Additive(DataParser& parser) { Term(parser); @@ -464,13 +474,11 @@ namespace Parse { { case '+': Add(parser); break; case '-': Subtract(parser); break; - default: - looping = false; + default: looping = false; } } } - static void Term(DataParser& parser) { Factor(parser); @@ -482,8 +490,7 @@ namespace Parse { { case '*': Multiply(parser); break; case '/': Divide(parser); break; - default: - looping = false; + default: looping = false; } } } @@ -563,11 +570,13 @@ namespace Parse { while (c != '\0' && (c != '\'' || c_prev == '\\')) { - if (c_prev == '\\' && (c == '\\' || c == '\'')) { + if (c_prev == '\\' && (c == '\\' || c == '\'')) + { str.pop_back(); c_prev = '\0'; } - else { + else + { c_prev = c; } @@ -581,7 +590,8 @@ namespace Parse { { bool valid_function_name = true; String name = VariableOrFunctionName(parser, &valid_function_name); - if (name.empty()) { + if (name.empty()) + { parser.Error("Expected a variable or function name but got an empty name."); return; } @@ -665,11 +675,13 @@ namespace Parse { { Instruction instruction = Instruction::Less; parser.Match('<', false); - if (parser.Look() == '=') { + if (parser.Look() == '=') + { parser.Match('='); instruction = Instruction::LessEq; } - else { + else + { parser.SkipWhitespace(); } parser.Push(); @@ -681,11 +693,13 @@ namespace Parse { { Instruction instruction = Instruction::Greater; parser.Match('>', false); - if (parser.Look() == '=') { + if (parser.Look() == '=') + { parser.Match('='); instruction = Instruction::GreaterEq; } - else { + else + { parser.SkipWhitespace(); } parser.Push(); @@ -735,7 +749,8 @@ namespace Parse { bool looping = true; parser.Match('('); - if (parser.Look() == ')') { + if (parser.Look() == ')') + { parser.Match(')'); looping = false; } @@ -746,23 +761,29 @@ namespace Parse { Expression(parser); parser.Push(); - switch (parser.Look()) { - case ')': parser.Match(')'); looping = false; break; + switch (parser.Look()) + { + case ')': + parser.Match(')'); + looping = false; + break; case ',': parser.Match(','); break; default: parser.Expected("one of ')' or ','"); looping = false; + break; } } } - else { + else + { parser.SkipWhitespace(); } parser.Function(function_type, num_arguments, std::move(func_name)); } -} // +} // namespace Parse static String DumpProgram(const Program& program) { @@ -777,8 +798,9 @@ static String DumpProgram(const Program& program) class DataInterpreter { public: - DataInterpreter(const Program& program, const AddressList& addresses, DataExpressionInterface expression_interface) - : program(program), addresses(addresses), expression_interface(expression_interface) {} + DataInterpreter(const Program& program, const AddressList& addresses, DataExpressionInterface expression_interface) : + program(program), addresses(addresses), expression_interface(expression_interface) + {} bool Error(const String& message) const { @@ -799,8 +821,9 @@ class DataInterpreter { } } - if(success && !stack.empty()) - Log::Message(Log::LT_WARNING, "Possible data interpreter stack corruption. Stack size is %zu at end of execution (should be zero).", stack.size()); + if (success && !stack.empty()) + Log::Message(Log::LT_WARNING, "Possible data interpreter stack corruption. Stack size is %zu at end of execution (should be zero).", + stack.size()); if (!success) { @@ -812,10 +835,7 @@ class DataInterpreter { return success; } - Variant Result() const { - return R; - } - + Variant Result() const { return R; } private: Variant R, L, C; @@ -827,9 +847,7 @@ class DataInterpreter { bool Execute(const Instruction instruction, const Variant& data) { - auto AnyString = [](const Variant& v1, const Variant& v2) { - return v1.GetType() == Variant::STRING || v2.GetType() == Variant::STRING; - }; + auto AnyString = [](const Variant& v1, const Variant& v2) { return v1.GetType() == Variant::STRING || v2.GetType() == Variant::STRING; }; switch (instruction) { @@ -845,12 +863,14 @@ class DataInterpreter { return Error("Cannot pop stack, it is empty."); Register reg = Register(data.Get(-1)); - switch (reg) { + switch (reg) + { + // clang-format off case Register::R: R = stack.back(); stack.pop_back(); break; case Register::L: L = stack.back(); stack.pop_back(); break; case Register::C: C = stack.back(); stack.pop_back(); break; - default: - return Error(CreateString(50, "Invalid register %d.", int(reg))); + // clang-format on + default: return Error(CreateString(50, "Invalid register %d.", int(reg))); } } break; @@ -876,6 +896,7 @@ class DataInterpreter { R = Variant(L.Get() + R.Get()); } break; + // clang-format off case Instruction::Subtract: R = Variant(L.Get() - R.Get()); break; case Instruction::Multiply: R = Variant(L.Get() * R.Get()); break; case Instruction::Divide: R = Variant(L.Get() / R.Get()); break; @@ -886,6 +907,7 @@ class DataInterpreter { case Instruction::LessEq: R = Variant(L.Get() <= R.Get()); break; case Instruction::Greater: R = Variant(L.Get() > R.Get()); break; case Instruction::GreaterEq: R = Variant(L.Get() >= R.Get()); break; + // clang-format on case Instruction::Equal: { if (AnyString(L, R)) @@ -951,8 +973,7 @@ class DataInterpreter { return Error("Variable address not found."); } break; - default: - RMLUI_ERRORMSG("Instruction not implemented."); break; + default: RMLUI_ERRORMSG("Instruction not implemented."); break; } return true; } @@ -973,12 +994,9 @@ class DataInterpreter { } }; +DataExpression::DataExpression(String expression) : expression(std::move(expression)) {} -DataExpression::DataExpression(String expression) : expression(std::move(expression)) -{} - -DataExpression::~DataExpression() -{} +DataExpression::~DataExpression() {} bool DataExpression::Parse(const DataExpressionInterface& expression_interface, bool is_assignment_expression) { @@ -995,7 +1013,7 @@ bool DataExpression::Parse(const DataExpressionInterface& expression_interface, bool DataExpression::Run(const DataExpressionInterface& expression_interface, Variant& out_value) { DataInterpreter interpreter(program, addresses, expression_interface); - + if (!interpreter.Run()) return false; @@ -1015,20 +1033,21 @@ StringList DataExpression::GetVariableNameList() const return list; } -DataExpressionInterface::DataExpressionInterface(DataModel* data_model, Element* element, Event* event) : data_model(data_model), element(element), event(event) +DataExpressionInterface::DataExpressionInterface(DataModel* data_model, Element* element, Event* event) : + data_model(data_model), element(element), event(event) {} DataAddress DataExpressionInterface::ParseAddress(const String& address_str) const { if (address_str.size() >= 4 && address_str[0] == 'e' && address_str[1] == 'v' && address_str[2] == '.') - return DataAddress{ DataAddressEntry("ev"), DataAddressEntry(address_str.substr(3)) }; + return DataAddress{DataAddressEntry("ev"), DataAddressEntry(address_str.substr(3))}; return data_model ? data_model->ResolveAddress(address_str, element) : DataAddress(); } Variant DataExpressionInterface::GetValue(const DataAddress& address) const { Variant result; - if(event && address.size() == 2 && address.front().name == "ev") + if (event && address.size() == 2 && address.front().name == "ev") { auto& parameters = event->GetParameters(); auto it = parameters.find(address.back().name); diff --git a/Source/Core/DataExpression.h b/Source/Core/DataExpression.h index 43e282ad0..0c4b4b386 100644 --- a/Source/Core/DataExpression.h +++ b/Source/Core/DataExpression.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,9 +29,9 @@ #ifndef RMLUI_CORE_DATAEXPRESSION_H #define RMLUI_CORE_DATAEXPRESSION_H +#include "../../Include/RmlUi/Core/DataTypes.h" #include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Types.h" -#include "../../Include/RmlUi/Core/DataTypes.h" namespace Rml { @@ -43,39 +43,38 @@ using AddressList = Vector; class DataExpressionInterface { public: - DataExpressionInterface() = default; - DataExpressionInterface(DataModel* data_model, Element* element, Event* event = nullptr); + DataExpressionInterface() = default; + DataExpressionInterface(DataModel* data_model, Element* element, Event* event = nullptr); - DataAddress ParseAddress(const String& address_str) const; - Variant GetValue(const DataAddress& address) const; - bool SetValue(const DataAddress& address, const Variant& value) const; - bool CallTransform(const String& name, const VariantList& arguments, Variant& out_result); - bool EventCallback(const String& name, const VariantList& arguments); + DataAddress ParseAddress(const String& address_str) const; + Variant GetValue(const DataAddress& address) const; + bool SetValue(const DataAddress& address, const Variant& value) const; + bool CallTransform(const String& name, const VariantList& arguments, Variant& out_result); + bool EventCallback(const String& name, const VariantList& arguments); private: - DataModel* data_model = nullptr; - Element* element = nullptr; - Event* event = nullptr; + DataModel* data_model = nullptr; + Element* element = nullptr; + Event* event = nullptr; }; - class DataExpression { public: - DataExpression(String expression); - ~DataExpression(); + DataExpression(String expression); + ~DataExpression(); - bool Parse(const DataExpressionInterface& expression_interface, bool is_assignment_expression); + bool Parse(const DataExpressionInterface& expression_interface, bool is_assignment_expression); - bool Run(const DataExpressionInterface& expression_interface, Variant& out_value); + bool Run(const DataExpressionInterface& expression_interface, Variant& out_value); - // Available after Parse() - StringList GetVariableNameList() const; + // Available after Parse() + StringList GetVariableNameList() const; private: - String expression; - - Program program; - AddressList addresses; + String expression; + + Program program; + AddressList addresses; }; } // namespace Rml diff --git a/Source/Core/DataModel.cpp b/Source/Core/DataModel.cpp index 20d54cdc6..273801fa1 100644 --- a/Source/Core/DataModel.cpp +++ b/Source/Core/DataModel.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -79,10 +79,10 @@ static DataAddress ParseAddress(const String& address_str) static const char* LegalVariableName(const String& name) { static SmallUnorderedSet reserved_names{"it", "it_index", "ev", "true", "false", "size", "literal"}; - + if (name.empty()) return "Name cannot be empty."; - + const String name_lower = StringUtilities::ToLower(name); const char first = name_lower.front(); @@ -120,8 +120,7 @@ static String DataAddressToString(const DataAddress& address) return result; } -DataModel::DataModel(DataTypeRegister* data_type_register) : - data_type_register(data_type_register) +DataModel::DataModel(DataTypeRegister* data_type_register) : data_type_register(data_type_register) { views = MakeUnique(); controllers = MakeUnique(); @@ -132,11 +131,13 @@ DataModel::~DataModel() RMLUI_ASSERT(attached_elements.empty()); } -void DataModel::AddView(DataViewPtr view) { +void DataModel::AddView(DataViewPtr view) +{ views->Add(std::move(view)); } -void DataModel::AddController(DataControllerPtr controller) { +void DataModel::AddController(DataControllerPtr controller) +{ controllers->Add(std::move(controller)); } @@ -218,7 +219,7 @@ bool DataModel::InsertAlias(Element* element, const String& alias_name, DataAddr Log::Message(Log::LT_WARNING, "Alias variable '%s' is shadowed by a global variable.", alias_name.c_str()); auto& map = aliases.emplace(element, SmallUnorderedMap()).first->second; - + auto it = map.find(alias_name); if (it != map.end()) Log::Message(Log::LT_WARNING, "Alias name '%s' in data model already exists, replaced.", alias_name.c_str()); @@ -247,7 +248,7 @@ DataAddress DataModel::ResolveAddress(const String& address_str, Element* elemen return address; // Look for a variable alias for the first name. - + Element* ancestor = element; while (ancestor && ancestor->GetDataModel() == this) { @@ -321,7 +322,8 @@ const DataEventFunc* DataModel::GetEventCallback(const String& name) return &it->second; } -bool DataModel::GetVariableInto(const DataAddress& address, Variant& out_value) const { +bool DataModel::GetVariableInto(const DataAddress& address, Variant& out_value) const +{ DataVariable variable = GetVariable(address); bool result = (variable && variable.Get(out_value)); if (!result) @@ -342,9 +344,11 @@ bool DataModel::IsVariableDirty(const String& variable_name) const return dirty_variables.count(variable_name) == 1; } -void DataModel::DirtyAllVariables() { +void DataModel::DirtyAllVariables() +{ dirty_variables.reserve(variables.size()); - for (const auto& variable : variables) { + for (const auto& variable : variables) + { dirty_variables.emplace(variable.first); } } @@ -380,7 +384,7 @@ bool DataModel::Update(bool clear_dirty_variables) if (clear_dirty_variables) dirty_variables.clear(); - + return result; } diff --git a/Source/Core/DataModel.h b/Source/Core/DataModel.h index bee659850..c1a3ced4b 100644 --- a/Source/Core/DataModel.h +++ b/Source/Core/DataModel.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,11 +29,11 @@ #ifndef RMLUI_CORE_DATAMODEL_H #define RMLUI_CORE_DATAMODEL_H -#include "../../Include/RmlUi/Core/Header.h" -#include "../../Include/RmlUi/Core/Types.h" -#include "../../Include/RmlUi/Core/Traits.h" #include "../../Include/RmlUi/Core/DataModelHandle.h" #include "../../Include/RmlUi/Core/DataTypes.h" +#include "../../Include/RmlUi/Core/Header.h" +#include "../../Include/RmlUi/Core/Traits.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { @@ -43,7 +43,6 @@ class DataVariable; class Element; class FuncDefinition; - class DataModel : NonCopyMoveable { public: DataModel(DataTypeRegister* data_type_register = nullptr); @@ -80,9 +79,7 @@ class DataModel : NonCopyMoveable { bool Update(bool clear_dirty_variables); - inline DataTypeRegister* GetDataTypeRegister() const { - return data_type_register; - } + inline DataTypeRegister* GetDataTypeRegister() const { return data_type_register; } private: UniquePtr views; @@ -102,6 +99,5 @@ class DataModel : NonCopyMoveable { SmallUnorderedSet attached_elements; }; - } // namespace Rml #endif diff --git a/Source/Core/DataModelHandle.cpp b/Source/Core/DataModelHandle.cpp index bda10bdd6..29bc55c66 100644 --- a/Source/Core/DataModelHandle.cpp +++ b/Source/Core/DataModelHandle.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,42 +31,47 @@ namespace Rml { +DataModelHandle::DataModelHandle(DataModel* model) : model(model) {} -DataModelHandle::DataModelHandle(DataModel* model) : model(model) -{} - -bool DataModelHandle::IsVariableDirty(const String& variable_name) { +bool DataModelHandle::IsVariableDirty(const String& variable_name) +{ return model->IsVariableDirty(variable_name); } -void DataModelHandle::DirtyVariable(const String& variable_name) { +void DataModelHandle::DirtyVariable(const String& variable_name) +{ model->DirtyVariable(variable_name); } -void DataModelHandle::DirtyAllVariables() { +void DataModelHandle::DirtyAllVariables() +{ model->DirtyAllVariables(); } - DataModelConstructor::DataModelConstructor() : model(nullptr), type_register(nullptr) {} -DataModelConstructor::DataModelConstructor(DataModel* model) : model(model), type_register(model->GetDataTypeRegister()) { +DataModelConstructor::DataModelConstructor(DataModel* model) : model(model), type_register(model->GetDataTypeRegister()) +{ RMLUI_ASSERT(model); } -DataModelHandle DataModelConstructor::GetModelHandle() const { +DataModelHandle DataModelConstructor::GetModelHandle() const +{ return DataModelHandle(model); } -bool DataModelConstructor::BindFunc(const String& name, DataGetFunc get_func, DataSetFunc set_func) { +bool DataModelConstructor::BindFunc(const String& name, DataGetFunc get_func, DataSetFunc set_func) +{ return model->BindFunc(name, std::move(get_func), std::move(set_func)); } -bool DataModelConstructor::BindEventCallback(const String& name, DataEventFunc event_func) { +bool DataModelConstructor::BindEventCallback(const String& name, DataEventFunc event_func) +{ return model->BindEventCallback(name, std::move(event_func)); } -bool DataModelConstructor::BindVariable(const String& name, DataVariable data_variable) { +bool DataModelConstructor::BindVariable(const String& name, DataVariable data_variable) +{ return model->BindVariable(name, data_variable); } diff --git a/Source/Core/DataTypeRegister.cpp b/Source/Core/DataTypeRegister.cpp index a4813469f..967f4e84a 100644 --- a/Source/Core/DataTypeRegister.cpp +++ b/Source/Core/DataTypeRegister.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/DataVariable.cpp b/Source/Core/DataVariable.cpp index 50d5b74f6..4da3a9168 100644 --- a/Source/Core/DataVariable.cpp +++ b/Source/Core/DataVariable.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,141 +30,150 @@ namespace Rml { -bool DataVariable::Get(Variant& variant) { - return definition->Get(ptr, variant); +bool DataVariable::Get(Variant& variant) +{ + return definition->Get(ptr, variant); } -bool DataVariable::Set(const Variant& variant) { - return definition->Set(ptr, variant); +bool DataVariable::Set(const Variant& variant) +{ + return definition->Set(ptr, variant); } -int DataVariable::Size() { - return definition->Size(ptr); +int DataVariable::Size() +{ + return definition->Size(ptr); } -DataVariable DataVariable::Child(const DataAddressEntry& address) { - return definition->Child(ptr, address); +DataVariable DataVariable::Child(const DataAddressEntry& address) +{ + return definition->Child(ptr, address); } -DataVariableType DataVariable::Type() { - return definition->Type(); +DataVariableType DataVariable::Type() +{ + return definition->Type(); } - -bool VariableDefinition::Get(void* /*ptr*/, Variant& /*variant*/) { - Log::Message(Log::LT_WARNING, "Values can only be retrieved from scalar data types."); - return false; +bool VariableDefinition::Get(void* /*ptr*/, Variant& /*variant*/) +{ + Log::Message(Log::LT_WARNING, "Values can only be retrieved from scalar data types."); + return false; } -bool VariableDefinition::Set(void* /*ptr*/, const Variant& /*variant*/) { - Log::Message(Log::LT_WARNING, "Values can only be assigned to scalar data types."); - return false; +bool VariableDefinition::Set(void* /*ptr*/, const Variant& /*variant*/) +{ + Log::Message(Log::LT_WARNING, "Values can only be assigned to scalar data types."); + return false; } -int VariableDefinition::Size(void* /*ptr*/) { - Log::Message(Log::LT_WARNING, "Tried to get the size from a non-array data type."); - return 0; +int VariableDefinition::Size(void* /*ptr*/) +{ + Log::Message(Log::LT_WARNING, "Tried to get the size from a non-array data type."); + return 0; } -DataVariable VariableDefinition::Child(void* /*ptr*/, const DataAddressEntry& /*address*/) { - Log::Message(Log::LT_WARNING, "Tried to get the child of a scalar type."); - return DataVariable(); +DataVariable VariableDefinition::Child(void* /*ptr*/, const DataAddressEntry& /*address*/) +{ + Log::Message(Log::LT_WARNING, "Tried to get the child of a scalar type."); + return DataVariable(); } class LiteralIntDefinition final : public VariableDefinition { public: - LiteralIntDefinition() : VariableDefinition(DataVariableType::Scalar) {} + LiteralIntDefinition() : VariableDefinition(DataVariableType::Scalar) {} - bool Get(void* ptr, Variant& variant) override - { - variant = static_cast(reinterpret_cast(ptr)); - return true; - } + bool Get(void* ptr, Variant& variant) override + { + variant = static_cast(reinterpret_cast(ptr)); + return true; + } }; DataVariable MakeLiteralIntVariable(int value) { - static LiteralIntDefinition literal_int_definition; - return DataVariable(&literal_int_definition, reinterpret_cast(static_cast(value))); + static LiteralIntDefinition literal_int_definition; + return DataVariable(&literal_int_definition, reinterpret_cast(static_cast(value))); } -StructDefinition::StructDefinition() : VariableDefinition(DataVariableType::Struct) -{} +StructDefinition::StructDefinition() : VariableDefinition(DataVariableType::Struct) {} DataVariable StructDefinition::Child(void* ptr, const DataAddressEntry& address) { - const String& name = address.name; - if (name.empty()) - { - Log::Message(Log::LT_WARNING, "Expected a struct member name but none given."); - return DataVariable(); - } + const String& name = address.name; + if (name.empty()) + { + Log::Message(Log::LT_WARNING, "Expected a struct member name but none given."); + return DataVariable(); + } - auto it = members.find(name); - if (it == members.end()) - { - Log::Message(Log::LT_WARNING, "Member %s not found in data struct.", name.c_str()); - return DataVariable(); - } + auto it = members.find(name); + if (it == members.end()) + { + Log::Message(Log::LT_WARNING, "Member %s not found in data struct.", name.c_str()); + return DataVariable(); + } - VariableDefinition* next_definition = it->second.get(); + VariableDefinition* next_definition = it->second.get(); - return DataVariable(next_definition, ptr); + return DataVariable(next_definition, ptr); } void StructDefinition::AddMember(const String& name, UniquePtr member) { - RMLUI_ASSERT(member); - bool inserted = members.emplace(name, std::move(member)).second; - RMLUI_ASSERTMSG(inserted, "Member name already exists."); - (void)inserted; + RMLUI_ASSERT(member); + bool inserted = members.emplace(name, std::move(member)).second; + RMLUI_ASSERTMSG(inserted, "Member name already exists."); + (void)inserted; } -FuncDefinition::FuncDefinition(DataGetFunc get, DataSetFunc set) - : VariableDefinition(DataVariableType::Scalar), get(std::move(get)), set(std::move(set)) {} +FuncDefinition::FuncDefinition(DataGetFunc get, DataSetFunc set) : + VariableDefinition(DataVariableType::Scalar), get(std::move(get)), set(std::move(set)) +{} bool FuncDefinition::Get(void* /*ptr*/, Variant& variant) { - if (!get) - return false; - get(variant); - return true; + if (!get) + return false; + get(variant); + return true; } bool FuncDefinition::Set(void* /*ptr*/, const Variant& variant) { - if (!set) - return false; - set(variant); - return true; + if (!set) + return false; + set(variant); + return true; } -BasePointerDefinition::BasePointerDefinition(VariableDefinition* underlying_definition) - : VariableDefinition(underlying_definition->Type()), underlying_definition(underlying_definition) {} +BasePointerDefinition::BasePointerDefinition(VariableDefinition* underlying_definition) : + VariableDefinition(underlying_definition->Type()), underlying_definition(underlying_definition) +{} bool BasePointerDefinition::Get(void* ptr, Variant& variant) { - if(!ptr) - return false; - return underlying_definition->Get(DereferencePointer(ptr), variant); + if (!ptr) + return false; + return underlying_definition->Get(DereferencePointer(ptr), variant); } bool BasePointerDefinition::Set(void* ptr, const Variant& variant) { - if(!ptr) - return false; - return underlying_definition->Set(DereferencePointer(ptr), variant); + if (!ptr) + return false; + return underlying_definition->Set(DereferencePointer(ptr), variant); } int BasePointerDefinition::Size(void* ptr) { - if(!ptr) - return 0; - return underlying_definition->Size(DereferencePointer(ptr)); + if (!ptr) + return 0; + return underlying_definition->Size(DereferencePointer(ptr)); } DataVariable BasePointerDefinition::Child(void* ptr, const DataAddressEntry& address) { - if(!ptr) - return DataVariable(); - return underlying_definition->Child(DereferencePointer(ptr), address); + if (!ptr) + return DataVariable(); + return underlying_definition->Child(DereferencePointer(ptr), address); } } // namespace Rml diff --git a/Source/Core/DataView.cpp b/Source/Core/DataView.cpp index ac3bac439..b1c761d68 100644 --- a/Source/Core/DataView.cpp +++ b/Source/Core/DataView.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,8 +32,7 @@ namespace Rml { -DataView::~DataView() -{} +DataView::~DataView() {} Element* DataView::GetElement() const { @@ -43,15 +42,18 @@ Element* DataView::GetElement() const return result; } -int DataView::GetSortOrder() const { +int DataView::GetSortOrder() const +{ return sort_order; } -bool DataView::IsValid() const { +bool DataView::IsValid() const +{ return static_cast(attached_element); } -DataView::DataView(Element* element, int bias) : attached_element(element->GetObserverPtr()), sort_order(bias + 1000) { +DataView::DataView(Element* element, int bias) : attached_element(element->GetObserverPtr()), sort_order(bias + 1000) +{ RMLUI_ASSERT(bias >= -1000 && bias <= 999); if (element) @@ -61,18 +63,16 @@ DataView::DataView(Element* element, int bias) : attached_element(element->GetOb } } +DataViews::DataViews() {} -DataViews::DataViews() -{} - -DataViews::~DataViews() -{} +DataViews::~DataViews() {} -void DataViews::Add(DataViewPtr view) { +void DataViews::Add(DataViewPtr view) +{ views_to_add.push_back(std::move(view)); } -void DataViews::OnElementRemove(Element* element) +void DataViews::OnElementRemove(Element* element) { for (auto it = views.begin(); it != views.end();) { @@ -95,7 +95,7 @@ bool DataViews::Update(DataModel& model, const DirtyVariables& dirty_variables) // View updates may result in newly added views, or even new dirty variables. Thus, we do the // update recursively but with an upper limit. Without the loop, newly added views won't be // updated until the next Update() call. - for(int i = 0; (i == 0 || !views_to_add.empty() || num_dirty_variables_prev != dirty_variables.size()) && i < 10; i++) + for (int i = 0; (i == 0 || !views_to_add.empty() || num_dirty_variables_prev != dirty_variables.size()) && i < 10; i++) { num_dirty_variables_prev = dirty_variables.size(); @@ -127,8 +127,8 @@ bool DataViews::Update(DataModel& model, const DirtyVariables& dirty_variables) auto it_remove = std::unique(dirty_views.begin(), dirty_views.end()); dirty_views.erase(it_remove, dirty_views.end()); - // Sort by the element's depth in the document tree so that any structural changes due to a changed variable are reflected in the element's children. - // Eg. the 'data-for' view will remove children if any of its data variable array size is reduced. + // Sort by the element's depth in the document tree so that any structural changes due to a changed variable are reflected in the element's + // children. Eg. the 'data-for' view will remove children if any of its data variable array size is reduced. std::sort(dirty_views.begin(), dirty_views.end(), [](auto&& left, auto&& right) { return left->GetSortOrder() < right->GetSortOrder(); }); for (DataView* view : dirty_views) @@ -147,7 +147,7 @@ bool DataViews::Update(DataModel& model, const DirtyVariables& dirty_variables) { for (const auto& view : views_to_remove) { - for (auto it = name_view_map.begin(); it != name_view_map.end(); ) + for (auto it = name_view_map.begin(); it != name_view_map.end();) { if (it->second == view.get()) it = name_view_map.erase(it); diff --git a/Source/Core/DataView.h b/Source/Core/DataView.h index ada47c2a1..23d6d8fe1 100644 --- a/Source/Core/DataView.h +++ b/Source/Core/DataView.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,17 +29,16 @@ #ifndef RMLUI_CORE_DATAVIEW_H #define RMLUI_CORE_DATAVIEW_H +#include "../../Include/RmlUi/Core/DataTypes.h" #include "../../Include/RmlUi/Core/Header.h" -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/Traits.h" -#include "../../Include/RmlUi/Core/DataTypes.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { class Element; class DataModel; - class DataViewInstancer : public NonCopyMoveable { public: DataViewInstancer() {} @@ -47,23 +46,21 @@ class DataViewInstancer : public NonCopyMoveable { virtual DataViewPtr InstanceView(Element* element) = 0; }; -template +template class DataViewInstancerDefault final : public DataViewInstancer { public: - DataViewPtr InstanceView(Element* element) override { - return DataViewPtr(new T(element)); - } + DataViewPtr InstanceView(Element* element) override { return DataViewPtr(new T(element)); } }; /** - Data view. + Data view. + + Data views are used to present a data variable in the document by different means. + A data view is declared in the document by the element attribute: - Data views are used to present a data variable in the document by different means. - A data view is declared in the document by the element attribute: - - data-[type]-[modifier]="[expression]" + data-[type]-[modifier]="[expression]" - The modifier may or may not be required depending on the data view. + The modifier may or may not be required depending on the data view. */ class DataView : public Releasable { @@ -91,10 +88,10 @@ class DataView : public Releasable { // Data views are first sorted by the depth of the attached element in the // document tree, then optionally by an offset specified for each data view. int GetSortOrder() const; - + // Returns true if the element still exists. bool IsValid() const; - + protected: // @param[in] element The element this data view is attached to. // @param[in] sort_offset A number [-1000, 999] specifying the update order of this @@ -106,8 +103,6 @@ class DataView : public Releasable { int sort_order; }; - - class DataViews : NonCopyMoveable { public: DataViews(); @@ -123,7 +118,7 @@ class DataViews : NonCopyMoveable { using DataViewList = Vector; DataViewList views; - + DataViewList views_to_add; DataViewList views_to_remove; diff --git a/Source/Core/DataViewDefault.cpp b/Source/Core/DataViewDefault.cpp index 654f2a37d..d04123683 100644 --- a/Source/Core/DataViewDefault.cpp +++ b/Source/Core/DataViewDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,9 +27,6 @@ */ #include "DataViewDefault.h" -#include "DataExpression.h" -#include "DataModel.h" -#include "XMLParseTools.h" #include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/DataVariable.h" #include "../../Include/RmlUi/Core/Element.h" @@ -37,6 +34,9 @@ #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/SystemInterface.h" #include "../../Include/RmlUi/Core/Variant.h" +#include "DataExpression.h" +#include "DataModel.h" +#include "XMLParseTools.h" namespace Rml { @@ -46,8 +46,8 @@ static constexpr int SortOffset_DataValue = 100; // 'data-checked' may need a value attribute already set. static constexpr int SortOffset_DataChecked = 110; - -DataViewCommon::DataViewCommon(Element* element, String override_modifier, int sort_offset) : DataView(element, sort_offset), modifier(std::move(override_modifier)) +DataViewCommon::DataViewCommon(Element* element, String override_modifier, int sort_offset) : + DataView(element, sort_offset), modifier(std::move(override_modifier)) {} bool DataViewCommon::Initialize(DataModel& model, Element* element, const String& expression_str, const String& in_modifier) @@ -63,16 +63,19 @@ bool DataViewCommon::Initialize(DataModel& model, Element* element, const String return result; } -StringList DataViewCommon::GetVariableNameList() const { +StringList DataViewCommon::GetVariableNameList() const +{ RMLUI_ASSERT(expression); return expression->GetVariableNameList(); } -const String& DataViewCommon::GetModifier() const { +const String& DataViewCommon::GetModifier() const +{ return modifier; } -DataExpression& DataViewCommon::GetExpression() { +DataExpression& DataViewCommon::GetExpression() +{ RMLUI_ASSERT(expression); return *expression; } @@ -82,11 +85,10 @@ void DataViewCommon::Release() delete this; } +DataViewAttribute::DataViewAttribute(Element* element) : DataViewCommon(element) {} -DataViewAttribute::DataViewAttribute(Element* element) : DataViewCommon(element) -{} - -DataViewAttribute::DataViewAttribute(Element * element, String override_attribute, int sort_offset) : DataViewCommon(element, std::move(override_attribute), sort_offset) +DataViewAttribute::DataViewAttribute(Element* element, String override_attribute, int sort_offset) : + DataViewCommon(element, std::move(override_attribute), sort_offset) {} bool DataViewAttribute::Update(DataModel& model) @@ -101,7 +103,7 @@ bool DataViewAttribute::Update(DataModel& model) { const String value = variant.Get(); const Variant* attribute = element->GetAttribute(attribute_name); - + if (!attribute || (attribute && attribute->Get() != value)) { element->SetAttribute(attribute_name, value); @@ -111,9 +113,7 @@ bool DataViewAttribute::Update(DataModel& model) return result; } - -DataViewAttributeIf::DataViewAttributeIf(Element* element) : DataViewCommon(element) -{} +DataViewAttributeIf::DataViewAttributeIf(Element* element) : DataViewCommon(element) {} bool DataViewAttributeIf::Update(DataModel& model) { @@ -139,14 +139,11 @@ bool DataViewAttributeIf::Update(DataModel& model) return result; } +DataViewValue::DataViewValue(Element* element) : DataViewAttribute(element, "value", SortOffset_DataValue) {} -DataViewValue::DataViewValue(Element* element) : DataViewAttribute(element, "value", SortOffset_DataValue) -{} - -DataViewChecked::DataViewChecked(Element* element) : DataViewCommon(element, String(), SortOffset_DataChecked) -{} +DataViewChecked::DataViewChecked(Element* element) : DataViewCommon(element, String(), SortOffset_DataChecked) {} -bool DataViewChecked::Update(DataModel & model) +bool DataViewChecked::Update(DataModel& model) { bool result = false; Variant variant; @@ -182,9 +179,7 @@ bool DataViewChecked::Update(DataModel & model) return result; } - -DataViewStyle::DataViewStyle(Element* element) : DataViewCommon(element) -{} +DataViewStyle::DataViewStyle(Element* element) : DataViewCommon(element) {} bool DataViewStyle::Update(DataModel& model) { @@ -193,7 +188,7 @@ bool DataViewStyle::Update(DataModel& model) Variant variant; Element* element = GetElement(); DataExpressionInterface expr_interface(&model, element); - + if (element && GetExpression().Run(expr_interface, variant)) { const String value = variant.Get(); @@ -207,9 +202,7 @@ bool DataViewStyle::Update(DataModel& model) return result; } - -DataViewClass::DataViewClass(Element* element) : DataViewCommon(element) -{} +DataViewClass::DataViewClass(Element* element) : DataViewCommon(element) {} bool DataViewClass::Update(DataModel& model) { @@ -232,11 +225,9 @@ bool DataViewClass::Update(DataModel& model) return result; } +DataViewRml::DataViewRml(Element* element) : DataViewCommon(element) {} -DataViewRml::DataViewRml(Element* element) : DataViewCommon(element) -{} - -bool DataViewRml::Update(DataModel & model) +bool DataViewRml::Update(DataModel& model) { bool result = false; Variant variant; @@ -256,9 +247,7 @@ bool DataViewRml::Update(DataModel & model) return result; } - -DataViewIf::DataViewIf(Element* element) : DataViewCommon(element) -{} +DataViewIf::DataViewIf(Element* element) : DataViewCommon(element) {} bool DataViewIf::Update(DataModel& model) { @@ -271,7 +260,7 @@ bool DataViewIf::Update(DataModel& model) { const bool value = variant.Get(); const bool is_visible = (element->GetLocalStyleProperties().count(PropertyId::Display) == 0); - if(is_visible != value) + if (is_visible != value) { if (value) element->RemoveProperty(PropertyId::Display); @@ -283,9 +272,7 @@ bool DataViewIf::Update(DataModel& model) return result; } - -DataViewVisible::DataViewVisible(Element* element) : DataViewCommon(element) -{} +DataViewVisible::DataViewVisible(Element* element) : DataViewCommon(element) {} bool DataViewVisible::Update(DataModel& model) { @@ -310,21 +297,16 @@ bool DataViewVisible::Update(DataModel& model) return result; } +DataViewText::DataViewText(Element* element) : DataView(element, 0) {} -DataViewText::DataViewText(Element* element) : DataView(element, 0) -{} - -bool DataViewText::Initialize(DataModel& model, Element* element, const String& RMLUI_UNUSED_PARAMETER(expression), const String& RMLUI_UNUSED_PARAMETER(modifier)) +bool DataViewText::Initialize(DataModel& model, Element* element, const String& /*expression*/, const String& /*modifier*/) { - RMLUI_UNUSED(expression); - RMLUI_UNUSED(modifier); - ElementText* element_text = rmlui_dynamic_cast(element); if (!element_text) return false; const String& in_text = element_text->GetText(); - + text.reserve(in_text.size()); DataExpressionInterface expression_interface(&model, element); @@ -336,7 +318,8 @@ bool DataViewText::Initialize(DataModel& model, Element* element, const String& bool in_brackets = false; bool in_string = false; - for(char c : in_text) { + for (char c : in_text) + { was_in_brackets = in_brackets; const char* error_str = XMLParseTools::ParseDataBrackets(in_brackets, in_string, c, previous); @@ -408,7 +391,8 @@ bool DataViewText::Update(DataModel& model) { if (Element* element = GetElement()) { - RMLUI_ASSERTMSG(rmlui_dynamic_cast(element), "Somehow the element type was changed from ElementText since construction of the view. Should not be possible?"); + RMLUI_ASSERTMSG(rmlui_dynamic_cast(element), + "Somehow the element type was changed from ElementText since construction of the view. Should not be possible?"); if (ElementText* text_element = static_cast(element)) { @@ -439,10 +423,7 @@ StringList DataViewText::GetVariableNameList() const RMLUI_ASSERT(entry.data_expression); StringList entry_list = entry.data_expression->GetVariableNameList(); - full_list.insert(full_list.end(), - MakeMoveIterator(entry_list.begin()), - MakeMoveIterator(entry_list.end()) - ); + full_list.insert(full_list.end(), MakeMoveIterator(entry_list.begin()), MakeMoveIterator(entry_list.end())); } return full_list; @@ -477,10 +458,7 @@ String DataViewText::BuildText() const return result; } - - -DataViewFor::DataViewFor(Element* element) : DataView(element, 0) -{} +DataViewFor::DataViewFor(Element* element) : DataView(element, 0) {} bool DataViewFor::Initialize(DataModel& model, Element* element, const String& in_expression, const String& in_rml_content) { @@ -489,7 +467,8 @@ bool DataViewFor::Initialize(DataModel& model, Element* element, const String& i StringList iterator_container_pair; StringUtilities::ExpandString(iterator_container_pair, in_expression, ':'); - if (iterator_container_pair.empty() || iterator_container_pair.size() > 2 || iterator_container_pair.front().empty() || iterator_container_pair.back().empty()) + if (iterator_container_pair.empty() || iterator_container_pair.size() > 2 || iterator_container_pair.front().empty() || + iterator_container_pair.back().empty()) { Log::Message(Log::LT_WARNING, "Invalid syntax in data-for '%s'", in_expression.c_str()); return false; @@ -544,7 +523,6 @@ bool DataViewFor::Initialize(DataModel& model, Element* element, const String& i return true; } - bool DataViewFor::Update(DataModel& model) { DataVariable variable = model.GetVariable(container_address); @@ -567,9 +545,7 @@ bool DataViewFor::Update(DataModel& model) iterator_address = container_address; iterator_address.push_back(DataAddressEntry(i)); - DataAddress iterator_index_address = { - {"literal"}, {"int"}, {i} - }; + DataAddress iterator_index_address = {{"literal"}, {"int"}, {i}}; model.InsertAlias(new_element_ptr.get(), iterator_name, std::move(iterator_address)); model.InsertAlias(new_element_ptr.get(), iterator_index_name, std::move(iterator_index_address)); @@ -595,9 +571,10 @@ bool DataViewFor::Update(DataModel& model) return result; } -StringList DataViewFor::GetVariableNameList() const { +StringList DataViewFor::GetVariableNameList() const +{ RMLUI_ASSERT(!container_address.empty()); - return StringList{ container_address.front().name }; + return StringList{container_address.front().name}; } void DataViewFor::Release() diff --git a/Source/Core/DataViewDefault.h b/Source/Core/DataViewDefault.h index c7c320938..a36f42e7c 100644 --- a/Source/Core/DataViewDefault.h +++ b/Source/Core/DataViewDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -40,7 +40,6 @@ class Element; class DataExpression; using DataExpressionPtr = UniquePtr; - class DataViewCommon : public DataView { public: DataViewCommon(Element* element, String override_modifier = String(), int sort_offset = 0); @@ -61,7 +60,6 @@ class DataViewCommon : public DataView { DataExpressionPtr expression; }; - class DataViewAttribute : public DataViewCommon { public: DataViewAttribute(Element* element); @@ -96,7 +94,6 @@ class DataViewStyle final : public DataViewCommon { bool Update(DataModel& model) override; }; - class DataViewClass final : public DataViewCommon { public: DataViewClass(Element* element); @@ -104,7 +101,6 @@ class DataViewClass final : public DataViewCommon { bool Update(DataModel& model) override; }; - class DataViewRml final : public DataViewCommon { public: DataViewRml(Element* element); @@ -115,7 +111,6 @@ class DataViewRml final : public DataViewCommon { String previous_rml; }; - class DataViewIf final : public DataViewCommon { public: DataViewIf(Element* element); @@ -123,7 +118,6 @@ class DataViewIf final : public DataViewCommon { bool Update(DataModel& model) override; }; - class DataViewVisible final : public DataViewCommon { public: DataViewVisible(Element* element); @@ -131,7 +125,6 @@ class DataViewVisible final : public DataViewCommon { bool Update(DataModel& model) override; }; - class DataViewText final : public DataView { public: DataViewText(Element* in_element); @@ -157,7 +150,6 @@ class DataViewText final : public DataView { Vector data_entries; }; - class DataViewFor final : public DataView { public: DataViewFor(Element* element); diff --git a/Source/Core/Decorator.cpp b/Source/Core/Decorator.cpp index a30391a53..44a188466 100644 --- a/Source/Core/Decorator.cpp +++ b/Source/Core/Decorator.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,20 +27,16 @@ */ #include "../../Include/RmlUi/Core/Decorator.h" -#include "TextureDatabase.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" #include "../../Include/RmlUi/Core/Texture.h" +#include "TextureDatabase.h" #include namespace Rml { -Decorator::Decorator() -{ -} +Decorator::Decorator() {} -Decorator::~Decorator() -{ -} +Decorator::~Decorator() {} int Decorator::AddTexture(const Texture& texture) { @@ -68,12 +64,11 @@ int Decorator::GetNumTextures() const return result; } -// Returns one of the decorator's previously loaded textures. const Texture* Decorator::GetTexture(int index) const { if (index == 0) return &first_texture; - + index -= 1; if (index < 0 || index >= (int)additional_textures.size()) return nullptr; @@ -81,5 +76,4 @@ const Texture* Decorator::GetTexture(int index) const return &(additional_textures[index]); } - } // namespace Rml diff --git a/Source/Core/DecoratorGradient.cpp b/Source/Core/DecoratorGradient.cpp index f37ea5c4d..9baadc7df 100644 --- a/Source/Core/DecoratorGradient.cpp +++ b/Source/Core/DecoratorGradient.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -47,15 +47,9 @@ stop-color: #00ff00; namespace Rml { -//======================================================= +DecoratorGradient::DecoratorGradient() {} -DecoratorGradient::DecoratorGradient() -{ -} - -DecoratorGradient::~DecoratorGradient() -{ -} +DecoratorGradient::~DecoratorGradient() {} bool DecoratorGradient::Initialise(const Direction dir_, const Colourb start_, const Colourb stop_) { @@ -123,8 +117,6 @@ void DecoratorGradient::RenderElement(Element* element, DecoratorDataHandle elem data->Render(element->GetAbsoluteOffset(Box::BORDER)); } -//======================================================= - DecoratorGradientInstancer::DecoratorGradientInstancer() { // register properties for the decorator @@ -134,22 +126,18 @@ DecoratorGradientInstancer::DecoratorGradientInstancer() RegisterShorthand("decorator", "direction, start-color, stop-color", ShorthandType::FallThrough); } -DecoratorGradientInstancer::~DecoratorGradientInstancer() -{ -} +DecoratorGradientInstancer::~DecoratorGradientInstancer() {} -SharedPtr DecoratorGradientInstancer::InstanceDecorator(const String & RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties_, - const DecoratorInstancerInterface& RMLUI_UNUSED_PARAMETER(interface_)) +SharedPtr DecoratorGradientInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties_, + const DecoratorInstancerInterface& /*interface_*/) { - RMLUI_UNUSED(name); - RMLUI_UNUSED(interface_); - - DecoratorGradient::Direction dir = (DecoratorGradient::Direction)properties_.GetProperty(ids.direction)->Get< int >(); + DecoratorGradient::Direction dir = (DecoratorGradient::Direction)properties_.GetProperty(ids.direction)->Get(); Colourb start = properties_.GetProperty(ids.start)->Get(); Colourb stop = properties_.GetProperty(ids.stop)->Get(); auto decorator = MakeShared(); - if (decorator->Initialise(dir, start, stop)) { + if (decorator->Initialise(dir, start, stop)) + { return decorator; } diff --git a/Source/Core/DecoratorGradient.h b/Source/Core/DecoratorGradient.h index 73264831e..56a36bbf0 100644 --- a/Source/Core/DecoratorGradient.h +++ b/Source/Core/DecoratorGradient.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,8 +35,7 @@ namespace Rml { -class DecoratorGradient : public Decorator -{ +class DecoratorGradient : public Decorator { public: enum class Direction { Horizontal = 0, Vertical = 1 }; @@ -55,22 +54,19 @@ class DecoratorGradient : public Decorator Colourb start, stop; }; - - -class DecoratorGradientInstancer : public DecoratorInstancer -{ +class DecoratorGradientInstancer : public DecoratorInstancer { public: DecoratorGradientInstancer(); ~DecoratorGradientInstancer(); - SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) override; + SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) override; private: struct GradientPropertyIds { PropertyId direction, start, stop; }; GradientPropertyIds ids; - }; } // namespace Rml diff --git a/Source/Core/DecoratorInstancer.cpp b/Source/Core/DecoratorInstancer.cpp index d475ad5fd..fc4772dbd 100644 --- a/Source/Core/DecoratorInstancer.cpp +++ b/Source/Core/DecoratorInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,39 +26,32 @@ * */ -#include "../../Include/RmlUi/Core/StyleSheet.h" #include "../../Include/RmlUi/Core/DecoratorInstancer.h" +#include "../../Include/RmlUi/Core/StyleSheet.h" namespace Rml { -DecoratorInstancer::DecoratorInstancer() : properties(10, 10) -{ -} +DecoratorInstancer::DecoratorInstancer() : properties(10, 10) {} -DecoratorInstancer::~DecoratorInstancer() -{ -} +DecoratorInstancer::~DecoratorInstancer() {} -// Returns the property specification associated with the instancer. const PropertySpecification& DecoratorInstancer::GetPropertySpecification() const { return properties; } -// Registers a property for the decorator. PropertyDefinition& DecoratorInstancer::RegisterProperty(const String& property_name, const String& default_value) { return properties.RegisterProperty(property_name, default_value, false, false); } -// Registers a shorthand property definition. ShorthandId DecoratorInstancer::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type) { return properties.RegisterShorthand(shorthand_name, property_names, type); } - -const Sprite* DecoratorInstancerInterface::GetSprite(const String& name) const { +const Sprite* DecoratorInstancerInterface::GetSprite(const String& name) const +{ return style_sheet.GetSprite(name); } diff --git a/Source/Core/DecoratorNinePatch.cpp b/Source/Core/DecoratorNinePatch.cpp index 66ef17f7b..655857707 100644 --- a/Source/Core/DecoratorNinePatch.cpp +++ b/Source/Core/DecoratorNinePatch.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,29 +29,26 @@ #include "DecoratorNinePatch.h" #include "../../Include/RmlUi/Core/ComputedValues.h" #include "../../Include/RmlUi/Core/Element.h" -#include "../../Include/RmlUi/Core/Geometry.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" +#include "../../Include/RmlUi/Core/Geometry.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" namespace Rml { -DecoratorNinePatch::DecoratorNinePatch() -{ -} +DecoratorNinePatch::DecoratorNinePatch() {} -DecoratorNinePatch::~DecoratorNinePatch() -{ -} +DecoratorNinePatch::~DecoratorNinePatch() {} -bool DecoratorNinePatch::Initialise(const Rectanglef& _rect_outer, const Rectanglef& _rect_inner, const Array* _edges, const Texture& _texture, float _display_scale) +bool DecoratorNinePatch::Initialise(const Rectanglef& _rect_outer, const Rectanglef& _rect_inner, const Array* _edges, + const Texture& _texture, float _display_scale) { rect_outer = _rect_outer; rect_inner = _rect_inner; - + display_scale = _display_scale; if (_edges) - edges = MakeUnique< Array >(*_edges); + edges = MakeUnique>(*_edges); int texture_index = AddTexture(_texture); return (texture_index >= 0); @@ -75,7 +72,6 @@ DecoratorDataHandle DecoratorNinePatch::GenerateElementData(Element* element) co quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha); - /* In the following, we operate on the four diagonal vertices in the grid, as they define the whole grid. */ // Absolute texture coordinates 'px' @@ -98,7 +94,7 @@ DecoratorDataHandle DecoratorNinePatch::GenerateElementData(Element* element) co // Surface position in pixels [0, surface_dimensions] // Need to keep the corner patches at their natural size, but stretch the inner patches. Vector2f surface_pos[4]; - surface_pos[0] = { 0, 0 }; + surface_pos[0] = {0, 0}; surface_pos[1] = (tex_pos[1] - tex_pos[0]) * scale_raw_to_natural_dimensions; surface_pos[2] = surface_dimensions - (tex_pos[3] - tex_pos[2]) * scale_raw_to_natural_dimensions; surface_pos[3] = surface_dimensions; @@ -148,8 +144,8 @@ DecoratorDataHandle DecoratorNinePatch::GenerateElementData(Element* element) co { Vertex& vertex = vertices[y * 4 + x]; vertex.colour = quad_colour; - vertex.position = { surface_pos[x].x, surface_pos[y].y }; - vertex.tex_coord = { tex_coords[x].x, tex_coords[y].y }; + vertex.position = {surface_pos[x].x, surface_pos[y].y}; + vertex.tex_coord = {tex_coords[x].x, tex_coords[y].y}; } } @@ -157,12 +153,12 @@ DecoratorDataHandle DecoratorNinePatch::GenerateElementData(Element* element) co indices.resize(9 * 2 * 3); // Fill in the indices one rectangle at a time. - const int top_left_indices[9] = { 0, 1, 2, 4, 5, 6, 8, 9, 10 }; + const int top_left_indices[9] = {0, 1, 2, 4, 5, 6, 8, 9, 10}; for (int rectangle = 0; rectangle < 9; rectangle++) { int i = rectangle * 6; int top_left_index = top_left_indices[rectangle]; - indices[i] = top_left_index; + indices[i] = top_left_index; indices[i + 1] = top_left_index + 4; indices[i + 2] = top_left_index + 1; indices[i + 3] = top_left_index + 1; @@ -175,17 +171,15 @@ DecoratorDataHandle DecoratorNinePatch::GenerateElementData(Element* element) co void DecoratorNinePatch::ReleaseElementData(DecoratorDataHandle element_data) const { - delete reinterpret_cast< Geometry* >(element_data); + delete reinterpret_cast(element_data); } void DecoratorNinePatch::RenderElement(Element* element, DecoratorDataHandle element_data) const { - Geometry* data = reinterpret_cast< Geometry* >(element_data); + Geometry* data = reinterpret_cast(element_data); data->Render(element->GetAbsoluteOffset(Box::PADDING)); } - - DecoratorNinePatchInstancer::DecoratorNinePatchInstancer() { sprite_outer_id = RegisterProperty("outer", "").AddParser("string").GetId(); @@ -196,22 +190,19 @@ DecoratorNinePatchInstancer::DecoratorNinePatchInstancer() edge_ids[3] = RegisterProperty("edge-left", "0px").AddParser("number_length_percent").GetId(); RegisterShorthand("edge", "edge-top, edge-right, edge-bottom, edge-left", ShorthandType::Box); - + RMLUI_ASSERT(sprite_outer_id != PropertyId::Invalid && sprite_inner_id != PropertyId::Invalid); RegisterShorthand("decorator", "outer, inner, edge?", ShorthandType::RecursiveCommaSeparated); } -DecoratorNinePatchInstancer::~DecoratorNinePatchInstancer() -{ -} +DecoratorNinePatchInstancer::~DecoratorNinePatchInstancer() {} -SharedPtr DecoratorNinePatchInstancer::InstanceDecorator(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) +SharedPtr DecoratorNinePatchInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) { - RMLUI_UNUSED(name); - bool edges_set = false; - Array edges; + Array edges; for (int i = 0; i < 4; i++) { edges[i] = *properties.GetProperty(edge_ids[i]); @@ -225,7 +216,7 @@ SharedPtr DecoratorNinePatchInstancer::InstanceDecorator(const String const Sprite* sprite_inner = nullptr; { - const String sprite_name = properties.GetProperty(sprite_outer_id)->Get< String >(); + const String sprite_name = properties.GetProperty(sprite_outer_id)->Get(); sprite_outer = instancer_interface.GetSprite(sprite_name); if (!sprite_outer) { @@ -234,7 +225,7 @@ SharedPtr DecoratorNinePatchInstancer::InstanceDecorator(const String } } { - const String sprite_name = properties.GetProperty(sprite_inner_id)->Get< String >(); + const String sprite_name = properties.GetProperty(sprite_inner_id)->Get(); sprite_inner = instancer_interface.GetSprite(sprite_name); if (!sprite_inner) { @@ -251,8 +242,8 @@ SharedPtr DecoratorNinePatchInstancer::InstanceDecorator(const String auto decorator = MakeShared(); - if (!decorator->Initialise(sprite_outer->rectangle, sprite_inner->rectangle, (edges_set ? &edges : nullptr), - sprite_outer->sprite_sheet->texture, sprite_outer->sprite_sheet->display_scale)) + if (!decorator->Initialise(sprite_outer->rectangle, sprite_inner->rectangle, (edges_set ? &edges : nullptr), sprite_outer->sprite_sheet->texture, + sprite_outer->sprite_sheet->display_scale)) { return nullptr; } diff --git a/Source/Core/DecoratorNinePatch.h b/Source/Core/DecoratorNinePatch.h index 55151c233..ad42ea207 100644 --- a/Source/Core/DecoratorNinePatch.h +++ b/Source/Core/DecoratorNinePatch.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,13 @@ namespace Rml { -class DecoratorNinePatch : public Decorator -{ +class DecoratorNinePatch : public Decorator { public: DecoratorNinePatch(); virtual ~DecoratorNinePatch(); - bool Initialise(const Rectanglef& rect_outer, const Rectanglef& rect_inner, const Array* _edges, const Texture& texture, float display_scale); + bool Initialise(const Rectanglef& rect_outer, const Rectanglef& rect_inner, const Array* _edges, const Texture& texture, + float display_scale); DecoratorDataHandle GenerateElementData(Element* element) const override; void ReleaseElementData(DecoratorDataHandle element_data) const override; @@ -52,23 +52,20 @@ class DecoratorNinePatch : public Decorator private: Rectanglef rect_outer, rect_inner; float display_scale = 1; - UniquePtr> edges; + UniquePtr> edges; }; - - -class DecoratorNinePatchInstancer : public DecoratorInstancer -{ +class DecoratorNinePatchInstancer : public DecoratorInstancer { public: DecoratorNinePatchInstancer(); ~DecoratorNinePatchInstancer(); - SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) override; + SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) override; private: PropertyId sprite_outer_id, sprite_inner_id; PropertyId edge_ids[4]; - }; } // namespace Rml diff --git a/Source/Core/DecoratorTiled.cpp b/Source/Core/DecoratorTiled.cpp index 498cf3a8b..0edfc9759 100644 --- a/Source/Core/DecoratorTiled.cpp +++ b/Source/Core/DecoratorTiled.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,26 +29,21 @@ #include "DecoratorTiled.h" #include "../../Include/RmlUi/Core/Element.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" -#include "../../Include/RmlUi/Core/Math.h" #include "../../Include/RmlUi/Core/GeometryUtilities.h" -#include "../../Include/RmlUi/Core/ElementUtilities.h" +#include "../../Include/RmlUi/Core/Math.h" #include namespace Rml { -DecoratorTiled::DecoratorTiled() -{ -} +DecoratorTiled::DecoratorTiled() {} -DecoratorTiled::~DecoratorTiled() -{ -} +DecoratorTiled::~DecoratorTiled() {} static const Vector2f oriented_texcoords[4][2] = { - {Vector2f(0, 0), Vector2f(1, 1)}, // ORIENTATION_NONE - {Vector2f(1, 0), Vector2f(0, 1)}, // FLIP_HORIZONTAL - {Vector2f(0, 1), Vector2f(1, 0)}, // FLIP_VERTICAL - {Vector2f(1, 1), Vector2f(0, 0)} // ROTATE_180 + {Vector2f(0, 0), Vector2f(1, 1)}, // ORIENTATION_NONE + {Vector2f(1, 0), Vector2f(0, 1)}, // FLIP_HORIZONTAL + {Vector2f(0, 1), Vector2f(1, 0)}, // FLIP_VERTICAL + {Vector2f(1, 1), Vector2f(0, 0)} // ROTATE_180 }; DecoratorTiled::Tile::Tile() : display_scale(1), position(0, 0), size(0, 0) @@ -58,8 +53,6 @@ DecoratorTiled::Tile::Tile() : display_scale(1), position(0, 0), size(0, 0) orientation = ORIENTATION_NONE; } - -// Calculates the tile's dimensions from the texture and texture coordinates. void DecoratorTiled::Tile::CalculateDimensions(Element* element, const Texture& texture) const { RenderInterface* render_interface = element->GetRenderInterface(); @@ -82,7 +75,7 @@ void DecoratorTiled::Tile::CalculateDimensions(Element* element, const Texture& new_data.size = texture_dimensions; else new_data.size = size; - + const Vector2f size_relative = new_data.size / texture_dimensions; new_data.size = Vector2f(Math::AbsoluteValue(new_data.size.x), Math::AbsoluteValue(new_data.size.y)); @@ -91,11 +84,10 @@ void DecoratorTiled::Tile::CalculateDimensions(Element* element, const Texture& new_data.texcoords[1] = size_relative + new_data.texcoords[0]; } - data.emplace( render_interface, new_data ); + data.emplace(render_interface, new_data); } } -// Get this tile's dimensions. Vector2f DecoratorTiled::Tile::GetNaturalDimensions(Element* element) const { RenderInterface* render_interface = element->GetRenderInterface(); @@ -109,8 +101,8 @@ Vector2f DecoratorTiled::Tile::GetNaturalDimensions(Element* element) const return raw_dimensions * scale_raw_to_natural_dimensions; } -// Generates geometry to render this tile across a surface. -void DecoratorTiled::Tile::GenerateGeometry(Vector< Vertex >& vertices, Vector< int >& indices, Element* element, const Vector2f surface_origin, const Vector2f surface_dimensions, const Vector2f tile_dimensions) const +void DecoratorTiled::Tile::GenerateGeometry(Vector& vertices, Vector& indices, Element* element, const Vector2f surface_origin, + const Vector2f surface_dimensions, const Vector2f tile_dimensions) const { if (surface_dimensions.x <= 0 || surface_dimensions.y <= 0) return; @@ -121,8 +113,8 @@ void DecoratorTiled::Tile::GenerateGeometry(Vector< Vertex >& vertices, Vector< float opacity = computed.opacity(); Colourb quad_colour = computed.image_color(); - // Apply opacity - quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha); + // Apply opacity + quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha); auto data_iterator = data.find(render_interface); if (data_iterator == data.end()) @@ -168,7 +160,7 @@ void DecoratorTiled::Tile::GenerateGeometry(Vector< Vertex >& vertices, Vector< case SCALE_NONE: { final_tile_dimensions = tile_dimensions; - + offset_and_clip_tile = true; } break; @@ -186,29 +178,31 @@ void DecoratorTiled::Tile::GenerateGeometry(Vector< Vertex >& vertices, Vector< break; } - Vector2f tile_offset(0, 0); if (offset_and_clip_tile) { // Offset tile along each dimension. - for(int i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - switch (align[i].type) { - case Style::LengthPercentage::Length: tile_offset[i] = align[i].value; break; - case Style::LengthPercentage::Percentage: tile_offset[i] = (surface_dimensions[i] - final_tile_dimensions[i]) * align[i].value * 0.01f; break; + switch (align[i].type) + { + case Style::LengthPercentage::Length: tile_offset[i] = align[i].value; break; + case Style::LengthPercentage::Percentage: + tile_offset[i] = (surface_dimensions[i] - final_tile_dimensions[i]) * align[i].value * 0.01f; + break; } } tile_offset = tile_offset.Round(); // Clip tile. See if our tile extends outside the boundary at either side, along each dimension. - for(int i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { // Left/right acts as top/bottom during the second iteration. float overshoot_left = std::max(-tile_offset[i], 0.0f); float overshoot_right = std::max(tile_offset[i] + final_tile_dimensions[i] - surface_dimensions[i], 0.0f); - if(overshoot_left > 0.f || overshoot_right > 0.f) + if (overshoot_left > 0.f || overshoot_right > 0.f) { float& left = scaled_texcoords[0][i]; float& right = scaled_texcoords[1][i]; @@ -223,9 +217,8 @@ void DecoratorTiled::Tile::GenerateGeometry(Vector< Vertex >& vertices, Vector< } } - // Resize the vertex and index arrays to fit the new geometry. - int index_offset = (int) vertices.size(); + int index_offset = (int)vertices.size(); vertices.resize(vertices.size() + 4); Vertex* new_vertices = &vertices[0] + index_offset; @@ -238,10 +231,10 @@ void DecoratorTiled::Tile::GenerateGeometry(Vector< Vertex >& vertices, Vector< Math::SnapToPixelGrid(tile_position, final_tile_dimensions); - GeometryUtilities::GenerateQuad(new_vertices, new_indices, tile_position, final_tile_dimensions, quad_colour, scaled_texcoords[0], scaled_texcoords[1], index_offset); + GeometryUtilities::GenerateQuad(new_vertices, new_indices, tile_position, final_tile_dimensions, quad_colour, scaled_texcoords[0], + scaled_texcoords[1], index_offset); } -// Scales a tile dimensions by a fixed value along one axis. void DecoratorTiled::ScaleTileDimensions(Vector2f& tile_dimensions, float axis_value, Axis axis_enum) const { int axis = static_cast(axis_enum); diff --git a/Source/Core/DecoratorTiled.h b/Source/Core/DecoratorTiled.h index f9b693886..399b1548f 100644 --- a/Source/Core/DecoratorTiled.h +++ b/Source/Core/DecoratorTiled.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,32 +38,29 @@ namespace Rml { struct Texture; /** - Base class for tiled decorators. + Base class for tiled decorators. - @author Peter Curry + @author Peter Curry */ -class DecoratorTiled : public Decorator -{ +class DecoratorTiled : public Decorator { public: DecoratorTiled(); virtual ~DecoratorTiled(); /** - Stores the orientation of a tile. + Stores the orientation of a tile. */ - enum TileOrientation - { - ORIENTATION_NONE, // No orientation. - FLIP_HORIZONTAL, // Flipped horizontally. - FLIP_VERTICAL, // Flipped vertically. - ROTATE_180, // Rotated 180 degrees clockwise. + enum TileOrientation { + ORIENTATION_NONE, // No orientation. + FLIP_HORIZONTAL, // Flipped horizontally. + FLIP_VERTICAL, // Flipped vertically. + ROTATE_180, // Rotated 180 degrees clockwise. }; /** - Stores the fit mode of a tile. + Stores the fit mode of a tile. */ - enum TileFitMode - { + enum TileFitMode { FILL, // Tile is stretched to boundaries. CONTAIN, // Tile is stretched to boundaries, keeping aspect ratio fixed, 'letter-boxed'. COVER, // Tile is stretched to cover the boundaries, keeping aspect ratio fixed. @@ -72,13 +69,12 @@ class DecoratorTiled : public Decorator }; /** - Structure for storing the different tiles the tiled decorator uses internally over its - surface. + Structure for storing the different tiles the tiled decorator uses internally over its + surface. - @author Peter Curry + @author Peter Curry */ - struct Tile - { + struct Tile { /// Constructs the tile with safe default values. Tile(); @@ -95,15 +91,15 @@ class DecoratorTiled : public Decorator /// @param[in] surface_origin The starting point of the first tile to generate. /// @param[in] surface_dimensions The dimensions of the surface to be tiled. /// @param[in] tile_dimensions The dimensions to render this tile at. - void GenerateGeometry(Vector< Vertex >& vertices, Vector< int >& indices, Element* element, Vector2f surface_origin, Vector2f surface_dimensions, Vector2f tile_dimensions) const; + void GenerateGeometry(Vector& vertices, Vector& indices, Element* element, Vector2f surface_origin, Vector2f surface_dimensions, + Vector2f tile_dimensions) const; - struct TileData - { - Vector2f size; // 'px' units + struct TileData { + Vector2f size; // 'px' units Vector2f texcoords[2]; // relative units }; - using TileDataMap = SmallUnorderedMap< RenderInterface*, TileData >; + using TileDataMap = SmallUnorderedMap; int texture_index; @@ -118,8 +114,7 @@ class DecoratorTiled : public Decorator TileOrientation orientation; TileFitMode fit_mode; - Style::LengthPercentage align[2]; - + Style::LengthPercentage align[2]; }; protected: diff --git a/Source/Core/DecoratorTiledBox.cpp b/Source/Core/DecoratorTiledBox.cpp index 331488d0f..17560eb80 100644 --- a/Source/Core/DecoratorTiledBox.cpp +++ b/Source/Core/DecoratorTiledBox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,8 +32,7 @@ namespace Rml { -struct DecoratorTiledBoxData -{ +struct DecoratorTiledBoxData { DecoratorTiledBoxData(Element* host_element, int num_textures) : num_textures(num_textures) { geometry = new Geometry[num_textures]; @@ -41,24 +40,16 @@ struct DecoratorTiledBoxData geometry[i].SetHostElement(host_element); } - ~DecoratorTiledBoxData() - { - delete[] geometry; - } + ~DecoratorTiledBoxData() { delete[] geometry; } const int num_textures; Geometry* geometry; }; -DecoratorTiledBox::DecoratorTiledBox() -{ -} +DecoratorTiledBox::DecoratorTiledBox() {} -DecoratorTiledBox::~DecoratorTiledBox() -{ -} +DecoratorTiledBox::~DecoratorTiledBox() {} -// Initialises the tiles for the decorator. bool DecoratorTiledBox::Initialise(const Tile* _tiles, const Texture* _textures) { // Load the textures. @@ -109,7 +100,6 @@ bool DecoratorTiledBox::Initialise(const Tile* _tiles, const Texture* _textures) return true; } -// Called on a decorator to generate any required per-element data for a newly decorated element. DecoratorDataHandle DecoratorTiledBox::GenerateElementData(Element* element) const { // Initialise the tiles for this element. @@ -121,7 +111,6 @@ DecoratorDataHandle DecoratorTiledBox::GenerateElementData(Element* element) con Vector2f padded_size = element->GetBox().GetSize(Box::PADDING); - // Calculate the natural dimensions of tile corners and edges. const Vector2f natural_top_left = tiles[TOP_LEFT_CORNER].GetNaturalDimensions(element); const Vector2f natural_top = tiles[TOP_EDGE].GetNaturalDimensions(element); @@ -142,7 +131,7 @@ DecoratorDataHandle DecoratorTiledBox::GenerateElementData(Element* element) con Vector2f bottom_left = natural_bottom_left; Vector2f bottom = natural_bottom; Vector2f bottom_right = natural_bottom_right; - + Vector2f left = natural_left; Vector2f right = natural_right; @@ -211,75 +200,44 @@ DecoratorDataHandle DecoratorTiledBox::GenerateElementData(Element* element) con // Generate the geometry for the top-left tile. tiles[TOP_LEFT_CORNER].GenerateGeometry(data->geometry[tiles[TOP_LEFT_CORNER].texture_index].GetVertices(), - data->geometry[tiles[TOP_LEFT_CORNER].texture_index].GetIndices(), - element, - Vector2f(0, 0), - top_left, - top_left); + data->geometry[tiles[TOP_LEFT_CORNER].texture_index].GetIndices(), element, Vector2f(0, 0), top_left, top_left); // Generate the geometry for the top edge tiles. tiles[TOP_EDGE].GenerateGeometry(data->geometry[tiles[TOP_EDGE].texture_index].GetVertices(), - data->geometry[tiles[TOP_EDGE].texture_index].GetIndices(), - element, - Vector2f(top_left.x, 0), - Vector2f(padded_size.x - (top_left.x + top_right.x), top.y), - top); + data->geometry[tiles[TOP_EDGE].texture_index].GetIndices(), element, Vector2f(top_left.x, 0), + Vector2f(padded_size.x - (top_left.x + top_right.x), top.y), top); // Generate the geometry for the top-right tile. tiles[TOP_RIGHT_CORNER].GenerateGeometry(data->geometry[tiles[TOP_RIGHT_CORNER].texture_index].GetVertices(), - data->geometry[tiles[TOP_RIGHT_CORNER].texture_index].GetIndices(), - element, - Vector2f(padded_size.x - top_right.x, 0), - top_right, - top_right); + data->geometry[tiles[TOP_RIGHT_CORNER].texture_index].GetIndices(), element, Vector2f(padded_size.x - top_right.x, 0), top_right, top_right); // Generate the geometry for the left side. tiles[LEFT_EDGE].GenerateGeometry(data->geometry[tiles[LEFT_EDGE].texture_index].GetVertices(), - data->geometry[tiles[LEFT_EDGE].texture_index].GetIndices(), - element, - Vector2f(0, top_left.y), - Vector2f(left.x, padded_size.y - (top_left.y + bottom_left.y)), - left); + data->geometry[tiles[LEFT_EDGE].texture_index].GetIndices(), element, Vector2f(0, top_left.y), + Vector2f(left.x, padded_size.y - (top_left.y + bottom_left.y)), left); // Generate the geometry for the right side. tiles[RIGHT_EDGE].GenerateGeometry(data->geometry[tiles[RIGHT_EDGE].texture_index].GetVertices(), - data->geometry[tiles[RIGHT_EDGE].texture_index].GetIndices(), - element, - Vector2f((padded_size.x - right.x), top_right.y), - Vector2f(right.x, padded_size.y - (top_right.y + bottom_right.y)), - right); + data->geometry[tiles[RIGHT_EDGE].texture_index].GetIndices(), element, Vector2f((padded_size.x - right.x), top_right.y), + Vector2f(right.x, padded_size.y - (top_right.y + bottom_right.y)), right); // Generate the geometry for the bottom-left tile. tiles[BOTTOM_LEFT_CORNER].GenerateGeometry(data->geometry[tiles[BOTTOM_LEFT_CORNER].texture_index].GetVertices(), - data->geometry[tiles[BOTTOM_LEFT_CORNER].texture_index].GetIndices(), - element, - Vector2f(0, padded_size.y - bottom_left.y), - bottom_left, - bottom_left); + data->geometry[tiles[BOTTOM_LEFT_CORNER].texture_index].GetIndices(), element, Vector2f(0, padded_size.y - bottom_left.y), bottom_left, + bottom_left); // Generate the geometry for the bottom edge tiles. tiles[BOTTOM_EDGE].GenerateGeometry(data->geometry[tiles[BOTTOM_EDGE].texture_index].GetVertices(), - data->geometry[tiles[BOTTOM_EDGE].texture_index].GetIndices(), - element, - Vector2f(bottom_left.x, padded_size.y - bottom.y), - Vector2f(padded_size.x - (bottom_left.x + bottom_right.x), bottom.y), - bottom); + data->geometry[tiles[BOTTOM_EDGE].texture_index].GetIndices(), element, Vector2f(bottom_left.x, padded_size.y - bottom.y), + Vector2f(padded_size.x - (bottom_left.x + bottom_right.x), bottom.y), bottom); // Generate the geometry for the bottom-right tile. tiles[BOTTOM_RIGHT_CORNER].GenerateGeometry(data->geometry[tiles[BOTTOM_RIGHT_CORNER].texture_index].GetVertices(), - data->geometry[tiles[BOTTOM_RIGHT_CORNER].texture_index].GetIndices(), - element, - Vector2f(padded_size.x - bottom_right.x, padded_size.y - bottom_right.y), - bottom_right, - bottom_right); + data->geometry[tiles[BOTTOM_RIGHT_CORNER].texture_index].GetIndices(), element, + Vector2f(padded_size.x - bottom_right.x, padded_size.y - bottom_right.y), bottom_right, bottom_right); // Generate the centre geometry. Vector2f centre_dimensions = tiles[CENTRE].GetNaturalDimensions(element); - Vector2f centre_surface_dimensions(padded_size.x - (left.x + right.x), - padded_size.y - (top.y + bottom.y)); + Vector2f centre_surface_dimensions(padded_size.x - (left.x + right.x), padded_size.y - (top.y + bottom.y)); tiles[CENTRE].GenerateGeometry(data->geometry[tiles[CENTRE].texture_index].GetVertices(), - data->geometry[tiles[CENTRE].texture_index].GetIndices(), - element, - Vector2f(left.x, top.y), - centre_surface_dimensions, - centre_dimensions); + data->geometry[tiles[CENTRE].texture_index].GetIndices(), element, Vector2f(left.x, top.y), centre_surface_dimensions, centre_dimensions); // Set the textures on the geometry. const Texture* texture = nullptr; @@ -290,17 +248,15 @@ DecoratorDataHandle DecoratorTiledBox::GenerateElementData(Element* element) con return reinterpret_cast(data); } -// Called to release element data generated by this decorator. void DecoratorTiledBox::ReleaseElementData(DecoratorDataHandle element_data) const { - delete reinterpret_cast< DecoratorTiledBoxData* >(element_data); + delete reinterpret_cast(element_data); } -// Called to render the decorator on an element. void DecoratorTiledBox::RenderElement(Element* element, DecoratorDataHandle element_data) const { Vector2f translation = element->GetAbsoluteOffset(Box::PADDING).Round(); - DecoratorTiledBoxData* data = reinterpret_cast< DecoratorTiledBoxData* >(element_data); + DecoratorTiledBoxData* data = reinterpret_cast(element_data); for (int i = 0; i < data->num_textures; i++) data->geometry[i].Render(translation); diff --git a/Source/Core/DecoratorTiledBox.h b/Source/Core/DecoratorTiledBox.h index d4cfb95cb..1a7f2443c 100644 --- a/Source/Core/DecoratorTiledBox.h +++ b/Source/Core/DecoratorTiledBox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledBox : public DecoratorTiled -{ +class DecoratorTiledBox : public DecoratorTiled { public: DecoratorTiledBox(); virtual ~DecoratorTiledBox(); @@ -58,8 +57,7 @@ class DecoratorTiledBox : public DecoratorTiled void RenderElement(Element* element, DecoratorDataHandle element_data) const override; private: - enum - { + enum { TOP_LEFT_CORNER = 0, TOP_RIGHT_CORNER = 1, BOTTOM_LEFT_CORNER = 2, diff --git a/Source/Core/DecoratorTiledBoxInstancer.cpp b/Source/Core/DecoratorTiledBoxInstancer.cpp index 4e9a23d3b..92a88dfdb 100644 --- a/Source/Core/DecoratorTiledBoxInstancer.cpp +++ b/Source/Core/DecoratorTiledBoxInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -45,18 +45,16 @@ DecoratorTiledBoxInstancer::DecoratorTiledBoxInstancer() : DecoratorTiledInstanc RegisterTileProperty("center-image"); - RegisterShorthand("decorator", "top-left-image, top-image, top-right-image, left-image, center-image, right-image, bottom-left-image, bottom-image, bottom-right-image", ShorthandType::RecursiveCommaSeparated); + RegisterShorthand("decorator", + "top-left-image, top-image, top-right-image, left-image, center-image, right-image, bottom-left-image, bottom-image, bottom-right-image", + ShorthandType::RecursiveCommaSeparated); } -DecoratorTiledBoxInstancer::~DecoratorTiledBoxInstancer() -{ -} +DecoratorTiledBoxInstancer::~DecoratorTiledBoxInstancer() {} -// Instances a box decorator. -SharedPtrDecoratorTiledBoxInstancer::InstanceDecorator(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) +SharedPtr DecoratorTiledBoxInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) { - RMLUI_UNUSED(name); - constexpr size_t num_tiles = 9; DecoratorTiled::Tile tiles[num_tiles]; diff --git a/Source/Core/DecoratorTiledBoxInstancer.h b/Source/Core/DecoratorTiledBoxInstancer.h index a5734bfc4..d377660b4 100644 --- a/Source/Core/DecoratorTiledBoxInstancer.h +++ b/Source/Core/DecoratorTiledBoxInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,17 +34,17 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledBoxInstancer : public DecoratorTiledInstancer -{ +class DecoratorTiledBoxInstancer : public DecoratorTiledInstancer { public: DecoratorTiledBoxInstancer(); ~DecoratorTiledBoxInstancer(); /// Instances a box decorator. - SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) override; + SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) override; }; } // namespace Rml diff --git a/Source/Core/DecoratorTiledHorizontal.cpp b/Source/Core/DecoratorTiledHorizontal.cpp index cf30bcde2..189321346 100644 --- a/Source/Core/DecoratorTiledHorizontal.cpp +++ b/Source/Core/DecoratorTiledHorizontal.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,8 +33,7 @@ namespace Rml { -struct DecoratorTiledHorizontalData -{ +struct DecoratorTiledHorizontalData { DecoratorTiledHorizontalData(Element* host_element, int num_textures) : num_textures(num_textures) { geometry = new Geometry[num_textures]; @@ -42,24 +41,16 @@ struct DecoratorTiledHorizontalData geometry[i].SetHostElement(host_element); } - ~DecoratorTiledHorizontalData() - { - delete[] geometry; - } + ~DecoratorTiledHorizontalData() { delete[] geometry; } const int num_textures; Geometry* geometry; }; -DecoratorTiledHorizontal::DecoratorTiledHorizontal() -{ -} +DecoratorTiledHorizontal::DecoratorTiledHorizontal() {} -DecoratorTiledHorizontal::~DecoratorTiledHorizontal() -{ -} +DecoratorTiledHorizontal::~DecoratorTiledHorizontal() {} -// Initialises the tiles for the decorator. bool DecoratorTiledHorizontal::Initialise(const Tile* _tiles, const Texture* _textures) { // Load the textures. @@ -89,7 +80,6 @@ bool DecoratorTiledHorizontal::Initialise(const Tile* _tiles, const Texture* _te return true; } -// Called on a decorator to generate any required per-element data for a newly decorated element. DecoratorDataHandle DecoratorTiledHorizontal::GenerateElementData(Element* element) const { // Initialise the tiles for this element. @@ -123,11 +113,15 @@ DecoratorDataHandle DecoratorTiledHorizontal::GenerateElementData(Element* eleme } // Generate the geometry for the left tile. - tiles[LEFT].GenerateGeometry(data->geometry[tiles[LEFT].texture_index].GetVertices(), data->geometry[tiles[LEFT].texture_index].GetIndices(), element, Vector2f(0, 0), left_dimensions, left_dimensions); + tiles[LEFT].GenerateGeometry(data->geometry[tiles[LEFT].texture_index].GetVertices(), data->geometry[tiles[LEFT].texture_index].GetIndices(), + element, Vector2f(0, 0), left_dimensions, left_dimensions); // Generate the geometry for the centre tiles. - tiles[CENTRE].GenerateGeometry(data->geometry[tiles[CENTRE].texture_index].GetVertices(), data->geometry[tiles[CENTRE].texture_index].GetIndices(), element, Vector2f(left_dimensions.x, 0), Vector2f(padded_size.x - (left_dimensions.x + right_dimensions.x), centre_dimensions.y), centre_dimensions); + tiles[CENTRE].GenerateGeometry(data->geometry[tiles[CENTRE].texture_index].GetVertices(), + data->geometry[tiles[CENTRE].texture_index].GetIndices(), element, Vector2f(left_dimensions.x, 0), + Vector2f(padded_size.x - (left_dimensions.x + right_dimensions.x), centre_dimensions.y), centre_dimensions); // Generate the geometry for the right tile. - tiles[RIGHT].GenerateGeometry(data->geometry[tiles[RIGHT].texture_index].GetVertices(), data->geometry[tiles[RIGHT].texture_index].GetIndices(), element, Vector2f(padded_size.x - right_dimensions.x, 0), right_dimensions, right_dimensions); + tiles[RIGHT].GenerateGeometry(data->geometry[tiles[RIGHT].texture_index].GetVertices(), data->geometry[tiles[RIGHT].texture_index].GetIndices(), + element, Vector2f(padded_size.x - right_dimensions.x, 0), right_dimensions, right_dimensions); // Set the textures on the geometry. const Texture* texture = nullptr; @@ -138,17 +132,15 @@ DecoratorDataHandle DecoratorTiledHorizontal::GenerateElementData(Element* eleme return reinterpret_cast(data); } -// Called to release element data generated by this decorator. void DecoratorTiledHorizontal::ReleaseElementData(DecoratorDataHandle element_data) const { - delete reinterpret_cast< DecoratorTiledHorizontalData* >(element_data); + delete reinterpret_cast(element_data); } -// Called to render the decorator on an element. void DecoratorTiledHorizontal::RenderElement(Element* element, DecoratorDataHandle element_data) const { Vector2f translation = element->GetAbsoluteOffset(Box::PADDING).Round(); - DecoratorTiledHorizontalData* data = reinterpret_cast< DecoratorTiledHorizontalData* >(element_data); + DecoratorTiledHorizontalData* data = reinterpret_cast(element_data); for (int i = 0; i < data->num_textures; i++) data->geometry[i].Render(translation); diff --git a/Source/Core/DecoratorTiledHorizontal.h b/Source/Core/DecoratorTiledHorizontal.h index b70f1dc69..b236b1863 100644 --- a/Source/Core/DecoratorTiledHorizontal.h +++ b/Source/Core/DecoratorTiledHorizontal.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledHorizontal : public DecoratorTiled -{ +class DecoratorTiledHorizontal : public DecoratorTiled { public: DecoratorTiledHorizontal(); virtual ~DecoratorTiledHorizontal(); @@ -58,12 +57,7 @@ class DecoratorTiledHorizontal : public DecoratorTiled void RenderElement(Element* element, DecoratorDataHandle element_data) const override; private: - enum - { - LEFT = 0, - RIGHT = 1, - CENTRE = 2 - }; + enum { LEFT = 0, RIGHT = 1, CENTRE = 2 }; Tile tiles[3]; }; diff --git a/Source/Core/DecoratorTiledHorizontalInstancer.cpp b/Source/Core/DecoratorTiledHorizontalInstancer.cpp index bc17a33c4..69db9fea5 100644 --- a/Source/Core/DecoratorTiledHorizontalInstancer.cpp +++ b/Source/Core/DecoratorTiledHorizontalInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,14 +39,11 @@ DecoratorTiledHorizontalInstancer::DecoratorTiledHorizontalInstancer() : Decorat RegisterShorthand("decorator", "left-image, center-image, right-image", ShorthandType::RecursiveCommaSeparated); } -DecoratorTiledHorizontalInstancer::~DecoratorTiledHorizontalInstancer() -{ -} +DecoratorTiledHorizontalInstancer::~DecoratorTiledHorizontalInstancer() {} -SharedPtr DecoratorTiledHorizontalInstancer::InstanceDecorator(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) +SharedPtr DecoratorTiledHorizontalInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) { - RMLUI_UNUSED(name); - constexpr size_t num_tiles = 3; DecoratorTiled::Tile tiles[num_tiles]; @@ -62,5 +59,4 @@ SharedPtr DecoratorTiledHorizontalInstancer::InstanceDecorator(const return decorator; } - } // namespace Rml diff --git a/Source/Core/DecoratorTiledHorizontalInstancer.h b/Source/Core/DecoratorTiledHorizontalInstancer.h index 7a3d6adce..77c6549fe 100644 --- a/Source/Core/DecoratorTiledHorizontalInstancer.h +++ b/Source/Core/DecoratorTiledHorizontalInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,17 +34,17 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledHorizontalInstancer : public DecoratorTiledInstancer -{ +class DecoratorTiledHorizontalInstancer : public DecoratorTiledInstancer { public: DecoratorTiledHorizontalInstancer(); ~DecoratorTiledHorizontalInstancer(); /// Instances a horizontal decorator. - SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) override; + SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) override; }; } // namespace Rml diff --git a/Source/Core/DecoratorTiledImage.cpp b/Source/Core/DecoratorTiledImage.cpp index e7082b67f..f8631c618 100644 --- a/Source/Core/DecoratorTiledImage.cpp +++ b/Source/Core/DecoratorTiledImage.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,13 +33,9 @@ namespace Rml { -DecoratorTiledImage::DecoratorTiledImage() -{ -} +DecoratorTiledImage::DecoratorTiledImage() {} -DecoratorTiledImage::~DecoratorTiledImage() -{ -} +DecoratorTiledImage::~DecoratorTiledImage() {} bool DecoratorTiledImage::Initialise(const Tile& _tile, const Texture& _texture) { @@ -48,7 +44,6 @@ bool DecoratorTiledImage::Initialise(const Tile& _tile, const Texture& _texture) return (tile.texture_index >= 0); } -// Called on a decorator to generate any required per-element data for a newly decorated element. DecoratorDataHandle DecoratorTiledImage::GenerateElementData(Element* element) const { // Calculate the tile's dimensions for this element. @@ -58,21 +53,20 @@ DecoratorDataHandle DecoratorTiledImage::GenerateElementData(Element* element) c data->SetTexture(GetTexture()); // Generate the geometry for the tile. - tile.GenerateGeometry(data->GetVertices(), data->GetIndices(), element, Vector2f(0, 0), element->GetBox().GetSize(Box::PADDING), tile.GetNaturalDimensions(element)); + tile.GenerateGeometry(data->GetVertices(), data->GetIndices(), element, Vector2f(0, 0), element->GetBox().GetSize(Box::PADDING), + tile.GetNaturalDimensions(element)); return reinterpret_cast(data); } -// Called to release element data generated by this decorator. void DecoratorTiledImage::ReleaseElementData(DecoratorDataHandle element_data) const { - delete reinterpret_cast< Geometry* >(element_data); + delete reinterpret_cast(element_data); } -// Called to render the decorator on an element. void DecoratorTiledImage::RenderElement(Element* element, DecoratorDataHandle element_data) const { - Geometry* data = reinterpret_cast< Geometry* >(element_data); + Geometry* data = reinterpret_cast(element_data); data->Render(element->GetAbsoluteOffset(Box::PADDING).Round()); } diff --git a/Source/Core/DecoratorTiledImage.h b/Source/Core/DecoratorTiledImage.h index d369c58b7..b912fe770 100644 --- a/Source/Core/DecoratorTiledImage.h +++ b/Source/Core/DecoratorTiledImage.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledImage : public DecoratorTiled -{ +class DecoratorTiledImage : public DecoratorTiled { public: DecoratorTiledImage(); virtual ~DecoratorTiledImage(); diff --git a/Source/Core/DecoratorTiledImageInstancer.cpp b/Source/Core/DecoratorTiledImageInstancer.cpp index 5983bcb17..7fd95cc88 100644 --- a/Source/Core/DecoratorTiledImageInstancer.cpp +++ b/Source/Core/DecoratorTiledImageInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,21 +37,17 @@ DecoratorTiledImageInstancer::DecoratorTiledImageInstancer() : DecoratorTiledIns RegisterShorthand("decorator", "image", ShorthandType::RecursiveRepeat); } -DecoratorTiledImageInstancer::~DecoratorTiledImageInstancer() -{ -} - +DecoratorTiledImageInstancer::~DecoratorTiledImageInstancer() {} -SharedPtr DecoratorTiledImageInstancer::InstanceDecorator(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) +SharedPtr DecoratorTiledImageInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) { - RMLUI_UNUSED(name); - DecoratorTiled::Tile tile; Texture texture; if (!GetTileProperties(&tile, &texture, 1, properties, instancer_interface)) return nullptr; - + auto decorator = MakeShared(); if (!decorator->Initialise(tile, texture)) diff --git a/Source/Core/DecoratorTiledImageInstancer.h b/Source/Core/DecoratorTiledImageInstancer.h index 2b0b6c5b8..433c37d7b 100644 --- a/Source/Core/DecoratorTiledImageInstancer.h +++ b/Source/Core/DecoratorTiledImageInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,17 +34,17 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledImageInstancer : public DecoratorTiledInstancer -{ +class DecoratorTiledImageInstancer : public DecoratorTiledInstancer { public: DecoratorTiledImageInstancer(); ~DecoratorTiledImageInstancer(); /// Instances an image decorator. - SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) override; + SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) override; }; } // namespace Rml diff --git a/Source/Core/DecoratorTiledInstancer.cpp b/Source/Core/DecoratorTiledInstancer.cpp index 209bfb6c5..227e90de4 100644 --- a/Source/Core/DecoratorTiledInstancer.cpp +++ b/Source/Core/DecoratorTiledInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,7 +37,6 @@ DecoratorTiledInstancer::DecoratorTiledInstancer(size_t num_tiles) tile_property_ids.reserve(num_tiles); } -// Adds the property declarations for a tile. void DecoratorTiledInstancer::RegisterTileProperty(const String& name, bool register_fit_modes) { TilePropertyIds ids = {}; @@ -49,51 +48,43 @@ void DecoratorTiledInstancer::RegisterTileProperty(const String& name, bool regi if (register_fit_modes) { String fit_name = CreateString(32, "%s-fit", name.c_str()); - ids.fit = RegisterProperty(fit_name, "fill") - .AddParser("keyword", "fill, contain, cover, scale-none, scale-down") - .GetId(); + ids.fit = RegisterProperty(fit_name, "fill").AddParser("keyword", "fill, contain, cover, scale-none, scale-down").GetId(); String align_x_name = CreateString(32, "%s-align-x", name.c_str()); - ids.align_x = RegisterProperty(align_x_name, "center") - .AddParser("keyword", "left, center, right") - .AddParser("length_percent") - .GetId(); + ids.align_x = RegisterProperty(align_x_name, "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId(); String align_y_name = CreateString(32, "%s-align-y", name.c_str()); - ids.align_y = RegisterProperty(align_y_name, "center") - .AddParser("keyword", "top, center, bottom") - .AddParser("length_percent") - .GetId(); + ids.align_y = RegisterProperty(align_y_name, "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId(); additional_modes += ", " + fit_name + ", " + align_x_name + ", " + align_y_name; } ids.orientation = RegisterProperty(CreateString(32, "%s-orientation", name.c_str()), "none") - .AddParser("keyword", "none, flip-horizontal, flip-vertical, rotate-180") - .GetId(); + .AddParser("keyword", "none, flip-horizontal, flip-vertical, rotate-180") + .GetId(); - RegisterShorthand(name, CreateString(256, ("%s-src, %s-orientation" + additional_modes).c_str(), - name.c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str()), + RegisterShorthand(name, + CreateString(256, ("%s-src, %s-orientation" + additional_modes).c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(), + name.c_str()), ShorthandType::FallThrough); tile_property_ids.push_back(ids); } - -// Retrieves all the properties for a tile from the property dictionary. -bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) const +bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures, + const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) const { RMLUI_ASSERT(num_tiles_and_textures == tile_property_ids.size()); String previous_texture_name; Texture previous_texture; - for(size_t i = 0; i < num_tiles_and_textures; i++) + for (size_t i = 0; i < num_tiles_and_textures; i++) { const TilePropertyIds& ids = tile_property_ids[i]; const Property* src_property = properties.GetProperty(ids.src); - const String texture_name = src_property->Get< String >(); + const String texture_name = src_property->Get(); // Skip the tile if it has no source name. // Declaring the name 'auto' is the same as an empty string. This gives an easy way to skip certain @@ -101,14 +92,15 @@ bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Tex if (texture_name.empty() || texture_name == "auto") continue; - // We are required to set default values before instancing the tile, thus, all properties should always be dereferencable. - // If the debugger captures a zero-dereference, check that all properties for every tile is set and default values are set just before instancing. + // We are required to set default values before instancing the tile, thus, all properties should always be + // dereferencable. If the debugger captures a zero-dereference, check that all properties for every tile is set + // and default values are set just before instancing. DecoratorTiled::Tile& tile = tiles[i]; Texture& texture = textures[i]; // A tile is always either a sprite or an image. - if (const Sprite * sprite = instancer_interface.GetSprite(texture_name)) + if (const Sprite* sprite = instancer_interface.GetSprite(texture_name)) { tile.position = sprite->rectangle.Position(); tile.size = sprite->rectangle.Size(); @@ -118,9 +110,8 @@ bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Tex } else { - // No sprite found, we assume then that the name is an image source. - // Since the common use case is to specify the same texture for all tiles, we - // check the previous texture first before fetching from the global database. + // No sprite found, so assume that the name is an image source. Since the common use case is to specify the + // same texture for all tiles, check the previous texture first before fetching from the global database. if (texture_name == previous_texture_name) { texture = previous_texture; @@ -141,12 +132,9 @@ bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Tex { RMLUI_ASSERT(ids.align_x != PropertyId::Invalid && ids.align_y != PropertyId::Invalid); const Property& fit_property = *properties.GetProperty(ids.fit); - tile.fit_mode = (DecoratorTiled::TileFitMode)fit_property.value.Get< int >(); + tile.fit_mode = (DecoratorTiled::TileFitMode)fit_property.value.Get(); - const Property* align_properties[2] = { - properties.GetProperty(ids.align_x), - properties.GetProperty(ids.align_y) - }; + const Property* align_properties[2] = {properties.GetProperty(ids.align_x), properties.GetProperty(ids.align_y)}; for (int dimension = 0; dimension < 2; dimension++) { @@ -159,8 +147,8 @@ bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Tex enum { TOP_LEFT, CENTER, BOTTOM_RIGHT }; switch (property.Get()) { - case TOP_LEFT: align = LengthPercentage(LengthPercentage::Percentage, 0.0f); break; - case CENTER: align = LengthPercentage(LengthPercentage::Percentage, 50.0f); break; + case TOP_LEFT: align = LengthPercentage(LengthPercentage::Percentage, 0.0f); break; + case CENTER: align = LengthPercentage(LengthPercentage::Percentage, 50.0f); break; case BOTTOM_RIGHT: align = LengthPercentage(LengthPercentage::Percentage, 100.0f); break; } } @@ -168,13 +156,14 @@ bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Tex { align = LengthPercentage(LengthPercentage::Percentage, property.Get()); } - else if(property.unit == Property::PX) + else if (property.unit == Property::PX) { align = LengthPercentage(LengthPercentage::Length, property.Get()); } else { - Log::Message(Log::LT_WARNING, "Decorator alignment value is '%s' which uses an unsupported unit (use px, %%, or keyword)", property.ToString().c_str()); + Log::Message(Log::LT_WARNING, "Decorator alignment value is '%s' which uses an unsupported unit (use px, %%, or keyword)", + property.ToString().c_str()); } } } @@ -182,7 +171,7 @@ bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Tex if (ids.orientation != PropertyId::Invalid) { const Property& orientation_property = *properties.GetProperty(ids.orientation); - tile.orientation = (DecoratorTiled::TileOrientation)orientation_property.value.Get< int >(); + tile.orientation = (DecoratorTiled::TileOrientation)orientation_property.value.Get(); } } diff --git a/Source/Core/DecoratorTiledInstancer.h b/Source/Core/DecoratorTiledInstancer.h index 8a5d7bea3..83ef750c7 100644 --- a/Source/Core/DecoratorTiledInstancer.h +++ b/Source/Core/DecoratorTiledInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,12 +37,10 @@ namespace Rml { class StyleSheet; /** - @author Peter Curry + @author Peter Curry */ - -class DecoratorTiledInstancer : public DecoratorInstancer -{ +class DecoratorTiledInstancer : public DecoratorInstancer { public: DecoratorTiledInstancer(size_t num_tiles); @@ -57,7 +55,8 @@ class DecoratorTiledInstancer : public DecoratorInstancer /// @param[out] textures Holds the textures declared for the tile. /// @param[in] properties The user-defined list of parameters for the decorator. /// @param[in] instancer_interface An interface for querying the active style sheet. - bool GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) const; + bool GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) const; private: struct TilePropertyIds { diff --git a/Source/Core/DecoratorTiledVertical.cpp b/Source/Core/DecoratorTiledVertical.cpp index b24f19062..049e01010 100644 --- a/Source/Core/DecoratorTiledVertical.cpp +++ b/Source/Core/DecoratorTiledVertical.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,8 +34,7 @@ namespace Rml { -struct DecoratorTiledVerticalData -{ +struct DecoratorTiledVerticalData { DecoratorTiledVerticalData(Element* host_element, int num_textures) : num_textures(num_textures) { geometry = new Geometry[num_textures]; @@ -43,24 +42,16 @@ struct DecoratorTiledVerticalData geometry[i].SetHostElement(host_element); } - ~DecoratorTiledVerticalData() - { - delete[] geometry; - } + ~DecoratorTiledVerticalData() { delete[] geometry; } const int num_textures; Geometry* geometry; }; -DecoratorTiledVertical::DecoratorTiledVertical() -{ -} +DecoratorTiledVertical::DecoratorTiledVertical() {} -DecoratorTiledVertical::~DecoratorTiledVertical() -{ -} +DecoratorTiledVertical::~DecoratorTiledVertical() {} -// Initialises the tiles for the decorator. bool DecoratorTiledVertical::Initialise(const Tile* _tiles, const Texture* _textures) { // Load the textures. @@ -90,7 +81,6 @@ bool DecoratorTiledVertical::Initialise(const Tile* _tiles, const Texture* _text return true; } -// Called on a decorator to generate any required per-element data for a newly decorated element. DecoratorDataHandle DecoratorTiledVertical::GenerateElementData(Element* element) const { // Initialise the tile for this element. @@ -124,11 +114,16 @@ DecoratorDataHandle DecoratorTiledVertical::GenerateElementData(Element* element } // Generate the geometry for the left tile. - tiles[TOP].GenerateGeometry(data->geometry[tiles[TOP].texture_index].GetVertices(), data->geometry[tiles[TOP].texture_index].GetIndices(), element, Vector2f(0, 0), top_dimensions, top_dimensions); + tiles[TOP].GenerateGeometry(data->geometry[tiles[TOP].texture_index].GetVertices(), data->geometry[tiles[TOP].texture_index].GetIndices(), + element, Vector2f(0, 0), top_dimensions, top_dimensions); // Generate the geometry for the centre tiles. - tiles[CENTRE].GenerateGeometry(data->geometry[tiles[CENTRE].texture_index].GetVertices(), data->geometry[tiles[CENTRE].texture_index].GetIndices(), element, Vector2f(0, top_dimensions.y), Vector2f(centre_dimensions.x, padded_size.y - (top_dimensions.y + bottom_dimensions.y)), centre_dimensions); + tiles[CENTRE].GenerateGeometry(data->geometry[tiles[CENTRE].texture_index].GetVertices(), + data->geometry[tiles[CENTRE].texture_index].GetIndices(), element, Vector2f(0, top_dimensions.y), + Vector2f(centre_dimensions.x, padded_size.y - (top_dimensions.y + bottom_dimensions.y)), centre_dimensions); // Generate the geometry for the right tile. - tiles[BOTTOM].GenerateGeometry(data->geometry[tiles[BOTTOM].texture_index].GetVertices(), data->geometry[tiles[BOTTOM].texture_index].GetIndices(), element, Vector2f(0, padded_size.y - bottom_dimensions.y), bottom_dimensions, bottom_dimensions); + tiles[BOTTOM].GenerateGeometry(data->geometry[tiles[BOTTOM].texture_index].GetVertices(), + data->geometry[tiles[BOTTOM].texture_index].GetIndices(), element, Vector2f(0, padded_size.y - bottom_dimensions.y), bottom_dimensions, + bottom_dimensions); // Set the textures on the geometry. const Texture* texture = nullptr; @@ -139,17 +134,15 @@ DecoratorDataHandle DecoratorTiledVertical::GenerateElementData(Element* element return reinterpret_cast(data); } -// Called to release element data generated by this decorator. void DecoratorTiledVertical::ReleaseElementData(DecoratorDataHandle element_data) const { - delete reinterpret_cast< DecoratorTiledVerticalData* >(element_data); + delete reinterpret_cast(element_data); } -// Called to render the decorator on an element. void DecoratorTiledVertical::RenderElement(Element* element, DecoratorDataHandle element_data) const { Vector2f translation = element->GetAbsoluteOffset(Box::PADDING).Round(); - DecoratorTiledVerticalData* data = reinterpret_cast< DecoratorTiledVerticalData* >(element_data); + DecoratorTiledVerticalData* data = reinterpret_cast(element_data); for (int i = 0; i < data->num_textures; i++) data->geometry[i].Render(translation); diff --git a/Source/Core/DecoratorTiledVertical.h b/Source/Core/DecoratorTiledVertical.h index e74abe4b7..9d2113c55 100644 --- a/Source/Core/DecoratorTiledVertical.h +++ b/Source/Core/DecoratorTiledVertical.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledVertical : public DecoratorTiled -{ +class DecoratorTiledVertical : public DecoratorTiled { public: DecoratorTiledVertical(); virtual ~DecoratorTiledVertical(); @@ -58,12 +57,7 @@ class DecoratorTiledVertical : public DecoratorTiled void RenderElement(Element* element, DecoratorDataHandle element_data) const override; private: - enum - { - TOP = 0, - BOTTOM = 1, - CENTRE = 2 - }; + enum { TOP = 0, BOTTOM = 1, CENTRE = 2 }; Tile tiles[3]; }; diff --git a/Source/Core/DecoratorTiledVerticalInstancer.cpp b/Source/Core/DecoratorTiledVerticalInstancer.cpp index 98566bb92..27133ff50 100644 --- a/Source/Core/DecoratorTiledVerticalInstancer.cpp +++ b/Source/Core/DecoratorTiledVerticalInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,8 +26,8 @@ * */ -#include "DecoratorTiledVertical.h" #include "DecoratorTiledVerticalInstancer.h" +#include "DecoratorTiledVertical.h" namespace Rml { @@ -39,14 +39,11 @@ DecoratorTiledVerticalInstancer::DecoratorTiledVerticalInstancer() : DecoratorTi RegisterShorthand("decorator", "top-image, center-image, bottom-image", ShorthandType::RecursiveCommaSeparated); } -DecoratorTiledVerticalInstancer::~DecoratorTiledVerticalInstancer() -{ -} +DecoratorTiledVerticalInstancer::~DecoratorTiledVerticalInstancer() {} -SharedPtr DecoratorTiledVerticalInstancer::InstanceDecorator(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) +SharedPtr DecoratorTiledVerticalInstancer::InstanceDecorator(const String& /*name*/, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) { - RMLUI_UNUSED(name); - constexpr size_t num_tiles = 3; DecoratorTiled::Tile tiles[num_tiles]; diff --git a/Source/Core/DecoratorTiledVerticalInstancer.h b/Source/Core/DecoratorTiledVerticalInstancer.h index a79af6740..4c6d31f29 100644 --- a/Source/Core/DecoratorTiledVerticalInstancer.h +++ b/Source/Core/DecoratorTiledVerticalInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,17 +34,17 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class DecoratorTiledVerticalInstancer : public DecoratorTiledInstancer -{ +class DecoratorTiledVerticalInstancer : public DecoratorTiledInstancer { public: DecoratorTiledVerticalInstancer(); ~DecoratorTiledVerticalInstancer(); /// Instances a vertical decorator. - SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) override; + SharedPtr InstanceDecorator(const String& name, const PropertyDictionary& properties, + const DecoratorInstancerInterface& instancer_interface) override; }; } // namespace Rml diff --git a/Source/Core/DocumentHeader.cpp b/Source/Core/DocumentHeader.cpp index 1d3b10665..5fffcd482 100644 --- a/Source/Core/DocumentHeader.cpp +++ b/Source/Core/DocumentHeader.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,10 +27,10 @@ */ #include "DocumentHeader.h" -#include "XMLParseTools.h" #include "../../Include/RmlUi/Core/Core.h" -#include "../../Include/RmlUi/Core/SystemInterface.h" #include "../../Include/RmlUi/Core/StringUtilities.h" +#include "../../Include/RmlUi/Core/SystemInterface.h" +#include "XMLParseTools.h" namespace Rml { @@ -54,7 +54,8 @@ void DocumentHeader::MergePaths(StringList& target, const StringList& source, co for (size_t i = 0; i < source.size(); i++) { String joined_path; - ::Rml::GetSystemInterface()->JoinPath(joined_path, StringUtilities::Replace(source_path, '|', ':'), StringUtilities::Replace(source[i], '|', ':')); + ::Rml::GetSystemInterface()->JoinPath(joined_path, StringUtilities::Replace(source_path, '|', ':'), + StringUtilities::Replace(source[i], '|', ':')); target.push_back(StringUtilities::Replace(joined_path, ':', '|')); } diff --git a/Source/Core/DocumentHeader.h b/Source/Core/DocumentHeader.h index 85cf75e04..12614d2e5 100644 --- a/Source/Core/DocumentHeader.h +++ b/Source/Core/DocumentHeader.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,27 +36,26 @@ namespace Rml { using LineNumberList = Vector; /** - The document header struct contains the - header details gathered from an XML document parse. + The document header struct contains the + header details gathered from an XML document parse. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class DocumentHeader -{ +class DocumentHeader { public: /// Path and filename this document was loaded from String source; /// The title of the document - String title; + String title; /// A list of template resources that can used while parsing the document StringList template_resources; struct Resource { - String path; // Content path for inline resources, source path for external resources. + String path; // Content path for inline resources, source path for external resources. String content; // Only set for inline resources. bool is_inline = false; - int line = 0; // Only set for inline resources. + int line = 0; // Only set for inline resources. }; using ResourceList = Vector; diff --git a/Source/Core/Element.cpp b/Source/Core/Element.cpp index a0863b7ce..c328e22d4 100644 --- a/Source/Core/Element.cpp +++ b/Source/Core/Element.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,20 +26,19 @@ * */ - #include "../../Include/RmlUi/Core/Element.h" #include "../../Include/RmlUi/Core/Context.h" #include "../../Include/RmlUi/Core/Core.h" +#include "../../Include/RmlUi/Core/Dictionary.h" #include "../../Include/RmlUi/Core/ElementDocument.h" #include "../../Include/RmlUi/Core/ElementInstancer.h" #include "../../Include/RmlUi/Core/ElementScroll.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" #include "../../Include/RmlUi/Core/Factory.h" -#include "../../Include/RmlUi/Core/Dictionary.h" #include "../../Include/RmlUi/Core/Profiling.h" -#include "../../Include/RmlUi/Core/PropertyIdSet.h" #include "../../Include/RmlUi/Core/PropertiesIteratorView.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" +#include "../../Include/RmlUi/Core/PropertyIdSet.h" #include "../../Include/RmlUi/Core/StyleSheet.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" #include "../../Include/RmlUi/Core/TransformPrimitive.h" @@ -48,17 +47,17 @@ #include "DataModel.h" #include "ElementAnimation.h" #include "ElementBackgroundBorder.h" +#include "ElementDecoration.h" #include "ElementDefinition.h" #include "ElementStyle.h" #include "EventDispatcher.h" #include "EventSpecification.h" -#include "ElementDecoration.h" #include "Layout/LayoutEngine.h" #include "PluginRegistry.h" -#include "PropertiesIterator.h" #include "Pool.h" -#include "StyleSheetParser.h" +#include "PropertiesIterator.h" #include "StyleSheetNode.h" +#include "StyleSheetParser.h" #include "TransformState.h" #include "TransformUtilities.h" #include "XMLParseTools.h" @@ -92,8 +91,7 @@ static float GetScrollOffsetDelta(ScrollAlignment alignment, float begin_offset, } // Meta objects for element collected in a single struct to reduce memory allocations -struct ElementMeta -{ +struct ElementMeta { ElementMeta(Element* el) : event_dispatcher(el), style(el), background_border(el), decoration(el), scroll(el), computed_values(el) {} SmallUnorderedMap attribute_event_listeners; EventDispatcher event_dispatcher; @@ -104,7 +102,7 @@ struct ElementMeta Style::ComputedValues computed_values; }; -static Pool< ElementMeta > element_meta_chunk_pool(200, true); +static Pool element_meta_chunk_pool(200, true); Element::Element(const String& tag) : local_stacking_context(false), local_stacking_context_forced(false), stacking_context_dirty(false), computed_values_are_default_initialized(true), @@ -133,7 +131,7 @@ Element::Element(const String& tag) : Element::~Element() { - RMLUI_ASSERT(parent == nullptr); + RMLUI_ASSERT(parent == nullptr); PluginRegistry::NotifyElementDestroy(this); @@ -184,8 +182,9 @@ void Element::Update(float dp_ratio, Vector2f vp_dimensions) for (size_t i = 0; i < children.size(); i++) children[i]->Update(dp_ratio, vp_dimensions); - if(!animations.empty() && IsVisible(true)) { - if(Context* ctx = GetContext()) + if (!animations.empty() && IsVisible(true)) + { + if (Context* ctx = GetContext()) ctx->RequestNextUpdate(0); } } @@ -200,7 +199,8 @@ void Element::UpdateProperties(const float dp_ratio, const Vector2f vp_dimension const ComputedValues* document_values = owner_document ? &owner_document->GetComputedValues() : nullptr; // Compute values and clear dirty properties - PropertyIdSet dirty_properties = meta->style.ComputeValues(meta->computed_values, parent_values, document_values, computed_values_are_default_initialized, dp_ratio, vp_dimensions); + PropertyIdSet dirty_properties = meta->style.ComputeValues(meta->computed_values, parent_values, document_values, + computed_values_are_default_initialized, dp_ratio, vp_dimensions); computed_values_are_default_initialized = false; @@ -251,7 +251,6 @@ void Element::Render() element->Render(); } -// Clones this element, returning a new, unparented element. ElementPtr Element::Clone() const { ElementPtr clone; @@ -289,40 +288,34 @@ ElementPtr Element::Clone() const return clone; } -// Sets or removes a class on the element. void Element::SetClass(const String& class_name, bool activate) { if (meta->style.SetClass(class_name, activate)) DirtyDefinition(DirtyNodes::SelfAndSiblings); } -// Checks if a class is set on the element. bool Element::IsClassSet(const String& class_name) const { return meta->style.IsClassSet(class_name); } -// Specifies the entire list of classes for this element. This will replace any others specified. void Element::SetClassNames(const String& class_names) { SetAttribute("class", class_names); } -/// Return the active class list String Element::GetClassNames() const { return meta->style.GetClassNames(); } -// Returns the active style sheet for this element. This may be nullptr. const StyleSheet* Element::GetStyleSheet() const { - if (ElementDocument * document = GetOwnerDocument()) + if (ElementDocument* document = GetOwnerDocument()) return document->GetStyleSheet(); return nullptr; } -// Fills an String with the full address of this element. String Element::GetAddress(bool include_pseudo_classes, bool include_parents) const { // Add the tag name onto the address. @@ -362,16 +355,13 @@ String Element::GetAddress(bool include_pseudo_classes, bool include_parents) co return address; } -// Sets the position of this element, as a two-dimensional offset from another element. void Element::SetOffset(Vector2f offset, Element* _offset_parent, bool _offset_fixed) { _offset_fixed |= GetPosition() == Style::Position::Fixed; // If our offset has definitely changed, or any of our parenting has, then these are set and // updated based on our left / right / top / bottom properties. - if (relative_offset_base != offset || - offset_parent != _offset_parent || - offset_fixed != _offset_fixed) + if (relative_offset_base != offset || offset_parent != _offset_parent || offset_fixed != _offset_fixed) { relative_offset_base = offset; offset_fixed = _offset_fixed; @@ -389,19 +379,16 @@ void Element::SetOffset(Vector2f offset, Element* _offset_parent, bool _offset_f UpdateOffset(); - if (old_base != relative_offset_base || - old_position != relative_offset_position) + if (old_base != relative_offset_base || old_position != relative_offset_position) DirtyAbsoluteOffset(); } } -// Returns the position of the top-left corner of one of the areas of this element's primary box. Vector2f Element::GetRelativeOffset(Box::Area area) { return relative_offset_base + relative_offset_position + GetBox().GetPosition(area); } -// Returns the position of the top-left corner of one of the areas of this element's primary box. Vector2f Element::GetAbsoluteOffset(Box::Area area) { if (absolute_offset_dirty) @@ -428,19 +415,16 @@ Vector2f Element::GetAbsoluteOffset(Box::Area area) return absolute_offset + GetBox().GetPosition(area); } -// Sets an alternate area to use as the client area. void Element::SetClientArea(Box::Area _client_area) { client_area = _client_area; } -// Returns the area the element uses as its client area. Box::Area Element::GetClientArea() const { return client_area; } -// Sets the dimensions of the element's internal content. void Element::SetScrollableOverflowRectangle(Vector2f _scrollable_overflow_rectangle) { if (scrollable_overflow_rectangle != _scrollable_overflow_rectangle) @@ -453,7 +437,6 @@ void Element::SetScrollableOverflowRectangle(Vector2f _scrollable_overflow_recta } } -// Sets the box describing the size of the element. void Element::SetBox(const Box& box) { if (box != main_box || additional_boxes.size() > 0) @@ -469,10 +452,9 @@ void Element::SetBox(const Box& box) } } -// Adds a box to the end of the list describing this element's geometry. void Element::AddBox(const Box& box, Vector2f offset) { - additional_boxes.emplace_back(PositionedBox{ box, offset }); + additional_boxes.emplace_back(PositionedBox{box, offset}); OnResize(); @@ -481,20 +463,18 @@ void Element::AddBox(const Box& box, Vector2f offset) meta->decoration.DirtyDecoratorsData(); } -// Returns one of the boxes describing the size of the element. const Box& Element::GetBox() { return main_box; } -// Returns one of the boxes describing the size of the element. const Box& Element::GetBox(int index, Vector2f& offset) { offset = Vector2f(0); if (index < 1) return main_box; - + const int additional_box_index = index - 1; if (additional_box_index >= (int)additional_boxes.size()) return main_box; @@ -504,23 +484,18 @@ const Box& Element::GetBox(int index, Vector2f& offset) return additional_boxes[additional_box_index].box; } -// Returns the number of boxes making up this element's geometry. int Element::GetNumBoxes() { return 1 + (int)additional_boxes.size(); } -// Returns the baseline of the element, in pixels offset from the bottom of the element's content area. float Element::GetBaseline() const { return baseline; } -// Gets the intrinsic dimensions of this element, if it is of a type that has an inherent size. -bool Element::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions), float& RMLUI_UNUSED_PARAMETER(ratio)) +bool Element::GetIntrinsicDimensions(Vector2f& /*dimensions*/, float& /*ratio*/) { - RMLUI_UNUSED(dimensions); - RMLUI_UNUSED(ratio); return false; } @@ -531,7 +506,6 @@ bool Element::IsReplaced() return GetIntrinsicDimensions(unused_dimensions, unused_ratio); } -// Checks if a given point in screen coordinates lies within the bordered area of this element. bool Element::IsPointWithinElement(const Vector2f point) { const Vector2f position = GetAbsoluteOffset(Box::BORDER); @@ -543,9 +517,7 @@ bool Element::IsPointWithinElement(const Vector2f point) const Vector2f box_position = position + box_offset; const Vector2f box_dimensions = box.GetSize(Box::BORDER); - if (point.x >= box_position.x && - point.x <= (box_position.x + box_dimensions.x) && - point.y >= box_position.y && + if (point.x >= box_position.x && point.x <= (box_position.x + box_dimensions.x) && point.y >= box_position.y && point.y <= (box_position.y + box_dimensions.y)) { return true; @@ -555,7 +527,6 @@ bool Element::IsPointWithinElement(const Vector2f point) return false; } -// Returns the visibility of the element. bool Element::IsVisible(bool include_ancestors) const { if (!include_ancestors) @@ -570,19 +541,16 @@ bool Element::IsVisible(bool include_ancestors) const return true; } -// Returns the z-index of the element. float Element::GetZIndex() const { return z_index; } -// Returns the element's font face handle. FontFaceHandle Element::GetFontFaceHandle() const { return meta->computed_values.font_face_handle(); } -// Sets a local property override on the element. bool Element::SetProperty(const String& name, const String& value) { // The name may be a shorthand giving us multiple underlying properties @@ -600,37 +568,31 @@ bool Element::SetProperty(const String& name, const String& value) return true; } -// Sets a local property override on the element to a pre-parsed value. bool Element::SetProperty(PropertyId id, const Property& property) { return meta->style.SetProperty(id, property); } -// Removes a local property override on the element. void Element::RemoveProperty(const String& name) { meta->style.RemoveProperty(StyleSheetSpecification::GetPropertyId(name)); } -// Removes a local property override on the element. void Element::RemoveProperty(PropertyId id) { meta->style.RemoveProperty(id); } -// Returns one of this element's properties. const Property* Element::GetProperty(const String& name) { return meta->style.GetProperty(StyleSheetSpecification::GetPropertyId(name)); } -// Returns one of this element's properties. const Property* Element::GetProperty(PropertyId id) { return meta->style.GetProperty(id); } -// Returns one of this element's properties. const Property* Element::GetLocalProperty(const String& name) { return meta->style.GetLocalProperty(StyleSheetSpecification::GetPropertyId(name)); @@ -646,7 +608,7 @@ const PropertyMap& Element::GetLocalStyleProperties() return meta->style.GetLocalStyleProperties(); } -float Element::ResolveNumericProperty(const Property *property, float base_value) +float Element::ResolveNumericProperty(const Property* property, float base_value) { return meta->style.ResolveNumericProperty(property, base_value); } @@ -665,7 +627,7 @@ float Element::ResolveNumericProperty(const String& property_name) relative_target = property->definition->GetRelativeTarget(); float result = meta->style.ResolveLength(property, relative_target); - + return result; } @@ -683,12 +645,12 @@ Vector2f Element::GetContainingBlock() { containing_block = parent_box.GetSize(); } - else if(position_property == Position::Absolute || position_property == Position::Fixed) + else if (position_property == Position::Absolute || position_property == Position::Fixed) { containing_block = parent_box.GetSize(Box::PADDING); } } - + return containing_block; } @@ -712,16 +674,14 @@ float Element::GetLineHeight() return meta->computed_values.line_height().value; } -// Returns this element's TransformState -const TransformState *Element::GetTransformState() const noexcept +const TransformState* Element::GetTransformState() const noexcept { return transform_state.get(); } -// Project a 2D point in pixel coordinates onto the element's plane. bool Element::Project(Vector2f& point) const noexcept { - if(!transform_state || !transform_state->GetTransform()) + if (!transform_state || !transform_state->GetTransform()) return true; // The input point is in window coordinates. Need to find the projection of the point onto the current element plane, @@ -730,23 +690,20 @@ bool Element::Project(Vector2f& point) const noexcept if (const Matrix4f* inv_transform = transform_state->GetInverseTransform()) { // Pick two points forming a line segment perpendicular to the window. - Vector4f window_points[2] = {{ point.x, point.y, -10, 1}, { point.x, point.y, 10, 1 }}; + Vector4f window_points[2] = {{point.x, point.y, -10, 1}, {point.x, point.y, 10, 1}}; // Project them into the local element space. window_points[0] = *inv_transform * window_points[0]; window_points[1] = *inv_transform * window_points[1]; - Vector3f local_points[2] = { - window_points[0].PerspectiveDivide(), - window_points[1].PerspectiveDivide() - }; + Vector3f local_points[2] = {window_points[0].PerspectiveDivide(), window_points[1].PerspectiveDivide()}; // Construct a ray from the two projected points in the local space of the current element. // Find the intersection with the z=0 plane to produce our destination point. Vector3f ray = local_points[1] - local_points[0]; // Only continue if we are not close to parallel with the plane. - if(std::fabs(ray.z) > 1.0f) + if (std::fabs(ray.z) > 1.0f) { // Solving the line equation p = p0 + t*ray for t, knowing that p.z = 0, produces the following. float t = -local_points[0].z / ray.z; @@ -766,8 +723,6 @@ PropertiesIteratorView Element::IterateLocalProperties() const return PropertiesIteratorView(MakeUnique(meta->style.Iterate())); } - -// Sets or removes a pseudo-class on the element. void Element::SetPseudoClass(const String& pseudo_class, bool activate) { if (meta->style.SetPseudoClass(pseudo_class, activate, false)) @@ -778,13 +733,11 @@ void Element::SetPseudoClass(const String& pseudo_class, bool activate) } } -// Checks if a specific pseudo-class has been set on the element. bool Element::IsPseudoClassSet(const String& pseudo_class) const { return meta->style.IsPseudoClassSet(pseudo_class); } -// Checks if a complete set of pseudo-classes are set on the element. bool Element::ArePseudoClassesSet(const StringList& pseudo_classes) const { for (const String& pseudo_class : pseudo_classes) @@ -796,7 +749,6 @@ bool Element::ArePseudoClassesSet(const StringList& pseudo_classes) const return true; } -// Gets a list of the current active pseudo classes StringList Element::GetActivePseudoClasses() const { const PseudoClassMap& pseudo_classes = meta->style.GetActivePseudoClasses(); @@ -826,13 +778,11 @@ const Variant* Element::GetAttribute(const String& name) const return GetIf(attributes, name); } -// Checks if the element has a certain attribute. bool Element::HasAttribute(const String& name) const { return attributes.find(name) != attributes.end(); } -// Removes an attribute from the element void Element::RemoveAttribute(const String& name) { auto it = attributes.find(name); @@ -846,7 +796,6 @@ void Element::RemoveAttribute(const String& name) } } -// Gets the outer most focus element down the tree from this node Element* Element::GetFocusLeafNode() { // If there isn't a focus, then we are the leaf. @@ -863,7 +812,6 @@ Element* Element::GetFocusLeafNode() return focus_element; } -// Returns the element's context. Context* Element::GetContext() const { ElementDocument* document = GetOwnerDocument(); @@ -873,7 +821,6 @@ Context* Element::GetContext() const return nullptr; } -// Set a group of attributes void Element::SetAttributes(const ElementAttributes& _attributes) { attributes.reserve(attributes.size() + _attributes.size()); @@ -883,103 +830,86 @@ void Element::SetAttributes(const ElementAttributes& _attributes) OnAttributeChange(_attributes); } -// Returns the number of attributes on the element. int Element::GetNumAttributes() const { return (int)attributes.size(); } -// Gets the name of the element. const String& Element::GetTagName() const { return tag; } -// Gets the ID of the element. const String& Element::GetId() const { return id; } -// Sets the ID of the element. void Element::SetId(const String& _id) { SetAttribute("id", _id); } -// Gets the horizontal offset from the context's left edge to element's left border edge. float Element::GetAbsoluteLeft() { return GetAbsoluteOffset(Box::BORDER).x; } -// Gets the vertical offset from the context's top edge to element's top border edge. float Element::GetAbsoluteTop() { return GetAbsoluteOffset(Box::BORDER).y; } -// Gets the width of the left border of an element. float Element::GetClientLeft() { return GetBox().GetPosition(client_area).x; } -// Gets the height of the top border of an element. float Element::GetClientTop() { return GetBox().GetPosition(client_area).y; } -// Gets the inner width of the element. float Element::GetClientWidth() { return GetBox().GetSize(client_area).x - meta->scroll.GetScrollbarSize(ElementScroll::VERTICAL); } -// Gets the inner height of the element. float Element::GetClientHeight() { return GetBox().GetSize(client_area).y - meta->scroll.GetScrollbarSize(ElementScroll::HORIZONTAL); } -// Returns the element from which all offset calculations are currently computed. Element* Element::GetOffsetParent() { return offset_parent; } -// Gets the distance from this element's left border to its offset parent's left border. float Element::GetOffsetLeft() { return relative_offset_base.x + relative_offset_position.x; } -// Gets the distance from this element's top border to its offset parent's top border. float Element::GetOffsetTop() { return relative_offset_base.y + relative_offset_position.y; } -// Gets the width of the element, including the client area, padding, borders and scrollbars, but not margins. float Element::GetOffsetWidth() { return GetBox().GetSize(Box::BORDER).x; } -// Gets the height of the element, including the client area, padding, borders and scrollbars, but not margins. float Element::GetOffsetHeight() { return GetBox().GetSize(Box::BORDER).y; } -// Gets the left scroll offset of the element. float Element::GetScrollLeft() { return scroll_offset.x; } -// Sets the left scroll offset of the element. void Element::SetScrollLeft(float scroll_left) { const float new_offset = Math::Clamp(Math::RoundFloat(scroll_left), 0.0f, GetScrollWidth() - GetClientWidth()); @@ -993,17 +923,15 @@ void Element::SetScrollLeft(float scroll_left) } } -// Gets the top scroll offset of the element. float Element::GetScrollTop() { return scroll_offset.y; } -// Sets the top scroll offset of the element. void Element::SetScrollTop(float scroll_top) { const float new_offset = Math::Clamp(Math::RoundFloat(scroll_top), 0.0f, GetScrollHeight() - GetClientHeight()); - if(new_offset != scroll_offset.y) + if (new_offset != scroll_offset.y) { scroll_offset.y = new_offset; meta->scroll.UpdateScrollbar(ElementScroll::VERTICAL); @@ -1013,25 +941,21 @@ void Element::SetScrollTop(float scroll_top) } } -// Gets the width of the scrollable content of the element; it includes the element padding but not its margin. float Element::GetScrollWidth() { return Math::Max(scrollable_overflow_rectangle.x, GetClientWidth()); } -// Gets the height of the scrollable content of the element; it includes the element padding but not its margin. float Element::GetScrollHeight() { return Math::Max(scrollable_overflow_rectangle.y, GetClientHeight()); } -// Gets the object representing the declarations of an element's style attributes. ElementStyle* Element::GetStyle() const { return &meta->style; } -// Gets the document this element belongs to. ElementDocument* Element::GetOwnerDocument() const { #ifdef RMLUI_DEBUG @@ -1047,13 +971,11 @@ ElementDocument* Element::GetOwnerDocument() const return owner_document; } -// Gets this element's parent node. Element* Element::GetParentNode() const { return parent; } -// Recursively search for a ancestor of this node matching the given selector. Element* Element::Closest(const String& selectors) const { StyleSheetNode root_node; @@ -1067,7 +989,7 @@ Element* Element::Closest(const String& selectors) const Element* parent = GetParentNode(); - while(parent) + while (parent) { for (const StyleSheetNode* node : leaf_nodes) { @@ -1076,14 +998,13 @@ Element* Element::Closest(const String& selectors) const return parent; } } - + parent = parent->GetParentNode(); } return nullptr; } -// Gets the element immediately following this one in the tree. Element* Element::GetNextSibling() const { if (parent == nullptr) @@ -1098,7 +1019,6 @@ Element* Element::GetNextSibling() const return nullptr; } -// Gets the element immediately preceding this one in the tree. Element* Element::GetPreviousSibling() const { if (parent == nullptr) @@ -1113,7 +1033,6 @@ Element* Element::GetPreviousSibling() const return nullptr; } -// Returns the first child of this element. Element* Element::GetFirstChild() const { if (GetNumChildren() > 0) @@ -1122,7 +1041,6 @@ Element* Element::GetFirstChild() const return nullptr; } -// Gets the last child of this element. Element* Element::GetLastChild() const { if (GetNumChildren() > 0) @@ -1133,7 +1051,7 @@ Element* Element::GetLastChild() const Element* Element::GetChild(int index) const { - if (index < 0 || index >= (int) children.size()) + if (index < 0 || index >= (int)children.size()) return nullptr; return children[index].get(); @@ -1141,10 +1059,9 @@ Element* Element::GetChild(int index) const int Element::GetNumChildren(bool include_non_dom_elements) const { - return (int) children.size() - (include_non_dom_elements ? 0 : num_non_dom_children); + return (int)children.size() - (include_non_dom_elements ? 0 : num_non_dom_children); } -// Gets the markup and content of the element. void Element::GetInnerRML(String& content) const { for (int i = 0; i < GetNumChildren(); i++) @@ -1153,27 +1070,25 @@ void Element::GetInnerRML(String& content) const } } -// Gets the markup and content of the element. -String Element::GetInnerRML() const { +String Element::GetInnerRML() const +{ String result; GetInnerRML(result); return result; } -// Sets the markup and content of the element. All existing children will be replaced. void Element::SetInnerRML(const String& rml) { RMLUI_ZoneScopedC(0x6495ED); // Remove all DOM children. - while ((int) children.size() > num_non_dom_children) + while ((int)children.size() > num_non_dom_children) RemoveChild(children.front().get()); - if(!rml.empty()) + if (!rml.empty()) Factory::InstanceElementText(this, rml); } -// Sets the current element as the focus object. bool Element::Focus() { // Are we allowed focus? @@ -1203,7 +1118,6 @@ bool Element::Focus() return true; } -// Removes focus from from this element. void Element::Blur() { if (parent) @@ -1223,7 +1137,6 @@ void Element::Blur() } } -// Fakes a mouse click on this element. void Element::Click() { Context* context = GetContext(); @@ -1233,55 +1146,48 @@ void Element::Click() context->GenerateClickEvent(this); } -// Adds an event listener void Element::AddEventListener(const String& event, EventListener* listener, const bool in_capture_phase) { const EventId id = EventSpecificationInterface::GetIdOrInsert(event); meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase); } -// Adds an event listener void Element::AddEventListener(const EventId id, EventListener* listener, const bool in_capture_phase) { meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase); } -// Removes an event listener from this element. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase) { EventId id = EventSpecificationInterface::GetIdOrInsert(event); meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase); } -// Removes an event listener from this element. void Element::RemoveEventListener(EventId id, EventListener* listener, bool in_capture_phase) { meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase); } - -// Dispatches the specified event bool Element::DispatchEvent(const String& type, const Dictionary& parameters) { const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type); - return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase); + return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, + specification.default_action_phase); } -// Dispatches the specified event bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles) { const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type); return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase); } -// Dispatches the specified event bool Element::DispatchEvent(EventId id, const Dictionary& parameters) { const EventSpecification& specification = EventSpecificationInterface::Get(id); - return EventDispatcher::DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase); + return EventDispatcher::DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, + specification.default_action_phase); } -// Scrolls the parent element's contents so that this element is visible. void Element::ScrollIntoView(const ScrollIntoViewOptions options) { const Vector2f size = main_box.GetSize(Box::BORDER); @@ -1343,7 +1249,6 @@ void Element::ScrollTo(Vector2f offset, ScrollBehavior behavior) SetScrollTop(offset.y); } -// Appends a child to this element Element* Element::AppendChild(ElementPtr child, bool dom_element) { RMLUI_ASSERT(child); @@ -1374,8 +1279,6 @@ Element* Element::AppendChild(ElementPtr child, bool dom_element) return child_ptr; } -// Adds a child to this element, directly after the adjacent element. Inherits -// the dom/non-dom status from the adjacent element. Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element) { RMLUI_ASSERT(child); @@ -1402,7 +1305,7 @@ Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element) { child_ptr = child.get(); - if ((int) child_index >= GetNumChildren()) + if ((int)child_index >= GetNumChildren()) num_non_dom_children++; else DirtyLayout(); @@ -1420,12 +1323,11 @@ Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element) else { child_ptr = AppendChild(std::move(child)); - } + } return child_ptr; } -// Replaces the second node with the first node. ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_element) { RMLUI_ASSERT(inserted_element); @@ -1455,7 +1357,6 @@ ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_ return result; } -// Removes the specified child ElementPtr Element::RemoveChild(Element* child) { size_t child_index = 0; @@ -1482,7 +1383,7 @@ ElementPtr Element::RemoveChild(Element* child) // If this child (or a descendant of this child) is the context's currently // focused element, set the focus to us instead. - if (Context * context = GetContext()) + if (Context* context = GetContext()) { Element* focus_element = context->GetFocusElement(); while (focus_element) @@ -1513,10 +1414,9 @@ ElementPtr Element::RemoveChild(Element* child) return nullptr; } - bool Element::HasChildNodes() const { - return (int) children.size() > num_non_dom_children; + return (int)children.size() > num_non_dom_children; } Element* Element::GetElementById(const String& id) @@ -1537,13 +1437,11 @@ Element* Element::GetElementById(const String& id) } } -// Get all elements with the given tag. void Element::GetElementsByTagName(ElementList& elements, const String& tag) { return ElementUtilities::GetElementsByTagName(elements, this, tag); } -// Get all elements with the given class set on them. void Element::GetElementsByClassName(ElementList& elements, const String& class_name) { return ElementUtilities::GetElementsByClassName(elements, this, class_name); @@ -1624,7 +1522,6 @@ void Element::QuerySelectorAll(ElementList& elements, const String& selectors) QuerySelectorAllMatchRecursive(elements, leaf_nodes, this); } -// Access the event dispatcher EventDispatcher* Element::GetEventDispatcher() const { return &meta->event_dispatcher; @@ -1635,13 +1532,11 @@ String Element::GetEventDispatcherSummary() const return meta->event_dispatcher.ToString(); } -// Access the element decorators ElementDecoration* Element::GetElementDecoration() const { return &meta->decoration; } -// Returns the element's scrollbar functionality. ElementScroll* Element::GetElementScroll() const { return &meta->scroll; @@ -1652,7 +1547,6 @@ DataModel* Element::GetDataModel() const return data_model; } -// Gets the render interface owned by this element's context. RenderInterface* Element::GetRenderInterface() { if (Context* context = GetContext()) @@ -1671,7 +1565,6 @@ void Element::SetInstancer(ElementInstancer* _instancer) } } -// Forces the element to generate a local stacking context, regardless of the value of its z-index property. void Element::ForceLocalStackingContext() { local_stacking_context_forced = true; @@ -1680,34 +1573,18 @@ void Element::ForceLocalStackingContext() DirtyStackingContext(); } -// Called during the update loop after children are rendered. -void Element::OnUpdate() -{ -} +void Element::OnUpdate() {} -// Called during render after backgrounds, borders, decorators, but before children, are rendered. -void Element::OnRender() -{ -} +void Element::OnRender() {} -void Element::OnResize() -{ -} +void Element::OnResize() {} -// Called during a layout operation, when the element is being positioned and sized. -void Element::OnLayout() -{ -} +void Element::OnLayout() {} -void Element::OnDpRatioChange() -{ -} +void Element::OnDpRatioChange() {} -void Element::OnStyleSheetChange() -{ -} +void Element::OnStyleSheetChange() {} -// Called when attributes on the element are changed. void Element::OnAttributeChange(const ElementAttributes& changed_attributes) { for (const auto& element_attribute : changed_attributes) @@ -1722,8 +1599,10 @@ void Element::OnAttributeChange(const ElementAttributes& changed_attributes) { meta->style.SetClassNames(value.Get()); } - else if (((attribute == "colspan" || attribute == "rowspan") && meta->computed_values.display() == Style::Display::TableCell) - || (attribute == "span" && (meta->computed_values.display() == Style::Display::TableColumn || meta->computed_values.display() == Style::Display::TableColumnGroup))) + else if (((attribute == "colspan" || attribute == "rowspan") && meta->computed_values.display() == Style::Display::TableCell) || + (attribute == "span" && + (meta->computed_values.display() == Style::Display::TableColumn || + meta->computed_values.display() == Style::Display::TableColumnGroup))) { DirtyLayout(); } @@ -1734,8 +1613,7 @@ void Element::OnAttributeChange(const ElementAttributes& changed_attributes) auto& attribute_event_listeners = meta->attribute_event_listeners; auto& event_dispatcher = meta->event_dispatcher; const auto event_id = EventSpecificationInterface::GetIdOrInsert(attribute.substr(2)); - const auto remove_event_listener_if_exists = [&attribute_event_listeners, &event_dispatcher, event_id]() - { + const auto remove_event_listener_if_exists = [&attribute_event_listeners, &event_dispatcher, event_id]() { const auto listener_it = attribute_event_listeners.find(event_id); if (listener_it != attribute_event_listeners.cend()) { @@ -1777,15 +1655,14 @@ void Element::OnAttributeChange(const ElementAttributes& changed_attributes) DirtyDefinition(DirtyNodes::SelfAndSiblings); } -// Called when properties on the element are changed. void Element::OnPropertyChange(const PropertyIdSet& changed_properties) { RMLUI_ZoneScoped; - const bool top_right_bottom_left_changed = ( - changed_properties.Contains(PropertyId::Top) || - changed_properties.Contains(PropertyId::Right) || - changed_properties.Contains(PropertyId::Bottom) || - changed_properties.Contains(PropertyId::Left) + const bool top_right_bottom_left_changed = ( // + changed_properties.Contains(PropertyId::Top) || // + changed_properties.Contains(PropertyId::Right) || // + changed_properties.Contains(PropertyId::Bottom) || // + changed_properties.Contains(PropertyId::Left) // ); // See if the document layout needs to be updated. @@ -1823,14 +1700,13 @@ void Element::OnPropertyChange(const PropertyIdSet& changed_properties) UpdateOffset(); DirtyAbsoluteOffset(); } - + // Update the visibility. - if (changed_properties.Contains(PropertyId::Visibility) || - changed_properties.Contains(PropertyId::Display)) + if (changed_properties.Contains(PropertyId::Visibility) || changed_properties.Contains(PropertyId::Display)) { bool new_visibility = (meta->computed_values.display() != Style::Display::None && meta->computed_values.visibility() == Style::Visibility::Visible); - + if (visible != new_visibility) { visible = new_visibility; @@ -1850,8 +1726,7 @@ void Element::OnPropertyChange(const PropertyIdSet& changed_properties) if (z_index_property.type == Style::ZIndex::Auto) { - if (local_stacking_context && - !local_stacking_context_forced) + if (local_stacking_context && !local_stacking_context_forced) { // We're no longer acting as a stacking context. local_stacking_context = false; @@ -1886,38 +1761,38 @@ void Element::OnPropertyChange(const PropertyIdSet& changed_properties) } } } - - const bool border_radius_changed = ( - changed_properties.Contains(PropertyId::BorderTopLeftRadius) || - changed_properties.Contains(PropertyId::BorderTopRightRadius) || - changed_properties.Contains(PropertyId::BorderBottomRightRadius) || - changed_properties.Contains(PropertyId::BorderBottomLeftRadius) + + const bool border_radius_changed = ( // + changed_properties.Contains(PropertyId::BorderTopLeftRadius) || // + changed_properties.Contains(PropertyId::BorderTopRightRadius) || // + changed_properties.Contains(PropertyId::BorderBottomRightRadius) || // + changed_properties.Contains(PropertyId::BorderBottomLeftRadius) // ); // Dirty the background if it's changed. - if (border_radius_changed || - changed_properties.Contains(PropertyId::BackgroundColor) || - changed_properties.Contains(PropertyId::Opacity) || - changed_properties.Contains(PropertyId::ImageColor)) + if (border_radius_changed || // + changed_properties.Contains(PropertyId::BackgroundColor) || // + changed_properties.Contains(PropertyId::Opacity) || // + changed_properties.Contains(PropertyId::ImageColor)) // { meta->background_border.DirtyBackground(); - } + } // Dirty the border if it's changed. - if (border_radius_changed || - changed_properties.Contains(PropertyId::BorderTopWidth) || - changed_properties.Contains(PropertyId::BorderRightWidth) || - changed_properties.Contains(PropertyId::BorderBottomWidth) || - changed_properties.Contains(PropertyId::BorderLeftWidth) || - changed_properties.Contains(PropertyId::BorderTopColor) || - changed_properties.Contains(PropertyId::BorderRightColor) || - changed_properties.Contains(PropertyId::BorderBottomColor) || - changed_properties.Contains(PropertyId::BorderLeftColor) || + if (border_radius_changed || // + changed_properties.Contains(PropertyId::BorderTopWidth) || // + changed_properties.Contains(PropertyId::BorderRightWidth) || // + changed_properties.Contains(PropertyId::BorderBottomWidth) || // + changed_properties.Contains(PropertyId::BorderLeftWidth) || // + changed_properties.Contains(PropertyId::BorderTopColor) || // + changed_properties.Contains(PropertyId::BorderRightColor) || // + changed_properties.Contains(PropertyId::BorderBottomColor) || // + changed_properties.Contains(PropertyId::BorderLeftColor) || // changed_properties.Contains(PropertyId::Opacity)) { meta->background_border.DirtyBorder(); } - + // Dirty the decoration if it's changed. if (border_radius_changed || changed_properties.Contains(PropertyId::Decorator)) { @@ -1925,25 +1800,25 @@ void Element::OnPropertyChange(const PropertyIdSet& changed_properties) } // Dirty the decoration data when its visual looks may have changed. - if (border_radius_changed || - changed_properties.Contains(PropertyId::Opacity) || + if (border_radius_changed || // + changed_properties.Contains(PropertyId::Opacity) || // changed_properties.Contains(PropertyId::ImageColor)) { meta->decoration.DirtyDecoratorsData(); } // Check for `perspective' and `perspective-origin' changes - if (changed_properties.Contains(PropertyId::Perspective) || - changed_properties.Contains(PropertyId::PerspectiveOriginX) || + if (changed_properties.Contains(PropertyId::Perspective) || // + changed_properties.Contains(PropertyId::PerspectiveOriginX) || // changed_properties.Contains(PropertyId::PerspectiveOriginY)) { DirtyTransformState(true, false); } // Check for `transform' and `transform-origin' changes - if (changed_properties.Contains(PropertyId::Transform) || - changed_properties.Contains(PropertyId::TransformOriginX) || - changed_properties.Contains(PropertyId::TransformOriginY) || + if (changed_properties.Contains(PropertyId::Transform) || // + changed_properties.Contains(PropertyId::TransformOriginX) || // + changed_properties.Contains(PropertyId::TransformOriginY) || // changed_properties.Contains(PropertyId::TransformOriginZ)) { DirtyTransformState(false, true); @@ -1961,19 +1836,11 @@ void Element::OnPropertyChange(const PropertyIdSet& changed_properties) } } -void Element::OnPseudoClassChange(const String& /*pseudo_class*/, bool /*activate*/) -{ -} +void Element::OnPseudoClassChange(const String& /*pseudo_class*/, bool /*activate*/) {} -// Called when a child node has been added somewhere in the hierarchy -void Element::OnChildAdd(Element* /*child*/) -{ -} +void Element::OnChildAdd(Element* /*child*/) {} -// Called when a child node has been removed somewhere in the hierarchy -void Element::OnChildRemove(Element* /*child*/) -{ -} +void Element::OnChildRemove(Element* /*child*/) {} void Element::DirtyLayout() { @@ -2022,20 +1889,11 @@ void Element::ProcessDefaultAction(Event& event) { switch (event.GetId()) { - case EventId::Mouseover: - SetPseudoClass("hover", true); - break; - case EventId::Mouseout: - SetPseudoClass("hover", false); - break; - case EventId::Focus: - SetPseudoClass("focus", true); - break; - case EventId::Blur: - SetPseudoClass("focus", false); - break; - default: - break; + case EventId::Mouseover: SetPseudoClass("hover", true); break; + case EventId::Mouseout: SetPseudoClass("hover", false); break; + case EventId::Focus: SetPseudoClass("focus", true); break; + case EventId::Blur: SetPseudoClass("focus", false); break; + default: break; } } } @@ -2101,7 +1959,7 @@ void Element::SetOwnerDocument(ElementDocument* document) } } -void Element::SetDataModel(DataModel* new_data_model) +void Element::SetDataModel(DataModel* new_data_model) { RMLUI_ASSERTMSG(!data_model || !new_data_model, "We must either attach a new data model, or detach the old one."); @@ -2129,7 +1987,7 @@ void Element::Release() } void Element::SetParent(Element* _parent) -{ +{ // Assumes we are already detached from the hierarchy or we are detaching now. RMLUI_ASSERT(!parent || !_parent); @@ -2153,7 +2011,7 @@ void Element::SetParent(Element* _parent) if (data_model) SetDataModel(nullptr); } - else + else { auto it = attributes.find("data-model"); if (it == attributes.end()) @@ -2163,7 +2021,8 @@ void Element::SetParent(Element* _parent) else if (parent->data_model) { String name = it->second.Get(); - Log::Message(Log::LT_ERROR, "Nested data models are not allowed. Data model '%s' given in element %s.", name.c_str(), GetAddress().c_str()); + Log::Message(Log::LT_ERROR, "Nested data models are not allowed. Data model '%s' given in element %s.", name.c_str(), + GetAddress().c_str()); } else if (Context* context = GetContext()) { @@ -2205,8 +2064,7 @@ void Element::UpdateOffset() const auto& computed = meta->computed_values; Position position_property = computed.position(); - if (position_property == Position::Absolute || - position_property == Position::Fixed) + if (position_property == Position::Absolute || position_property == Position::Fixed) { if (offset_parent != nullptr) { @@ -2456,9 +2314,7 @@ void Element::DirtyDefinition(DirtyNodes dirty_nodes) { switch (dirty_nodes) { - case DirtyNodes::Self: - dirty_definition = true; - break; + case DirtyNodes::Self: dirty_definition = true; break; case DirtyNodes::SelfAndSiblings: dirty_definition = true; if (parent) @@ -2489,8 +2345,8 @@ void Element::UpdateDefinition() } } - -bool Element::Animate(const String & property_name, const Property & target_value, float duration, Tween tween, int num_iterations, bool alternate_direction, float delay, const Property* start_value) +bool Element::Animate(const String& property_name, const Property& target_value, float duration, Tween tween, int num_iterations, + bool alternate_direction, float delay, const Property* start_value) { bool result = false; PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name); @@ -2506,15 +2362,16 @@ bool Element::Animate(const String & property_name, const Property & target_valu return result; } - -bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween) +bool Element::AddAnimationKey(const String& property_name, const Property& target_value, float duration, Tween tween) { ElementAnimation* animation = nullptr; PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name); - for (auto& existing_animation : animations) { - if (existing_animation.GetPropertyId() == property_id) { + for (auto& existing_animation : animations) + { + if (existing_animation.GetPropertyId() == property_id) + { animation = &existing_animation; break; } @@ -2527,8 +2384,8 @@ bool Element::AddAnimationKey(const String & property_name, const Property & tar return result; } - -ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations, bool alternate_direction, float delay, bool initiated_by_animation_property) +ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations, + bool alternate_direction, float delay, bool initiated_by_animation_property) { auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; }); @@ -2548,8 +2405,8 @@ ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, c { value = *start_value; if (!value.definition) - if(auto default_value = GetProperty(property_id)) - value.definition = default_value->definition; + if (auto default_value = GetProperty(property_id)) + value.definition = default_value->definition; } else if (auto default_value = GetProperty(property_id)) { @@ -2560,10 +2417,10 @@ ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, c { ElementAnimationOrigin origin = (initiated_by_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User); double start_time = Clock::GetElapsedTime() + (double)delay; - *it = ElementAnimation{ property_id, origin, value, *this, start_time, 0.0f, num_iterations, alternate_direction }; + *it = ElementAnimation{property_id, origin, value, *this, start_time, 0.0f, num_iterations, alternate_direction}; } - - if(!it->IsInitalized()) + + if (!it->IsInitalized()) { animations.erase(it); it = animations.end(); @@ -2572,7 +2429,6 @@ ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, c return it; } - bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target_value, float time, Tween tween) { if (!target_value) @@ -2582,8 +2438,10 @@ bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target ElementAnimation* animation = nullptr; - for (auto& existing_animation : animations) { - if (existing_animation.GetPropertyId() == property_id) { + for (auto& existing_animation : animations) + { + if (existing_animation.GetPropertyId() == property_id) + { animation = &existing_animation; break; } @@ -2596,7 +2454,7 @@ bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target return result; } -bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value) +bool Element::StartTransition(const Transition& transition, const Property& start_value, const Property& target_value) { auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == transition.id; }); @@ -2609,19 +2467,17 @@ bool Element::StartTransition(const Transition & transition, const Property& sta if (it == animations.end()) { // Add transition as new animation - animations.push_back( - ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false } - ); + animations.push_back(ElementAnimation{transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false}); it = (animations.end() - 1); } else { // Compress the duration based on the progress of the current animation float f = it->GetInterpolationFactor(); - f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor; + f = 1.0f - (1.0f - f) * transition.reverse_adjustment_factor; duration = duration * f; // Replace old transition - *it = ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false }; + *it = ElementAnimation{transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false}; } bool result = it->AddKey(duration, target_value, *this, transition.tween, true); @@ -2636,7 +2492,7 @@ bool Element::StartTransition(const Transition & transition, const Property& sta void Element::HandleTransitionProperty() { - if(dirty_transition) + if (dirty_transition) { dirty_transition = false; @@ -2653,8 +2509,7 @@ void Element::HandleTransitionProperty() // All transitions should be removed, but only touch the animations that originate from the 'transition' property. // Move all animations to be erased in a valid state at the end of the list, and erase later. it_remove = std::partition(animations.begin(), animations.end(), - [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); } - ); + [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); }); } else { @@ -2663,17 +2518,14 @@ void Element::HandleTransitionProperty() // Only remove the transitions that are not in our keep list. const auto& keep_transitions_list = keep_transitions->transitions; - it_remove = std::partition(animations.begin(), animations.end(), - [&keep_transitions_list](const ElementAnimation& animation) -> bool { - if (!animation.IsTransition()) - return true; - auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(), - [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; } - ); - bool keep_animation = (it != keep_transitions_list.end()); - return keep_animation; - } - ); + it_remove = std::partition(animations.begin(), animations.end(), [&keep_transitions_list](const ElementAnimation& animation) -> bool { + if (!animation.IsTransition()) + return true; + auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(), + [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; }); + bool keep_animation = (it != keep_transitions_list.end()); + return keep_animation; + }); } // We can decide what to do with cancelled transitions here. @@ -2704,9 +2556,8 @@ void Element::HandleAnimationProperty() // Remove existing animations { // We only touch the animations that originate from the 'animation' property. - auto it_remove = std::partition(animations.begin(), animations.end(), - [](const ElementAnimation & animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; } - ); + auto it_remove = std::partition(animations.begin(), animations.end(), + [](const ElementAnimation& animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; }); // We can decide what to do with cancelled animations here. for (auto it = it_remove; it != animations.end(); ++it) @@ -2769,7 +2620,8 @@ void Element::AdvanceAnimations() } // Move all completed animations to the end of the list - auto it_completed = std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); }); + auto it_completed = + std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); }); Vector dictionary_list; Vector is_transition; @@ -2798,15 +2650,12 @@ void Element::AdvanceAnimations() } } - - void Element::DirtyTransformState(bool perspective_dirty, bool transform_dirty) { dirty_perspective |= perspective_dirty; dirty_transform |= transform_dirty; } - void Element::UpdateTransformState() { if (!dirty_perspective && !dirty_transform) @@ -2816,12 +2665,12 @@ void Element::UpdateTransformState() const Vector2f pos = GetAbsoluteOffset(Box::BORDER); const Vector2f size = GetBox().GetSize(Box::BORDER); - + bool perspective_or_transform_changed = false; if (dirty_perspective) { - // If perspective is set on this element, then it applies to our children. We just calculate it here, + // If perspective is set on this element, then it applies to our children. We just calculate it here, // and let the children's transform update merge it with their transform. bool had_perspective = (transform_state && transform_state->GetLocalPerspective()); @@ -2848,11 +2697,11 @@ void Element::UpdateTransformState() if (have_perspective) { // Equivalent to: Translate(x,y,0) * Perspective(distance) * Translate(-x,-y,0) - Matrix4f perspective = Matrix4f::FromRows( - { 1, 0, -vanish.x / distance, 0 }, - { 0, 1, -vanish.y / distance, 0 }, - { 0, 0, 1, 0 }, - { 0, 0, -1 / distance, 1 } + Matrix4f perspective = Matrix4f::FromRows( // + {1, 0, -vanish.x / distance, 0}, // + {0, 1, -vanish.y / distance, 0}, // + {0, 0, 1, 0}, // + {0, 0, -1 / distance, 1} // ); if (!transform_state) @@ -2868,7 +2717,6 @@ void Element::UpdateTransformState() dirty_perspective = false; } - if (dirty_transform) { // We want to find the accumulated transform given all our ancestors. It is assumed here that the parent transform is already updated, @@ -2890,7 +2738,7 @@ void Element::UpdateTransformState() have_transform = true; } - if(have_transform) + if (have_transform) { // Compute the transform origin Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0); @@ -2911,14 +2759,15 @@ void Element::UpdateTransformState() transform = Matrix4f::Translate(transform_origin) * transform * Matrix4f::Translate(-transform_origin); } - // We may want to include the local offsets here, as suggested by the CSS specs, so that the local transform is applied after the offset I believe - // the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms. + // We may want to include the local offsets here, as suggested by the CSS specs, so that the local transform is applied after the offset I + // believe the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms. } if (parent && parent->transform_state) { // Apply the parent's local perspective and transform. - // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of copying it. + // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of + // copying it. const TransformState& parent_state = *parent->transform_state; if (auto parent_perspective = parent_state.GetLocalPerspective()) diff --git a/Source/Core/ElementAnimation.cpp b/Source/Core/ElementAnimation.cpp index f3a463f63..7551dfa90 100644 --- a/Source/Core/ElementAnimation.cpp +++ b/Source/Core/ElementAnimation.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,13 +28,13 @@ #include "ElementAnimation.h" #include "../../Include/RmlUi/Core/DecoratorInstancer.h" -#include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Element.h" +#include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" #include "../../Include/RmlUi/Core/PropertySpecification.h" +#include "../../Include/RmlUi/Core/StyleSheet.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" #include "../../Include/RmlUi/Core/StyleSheetTypes.h" -#include "../../Include/RmlUi/Core/StyleSheet.h" #include "../../Include/RmlUi/Core/Transform.h" #include "../../Include/RmlUi/Core/TransformPrimitive.h" #include "ElementStyle.h" @@ -59,10 +59,10 @@ static Colourf ColourToLinearSpace(Colourb c) static Colourb ColourFromLinearSpace(Colourf c) { Colourb result; - result.red = (byte)Math::Clamp(Math::SquareRoot(c.red)*255.f, 0.0f, 255.f); - result.green = (byte)Math::Clamp(Math::SquareRoot(c.green)*255.f, 0.0f, 255.f); - result.blue = (byte)Math::Clamp(Math::SquareRoot(c.blue)*255.f, 0.0f, 255.f); - result.alpha = (byte)Math::Clamp(c.alpha*255.f, 0.0f, 255.f); + result.red = (byte)Math::Clamp(Math::SquareRoot(c.red) * 255.f, 0.0f, 255.f); + result.green = (byte)Math::Clamp(Math::SquareRoot(c.green) * 255.f, 0.0f, 255.f); + result.blue = (byte)Math::Clamp(Math::SquareRoot(c.blue) * 255.f, 0.0f, 255.f); + result.alpha = (byte)Math::Clamp(c.alpha * 255.f, 0.0f, 255.f); return result; } @@ -88,8 +88,7 @@ static bool CombineAndDecompose(Transform& t, Element& e) return true; } - -static Property InterpolateProperties(const Property & p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition) +static Property InterpolateProperties(const Property& p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition) { if ((p0.unit & Property::NUMBER_LENGTH_PERCENT) && (p1.unit & Property::NUMBER_LENGTH_PERCENT)) { @@ -100,7 +99,7 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f float f0 = p0.value.Get(); float f1 = p1.value.Get(); float f = (1.0f - alpha) * f0 + alpha * f1; - return Property{ f, p0.unit }; + return Property{f, p0.unit}; } else { @@ -108,14 +107,14 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f float f0 = element.GetStyle()->ResolveLength(&p0, definition->GetRelativeTarget()); float f1 = element.GetStyle()->ResolveLength(&p1, definition->GetRelativeTarget()); float f = (1.0f - alpha) * f0 + alpha * f1; - return Property{ f, Property::PX }; + return Property{f, Property::PX}; } } if (p0.unit == Property::KEYWORD && p1.unit == Property::KEYWORD) { // Discrete interpolation, swap at alpha = 0.5. - // Special case for the 'visibility' property as in the CSS specs: + // Special case for the 'visibility' property as in the CSS specs: // Apply the visible property if present during the entire transition period, ie. alpha (0,1). if (definition && definition->GetId() == PropertyId::Visibility) { @@ -135,7 +134,7 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f Colourf c = c0 * (1.0f - alpha) + c1 * alpha; - return Property{ ColourFromLinearSpace(c), Property::COLOUR }; + return Property{ColourFromLinearSpace(c), Property::COLOUR}; } if (p0.unit == Property::TRANSFORM && p1.unit == Property::TRANSFORM) @@ -149,7 +148,7 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f if (prim0.size() != prim1.size()) { RMLUI_ERRORMSG("Transform primitives not of same size during interpolation. Were the transforms properly prepared for interpolation?"); - return Property{ t0, Property::TRANSFORM }; + return Property{t0, Property::TRANSFORM}; } // Build the new, interpolating transform @@ -162,38 +161,39 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f if (!TransformUtilities::InterpolateWith(p, prim1[i], alpha)) { RMLUI_ERRORMSG("Transform primitives can not be interpolated. Were the transforms properly prepared for interpolation?"); - return Property{ t0, Property::TRANSFORM }; + return Property{t0, Property::TRANSFORM}; } t->AddPrimitive(p); } - return Property{ TransformPtr(std::move(t)), Property::TRANSFORM }; + return Property{TransformPtr(std::move(t)), Property::TRANSFORM}; } if (p0.unit == Property::DECORATOR && p1.unit == Property::DECORATOR) { auto DiscreteInterpolation = [&]() { return alpha < 0.5f ? p0 : p1; }; - - // We construct DecoratorDeclarationView from declaration if it has instancer, otherwise we look for DecoratorSpecification and return DecoratorDeclarationView from it + + // We construct DecoratorDeclarationView from declaration if it has instancer, otherwise we look for DecoratorSpecification and return + // DecoratorDeclarationView from it auto GetDecoratorDeclarationView = [&](const DecoratorDeclaration& declaration) -> DecoratorDeclarationView { if (declaration.instancer) - return DecoratorDeclarationView{ declaration }; + return DecoratorDeclarationView{declaration}; const StyleSheet* style_sheet = element.GetStyleSheet(); if (!style_sheet) { Log::Message(Log::LT_WARNING, "Failed to get element stylesheet for '%s' decorator rule.", declaration.type.c_str()); - return DecoratorDeclarationView{ declaration }; + return DecoratorDeclarationView{declaration}; } const DecoratorSpecification* specification = style_sheet->GetDecoratorSpecification(declaration.type); if (!specification) { Log::Message(Log::LT_WARNING, "Could not find DecoratorSpecification for '%s' decorator rule.", declaration.type.c_str()); - return DecoratorDeclarationView{ declaration }; + return DecoratorDeclarationView{declaration}; } - return DecoratorDeclarationView{ specification }; + return DecoratorDeclarationView{specification}; }; auto& ptr0 = p0.value.GetReference(); @@ -215,8 +215,8 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f // Interpolate decorators that have common types. for (size_t i = 0; i < small.size(); i++) { - DecoratorDeclarationView d0_view{ GetDecoratorDeclarationView(ptr0->list[i]) }; - DecoratorDeclarationView d1_view{ GetDecoratorDeclarationView(ptr1->list[i]) }; + DecoratorDeclarationView d0_view{GetDecoratorDeclarationView(ptr0->list[i])}; + DecoratorDeclarationView d1_view{GetDecoratorDeclarationView(ptr1->list[i])}; if (!d0_view.instancer || !d1_view.instancer) return DiscreteInterpolation(); @@ -228,7 +228,7 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f return DiscreteInterpolation(); } - decorator->list.push_back(DecoratorDeclaration{ d0_view.type, d0_view.instancer, PropertyDictionary() }); + decorator->list.push_back(DecoratorDeclaration{d0_view.type, d0_view.instancer, PropertyDictionary()}); PropertyDictionary& props = decorator->list.back().properties; const auto& props0 = d0_view.properties.GetProperties(); @@ -256,12 +256,12 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f // Append any trailing decorators from the largest list and interpolate against the default values of its type. for (size_t i = small.size(); i < big.size(); i++) { - DecoratorDeclarationView dbig_view{ GetDecoratorDeclarationView(big[i]) }; + DecoratorDeclarationView dbig_view{GetDecoratorDeclarationView(big[i])}; if (!dbig_view.instancer) return DiscreteInterpolation(); - decorator->list.push_back(DecoratorDeclaration{ dbig_view.type, dbig_view.instancer, PropertyDictionary() }); + decorator->list.push_back(DecoratorDeclaration{dbig_view.type, dbig_view.instancer, PropertyDictionary()}); DecoratorDeclaration& d_new = decorator->list.back(); const PropertySpecification& specification = d_new.instancer->GetPropertySpecification(); @@ -285,16 +285,13 @@ static Property InterpolateProperties(const Property & p0, const Property& p1, f } } - return Property{ DecoratorsPtr(std::move(decorator)), Property::DECORATOR }; + return Property{DecoratorsPtr(std::move(decorator)), Property::DECORATOR}; } // Fall back to discrete interpolation for incompatible units. return alpha < 0.5f ? p0 : p1; } - - - enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 }; static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element) @@ -342,10 +339,10 @@ static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, // Requirement: The small set must match types in the same order they appear in the big set. // Example: (letter indicates type, number represents values) // big: a0 b0 c0 b1 - // ^ ^ - // small: b2 b3 + // ^ ^ + // small: b2 b3 // ^ ^ - // new small: a1 b2 c1 b3 + // new small: a1 b2 c1 b3 bool prims0_smallest = (prims0.size() < prims1.size()); auto& small = (prims0_smallest ? prims0 : prims1); @@ -388,7 +385,6 @@ static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, break; } - if (match_success) { // Success, insert the missing primitives into the small set @@ -417,9 +413,8 @@ static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, } } - // If we get here, things get tricky. Need to do full matrix interpolation. - // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components. + // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components. // Then, during update, interpolate these components and combine into a new transform matrix. if (!CombineAndDecompose(t0, element)) return PrepareTransformResult::Invalid; @@ -429,7 +424,6 @@ static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, return PrepareTransformResult::ChangedT0andT1; } - static bool PrepareTransforms(Vector& keys, Element& element, int start_index) { bool result = true; @@ -487,7 +481,7 @@ static bool PrepareTransforms(Vector& keys, Element& element, int auto& prop0 = keys[i - 1].property; auto& prop1 = keys[i].property; - if(prop0.unit != Property::TRANSFORM || prop1.unit != Property::TRANSFORM) + if (prop0.unit != Property::TRANSFORM || prop1.unit != Property::TRANSFORM) return false; auto& t0 = prop0.value.GetReference(); @@ -524,7 +518,6 @@ static void PrepareDecorator(AnimationKey& key) property.value = MakeShared(); } - ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element, double start_world_time, float duration, int num_iterations, bool alternate_direction) : property_id(property_id), @@ -533,15 +526,16 @@ ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigi { if (!current_value.definition) { - Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').", current_value.ToString().c_str()); + Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').", + current_value.ToString().c_str()); } InternalAddKey(0.0f, current_value, element, Tween{}); } - bool ElementAnimation::InternalAddKey(float time, const Property& in_property, Element& element, Tween tween) { - int valid_properties = (Property::NUMBER_LENGTH_PERCENT | Property::ANGLE | Property::COLOUR | Property::TRANSFORM | Property::KEYWORD | Property::DECORATOR); + int valid_properties = + (Property::NUMBER_LENGTH_PERCENT | Property::ANGLE | Property::COLOUR | Property::TRANSFORM | Property::KEYWORD | Property::DECORATOR); if (!(in_property.unit & valid_properties)) { @@ -570,8 +564,7 @@ bool ElementAnimation::InternalAddKey(float time, const Property& in_property, E return result; } - -bool ElementAnimation::AddKey(float target_time, const Property & in_property, Element& element, Tween tween, bool extend_duration) +bool ElementAnimation::AddKey(float target_time, const Property& in_property, Element& element, Tween tween, bool extend_duration) { if (!IsInitalized()) { @@ -609,7 +602,8 @@ float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_ke } } - if (key1 < 0) key1 = (int)keys.size() - 1; + if (key1 < 0) + key1 = (int)keys.size() - 1; key0 = (key1 == 0 ? 0 : key1 - 1); } @@ -631,14 +625,14 @@ float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_ke alpha = keys[key1].tween(alpha); - if (out_key0) *out_key0 = key0; - if (out_key1) *out_key1 = key1; + if (out_key0) + *out_key0 = key0; + if (out_key1) + *out_key1 = key1; return alpha; } - - Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element) { float dt = float(world_time - last_update_world_time); @@ -675,9 +669,8 @@ Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& elem float alpha = GetInterpolationFactorAndKeys(&key0, &key1); Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition); - + return result; } - } // namespace Rml diff --git a/Source/Core/ElementAnimation.h b/Source/Core/ElementAnimation.h index 8e0312e8f..14a7fd572 100644 --- a/Source/Core/ElementAnimation.h +++ b/Source/Core/ElementAnimation.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -37,9 +37,9 @@ namespace Rml { struct AnimationKey { AnimationKey(float time, const Property& property, Tween tween) : time(time), property(property), tween(tween) {} - float time; // Local animation time (Zero means the time when the animation iteration starts) + float time; // Local animation time (Zero means the time when the animation iteration starts) Property property; - Tween tween; // Tweening between the previous and this key. Ignored for the first animation key. + Tween tween; // Tweening between the previous and this key. Ignored for the first animation key. }; // The origin is tracked for determining its behavior when adding and removing animations. @@ -48,8 +48,7 @@ struct AnimationKey { // Transition: Animation started by the 'transition' property enum class ElementAnimationOrigin : uint8_t { User, Animation, Transition }; -class ElementAnimation -{ +class ElementAnimation { private: PropertyId property_id = PropertyId::Invalid; @@ -73,10 +72,10 @@ class ElementAnimation public: ElementAnimation() {} - ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element, - double start_world_time, float duration, int num_iterations, bool alternate_direction); + ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element, double start_world_time, + float duration, int num_iterations, bool alternate_direction); - bool AddKey(float target_time, const Property & property, Element & element, Tween tween, bool extend_duration); + bool AddKey(float target_time, const Property& property, Element& element, Tween tween, bool extend_duration); Property UpdateAndGetProperty(double time, Element& element); @@ -89,6 +88,5 @@ class ElementAnimation ElementAnimationOrigin GetOrigin() const { return origin; } }; - } // namespace Rml #endif diff --git a/Source/Core/ElementBackgroundBorder.cpp b/Source/Core/ElementBackgroundBorder.cpp index a39dd7bba..09663f88c 100644 --- a/Source/Core/ElementBackgroundBorder.cpp +++ b/Source/Core/ElementBackgroundBorder.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,9 @@ namespace Rml { +ElementBackgroundBorder::ElementBackgroundBorder(Element* element) : geometry(element) {} -ElementBackgroundBorder::ElementBackgroundBorder(Element* element) : geometry(element) -{} - -void ElementBackgroundBorder::Render(Element * element) +void ElementBackgroundBorder::Render(Element* element) { if (background_dirty || border_dirty) { @@ -73,7 +71,7 @@ void ElementBackgroundBorder::GenerateGeometry(Element* element) computed.border_bottom_color(), computed.border_left_color(), }; - + // Apply opacity const float opacity = computed.opacity(); background_color.alpha = (byte)(opacity * (float)background_color.alpha); diff --git a/Source/Core/ElementBackgroundBorder.h b/Source/Core/ElementBackgroundBorder.h index fc8162ef6..0c370a013 100644 --- a/Source/Core/ElementBackgroundBorder.h +++ b/Source/Core/ElementBackgroundBorder.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_ELEMENTBACKGROUNDBORDER_H #define RMLUI_CORE_ELEMENTBACKGROUNDBORDER_H -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/Geometry.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { diff --git a/Source/Core/ElementDecoration.cpp b/Source/Core/ElementDecoration.cpp index 03057c2a0..a7bcdf88b 100644 --- a/Source/Core/ElementDecoration.cpp +++ b/Source/Core/ElementDecoration.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,16 +29,15 @@ #include "ElementDecoration.h" #include "../../Include/RmlUi/Core/ComputedValues.h" #include "../../Include/RmlUi/Core/Decorator.h" +#include "../../Include/RmlUi/Core/DecoratorInstancer.h" #include "../../Include/RmlUi/Core/Element.h" #include "../../Include/RmlUi/Core/ElementDocument.h" #include "../../Include/RmlUi/Core/Profiling.h" -#include "../../Include/RmlUi/Core/DecoratorInstancer.h" #include "../../Include/RmlUi/Core/StyleSheet.h" namespace Rml { -ElementDecoration::ElementDecoration(Element* _element) : element(_element) -{} +ElementDecoration::ElementDecoration(Element* _element) : element(_element) {} ElementDecoration::~ElementDecoration() { @@ -55,7 +54,6 @@ void ElementDecoration::InstanceDecorators() } } -// Releases existing decorators and loads all decorators required by the element's definition. bool ElementDecoration::ReloadDecorators() { RMLUI_ZoneScopedC(0xB22222); @@ -105,7 +103,6 @@ bool ElementDecoration::ReloadDecorators() return true; } -// Loads a single decorator and adds it to the list of loaded decorators for this element. void ElementDecoration::ReloadDecoratorsData() { if (decorators_data_dirty) @@ -122,7 +119,6 @@ void ElementDecoration::ReloadDecoratorsData() } } -// Releases all existing decorators and frees their data. void ElementDecoration::ReleaseDecorators() { for (DecoratorHandle& decorator : decorators) @@ -134,7 +130,6 @@ void ElementDecoration::ReleaseDecorators() decorators.clear(); } - void ElementDecoration::RenderDecorators() { InstanceDecorators(); diff --git a/Source/Core/ElementDecoration.h b/Source/Core/ElementDecoration.h index 2d72409c3..5b27f5689 100644 --- a/Source/Core/ElementDecoration.h +++ b/Source/Core/ElementDecoration.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ class Decorator; class Element; /** - Manages an elements decorator state + Manages an elements decorator state - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class ElementDecoration -{ +class ElementDecoration { public: /// Constructor /// @param element The element this decorator with acting on @@ -69,13 +68,12 @@ class ElementDecoration // Releases all existing decorators and frees their data. void ReleaseDecorators(); - struct DecoratorHandle - { + struct DecoratorHandle { SharedPtr decorator; DecoratorDataHandle decorator_data; }; - using DecoratorHandleList = Vector< DecoratorHandle >; + using DecoratorHandleList = Vector; // The element this decorator belongs to Element* element; diff --git a/Source/Core/ElementDefinition.cpp b/Source/Core/ElementDefinition.cpp index accfc4a8d..2c6a69d10 100644 --- a/Source/Core/ElementDefinition.cpp +++ b/Source/Core/ElementDefinition.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,12 +27,12 @@ */ #include "ElementDefinition.h" -#include "StyleSheetNode.h" #include "../../Include/RmlUi/Core/PropertyIdSet.h" +#include "StyleSheetNode.h" namespace Rml { -ElementDefinition::ElementDefinition(const Vector< const StyleSheetNode* >& style_sheet_nodes) +ElementDefinition::ElementDefinition(const Vector& style_sheet_nodes) { // Initialises the element definition from the list of style sheet nodes. for (size_t i = 0; i < style_sheet_nodes.size(); ++i) diff --git a/Source/Core/ElementDefinition.h b/Source/Core/ElementDefinition.h index 990ea6f44..712c6a80d 100644 --- a/Source/Core/ElementDefinition.h +++ b/Source/Core/ElementDefinition.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,15 +39,14 @@ class StyleSheetNode; class ElementDefinitionIterator; /** - ElementDefinition provides an element's applicable properties from its stylesheet. + ElementDefinition provides an element's applicable properties from its stylesheet. - @author Peter Curry + @author Peter Curry */ -class ElementDefinition : public NonCopyMoveable -{ +class ElementDefinition : public NonCopyMoveable { public: - ElementDefinition(const Vector< const StyleSheetNode* >& style_sheet_nodes); + ElementDefinition(const Vector& style_sheet_nodes); /// Returns a specific property from the element definition. /// @param[in] id The id of the property to return. diff --git a/Source/Core/ElementDocument.cpp b/Source/Core/ElementDocument.cpp index 971635f5e..587bf04e3 100644 --- a/Source/Core/ElementDocument.cpp +++ b/Source/Core/ElementDocument.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -61,9 +61,7 @@ ElementDocument::ElementDocument(const String& tag) : Element(tag) SetProperty(PropertyId::Position, Property(Style::Position::Absolute)); } -ElementDocument::~ElementDocument() -{ -} +ElementDocument::~ElementDocument() {} void ElementDocument::ProcessHeader(const DocumentHeader* document_header) { @@ -79,7 +77,7 @@ void ElementDocument::ProcessHeader(const DocumentHeader* document_header) // Merge in any templates, note a merge may cause more templates to merge for (size_t i = 0; i < header.template_resources.size(); i++) { - Template* merge_template = TemplateCache::LoadTemplate(URL(header.template_resources[i]).GetURL()); + Template* merge_template = TemplateCache::LoadTemplate(URL(header.template_resources[i]).GetURL()); if (merge_template) header.MergeHeader(*merge_template->GetHeader()); @@ -158,13 +156,11 @@ void ElementDocument::ProcessHeader(const DocumentHeader* document_header) UpdateProperties(dp_ratio, vp_dimensions); } -// Returns the document's context. Context* ElementDocument::GetContext() { return context; } -// Sets the document's title. void ElementDocument::SetTitle(const String& _title) { title = _title; @@ -180,7 +176,6 @@ const String& ElementDocument::GetSourceURL() const return source_url; } -// Returns the document's style sheet. const StyleSheet* ElementDocument::GetStyleSheet() const { if (style_sheet_container) @@ -188,13 +183,11 @@ const StyleSheet* ElementDocument::GetStyleSheet() const return nullptr; } -// Returns the document's style sheet container. const StyleSheetContainer* ElementDocument::GetStyleSheetContainer() const { return style_sheet_container.get(); } -// Sets the style sheet this document, and all of its children, uses. void ElementDocument::SetStyleSheetContainer(SharedPtr _style_sheet_container) { RMLUI_ZoneScoped; @@ -207,7 +200,6 @@ void ElementDocument::SetStyleSheetContainer(SharedPtr _sty DirtyMediaQueries(); } -// Reload the document's style sheet from source files. void ElementDocument::ReloadStyleSheet() { if (!context) @@ -223,7 +215,8 @@ void ElementDocument::ReloadStyleSheet() Factory::ClearStyleSheetCache(); Factory::ClearTemplateCache(); ElementPtr temp_doc = Factory::InstanceDocumentStream(nullptr, stream.get(), context->GetDocumentsBaseTag()); - if (!temp_doc) { + if (!temp_doc) + { Log::Message(Log::LT_WARNING, "Failed to reload style sheet, could not instance document: %s", source_url.c_str()); return; } @@ -245,14 +238,12 @@ void ElementDocument::DirtyMediaQueries() } } -// Brings the document to the front of the document stack. void ElementDocument::PullToFront() { if (context != nullptr) context->PullDocumentToFront(this); } -// Sends the document to the back of the document stack. void ElementDocument::PushToBack() { if (context != nullptr) @@ -263,8 +254,8 @@ void ElementDocument::Show(ModalFlag modal_flag, FocusFlag focus_flag) { switch (modal_flag) { - case ModalFlag::None: modal = false; break; - case ModalFlag::Modal: modal = true; break; + case ModalFlag::None: modal = false; break; + case ModalFlag::Modal: modal = true; break; case ModalFlag::Keep: break; } @@ -274,11 +265,8 @@ void ElementDocument::Show(ModalFlag modal_flag, FocusFlag focus_flag) switch (focus_flag) { - case FocusFlag::None: - break; - case FocusFlag::Document: - focus = true; - break; + case FocusFlag::None: break; + case FocusFlag::Document: focus = true; break; case FocusFlag::Keep: focus = true; focus_previous = true; @@ -291,7 +279,7 @@ void ElementDocument::Show(ModalFlag modal_flag, FocusFlag focus_flag) // Set to visible and switch focus if necessary SetProperty(PropertyId::Visibility, Property(Style::Visibility::Visible)); - + // We should update the document now, otherwise the focusing methods below do not think we are visible // If this turns out to be slow, the more performant approach is just to compute the new visibility property UpdateDocument(); @@ -341,14 +329,13 @@ void ElementDocument::Hide() UpdateDocument(); DispatchEvent(EventId::Hide, Dictionary()); - + if (context) { context->UnfocusDocument(this); } } -// Close this document void ElementDocument::Close() { if (context != nullptr) @@ -360,7 +347,6 @@ ElementPtr ElementDocument::CreateElement(const String& name) return Factory::InstanceElement(nullptr, name, name, XMLAttributes()); } -// Create a text element. ElementPtr ElementDocument::CreateTextNode(const String& text) { // Create the element. @@ -372,40 +358,28 @@ ElementPtr ElementDocument::CreateTextNode(const String& text) } // Cast up - ElementText* element_text = rmlui_dynamic_cast< ElementText* >(element.get()); + ElementText* element_text = rmlui_dynamic_cast(element.get()); if (!element_text) { Log::Message(Log::LT_ERROR, "Failed to create text element, instancer didn't return a derivative of ElementText."); return nullptr; } - + // Set the text element_text->SetText(text); return element; } -// Is the current document modal bool ElementDocument::IsModal() const { return modal && IsVisible(); } -// Default load inline script implementation -void ElementDocument::LoadInlineScript(const String& RMLUI_UNUSED_PARAMETER(content), const String& RMLUI_UNUSED_PARAMETER(source_path), int RMLUI_UNUSED_PARAMETER(line)) -{ - RMLUI_UNUSED(content); - RMLUI_UNUSED(source_path); - RMLUI_UNUSED(line); -} +void ElementDocument::LoadInlineScript(const String& /*content*/, const String& /*source_path*/, int /*line*/) {} -// Default load external script implementation -void ElementDocument::LoadExternalScript(const String& RMLUI_UNUSED_PARAMETER(source_path)) -{ - RMLUI_UNUSED(source_path); -} +void ElementDocument::LoadExternalScript(const String& /*source_path*/) {} -// Updates the document, including its layout void ElementDocument::UpdateDocument() { const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f); @@ -415,12 +389,11 @@ void ElementDocument::UpdateDocument() UpdatePosition(); } -// Updates the layout if necessary. void ElementDocument::UpdateLayout() { // Note: Carefully consider when to call this function for performance reasons. // Ideally, only called once per update loop. - if(layout_dirty) + if (layout_dirty) { RMLUI_ZoneScoped; RMLUI_ZoneText(source_url.c_str(), source_url.size()); @@ -437,7 +410,6 @@ void ElementDocument::UpdateLayout() } } -// Updates the position of the document based on the style properties. void ElementDocument::UpdatePosition() { if (position_dirty) @@ -499,7 +471,6 @@ void ElementDocument::DirtyVwAndVhProperties() GetStyle()->DirtyPropertiesWithUnitsRecursive(Property::VW | Property::VH); } -// Repositions the document if necessary. void ElementDocument::OnPropertyChange(const PropertyIdSet& changed_properties) { Element::OnPropertyChange(changed_properties); @@ -508,14 +479,13 @@ void ElementDocument::OnPropertyChange(const PropertyIdSet& changed_properties) if (changed_properties.Contains(PropertyId::FontSize)) GetStyle()->DirtyPropertiesWithUnitsRecursive(Property::REM); - if (changed_properties.Contains(PropertyId::Top) || - changed_properties.Contains(PropertyId::Right) || - changed_properties.Contains(PropertyId::Bottom) || + if (changed_properties.Contains(PropertyId::Top) || // + changed_properties.Contains(PropertyId::Right) || // + changed_properties.Contains(PropertyId::Bottom) || // changed_properties.Contains(PropertyId::Left)) DirtyPosition(); } -// Processes the 'onpropertychange' event, checking for a change in position or size. void ElementDocument::ProcessDefaultAction(Event& event) { Element::ProcessDefaultAction(event); @@ -530,7 +500,7 @@ void ElementDocument::ProcessDefaultAction(Event& event) { if (Element* element = FindNextTabElement(event.GetTargetElement(), !event.GetParameter("shift_key", false))) { - if(element->Focus()) + if (element->Focus()) { element->ScrollIntoView(false); event.StopPropagation(); @@ -538,8 +508,7 @@ void ElementDocument::ProcessDefaultAction(Event& event) } } // Process ENTER being pressed on a focusable object (emulate click) - else if (key_identifier == Input::KI_RETURN || - key_identifier == Input::KI_NUMPADENTER) + else if (key_identifier == Input::KI_RETURN || key_identifier == Input::KI_NUMPADENTER) { Element* focus_node = GetFocusLeafNode(); @@ -574,14 +543,12 @@ static CanFocus CanFocusElement(Element* element) return CanFocus::No; } -// Find the next element to focus, starting at the current element -// -// This algorithm is quite sneaky, I originally thought a depth first search would -// work, but it appears not. What is required is to cut the tree in half along the nodes -// from current_element up the root and then either traverse the tree in a clockwise or -// anticlock wise direction depending if you're searching forward or backward respectively Element* ElementDocument::FindNextTabElement(Element* current_element, bool forward) { + // This algorithm is quite sneaky, I originally thought a depth first search would work, but it appears not. What is + // required is to cut the tree in half along the nodes from current_element up the root and then either traverse the + // tree in a clockwise or anticlock wise direction depending if you're searching forward or backward respectively. + // If we're searching forward, check the immediate children of this node first off. if (forward) { @@ -608,7 +575,7 @@ Element* ElementDocument::FindNextTabElement(Element* current_element, bool forw // Do a search if its enabled if (search_enabled) - if(Element* result = SearchFocusSubtree(search_child, forward)) + if (Element* result = SearchFocusSubtree(search_child, forward)) return result; // Enable searching when we reach the child. @@ -654,7 +621,7 @@ Element* ElementDocument::SearchFocusSubtree(Element* element, bool forward) int child_index = i; if (!forward) child_index = element->GetNumChildren() - i - 1; - if (Element * result = SearchFocusSubtree(element->GetChild(child_index), forward)) + if (Element* result = SearchFocusSubtree(element->GetChild(child_index), forward)) return result; } diff --git a/Source/Core/ElementHandle.cpp b/Source/Core/ElementHandle.cpp index 416b4ed25..ef73e9720 100644 --- a/Source/Core/ElementHandle.cpp +++ b/Source/Core/ElementHandle.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,8 +30,8 @@ #include "../../Include/RmlUi/Core/ComputedValues.h" #include "../../Include/RmlUi/Core/ElementDocument.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" -#include "../../Include/RmlUi/Core/Property.h" #include "../../Include/RmlUi/Core/Event.h" +#include "../../Include/RmlUi/Core/Property.h" namespace Rml { @@ -45,17 +45,14 @@ ElementHandle::ElementHandle(const String& tag) : Element(tag), drag_start(0, 0) initialised = false; } -ElementHandle::~ElementHandle() -{ -} +ElementHandle::~ElementHandle() {} void ElementHandle::OnAttributeChange(const ElementAttributes& changed_attributes) { Element::OnAttributeChange(changed_attributes); // Reset initialised state if the move or size targets have changed. - if (changed_attributes.find("move_target") != changed_attributes.end() || - changed_attributes.find("size_target") != changed_attributes.end()) + if (changed_attributes.find("move_target") != changed_attributes.end() || changed_attributes.find("size_target") != changed_attributes.end()) { initialised = false; move_target = nullptr; diff --git a/Source/Core/ElementHandle.h b/Source/Core/ElementHandle.h index 401d2dde2..b2882df91 100644 --- a/Source/Core/ElementHandle.h +++ b/Source/Core/ElementHandle.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,21 +29,20 @@ #ifndef RMLUI_CORE_ELEMENTHANDLE_H #define RMLUI_CORE_ELEMENTHANDLE_H -#include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Element.h" +#include "../../Include/RmlUi/Core/Header.h" namespace Rml { /** - A derivation of an element for use as a mouse handle. A handle is designed to be instanced and attached as a non- - DOM element to a window-style element, and listened to for movement events which can be responsed to to move or - resize the element as appropriate. + A derivation of an element for use as a mouse handle. A handle is designed to be instanced and attached as a non- + DOM element to a window-style element, and listened to for movement events which can be responsed to to move or + resize the element as appropriate. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementHandle : public Element -{ +class RMLUICORE_API ElementHandle : public Element { public: RMLUI_RTTI_DefineWithParent(ElementHandle, Element) diff --git a/Source/Core/ElementInstancer.cpp b/Source/Core/ElementInstancer.cpp index 0a2b87d66..30d65aa35 100644 --- a/Source/Core/ElementInstancer.cpp +++ b/Source/Core/ElementInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,18 +28,15 @@ #include "../../Include/RmlUi/Core/ElementInstancer.h" #include "../../Include/RmlUi/Core/ElementText.h" -#include "XMLParseTools.h" #include "Pool.h" +#include "XMLParseTools.h" namespace Rml { -ElementInstancer::~ElementInstancer() -{ -} - -static Pool< Element > pool_element(200, true); -static Pool< ElementText > pool_text_default(200, true); +ElementInstancer::~ElementInstancer() {} +static Pool pool_element(200, true); +static Pool pool_text_default(200, true); ElementPtr ElementInstancerElement::InstanceElement(Element* /*parent*/, const String& tag, const XMLAttributes& /*attributes*/) { diff --git a/Source/Core/ElementScroll.cpp b/Source/Core/ElementScroll.cpp index 543aa8bcd..1219777b2 100644 --- a/Source/Core/ElementScroll.cpp +++ b/Source/Core/ElementScroll.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,10 +44,8 @@ ElementScroll::ElementScroll(Element* _element) corner = nullptr; } -ElementScroll::~ElementScroll() -{} +ElementScroll::~ElementScroll() {} -// Updates the increment / decrement arrows. void ElementScroll::Update() { for (int i = 0; i < 2; i++) @@ -57,7 +55,6 @@ void ElementScroll::Update() } } -// Enables and sizes one of the scrollbars. void ElementScroll::EnableScrollbar(Orientation orientation, float element_width) { if (!scrollbars[orientation].enabled) @@ -76,15 +73,13 @@ void ElementScroll::EnableScrollbar(Orientation orientation, float element_width if (orientation == HORIZONTAL) { if (box.GetSize().y < 0) - scrollbars[orientation].size = box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + - box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT) + - ResolveValue(scrollbars[orientation].element->GetComputedValues().height(), element_width); + scrollbars[orientation].size = box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT) + + ResolveValue(scrollbars[orientation].element->GetComputedValues().height(), element_width); else scrollbars[orientation].size = box.GetSize(Box::MARGIN).y; } } -// Disables and hides one of the scrollbars. void ElementScroll::DisableScrollbar(Orientation orientation) { if (scrollbars[orientation].enabled) @@ -97,7 +92,6 @@ void ElementScroll::DisableScrollbar(Orientation orientation) } } -// Updates the position of the scrollbar. void ElementScroll::UpdateScrollbar(Orientation orientation) { float bar_position; @@ -127,13 +121,11 @@ void ElementScroll::UpdateScrollbar(Orientation orientation) } } -// Returns one of the scrollbar elements. Element* ElementScroll::GetScrollbar(Orientation orientation) { return scrollbars[orientation].element; } -// Returns the size, in pixels, of one of the scrollbars; for a vertical scrollbar, this is width, for a horizontal scrollbar, this is height. float ElementScroll::GetScrollbarSize(Orientation orientation) { if (!scrollbars[orientation].enabled) @@ -142,7 +134,6 @@ float ElementScroll::GetScrollbarSize(Orientation orientation) return scrollbars[orientation].size; } -// Formats the enabled scrollbars based on the current size of the host element. void ElementScroll::FormatScrollbars() { const Box& element_box = element->GetBox(); @@ -185,7 +176,9 @@ void ElementScroll::FormatScrollbars() int variable_axis = i == VERTICAL ? 0 : 1; Vector2f offset = element_box.GetPosition(Box::PADDING); - offset[variable_axis] += containing_block[variable_axis] - (scrollbars[i].element->GetBox().GetSize(Box::BORDER)[variable_axis] + scrollbars[i].element->GetBox().GetEdge(Box::MARGIN, i == VERTICAL ? Box::RIGHT : Box::BOTTOM)); + offset[variable_axis] += containing_block[variable_axis] - + (scrollbars[i].element->GetBox().GetSize(Box::BORDER)[variable_axis] + + scrollbars[i].element->GetBox().GetEdge(Box::MARGIN, i == VERTICAL ? Box::RIGHT : Box::BOTTOM)); // Add the top or left margin (as appropriate) onto the scrollbar's position. offset[1 - variable_axis] += scrollbars[i].element->GetBox().GetEdge(Box::MARGIN, i == VERTICAL ? Box::TOP : Box::LEFT); scrollbars[i].element->SetOffset(offset, element, true); @@ -199,20 +192,20 @@ void ElementScroll::FormatScrollbars() Box corner_box; corner_box.SetContent(Vector2f(scrollbars[VERTICAL].size, scrollbars[HORIZONTAL].size)); corner->SetBox(corner_box); - corner->SetOffset(containing_block + element_box.GetPosition(Box::PADDING) - Vector2f(scrollbars[VERTICAL].size, scrollbars[HORIZONTAL].size), element, true); + corner->SetOffset(containing_block + element_box.GetPosition(Box::PADDING) - Vector2f(scrollbars[VERTICAL].size, scrollbars[HORIZONTAL].size), + element, true); corner->SetProperty(PropertyId::Visibility, Property(Style::Visibility::Visible)); } } -// Creates one of the scroll component's scrollbar. bool ElementScroll::CreateScrollbar(Orientation orientation) { - if (scrollbars[orientation].element && - scrollbars[orientation].widget) + if (scrollbars[orientation].element && scrollbars[orientation].widget) return true; - - ElementPtr scrollbar_element = Factory::InstanceElement(element, "*", orientation == VERTICAL ? "scrollbarvertical" : "scrollbarhorizontal", XMLAttributes()); + + ElementPtr scrollbar_element = + Factory::InstanceElement(element, "*", orientation == VERTICAL ? "scrollbarvertical" : "scrollbarhorizontal", XMLAttributes()); scrollbars[orientation].element = scrollbar_element.get(); scrollbars[orientation].element->SetProperty(PropertyId::Clip, Property(1, Property::NUMBER)); @@ -226,7 +219,6 @@ bool ElementScroll::CreateScrollbar(Orientation orientation) return true; } -// Creates the scrollbar corner. bool ElementScroll::CreateCorner() { if (corner != nullptr) @@ -255,10 +247,8 @@ void ElementScroll::UpdateScrollElementProperties(Element* scroll_element) scroll_element->Update(dp_ratio, vp_dimensions); } -ElementScroll::Scrollbar::Scrollbar() -{} +ElementScroll::Scrollbar::Scrollbar() {} -ElementScroll::Scrollbar::~Scrollbar() -{} +ElementScroll::Scrollbar::~Scrollbar() {} } // namespace Rml diff --git a/Source/Core/ElementStyle.cpp b/Source/Core/ElementStyle.cpp index 1eb1ec964..346c17315 100644 --- a/Source/Core/ElementStyle.cpp +++ b/Source/Core/ElementStyle.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,24 +35,22 @@ #include "../../Include/RmlUi/Core/FontEngineInterface.h" #include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/Math.h" +#include "../../Include/RmlUi/Core/Profiling.h" #include "../../Include/RmlUi/Core/Property.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" #include "../../Include/RmlUi/Core/PropertyDictionary.h" #include "../../Include/RmlUi/Core/PropertyIdSet.h" -#include "../../Include/RmlUi/Core/Profiling.h" #include "../../Include/RmlUi/Core/StyleSheet.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" #include "../../Include/RmlUi/Core/TransformPrimitive.h" +#include "ComputeProperty.h" #include "ElementDecoration.h" #include "ElementDefinition.h" -#include "ComputeProperty.h" #include "PropertiesIterator.h" #include - namespace Rml { -// Bitwise operations on the PseudoClassState. inline PseudoClassState operator|(PseudoClassState lhs, PseudoClassState rhs) { return PseudoClassState(int(lhs) | int(rhs)); @@ -67,7 +65,6 @@ ElementStyle::ElementStyle(Element* _element) element = _element; } -// Returns one of this element's properties. const Property* ElementStyle::GetLocalProperty(PropertyId id, const PropertyDictionary& inline_properties, const ElementDefinition* definition) { // Check for overriding local properties. @@ -82,8 +79,8 @@ const Property* ElementStyle::GetLocalProperty(PropertyId id, const PropertyDict return nullptr; } -// Returns one of this element's properties. -const Property* ElementStyle::GetProperty(PropertyId id, const Element* element, const PropertyDictionary& inline_properties, const ElementDefinition* definition) +const Property* ElementStyle::GetProperty(PropertyId id, const Element* element, const PropertyDictionary& inline_properties, + const ElementDefinition* definition) { const Property* local_property = GetLocalProperty(id, inline_properties, definition); if (local_property) @@ -112,16 +109,18 @@ const Property* ElementStyle::GetProperty(PropertyId id, const Element* element, return property->GetDefaultValue(); } -// Apply transition to relevant properties if a transition is defined on element. -// Properties that are part of a transition are removed from the properties list. -void ElementStyle::TransitionPropertyChanges(Element* element, PropertyIdSet& properties, const PropertyDictionary& inline_properties, const ElementDefinition* old_definition, const ElementDefinition* new_definition) +void ElementStyle::TransitionPropertyChanges(Element* element, PropertyIdSet& properties, const PropertyDictionary& inline_properties, + const ElementDefinition* old_definition, const ElementDefinition* new_definition) { + // Apply transition to relevant properties if a transition is defined on element. + // Properties that are part of a transition are removed from the properties list. + RMLUI_ASSERT(element); if (!old_definition || !new_definition || properties.Empty()) return; - // We get the local property instead of the computed value here, because we want to intercept property changes even before the computed values are ready. - // Now that we have the concept of computed values, we may want do this operation directly on them instead. + // We get the local property instead of the computed value here, because we want to intercept property changes even before the computed values are + // ready. Now that we have the concept of computed values, we may want do this operation directly on them instead. if (const Property* transition_property = GetLocalProperty(PropertyId::Transition, inline_properties, new_definition)) { if (transition_property->value.GetType() != Variant::TRANSITIONLIST) @@ -145,7 +144,7 @@ void ElementStyle::TransitionPropertyChanges(Element* element, PropertyIdSet& pr if (transition_list.all) { Transition transition = transition_list.transitions[0]; - for (auto it = properties.begin(); it != properties.end(); ) + for (auto it = properties.begin(); it != properties.end();) { transition.id = *it; if (add_transition(transition)) @@ -214,7 +213,6 @@ void ElementStyle::UpdateDefinition() } } -// Sets or removes a pseudo-class on the element. bool ElementStyle::SetPseudoClass(const String& pseudo_class, bool activate, bool override_class) { bool changed = false; @@ -243,7 +241,6 @@ bool ElementStyle::SetPseudoClass(const String& pseudo_class, bool activate, boo return changed; } -// Checks if a specific pseudo-class has been set on the element. bool ElementStyle::IsPseudoClassSet(const String& pseudo_class) const { return (pseudo_classes.count(pseudo_class) == 1); @@ -279,20 +276,17 @@ bool ElementStyle::SetClass(const String& class_name, bool activate) return changed; } -// Checks if a class is set on the element. bool ElementStyle::IsClassSet(const String& class_name) const { return std::find(classes.begin(), classes.end(), class_name) != classes.end(); } -// Specifies the entire list of classes for this element. This will replace any others specified. void ElementStyle::SetClassNames(const String& class_names) { classes.clear(); StringUtilities::ExpandString(classes, class_names, ' '); } -// Returns the list of classes specified for this element. String ElementStyle::GetClassNames() const { String class_names; @@ -313,7 +307,6 @@ const StringList& ElementStyle::GetClassNameList() const return classes; } -// Sets a local property override on the element to a pre-parsed value. bool ElementStyle::SetProperty(PropertyId id, const Property& property) { Property new_property = property; @@ -328,25 +321,20 @@ bool ElementStyle::SetProperty(PropertyId id, const Property& property) return true; } -// Removes a local property override on the element. void ElementStyle::RemoveProperty(PropertyId id) { int size_before = inline_properties.GetNumProperties(); inline_properties.RemoveProperty(id); - if(inline_properties.GetNumProperties() != size_before) + if (inline_properties.GetNumProperties() != size_before) DirtyProperty(id); } - - -// Returns one of this element's properties. const Property* ElementStyle::GetProperty(PropertyId id) const { return GetProperty(id, element, inline_properties, definition.get()); } -// Returns one of this element's properties. const Property* ElementStyle::GetLocalProperty(PropertyId id) const { return GetLocalProperty(id, inline_properties, definition.get()); @@ -411,27 +399,17 @@ float ElementStyle::ResolveLength(const Property* property, RelativeTarget relat switch (relative_target) { - case RelativeTarget::None: - base_value = 1.0f; - break; - case RelativeTarget::ContainingBlockWidth: - base_value = element->GetContainingBlock().x; - break; - case RelativeTarget::ContainingBlockHeight: - base_value = element->GetContainingBlock().y; - break; - case RelativeTarget::FontSize: - base_value = element->GetComputedValues().font_size(); - break; + case RelativeTarget::None: base_value = 1.0f; break; + case RelativeTarget::ContainingBlockWidth: base_value = element->GetContainingBlock().x; break; + case RelativeTarget::ContainingBlockHeight: base_value = element->GetContainingBlock().y; break; + case RelativeTarget::FontSize: base_value = element->GetComputedValues().font_size(); break; case RelativeTarget::ParentFontSize: { auto p = element->GetParentNode(); base_value = (p ? p->GetComputedValues().font_size() : DefaultComputedValues.font_size()); } - break; - case RelativeTarget::LineHeight: - base_value = element->GetLineHeight(); - break; + break; + case RelativeTarget::LineHeight: base_value = element->GetLineHeight(); break; } float scale_value = 0.0f; @@ -439,14 +417,9 @@ float ElementStyle::ResolveLength(const Property* property, RelativeTarget relat switch (property->unit) { case Property::EM: - case Property::NUMBER: - scale_value = property->value.Get< float >(); - break; - case Property::PERCENT: - scale_value = property->value.Get< float >() * 0.01f; - break; - default: - break; + case Property::NUMBER: scale_value = property->value.Get(); break; + case Property::PERCENT: scale_value = property->value.Get() * 0.01f; break; + default: break; } return base_value * scale_value; @@ -480,13 +453,15 @@ void ElementStyle::DirtyPropertiesWithUnitsRecursive(Property::Unit units) element->GetChild(i)->GetStyle()->DirtyPropertiesWithUnitsRecursive(units); } -bool ElementStyle::AnyPropertiesDirty() const +bool ElementStyle::AnyPropertiesDirty() const { - return !dirty_properties.Empty(); + return !dirty_properties.Empty(); } -PropertiesIterator ElementStyle::Iterate() const { - // Note: Value initialized iterators are only guaranteed to compare equal in C++14, and only for iterators satisfying the ForwardIterator requirements. +PropertiesIterator ElementStyle::Iterate() const +{ + // Note: Value initialized iterators are only guaranteed to compare equal in C++14, and only for iterators + // satisfying the ForwardIterator requirements. #ifdef _MSC_VER // Null forward iterator supported since VS 2015 static_assert(_MSC_VER >= 1900, "Visual Studio 2015 or higher required, see comment."); @@ -508,19 +483,18 @@ PropertiesIterator ElementStyle::Iterate() const { return PropertiesIterator(it_style_begin, it_style_end, it_definition, it_definition_end); } -// Sets a single property as dirty. void ElementStyle::DirtyProperty(PropertyId id) { dirty_properties.Insert(id); } -// Sets a list of properties as dirty. void ElementStyle::DirtyProperties(const PropertyIdSet& properties) { dirty_properties |= properties; } -PropertyIdSet ElementStyle::ComputeValues(Style::ComputedValues& values, const Style::ComputedValues* parent_values, const Style::ComputedValues* document_values, bool values_are_default_initialized, float dp_ratio, Vector2f vp_dimensions) +PropertyIdSet ElementStyle::ComputeValues(Style::ComputedValues& values, const Style::ComputedValues* parent_values, + const Style::ComputedValues* document_values, bool values_are_default_initialized, float dp_ratio, Vector2f vp_dimensions) { if (dirty_properties.Empty()) return PropertyIdSet(); @@ -554,13 +528,13 @@ PropertyIdSet ElementStyle::ComputeValues(Style::ComputedValues& values, const S bool dirty_em_properties = false; // Always do font-size first if dirty, because of em-relative values - if(dirty_properties.Contains(PropertyId::FontSize)) + if (dirty_properties.Contains(PropertyId::FontSize)) { if (auto p = GetLocalProperty(PropertyId::FontSize)) values.font_size(ComputeFontsize(*p, values, parent_values, document_values, dp_ratio, vp_dimensions)); else if (parent_values) values.font_size(parent_values->font_size()); - + if (font_size_before != values.font_size()) { dirty_em_properties = true; @@ -614,6 +588,7 @@ PropertyIdSet ElementStyle::ComputeValues(Style::ComputedValues& values, const S using namespace Style; + // clang-format off switch (id) { case PropertyId::MarginTop: @@ -888,6 +863,7 @@ PropertyIdSet ElementStyle::ComputeValues(Style::ComputedValues& values, const S case PropertyId::MaxNumIds: break; } + // clang-format on } // The font-face handle is nulled when local font properties are set. In that case we need to retrieve a new handle. @@ -909,7 +885,7 @@ PropertyIdSet ElementStyle::ComputeValues(Style::ComputedValues& values, const S child->GetStyle()->dirty_properties |= dirty_inherited_properties; } } - + PropertyIdSet result(std::move(dirty_properties)); dirty_properties.Clear(); return result; diff --git a/Source/Core/ElementStyle.h b/Source/Core/ElementStyle.h index a89eb7ed4..12bb2706f 100644 --- a/Source/Core/ElementStyle.h +++ b/Source/Core/ElementStyle.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,9 +30,9 @@ #define RMLUI_CORE_ELEMENTSTYLE_H #include "../../Include/RmlUi/Core/ComputedValues.h" -#include "../../Include/RmlUi/Core/Types.h" -#include "../../Include/RmlUi/Core/PropertyIdSet.h" #include "../../Include/RmlUi/Core/PropertyDictionary.h" +#include "../../Include/RmlUi/Core/PropertyIdSet.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { @@ -41,16 +41,14 @@ class PropertiesIterator; enum class RelativeTarget; enum class PseudoClassState : std::uint8_t { Clear = 0, Set = 1, Override = 2 }; -using PseudoClassMap = SmallUnorderedMap< String, PseudoClassState >; - +using PseudoClassMap = SmallUnorderedMap; /** - Manages an element's style and property information. - @author Lloyd Weehuizen + Manages an element's style and property information. + @author Lloyd Weehuizen */ -class ElementStyle -{ +class ElementStyle { public: /// Constructor /// @param[in] element The element this structure belongs to. @@ -138,7 +136,8 @@ class ElementStyle /// Turns the local and inherited properties into computed values for this element. These values can in turn be used during the layout procedure. /// Must be called in correct order, always parent before its children. - PropertyIdSet ComputeValues(Style::ComputedValues& values, const Style::ComputedValues* parent_values, const Style::ComputedValues* document_values, bool values_are_default_initialized, float dp_ratio, Vector2f vp_dimensions); + PropertyIdSet ComputeValues(Style::ComputedValues& values, const Style::ComputedValues* parent_values, + const Style::ComputedValues* document_values, bool values_are_default_initialized, float dp_ratio, Vector2f vp_dimensions); /// Returns an iterator for iterating the local properties of this element. /// Note: Modifying the element's style invalidates its iterator. @@ -148,9 +147,11 @@ class ElementStyle // Sets a list of properties as dirty. void DirtyProperties(const PropertyIdSet& properties); - static const Property* GetLocalProperty(PropertyId id, const PropertyDictionary & inline_properties, const ElementDefinition * definition); - static const Property* GetProperty(PropertyId id, const Element * element, const PropertyDictionary & inline_properties, const ElementDefinition * definition); - static void TransitionPropertyChanges(Element * element, PropertyIdSet & properties, const PropertyDictionary & inline_properties, const ElementDefinition * old_definition, const ElementDefinition * new_definition); + static const Property* GetLocalProperty(PropertyId id, const PropertyDictionary& inline_properties, const ElementDefinition* definition); + static const Property* GetProperty(PropertyId id, const Element* element, const PropertyDictionary& inline_properties, + const ElementDefinition* definition); + static void TransitionPropertyChanges(Element* element, PropertyIdSet& properties, const PropertyDictionary& inline_properties, + const ElementDefinition* old_definition, const ElementDefinition* new_definition); // Element these properties belong to Element* element; diff --git a/Source/Core/ElementText.cpp b/Source/Core/ElementText.cpp index cdf25e470..2da1b7f6a 100644 --- a/Source/Core/ElementText.cpp +++ b/Source/Core/ElementText.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,7 +42,8 @@ namespace Rml { -static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters); +static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, + bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters); static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline); void LogMissingFontFace(Element* element) @@ -95,7 +96,7 @@ void ElementText::OnRender() FontFaceHandle font_face_handle = GetFontFaceHandle(); if (font_face_handle == 0) return; - + // If our font effects have potentially changed, update it and force a geometry generation if necessary. if (font_effects_dirty && UpdateFontEffects()) geometry_dirty = true; @@ -161,7 +162,7 @@ void ElementText::OnRender() break; } } - + if (render) { for (size_t i = 0; i < geometry.size(); ++i) @@ -172,12 +173,12 @@ void ElementText::OnRender() decoration->Render(translation); } -// Generates a line of text rendered from this element bool ElementText::GenerateLine(String& line, int& line_length, float& line_width, int line_begin, float maximum_line_width, float right_spacing_width, bool trim_whitespace_prefix, bool decode_escape_characters, bool allow_empty) { RMLUI_ZoneScoped; - RMLUI_ASSERT(maximum_line_width >= 0.f); // TODO: Check all callers for conformance, check break at line condition below. Possibly check for FLT_MAX. + RMLUI_ASSERT( + maximum_line_width >= 0.f); // TODO: Check all callers for conformance, check break at line condition below. Possibly check for FLT_MAX. FontFaceHandle font_face_handle = GetFontFaceHandle(); @@ -197,16 +198,12 @@ bool ElementText::GenerateLine(String& line, int& line_length, float& line_width using namespace Style; auto& computed = GetComputedValues(); WhiteSpace white_space_property = computed.white_space(); - bool collapse_white_space = white_space_property == WhiteSpace::Normal || - white_space_property == WhiteSpace::Nowrap || - white_space_property == WhiteSpace::Preline; - bool break_at_line = (maximum_line_width >= 0) && - (white_space_property == WhiteSpace::Normal || - white_space_property == WhiteSpace::Prewrap || - white_space_property == WhiteSpace::Preline); - bool break_at_endline = white_space_property == WhiteSpace::Pre || - white_space_property == WhiteSpace::Prewrap || - white_space_property == WhiteSpace::Preline; + bool collapse_white_space = + white_space_property == WhiteSpace::Normal || white_space_property == WhiteSpace::Nowrap || white_space_property == WhiteSpace::Preline; + bool break_at_line = (maximum_line_width >= 0) && + (white_space_property == WhiteSpace::Normal || white_space_property == WhiteSpace::Prewrap || white_space_property == WhiteSpace::Preline); + bool break_at_endline = + white_space_property == WhiteSpace::Pre || white_space_property == WhiteSpace::Prewrap || white_space_property == WhiteSpace::Preline; float letter_spacing = computed.letter_spacing(); @@ -229,7 +226,8 @@ bool ElementText::GenerateLine(String& line, int& line_length, float& line_width previous_codepoint = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&line.back(), line.data())); // Generate the next token and determine its pixel-length. - bool break_line = BuildToken(token, next_token_begin, string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, break_at_endline, text_transform_property, decode_escape_characters); + bool break_line = BuildToken(token, next_token_begin, string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, + break_at_endline, text_transform_property, decode_escape_characters); int token_width = font_engine_interface->GetStringWidth(font_face_handle, token, letter_spacing, previous_codepoint); // If we're breaking to fit a line box, check if the token can fit on the line before we add it. @@ -253,7 +251,8 @@ bool ElementText::GenerateLine(String& line, int& line_length, float& line_width token.clear(); next_token_begin = token_begin; const char* partial_string_end = StringUtilities::SeekBackwardUTF8(token_begin + i, token_begin); - BuildToken(token, next_token_begin, partial_string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, break_at_endline, text_transform_property, decode_escape_characters); + BuildToken(token, next_token_begin, partial_string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, + break_at_endline, text_transform_property, decode_escape_characters); token_width = font_engine_interface->GetStringWidth(font_face_handle, token, letter_spacing, previous_codepoint); if (force_loop_break_after_next || token_width <= max_token_width) @@ -298,7 +297,6 @@ bool ElementText::GenerateLine(String& line, int& line_length, float& line_width return true; } -// Clears all lines of generated text and prepares the element for generating new lines. void ElementText::ClearLines() { // Clear the rendering information. @@ -309,7 +307,6 @@ void ElementText::ClearLines() generated_decoration = Style::TextDecoration::None; } -// Adds a new line into the text element. void ElementText::AddLine(Vector2f line_position, String line) { if (font_effects_dirty) @@ -320,7 +317,6 @@ void ElementText::AddLine(Vector2f line_position, String line) geometry_dirty = true; } -// Prevents the element from dirtying its document's layout when its text is changed. void ElementText::SuppressAutoLayout() { dirty_layout_on_change = false; @@ -336,8 +332,7 @@ void ElementText::OnPropertyChange(const PropertyIdSet& changed_properties) bool font_face_changed = false; auto& computed = GetComputedValues(); - if (changed_properties.Contains(PropertyId::Color) || - changed_properties.Contains(PropertyId::Opacity)) + if (changed_properties.Contains(PropertyId::Color) || changed_properties.Contains(PropertyId::Opacity)) { const float new_opacity = computed.opacity(); const bool opacity_changed = opacity != new_opacity; @@ -358,10 +353,10 @@ void ElementText::OnPropertyChange(const PropertyIdSet& changed_properties) } } - if (changed_properties.Contains(PropertyId::FontFamily) || - changed_properties.Contains(PropertyId::FontWeight) || - changed_properties.Contains(PropertyId::FontStyle) || - changed_properties.Contains(PropertyId::FontSize) || + if (changed_properties.Contains(PropertyId::FontFamily) || // + changed_properties.Contains(PropertyId::FontWeight) || // + changed_properties.Contains(PropertyId::FontStyle) || // + changed_properties.Contains(PropertyId::FontSize) || // changed_properties.Contains(PropertyId::LetterSpacing)) { font_face_changed = true; @@ -409,13 +404,11 @@ void ElementText::OnPropertyChange(const PropertyIdSet& changed_properties) } } -// Returns the RML of this element void ElementText::GetRML(String& content) { content += StringUtilities::EncodeRml(text); } -// Updates the configuration this element uses for its font. bool ElementText::UpdateFontEffects() { RMLUI_ZoneScoped; @@ -448,7 +441,6 @@ bool ElementText::UpdateFontEffects() return false; } -// Clears and regenerates all of the text's geometry. void ElementText::GenerateGeometry(const FontFaceHandle font_face_handle) { RMLUI_ZoneScopedC(0xD2691E); @@ -470,7 +462,8 @@ void ElementText::GenerateGeometry(const FontFaceHandle font_face_handle, Line& { const float letter_spacing = GetComputedValues().letter_spacing(); - line.width = GetFontEngineInterface()->GenerateString(font_face_handle, font_effects_handle, line.text, line.position, colour, opacity, letter_spacing, geometry); + line.width = GetFontEngineInterface()->GenerateString(font_face_handle, font_effects_handle, line.text, line.position, colour, opacity, + letter_spacing, geometry); for (size_t i = 0; i < geometry.size(); ++i) geometry[i].SetHostElement(this); } @@ -499,7 +492,8 @@ void ElementText::GenerateDecoration(const FontFaceHandle font_face_handle) } } -static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters) +static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, + bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters) { RMLUI_ASSERT(token_begin != string_end); @@ -524,8 +518,7 @@ static bool BuildToken(String& token, const char*& token_begin, const char* stri if (decode_escape_characters && character == '&') { // Find the terminating ';'. - while (token_begin != string_end && - *token_begin != ';') + while (token_begin != string_end && *token_begin != ';') ++token_begin; // If we couldn't find the ';', print the token like normal text. @@ -560,8 +553,7 @@ static bool BuildToken(String& token, const char*& token_begin, const char* stri // Check for an endline token; if we're breaking on endlines and we find one, then return true to indicate a // forced break. - if (break_at_endline && - character == '\n') + if (break_at_endline && character == '\n') { token += '\n'; token_begin++; @@ -588,8 +580,7 @@ static bool BuildToken(String& token, const char*& token_begin, const char* stri // However, if we are the last non-whitespace character in the string, and there are trailing // whitespace characters after this token, then we need to append a single space to the end of this // token. - if (token_begin != string_end && - LastToken(token_begin, string_end, collapse_white_space, break_at_endline)) + if (token_begin != string_end && LastToken(token_begin, string_end, collapse_white_space, break_at_endline)) token += ' '; return false; @@ -634,16 +625,14 @@ static bool BuildToken(String& token, const char*& token_begin, const char* stri static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline) { bool last_token = (token_begin == string_end); - if (collapse_white_space && - !last_token) + if (collapse_white_space && !last_token) { last_token = true; const char* character = token_begin; while (character != string_end) { - if (!StringUtilities::IsWhitespace(*character) || - (break_at_endline && *character == '\n')) + if (!StringUtilities::IsWhitespace(*character) || (break_at_endline && *character == '\n')) { last_token = false; break; diff --git a/Source/Core/ElementUtilities.cpp b/Source/Core/ElementUtilities.cpp index 966da3998..f95ad1a02 100644 --- a/Source/Core/ElementUtilities.cpp +++ b/Source/Core/ElementUtilities.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -86,12 +86,12 @@ Element* ElementUtilities::GetElementById(Element* root_element, const String& i { Element* element = search_queue.front(); search_queue.pop(); - + if (element->GetId() == id) { return element; } - + // Add all children to search for (int i = 0; i < element->GetNumChildren(); i++) search_queue.push(element->GetChild(i)); @@ -103,7 +103,7 @@ Element* ElementUtilities::GetElementById(Element* root_element, const String& i void ElementUtilities::GetElementsByTagName(ElementList& elements, Element* root_element, const String& tag) { // Breadth first search on elements for the corresponding id - typedef Queue< Element* > SearchQueue; + typedef Queue SearchQueue; SearchQueue search_queue; for (int i = 0; i < root_element->GetNumChildren(); ++i) search_queue.push(root_element->GetChild(i)); @@ -125,7 +125,7 @@ void ElementUtilities::GetElementsByTagName(ElementList& elements, Element* root void ElementUtilities::GetElementsByClassName(ElementList& elements, Element* root_element, const String& class_name) { // Breadth first search on elements for the corresponding id - typedef Queue< Element* > SearchQueue; + typedef Queue SearchQueue; SearchQueue search_queue; for (int i = 0; i < root_element->GetNumChildren(); ++i) search_queue.push(root_element->GetChild(i)); @@ -144,7 +144,7 @@ void ElementUtilities::GetElementsByClassName(ElementList& elements, Element* ro } } -float ElementUtilities::GetDensityIndependentPixelRatio(Element * element) +float ElementUtilities::GetDensityIndependentPixelRatio(Element* element) { Context* context = element->GetContext(); if (context == nullptr) @@ -153,7 +153,6 @@ float ElementUtilities::GetDensityIndependentPixelRatio(Element * element) return context->GetDensityIndependentPixelRatio(); } -// Returns the width of a string rendered within the context of the given element. int ElementUtilities::GetStringWidth(Element* element, const String& string, Character prior_character) { const float letter_spacing = element->GetComputedValues().letter_spacing(); @@ -165,7 +164,6 @@ int ElementUtilities::GetStringWidth(Element* element, const String& string, Cha return GetFontEngineInterface()->GetStringWidth(font_face_handle, string, letter_spacing, prior_character); } -// Generates the clipping region for an element. bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_dimensions, Element* element) { using Style::Clip; @@ -205,7 +203,7 @@ bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_d const Vector2i element_origin(element_origin_f); const Vector2i element_dimensions(element_dimensions_f); - + if (clip_origin == Vector2i(-1, -1) && clip_dimensions == Vector2i(-1, -1)) { clip_origin = element_origin; @@ -215,7 +213,7 @@ bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_d { const Vector2i top_left = Math::Max(clip_origin, element_origin); const Vector2i bottom_right = Math::Min(clip_origin + clip_dimensions, element_origin + element_dimensions); - + clip_origin = top_left; clip_dimensions = Math::Max(Vector2i(0), bottom_right - top_left); } @@ -225,7 +223,7 @@ bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_d // If this region is meant to clip and we're skipping regions, update the counter. if (num_ignored_clips > 0 && clip_enabled) num_ignored_clips--; - + // Inherit how many clip regions this ancestor ignores. num_ignored_clips = Math::Max(num_ignored_clips, clip_number); @@ -236,13 +234,12 @@ bool ElementUtilities::GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_d // Climb the tree to this region's parent. clipping_element = clipping_element->GetOffsetParent(); } - + return clip_dimensions.x >= 0 && clip_dimensions.y >= 0; } -// Sets the clipping region from an element and its ancestors. bool ElementUtilities::SetClippingRegion(Element* element, Context* context) -{ +{ RenderInterface* render_interface = nullptr; if (element) { @@ -259,13 +256,13 @@ bool ElementUtilities::SetClippingRegion(Element* element, Context* context) if (!render_interface || !context) return false; - - Vector2i clip_origin = { -1, -1 }; - Vector2i clip_dimensions = { -1, -1 }; + + Vector2i clip_origin = {-1, -1}; + Vector2i clip_dimensions = {-1, -1}; bool clip = element && GetClippingRegion(clip_origin, clip_dimensions, element); - - Vector2i current_origin = { -1, -1 }; - Vector2i current_dimensions = { -1, -1 }; + + Vector2i current_origin = {-1, -1}; + Vector2i current_dimensions = {-1, -1}; bool current_clip = context->GetActiveClipRegion(current_origin, current_dimensions); if (current_clip != clip || (clip && (clip_origin != current_origin || clip_dimensions != current_dimensions))) { @@ -280,7 +277,7 @@ void ElementUtilities::ApplyActiveClipRegion(Context* context, RenderInterface* { if (render_interface == nullptr) return; - + Vector2i origin; Vector2i dimensions; bool clip_enabled = context->GetActiveClipRegion(origin, dimensions); @@ -292,19 +289,16 @@ void ElementUtilities::ApplyActiveClipRegion(Context* context, RenderInterface* } } -// Formats the contents of an element. void ElementUtilities::FormatElement(Element* element, Vector2f containing_block) { LayoutEngine::FormatElement(element, containing_block); } -// Generates the box for an element. void ElementUtilities::BuildBox(Box& box, Vector2f containing_block, Element* element, bool inline_element) { LayoutDetails::BuildBox(box, containing_block, element, inline_element ? BuildBoxMode::Inline : BuildBoxMode::Block); } -// Sizes an element, and positions it within its parent offset from the borders of its content area. bool ElementUtilities::PositionElement(Element* element, Vector2f offset, PositionAnchor anchor) { Element* parent = element->GetParentNode(); @@ -329,9 +323,9 @@ bool ElementUtilities::PositionElement(Element* element, Vector2f offset, Positi return true; } -bool ElementUtilities::ApplyTransform(Element &element) +bool ElementUtilities::ApplyTransform(Element& element) { - RenderInterface *render_interface = element.GetRenderInterface(); + RenderInterface* render_interface = element.GetRenderInterface(); if (!render_interface) return false; @@ -343,7 +337,7 @@ bool ElementUtilities::ApplyTransform(Element &element) auto it = previous_matrix.find(render_interface); if (it == previous_matrix.end()) - it = previous_matrix.emplace(render_interface, PreviousMatrix{ nullptr, Matrix4f::Identity() }).first; + it = previous_matrix.emplace(render_interface, PreviousMatrix{nullptr, Matrix4f::Identity()}).first; RMLUI_ASSERT(it != previous_matrix.end()); @@ -359,11 +353,11 @@ bool ElementUtilities::ApplyTransform(Element &element) Matrix4f& old_transform_value = it->second.value; // Do a deep comparison as well to avoid submitting a new transform which is equal. - if(!old_transform || !new_transform || (old_transform_value != *new_transform)) + if (!old_transform || !new_transform || (old_transform_value != *new_transform)) { render_interface->SetTransform(new_transform); - if(new_transform) + if (new_transform) old_transform_value = *new_transform; } @@ -373,7 +367,6 @@ bool ElementUtilities::ApplyTransform(Element &element) return true; } - static bool ApplyDataViewsControllersInternal(Element* element, const bool construct_structural_view, const String& structural_view_inner_rml) { RMLUI_ASSERT(element); @@ -391,7 +384,7 @@ static bool ApplyDataViewsControllersInternal(Element* element, const bool const explicit operator bool() const { return view || controller; } }; - // Since data views and controllers may modify the element's attributes during initialization, we + // Since data views and controllers may modify the element's attributes during initialization, we // need to iterate over all the attributes _before_ initializing any views or controllers. We store // the information needed to initialize them in the following container. Vector initializer_list; @@ -467,7 +460,8 @@ static bool ApplyDataViewsControllersInternal(Element* element, const bool const result = true; } else - Log::Message(Log::LT_WARNING, "Could not add data-%s view to element: %s", initializer.type.c_str(), element->GetAddress().c_str()); + Log::Message(Log::LT_WARNING, "Could not add data-%s view to element: %s", initializer.type.c_str(), + element->GetAddress().c_str()); } if (controller) @@ -478,7 +472,8 @@ static bool ApplyDataViewsControllersInternal(Element* element, const bool const result = true; } else - Log::Message(Log::LT_WARNING, "Could not add data-%s controller to element: %s", initializer.type.c_str(), element->GetAddress().c_str()); + Log::Message(Log::LT_WARNING, "Could not add data-%s controller to element: %s", initializer.type.c_str(), + element->GetAddress().c_str()); } } } @@ -486,7 +481,6 @@ static bool ApplyDataViewsControllersInternal(Element* element, const bool const return result; } - bool ElementUtilities::ApplyDataViewsControllers(Element* element) { return ApplyDataViewsControllersInternal(element, false, String()); diff --git a/Source/Core/Elements/ElementForm.cpp b/Source/Core/Elements/ElementForm.cpp index f8d03911f..41536a3e1 100644 --- a/Source/Core/Elements/ElementForm.cpp +++ b/Source/Core/Elements/ElementForm.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,16 +33,10 @@ namespace Rml { -// Constructs a new ElementForm. This should not be called directly; use the Factory instead. -ElementForm::ElementForm(const String& tag) : Element(tag) -{ -} +ElementForm::ElementForm(const String& tag) : Element(tag) {} -ElementForm::~ElementForm() -{ -} +ElementForm::~ElementForm() {} -// Submits the form. void ElementForm::Submit(const String& name, const String& submit_value) { Dictionary values; @@ -58,7 +52,7 @@ void ElementForm::Submit(const String& name, const String& submit_value) for (size_t i = 0; i < form_controls.size(); i++) { - ElementFormControl* control = rmlui_dynamic_cast< ElementFormControl* >(form_controls[i]); + ElementFormControl* control = rmlui_dynamic_cast(form_controls[i]); if (!control) continue; @@ -80,7 +74,7 @@ void ElementForm::Submit(const String& name, const String& submit_value) // If the item already exists, append to it. Variant* value = GetIf(values, control_name); if (value != nullptr) - *value = value->Get< String >() + ", " + control_value; + *value = value->Get() + ", " + control_value; else values[control_name] = control_value; } diff --git a/Source/Core/Elements/ElementFormControl.cpp b/Source/Core/Elements/ElementFormControl.cpp index 59a1e031f..6bd35ee5b 100644 --- a/Source/Core/Elements/ElementFormControl.cpp +++ b/Source/Core/Elements/ElementFormControl.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,35 +36,28 @@ ElementFormControl::ElementFormControl(const String& tag) : Element(tag) SetProperty(PropertyId::TabIndex, Property(Style::TabIndex::Auto)); } -ElementFormControl::~ElementFormControl() -{ -} +ElementFormControl::~ElementFormControl() {} -// Returns the name of the form control. String ElementFormControl::GetName() const { - return GetAttribute("name", ""); + return GetAttribute("name", ""); } -// Sets the name of the form control. void ElementFormControl::SetName(const String& name) { SetAttribute("name", name); } -// Returns if this value should be submitted with the form bool ElementFormControl::IsSubmitted() { return true; } -// Returns the disabled status of the form control. bool ElementFormControl::IsDisabled() const { return HasAttribute("disabled"); } -// Sets the disabled status of the form control. void ElementFormControl::SetDisabled(bool disable) { if (disable) @@ -73,7 +66,6 @@ void ElementFormControl::SetDisabled(bool disable) RemoveAttribute("disabled"); } -// Checks for changes to the 'disabled' attribute. void ElementFormControl::OnAttributeChange(const ElementAttributes& changed_attributes) { Element::OnAttributeChange(changed_attributes); diff --git a/Source/Core/Elements/ElementFormControlInput.cpp b/Source/Core/Elements/ElementFormControlInput.cpp index 4e292fb19..732a70f59 100644 --- a/Source/Core/Elements/ElementFormControlInput.cpp +++ b/Source/Core/Elements/ElementFormControlInput.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -37,7 +37,6 @@ namespace Rml { -// Constructs a new ElementFormControlInput. ElementFormControlInput::ElementFormControlInput(const String& tag) : ElementFormControl(tag) { // OnAttributeChange will be called right after this, possible with a non-default type. Thus, @@ -45,23 +44,19 @@ ElementFormControlInput::ElementFormControlInput(const String& tag) : ElementFor // Instead, we create the InputTypeText in OnAttributeChange in the case where the type attribute has not been set. } -ElementFormControlInput::~ElementFormControlInput() -{} +ElementFormControlInput::~ElementFormControlInput() {} -// Returns a string representation of the current value of the form control. String ElementFormControlInput::GetValue() const { RMLUI_ASSERT(type); return type->GetValue(); } -// Sets the current value of the form control. void ElementFormControlInput::SetValue(const String& value) { SetAttribute("value", value); } -// Returns if this value should be submitted with the form. bool ElementFormControlInput::IsSubmitted() { RMLUI_ASSERT(type); @@ -86,14 +81,12 @@ void ElementFormControlInput::GetSelection(int* selection_start, int* selection_ type->GetSelection(selection_start, selection_end, selected_text); } -// Updates the element's underlying type. void ElementFormControlInput::OnUpdate() { RMLUI_ASSERT(type); type->OnUpdate(); } -// Renders the element's underlying type. void ElementFormControlInput::OnRender() { RMLUI_ASSERT(type); @@ -112,7 +105,6 @@ void ElementFormControlInput::OnLayout() type->OnLayout(); } -// Checks for necessary functional changes in the control as a result of changed attributes. void ElementFormControlInput::OnAttributeChange(const ElementAttributes& changed_attributes) { ElementFormControl::OnAttributeChange(changed_attributes); @@ -163,7 +155,6 @@ void ElementFormControlInput::OnAttributeChange(const ElementAttributes& changed DirtyLayout(); } -// Called when properties on the element are changed. void ElementFormControlInput::OnPropertyChange(const PropertyIdSet& changed_properties) { ElementFormControl::OnPropertyChange(changed_properties); @@ -172,21 +163,18 @@ void ElementFormControlInput::OnPropertyChange(const PropertyIdSet& changed_prop type->OnPropertyChange(changed_properties); } -// If we are the added element, this will pass the call onto our type handler. void ElementFormControlInput::OnChildAdd(Element* child) { if (child == this && type) type->OnChildAdd(); } -// If we are the removed element, this will pass the call onto our type handler. void ElementFormControlInput::OnChildRemove(Element* child) { if (child == this && type) type->OnChildRemove(); } -// Handles the "click" event to toggle the control's checked status. void ElementFormControlInput::ProcessDefaultAction(Event& event) { ElementFormControl::ProcessDefaultAction(event); diff --git a/Source/Core/Elements/ElementFormControlSelect.cpp b/Source/Core/Elements/ElementFormControlSelect.cpp index 6de1246ee..d447614b5 100644 --- a/Source/Core/Elements/ElementFormControlSelect.cpp +++ b/Source/Core/Elements/ElementFormControlSelect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,13 +28,12 @@ #include "../../../Include/RmlUi/Core/Elements/ElementFormControlSelect.h" #include "../../../Include/RmlUi/Core/ElementText.h" -#include "../../../Include/RmlUi/Core/Event.h" #include "../../../Include/RmlUi/Core/ElementUtilities.h" +#include "../../../Include/RmlUi/Core/Event.h" #include "WidgetDropDown.h" namespace Rml { -// Constructs a new ElementFormControlSelect. ElementFormControlSelect::ElementFormControlSelect(const String& tag) : ElementFormControl(tag), widget(nullptr) { widget = new WidgetDropDown(this); @@ -45,13 +44,11 @@ ElementFormControlSelect::~ElementFormControlSelect() delete widget; } -// Returns a string representation of the current value of the form control. String ElementFormControlSelect::GetValue() const { return GetAttribute("value", String()); } -// Sets the current value of the form control. void ElementFormControlSelect::SetValue(const String& value) { MoveChildren(); @@ -59,7 +56,6 @@ void ElementFormControlSelect::SetValue(const String& value) SetAttribute("value", value); } -// Sets the index of the selection. If the new index lies outside of the bounds, it will be clamped. void ElementFormControlSelect::SetSelection(int selection) { MoveChildren(); @@ -67,13 +63,11 @@ void ElementFormControlSelect::SetSelection(int selection) widget->SetSelection(widget->GetOption(selection)); } -// Returns the index of the currently selected item. int ElementFormControlSelect::GetSelection() const { return widget->GetSelection(); } -// Returns one of the select control's option elements. Element* ElementFormControlSelect::GetOption(int index) { MoveChildren(); @@ -81,7 +75,6 @@ Element* ElementFormControlSelect::GetOption(int index) return widget->GetOption(index); } -// Returns the number of options in the select control. int ElementFormControlSelect::GetNumOptions() { MoveChildren(); @@ -89,7 +82,6 @@ int ElementFormControlSelect::GetNumOptions() return widget->GetNumOptions(); } -// Adds a new option to the select control. int ElementFormControlSelect::Add(const String& rml, const String& value, int before, bool selectable) { MoveChildren(); @@ -104,7 +96,6 @@ int ElementFormControlSelect::Add(ElementPtr element, int before) return widget->AddOption(std::move(element), before); } -// Removes an option from the select control. void ElementFormControlSelect::Remove(int index) { MoveChildren(); @@ -112,7 +103,6 @@ void ElementFormControlSelect::Remove(int index) widget->RemoveOption(index); } -// Removes all options from the select control. void ElementFormControlSelect::RemoveAll() { MoveChildren(); @@ -120,7 +110,6 @@ void ElementFormControlSelect::RemoveAll() widget->ClearOptions(); } -// Moves all children to be under control of the widget. void ElementFormControlSelect::OnUpdate() { ElementFormControl::OnUpdate(); @@ -130,7 +119,6 @@ void ElementFormControlSelect::OnUpdate() widget->OnUpdate(); } -// Updates the layout of the widget's elements. void ElementFormControlSelect::OnRender() { ElementFormControl::OnRender(); @@ -138,7 +126,6 @@ void ElementFormControlSelect::OnRender() widget->OnRender(); } -// Forces an internal layout. void ElementFormControlSelect::OnLayout() { widget->OnLayout(); @@ -166,7 +153,6 @@ void ElementFormControlSelect::MoveChildren() } } -// Returns true to mark this element as replaced. bool ElementFormControlSelect::GetIntrinsicDimensions(Vector2f& intrinsic_dimensions, float& /*ratio*/) { intrinsic_dimensions.x = 128; diff --git a/Source/Core/Elements/ElementFormControlTextArea.cpp b/Source/Core/Elements/ElementFormControlTextArea.cpp index c5e182a7f..041fe4074 100644 --- a/Source/Core/Elements/ElementFormControlTextArea.cpp +++ b/Source/Core/Elements/ElementFormControlTextArea.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,7 +36,6 @@ namespace Rml { -// Constructs a new ElementFormControlTextArea. ElementFormControlTextArea::ElementFormControlTextArea(const String& tag) : ElementFormControl(tag) { widget = MakeUnique(this); @@ -48,56 +47,46 @@ ElementFormControlTextArea::ElementFormControlTextArea(const String& tag) : Elem ElementFormControlTextArea::~ElementFormControlTextArea() {} -// Returns a string representation of the current value of the form control. String ElementFormControlTextArea::GetValue() const { - return GetAttribute< String >("value", ""); + return GetAttribute("value", ""); } -// Sets the current value of the form control. void ElementFormControlTextArea::SetValue(const String& value) { SetAttribute("value", value); } -// Sets the number of characters visible across the text area. Note that this will only be precise when using a -// fixed-width font. void ElementFormControlTextArea::SetNumColumns(int num_columns) { - SetAttribute< int >("cols", Math::Max(1, num_columns)); + SetAttribute("cols", Math::Max(1, num_columns)); } -// Returns the approximate number of characters visible at once. int ElementFormControlTextArea::GetNumColumns() const { - return GetAttribute< int >("cols", 20); + return GetAttribute("cols", 20); } -// Sets the number of visible lines of text in the text area. void ElementFormControlTextArea::SetNumRows(int num_rows) { - SetAttribute< int >("rows", Math::Max(1, num_rows)); + SetAttribute("rows", Math::Max(1, num_rows)); } -// Returns the number of visible lines of text in the text area. int ElementFormControlTextArea::GetNumRows() const { - return GetAttribute< int >("rows", 2); + return GetAttribute("rows", 2); } -// Sets the maximum length (in characters) of this text field. void ElementFormControlTextArea::SetMaxLength(int max_length) { - SetAttribute< int >("maxlength", max_length); + SetAttribute("maxlength", max_length); } -// Returns the maximum length (in characters) of this text field. int ElementFormControlTextArea::GetMaxLength() const { - return GetAttribute< int >("maxlength", -1); + return GetAttribute("maxlength", -1); } -// Enables or disables word-wrapping in the text area. void ElementFormControlTextArea::SetWordWrap(bool word_wrap) { if (word_wrap != GetWordWrap()) @@ -109,10 +98,9 @@ void ElementFormControlTextArea::SetWordWrap(bool word_wrap) } } -// Returns the state of word-wrapping in the text area. bool ElementFormControlTextArea::GetWordWrap() { - String attribute = GetAttribute< String >("wrap", ""); + String attribute = GetAttribute("wrap", ""); return attribute != "nowrap"; } @@ -131,40 +119,34 @@ void ElementFormControlTextArea::GetSelection(int* selection_start, int* selecti widget->GetSelection(selection_start, selection_end, selected_text); } -// Returns the control's inherent size, based on the length of the input field and the current font size. bool ElementFormControlTextArea::GetIntrinsicDimensions(Vector2f& dimensions, float& /*ratio*/) { - dimensions.x = (float) (GetNumColumns() * ElementUtilities::GetStringWidth(this, "m")); + dimensions.x = (float)(GetNumColumns() * ElementUtilities::GetStringWidth(this, "m")); dimensions.y = (float)GetNumRows() * GetLineHeight(); return true; } -// Updates the control's widget. void ElementFormControlTextArea::OnUpdate() { widget->OnUpdate(); } -// Renders the control's widget. void ElementFormControlTextArea::OnRender() { widget->OnRender(); } -// Formats the element. void ElementFormControlTextArea::OnResize() { widget->OnResize(); } -// Formats the element. void ElementFormControlTextArea::OnLayout() { widget->OnLayout(); } -// Called when attributes on the element are changed. void ElementFormControlTextArea::OnAttributeChange(const ElementAttributes& changed_attributes) { ElementFormControl::OnAttributeChange(changed_attributes); @@ -189,7 +171,6 @@ void ElementFormControlTextArea::OnAttributeChange(const ElementAttributes& chan widget->SetValue(it->second.Get()); } -// Called when properties on the control are changed. void ElementFormControlTextArea::OnPropertyChange(const PropertyIdSet& changed_properties) { ElementFormControl::OnPropertyChange(changed_properties); @@ -208,7 +189,6 @@ void ElementFormControlTextArea::OnPropertyChange(const PropertyIdSet& changed_p widget->GenerateCursor(); } -// Returns the text content of the element. void ElementFormControlTextArea::GetInnerRML(String& content) const { content = GetValue(); diff --git a/Source/Core/Elements/ElementImage.cpp b/Source/Core/Elements/ElementImage.cpp index 07f69bcdb..99d9811e5 100644 --- a/Source/Core/Elements/ElementImage.cpp +++ b/Source/Core/Elements/ElementImage.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,7 +38,6 @@ namespace Rml { -// Constructs a new ElementImage. ElementImage::ElementImage(const String& tag) : Element(tag), dimensions(-1, -1), rect_source(RectSource::None), geometry(this) { dimensions_scale = 1.0f; @@ -46,11 +45,8 @@ ElementImage::ElementImage(const String& tag) : Element(tag), dimensions(-1, -1) texture_dirty = true; } -ElementImage::~ElementImage() -{ -} +ElementImage::~ElementImage() {} -// Sizes the box to the element's inherent size. bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions, float& _ratio) { // Check if we need to reload the texture. @@ -67,7 +63,7 @@ bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions, float& _ratio) // Calculate the y dimension. if (HasAttribute("height")) - dimensions.y = GetAttribute< float >("height", -1); + dimensions.y = GetAttribute("height", -1); else if (rect_source == RectSource::None) dimensions.y = (float)texture.GetDimensions(GetRenderInterface()).y; else @@ -83,7 +79,6 @@ bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions, float& _ratio) return true; } -// Renders the element. void ElementImage::OnRender() { // Regenerate the geometry if required (this will be set if 'rect' changes but does not result in a resize). @@ -94,7 +89,6 @@ void ElementImage::OnRender() geometry.Render(GetAbsoluteOffset(Box::CONTENT)); } -// Called when attributes on the element are changed. void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes) { // Call through to the base element's OnAttributeChange(). @@ -104,8 +98,7 @@ void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes // Check for a changed 'src' attribute. If this changes, the old texture handle is released, // forcing a reload when the layout is regenerated. - if (changed_attributes.find("src") != changed_attributes.end() || - changed_attributes.find("sprite") != changed_attributes.end()) + if (changed_attributes.find("src") != changed_attributes.end() || changed_attributes.find("sprite") != changed_attributes.end()) { texture_dirty = true; dirty_layout = true; @@ -113,8 +106,7 @@ void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes // Check for a changed 'width' attribute. If this changes, a layout is forced which will // recalculate the dimensions. - if (changed_attributes.find("width") != changed_attributes.end() || - changed_attributes.find("height") != changed_attributes.end()) + if (changed_attributes.find("width") != changed_attributes.end() || changed_attributes.find("height") != changed_attributes.end()) { dirty_layout = true; } @@ -135,12 +127,12 @@ void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes void ElementImage::OnPropertyChange(const PropertyIdSet& changed_properties) { - Element::OnPropertyChange(changed_properties); + Element::OnPropertyChange(changed_properties); - if (changed_properties.Contains(PropertyId::ImageColor) || - changed_properties.Contains(PropertyId::Opacity)) { - GenerateGeometry(); - } + if (changed_properties.Contains(PropertyId::ImageColor) || changed_properties.Contains(PropertyId::Opacity)) + { + GenerateGeometry(); + } } void ElementImage::OnChildAdd(Element* child) @@ -154,7 +146,6 @@ void ElementImage::OnChildAdd(Element* child) } } -// Regenerates the element's geometry. void ElementImage::OnResize() { GenerateGeometry(); @@ -180,8 +171,8 @@ void ElementImage::GenerateGeometry() // Release the old geometry before specifying the new vertices. geometry.Release(true); - Vector< Vertex >& vertices = geometry.GetVertices(); - Vector< int >& indices = geometry.GetIndices(); + Vector& vertices = geometry.GetVertices(); + Vector& indices = geometry.GetIndices(); vertices.resize(4); indices.resize(6); @@ -204,8 +195,8 @@ void ElementImage::GenerateGeometry() float opacity = computed.opacity(); Colourb quad_colour = computed.image_color(); - quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha); - + quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha); + Vector2f quad_size = GetBox().GetSize(Box::CONTENT).Round(); GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), quad_size, quad_colour, texcoords[0], texcoords[1]); @@ -222,7 +213,7 @@ bool ElementImage::LoadTexture() const float dp_ratio = ElementUtilities::GetDensityIndependentPixelRatio(this); // Check for a sprite first, this takes precedence. - const String sprite_name = GetAttribute< String >("sprite", ""); + const String sprite_name = GetAttribute("sprite", ""); if (!sprite_name.empty()) { // Load sprite. @@ -255,7 +246,7 @@ bool ElementImage::LoadTexture() else { // Load image from source URL. - const String source_name = GetAttribute< String >("src", ""); + const String source_name = GetAttribute("src", ""); if (source_name.empty()) { texture = Texture(); @@ -281,11 +272,11 @@ bool ElementImage::LoadTexture() void ElementImage::UpdateRect() { - if(rect_source != RectSource::Sprite) + if (rect_source != RectSource::Sprite) { bool valid_rect = false; - String rect_string = GetAttribute< String >("rect", ""); + String rect_string = GetAttribute("rect", ""); if (!rect_string.empty()) { StringList coords_list; @@ -293,7 +284,8 @@ void ElementImage::UpdateRect() if (coords_list.size() != 4) { - Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'rect' attribute; rect requires 4 space-separated values, found %zu.", GetAddress().c_str(), coords_list.size()); + Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'rect' attribute; rect requires 4 space-separated values, found %zu.", + GetAddress().c_str(), coords_list.size()); } else { diff --git a/Source/Core/Elements/ElementImage.h b/Source/Core/Elements/ElementImage.h index fe96afc26..ae5173460 100644 --- a/Source/Core/Elements/ElementImage.h +++ b/Source/Core/Elements/ElementImage.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,41 +29,40 @@ #ifndef RMLUI_CORE_ELEMENTS_ELEMENTIMAGE_H #define RMLUI_CORE_ELEMENTS_ELEMENTIMAGE_H -#include "../../../Include/RmlUi/Core/Header.h" #include "../../../Include/RmlUi/Core/Element.h" #include "../../../Include/RmlUi/Core/Geometry.h" -#include "../../../Include/RmlUi/Core/Texture.h" +#include "../../../Include/RmlUi/Core/Header.h" #include "../../../Include/RmlUi/Core/Spritesheet.h" +#include "../../../Include/RmlUi/Core/Texture.h" namespace Rml { /** - The 'img' element can render images and sprites. + The 'img' element can render images and sprites. - The 'src' attribute is used to specify an image url. If instead the `sprite` attribute is set, - it will load a sprite and ignore the `src` and `rect` attributes. + The 'src' attribute is used to specify an image url. If instead the `sprite` attribute is set, + it will load a sprite and ignore the `src` and `rect` attributes. - The 'rect' attribute takes four space-separated integer values, specifying a rectangle - using 'x y width height' in pixel coordinates inside the image. No clamping to the - dimensions of the source image will occur; rendered results in this case will - depend on the user's texture addressing mode. + The 'rect' attribute takes four space-separated integer values, specifying a rectangle + using 'x y width height' in pixel coordinates inside the image. No clamping to the + dimensions of the source image will occur; rendered results in this case will + depend on the user's texture addressing mode. - The intrinsic dimensions of the image can now come from three different sources. They are - used in the following order: + The intrinsic dimensions of the image can now come from three different sources. They are + used in the following order: - 1) 'width' / 'height' attributes if present - 2) pixel width / height of the sprite - 3) pixel width / height given by the 'rect' attribute - 4) width / height of the image texture + 1) 'width' / 'height' attributes if present + 2) pixel width / height of the sprite + 3) pixel width / height given by the 'rect' attribute + 4) width / height of the image texture - This has the result of sizing the element to the pixel-size of the rendered image, unless - overridden by the 'width' or 'height' attributes. + This has the result of sizing the element to the pixel-size of the rendered image, unless + overridden by the 'width' or 'height' attributes. - @author Peter Curry + @author Peter Curry */ -class RMLUICORE_API ElementImage : public Element -{ +class RMLUICORE_API ElementImage : public Element { public: RMLUI_RTTI_DefineWithParent(ElementImage, Element) @@ -81,7 +80,7 @@ class RMLUICORE_API ElementImage : public Element /// Regenerates the element's geometry. void OnResize() override; - + /// Our intrinsic dimensions may change with the dp-ratio. void OnDpRatioChange() override; diff --git a/Source/Core/Elements/ElementLabel.cpp b/Source/Core/Elements/ElementLabel.cpp index 6db009ec3..03c0e1b00 100644 --- a/Source/Core/Elements/ElementLabel.cpp +++ b/Source/Core/Elements/ElementLabel.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -100,7 +100,7 @@ Element* ElementLabel::GetTarget() if (target_id.empty()) { - const StringList matching_tags = { "button", "input", "textarea", "progress", "progressbar", "select" }; + const StringList matching_tags = {"button", "input", "textarea", "progress", "progressbar", "select"}; return TagMatchRecursive(matching_tags, this); } diff --git a/Source/Core/Elements/ElementLabel.h b/Source/Core/Elements/ElementLabel.h index 8ec67931a..216edcc03 100644 --- a/Source/Core/Elements/ElementLabel.h +++ b/Source/Core/Elements/ElementLabel.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,26 +29,24 @@ #ifndef RMLUI_CORE_ELEMENTS_ELEMENTLABEL_H #define RMLUI_CORE_ELEMENTS_ELEMENTLABEL_H -#include "../../../Include/RmlUi/Core/Header.h" #include "../../../Include/RmlUi/Core/Element.h" #include "../../../Include/RmlUi/Core/EventListener.h" - +#include "../../../Include/RmlUi/Core/Header.h" namespace Rml { /** - A specialisation of the generic Core::Element representing a label element. - + A specialisation of the generic Core::Element representing a label element. + */ -class ElementLabel : public Element, public EventListener -{ +class ElementLabel : public Element, public EventListener { public: RMLUI_RTTI_DefineWithParent(ElementLabel, Element) ElementLabel(const String& tag); virtual ~ElementLabel(); - + protected: void OnPseudoClassChange(const String& pseudo_class, bool activate) override; diff --git a/Source/Core/Elements/ElementProgress.cpp b/Source/Core/Elements/ElementProgress.cpp index dfb0a74fc..8e5a0eb68 100644 --- a/Source/Core/Elements/ElementProgress.cpp +++ b/Source/Core/Elements/ElementProgress.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,7 +40,8 @@ namespace Rml { -ElementProgress::ElementProgress(const String& tag) : Element(tag), direction(DefaultDirection), start_edge(DefaultStartEdge), fill(nullptr), rect_set(false), geometry(this) +ElementProgress::ElementProgress(const String& tag) : + Element(tag), direction(DefaultDirection), start_edge(DefaultStartEdge), fill(nullptr), rect_set(false), geometry(this) { if (tag == "progressbar") Log::Message(Log::LT_WARNING, "Deprecation notice: Element '' renamed to '', please adjust RML tags accordingly."); @@ -53,19 +54,17 @@ ElementProgress::ElementProgress(const String& tag) : Element(tag), direction(De fill = AppendChild(std::move(fill_element), false); } -ElementProgress::~ElementProgress() -{ -} +ElementProgress::~ElementProgress() {} float ElementProgress::GetValue() const { const float max_value = GetMax(); - return Math::Clamp(GetAttribute< float >("value", 0.0f), 0.0f, max_value); + return Math::Clamp(GetAttribute("value", 0.0f), 0.0f, max_value); } float ElementProgress::GetMax() const { - const float max_value = GetAttribute< float >("max", 1.0f); + const float max_value = GetAttribute("max", 1.0f); return max_value <= 0.0f ? 1.0f : max_value; } @@ -100,8 +99,7 @@ void ElementProgress::OnAttributeChange(const ElementAttributes& changed_attribu { Element::OnAttributeChange(changed_attributes); - if (changed_attributes.find("value") != changed_attributes.end() - || changed_attributes.find("max") != changed_attributes.end()) + if (changed_attributes.find("value") != changed_attributes.end() || changed_attributes.find("max") != changed_attributes.end()) { geometry_dirty = true; } @@ -109,11 +107,11 @@ void ElementProgress::OnAttributeChange(const ElementAttributes& changed_attribu if (changed_attributes.find("direction") != changed_attributes.end()) { using DirectionNameList = Array; - static const DirectionNameList names = { "top", "right", "bottom", "left", "clockwise", "counter-clockwise" }; + static const DirectionNameList names = {"top", "right", "bottom", "left", "clockwise", "counter-clockwise"}; direction = DefaultDirection; - String name = StringUtilities::ToLower( GetAttribute< String >("direction", "") ); + String name = StringUtilities::ToLower(GetAttribute("direction", "")); auto it = std::find(names.begin(), names.end(), name); size_t index = size_t(it - names.begin()); @@ -126,11 +124,11 @@ void ElementProgress::OnAttributeChange(const ElementAttributes& changed_attribu if (changed_attributes.find("start-edge") != changed_attributes.end()) { using StartEdgeNameList = Array; - static const StartEdgeNameList names = { "top", "right", "bottom", "left" }; + static const StartEdgeNameList names = {"top", "right", "bottom", "left"}; start_edge = DefaultStartEdge; - String name = StringUtilities::ToLower(GetAttribute< String >("start-edge", "")); + String name = StringUtilities::ToLower(GetAttribute("start-edge", "")); auto it = std::find(names.begin(), names.end(), name); size_t index = size_t(it - names.begin()); @@ -143,14 +141,15 @@ void ElementProgress::OnAttributeChange(const ElementAttributes& changed_attribu void ElementProgress::OnPropertyChange(const PropertyIdSet& changed_properties) { - Element::OnPropertyChange(changed_properties); + Element::OnPropertyChange(changed_properties); - if (changed_properties.Contains(PropertyId::ImageColor) || - changed_properties.Contains(PropertyId::Opacity)) { + if (changed_properties.Contains(PropertyId::ImageColor) || changed_properties.Contains(PropertyId::Opacity)) + { geometry_dirty = true; - } + } - if (changed_properties.Contains(PropertyId::FillImage)) { + if (changed_properties.Contains(PropertyId::FillImage)) + { LoadTexture(); } } @@ -165,11 +164,8 @@ void ElementProgress::OnResize() Box fill_box; ElementUtilities::BuildBox(fill_box, element_size, fill); - - const Vector2f margin_top_left( - fill_box.GetEdge(Box::MARGIN, Box::LEFT), - fill_box.GetEdge(Box::MARGIN, Box::TOP) - ); + + const Vector2f margin_top_left(fill_box.GetEdge(Box::MARGIN, Box::LEFT), fill_box.GetEdge(Box::MARGIN, Box::TOP)); const Vector2f edge_size = fill_box.GetSize(Box::MARGIN) - fill_box.GetSize(Box::CONTENT); fill_offset = GetBox().GetPosition() + margin_top_left; @@ -185,7 +181,9 @@ void ElementProgress::GenerateGeometry() { // Warn the user when using the old approach of adding the 'fill-image' property to the 'fill' element. if (fill->GetLocalProperty(PropertyId::FillImage)) - Log::Message(Log::LT_WARNING, "Breaking change: The 'fill-image' property now needs to be set on the element, instead of its inner element. Please update your RCSS source to fix progress bars in this document."); + Log::Message(Log::LT_WARNING, + "Breaking change: The 'fill-image' property now needs to be set on the element, instead of its inner element. Please " + "update your RCSS source to fix progress bars in this document."); const float normalized_value = GetValue() / GetMax(); Vector2f render_size = fill_size; @@ -194,28 +192,24 @@ void ElementProgress::GenerateGeometry() // Size and offset the fill element depending on the progress value. Vector2f offset = fill_offset; - switch (direction) { + switch (direction) + { case Direction::Top: render_size.y = fill_size.y * normalized_value; offset.y = fill_offset.y + fill_size.y - render_size.y; break; - case Direction::Right: - render_size.x = fill_size.x * normalized_value; - break; - case Direction::Bottom: - render_size.y = fill_size.y * normalized_value; - break; + case Direction::Right: render_size.x = fill_size.x * normalized_value; break; + case Direction::Bottom: render_size.y = fill_size.y * normalized_value; break; case Direction::Left: render_size.x = fill_size.x * normalized_value; offset.x = fill_offset.x + fill_size.x - render_size.x; break; case Direction::Clockwise: case Direction::CounterClockwise: - // Circular progress bars cannot use a box to shape the fill element, instead we need to manually create the geometry from the image texture. - // Thus, we leave the size and offset untouched as a canvas for the manual geometry. + // Circular progress bars cannot use a box to shape the fill element, instead we need to manually create the geometry from the image + // texture. Thus, we leave the size and offset untouched as a canvas for the manual geometry. break; - - RMLUI_UNUSED_SWITCH_ENUM(Direction::Count); + case Direction::Count: break; } Box fill_box = fill->GetBox(); @@ -257,15 +251,14 @@ void ElementProgress::GenerateGeometry() quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha); } - - switch (direction) + switch (direction) { // For the top, right, bottom, left directions the fill element already describes where we should draw the fill, // we only need to generate the final texture coordinates here. - case Direction::Top: texcoords[0].y = texcoords[0].y + (1.0f - normalized_value) * (texcoords[1].y - texcoords[0].y); break; - case Direction::Right: texcoords[1].x = texcoords[0].x + normalized_value * (texcoords[1].x - texcoords[0].x); break; - case Direction::Bottom: texcoords[1].y = texcoords[0].y + normalized_value * (texcoords[1].y - texcoords[0].y); break; - case Direction::Left: texcoords[0].x = texcoords[0].x + (1.0f - normalized_value) * (texcoords[1].x - texcoords[0].x); break; + case Direction::Top: texcoords[0].y = texcoords[0].y + (1.0f - normalized_value) * (texcoords[1].y - texcoords[0].y); break; + case Direction::Right: texcoords[1].x = texcoords[0].x + normalized_value * (texcoords[1].x - texcoords[0].x); break; + case Direction::Bottom: texcoords[1].y = texcoords[0].y + normalized_value * (texcoords[1].y - texcoords[0].y); break; + case Direction::Left: texcoords[0].x = texcoords[0].x + (1.0f - normalized_value) * (texcoords[1].x - texcoords[0].x); break; case Direction::Clockwise: case Direction::CounterClockwise: @@ -290,8 +283,8 @@ void ElementProgress::GenerateGeometry() const int start_octant = 2 * int(start_edge); // Positions along the unit square (clockwise, index 0 on top) - const float x[8] = { 0, 1, 1, 1, 0, -1, -1, -1 }; - const float y[8] = { -1, -1, 0, 1, 1, 1, 0, -1 }; + const float x[8] = {0, 1, 1, 1, 0, -1, -1, -1}; + const float y[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; // Set the position of the octant vertices to be rendered. for (int i = 0; i <= num_octants; i++) @@ -332,13 +325,14 @@ void ElementProgress::GenerateGeometry() vertices[i].colour = quad_colour; } } - break; - RMLUI_UNUSED_SWITCH_ENUM(Direction::Count); + break; + + case Direction::Count: break; } const bool is_circular = (direction == Direction::Clockwise || direction == Direction::CounterClockwise); - if(!is_circular) + if (!is_circular) { vertices.resize(4); indices.resize(6); @@ -360,7 +354,7 @@ bool ElementProgress::LoadTexture() bool texture_set = false; - if(!name.empty() && document) + if (!name.empty() && document) { // Check for a sprite first, this takes precedence. if (const StyleSheet* style_sheet = document->GetStyleSheet()) diff --git a/Source/Core/Elements/ElementTabSet.cpp b/Source/Core/Elements/ElementTabSet.cpp index 39fbe4da2..4f4fdc999 100644 --- a/Source/Core/Elements/ElementTabSet.cpp +++ b/Source/Core/Elements/ElementTabSet.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +27,8 @@ */ #include "../../../Include/RmlUi/Core/Elements/ElementTabSet.h" -#include "../../../Include/RmlUi/Core/Math.h" #include "../../../Include/RmlUi/Core/Factory.h" +#include "../../../Include/RmlUi/Core/Math.h" namespace Rml { @@ -37,11 +37,8 @@ ElementTabSet::ElementTabSet(const String& tag) : Element(tag) active_tab = 0; } -ElementTabSet::~ElementTabSet() -{ -} +ElementTabSet::~ElementTabSet() {} -// Sets the specifed tab index's tab title RML. void ElementTabSet::SetTab(int tab_index, const String& rml) { ElementPtr element = Factory::InstanceElement(nullptr, "*", "tab", XMLAttributes()); @@ -49,7 +46,6 @@ void ElementTabSet::SetTab(int tab_index, const String& rml) SetTab(tab_index, std::move(element)); } -// Sets the specifed tab index's tab panel RML. void ElementTabSet::SetPanel(int tab_index, const String& rml) { ElementPtr element = Factory::InstanceElement(nullptr, "*", "panel", XMLAttributes()); @@ -57,30 +53,25 @@ void ElementTabSet::SetPanel(int tab_index, const String& rml) SetPanel(tab_index, std::move(element)); } -// Set the specifed tab index's title element. void ElementTabSet::SetTab(int tab_index, ElementPtr element) -{ +{ Element* tabs = GetChildByTag("tabs"); - if (tab_index >= 0 && - tab_index < tabs->GetNumChildren()) + if (tab_index >= 0 && tab_index < tabs->GetNumChildren()) tabs->ReplaceChild(std::move(element), tabs->GetChild(tab_index)); else tabs->AppendChild(std::move(element)); } -// Set the specified tab index's body element. void ElementTabSet::SetPanel(int tab_index, ElementPtr element) -{ +{ // append the window Element* windows = GetChildByTag("panels"); - if (tab_index >= 0 && - tab_index < windows->GetNumChildren()) + if (tab_index >= 0 && tab_index < windows->GetNumChildren()) windows->ReplaceChild(std::move(element), windows->GetChild(tab_index)); else windows->AppendChild(std::move(element)); } -// Remove one of the tab set's panels and its corresponding tab. void ElementTabSet::RemoveTab(int tab_index) { if (tab_index < 0) @@ -89,15 +80,13 @@ void ElementTabSet::RemoveTab(int tab_index) Element* panels = GetChildByTag("panels"); Element* tabs = GetChildByTag("tabs"); - if (panels->GetNumChildren() > tab_index && - tabs->GetNumChildren() > tab_index) + if (panels->GetNumChildren() > tab_index && tabs->GetNumChildren() > tab_index) { panels->RemoveChild(panels->GetChild(tab_index)); tabs->RemoveChild(tabs->GetChild(tab_index)); } } -// Retrieve the number of tabs in the tabset. int ElementTabSet::GetNumTabs() { return GetChildByTag("tabs")->GetNumChildren(); @@ -187,7 +176,7 @@ void ElementTabSet::OnChildAdd(Element* child) { // Hide the new tab window child->SetProperty(PropertyId::Display, Property(Style::Display::None)); - + // Make the new element visible if its the active tab if (child->GetParentNode()->GetChild(active_tab) == child) child->RemoveProperty(PropertyId::Display); @@ -209,5 +198,4 @@ Element* ElementTabSet::GetChildByTag(const String& tag) return result; } - } // namespace Rml diff --git a/Source/Core/Elements/ElementTextSelection.cpp b/Source/Core/Elements/ElementTextSelection.cpp index 51238adee..5b8e8b5df 100644 --- a/Source/Core/Elements/ElementTextSelection.cpp +++ b/Source/Core/Elements/ElementTextSelection.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +27,8 @@ */ #include "ElementTextSelection.h" -#include "WidgetTextInput.h" #include "../../../Include/RmlUi/Core/PropertyIdSet.h" +#include "WidgetTextInput.h" namespace Rml { @@ -37,17 +37,13 @@ ElementTextSelection::ElementTextSelection(const String& tag) : Element(tag) widget = nullptr; } -ElementTextSelection::~ElementTextSelection() -{ -} +ElementTextSelection::~ElementTextSelection() {} -// Set the widget that this selection element was created for. void ElementTextSelection::SetWidget(WidgetTextInput* _widget) { widget = _widget; } -// Processes 'color' and 'background-color' property changes. void ElementTextSelection::OnPropertyChange(const PropertyIdSet& changed_properties) { Element::OnPropertyChange(changed_properties); @@ -55,8 +51,7 @@ void ElementTextSelection::OnPropertyChange(const PropertyIdSet& changed_propert if (widget == nullptr) return; - if (changed_properties.Contains(PropertyId::Color) || - changed_properties.Contains(PropertyId::BackgroundColor)) + if (changed_properties.Contains(PropertyId::Color) || changed_properties.Contains(PropertyId::BackgroundColor)) { widget->UpdateSelectionColours(); } diff --git a/Source/Core/Elements/ElementTextSelection.h b/Source/Core/Elements/ElementTextSelection.h index 3eb1bd18c..eaa044eae 100644 --- a/Source/Core/Elements/ElementTextSelection.h +++ b/Source/Core/Elements/ElementTextSelection.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,14 +36,13 @@ namespace Rml { class WidgetTextInput; /** - A stub element used by the WidgetTextInput to query the RCSS-specified text colour and - background colour for selected text. + A stub element used by the WidgetTextInput to query the RCSS-specified text colour and + background colour for selected text. - @author Peter Curry + @author Peter Curry */ -class ElementTextSelection : public Element -{ +class ElementTextSelection : public Element { public: RMLUI_RTTI_DefineWithParent(ElementTextSelection, Element) diff --git a/Source/Core/Elements/InputType.cpp b/Source/Core/Elements/InputType.cpp index fe7ad467c..753f68920 100644 --- a/Source/Core/Elements/InputType.cpp +++ b/Source/Core/Elements/InputType.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,67 +31,38 @@ namespace Rml { -InputType::InputType(ElementFormControlInput* element) : element(element) -{ -} +InputType::InputType(ElementFormControlInput* element) : element(element) {} -InputType::~InputType() -{ -} +InputType::~InputType() {} -// Returns a string representation of the current value of the form control. String InputType::GetValue() const { - return element->GetAttribute< String >("value", ""); + return element->GetAttribute("value", ""); } -// Returns if this value should be submitted with the form. bool InputType::IsSubmitted() { return true; } -// Called every update from the host element. -void InputType::OnUpdate() -{ -} +void InputType::OnUpdate() {} -// Called every render from the host element. -void InputType::OnRender() -{ -} +void InputType::OnRender() {} -void InputType::OnResize() -{ -} +void InputType::OnResize() {} -void InputType::OnLayout() -{ -} +void InputType::OnLayout() {} -// Checks for necessary functional changes in the control as a result of changed attributes. -bool InputType::OnAttributeChange(const ElementAttributes& RMLUI_UNUSED_PARAMETER(changed_attributes)) +bool InputType::OnAttributeChange(const ElementAttributes& /*changed_attributes*/) { - RMLUI_UNUSED(changed_attributes); - return true; } -// Called when properties on the control are changed. -void InputType::OnPropertyChange(const PropertyIdSet& RMLUI_UNUSED_PARAMETER(changed_properties)) -{ - RMLUI_UNUSED(changed_properties); -} +void InputType::OnPropertyChange(const PropertyIdSet& /*changed_properties*/) {} -// Called when the element is added into a hierarchy. -void InputType::OnChildAdd() -{ -} +void InputType::OnChildAdd() {} -// Called when the element is removed from a hierarchy. -void InputType::OnChildRemove() -{ -} +void InputType::OnChildRemove() {} void InputType::Select() {} diff --git a/Source/Core/Elements/InputType.h b/Source/Core/Elements/InputType.h index 2238cd232..477eee506 100644 --- a/Source/Core/Elements/InputType.h +++ b/Source/Core/Elements/InputType.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,14 +37,13 @@ namespace Rml { class ElementFormControlInput; /** - An interface for a input type handler used by ElementFormControlInput. A concrete InputType object handles the - functionality of an input element. + An interface for a input type handler used by ElementFormControlInput. A concrete InputType object handles the + functionality of an input element. - @author Peter Curry + @author Peter Curry */ -class InputType -{ +class InputType { public: InputType(ElementFormControlInput* element); virtual ~InputType(); diff --git a/Source/Core/Elements/InputTypeButton.cpp b/Source/Core/Elements/InputTypeButton.cpp index 27698620f..c0f91c04b 100644 --- a/Source/Core/Elements/InputTypeButton.cpp +++ b/Source/Core/Elements/InputTypeButton.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,25 +32,18 @@ namespace Rml { -InputTypeButton::InputTypeButton(ElementFormControlInput* element) : InputType(element) -{ -} +InputTypeButton::InputTypeButton(ElementFormControlInput* element) : InputType(element) {} -InputTypeButton::~InputTypeButton() -{ -} +InputTypeButton::~InputTypeButton() {} -// Buttons are never submitted. bool InputTypeButton::IsSubmitted() { + // Buttons are never submitted. return false; } -void InputTypeButton::ProcessDefaultAction(Event& /*event*/) -{ -} +void InputTypeButton::ProcessDefaultAction(Event& /*event*/) {} -// Sizes the dimensions to the element's inherent size. bool InputTypeButton::GetIntrinsicDimensions(Vector2f& /*dimensions*/, float& /*ratio*/) { return false; diff --git a/Source/Core/Elements/InputTypeButton.h b/Source/Core/Elements/InputTypeButton.h index c0e853658..16f11e059 100644 --- a/Source/Core/Elements/InputTypeButton.h +++ b/Source/Core/Elements/InputTypeButton.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,21 +29,20 @@ #ifndef RMLUI_CORE_ELEMENTS_INPUTTYPEBUTTON_H #define RMLUI_CORE_ELEMENTS_INPUTTYPEBUTTON_H -#include "../../../Include/RmlUi/Core/EventListener.h" #include "../../../Include/RmlUi/Core/ElementDocument.h" +#include "../../../Include/RmlUi/Core/EventListener.h" #include "InputType.h" namespace Rml { /** - A button input type handler. The only functionality a button provides over a normal element is the ability - to be disabled. This prevents 'click' events on this element and the ability to receive focus. + A button input type handler. The only functionality a button provides over a normal element is the ability + to be disabled. This prevents 'click' events on this element and the ability to receive focus. - @author Peter Curry + @author Peter Curry */ -class InputTypeButton : public InputType -{ +class InputTypeButton : public InputType { public: InputTypeButton(ElementFormControlInput* element); virtual ~InputTypeButton(); diff --git a/Source/Core/Elements/InputTypeCheckbox.cpp b/Source/Core/Elements/InputTypeCheckbox.cpp index d5c701c20..52b54a294 100644 --- a/Source/Core/Elements/InputTypeCheckbox.cpp +++ b/Source/Core/Elements/InputTypeCheckbox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,13 +31,9 @@ namespace Rml { -InputTypeCheckbox::InputTypeCheckbox(ElementFormControlInput* element) : InputType(element) -{ -} +InputTypeCheckbox::InputTypeCheckbox(ElementFormControlInput* element) : InputType(element) {} -InputTypeCheckbox::~InputTypeCheckbox() -{ -} +InputTypeCheckbox::~InputTypeCheckbox() {} String InputTypeCheckbox::GetValue() const { @@ -45,29 +41,23 @@ String InputTypeCheckbox::GetValue() const return value.empty() ? "on" : value; } -// Returns if this value should be submitted with the form. bool InputTypeCheckbox::IsSubmitted() { return element->HasAttribute("checked"); } -// Checks for necessary functional changes in the control as a result of changed attributes. bool InputTypeCheckbox::OnAttributeChange(const ElementAttributes& changed_attributes) { if (changed_attributes.count("checked")) { const bool checked = element->HasAttribute("checked"); element->SetPseudoClass("checked", checked); - element->DispatchEvent(EventId::Change, { - { "data-binding-override-value", Variant(checked) }, - { "value", Variant(checked ? GetValue() : "") } - }); + element->DispatchEvent(EventId::Change, {{"data-binding-override-value", Variant(checked)}, {"value", Variant(checked ? GetValue() : "")}}); } return true; } -// Checks for necessary functional changes in the control as a result of the event. void InputTypeCheckbox::ProcessDefaultAction(Event& event) { if (event == EventId::Click && !element->IsDisabled()) @@ -79,7 +69,6 @@ void InputTypeCheckbox::ProcessDefaultAction(Event& event) } } -// Sizes the dimensions to the element's inherent size. bool InputTypeCheckbox::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio) { dimensions.x = 16; diff --git a/Source/Core/Elements/InputTypeCheckbox.h b/Source/Core/Elements/InputTypeCheckbox.h index 0f72fd2cc..e5bcbb553 100644 --- a/Source/Core/Elements/InputTypeCheckbox.h +++ b/Source/Core/Elements/InputTypeCheckbox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A checkbox input type handler. + A checkbox input type handler. - @author Peter Curry + @author Peter Curry */ -class InputTypeCheckbox : public InputType -{ +class InputTypeCheckbox : public InputType { public: InputTypeCheckbox(ElementFormControlInput* element); virtual ~InputTypeCheckbox(); diff --git a/Source/Core/Elements/InputTypeRadio.cpp b/Source/Core/Elements/InputTypeRadio.cpp index 63554cdab..179a8ab00 100644 --- a/Source/Core/Elements/InputTypeRadio.cpp +++ b/Source/Core/Elements/InputTypeRadio.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,9 +27,9 @@ */ #include "InputTypeRadio.h" -#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h" #include "../../../Include/RmlUi/Core/ElementUtilities.h" #include "../../../Include/RmlUi/Core/Elements/ElementForm.h" +#include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h" namespace Rml { @@ -39,9 +39,7 @@ InputTypeRadio::InputTypeRadio(ElementFormControlInput* element) : InputType(ele PopRadioSet(); } -InputTypeRadio::~InputTypeRadio() -{ -} +InputTypeRadio::~InputTypeRadio() {} String InputTypeRadio::GetValue() const { @@ -49,13 +47,11 @@ String InputTypeRadio::GetValue() const return value.empty() ? "on" : value; } -// Returns if this value should be submitted with the form. bool InputTypeRadio::IsSubmitted() { return element->HasAttribute("checked"); } -// Checks for necessary functional changes in the control as a result of changed attributes. bool InputTypeRadio::OnAttributeChange(const ElementAttributes& changed_attributes) { if (changed_attributes.count("checked")) @@ -67,30 +63,25 @@ bool InputTypeRadio::OnAttributeChange(const ElementAttributes& changed_attribut PopRadioSet(); const auto perceived_value = Variant(checked ? GetValue() : ""); - element->DispatchEvent(EventId::Change, { - { "data-binding-override-value", checked ? Variant(perceived_value) : Variant() }, - { "value", perceived_value } - }); + element->DispatchEvent(EventId::Change, + {{"data-binding-override-value", checked ? Variant(perceived_value) : Variant()}, {"value", perceived_value}}); } return true; } -// Pops the element's radio set if we are checked. void InputTypeRadio::OnChildAdd() { if (element->HasAttribute("checked")) PopRadioSet(); } -// Checks for necessary functional changes in the control as a result of the event. void InputTypeRadio::ProcessDefaultAction(Event& event) { if (event == EventId::Click && !element->IsDisabled()) element->SetAttribute("checked", ""); } -// Sizes the dimensions to the element's inherent size. bool InputTypeRadio::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio) { dimensions.x = 16; @@ -100,15 +91,13 @@ bool InputTypeRadio::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio) return true; } -// Pops all other radio buttons in our form that share our name. void InputTypeRadio::PopRadioSet() { // Uncheck all other radio buttons with our name in the form. ElementForm* form = nullptr; Element* parent = element->GetParentNode(); - while (parent != nullptr && - (form = rmlui_dynamic_cast< ElementForm* >(parent)) == nullptr) - parent = parent->GetParentNode(); + while (parent != nullptr && (form = rmlui_dynamic_cast(parent)) == nullptr) + parent = parent->GetParentNode(); if (form != nullptr) { @@ -117,10 +106,8 @@ void InputTypeRadio::PopRadioSet() for (size_t i = 0; i < form_controls.size(); ++i) { - ElementFormControlInput* radio_control = rmlui_dynamic_cast< ElementFormControlInput* >(form_controls[i]); - if (radio_control != nullptr && - element != radio_control && - radio_control->GetAttribute< String >("type", "text") == "radio" && + ElementFormControlInput* radio_control = rmlui_dynamic_cast(form_controls[i]); + if (radio_control != nullptr && element != radio_control && radio_control->GetAttribute("type", "text") == "radio" && radio_control->GetName() == element->GetName()) { radio_control->RemoveAttribute("checked"); diff --git a/Source/Core/Elements/InputTypeRadio.h b/Source/Core/Elements/InputTypeRadio.h index a82b25aa6..d041c9247 100644 --- a/Source/Core/Elements/InputTypeRadio.h +++ b/Source/Core/Elements/InputTypeRadio.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A radio button input type handler. + A radio button input type handler. - @author Peter Curry + @author Peter Curry */ -class InputTypeRadio : public InputType -{ +class InputTypeRadio : public InputType { public: InputTypeRadio(ElementFormControlInput* element); virtual ~InputTypeRadio(); diff --git a/Source/Core/Elements/InputTypeRange.cpp b/Source/Core/Elements/InputTypeRange.cpp index f7b177c8e..0801b4d16 100644 --- a/Source/Core/Elements/InputTypeRange.cpp +++ b/Source/Core/Elements/InputTypeRange.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +27,8 @@ */ #include "InputTypeRange.h" -#include "WidgetSlider.h" #include "../../../Include/RmlUi/Core/Elements/ElementFormControlInput.h" +#include "WidgetSlider.h" namespace Rml { @@ -43,13 +43,11 @@ InputTypeRange::~InputTypeRange() delete widget; } -// Returns a string representation of the current value of the form control. String InputTypeRange::GetValue() const { return CreateString(32, "%f", widget->GetValue()); } -// Called every update from the host element. void InputTypeRange::OnUpdate() { widget->Update(); @@ -60,7 +58,6 @@ void InputTypeRange::OnResize() widget->FormatElements(); } -// Checks for necessary functional changes in the control as a result of changed attributes. bool InputTypeRange::OnAttributeChange(const ElementAttributes& changed_attributes) { bool dirty_layout = false; @@ -92,12 +89,8 @@ bool InputTypeRange::OnAttributeChange(const ElementAttributes& changed_attribut return !dirty_layout; } -// Checks for necessary functional changes in the control as a result of the event. -void InputTypeRange::ProcessDefaultAction(Event& /*event*/) -{ -} +void InputTypeRange::ProcessDefaultAction(Event& /*event*/) {} -// Sizes the dimensions to the element's inherent size. bool InputTypeRange::GetIntrinsicDimensions(Vector2f& dimensions, float& /*ratio*/) { widget->GetDimensions(dimensions); diff --git a/Source/Core/Elements/InputTypeRange.h b/Source/Core/Elements/InputTypeRange.h index b75c4a7e6..3b581cc2d 100644 --- a/Source/Core/Elements/InputTypeRange.h +++ b/Source/Core/Elements/InputTypeRange.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,12 @@ namespace Rml { class WidgetSlider; /** - A range input type handler. + A range input type handler. - @author Peter Curry + @author Peter Curry */ -class InputTypeRange : public InputType -{ +class InputTypeRange : public InputType { public: InputTypeRange(ElementFormControlInput* element); virtual ~InputTypeRange(); diff --git a/Source/Core/Elements/InputTypeSubmit.cpp b/Source/Core/Elements/InputTypeSubmit.cpp index 81d1fb7e9..7dd36a5ea 100644 --- a/Source/Core/Elements/InputTypeSubmit.cpp +++ b/Source/Core/Elements/InputTypeSubmit.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,33 +32,27 @@ namespace Rml { -InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element) -{ -} +InputTypeSubmit::InputTypeSubmit(ElementFormControlInput* element) : InputType(element) {} -InputTypeSubmit::~InputTypeSubmit() -{ -} +InputTypeSubmit::~InputTypeSubmit() {} -// Submit buttons are never submitted; they submit themselves if appropriate. bool InputTypeSubmit::IsSubmitted() { + // Submit buttons are never submitted; they submit themselves if appropriate. return false; } -// Checks for necessary functional changes in the control as a result of the event. void InputTypeSubmit::ProcessDefaultAction(Event& event) { - if (event == EventId::Click && - !element->IsDisabled()) + if (event == EventId::Click && !element->IsDisabled()) { Element* parent = element->GetParentNode(); while (parent) { - ElementForm* form = rmlui_dynamic_cast< ElementForm* >(parent); + ElementForm* form = rmlui_dynamic_cast(parent); if (form != nullptr) { - form->Submit(element->GetAttribute< String >("name", ""), element->GetAttribute< String >("value", "")); + form->Submit(element->GetAttribute("name", ""), element->GetAttribute("value", "")); return; } else @@ -69,7 +63,6 @@ void InputTypeSubmit::ProcessDefaultAction(Event& event) } } -// Sizes the dimensions to the element's inherent size. bool InputTypeSubmit::GetIntrinsicDimensions(Vector2f& /*dimensions*/, float& /*ratio*/) { return false; diff --git a/Source/Core/Elements/InputTypeSubmit.h b/Source/Core/Elements/InputTypeSubmit.h index e502c6bba..e9ad68e24 100644 --- a/Source/Core/Elements/InputTypeSubmit.h +++ b/Source/Core/Elements/InputTypeSubmit.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A submit input type handler. + A submit input type handler. - @author Peter Curry + @author Peter Curry */ -class InputTypeSubmit : public InputType -{ +class InputTypeSubmit : public InputType { public: InputTypeSubmit(ElementFormControlInput* element); virtual ~InputTypeSubmit(); diff --git a/Source/Core/Elements/InputTypeText.cpp b/Source/Core/Elements/InputTypeText.cpp index 9bacd982b..b379b2e23 100644 --- a/Source/Core/Elements/InputTypeText.cpp +++ b/Source/Core/Elements/InputTypeText.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -46,13 +46,11 @@ InputTypeText::InputTypeText(ElementFormControlInput* element, Visibility visibi InputTypeText::~InputTypeText() {} -// Called every update from the host element. void InputTypeText::OnUpdate() { widget->OnUpdate(); } -// Called every render from the host element. void InputTypeText::OnRender() { widget->OnRender(); @@ -68,7 +66,6 @@ void InputTypeText::OnLayout() widget->OnLayout(); } -// Checks for necessary functional changes in the control as a result of changed attributes. bool InputTypeText::OnAttributeChange(const ElementAttributes& changed_attributes) { bool dirty_layout = false; @@ -94,7 +91,6 @@ bool InputTypeText::OnAttributeChange(const ElementAttributes& changed_attribute return !dirty_layout; } -// Called when properties on the control are changed. void InputTypeText::OnPropertyChange(const PropertyIdSet& changed_properties) { // Some inherited properties require text formatting update, mainly font and line-height properties. @@ -111,16 +107,11 @@ void InputTypeText::OnPropertyChange(const PropertyIdSet& changed_properties) widget->GenerateCursor(); } -// Checks for necessary functional changes in the control as a result of the event. -void InputTypeText::ProcessDefaultAction(Event& RMLUI_UNUSED_PARAMETER(event)) -{ - RMLUI_UNUSED(event); -} +void InputTypeText::ProcessDefaultAction(Event& /*event*/) {} -// Sizes the dimensions to the element's inherent size. bool InputTypeText::GetIntrinsicDimensions(Vector2f& dimensions, float& /*ratio*/) { - dimensions.x = (float) (size * ElementUtilities::GetStringWidth(element, "m")); + dimensions.x = (float)(size * ElementUtilities::GetStringWidth(element, "m")); dimensions.y = element->GetLineHeight() + 2.0f; return true; diff --git a/Source/Core/Elements/InputTypeText.h b/Source/Core/Elements/InputTypeText.h index 1e8d11d4f..5143e4967 100644 --- a/Source/Core/Elements/InputTypeText.h +++ b/Source/Core/Elements/InputTypeText.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,19 +36,14 @@ namespace Rml { class WidgetTextInput; /** - A single-line input type handler. + A single-line input type handler. - @author Peter Curry + @author Peter Curry */ -class InputTypeText : public InputType -{ +class InputTypeText : public InputType { public: - enum Visibility - { - VISIBLE, - OBSCURED - }; + enum Visibility { VISIBLE, OBSCURED }; InputTypeText(ElementFormControlInput* element, Visibility visibility = VISIBLE); virtual ~InputTypeText(); diff --git a/Source/Core/Elements/WidgetDropDown.cpp b/Source/Core/Elements/WidgetDropDown.cpp index 75e811b80..be948f88a 100644 --- a/Source/Core/Elements/WidgetDropDown.cpp +++ b/Source/Core/Elements/WidgetDropDown.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,14 +30,14 @@ #include "../../../Include/RmlUi/Core/ComputedValues.h" #include "../../../Include/RmlUi/Core/Context.h" #include "../../../Include/RmlUi/Core/ElementDocument.h" -#include "../../../Include/RmlUi/Core/Math.h" -#include "../../../Include/RmlUi/Core/Factory.h" #include "../../../Include/RmlUi/Core/ElementUtilities.h" +#include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h" #include "../../../Include/RmlUi/Core/Event.h" +#include "../../../Include/RmlUi/Core/Factory.h" #include "../../../Include/RmlUi/Core/Input.h" -#include "../../../Include/RmlUi/Core/Property.h" +#include "../../../Include/RmlUi/Core/Math.h" #include "../../../Include/RmlUi/Core/Profiling.h" -#include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h" +#include "../../../Include/RmlUi/Core/Property.h" namespace Rml { @@ -144,7 +144,7 @@ void WidgetDropDown::OnRender() { if (box_visible && box_layout_dirty) { - // Layout the selection box. + // Layout the selection box. // The following procedure should ensure that the selection box is never (partly) outside of the context's window. // This is achieved by positioning the box either above or below the 'select' element, and possibly shrinking // the element's height. @@ -152,7 +152,7 @@ void WidgetDropDown::OnRender() // we will override the 'height' property. // Previously set 'height' property from this procedure must be removed for the calculations below to work as intended. - if(selection_element->GetLocalStyleProperties().count(PropertyId::Height) == 1) + if (selection_element->GetLocalStyleProperties().count(PropertyId::Height) == 1) { selection_element->RemoveProperty(PropertyId::Height); selection_element->GetOwnerDocument()->UpdateDocument(); @@ -191,11 +191,10 @@ void WidgetDropDown::OnRender() // Position box above selection_element->SetOffset(Vector2f(offset_x, -content_height + offset_y_above), parent_element); } - else + else { // Shrink box and position either below or above - const float padding_border_size = - box.GetEdge(Box::BORDER, Box::TOP) + box.GetEdge(Box::BORDER, Box::BOTTOM) + + const float padding_border_size = box.GetEdge(Box::BORDER, Box::TOP) + box.GetEdge(Box::BORDER, Box::BOTTOM) + box.GetEdge(Box::PADDING, Box::TOP) + box.GetEdge(Box::PADDING, Box::BOTTOM); float height = 0.f; @@ -238,7 +237,7 @@ void WidgetDropDown::OnLayout() { RMLUI_ZoneScopedNC("DropDownLayout", 0x7FFF00); - if(parent_element->IsDisabled()) + if (parent_element->IsDisabled()) { // Propagate disabled state to selectvalue and selectarrow value_element->SetPseudoClass("disabled", true); @@ -263,7 +262,6 @@ void WidgetDropDown::OnLayout() value_layout_dirty = true; } -// Sets the value of the widget. void WidgetDropDown::OnValueChange(const String& value) { if (!lock_selection) @@ -347,7 +345,6 @@ void WidgetDropDown::SeekSelection(bool seek_forward) // No valid option found, leave selection unchanged. } -// Returns the index of the currently selected item. int WidgetDropDown::GetSelection() const { const int num_options = selection_element->GetNumChildren(); @@ -360,7 +357,6 @@ int WidgetDropDown::GetSelection() const return -1; } -// Adds a new option to the select control. int WidgetDropDown::AddOption(const String& rml, const String& option_value, int before, bool select, bool selectable) { ElementPtr element = Factory::InstanceElement(selection_element, "*", "option", XMLAttributes()); @@ -382,7 +378,8 @@ int WidgetDropDown::AddOption(ElementPtr element, int before) { if (element->GetTagName() != "option") { - Log::Message(Log::LT_WARNING, "A child of '%s' must be of type 'option' but '%s' was given. See element '%s'.", parent_element->GetTagName().c_str(), element->GetTagName().c_str(), parent_element->GetAddress().c_str()); + Log::Message(Log::LT_WARNING, "A child of '%s' must be of type 'option' but '%s' was given. See element '%s'.", + parent_element->GetTagName().c_str(), element->GetTagName().c_str(), parent_element->GetAddress().c_str()); return -1; } @@ -402,7 +399,6 @@ int WidgetDropDown::AddOption(ElementPtr element, int before) return option_index; } -// Removes an option from the select control. void WidgetDropDown::RemoveOption(int index) { Element* element = selection_element->GetChild(index); @@ -412,20 +408,17 @@ void WidgetDropDown::RemoveOption(int index) selection_element->RemoveChild(element); } -// Removes all options from the list. void WidgetDropDown::ClearOptions() { while (Element* element = selection_element->GetLastChild()) selection_element->RemoveChild(element); } -// Returns on of the widget's options. Element* WidgetDropDown::GetOption(int index) { return selection_element->GetChild(index); } -// Returns the number of options in the widget. int WidgetDropDown::GetNumOptions() const { return selection_element->GetNumChildren(); @@ -478,7 +471,7 @@ void WidgetDropDown::DetachScrollEvent() void WidgetDropDown::ProcessEvent(Event& event) { - if (parent_element->IsDisabled()) + if (parent_element->IsDisabled()) return; // Process the button onclick @@ -548,7 +541,7 @@ void WidgetDropDown::ProcessEvent(Event& event) break; case EventId::Keydown: { - Input::KeyIdentifier key_identifier = (Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); + Input::KeyIdentifier key_identifier = (Input::KeyIdentifier)event.GetParameter("key_identifier", 0); switch (key_identifier) { @@ -565,8 +558,7 @@ void WidgetDropDown::ProcessEvent(Event& event) parent_element->Click(); event.StopPropagation(); break; - default: - break; + default: break; } } break; @@ -591,12 +583,10 @@ void WidgetDropDown::ProcessEvent(Event& event) } } break; - default: - break; + default: break; } } -// Shows or hides the selection box. void WidgetDropDown::ShowSelectBox(bool show) { if (show) diff --git a/Source/Core/Elements/WidgetDropDown.h b/Source/Core/Elements/WidgetDropDown.h index 6f61311db..97564ec26 100644 --- a/Source/Core/Elements/WidgetDropDown.h +++ b/Source/Core/Elements/WidgetDropDown.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,12 +36,11 @@ namespace Rml { class ElementFormControl; /** - Widget for drop-down functionality. - @author Lloyd Weehuizen + Widget for drop-down functionality. + @author Lloyd Weehuizen */ -class WidgetDropDown : public EventListener -{ +class WidgetDropDown : public EventListener { public: WidgetDropDown(ElementFormControl* element); virtual ~WidgetDropDown(); diff --git a/Source/Core/Elements/WidgetSlider.cpp b/Source/Core/Elements/WidgetSlider.cpp index 807dbc525..ff0775361 100644 --- a/Source/Core/Elements/WidgetSlider.cpp +++ b/Source/Core/Elements/WidgetSlider.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,13 +28,13 @@ #include "WidgetSlider.h" #include "../../../Include/RmlUi/Core/ComputedValues.h" -#include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h" +#include "../../../Include/RmlUi/Core/Context.h" #include "../../../Include/RmlUi/Core/ElementUtilities.h" +#include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h" #include "../../../Include/RmlUi/Core/Factory.h" #include "../../../Include/RmlUi/Core/Input.h" #include "../../../Include/RmlUi/Core/Profiling.h" #include "../Clock.h" -#include "../../../Include/RmlUi/Core/Context.h" namespace Rml { @@ -89,7 +89,6 @@ WidgetSlider::~WidgetSlider() } } -// Initialises the slider to a given orientation. bool WidgetSlider::Initialise() { // Create all of our child elements as standard elements, and abort if we can't create them. @@ -126,7 +125,6 @@ bool WidgetSlider::Initialise() return true; } -// Updates the key repeats for the increment / decrement arrows. void WidgetSlider::Update() { for (int i = 0; i < 2; i++) @@ -150,48 +148,48 @@ void WidgetSlider::Update() SetBarPosition(i == 0 ? OnLineDecrement() : OnLineIncrement()); } - if(Context* ctx = parent->GetContext()) + if (Context* ctx = parent->GetContext()) ctx->RequestNextUpdate(arrow_timers[i]); } } } -// Sets the position of the bar. void WidgetSlider::SetBarPosition(float _bar_position) { bar_position = Math::Clamp(_bar_position, 0.0f, 1.0f); PositionBar(); } -// Returns the current position of the bar. float WidgetSlider::GetBarPosition() { return bar_position; } -// Sets the orientation of the slider. void WidgetSlider::SetOrientation(Orientation _orientation) { orientation = _orientation; } -// Returns the slider's orientation. WidgetSlider::Orientation WidgetSlider::GetOrientation() const { return orientation; } -// Sets the dimensions to the size of the slider. void WidgetSlider::GetDimensions(Vector2f& dimensions) const { switch (orientation) { - case VERTICAL: dimensions.x = 16; dimensions.y = 256; break; - case HORIZONTAL: dimensions.x = 256; dimensions.y = 16; break; + case VERTICAL: + dimensions.x = 16; + dimensions.y = 256; + break; + case HORIZONTAL: + dimensions.x = 256; + dimensions.y = 16; + break; } } - void WidgetSlider::SetValue(float target_value) { float num_steps = (target_value - min_value) / step; @@ -206,7 +204,6 @@ float WidgetSlider::GetValue() const return value; } -// Sets the minimum value of the slider. void WidgetSlider::SetMinValue(float _min_value) { if (_min_value != min_value) @@ -216,7 +213,6 @@ void WidgetSlider::SetMinValue(float _min_value) } } -// Sets the maximum value of the slider. void WidgetSlider::SetMaxValue(float _max_value) { if (_max_value != max_value) @@ -226,7 +222,6 @@ void WidgetSlider::SetMaxValue(float _max_value) } } -// Sets the slider's value increment. void WidgetSlider::SetStep(float _step) { // Can't have a zero step! @@ -236,7 +231,6 @@ void WidgetSlider::SetStep(float _step) step = _step; } -// Formats the slider's elements. void WidgetSlider::FormatElements() { RMLUI_ZoneScopedNC("RangeOnResize", 0x228044); @@ -245,8 +239,6 @@ void WidgetSlider::FormatElements() WidgetSlider::FormatElements(box, GetOrientation() == VERTICAL ? box.y : box.x); } - -// Lays out and resizes the internal elements. void WidgetSlider::FormatElements(const Vector2f containing_block, float slider_length) { int length_axis = orientation == VERTICAL ? 1 : 0; @@ -264,12 +256,12 @@ void WidgetSlider::FormatElements(const Vector2f containing_block, float slider_ Box track_box; ElementUtilities::BuildBox(track_box, parent_box.GetSize(), track); content = track_box.GetSize(); - content[length_axis] = slider_length -= orientation == VERTICAL ? (track_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + track_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)) : - (track_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + track_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); + content[length_axis] = slider_length -= orientation == VERTICAL + ? (track_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + track_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)) + : (track_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + track_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); // If no height has been explicitly specified for the track, it'll be initialised to -1 as per normal block // elements. We'll fix that up here. - if (orientation == HORIZONTAL && - content.y < 0) + if (orientation == HORIZONTAL && content.y < 0) content.y = parent_box.GetSize().y; // Now we size the arrows. @@ -280,8 +272,7 @@ void WidgetSlider::FormatElements(const Vector2f containing_block, float slider_ // Clamp the size to (0, 0). Vector2f arrow_size = arrow_box.GetSize(); - if (arrow_size.x < 0 || - arrow_size.y < 0) + if (arrow_size.x < 0 || arrow_size.y < 0) arrow_box.SetContent(Vector2f(0, 0)); arrows[i]->SetBox(arrow_box); @@ -300,11 +291,13 @@ void WidgetSlider::FormatElements(const Vector2f containing_block, float slider_ arrows[0]->SetOffset(offset, parent); offset.x = track->GetBox().GetEdge(Box::MARGIN, Box::LEFT); - offset.y += arrows[0]->GetBox().GetSize(Box::BORDER).y + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + track->GetBox().GetEdge(Box::MARGIN, Box::TOP); + offset.y += arrows[0]->GetBox().GetSize(Box::BORDER).y + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + + track->GetBox().GetEdge(Box::MARGIN, Box::TOP); track->SetOffset(offset, parent); offset.x = arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::LEFT); - offset.y += track->GetBox().GetSize(Box::BORDER).y + track->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::TOP); + offset.y += track->GetBox().GetSize(Box::BORDER).y + track->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::TOP); arrows[1]->SetOffset(offset, parent); } else @@ -312,11 +305,13 @@ void WidgetSlider::FormatElements(const Vector2f containing_block, float slider_ Vector2f offset(arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::LEFT), arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::TOP)); arrows[0]->SetOffset(offset, parent); - offset.x += arrows[0]->GetBox().GetSize(Box::BORDER).x + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + track->GetBox().GetEdge(Box::MARGIN, Box::LEFT); + offset.x += arrows[0]->GetBox().GetSize(Box::BORDER).x + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + + track->GetBox().GetEdge(Box::MARGIN, Box::LEFT); offset.y = track->GetBox().GetEdge(Box::MARGIN, Box::TOP); track->SetOffset(offset, parent); - offset.x += track->GetBox().GetSize(Box::BORDER).x + track->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::LEFT); + offset.x += track->GetBox().GetSize(Box::BORDER).x + track->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::LEFT); offset.y = arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::TOP); arrows[1]->SetOffset(offset, parent); } @@ -325,15 +320,14 @@ void WidgetSlider::FormatElements(const Vector2f containing_block, float slider_ if (parent->IsDisabled()) { - // Propagate disabled state to child elements - bar->SetPseudoClass("disabled", true); - track->SetPseudoClass("disabled", true); - arrows[0]->SetPseudoClass("disabled", true); - arrows[1]->SetPseudoClass("disabled", true); + // Propagate disabled state to child elements + bar->SetPseudoClass("disabled", true); + track->SetPseudoClass("disabled", true); + arrows[0]->SetPseudoClass("disabled", true); + arrows[1]->SetPseudoClass("disabled", true); } } -// Lays out and positions the bar element. void WidgetSlider::FormatBar() { Box bar_box; @@ -355,13 +349,11 @@ void WidgetSlider::FormatBar() PositionBar(); } -// Returns the widget's parent element. Element* WidgetSlider::GetParent() const { return parent; } -// Handles events coming through from the slider's components. void WidgetSlider::ProcessEvent(Event& event) { if (parent->IsDisabled()) @@ -381,12 +373,12 @@ void WidgetSlider::ProcessEvent(Event& event) if (orientation == HORIZONTAL) { - mouse_position = event.GetParameter< float >("mouse_x", 0); + mouse_position = event.GetParameter("mouse_x", 0); bar_halfsize = 0.5f * bar->GetBox().GetSize(Box::BORDER).x; } else { - mouse_position = event.GetParameter< float >("mouse_y", 0); + mouse_position = event.GetParameter("mouse_y", 0); bar_halfsize = 0.5f * bar->GetBox().GetSize(Box::BORDER).y; } @@ -425,9 +417,9 @@ void WidgetSlider::ProcessEvent(Event& event) bar->SetPseudoClass("active", true); if (orientation == HORIZONTAL) - bar_drag_anchor = event.GetParameter< float >("mouse_x", 0) - bar->GetAbsoluteOffset().x; + bar_drag_anchor = event.GetParameter("mouse_x", 0) - bar->GetAbsoluteOffset().x; else - bar_drag_anchor = event.GetParameter< float >("mouse_y", 0) - bar->GetAbsoluteOffset().y; + bar_drag_anchor = event.GetParameter("mouse_y", 0) - bar->GetAbsoluteOffset().y; } } break; @@ -435,7 +427,7 @@ void WidgetSlider::ProcessEvent(Event& event) { if (event.GetTargetElement() == bar || event.GetTargetElement() == track) { - float new_bar_offset = event.GetParameter< float >((orientation == HORIZONTAL ? "mouse_x" : "mouse_y"), 0) - bar_drag_anchor; + float new_bar_offset = event.GetParameter((orientation == HORIZONTAL ? "mouse_x" : "mouse_y"), 0) - bar_drag_anchor; float new_bar_position = AbsolutePositionToBarPosition(new_bar_offset); SetBarPosition(OnBarChange(new_bar_position)); @@ -451,13 +443,14 @@ void WidgetSlider::ProcessEvent(Event& event) } break; - case EventId::Keydown: { - const Input::KeyIdentifier key_identifier = (Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); + const Input::KeyIdentifier key_identifier = (Input::KeyIdentifier)event.GetParameter("key_identifier", 0); - const bool increment = (key_identifier == Input::KI_RIGHT && orientation == HORIZONTAL) || (key_identifier == Input::KI_DOWN && orientation == VERTICAL); - const bool decrement = (key_identifier == Input::KI_LEFT && orientation == HORIZONTAL) || (key_identifier == Input::KI_UP && orientation == VERTICAL); + const bool increment = + (key_identifier == Input::KI_RIGHT && orientation == HORIZONTAL) || (key_identifier == Input::KI_DOWN && orientation == VERTICAL); + const bool decrement = + (key_identifier == Input::KI_LEFT && orientation == HORIZONTAL) || (key_identifier == Input::KI_UP && orientation == VERTICAL); if (increment || decrement) { @@ -480,12 +473,10 @@ void WidgetSlider::ProcessEvent(Event& event) } break; - default: - break; + default: break; } } -// Called when the slider's bar position is set or dragged. float WidgetSlider::OnBarChange(float bar_position) { float new_value = min_value + bar_position * (max_value - min_value); @@ -494,13 +485,11 @@ float WidgetSlider::OnBarChange(float bar_position) return SetValueInternal(value + num_steps * step); } -// Called when the slider is incremented by one 'line'. float WidgetSlider::OnLineIncrement() { return SetValueInternal(value + step); } -// Called when the slider is decremented by one 'line'. float WidgetSlider::OnLineDecrement() { return SetValueInternal(value - step); @@ -540,7 +529,6 @@ float WidgetSlider::AbsolutePositionToBarPosition(float absolute_position) const return new_bar_position; } - void WidgetSlider::PositionBar() { const Vector2f track_dimensions = track->GetBox().GetSize(); @@ -552,13 +540,9 @@ void WidgetSlider::PositionBar() const float edge_bottom = bar->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM); float traversable_track_length = track_dimensions.y - bar_dimensions.y - edge_top - edge_bottom; - bar->SetOffset( - Vector2f( - bar->GetBox().GetEdge(Box::MARGIN, Box::LEFT), - track->GetRelativeOffset().y + edge_top + traversable_track_length * bar_position - ), - parent - ); + bar->SetOffset(Vector2f(bar->GetBox().GetEdge(Box::MARGIN, Box::LEFT), + track->GetRelativeOffset().y + edge_top + traversable_track_length * bar_position), + parent); } else { @@ -566,17 +550,12 @@ void WidgetSlider::PositionBar() const float edge_right = bar->GetBox().GetEdge(Box::MARGIN, Box::RIGHT); float traversable_track_length = track_dimensions.x - bar_dimensions.x - edge_left - edge_right; - bar->SetOffset( - Vector2f( - track->GetRelativeOffset().x + edge_left + traversable_track_length * bar_position, - bar->GetBox().GetEdge(Box::MARGIN, Box::TOP) - ), - parent - ); + bar->SetOffset(Vector2f(track->GetRelativeOffset().x + edge_left + traversable_track_length * bar_position, + bar->GetBox().GetEdge(Box::MARGIN, Box::TOP)), + parent); } } -// Clamps the new value, sets it on the slider. float WidgetSlider::SetValueInternal(float new_value, bool force_submit_change_event) { if (min_value < max_value) diff --git a/Source/Core/Elements/WidgetSlider.h b/Source/Core/Elements/WidgetSlider.h index da6ba004e..6349f2a48 100644 --- a/Source/Core/Elements/WidgetSlider.h +++ b/Source/Core/Elements/WidgetSlider.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,19 +36,14 @@ namespace Rml { class ElementFormControl; /** - A generic widget for incorporating sliding functionality into an element. + A generic widget for incorporating sliding functionality into an element. - @author Peter Curry + @author Peter Curry */ -class WidgetSlider final : public EventListener -{ +class WidgetSlider final : public EventListener { public: - enum Orientation - { - VERTICAL, - HORIZONTAL - }; + enum Orientation { VERTICAL, HORIZONTAL }; WidgetSlider(ElementFormControl* parent); virtual ~WidgetSlider(); @@ -126,7 +121,7 @@ class WidgetSlider final : public EventListener // Clamps the new value, sets it on the slider and returns it as a normalized number from 0 to 1. float SetValueInternal(float new_value, bool force_submit_change_event = true); - ElementFormControl* parent; + ElementFormControl* parent; Orientation orientation; diff --git a/Source/Core/Elements/WidgetTextInput.cpp b/Source/Core/Elements/WidgetTextInput.cpp index 5b3cd9dba..d93571592 100644 --- a/Source/Core/Elements/WidgetTextInput.cpp +++ b/Source/Core/Elements/WidgetTextInput.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,6 +28,7 @@ #include "WidgetTextInput.h" #include "../../../Include/RmlUi/Core/ComputedValues.h" +#include "../../../Include/RmlUi/Core/Context.h" #include "../../../Include/RmlUi/Core/Core.h" #include "../../../Include/RmlUi/Core/ElementScroll.h" #include "../../../Include/RmlUi/Core/ElementText.h" @@ -40,7 +41,6 @@ #include "../../../Include/RmlUi/Core/Math.h" #include "../../../Include/RmlUi/Core/StringUtilities.h" #include "../../../Include/RmlUi/Core/SystemInterface.h" -#include "../../../Include/RmlUi/Core/Context.h" #include "../Clock.h" #include "ElementTextSelection.h" #include @@ -104,10 +104,11 @@ static bool ClampValue(String& value, int max_length) return false; } -WidgetTextInput::WidgetTextInput(ElementFormControl* _parent) : internal_dimensions(0, 0), scroll_offset(0, 0), selection_geometry(_parent), cursor_position(0, 0), cursor_size(0, 0), cursor_geometry(_parent) +WidgetTextInput::WidgetTextInput(ElementFormControl* _parent) : + internal_dimensions(0, 0), scroll_offset(0, 0), selection_geometry(_parent), cursor_position(0, 0), cursor_size(0, 0), cursor_geometry(_parent) { keyboard_showed = false; - + parent = _parent; parent->SetProperty(PropertyId::WhiteSpace, Property(Style::WhiteSpace::Pre)); parent->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Hidden)); @@ -126,9 +127,9 @@ WidgetTextInput::WidgetTextInput(ElementFormControl* _parent) : internal_dimensi parent->AddEventListener(EventId::Drag, this, true); ElementPtr unique_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes()); - text_element = rmlui_dynamic_cast< ElementText* >(unique_text.get()); + text_element = rmlui_dynamic_cast(unique_text.get()); ElementPtr unique_selected_text = Factory::InstanceElement(parent, "#text", "#text", XMLAttributes()); - selected_text_element = rmlui_dynamic_cast< ElementText* >(unique_selected_text.get()); + selected_text_element = rmlui_dynamic_cast(unique_selected_text.get()); if (text_element) { text_element->SuppressAutoLayout(); @@ -215,7 +216,6 @@ void WidgetTextInput::SetValue(String value) void WidgetTextInput::TransformValue(String& /*value*/) {} -// Sets the maximum length (in characters) of this text field. void WidgetTextInput::SetMaxLength(int _max_length) { if (max_length != _max_length) @@ -228,7 +228,6 @@ void WidgetTextInput::SetMaxLength(int _max_length) } } -// Returns the maximum length (in characters) of this text field. int WidgetTextInput::GetMaxLength() const { return max_length; @@ -251,7 +250,7 @@ void WidgetTextInput::SetSelectionRange(int selection_start, int selection_end) const int byte_start = ConvertCharacterOffsetToByteOffset(value, selection_start); const int byte_end = ConvertCharacterOffsetToByteOffset(value, selection_end); const bool is_selecting = (byte_start != byte_end); - + cursor_wrap_down = true; absolute_cursor_index = byte_end; @@ -283,7 +282,6 @@ void WidgetTextInput::GetSelection(int* selection_start, int* selection_end, Str *selected_text = value.substr(Math::Min((size_t)selection_begin_index, (size_t)value.size()), (size_t)selection_length); } -// Update the colours of the selected text. void WidgetTextInput::UpdateSelectionColours() { // Determine what the colour of the selected text is. If our 'selection' element has the 'color' @@ -291,7 +289,7 @@ void WidgetTextInput::UpdateSelectionColours() Colourb colour; const Property* colour_property = selection_element->GetLocalProperty("color"); if (colour_property != nullptr) - colour = colour_property->Get< Colourb >(); + colour = colour_property->Get(); else { colour = parent->GetComputedValues().color(); @@ -308,7 +306,7 @@ void WidgetTextInput::UpdateSelectionColours() // colour. colour_property = selection_element->GetLocalProperty("background-color"); if (colour_property != nullptr) - selection_colour = colour_property->Get< Colourb >(); + selection_colour = colour_property->Get(); else selection_colour = Colourb(255 - colour.red, 255 - colour.green, 255 - colour.blue, colour.alpha); @@ -316,7 +314,6 @@ void WidgetTextInput::UpdateSelectionColours() GenerateCursor(); } -// Updates the cursor, if necessary. void WidgetTextInput::OnUpdate() { if (cursor_timer > 0) @@ -331,8 +328,9 @@ void WidgetTextInput::OnUpdate() cursor_visible = !cursor_visible; } - if(parent->IsVisible(true)) { - if(Context* ctx = parent->GetContext()) + if (parent->IsVisible(true)) + { + if (Context* ctx = parent->GetContext()) ctx->RequestNextUpdate(cursor_timer); } } @@ -349,7 +347,6 @@ void WidgetTextInput::OnResize() ForceFormattingOnNextLayout(); } -// Renders the cursor, if it is visible. void WidgetTextInput::OnRender() { ElementUtilities::SetClippingRegion(text_element); @@ -357,14 +354,12 @@ void WidgetTextInput::OnRender() Vector2f text_translation = parent->GetAbsoluteOffset() - Vector2f(parent->GetScrollLeft(), parent->GetScrollTop()); selection_geometry.Render(text_translation); - if (cursor_visible && - !parent->IsDisabled()) + if (cursor_visible && !parent->IsDisabled()) { cursor_geometry.Render(text_translation + cursor_position); } } -// Formats the widget's internal content. void WidgetTextInput::OnLayout() { if (force_formatting_on_next_layout) @@ -379,13 +374,11 @@ void WidgetTextInput::OnLayout() parent->SetScrollTop(scroll_offset.y); } -// Gets the parent element containing the widget. Element* WidgetTextInput::GetElement() const { return parent; } -// Dispatches a change event to the widget's element. void WidgetTextInput::DispatchChangeEvent(bool linebreak) { Dictionary parameters; @@ -394,8 +387,6 @@ void WidgetTextInput::DispatchChangeEvent(bool linebreak) GetElement()->DispatchEvent(EventId::Change, parameters); } -// Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and "blur" to set -// the state of the cursor. void WidgetTextInput::ProcessEvent(Event& event) { if (parent->IsDisabled()) @@ -405,10 +396,10 @@ void WidgetTextInput::ProcessEvent(Event& event) { case EventId::Keydown: { - Input::KeyIdentifier key_identifier = (Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0); - bool numlock = event.GetParameter< int >("num_lock_key", 0) > 0; - bool shift = event.GetParameter< int >("shift_key", 0) > 0; - bool ctrl = event.GetParameter< int >("ctrl_key", 0) > 0; + Input::KeyIdentifier key_identifier = (Input::KeyIdentifier)event.GetParameter("key_identifier", 0); + bool numlock = event.GetParameter("num_lock_key", 0) > 0; + bool shift = event.GetParameter("shift_key", 0) > 0; + bool ctrl = event.GetParameter("ctrl_key", 0) > 0; bool selection_changed = false; switch (key_identifier) @@ -454,7 +445,7 @@ void WidgetTextInput::ProcessEvent(Event& event) ShowCursor(true); } break; - // clang-format on + // clang-format on case Input::KI_NUMPADENTER: case Input::KI_RETURN: @@ -503,11 +494,9 @@ void WidgetTextInput::ProcessEvent(Event& event) break; // Ignore tabs so input fields can be navigated through with keys. - case Input::KI_TAB: - return; + case Input::KI_TAB: return; - default: - break; + default: break; } event.StopPropagation(); @@ -519,9 +508,7 @@ void WidgetTextInput::ProcessEvent(Event& event) case EventId::Textinput: { // Only process the text if no modifier keys are pressed. - if (event.GetParameter< int >("ctrl_key", 0) == 0 && - event.GetParameter< int >("alt_key", 0) == 0 && - event.GetParameter< int >("meta_key", 0) == 0) + if (event.GetParameter("ctrl_key", 0) == 0 && event.GetParameter("alt_key", 0) == 0 && event.GetParameter("meta_key", 0) == 0) { String text = event.GetParameter("text", String{}); AddCharacters(text); @@ -563,7 +550,7 @@ void WidgetTextInput::ProcessEvent(Event& event) { if (event.GetTargetElement() == parent) { - Vector2f mouse_position = Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0)); + Vector2f mouse_position = Vector2f(event.GetParameter("mouse_x", 0), event.GetParameter("mouse_y", 0)); mouse_position -= text_element->GetAbsoluteOffset(); const int cursor_line_index = CalculateLineIndex(mouse_position.y); @@ -593,12 +580,10 @@ void WidgetTextInput::ProcessEvent(Event& event) } break; - default: - break; + default: break; } } -// Adds a new character to the string at the cursor position. bool WidgetTextInput::AddCharacters(String string) { SanitizeValue(string); @@ -625,7 +610,6 @@ bool WidgetTextInput::AddCharacters(String string) return true; } -// Deletes a character from the string. bool WidgetTextInput::DeleteCharacters(CursorMovement direction) { // We set a selection of characters according to direction, and then delete it. @@ -644,7 +628,6 @@ bool WidgetTextInput::DeleteCharacters(CursorMovement direction) return false; } -// Copies the selection (if any) to the clipboard. void WidgetTextInput::CopySelection() { const String& value = GetValue(); @@ -652,7 +635,6 @@ void WidgetTextInput::CopySelection() GetSystemInterface()->SetClipboardText(snippet); } -// Moves the cursor along the current line. bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select) { const String& value = GetValue(); @@ -668,12 +650,8 @@ bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select) switch (movement) { - case CursorMovement::Begin: - absolute_cursor_index = 0; - break; - case CursorMovement::BeginLine: - SetCursorFromRelativeIndices(cursor_line_index, 0); - break; + case CursorMovement::Begin: absolute_cursor_index = 0; break; + case CursorMovement::BeginLine: SetCursorFromRelativeIndices(cursor_line_index, 0); break; case CursorMovement::PreviousWord: { // First skip whitespace, then skip all characters of the same class as the first non-whitespace character. @@ -722,7 +700,7 @@ bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select) const CharacterClass character_class = GetCharacterClass(*p); if (skip_character_class == CharacterClass::Undefined) skip_character_class = character_class; - + if (character_class != skip_character_class) { if (character_class == CharacterClass::Whitespace) @@ -734,12 +712,8 @@ bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select) absolute_cursor_index += int(p - p_begin); } break; - case CursorMovement::EndLine: - SetCursorFromRelativeIndices(cursor_line_index, lines[cursor_line_index].editable_length); - break; - case CursorMovement::End: - absolute_cursor_index = INT_MAX; - break; + case CursorMovement::EndLine: SetCursorFromRelativeIndices(cursor_line_index, lines[cursor_line_index].editable_length); break; + case CursorMovement::End: absolute_cursor_index = INT_MAX; break; } absolute_cursor_index = Math::Clamp(absolute_cursor_index, 0, (int)GetValue().size()); @@ -753,7 +727,6 @@ bool WidgetTextInput::MoveCursorHorizontal(CursorMovement movement, bool select) return selection_changed; } -// Moves the cursor up and down the text field. bool WidgetTextInput::MoveCursorVertical(int distance, bool select) { int cursor_line_index = 0, cursor_character_index = 0; @@ -928,15 +901,13 @@ void WidgetTextInput::SetCursorFromRelativeIndices(int cursor_line_index, int cu cursor_wrap_down = !(cursor_character_index >= lines[cursor_line_index].editable_length); } -// Calculates the line index under a specific vertical position. int WidgetTextInput::CalculateLineIndex(float position) const { float line_height = parent->GetLineHeight(); int line_index = Math::RealToInteger(position / line_height); - return Math::Clamp(line_index, 0, (int) (lines.size() - 1)); + return Math::Clamp(line_index, 0, (int)(lines.size() - 1)); } -// Calculates the character index along a line under a specific horizontal position. int WidgetTextInput::CalculateCharacterIndex(int line_index, float position) { int prev_offset = 0; @@ -972,7 +943,6 @@ int WidgetTextInput::CalculateCharacterIndex(int line_index, float position) return prev_offset; } -// Shows or hides the cursor. void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor) { if (show) @@ -1016,7 +986,6 @@ void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor) } } -// Formats the element, laying out the text and inserting scrollbars as appropriate. void WidgetTextInput::FormatElement() { using namespace Style; @@ -1077,8 +1046,8 @@ Vector2f WidgetTextInput::FormatText(float height_constraint) // Clear the selection background geometry, and get the vertices and indices so the new geo can // be generated. selection_geometry.Release(true); - Vector< Vertex >& selection_vertices = selection_geometry.GetVertices(); - Vector< int >& selection_indices = selection_geometry.GetIndices(); + Vector& selection_vertices = selection_geometry.GetVertices(); + Vector& selection_indices = selection_geometry.GetIndices(); // Determine the line-height of the text element. const float line_height = parent->GetLineHeight(); @@ -1219,19 +1188,18 @@ Vector2f WidgetTextInput::FormatText(float height_constraint) return content_area; } -// Generates the text cursor. void WidgetTextInput::GenerateCursor() { // Generates the cursor. cursor_geometry.Release(); - Vector< Vertex >& vertices = cursor_geometry.GetVertices(); + Vector& vertices = cursor_geometry.GetVertices(); vertices.resize(4); - Vector< int >& indices = cursor_geometry.GetIndices(); + Vector& indices = cursor_geometry.GetIndices(); indices.resize(6); - cursor_size.x = Math::RoundFloat( ElementUtilities::GetDensityIndependentPixelRatio(text_element) ); + cursor_size.x = Math::RoundFloat(ElementUtilities::GetDensityIndependentPixelRatio(text_element)); cursor_size.y = text_element->GetLineHeight() + 2.0f; Colourb color = parent->GetComputedValues().color(); @@ -1258,7 +1226,8 @@ void WidgetTextInput::UpdateCursorPosition(bool update_ideal_cursor_position) int cursor_line_index = 0, cursor_character_index = 0; GetRelativeCursorIndices(cursor_line_index, cursor_character_index); - cursor_position.x = (float)ElementUtilities::GetStringWidth(text_element, GetValue().substr(lines[cursor_line_index].value_offset, cursor_character_index)); + cursor_position.x = + (float)ElementUtilities::GetStringWidth(text_element, GetValue().substr(lines[cursor_line_index].value_offset, cursor_character_index)); cursor_position.y = -1.f + (float)cursor_line_index * text_element->GetLineHeight(); if (update_ideal_cursor_position) @@ -1289,20 +1258,18 @@ bool WidgetTextInput::UpdateSelection(bool selecting) new_end_index = selection_anchor_index; } - if (new_begin_index != selection_begin_index || - new_end_index - new_begin_index != selection_length) + if (new_begin_index != selection_begin_index || new_end_index - new_begin_index != selection_length) { selection_begin_index = new_begin_index; selection_length = new_end_index - new_begin_index; - selection_changed = true; + selection_changed = true; } } - + return selection_changed; } -// Removes the selection of text. bool WidgetTextInput::ClearSelection() { if (selection_length > 0) @@ -1313,7 +1280,6 @@ bool WidgetTextInput::ClearSelection() return false; } -// Deletes all selected text and removes the selection. void WidgetTextInput::DeleteSelection() { if (selection_length > 0) @@ -1333,7 +1299,6 @@ void WidgetTextInput::DeleteSelection() } } -// Split one line of text into three parts, based on the current selection. void WidgetTextInput::GetLineSelection(String& pre_selection, String& selection, String& post_selection, const String& line, int line_begin) const { const int selection_end = selection_begin_index + selection_length; @@ -1350,7 +1315,8 @@ void WidgetTextInput::GetLineSelection(String& pre_selection, String& selection, // Split the line up into its three parts, depending on the size and placement of the selection. pre_selection = line.substr(0, Max(0, selection_begin_index - line_begin)); - selection = line.substr(Clamp(selection_begin_index - line_begin, 0, line_length), Max(0, selection_length + Min(0, selection_begin_index - line_begin))); + selection = + line.substr(Clamp(selection_begin_index - line_begin, 0, line_length), Max(0, selection_length + Min(0, selection_begin_index - line_begin))); post_selection = line.substr(Clamp(selection_end - line_begin, 0, line_length)); } diff --git a/Source/Core/Elements/WidgetTextInput.h b/Source/Core/Elements/WidgetTextInput.h index 9cf429a3f..51949aa88 100644 --- a/Source/Core/Elements/WidgetTextInput.h +++ b/Source/Core/Elements/WidgetTextInput.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,13 +40,12 @@ class ElementText; class ElementFormControl; /** - An abstract widget for editing and navigating around a text field. + An abstract widget for editing and navigating around a text field. - @author Peter Curry + @author Peter Curry */ -class WidgetTextInput : public EventListener -{ +class WidgetTextInput : public EventListener { public: WidgetTextInput(ElementFormControl* parent); virtual ~WidgetTextInput(); @@ -179,7 +178,8 @@ class WidgetTextInput : public EventListener void UpdateCursorPosition(bool update_ideal_cursor_position); /// Expand or shrink the text selection to the position of the cursor. - /// @param[in] selecting True if the new position of the cursor should expand / contract the selection area, false if it should only set the anchor for future selections. + /// @param[in] selecting True if the new position of the cursor should expand / contract the selection area, false if it should only set the + /// anchor for future selections. /// @return True if selection was changed. bool UpdateSelection(bool selecting); /// Removes the selection of text. @@ -193,13 +193,13 @@ class WidgetTextInput : public EventListener /// Split one line of text into three parts, based on the current selection. /// @param[out] pre_selection The section of unselected text before any selected text on the line. /// @param[out] selection The section of selected text on the line. - /// @param[out] post_selection The section of unselected text after any selected text on the line. If there is no selection on the line, then this will be empty. + /// @param[out] post_selection The section of unselected text after any selected text on the line. If there is no selection on the line, then this + /// will be empty. /// @param[in] line The text making up the line. /// @param[in] line_begin The absolute index at the beginning of the line. void GetLineSelection(String& pre_selection, String& selection, String& post_selection, const String& line, int line_begin) const; - struct Line - { + struct Line { // Offset into the text field's value. int value_offset; // The size of the contents of the line (including the trailing endline, if that terminated the line). diff --git a/Source/Core/Elements/WidgetTextInputMultiLine.cpp b/Source/Core/Elements/WidgetTextInputMultiLine.cpp index 832b0dea0..81c76d90a 100644 --- a/Source/Core/Elements/WidgetTextInputMultiLine.cpp +++ b/Source/Core/Elements/WidgetTextInputMultiLine.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -42,7 +42,6 @@ void WidgetTextInputMultiLine::SanitizeValue(String& value) value.erase(std::remove_if(value.begin(), value.end(), [](char c) { return c == '\r' || c == '\t'; }), value.end()); } -// Called when the user pressed enter. void WidgetTextInputMultiLine::LineBreak() {} } // namespace Rml diff --git a/Source/Core/Elements/WidgetTextInputMultiLine.h b/Source/Core/Elements/WidgetTextInputMultiLine.h index e0907c93a..0a8890c43 100644 --- a/Source/Core/Elements/WidgetTextInputMultiLine.h +++ b/Source/Core/Elements/WidgetTextInputMultiLine.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Elements/WidgetTextInputSingleLine.cpp b/Source/Core/Elements/WidgetTextInputSingleLine.cpp index bd8c6f280..1451450b5 100644 --- a/Source/Core/Elements/WidgetTextInputSingleLine.cpp +++ b/Source/Core/Elements/WidgetTextInputSingleLine.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Elements/WidgetTextInputSingleLine.h b/Source/Core/Elements/WidgetTextInputSingleLine.h index 529fa5658..f9d708def 100644 --- a/Source/Core/Elements/WidgetTextInputSingleLine.h +++ b/Source/Core/Elements/WidgetTextInputSingleLine.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Elements/WidgetTextInputSingleLinePassword.cpp b/Source/Core/Elements/WidgetTextInputSingleLinePassword.cpp index 6a8e3b922..88cdb677d 100644 --- a/Source/Core/Elements/WidgetTextInputSingleLinePassword.cpp +++ b/Source/Core/Elements/WidgetTextInputSingleLinePassword.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Elements/WidgetTextInputSingleLinePassword.h b/Source/Core/Elements/WidgetTextInputSingleLinePassword.h index d77297b4f..e03ba63fb 100644 --- a/Source/Core/Elements/WidgetTextInputSingleLinePassword.h +++ b/Source/Core/Elements/WidgetTextInputSingleLinePassword.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Elements/XMLNodeHandlerSelect.cpp b/Source/Core/Elements/XMLNodeHandlerSelect.cpp index 07ca4aaea..bb010b9a4 100644 --- a/Source/Core/Elements/XMLNodeHandlerSelect.cpp +++ b/Source/Core/Elements/XMLNodeHandlerSelect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,18 +27,16 @@ */ #include "XMLNodeHandlerSelect.h" -#include "../../../Include/RmlUi/Core/Log.h" +#include "../../../Include/RmlUi/Core/Elements/ElementFormControlSelect.h" #include "../../../Include/RmlUi/Core/Factory.h" +#include "../../../Include/RmlUi/Core/Log.h" #include "../../../Include/RmlUi/Core/XMLParser.h" -#include "../../../Include/RmlUi/Core/Elements/ElementFormControlSelect.h" namespace Rml { -XMLNodeHandlerSelect::XMLNodeHandlerSelect() -{} +XMLNodeHandlerSelect::XMLNodeHandlerSelect() {} -XMLNodeHandlerSelect::~XMLNodeHandlerSelect() -{} +XMLNodeHandlerSelect::~XMLNodeHandlerSelect() {} Element* XMLNodeHandlerSelect::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) { diff --git a/Source/Core/Elements/XMLNodeHandlerSelect.h b/Source/Core/Elements/XMLNodeHandlerSelect.h index 3beef6e50..db199b671 100644 --- a/Source/Core/Elements/XMLNodeHandlerSelect.h +++ b/Source/Core/Elements/XMLNodeHandlerSelect.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - XML node handler for processing the select and option tags. + XML node handler for processing the select and option tags. */ -class XMLNodeHandlerSelect : public XMLNodeHandlerDefault -{ +class XMLNodeHandlerSelect : public XMLNodeHandlerDefault { public: XMLNodeHandlerSelect(); virtual ~XMLNodeHandlerSelect(); diff --git a/Source/Core/Elements/XMLNodeHandlerTabSet.cpp b/Source/Core/Elements/XMLNodeHandlerTabSet.cpp index 1c67d391e..ca7409366 100644 --- a/Source/Core/Elements/XMLNodeHandlerTabSet.cpp +++ b/Source/Core/Elements/XMLNodeHandlerTabSet.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,28 +27,20 @@ */ #include "XMLNodeHandlerTabSet.h" -#include "../../../Include/RmlUi/Core/Log.h" +#include "../../../Include/RmlUi/Core/Elements/ElementTabSet.h" #include "../../../Include/RmlUi/Core/Factory.h" +#include "../../../Include/RmlUi/Core/Log.h" #include "../../../Include/RmlUi/Core/XMLParser.h" -#include "../../../Include/RmlUi/Core/Elements/ElementTabSet.h" namespace Rml { -XMLNodeHandlerTabSet::XMLNodeHandlerTabSet() -{ -} +XMLNodeHandlerTabSet::XMLNodeHandlerTabSet() {} -XMLNodeHandlerTabSet::~XMLNodeHandlerTabSet() -{ -} +XMLNodeHandlerTabSet::~XMLNodeHandlerTabSet() {} Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) { - RMLUI_ASSERT(name == "tabset" || - name == "tabs" || - name == "tab" || - name == "panels" || - name == "panel"); + RMLUI_ASSERT(name == "tabset" || name == "tabs" || name == "tab" || name == "panels" || name == "panel"); if (name == "tabset") { @@ -56,8 +48,8 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam parser->PushHandler("tabset"); // Attempt to instance the tabset - ElementPtr element = Factory::InstanceElement(parser->GetParseFrame()->element, name, name, attributes); - ElementTabSet* tabset = rmlui_dynamic_cast< ElementTabSet* >(element.get()); + ElementPtr element = Factory::InstanceElement(parser->GetParseFrame()->element, name, name, attributes); + ElementTabSet* tabset = rmlui_dynamic_cast(element.get()); if (!tabset) { Log::Message(Log::LT_ERROR, "Instancer failed to create element for tag %s.", name.c_str()); @@ -68,7 +60,7 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam Element* result = parser->GetParseFrame()->element->AppendChild(std::move(element)); return result; - } + } else if (name == "tab") { // Call default element handler for all children. @@ -77,7 +69,7 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam ElementPtr tab_element = Factory::InstanceElement(parser->GetParseFrame()->element, "*", "tab", attributes); Element* result = nullptr; - ElementTabSet* tabset = rmlui_dynamic_cast< ElementTabSet* >(parser->GetParseFrame()->element); + ElementTabSet* tabset = rmlui_dynamic_cast(parser->GetParseFrame()->element); if (tabset) { result = tab_element.get(); @@ -85,7 +77,6 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam } return result; - } else if (name == "panel") { @@ -95,7 +86,7 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam ElementPtr panel_element = Factory::InstanceElement(parser->GetParseFrame()->element, "*", "panel", attributes); Element* result = nullptr; - ElementTabSet* tabset = rmlui_dynamic_cast< ElementTabSet* >(parser->GetParseFrame()->element); + ElementTabSet* tabset = rmlui_dynamic_cast(parser->GetParseFrame()->element); if (tabset) { result = panel_element.get(); @@ -105,7 +96,7 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam return result; } else if (name == "tabs" || name == "panels") - { + { // Use the element handler to add the tabs and panels elements to the the tabset (this allows users to // style them nicely), but don't return the new element, as we still want the tabset to be the top of the // parser's node stack. @@ -127,17 +118,13 @@ Element* XMLNodeHandlerTabSet::ElementStart(XMLParser* parser, const String& nam return nullptr; } -bool XMLNodeHandlerTabSet::ElementEnd(XMLParser* RMLUI_UNUSED_PARAMETER(parser), const String& RMLUI_UNUSED_PARAMETER(name)) +bool XMLNodeHandlerTabSet::ElementEnd(XMLParser* /*parser*/, const String& /*name*/) { - RMLUI_UNUSED(parser); - RMLUI_UNUSED(name); - return true; } -bool XMLNodeHandlerTabSet::ElementData(XMLParser* parser, const String& data, XMLDataType RMLUI_UNUSED_PARAMETER(type)) -{ - RMLUI_UNUSED(type); +bool XMLNodeHandlerTabSet::ElementData(XMLParser* parser, const String& data, XMLDataType /*type*/) +{ return Factory::InstanceElementText(parser->GetParseFrame()->element, data); } diff --git a/Source/Core/Elements/XMLNodeHandlerTabSet.h b/Source/Core/Elements/XMLNodeHandlerTabSet.h index dd6c7a324..df64e9ec2 100644 --- a/Source/Core/Elements/XMLNodeHandlerTabSet.h +++ b/Source/Core/Elements/XMLNodeHandlerTabSet.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - XML node handler for processing the tabset tags. + XML node handler for processing the tabset tags. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class XMLNodeHandlerTabSet : public XMLNodeHandler -{ +class XMLNodeHandlerTabSet : public XMLNodeHandler { public: XMLNodeHandlerTabSet(); virtual ~XMLNodeHandlerTabSet(); diff --git a/Source/Core/Elements/XMLNodeHandlerTextArea.cpp b/Source/Core/Elements/XMLNodeHandlerTextArea.cpp index 45cd7a7a5..3617e8aac 100644 --- a/Source/Core/Elements/XMLNodeHandlerTextArea.cpp +++ b/Source/Core/Elements/XMLNodeHandlerTextArea.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,25 +27,21 @@ */ #include "XMLNodeHandlerTextArea.h" -#include "../../../Include/RmlUi/Core/Elements/ElementFormControlTextArea.h" #include "../../../Include/RmlUi/Core/Core.h" +#include "../../../Include/RmlUi/Core/Elements/ElementFormControlTextArea.h" #include "../../../Include/RmlUi/Core/Factory.h" #include "../../../Include/RmlUi/Core/SystemInterface.h" #include "../../../Include/RmlUi/Core/XMLParser.h" namespace Rml { -XMLNodeHandlerTextArea::XMLNodeHandlerTextArea() -{ -} +XMLNodeHandlerTextArea::XMLNodeHandlerTextArea() {} -XMLNodeHandlerTextArea::~XMLNodeHandlerTextArea() -{ -} +XMLNodeHandlerTextArea::~XMLNodeHandlerTextArea() {} Element* XMLNodeHandlerTextArea::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) { - ElementFormControlTextArea* text_area = rmlui_dynamic_cast< ElementFormControlTextArea* >(parser->GetParseFrame()->element); + ElementFormControlTextArea* text_area = rmlui_dynamic_cast(parser->GetParseFrame()->element); if (!text_area) { ElementPtr new_element = Factory::InstanceElement(parser->GetParseFrame()->element, name, name, attributes); @@ -60,19 +56,14 @@ Element* XMLNodeHandlerTextArea::ElementStart(XMLParser* parser, const String& n return nullptr; } -bool XMLNodeHandlerTextArea::ElementEnd(XMLParser* RMLUI_UNUSED_PARAMETER(parser), const String& RMLUI_UNUSED_PARAMETER(name)) +bool XMLNodeHandlerTextArea::ElementEnd(XMLParser* /*parser*/, const String& /*name*/) { - RMLUI_UNUSED(parser); - RMLUI_UNUSED(name); - return true; } -bool XMLNodeHandlerTextArea::ElementData(XMLParser* parser, const String& data, XMLDataType RMLUI_UNUSED_PARAMETER(type)) +bool XMLNodeHandlerTextArea::ElementData(XMLParser* parser, const String& data, XMLDataType /*type*/) { - RMLUI_UNUSED(type); - - ElementFormControlTextArea* text_area = rmlui_dynamic_cast< ElementFormControlTextArea* >(parser->GetParseFrame()->element); + ElementFormControlTextArea* text_area = rmlui_dynamic_cast(parser->GetParseFrame()->element); if (text_area != nullptr) { // Do any necessary translation. diff --git a/Source/Core/Elements/XMLNodeHandlerTextArea.h b/Source/Core/Elements/XMLNodeHandlerTextArea.h index daaedb395..62561fbba 100644 --- a/Source/Core/Elements/XMLNodeHandlerTextArea.h +++ b/Source/Core/Elements/XMLNodeHandlerTextArea.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - Node handler that processes the contents of the textarea tag. + Node handler that processes the contents of the textarea tag. - @author Peter Curry + @author Peter Curry */ -class XMLNodeHandlerTextArea : public XMLNodeHandler -{ +class XMLNodeHandlerTextArea : public XMLNodeHandler { public: XMLNodeHandlerTextArea(); virtual ~XMLNodeHandlerTextArea(); diff --git a/Source/Core/Event.cpp b/Source/Core/Event.cpp index b4cc062e5..75d508aad 100644 --- a/Source/Core/Event.cpp +++ b/Source/Core/Event.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,17 +27,15 @@ */ #include "../../Include/RmlUi/Core/Event.h" -#include "../../Include/RmlUi/Core/EventInstancer.h" #include "../../Include/RmlUi/Core/Element.h" +#include "../../Include/RmlUi/Core/EventInstancer.h" namespace Rml { -Event::Event() -{ -} +Event::Event() {} -Event::Event(Element* _target_element, EventId id, const String& type, const Dictionary& _parameters, bool interruptible) - : parameters(_parameters), target_element(_target_element), type(type), id(id), interruptible(interruptible) +Event::Event(Element* _target_element, EventId id, const String& type, const Dictionary& _parameters, bool interruptible) : + parameters(_parameters), target_element(_target_element), type(type), id(id), interruptible(interruptible) { const Variant* mouse_x = GetIf(parameters, "mouse_x"); const Variant* mouse_y = GetIf(parameters, "mouse_y"); @@ -49,14 +47,12 @@ Event::Event(Element* _target_element, EventId id, const String& type, const Dic } } -Event::~Event() -{ -} +Event::~Event() {} void Event::SetCurrentElement(Element* element) { current_element = element; - if(has_mouse_position) + if (has_mouse_position) { ProjectMouse(element); } @@ -122,7 +118,7 @@ bool Event::IsInterruptible() const void Event::StopImmediatePropagation() { - if(interruptible) + if (interruptible) { interrupted_immediate = true; interrupted = true; @@ -154,7 +150,7 @@ EventId Event::GetId() const void Event::ProjectMouse(Element* element) { - if(!element) + if (!element) { parameters["mouse_x"] = mouse_screen_position.x; parameters["mouse_y"] = mouse_screen_position.y; @@ -165,8 +161,8 @@ void Event::ProjectMouse(Element* element) if (element->GetTransformState()) { // Project mouse from parent (previous 'mouse_x/y' property) to child (element) - Variant *mouse_x = GetIf(parameters, "mouse_x"); - Variant *mouse_y = GetIf(parameters, "mouse_y"); + Variant* mouse_x = GetIf(parameters, "mouse_x"); + Variant* mouse_y = GetIf(parameters, "mouse_y"); if (!mouse_x || !mouse_y) { RMLUI_ERROR; diff --git a/Source/Core/EventDispatcher.cpp b/Source/Core/EventDispatcher.cpp index b18274791..5d1fdf48c 100644 --- a/Source/Core/EventDispatcher.cpp +++ b/Source/Core/EventDispatcher.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,22 +37,26 @@ namespace Rml { -bool operator==(EventListenerEntry a, EventListenerEntry b) { return a.id == b.id && a.in_capture_phase == b.in_capture_phase && a.listener == b.listener; } -bool operator!=(EventListenerEntry a, EventListenerEntry b) { return !(a == b); } +bool operator==(EventListenerEntry a, EventListenerEntry b) +{ + return a.id == b.id && a.in_capture_phase == b.in_capture_phase && a.listener == b.listener; +} +bool operator!=(EventListenerEntry a, EventListenerEntry b) +{ + return !(a == b); +} struct CompareId { bool operator()(EventListenerEntry a, EventListenerEntry b) const { return a.id < b.id; } -}; +}; struct CompareIdPhase { - bool operator()(EventListenerEntry a, EventListenerEntry b) const { return std::tie(a.id, a.in_capture_phase) < std::tie(b.id, b.in_capture_phase); } + bool operator()(EventListenerEntry a, EventListenerEntry b) const + { + return std::tie(a.id, a.in_capture_phase) < std::tie(b.id, b.in_capture_phase); + } }; - - -EventDispatcher::EventDispatcher(Element* _element) - : element(_element) -{ -} +EventDispatcher::EventDispatcher(Element* _element) : element(_element) {} EventDispatcher::~EventDispatcher() { @@ -75,7 +79,6 @@ void EventDispatcher::AttachEvent(const EventId id, EventListener* listener, con } } - void EventDispatcher::DetachEvent(const EventId id, EventListener* listener, const bool in_capture_phase) { const auto listenerIt = std::find(listeners.cbegin(), listeners.cend(), EventListenerEntry(id, listener, in_capture_phase)); @@ -86,7 +89,6 @@ void EventDispatcher::DetachEvent(const EventId id, EventListener* listener, con } } -// Detaches all events from this dispatcher and all child dispatchers. void EventDispatcher::DetachAllEvents() { for (const auto& event : listeners) @@ -99,14 +101,14 @@ void EventDispatcher::DetachAllEvents() } /* - CollectedListener + CollectedListener - When dispatching an event we collect all possible event listeners to execute. - They are stored in observer pointers, so that we can safely check if they have been destroyed since the previous listener execution. + When dispatching an event we collect all possible event listeners to execute. + They are stored in observer pointers, so that we can safely check if they have been destroyed since the previous listener execution. */ struct CollectedListener { - - CollectedListener(Element* _element, EventListener* _listener, int dom_distance_from_target, bool in_capture_phase) : element(_element->GetObserverPtr()), listener(_listener->GetObserverPtr()) + CollectedListener(Element* _element, EventListener* _listener, int dom_distance_from_target, bool in_capture_phase) : + element(_element->GetObserverPtr()), listener(_listener->GetObserverPtr()) { sort = dom_distance_from_target * (in_capture_phase ? -1 : 1); } @@ -121,21 +123,20 @@ struct CollectedListener { // Default actions are returned by EventPhase::None. EventPhase GetPhase() const { return sort < 0 ? EventPhase::Capture : (sort == 0 ? EventPhase::Target : EventPhase::Bubble); } - bool operator<(const CollectedListener& other) const { - return sort < other.sort; - } + bool operator<(const CollectedListener& other) const { return sort < other.sort; } }; - -bool EventDispatcher::DispatchEvent(Element* target_element, const EventId id, const String& type, const Dictionary& parameters, const bool interruptible, const bool bubbles, const DefaultActionPhase default_action_phase) +bool EventDispatcher::DispatchEvent(Element* target_element, const EventId id, const String& type, const Dictionary& parameters, + const bool interruptible, const bool bubbles, const DefaultActionPhase default_action_phase) { - RMLUI_ASSERTMSG(!((int)default_action_phase & (int)EventPhase::Capture), "We assume here that the default action phases cannot include capture phase."); + RMLUI_ASSERTMSG(!((int)default_action_phase & (int)EventPhase::Capture), + "We assume here that the default action phases cannot include capture phase."); Vector listeners; Vector> default_action_elements; const EventPhase phases_to_execute = EventPhase((int)EventPhase::Capture | (int)EventPhase::Target | (bubbles ? (int)EventPhase::Bubble : 0)); - + // Walk the DOM tree from target to root, collecting all possible listeners and elements with default actions in the process. int dom_distance_from_target = 0; Element* walk_element = target_element; @@ -144,12 +145,12 @@ bool EventDispatcher::DispatchEvent(Element* target_element, const EventId id, c EventDispatcher* dispatcher = walk_element->GetEventDispatcher(); dispatcher->CollectListeners(dom_distance_from_target, id, phases_to_execute, listeners); - if(dom_distance_from_target == 0) + if (dom_distance_from_target == 0) { if ((int)default_action_phase & (int)EventPhase::Target) default_action_elements.push_back(walk_element->GetObserverPtr()); } - else if((int)default_action_phase & (int)EventPhase::Bubble) + else if ((int)default_action_phase & (int)EventPhase::Bubble) { default_action_elements.push_back(walk_element->GetObserverPtr()); } @@ -216,8 +217,8 @@ bool EventDispatcher::DispatchEvent(Element* target_element, const EventId id, c return propagating; } - -void EventDispatcher::CollectListeners(int dom_distance_from_target, const EventId event_id, const EventPhase event_executes_in_phases, Vector& collect_listeners) +void EventDispatcher::CollectListeners(int dom_distance_from_target, const EventId event_id, const EventPhase event_executes_in_phases, + Vector& collect_listeners) { // Find all the entries with a matching id, given that listeners are sorted by id first. Listeners::iterator begin, end; @@ -247,7 +248,6 @@ void EventDispatcher::CollectListeners(int dom_distance_from_target, const Event } } - String EventDispatcher::ToString() const { String result; @@ -282,5 +282,4 @@ String EventDispatcher::ToString() const return result; } - } // namespace Rml diff --git a/Source/Core/EventDispatcher.h b/Source/Core/EventDispatcher.h index 31bed766d..b85dac33b 100644 --- a/Source/Core/EventDispatcher.h +++ b/Source/Core/EventDispatcher.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_EVENTDISPATCHER_H #define RMLUI_CORE_EVENTDISPATCHER_H -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/Event.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { @@ -39,23 +39,23 @@ class EventListener; struct CollectedListener; struct EventListenerEntry { - EventListenerEntry(const EventId id, EventListener* listener, const bool in_capture_phase) : id(id), in_capture_phase(in_capture_phase), listener(listener) {} + EventListenerEntry(const EventId id, EventListener* listener, const bool in_capture_phase) : + id(id), in_capture_phase(in_capture_phase), listener(listener) + {} EventId id; bool in_capture_phase; EventListener* listener; }; - /** - The Event Dispatcher manages a list of event listeners and triggers the events via EventHandlers - whenever requested. + The Event Dispatcher manages a list of event listeners and triggers the events via EventHandlers + whenever requested. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class EventDispatcher -{ +class EventDispatcher { public: /// Constructor /// @param element Element this dispatcher acts on @@ -88,7 +88,8 @@ class EventDispatcher /// @param[in] bubbles True if the event should execute the bubble phase /// @param[in] default_action_phase The phases to execute default actions in /// @return True if the event was not consumed (ie, was prevented from propagating by an element), false if it was. - static bool DispatchEvent(Element* target_element, EventId id, const String& type, const Dictionary& parameters, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase); + static bool DispatchEvent(Element* target_element, EventId id, const String& type, const Dictionary& parameters, bool interruptible, bool bubbles, + DefaultActionPhase default_action_phase); /// Returns event types with number of listeners for debugging. /// @return Summary of attached listeners. @@ -99,14 +100,12 @@ class EventDispatcher // Listeners are sorted first by (id, phase) and then by the order in which the listener was inserted. // All listeners added are unique. - typedef Vector< EventListenerEntry > Listeners; + typedef Vector Listeners; Listeners listeners; // Collect all the listeners from this dispatcher that are allowed to execute given the input arguments. void CollectListeners(int dom_distance_from_target, EventId event_id, EventPhase phases_to_execute, Vector& collect_listeners); }; - - } // namespace Rml #endif diff --git a/Source/Core/EventInstancer.cpp b/Source/Core/EventInstancer.cpp index 2a97fedbb..7bece40bd 100644 --- a/Source/Core/EventInstancer.cpp +++ b/Source/Core/EventInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,8 +30,6 @@ namespace Rml { -EventInstancer::~EventInstancer() -{ -} +EventInstancer::~EventInstancer() {} } // namespace Rml diff --git a/Source/Core/EventInstancerDefault.cpp b/Source/Core/EventInstancerDefault.cpp index dd3a345fd..1fd998214 100644 --- a/Source/Core/EventInstancerDefault.cpp +++ b/Source/Core/EventInstancerDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,20 +31,15 @@ namespace Rml { -EventInstancerDefault::EventInstancerDefault() -{ -} +EventInstancerDefault::EventInstancerDefault() {} -EventInstancerDefault::~EventInstancerDefault() -{ -} +EventInstancerDefault::~EventInstancerDefault() {} EventPtr EventInstancerDefault::InstanceEvent(Element* target, EventId id, const String& type, const Dictionary& parameters, bool interruptible) { return EventPtr(new Event(target, id, type, parameters, interruptible)); } -// Releases an event instanced by this instancer. void EventInstancerDefault::ReleaseEvent(Event* event) { delete event; diff --git a/Source/Core/EventInstancerDefault.h b/Source/Core/EventInstancerDefault.h index 4d6fd3284..547805d4f 100644 --- a/Source/Core/EventInstancerDefault.h +++ b/Source/Core/EventInstancerDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - Default instancer for instancing events. + Default instancer for instancing events. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class EventInstancerDefault : public EventInstancer -{ +class EventInstancerDefault : public EventInstancer { public: EventInstancerDefault(); virtual ~EventInstancerDefault(); diff --git a/Source/Core/EventListenerInstancer.cpp b/Source/Core/EventListenerInstancer.cpp index 0875f3f9d..5dff3a266 100644 --- a/Source/Core/EventListenerInstancer.cpp +++ b/Source/Core/EventListenerInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,8 +30,6 @@ namespace Rml { -EventListenerInstancer::~EventListenerInstancer() -{ -} +EventListenerInstancer::~EventListenerInstancer() {} } // namespace Rml diff --git a/Source/Core/EventSpecification.cpp b/Source/Core/EventSpecification.cpp index 8fb72f9e2..da6b97f77 100644 --- a/Source/Core/EventSpecification.cpp +++ b/Source/Core/EventSpecification.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,154 +29,153 @@ #include "EventSpecification.h" #include "../../Include/RmlUi/Core/ID.h" - namespace Rml { // An EventId is an index into the specifications vector. -static Vector specifications = { { EventId::Invalid, "invalid", false, false, DefaultActionPhase::None } }; +static Vector specifications = {{EventId::Invalid, "invalid", false, false, DefaultActionPhase::None}}; // Reverse lookup map from event type to id. static UnorderedMap type_lookup; - namespace EventSpecificationInterface { -void Initialize() -{ - // Must be specified in the same order as in EventId - specifications = { - // id type interruptible bubbles default_action - {EventId::Invalid , "invalid" , false , false , DefaultActionPhase::None}, - {EventId::Mousedown , "mousedown" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Mousescroll , "mousescroll" , true , true , DefaultActionPhase::None}, - {EventId::Mouseover , "mouseover" , true , true , DefaultActionPhase::Target}, - {EventId::Mouseout , "mouseout" , true , true , DefaultActionPhase::Target}, - {EventId::Focus , "focus" , false , false , DefaultActionPhase::Target}, - {EventId::Blur , "blur" , false , false , DefaultActionPhase::Target}, - {EventId::Keydown , "keydown" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Keyup , "keyup" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Textinput , "textinput" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Mouseup , "mouseup" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Click , "click" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Dblclick , "dblclick" , true , true , DefaultActionPhase::TargetAndBubble}, - {EventId::Load , "load" , false , false , DefaultActionPhase::None}, - {EventId::Unload , "unload" , false , false , DefaultActionPhase::None}, - {EventId::Show , "show" , false , false , DefaultActionPhase::None}, - {EventId::Hide , "hide" , false , false , DefaultActionPhase::None}, - {EventId::Mousemove , "mousemove" , true , true , DefaultActionPhase::None}, - {EventId::Dragmove , "dragmove" , true , true , DefaultActionPhase::None}, - {EventId::Drag , "drag" , false , true , DefaultActionPhase::Target}, - {EventId::Dragstart , "dragstart" , false , true , DefaultActionPhase::Target}, - {EventId::Dragover , "dragover" , true , true , DefaultActionPhase::None}, - {EventId::Dragdrop , "dragdrop" , true , true , DefaultActionPhase::None}, - {EventId::Dragout , "dragout" , true , true , DefaultActionPhase::None}, - {EventId::Dragend , "dragend" , true , true , DefaultActionPhase::None}, - {EventId::Handledrag , "handledrag" , false , true , DefaultActionPhase::None}, - {EventId::Resize , "resize" , false , false , DefaultActionPhase::None}, - {EventId::Scroll , "scroll" , false , true , DefaultActionPhase::None}, - {EventId::Animationend , "animationend" , false , true , DefaultActionPhase::None}, - {EventId::Transitionend , "transitionend" , false , true , DefaultActionPhase::None}, + void Initialize() + { + // Must be specified in the same order as in EventId + specifications = { + // id type interruptible bubbles default_action + // clang-format off + {EventId::Invalid , "invalid" , false , false , DefaultActionPhase::None}, + {EventId::Mousedown , "mousedown" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Mousescroll , "mousescroll" , true , true , DefaultActionPhase::None}, + {EventId::Mouseover , "mouseover" , true , true , DefaultActionPhase::Target}, + {EventId::Mouseout , "mouseout" , true , true , DefaultActionPhase::Target}, + {EventId::Focus , "focus" , false , false , DefaultActionPhase::Target}, + {EventId::Blur , "blur" , false , false , DefaultActionPhase::Target}, + {EventId::Keydown , "keydown" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Keyup , "keyup" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Textinput , "textinput" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Mouseup , "mouseup" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Click , "click" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Dblclick , "dblclick" , true , true , DefaultActionPhase::TargetAndBubble}, + {EventId::Load , "load" , false , false , DefaultActionPhase::None}, + {EventId::Unload , "unload" , false , false , DefaultActionPhase::None}, + {EventId::Show , "show" , false , false , DefaultActionPhase::None}, + {EventId::Hide , "hide" , false , false , DefaultActionPhase::None}, + {EventId::Mousemove , "mousemove" , true , true , DefaultActionPhase::None}, + {EventId::Dragmove , "dragmove" , true , true , DefaultActionPhase::None}, + {EventId::Drag , "drag" , false , true , DefaultActionPhase::Target}, + {EventId::Dragstart , "dragstart" , false , true , DefaultActionPhase::Target}, + {EventId::Dragover , "dragover" , true , true , DefaultActionPhase::None}, + {EventId::Dragdrop , "dragdrop" , true , true , DefaultActionPhase::None}, + {EventId::Dragout , "dragout" , true , true , DefaultActionPhase::None}, + {EventId::Dragend , "dragend" , true , true , DefaultActionPhase::None}, + {EventId::Handledrag , "handledrag" , false , true , DefaultActionPhase::None}, + {EventId::Resize , "resize" , false , false , DefaultActionPhase::None}, + {EventId::Scroll , "scroll" , false , true , DefaultActionPhase::None}, + {EventId::Animationend , "animationend" , false , true , DefaultActionPhase::None}, + {EventId::Transitionend , "transitionend" , false , true , DefaultActionPhase::None}, - {EventId::Change , "change" , false , true , DefaultActionPhase::None}, - {EventId::Submit , "submit" , true , true , DefaultActionPhase::None}, - {EventId::Tabchange , "tabchange" , false , true , DefaultActionPhase::None}, - {EventId::Columnadd , "columnadd" , false , true , DefaultActionPhase::None}, - {EventId::Rowadd , "rowadd" , false , true , DefaultActionPhase::None}, - {EventId::Rowchange , "rowchange" , false , true , DefaultActionPhase::None}, - {EventId::Rowremove , "rowremove" , false , true , DefaultActionPhase::None}, - {EventId::Rowupdate , "rowupdate" , false , true , DefaultActionPhase::None}, - }; - - type_lookup.clear(); - type_lookup.reserve(specifications.size()); - for (auto& specification : specifications) - type_lookup.emplace(specification.type, specification.id); + {EventId::Change , "change" , false , true , DefaultActionPhase::None}, + {EventId::Submit , "submit" , true , true , DefaultActionPhase::None}, + {EventId::Tabchange , "tabchange" , false , true , DefaultActionPhase::None}, + {EventId::Columnadd , "columnadd" , false , true , DefaultActionPhase::None}, + {EventId::Rowadd , "rowadd" , false , true , DefaultActionPhase::None}, + {EventId::Rowchange , "rowchange" , false , true , DefaultActionPhase::None}, + {EventId::Rowremove , "rowremove" , false , true , DefaultActionPhase::None}, + {EventId::Rowupdate , "rowupdate" , false , true , DefaultActionPhase::None}, + // clang-format on + }; + + type_lookup.clear(); + type_lookup.reserve(specifications.size()); + for (auto& specification : specifications) + type_lookup.emplace(specification.type, specification.id); #ifdef RMLUI_DEBUG - // Verify that all event ids are specified - RMLUI_ASSERT((int)specifications.size() == (int)EventId::NumDefinedIds); + // Verify that all event ids are specified + RMLUI_ASSERT((int)specifications.size() == (int)EventId::NumDefinedIds); + + for (int i = 0; i < (int)specifications.size(); i++) + { + // Verify correct order + RMLUI_ASSERT(i == (int)specifications[i].id); + } +#endif + } - for (int i = 0; i < (int)specifications.size(); i++) + static EventSpecification& GetMutable(EventId id) { - // Verify correct order - RMLUI_ASSERT(i == (int)specifications[i].id); + size_t i = static_cast(id); + if (i < specifications.size()) + return specifications[i]; + return specifications[0]; } -#endif -} - -static EventSpecification& GetMutable(EventId id) -{ - size_t i = static_cast(id); - if (i < specifications.size()) - return specifications[i]; - return specifications[0]; -} - -// Get event specification for the given type. -// If not found: Inserts a new entry with given values. -static EventSpecification& GetOrInsert(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase) -{ - auto it = type_lookup.find(event_type); - - if (it != type_lookup.end()) - return GetMutable(it->second); - - const size_t new_id_num = specifications.size(); - if (new_id_num >= size_t(EventId::MaxNumIds)) + + // Get event specification for the given type. + // If not found: Inserts a new entry with given values. + static EventSpecification& GetOrInsert(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase) { - Log::Message(Log::LT_ERROR, "Error while registering event type '%s': Maximum number of allowed events exceeded.", event_type.c_str()); - RMLUI_ERROR; - return specifications.front(); + auto it = type_lookup.find(event_type); + + if (it != type_lookup.end()) + return GetMutable(it->second); + + const size_t new_id_num = specifications.size(); + if (new_id_num >= size_t(EventId::MaxNumIds)) + { + Log::Message(Log::LT_ERROR, "Error while registering event type '%s': Maximum number of allowed events exceeded.", event_type.c_str()); + RMLUI_ERROR; + return specifications.front(); + } + + // No specification found for this name, insert a new entry with default values + EventId new_id = static_cast(new_id_num); + specifications.push_back(EventSpecification{new_id, event_type, interruptible, bubbles, default_action_phase}); + type_lookup.emplace(event_type, new_id); + return specifications.back(); } - // No specification found for this name, insert a new entry with default values - EventId new_id = static_cast(new_id_num); - specifications.push_back(EventSpecification{ new_id, event_type, interruptible, bubbles, default_action_phase }); - type_lookup.emplace(event_type, new_id); - return specifications.back(); -} - -const EventSpecification& Get(EventId id) -{ - return GetMutable(id); -} - -const EventSpecification& GetOrInsert(const String& event_type) -{ - // Default values for new event types defined as follows: - constexpr bool interruptible = true; - constexpr bool bubbles = true; - constexpr DefaultActionPhase default_action_phase = DefaultActionPhase::None; - - return GetOrInsert(event_type, interruptible, bubbles, default_action_phase); -} - -EventId GetIdOrInsert(const String& event_type) -{ - auto it = type_lookup.find(event_type); - if (it != type_lookup.end()) - return it->second; - - return GetOrInsert(event_type).id; -} - -EventId InsertOrReplaceCustom(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase) -{ - const size_t size_before = specifications.size(); - EventSpecification& specification = GetOrInsert(event_type, interruptible, bubbles, default_action_phase); - bool got_existing_entry = (size_before == specifications.size()); - - // If we found an existing entry of same type, replace it, but only if it is a custom event id. - if (got_existing_entry && (int)specification.id >= (int)EventId::FirstCustomId) + const EventSpecification& Get(EventId id) { - specification.interruptible = interruptible; - specification.bubbles = bubbles; - specification.default_action_phase = default_action_phase; + return GetMutable(id); } - return specification.id; -} + const EventSpecification& GetOrInsert(const String& event_type) + { + // Default values for new event types defined as follows: + constexpr bool interruptible = true; + constexpr bool bubbles = true; + constexpr DefaultActionPhase default_action_phase = DefaultActionPhase::None; + return GetOrInsert(event_type, interruptible, bubbles, default_action_phase); + } + + EventId GetIdOrInsert(const String& event_type) + { + auto it = type_lookup.find(event_type); + if (it != type_lookup.end()) + return it->second; + + return GetOrInsert(event_type).id; + } + + EventId InsertOrReplaceCustom(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase) + { + const size_t size_before = specifications.size(); + EventSpecification& specification = GetOrInsert(event_type, interruptible, bubbles, default_action_phase); + bool got_existing_entry = (size_before == specifications.size()); + + // If we found an existing entry of same type, replace it, but only if it is a custom event id. + if (got_existing_entry && (int)specification.id >= (int)EventId::FirstCustomId) + { + specification.interruptible = interruptible; + specification.bubbles = bubbles; + specification.default_action_phase = default_action_phase; + } + + return specification.id; + } -} +} // namespace EventSpecificationInterface } // namespace Rml diff --git a/Source/Core/EventSpecification.h b/Source/Core/EventSpecification.h index 061d23409..a45b4477a 100644 --- a/Source/Core/EventSpecification.h +++ b/Source/Core/EventSpecification.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_EVENTSPECIFICATION_H #define RMLUI_CORE_EVENTSPECIFICATION_H -#include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Event.h" +#include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/ID.h" namespace Rml { @@ -62,7 +62,7 @@ namespace EventSpecificationInterface { // Insert a new specification for the given event_type. // If the type already exists, it will be replaced if and only if the event type is not an internal type. EventId InsertOrReplaceCustom(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase); -} +} // namespace EventSpecificationInterface } // namespace Rml #endif diff --git a/Source/Core/Factory.cpp b/Source/Core/Factory.cpp index 9b44467f5..d12227249 100644 --- a/Source/Core/Factory.cpp +++ b/Source/Core/Factory.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,30 +34,33 @@ #include "../../Include/RmlUi/Core/ElementInstancer.h" #include "../../Include/RmlUi/Core/ElementText.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" -#include "../../Include/RmlUi/Core/EventListenerInstancer.h" -#include "../../Include/RmlUi/Core/StreamMemory.h" -#include "../../Include/RmlUi/Core/StyleSheet.h" -#include "../../Include/RmlUi/Core/StyleSheetContainer.h" -#include "../../Include/RmlUi/Core/SystemInterface.h" - #include "../../Include/RmlUi/Core/Elements/ElementForm.h" #include "../../Include/RmlUi/Core/Elements/ElementFormControlInput.h" #include "../../Include/RmlUi/Core/Elements/ElementFormControlSelect.h" -#include "../../Include/RmlUi/Core/Elements/ElementFormControlSelect.h" #include "../../Include/RmlUi/Core/Elements/ElementFormControlTextArea.h" -#include "../../Include/RmlUi/Core/Elements/ElementTabSet.h" #include "../../Include/RmlUi/Core/Elements/ElementProgress.h" - +#include "../../Include/RmlUi/Core/Elements/ElementTabSet.h" +#include "../../Include/RmlUi/Core/EventListenerInstancer.h" +#include "../../Include/RmlUi/Core/StreamMemory.h" +#include "../../Include/RmlUi/Core/StyleSheet.h" +#include "../../Include/RmlUi/Core/StyleSheetContainer.h" +#include "../../Include/RmlUi/Core/SystemInterface.h" #include "ContextInstancerDefault.h" #include "DataControllerDefault.h" #include "DataViewDefault.h" +#include "DecoratorGradient.h" +#include "DecoratorNinePatch.h" #include "DecoratorTiledBoxInstancer.h" #include "DecoratorTiledHorizontalInstancer.h" #include "DecoratorTiledImageInstancer.h" #include "DecoratorTiledVerticalInstancer.h" -#include "DecoratorNinePatch.h" -#include "DecoratorGradient.h" #include "ElementHandle.h" +#include "Elements/ElementImage.h" +#include "Elements/ElementLabel.h" +#include "Elements/ElementTextSelection.h" +#include "Elements/XMLNodeHandlerSelect.h" +#include "Elements/XMLNodeHandlerTabSet.h" +#include "Elements/XMLNodeHandlerTextArea.h" #include "EventInstancerDefault.h" #include "FontEffectBlur.h" #include "FontEffectGlow.h" @@ -72,40 +75,32 @@ #include "XMLNodeHandlerHead.h" #include "XMLNodeHandlerTemplate.h" #include "XMLParseTools.h" - -#include "Elements/ElementImage.h" -#include "Elements/ElementLabel.h" -#include "Elements/ElementTextSelection.h" -#include "Elements/XMLNodeHandlerSelect.h" -#include "Elements/XMLNodeHandlerTabSet.h" -#include "Elements/XMLNodeHandlerTextArea.h" - #include namespace Rml { // Element instancers. -using ElementInstancerMap = UnorderedMap< String, ElementInstancer* >; +using ElementInstancerMap = UnorderedMap; static ElementInstancerMap element_instancers; // Decorator instancers. -using DecoratorInstancerMap = UnorderedMap< String, DecoratorInstancer* >; +using DecoratorInstancerMap = UnorderedMap; static DecoratorInstancerMap decorator_instancers; // Font effect instancers. -using FontEffectInstancerMap = UnorderedMap< String, FontEffectInstancer* >; +using FontEffectInstancerMap = UnorderedMap; static FontEffectInstancerMap font_effect_instancers; // Data view instancers. -using DataViewInstancerMap = UnorderedMap< String, DataViewInstancer* >; +using DataViewInstancerMap = UnorderedMap; static DataViewInstancerMap data_view_instancers; // Data controller instancers. -using DataControllerInstancerMap = UnorderedMap< String, DataControllerInstancer* >; +using DataControllerInstancerMap = UnorderedMap; static DataControllerInstancerMap data_controller_instancers; // Structural data view instancers. -using StructuralDataViewInstancerMap = SmallUnorderedMap< String, DataViewInstancer* >; +using StructuralDataViewInstancerMap = SmallUnorderedMap; static StructuralDataViewInstancerMap structural_data_view_instancers; // Structural data view names. @@ -122,7 +117,6 @@ static EventListenerInstancer* event_listener_instancer = nullptr; // Default instancers are constructed and destroyed on Initialise and Shutdown, respectively. struct DefaultInstancers { - UniquePtr context_default; UniquePtr event_default; @@ -181,15 +175,9 @@ struct DefaultInstancers { static UniquePtr default_instancers; +Factory::Factory() {} -Factory::Factory() -{ -} - -Factory::~Factory() -{ -} - +Factory::~Factory() {} bool Factory::Initialise() { @@ -248,6 +236,7 @@ bool Factory::Initialise() RegisterFontEffectInstancer("shadow", &default_instancers->font_effect_shadow); // Data binding views + // clang-format off RegisterDataViewInstancer(&default_instancers->data_view_attribute, "attr", false); RegisterDataViewInstancer(&default_instancers->data_view_attribute_if, "attrif", false); RegisterDataViewInstancer(&default_instancers->data_view_class, "class", false); @@ -260,6 +249,7 @@ bool Factory::Initialise() RegisterDataViewInstancer(&default_instancers->data_view_checked, "checked", false); RegisterDataViewInstancer(&default_instancers->data_view_alias, "alias", false); RegisterDataViewInstancer(&default_instancers->structural_data_view_for, "for", true ); + // clang-format on // Data binding controllers RegisterDataControllerInstancer(&default_instancers->data_controller_value, "checked"); @@ -304,13 +294,11 @@ void Factory::Shutdown() default_instancers.reset(); } -// Registers the instancer to use when instancing contexts. void Factory::RegisterContextInstancer(ContextInstancer* instancer) { context_instancer = instancer; } -// Instances a new context. ContextPtr Factory::InstanceContext(const String& name) { ContextPtr new_context = context_instancer->InstanceContext(name); @@ -324,7 +312,6 @@ void Factory::RegisterElementInstancer(const String& name, ElementInstancer* ins element_instancers[StringUtilities::ToLower(name)] = instancer; } -// Looks up the instancer for the given element ElementInstancer* Factory::GetElementInstancer(const String& tag) { ElementInstancerMap::iterator instancer_iterator = element_instancers.find(tag); @@ -338,7 +325,6 @@ ElementInstancer* Factory::GetElementInstancer(const String& tag) return instancer_iterator->second; } -// Instances a single element. ElementPtr Factory::InstanceElement(Element* parent, const String& instancer_name, const String& tag, const XMLAttributes& attributes) { if (ElementInstancer* instancer = GetElementInstancer(instancer_name)) @@ -356,7 +342,6 @@ ElementPtr Factory::InstanceElement(Element* parent, const String& instancer_nam return nullptr; } -// Instances a single text element containing a string. bool Factory::InstanceElementText(Element* parent, const String& in_text) { RMLUI_ASSERT(parent); @@ -369,7 +354,7 @@ bool Factory::InstanceElementText(Element* parent, const String& in_text) const bool only_white_space = std::all_of(text.begin(), text.end(), &StringUtilities::IsWhitespace); if (only_white_space) return true; - + // See if we need to parse it as RML, and whether the text contains data expressions (curly brackets). bool parse_as_rml = false; bool has_data_expression = false; @@ -413,7 +398,7 @@ bool Factory::InstanceElementText(Element* parent, const String& in_text) else { RMLUI_ZoneScopedNC("InstanceText", 0x8FBC8F); - + // Attempt to instance the element. XMLAttributes attributes; @@ -429,16 +414,17 @@ bool Factory::InstanceElementText(Element* parent, const String& in_text) } // Assign the element its text value. - ElementText* text_element = rmlui_dynamic_cast< ElementText* >(element.get()); + ElementText* text_element = rmlui_dynamic_cast(element.get()); if (!text_element) { - Log::Message(Log::LT_ERROR, "Failed to instance text element '%s'. Found type '%s', was expecting a derivative of ElementText.", text.c_str(), rmlui_type_name(*element)); + Log::Message(Log::LT_ERROR, "Failed to instance text element '%s'. Found type '%s', was expecting a derivative of ElementText.", + text.c_str(), rmlui_type_name(*element)); return false; } // Unescape any escaped entities or unicode symbols text = StringUtilities::DecodeRml(text); - + text_element->SetText(text); // Add to active node. @@ -448,7 +434,6 @@ bool Factory::InstanceElementText(Element* parent, const String& in_text) return true; } -// Instances a element tree based on the stream bool Factory::InstanceElementStream(Element* parent, Stream* stream) { XMLParser parser(parent); @@ -456,7 +441,6 @@ bool Factory::InstanceElementStream(Element* parent, Stream* stream) return true; } -// Instances a element tree based on the stream ElementPtr Factory::InstanceDocumentStream(Context* context, Stream* stream, const String& document_base_tag) { RMLUI_ZoneScoped; @@ -468,10 +452,11 @@ ElementPtr Factory::InstanceDocumentStream(Context* context, Stream* stream, con return nullptr; } - ElementDocument* document = rmlui_dynamic_cast< ElementDocument* >(element.get()); + ElementDocument* document = rmlui_dynamic_cast(element.get()); if (!document) { - Log::Message(Log::LT_ERROR, "Failed to instance document element. Found type '%s', was expecting derivative of ElementDocument.", rmlui_type_name(*element)); + Log::Message(Log::LT_ERROR, "Failed to instance document element. Found type '%s', was expecting derivative of ElementDocument.", + rmlui_type_name(*element)); return nullptr; } @@ -483,25 +468,21 @@ ElementPtr Factory::InstanceDocumentStream(Context* context, Stream* stream, con return element; } - -// Registers an instancer that will be used to instance decorators. void Factory::RegisterDecoratorInstancer(const String& name, DecoratorInstancer* instancer) { RMLUI_ASSERT(instancer); decorator_instancers[StringUtilities::ToLower(name)] = instancer; } -// Retrieves a decorator instancer registered with the factory. DecoratorInstancer* Factory::GetDecoratorInstancer(const String& name) { auto iterator = decorator_instancers.find(name); if (iterator == decorator_instancers.end()) return nullptr; - + return iterator->second; } -// Registers an instancer that will be used to instance font effects. void Factory::RegisterFontEffectInstancer(const String& name, FontEffectInstancer* instancer) { RMLUI_ASSERT(instancer); @@ -517,15 +498,12 @@ FontEffectInstancer* Factory::GetFontEffectInstancer(const String& name) return iterator->second; } - -// Creates a style sheet containing the passed in styles. SharedPtr Factory::InstanceStyleSheetString(const String& string) { - auto memory_stream = MakeUnique((const byte*) string.c_str(), string.size()); + auto memory_stream = MakeUnique((const byte*)string.c_str(), string.size()); return InstanceStyleSheetStream(memory_stream.get()); } -// Creates a style sheet from a file. SharedPtr Factory::InstanceStyleSheetFile(const String& file_name) { auto file_stream = MakeUnique(); @@ -533,7 +511,6 @@ SharedPtr Factory::InstanceStyleSheetFile(const String& fil return InstanceStyleSheetStream(file_stream.get()); } -// Creates a style sheet from an Stream. SharedPtr Factory::InstanceStyleSheetStream(Stream* stream) { SharedPtr style_sheet_container = MakeShared(); @@ -544,25 +521,21 @@ SharedPtr Factory::InstanceStyleSheetStream(Stream* stream) return nullptr; } -// Clears the style sheet cache. This will force style sheets to be reloaded. void Factory::ClearStyleSheetCache() { StyleSheetFactory::ClearStyleSheetCache(); } -/// Clears the template cache. This will force templates to be reloaded. void Factory::ClearTemplateCache() { TemplateCache::Clear(); } -// Registers an instancer for all RmlEvents void Factory::RegisterEventInstancer(EventInstancer* instancer) { event_instancer = instancer; } -// Instance an event object. EventPtr Factory::InstanceEvent(Element* target, EventId id, const String& type, const Dictionary& parameters, bool interruptible) { EventPtr event = event_instancer->InstanceEvent(target, id, type, parameters, interruptible); @@ -571,13 +544,11 @@ EventPtr Factory::InstanceEvent(Element* target, EventId id, const String& type, return event; } -// Register an instancer for all event listeners void Factory::RegisterEventListenerInstancer(EventListenerInstancer* instancer) { event_listener_instancer = instancer; } -// Instance an event listener with the given string EventListener* Factory::InstanceEventListener(const String& value, Element* element) { // If we have an event listener instancer, use it @@ -600,7 +571,7 @@ void Factory::RegisterDataViewInstancer(DataViewInstancer* instancer, const Stri { inserted = data_view_instancers.emplace(name, instancer).second; } - + if (!inserted) Log::Message(Log::LT_WARNING, "Could not register data view instancer '%s'. The given name is already registered.", name.c_str()); } diff --git a/Source/Core/FileInterface.cpp b/Source/Core/FileInterface.cpp index 67d228af0..702633a5f 100644 --- a/Source/Core/FileInterface.cpp +++ b/Source/Core/FileInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,22 +31,17 @@ namespace Rml { -FileInterface::FileInterface() -{ -} +FileInterface::FileInterface() {} -FileInterface::~FileInterface() -{ -} +FileInterface::~FileInterface() {} -// Returns the length of the file. size_t FileInterface::Length(FileHandle file) { - size_t current_position = Tell(file); - Seek( file, 0, SEEK_END); - size_t length = Tell( file); - Seek( file, (long)current_position, SEEK_SET); - return length; + size_t current_position = Tell(file); + Seek(file, 0, SEEK_END); + size_t length = Tell(file); + Seek(file, (long)current_position, SEEK_SET); + return length; } bool FileInterface::LoadFile(const String& path, String& out_data) @@ -60,7 +55,7 @@ bool FileInterface::LoadFile(const String& path, String& out_data) out_data = String(length, 0); const size_t read_length = Read(&out_data[0], length, handle); - + if (length != read_length) { Log::Message(Log::LT_WARNING, "Could only read %zu of %zu bytes from file %s", read_length, length, path.c_str()); diff --git a/Source/Core/FileInterfaceDefault.cpp b/Source/Core/FileInterfaceDefault.cpp index c29f2d60e..711f84454 100644 --- a/Source/Core/FileInterfaceDefault.cpp +++ b/Source/Core/FileInterfaceDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,38 +32,31 @@ namespace Rml { -FileInterfaceDefault::~FileInterfaceDefault() -{ -} +FileInterfaceDefault::~FileInterfaceDefault() {} -// Opens a file. FileHandle FileInterfaceDefault::Open(const String& path) { - return (FileHandle)fopen(path.c_str(), "rb"); + return (FileHandle)fopen(path.c_str(), "rb"); } -// Closes a previously opened file. void FileInterfaceDefault::Close(FileHandle file) { - fclose((FILE*) file); + fclose((FILE*)file); } -// Reads data from a previously opened file. size_t FileInterfaceDefault::Read(void* buffer, size_t size, FileHandle file) { - return fread(buffer, 1, size, (FILE*) file); + return fread(buffer, 1, size, (FILE*)file); } -// Seeks to a point in a previously opened file. bool FileInterfaceDefault::Seek(FileHandle file, long offset, int origin) { - return fseek((FILE*) file, offset, origin) == 0; + return fseek((FILE*)file, offset, origin) == 0; } -// Returns the current position of the file pointer. size_t FileInterfaceDefault::Tell(FileHandle file) { - return ftell((FILE*) file); + return ftell((FILE*)file); } } // namespace Rml diff --git a/Source/Core/FileInterfaceDefault.h b/Source/Core/FileInterfaceDefault.h index 4e38ab2f3..eda49d964 100644 --- a/Source/Core/FileInterfaceDefault.h +++ b/Source/Core/FileInterfaceDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,18 +36,17 @@ namespace Rml { /** - Implementation of the RmlUi file interface using the Standard C file functions. + Implementation of the RmlUi file interface using the Standard C file functions. - @author Peter Curry + @author Peter Curry */ -class FileInterfaceDefault : public FileInterface -{ +class FileInterfaceDefault : public FileInterface { public: virtual ~FileInterfaceDefault(); - /// Opens a file. - /// @param path The path of the file to open. + /// Opens a file. + /// @param path The path of the file to open. /// @return A valid file handle, or nullptr on failure FileHandle Open(const String& path) override; /// Closes a previously opened file. @@ -63,7 +62,8 @@ class FileInterfaceDefault : public FileInterface /// Seeks to a point in a previously opened file. /// @param file The handle of the file to seek. /// @param offset The number of bytes to seek. - /// @param origin One of either SEEK_SET (seek from the beginning of the file), SEEK_END (seek from the end of the file) or SEEK_CUR (seek from the current file position). + /// @param origin One of either SEEK_SET (seek from the beginning of the file), SEEK_END (seek from the end of the file) or SEEK_CUR (seek from + /// the current file position). /// @return True if the operation completed successfully, false otherwise. bool Seek(FileHandle file, long offset, int origin) override; /// Returns the current position of the file pointer. diff --git a/Source/Core/FontEffect.cpp b/Source/Core/FontEffect.cpp index 7620479e7..084ae8f64 100644 --- a/Source/Core/FontEffect.cpp +++ b/Source/Core/FontEffect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,22 +40,14 @@ bool FontEffect::HasUniqueTexture() const return false; } -bool FontEffect::GetGlyphMetrics(Vector2i& RMLUI_UNUSED_PARAMETER(origin), Vector2i& RMLUI_UNUSED_PARAMETER(dimensions), const FontGlyph& RMLUI_UNUSED_PARAMETER(glyph)) const +bool FontEffect::GetGlyphMetrics(Vector2i& /*origin*/, Vector2i& /*dimensions*/, const FontGlyph& /*glyph*/) const { - RMLUI_UNUSED(origin); - RMLUI_UNUSED(dimensions); - RMLUI_UNUSED(glyph); - return false; } -void FontEffect::GenerateGlyphTexture(byte* RMLUI_UNUSED_PARAMETER(destination_data), Vector2i RMLUI_UNUSED_PARAMETER(destination_dimensions), int RMLUI_UNUSED_PARAMETER(destination_stride), const FontGlyph& RMLUI_UNUSED_PARAMETER(glyph)) const -{ - RMLUI_UNUSED(destination_data); - RMLUI_UNUSED(destination_dimensions); - RMLUI_UNUSED(destination_stride); - RMLUI_UNUSED(glyph); -} +void FontEffect::GenerateGlyphTexture(byte* /*destination_data*/, Vector2i /*destination_dimensions*/, int /*destination_stride*/, + const FontGlyph& /*glyph*/) const +{} void FontEffect::SetColour(const Colourb _colour) { diff --git a/Source/Core/FontEffectBlur.cpp b/Source/Core/FontEffectBlur.cpp index 89433e288..e8b9cfa0b 100644 --- a/Source/Core/FontEffectBlur.cpp +++ b/Source/Core/FontEffectBlur.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +27,8 @@ */ #include "FontEffectBlur.h" -#include "Memory.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" +#include "Memory.h" namespace Rml { @@ -38,9 +38,7 @@ FontEffectBlur::FontEffectBlur() SetLayer(Layer::Back); } -FontEffectBlur::~FontEffectBlur() -{ -} +FontEffectBlur::~FontEffectBlur() {} bool FontEffectBlur::HasUniqueTexture() const { @@ -83,10 +81,8 @@ bool FontEffectBlur::Initialise(int _width) return true; } -bool FontEffectBlur::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& RMLUI_UNUSED_PARAMETER(glyph)) const +bool FontEffectBlur::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& /*glyph*/) const { - RMLUI_UNUSED(glyph); - if (dimensions.x * dimensions.y > 0) { origin.x -= width; @@ -101,7 +97,8 @@ bool FontEffectBlur::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, con return false; } -void FontEffectBlur::GenerateGlyphTexture(byte* destination_data, const Vector2i destination_dimensions, int destination_stride, const FontGlyph& glyph) const +void FontEffectBlur::GenerateGlyphTexture(byte* destination_data, const Vector2i destination_dimensions, int destination_stride, + const FontGlyph& glyph) const { const Vector2i buf_dimensions = destination_dimensions; const int buf_stride = buf_dimensions.x; @@ -115,10 +112,6 @@ void FontEffectBlur::GenerateGlyphTexture(byte* destination_data, const Vector2i ColorFormat::A8); } - - - - FontEffectBlurInstancer::FontEffectBlurInstancer() : id_width(PropertyId::Invalid), id_color(PropertyId::Invalid) { id_width = RegisterProperty("width", "1px", true).AddParser("length").GetId(); @@ -126,16 +119,12 @@ FontEffectBlurInstancer::FontEffectBlurInstancer() : id_width(PropertyId::Invali RegisterShorthand("font-effect", "width, color", ShorthandType::FallThrough); } -FontEffectBlurInstancer::~FontEffectBlurInstancer() -{ -} +FontEffectBlurInstancer::~FontEffectBlurInstancer() {} -SharedPtr FontEffectBlurInstancer::InstanceFontEffect(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties) +SharedPtr FontEffectBlurInstancer::InstanceFontEffect(const String& /*name*/, const PropertyDictionary& properties) { - RMLUI_UNUSED(name); - - float width = properties.GetProperty(id_width)->Get< float >(); - Colourb color = properties.GetProperty(id_color)->Get< Colourb >(); + float width = properties.GetProperty(id_width)->Get(); + Colourb color = properties.GetProperty(id_color)->Get(); auto font_effect = MakeShared(); if (font_effect->Initialise(Math::RealToInteger(width))) diff --git a/Source/Core/FontEffectBlur.h b/Source/Core/FontEffectBlur.h index eee351a06..152ce765c 100644 --- a/Source/Core/FontEffectBlur.h +++ b/Source/Core/FontEffectBlur.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,11 +36,10 @@ namespace Rml { /** - A concrete font effect for rendering Gaussian blurred text. + A concrete font effect for rendering Gaussian blurred text. */ -class FontEffectBlur : public FontEffect -{ +class FontEffectBlur : public FontEffect { public: FontEffectBlur(); virtual ~FontEffectBlur(); @@ -58,14 +57,11 @@ class FontEffectBlur : public FontEffect ConvolutionFilter filter_x, filter_y; }; - - /** - A concrete font effect instancer for the blur effect. + A concrete font effect instancer for the blur effect. */ -class FontEffectBlurInstancer : public FontEffectInstancer -{ +class FontEffectBlurInstancer : public FontEffectInstancer { public: FontEffectBlurInstancer(); virtual ~FontEffectBlurInstancer(); @@ -76,6 +72,5 @@ class FontEffectBlurInstancer : public FontEffectInstancer PropertyId id_width, id_color; }; - } // namespace Rml #endif diff --git a/Source/Core/FontEffectGlow.cpp b/Source/Core/FontEffectGlow.cpp index 38e47902c..0f97704b9 100644 --- a/Source/Core/FontEffectGlow.cpp +++ b/Source/Core/FontEffectGlow.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +27,8 @@ */ #include "FontEffectGlow.h" -#include "Memory.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" +#include "Memory.h" namespace Rml { @@ -40,9 +40,7 @@ FontEffectGlow::FontEffectGlow() SetLayer(Layer::Back); } -FontEffectGlow::~FontEffectGlow() -{ -} +FontEffectGlow::~FontEffectGlow() {} bool FontEffectGlow::HasUniqueTexture() const { @@ -78,7 +76,6 @@ bool FontEffectGlow::Initialise(int _width_outline, int _width_blur, Vector2i _o } } - // Gaussian blur filter const float std_dev = (width_blur == 0 ? 1.f : .4f * float(width_blur)); const float two_variance = 2.f * std_dev * std_dev; @@ -109,10 +106,8 @@ bool FontEffectGlow::Initialise(int _width_outline, int _width_blur, Vector2i _o return true; } -bool FontEffectGlow::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& RMLUI_UNUSED_PARAMETER(glyph)) const +bool FontEffectGlow::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& /*glyph*/) const { - RMLUI_UNUSED(glyph); - if (dimensions.x * dimensions.y > 0) { origin.x += offset.x - combined_width; @@ -127,7 +122,8 @@ bool FontEffectGlow::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, con return false; } -void FontEffectGlow::GenerateGlyphTexture(byte* destination_data, const Vector2i destination_dimensions, int destination_stride, const FontGlyph& glyph) const +void FontEffectGlow::GenerateGlyphTexture(byte* destination_data, const Vector2i destination_dimensions, int destination_stride, + const FontGlyph& glyph) const { const Vector2i buf_dimensions = destination_dimensions; const int buf_stride = buf_dimensions.x; @@ -138,7 +134,7 @@ void FontEffectGlow::GenerateGlyphTexture(byte* destination_data, const Vector2i filter_outline.Run(outline_output.data(), buf_dimensions, buf_stride, ColorFormat::A8, glyph.bitmap_data, glyph.bitmap_dimensions, Vector2i(combined_width), glyph.color_format); - + filter_blur_x.Run(blur_x_output.data(), buf_dimensions, buf_stride, ColorFormat::A8, outline_output.data(), buf_dimensions, Vector2i(0), ColorFormat::A8); @@ -146,9 +142,8 @@ void FontEffectGlow::GenerateGlyphTexture(byte* destination_data, const Vector2i Vector2i(0), ColorFormat::A8); } - - -FontEffectGlowInstancer::FontEffectGlowInstancer() : id_width_outline(PropertyId::Invalid), id_width_blur(PropertyId::Invalid),id_color(PropertyId::Invalid) +FontEffectGlowInstancer::FontEffectGlowInstancer() : + id_width_outline(PropertyId::Invalid), id_width_blur(PropertyId::Invalid), id_color(PropertyId::Invalid) { id_width_outline = RegisterProperty("width-outline", "1px", true).AddParser("length").GetId(); id_width_blur = RegisterProperty("width-blur", "-1px", true).AddParser("length").GetId(); @@ -158,20 +153,16 @@ FontEffectGlowInstancer::FontEffectGlowInstancer() : id_width_outline(PropertyId RegisterShorthand("font-effect", "width-outline, width-blur, offset-x, offset-y, color", ShorthandType::FallThrough); } -FontEffectGlowInstancer::~FontEffectGlowInstancer() -{ -} +FontEffectGlowInstancer::~FontEffectGlowInstancer() {} -SharedPtr FontEffectGlowInstancer::InstanceFontEffect(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties) +SharedPtr FontEffectGlowInstancer::InstanceFontEffect(const String& /*name*/, const PropertyDictionary& properties) { - RMLUI_UNUSED(name); - Vector2i offset; - int width_outline = properties.GetProperty(id_width_outline)->Get< int >(); - int width_blur = properties.GetProperty(id_width_blur)->Get< int >(); - offset.x = properties.GetProperty(id_offset_x)->Get< int >(); - offset.y = properties.GetProperty(id_offset_y)->Get< int >(); - Colourb color = properties.GetProperty(id_color)->Get< Colourb >(); + int width_outline = properties.GetProperty(id_width_outline)->Get(); + int width_blur = properties.GetProperty(id_width_blur)->Get(); + offset.x = properties.GetProperty(id_offset_x)->Get(); + offset.y = properties.GetProperty(id_offset_y)->Get(); + Colourb color = properties.GetProperty(id_color)->Get(); if (width_blur < 0) width_blur = width_outline; diff --git a/Source/Core/FontEffectGlow.h b/Source/Core/FontEffectGlow.h index dea66212e..955901cb1 100644 --- a/Source/Core/FontEffectGlow.h +++ b/Source/Core/FontEffectGlow.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,14 +36,13 @@ namespace Rml { /** - A font effect for rendering glow around text. + A font effect for rendering glow around text. - Glow consists of an outline pass followed by a Gaussian blur pass. + Glow consists of an outline pass followed by a Gaussian blur pass. */ -class FontEffectGlow : public FontEffect -{ +class FontEffectGlow : public FontEffect { public: FontEffectGlow(); virtual ~FontEffectGlow(); @@ -62,14 +61,11 @@ class FontEffectGlow : public FontEffect ConvolutionFilter filter_outline, filter_blur_x, filter_blur_y; }; - - /** - A concrete font effect instancer for the glow effect. + A concrete font effect instancer for the glow effect. */ -class FontEffectGlowInstancer : public FontEffectInstancer -{ +class FontEffectGlowInstancer : public FontEffectInstancer { public: FontEffectGlowInstancer(); virtual ~FontEffectGlowInstancer(); @@ -80,6 +76,5 @@ class FontEffectGlowInstancer : public FontEffectInstancer PropertyId id_width_outline, id_width_blur, id_offset_x, id_offset_y, id_color; }; - } // namespace Rml #endif diff --git a/Source/Core/FontEffectInstancer.cpp b/Source/Core/FontEffectInstancer.cpp index 6cfbfef46..849121311 100644 --- a/Source/Core/FontEffectInstancer.cpp +++ b/Source/Core/FontEffectInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,21 +31,15 @@ namespace Rml { -FontEffectInstancer::FontEffectInstancer() : properties(10, 10) -{ -} +FontEffectInstancer::FontEffectInstancer() : properties(10, 10) {} -FontEffectInstancer::~FontEffectInstancer() -{ -} +FontEffectInstancer::~FontEffectInstancer() {} -// Returns the property specification associated with the instancer. const PropertySpecification& FontEffectInstancer::GetPropertySpecification() const { return properties; } -// Registers a property for the font effect. PropertyDefinition& FontEffectInstancer::RegisterProperty(const String& property_name, const String& default_value, bool affects_generation) { PropertyDefinition& definition = properties.RegisterProperty(property_name, default_value, false, false); @@ -55,7 +49,6 @@ PropertyDefinition& FontEffectInstancer::RegisterProperty(const String& property return definition; } -// Registers a shorthand property definition. ShorthandId FontEffectInstancer::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type) { return properties.RegisterShorthand(shorthand_name, property_names, type); diff --git a/Source/Core/FontEffectOutline.cpp b/Source/Core/FontEffectOutline.cpp index 7eb5d0948..916cb2be7 100644 --- a/Source/Core/FontEffectOutline.cpp +++ b/Source/Core/FontEffectOutline.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,9 +37,7 @@ FontEffectOutline::FontEffectOutline() SetLayer(Layer::Back); } -FontEffectOutline::~FontEffectOutline() -{ -} +FontEffectOutline::~FontEffectOutline() {} bool FontEffectOutline::HasUniqueTexture() const { @@ -74,10 +72,8 @@ bool FontEffectOutline::Initialise(int _width) return true; } -bool FontEffectOutline::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& RMLUI_UNUSED_PARAMETER(glyph)) const +bool FontEffectOutline::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, const FontGlyph& /*glyph*/) const { - RMLUI_UNUSED(glyph); - if (dimensions.x * dimensions.y > 0) { origin.x -= width; @@ -92,14 +88,13 @@ bool FontEffectOutline::GetGlyphMetrics(Vector2i& origin, Vector2i& dimensions, return false; } -void FontEffectOutline::GenerateGlyphTexture(byte* destination_data, const Vector2i destination_dimensions, int destination_stride, const FontGlyph& glyph) const +void FontEffectOutline::GenerateGlyphTexture(byte* destination_data, const Vector2i destination_dimensions, int destination_stride, + const FontGlyph& glyph) const { filter.Run(destination_data, destination_dimensions, destination_stride, ColorFormat::RGBA8, glyph.bitmap_data, glyph.bitmap_dimensions, Vector2i(width), glyph.color_format); } - - FontEffectOutlineInstancer::FontEffectOutlineInstancer() : id_width(PropertyId::Invalid), id_color(PropertyId::Invalid) { id_width = RegisterProperty("width", "1px", true).AddParser("length").GetId(); @@ -107,16 +102,12 @@ FontEffectOutlineInstancer::FontEffectOutlineInstancer() : id_width(PropertyId:: RegisterShorthand("font-effect", "width, color", ShorthandType::FallThrough); } -FontEffectOutlineInstancer::~FontEffectOutlineInstancer() -{ -} +FontEffectOutlineInstancer::~FontEffectOutlineInstancer() {} -SharedPtr FontEffectOutlineInstancer::InstanceFontEffect(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties) +SharedPtr FontEffectOutlineInstancer::InstanceFontEffect(const String& /*name*/, const PropertyDictionary& properties) { - RMLUI_UNUSED(name); - - float width = properties.GetProperty(id_width)->Get< float >(); - Colourb color = properties.GetProperty(id_color)->Get< Colourb >(); + float width = properties.GetProperty(id_width)->Get(); + Colourb color = properties.GetProperty(id_color)->Get(); auto font_effect = MakeShared(); if (font_effect->Initialise(Math::RealToInteger(width))) diff --git a/Source/Core/FontEffectOutline.h b/Source/Core/FontEffectOutline.h index dfd9c122d..36a8aa881 100644 --- a/Source/Core/FontEffectOutline.h +++ b/Source/Core/FontEffectOutline.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,12 @@ namespace Rml { /** - A concrete font effect for rendering outlines around text. + A concrete font effect for rendering outlines around text. - @author Peter Curry + @author Peter Curry */ -class FontEffectOutline : public FontEffect -{ +class FontEffectOutline : public FontEffect { public: FontEffectOutline(); virtual ~FontEffectOutline(); @@ -60,16 +59,13 @@ class FontEffectOutline : public FontEffect ConvolutionFilter filter; }; - - /** - A concrete font effect instancer for the outline effect. + A concrete font effect instancer for the outline effect. - @author Peter Curry + @author Peter Curry */ -class FontEffectOutlineInstancer : public FontEffectInstancer -{ +class FontEffectOutlineInstancer : public FontEffectInstancer { public: FontEffectOutlineInstancer(); virtual ~FontEffectOutlineInstancer(); @@ -80,6 +76,5 @@ class FontEffectOutlineInstancer : public FontEffectInstancer PropertyId id_width, id_color; }; - } // namespace Rml #endif diff --git a/Source/Core/FontEffectShadow.cpp b/Source/Core/FontEffectShadow.cpp index 6b255ab93..5496f6d4c 100644 --- a/Source/Core/FontEffectShadow.cpp +++ b/Source/Core/FontEffectShadow.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,9 +36,7 @@ FontEffectShadow::FontEffectShadow() : offset(0, 0) SetLayer(Layer::Back); } -FontEffectShadow::~FontEffectShadow() -{ -} +FontEffectShadow::~FontEffectShadow() {} bool FontEffectShadow::Initialise(const Vector2i _offset) { @@ -51,10 +49,8 @@ bool FontEffectShadow::HasUniqueTexture() const return false; } -bool FontEffectShadow::GetGlyphMetrics(Vector2i& origin, Vector2i& RMLUI_UNUSED_PARAMETER(dimensions), const FontGlyph& glyph) const +bool FontEffectShadow::GetGlyphMetrics(Vector2i& origin, Vector2i& /*dimensions*/, const FontGlyph& glyph) const { - RMLUI_UNUSED(dimensions); - if (glyph.color_format == ColorFormat::RGBA8) return false; @@ -62,9 +58,8 @@ bool FontEffectShadow::GetGlyphMetrics(Vector2i& origin, Vector2i& RMLUI_UNUSED_ return true; } - - -FontEffectShadowInstancer::FontEffectShadowInstancer() : id_offset_x(PropertyId::Invalid), id_offset_y(PropertyId::Invalid), id_color(PropertyId::Invalid) +FontEffectShadowInstancer::FontEffectShadowInstancer() : + id_offset_x(PropertyId::Invalid), id_offset_y(PropertyId::Invalid), id_color(PropertyId::Invalid) { id_offset_x = RegisterProperty("offset-x", "0px", true).AddParser("length").GetId(); id_offset_y = RegisterProperty("offset-y", "0px", true).AddParser("length").GetId(); @@ -73,18 +68,14 @@ FontEffectShadowInstancer::FontEffectShadowInstancer() : id_offset_x(PropertyId: RegisterShorthand("font-effect", "offset-x, offset-y, color", ShorthandType::FallThrough); } -FontEffectShadowInstancer::~FontEffectShadowInstancer() -{ -} +FontEffectShadowInstancer::~FontEffectShadowInstancer() {} -SharedPtr FontEffectShadowInstancer::InstanceFontEffect(const String& RMLUI_UNUSED_PARAMETER(name), const PropertyDictionary& properties) +SharedPtr FontEffectShadowInstancer::InstanceFontEffect(const String& /*name*/, const PropertyDictionary& properties) { - RMLUI_UNUSED(name); - Vector2i offset; - offset.x = Math::RealToInteger(properties.GetProperty(id_offset_x)->Get< float >()); - offset.y = Math::RealToInteger(properties.GetProperty(id_offset_y)->Get< float >()); - Colourb color = properties.GetProperty(id_color)->Get< Colourb >(); + offset.x = Math::RealToInteger(properties.GetProperty(id_offset_x)->Get()); + offset.y = Math::RealToInteger(properties.GetProperty(id_offset_y)->Get()); + Colourb color = properties.GetProperty(id_color)->Get(); auto font_effect = MakeShared(); if (font_effect->Initialise(offset)) diff --git a/Source/Core/FontEffectShadow.h b/Source/Core/FontEffectShadow.h index 06b57ddf4..5dbbc3eb8 100644 --- a/Source/Core/FontEffectShadow.h +++ b/Source/Core/FontEffectShadow.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - A concrete font effect for rendering text shadows. + A concrete font effect for rendering text shadows. - @author Peter Curry + @author Peter Curry */ -class FontEffectShadow : public FontEffect -{ +class FontEffectShadow : public FontEffect { public: FontEffectShadow(); virtual ~FontEffectShadow(); @@ -56,16 +55,13 @@ class FontEffectShadow : public FontEffect Vector2i offset; }; - - /** - A concrete font effect instancer for the shadow effect. + A concrete font effect instancer for the shadow effect. - @author Peter Curry + @author Peter Curry */ -class FontEffectShadowInstancer : public FontEffectInstancer -{ +class FontEffectShadowInstancer : public FontEffectInstancer { public: FontEffectShadowInstancer(); virtual ~FontEffectShadowInstancer(); @@ -76,6 +72,5 @@ class FontEffectShadowInstancer : public FontEffectInstancer PropertyId id_offset_x, id_offset_y, id_color; }; - } // namespace Rml #endif diff --git a/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.cpp b/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.cpp index df127bf23..4d2288655 100644 --- a/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.cpp +++ b/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,9 +26,9 @@ * */ -#include "FontProvider.h" -#include "FontFaceHandleDefault.h" #include "FontEngineInterfaceDefault.h" +#include "FontFaceHandleDefault.h" +#include "FontProvider.h" namespace Rml { @@ -47,7 +47,8 @@ bool FontEngineInterfaceDefault::LoadFontFace(const String& file_name, bool fall return FontProvider::LoadFontFace(file_name, fallback_face, weight); } -bool FontEngineInterfaceDefault::LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, Style::FontWeight weight, bool fallback_face) +bool FontEngineInterfaceDefault::LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, + Style::FontWeight weight, bool fallback_face) { return FontProvider::LoadFontFace(data, data_size, font_family, style, weight, fallback_face); } @@ -57,10 +58,10 @@ FontFaceHandle FontEngineInterfaceDefault::GetFontFaceHandle(const String& famil auto handle = FontProvider::GetFontFaceHandle(family, style, weight, size); return reinterpret_cast(handle); } - + FontEffectsHandle FontEngineInterfaceDefault::PrepareFontEffects(FontFaceHandle handle, const FontEffectList& font_effects) { - auto handle_default = reinterpret_cast(handle); + auto handle_default = reinterpret_cast(handle); return (FontEffectsHandle)handle_default->GenerateLayerConfiguration(font_effects); } @@ -72,14 +73,14 @@ const FontMetrics& FontEngineInterfaceDefault::GetFontMetrics(FontFaceHandle han int FontEngineInterfaceDefault::GetStringWidth(FontFaceHandle handle, const String& string, float letter_spacing, Character prior_character) { - auto handle_default = reinterpret_cast(handle); + auto handle_default = reinterpret_cast(handle); return handle_default->GetStringWidth(string, letter_spacing, prior_character); } int FontEngineInterfaceDefault::GenerateString(FontFaceHandle handle, FontEffectsHandle font_effects_handle, const String& string, const Vector2f& position, const Colourb& colour, float opacity, float letter_spacing, GeometryList& geometry) { - auto handle_default = reinterpret_cast(handle); + auto handle_default = reinterpret_cast(handle); return handle_default->GenerateString(geometry, string, position, colour, opacity, letter_spacing, (int)font_effects_handle); } diff --git a/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.h b/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.h index f91fecb8f..baa2fbeee 100644 --- a/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.h +++ b/Source/Core/FontEngineDefault/FontEngineInterfaceDefault.h @@ -32,8 +32,7 @@ namespace Rml { -class RMLUICORE_API FontEngineInterfaceDefault : public FontEngineInterface -{ +class RMLUICORE_API FontEngineInterfaceDefault : public FontEngineInterface { public: FontEngineInterfaceDefault(); virtual ~FontEngineInterfaceDefault(); @@ -42,7 +41,8 @@ class RMLUICORE_API FontEngineInterfaceDefault : public FontEngineInterface bool LoadFontFace(const String& file_name, bool fallback_face, Style::FontWeight weight) override; /// Adds a new font face to the database using the provided family, style and weight. - bool LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, Style::FontWeight weight, bool fallback_face) override; + bool LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, Style::FontWeight weight, + bool fallback_face) override; /// Returns a handle to a font face that can be used to position and render text. This will return the closest match /// it can find, but in the event a font family is requested that does not exist, NULL will be returned instead of a diff --git a/Source/Core/FontEngineDefault/FontFace.cpp b/Source/Core/FontEngineDefault/FontFace.cpp index 82675d347..36271cff8 100644 --- a/Source/Core/FontEngineDefault/FontFace.cpp +++ b/Source/Core/FontEngineDefault/FontFace.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,8 +26,8 @@ * */ -#include "../../../Include/RmlUi/Core/Log.h" #include "FontFace.h" +#include "../../../Include/RmlUi/Core/Log.h" #include "FontFaceHandleDefault.h" #include "FreeTypeInterface.h" @@ -42,17 +42,15 @@ FontFace::FontFace(FontFaceHandleFreetype _face, Style::FontStyle _style, Style: FontFace::~FontFace() { - if (face) + if (face) FreeType::ReleaseFace(face); } -// Returns the style of the font face. Style::FontStyle FontFace::GetStyle() const { return style; } -// Returns the weight of the font face. Style::FontWeight FontFace::GetWeight() const { return weight; diff --git a/Source/Core/FontEngineDefault/FontFace.h b/Source/Core/FontEngineDefault/FontFace.h index bd6e5f854..e50db8423 100644 --- a/Source/Core/FontEngineDefault/FontFace.h +++ b/Source/Core/FontEngineDefault/FontFace.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -37,11 +37,10 @@ namespace Rml { class FontFaceHandleDefault; /** - @author Peter Curry + @author Peter Curry */ -class FontFace -{ +class FontFace { public: FontFace(FontFaceHandleFreetype face, Style::FontStyle style, Style::FontWeight weight); ~FontFace(); @@ -63,7 +62,7 @@ class FontFace Style::FontWeight weight; // Key is font size - using HandleMap = UnorderedMap< int, UniquePtr >; + using HandleMap = UnorderedMap>; HandleMap handles; FontFaceHandleFreetype face; diff --git a/Source/Core/FontEngineDefault/FontFaceHandleDefault.cpp b/Source/Core/FontEngineDefault/FontFaceHandleDefault.cpp index 7c34f8ce8..fc8fa5ba0 100644 --- a/Source/Core/FontEngineDefault/FontFaceHandleDefault.cpp +++ b/Source/Core/FontEngineDefault/FontFaceHandleDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #include "FontFaceHandleDefault.h" #include "../../../Include/RmlUi/Core/StringUtilities.h" #include "../TextureLayout.h" -#include "FontProvider.h" #include "FontFaceLayer.h" +#include "FontProvider.h" #include "FreeTypeInterface.h" #include @@ -66,7 +66,7 @@ bool FontFaceHandleDefault::Initialize(FontFaceHandleFreetype face, int font_siz // Generate the default layer and layer configuration. base_layer = GetOrCreateLayer(nullptr); - layer_configurations.push_back(LayerConfiguration{ base_layer }); + layer_configurations.push_back(LayerConfiguration{base_layer}); return true; } @@ -81,7 +81,6 @@ const FontGlyphMap& FontFaceHandleDefault::GetGlyphs() const return glyphs; } -// Returns the width a string will take up if rendered with this handle. int FontFaceHandleDefault::GetStringWidth(const String& string, float letter_spacing, Character prior_character) { int width = 0; @@ -106,7 +105,6 @@ int FontFaceHandleDefault::GetStringWidth(const String& string, float letter_spa return Math::Max(width, 0); } -// Generates, if required, the layer configuration for a given array of font effects. int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font_effects) { if (font_effects.empty()) @@ -114,7 +112,7 @@ int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font // Check each existing configuration for a match with this arrangement of effects. int configuration_index = 1; - for (; configuration_index < (int) layer_configurations.size(); ++configuration_index) + for (; configuration_index < (int)layer_configurations.size(); ++configuration_index) { const LayerConfiguration& configuration = layer_configurations[configuration_index]; @@ -167,11 +165,11 @@ int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font if (!added_base_layer) layer_configuration.push_back(base_layer); - return (int) (layer_configurations.size() - 1); + return (int)(layer_configurations.size() - 1); } -// Generates the texture data for a layer (for the texture database). -bool FontFaceHandleDefault::GenerateLayerTexture(UniquePtr& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect, int texture_id, int handle_version) const +bool FontFaceHandleDefault::GenerateLayerTexture(UniquePtr& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect, + int texture_id, int handle_version) const { if (handle_version != version) { @@ -190,7 +188,6 @@ bool FontFaceHandleDefault::GenerateLayerTexture(UniquePtr& textur return it->layer->GenerateTexture(texture_data, texture_dimensions, texture_id, glyphs); } -// Generates the geometry required to render a single line of text. int FontFaceHandleDefault::GenerateString(GeometryList& geometry, const String& string, const Vector2f position, const Colourb colour, const float opacity, const float letter_spacing, const int layer_configuration_index) { @@ -198,7 +195,7 @@ int FontFaceHandleDefault::GenerateString(GeometryList& geometry, const String& int line_width = 0; RMLUI_ASSERT(layer_configuration_index >= 0); - RMLUI_ASSERT(layer_configuration_index < (int) layer_configurations.size()); + RMLUI_ASSERT(layer_configuration_index < (int)layer_configurations.size()); UpdateLayersOnDirty(); @@ -281,7 +278,7 @@ bool FontFaceHandleDefault::UpdateLayersOnDirty() bool result = false; // If we are dirty, regenerate all the layers and increment the version - if(is_layers_dirty && base_layer) + if (is_layers_dirty && base_layer) { is_layers_dirty = false; ++version; @@ -300,7 +297,7 @@ bool FontFaceHandleDefault::UpdateLayersOnDirty() return result; } -int FontFaceHandleDefault::GetVersion() const +int FontFaceHandleDefault::GetVersion() const { return version; } @@ -398,14 +395,14 @@ const FontGlyph* FontFaceHandleDefault::GetOrAppendGlyph(Character& character, b // Insert the new glyph into our own set of glyphs auto pair = glyphs.emplace(character, glyph->WeakCopy()); it_glyph = pair.first; - if(pair.second) + if (pair.second) is_layers_dirty = true; break; } } // If we still have not found a glyph, use the replacement character. - if(it_glyph == glyphs.end()) + if (it_glyph == glyphs.end()) { character = Character::Replacement; it_glyph = glyphs.find(character); @@ -423,20 +420,20 @@ const FontGlyph* FontFaceHandleDefault::GetOrAppendGlyph(Character& character, b return glyph; } -// Generates (or shares) a layer derived from a font effect. FontFaceLayer* FontFaceHandleDefault::GetOrCreateLayer(const SharedPtr& font_effect) { // Search for the font effect layer first, it may have been instanced before as part of a different configuration. const FontEffect* font_effect_ptr = font_effect.get(); - auto it = std::find_if(layers.begin(), layers.end(), [font_effect_ptr](const EffectLayerPair& pair) { return pair.font_effect == font_effect_ptr; }); + auto it = + std::find_if(layers.begin(), layers.end(), [font_effect_ptr](const EffectLayerPair& pair) { return pair.font_effect == font_effect_ptr; }); if (it != layers.end()) return it->layer.get(); // No existing effect matches, generate a new layer for the effect. - layers.push_back(EffectLayerPair{ font_effect_ptr, nullptr }); + layers.push_back(EffectLayerPair{font_effect_ptr, nullptr}); auto& layer = layers.back().layer; - + layer = MakeUnique(font_effect); GenerateLayer(layer.get()); diff --git a/Source/Core/FontEngineDefault/FontFaceHandleDefault.h b/Source/Core/FontEngineDefault/FontFaceHandleDefault.h index 69860b178..182aa9678 100644 --- a/Source/Core/FontEngineDefault/FontFaceHandleDefault.h +++ b/Source/Core/FontEngineDefault/FontFaceHandleDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,25 +29,23 @@ #ifndef RMLUI_CORE_FONTENGINEDEFAULT_FONTFACEHANDLE_H #define RMLUI_CORE_FONTENGINEDEFAULT_FONTFACEHANDLE_H -#include "../../../Include/RmlUi/Core/Traits.h" #include "../../../Include/RmlUi/Core/FontEffect.h" #include "../../../Include/RmlUi/Core/FontGlyph.h" #include "../../../Include/RmlUi/Core/FontMetrics.h" #include "../../../Include/RmlUi/Core/Geometry.h" #include "../../../Include/RmlUi/Core/Texture.h" +#include "../../../Include/RmlUi/Core/Traits.h" #include "FontTypes.h" namespace Rml { class FontFaceLayer; - /** - @author Peter Curry + @author Peter Curry */ -class FontFaceHandleDefault final : public NonCopyMoveable -{ +class FontFaceHandleDefault final : public NonCopyMoveable { public: FontFaceHandleDefault(); ~FontFaceHandleDefault(); @@ -55,12 +53,13 @@ class FontFaceHandleDefault final : public NonCopyMoveable bool Initialize(FontFaceHandleFreetype face, int font_size, bool load_default_glyphs); const FontMetrics& GetFontMetrics() const; - + const FontGlyphMap& GetGlyphs() const; /// Returns the width a string will take up if rendered with this handle. /// @param[in] string The string to measure. - /// @param[in] prior_character The optionally-specified character that immediately precedes the string. This may have an impact on the string width due to kerning. + /// @param[in] prior_character The optionally-specified character that immediately precedes the string. This may have an impact on the string + /// width due to kerning. /// @return The width, in pixels, this string will occupy if rendered with this handle. int GetStringWidth(const String& string, float letter_spacing, Character prior_character = Character::Null); @@ -74,7 +73,8 @@ class FontFaceHandleDefault final : public NonCopyMoveable /// @param[in] font_effect The font effect used for the layer. /// @param[in] texture_id The index of the texture within the layer to generate. /// @param[in] handle_version The version of the handle data. Function returns false if out of date. - bool GenerateLayerTexture(UniquePtr& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect, int texture_id, int handle_version) const; + bool GenerateLayerTexture(UniquePtr& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect, int texture_id, + int handle_version) const; /// Generates the geometry required to render a single line of text. /// @param[out] geometry An array of geometries to generate the geometry into. @@ -84,7 +84,8 @@ class FontFaceHandleDefault final : public NonCopyMoveable /// @param[in] opacity The opacity of the text, should be applied to font effects. /// @param[in] layer_configuration Face configuration index to use for generating string. /// @return The width, in pixels, of the string geometry. - int GenerateString(GeometryList& geometry, const String& string, Vector2f position, Colourb colour, float opacity, float letter_spacing, int layer_configuration = 0); + int GenerateString(GeometryList& geometry, const String& string, Vector2f position, Colourb colour, float opacity, float letter_spacing, + int layer_configuration = 0); /// Version is changed whenever the layers are dirtied, requiring regeneration of string geometry. int GetVersion() const; @@ -118,12 +119,12 @@ class FontFaceHandleDefault final : public NonCopyMoveable struct EffectLayerPair { const FontEffect* font_effect; - UniquePtr layer; + UniquePtr layer; }; - using FontLayerMap = Vector< EffectLayerPair >; - using FontLayerCache = SmallUnorderedMap< size_t, FontFaceLayer* >; - using LayerConfiguration = Vector< FontFaceLayer* >; - using LayerConfigurationList = Vector< LayerConfiguration >; + using FontLayerMap = Vector; + using FontLayerCache = SmallUnorderedMap; + using LayerConfiguration = Vector; + using LayerConfigurationList = Vector; // The list of all font layers, index by the effect that instanced them. FontFaceLayer* base_layer; @@ -134,7 +135,7 @@ class FontFaceHandleDefault final : public NonCopyMoveable // Pre-cache kerning pairs for some ascii subset of all characters. using AsciiPair = std::uint16_t; using KerningIntType = std::int16_t; - using KerningPairs = UnorderedMap< AsciiPair, KerningIntType >; + using KerningPairs = UnorderedMap; KerningPairs kerning_pair_cache; bool has_kerning = false; diff --git a/Source/Core/FontEngineDefault/FontFaceLayer.cpp b/Source/Core/FontEngineDefault/FontFaceLayer.cpp index 609006bce..0c559e041 100644 --- a/Source/Core/FontEngineDefault/FontFaceLayer.cpp +++ b/Source/Core/FontEngineDefault/FontFaceLayer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -41,8 +41,7 @@ FontFaceLayer::FontFaceLayer(const SharedPtr& _effect) : colou colour = effect->GetColour(); } -FontFaceLayer::~FontFaceLayer() -{} +FontFaceLayer::~FontFaceLayer() {} bool FontFaceLayer::Generate(const FontFaceHandleDefault* handle, const FontFaceLayer* clone, bool clone_glyph_origins) { @@ -117,7 +116,7 @@ bool FontFaceLayer::Generate(const FontFaceHandleDefault* handle, const FontFace TextureBox box; box.origin = Vector2f(float(glyph_origin.x + glyph.bearing.x), float(glyph_origin.y - glyph.bearing.y)); box.dimensions = Vector2f(glyph_dimensions); - + RMLUI_ASSERT(box.dimensions.x >= 0 && box.dimensions.y >= 0); character_boxes[character] = box; @@ -133,7 +132,6 @@ bool FontFaceLayer::Generate(const FontFaceHandleDefault* handle, const FontFace if (!texture_layout.GenerateLayout(max_texture_dimensions)) return false; - // Iterate over each rectangle in the layout, copying the glyph data into the rectangle as // appropriate and generating geometry. for (int i = 0; i < texture_layout.GetNumRectangles(); ++i) @@ -181,11 +179,9 @@ bool FontFaceLayer::Generate(const FontFaceHandleDefault* handle, const FontFace return true; } -// Generates the texture data for a layer (for the texture database). bool FontFaceLayer::GenerateTexture(UniquePtr& texture_data, Vector2i& texture_dimensions, int texture_id, const FontGlyphMap& glyphs) { - if (texture_id < 0 || - texture_id > texture_layout.GetNumTextures()) + if (texture_id < 0 || texture_id > texture_layout.GetNumTextures()) return false; // Generate the texture data. @@ -249,13 +245,11 @@ bool FontFaceLayer::GenerateTexture(UniquePtr& texture_data, Vecto return true; } -// Returns the effect used to generate the layer. const FontEffect* FontFaceLayer::GetFontEffect() const { return effect.get(); } -// Returns on the layer's textures. const Texture* FontFaceLayer::GetTexture(int index) { RMLUI_ASSERT(index >= 0); @@ -264,13 +258,11 @@ const Texture* FontFaceLayer::GetTexture(int index) return &(textures[index]); } -// Returns the number of textures employed by this layer. int FontFaceLayer::GetNumTextures() const { return (int)textures.size(); } -// Returns the layer's colour. Colourb FontFaceLayer::GetColour() const { return colour; diff --git a/Source/Core/FontEngineDefault/FontFaceLayer.h b/Source/Core/FontEngineDefault/FontFaceLayer.h index 134d69057..dc06bc1c1 100644 --- a/Source/Core/FontEngineDefault/FontFaceLayer.h +++ b/Source/Core/FontEngineDefault/FontFaceLayer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -41,14 +41,13 @@ class FontEffect; class FontFaceHandleDefault; /** - A textured layer stored as part of a font face handle. Each handle will have at least a base - layer for the standard font. Further layers can be added to allow rendering of text effects. + A textured layer stored as part of a font face handle. Each handle will have at least a base + layer for the standard font. Further layers can be added to allow rendering of text effects. - @author Peter Curry + @author Peter Curry */ -class FontFaceLayer -{ +class FontFaceLayer { public: FontFaceLayer(const SharedPtr& _effect); ~FontFaceLayer(); @@ -84,21 +83,14 @@ class FontFaceLayer return; // Generate the geometry for the character. - Vector< Vertex >& character_vertices = geometry[box.texture_index].GetVertices(); - Vector< int >& character_indices = geometry[box.texture_index].GetIndices(); + Vector& character_vertices = geometry[box.texture_index].GetVertices(); + Vector& character_indices = geometry[box.texture_index].GetIndices(); character_vertices.resize(character_vertices.size() + 4); character_indices.resize(character_indices.size() + 6); - GeometryUtilities::GenerateQuad( - &character_vertices[0] + (character_vertices.size() - 4), - &character_indices[0] + (character_indices.size() - 6), - Vector2f(position.x + box.origin.x, position.y + box.origin.y).Round(), - box.dimensions, - colour, - box.texcoords[0], - box.texcoords[1], - (int)character_vertices.size() - 4 - ); + GeometryUtilities::GenerateQuad(&character_vertices[0] + (character_vertices.size() - 4), + &character_indices[0] + (character_indices.size() - 6), Vector2f(position.x + box.origin.x, position.y + box.origin.y).Round(), + box.dimensions, colour, box.texcoords[0], box.texcoords[1], (int)character_vertices.size() - 4); } /// Returns the effect used to generate the layer. @@ -113,11 +105,8 @@ class FontFaceLayer Colourb GetColour() const; private: - - - struct TextureBox - { - TextureBox() : texture_index(-1) { } + struct TextureBox { + TextureBox() : texture_index(-1) {} // The offset, in pixels, of the baseline from the start of this character's geometry. Vector2f origin; diff --git a/Source/Core/FontEngineDefault/FontFamily.cpp b/Source/Core/FontEngineDefault/FontFamily.cpp index 71fc96516..29487ab78 100644 --- a/Source/Core/FontEngineDefault/FontFamily.cpp +++ b/Source/Core/FontEngineDefault/FontFamily.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -34,8 +34,7 @@ namespace Rml { -FontFamily::FontFamily(const String& name) : name(name) -{} +FontFamily::FontFamily(const String& name) : name(name) {} FontFamily::~FontFamily() { @@ -45,7 +44,6 @@ FontFamily::~FontFamily() entry.face.reset(); } -// Returns a handle to the most appropriate font in the family, at the correct size. FontFaceHandleDefault* FontFamily::GetFaceHandle(Style::FontStyle style, Style::FontWeight weight, int size) { int best_dist = INT_MAX; @@ -78,7 +76,6 @@ FontFaceHandleDefault* FontFamily::GetFaceHandle(Style::FontStyle style, Style:: return matching_face->GetHandle(size, true); } -// Adds a new face to the family. FontFace* FontFamily::AddFace(FontFaceHandleFreetype ft_face, Style::FontStyle style, Style::FontWeight weight, UniquePtr face_memory) { auto face = MakeUnique(ft_face, style, weight); diff --git a/Source/Core/FontEngineDefault/FontFamily.h b/Source/Core/FontEngineDefault/FontFamily.h index e0cbb3c09..cd18ff28f 100644 --- a/Source/Core/FontEngineDefault/FontFamily.h +++ b/Source/Core/FontEngineDefault/FontFamily.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -37,11 +37,10 @@ class FontFace; class FontFaceHandleDefault; /** - @author Peter Curry + @author Peter Curry */ -class FontFamily -{ +class FontFamily { public: FontFamily(const String& name); ~FontFamily(); @@ -60,7 +59,7 @@ class FontFamily /// @param[in] face_memory Optionally pass ownership of the face's memory to the face itself, automatically releasing it on destruction. /// @return True if the face was loaded successfully, false otherwise. FontFace* AddFace(FontFaceHandleFreetype ft_face, Style::FontStyle style, Style::FontWeight weight, UniquePtr face_memory); - + /// Releases resources owned by sized font faces, including their textures and rendered glyphs. void ReleaseFontResources(); diff --git a/Source/Core/FontEngineDefault/FontProvider.cpp b/Source/Core/FontEngineDefault/FontProvider.cpp index c71bf3839..4a8718f37 100644 --- a/Source/Core/FontEngineDefault/FontProvider.cpp +++ b/Source/Core/FontEngineDefault/FontProvider.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -133,18 +133,16 @@ bool FontProvider::LoadFontFace(const String& file_name, bool fallback_face, Sty return result; } - bool FontProvider::LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, Style::FontWeight weight, bool fallback_face) { const String source = "memory"; - + bool result = Get().LoadFontFace(data, data_size, fallback_face, nullptr, source, font_family, style, weight); - + return result; } - bool FontProvider::LoadFontFace(const byte* data, int data_size, bool fallback_face, UniquePtr face_memory, const String& source, String font_family, Style::FontStyle style, Style::FontWeight weight) { @@ -180,7 +178,7 @@ bool FontProvider::LoadFontFace(const byte* data, int data_size, bool fallback_f int best_width_distance = Math::AbsoluteValue((int)it->width - search_width); auto it_best_width = it; - + // Search forward to find the best 'width' with the same weight. for (++it; it != face_variations.end(); ++it) { @@ -265,5 +263,4 @@ bool FontProvider::AddFace(FontFaceHandleFreetype face, const String& family, St return static_cast(font_face_result); } - } // namespace Rml diff --git a/Source/Core/FontEngineDefault/FontProvider.h b/Source/Core/FontEngineDefault/FontProvider.h index 35816cd44..4a8bced8c 100644 --- a/Source/Core/FontEngineDefault/FontProvider.h +++ b/Source/Core/FontEngineDefault/FontProvider.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_FONTENGINEDEFAULT_FONTPROVIDER_H #define RMLUI_CORE_FONTENGINEDEFAULT_FONTPROVIDER_H -#include "../../../Include/RmlUi/Core/Types.h" #include "../../../Include/RmlUi/Core/StyleTypes.h" +#include "../../../Include/RmlUi/Core/Types.h" #include "FontTypes.h" namespace Rml { @@ -40,12 +40,11 @@ class FontFamily; class FontFaceHandleDefault; /** - The font provider contains all font families currently in use by RmlUi. - @author Peter Curry + The font provider contains all font families currently in use by RmlUi. + @author Peter Curry */ -class FontProvider -{ +class FontProvider { public: static bool Initialise(); static void Shutdown(); @@ -64,7 +63,8 @@ class FontProvider static bool LoadFontFace(const String& file_name, bool fallback_face, Style::FontWeight weight = Style::FontWeight::Auto); /// Adds a new font face from memory. - static bool LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, Style::FontWeight weight, bool fallback_face); + static bool LoadFontFace(const byte* data, int data_size, const String& font_family, Style::FontStyle style, Style::FontWeight weight, + bool fallback_face); /// Return the number of fallback font faces. static int CountFallbackFontFaces(); @@ -81,20 +81,19 @@ class FontProvider static FontProvider& Get(); - bool LoadFontFace(const byte* data, int data_size, bool fallback_face, UniquePtr face_memory, const String& source, - String font_family, Style::FontStyle style, Style::FontWeight weight); + bool LoadFontFace(const byte* data, int data_size, bool fallback_face, UniquePtr face_memory, const String& source, String font_family, + Style::FontStyle style, Style::FontWeight weight); bool AddFace(FontFaceHandleFreetype face, const String& family, Style::FontStyle style, Style::FontWeight weight, bool fallback_face, UniquePtr face_memory); using FontFaceList = Vector; - using FontFamilyMap = UnorderedMap< String, UniquePtr>; + using FontFamilyMap = UnorderedMap>; FontFamilyMap font_families; FontFaceList fallback_font_faces; static const String debugger_font_family_name; - }; } // namespace Rml diff --git a/Source/Core/FontEngineDefault/FontTypes.h b/Source/Core/FontEngineDefault/FontTypes.h index cbc6166a9..5b76ae9ae 100644 --- a/Source/Core/FontEngineDefault/FontTypes.h +++ b/Source/Core/FontEngineDefault/FontTypes.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/FontEngineDefault/FreeTypeInterface.cpp b/Source/Core/FontEngineDefault/FreeTypeInterface.cpp index 24cd79fba..eceafa087 100644 --- a/Source/Core/FontEngineDefault/FreeTypeInterface.cpp +++ b/Source/Core/FontEngineDefault/FreeTypeInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -31,10 +31,9 @@ #include "../../../Include/RmlUi/Core/FontMetrics.h" #include "../../../Include/RmlUi/Core/Log.h" #include -#include -#include - #include +#include +#include #include FT_FREETYPE_H #include FT_MULTIPLE_MASTERS_H #include FT_TRUETYPE_TABLES_H @@ -118,13 +117,8 @@ bool FreeType::GetFaceVariations(const byte* data, int data_length, Vectornamedstyle[i].coords[axis_index_width]) : 0); int named_instance_index = (i + 1); - out_face_variations.push_back( - FaceVariation{ - weight == 0 ? Style::FontWeight::Normal : (Style::FontWeight)weight, - width == 0 ? (uint16_t)100 : width, - named_instance_index - } - ); + out_face_variations.push_back(FaceVariation{weight == 0 ? Style::FontWeight::Normal : (Style::FontWeight)weight, + width == 0 ? (uint16_t)100 : width, named_instance_index}); } } @@ -193,7 +187,6 @@ void FreeType::GetFaceStyle(FontFaceHandleFreetype in_face, String* font_family, } } -// Initialises the handle so it is able to render text. bool FreeType::InitialiseFaceHandle(FontFaceHandleFreetype face, int font_size, FontGlyphMap& glyphs, FontMetrics& metrics, bool load_default_glyphs) { FT_Face ft_face = (FT_Face)face; @@ -231,7 +224,6 @@ bool FreeType::AppendGlyph(FontFaceHandleFreetype face, int font_size, Character return true; } - int FreeType::GetKerning(FontFaceHandleFreetype face, int font_size, Character lhs, Character rhs) { FT_Face ft_face = (FT_Face)face; @@ -249,13 +241,8 @@ int FreeType::GetKerning(FontFaceHandleFreetype face, int font_size, Character l FT_Vector ft_kerning; - FT_Error ft_error = FT_Get_Kerning( - ft_face, - FT_Get_Char_Index(ft_face, (FT_ULong)lhs), - FT_Get_Char_Index(ft_face, (FT_ULong)rhs), - FT_KERNING_DEFAULT, - &ft_kerning - ); + FT_Error ft_error = FT_Get_Kerning(ft_face, FT_Get_Char_Index(ft_face, (FT_ULong)lhs), FT_Get_Char_Index(ft_face, (FT_ULong)rhs), + FT_KERNING_DEFAULT, &ft_kerning); if (ft_error) return 0; @@ -271,8 +258,6 @@ bool FreeType::HasKerning(FontFaceHandleFreetype face) return FT_HAS_KERNING(ft_face); } - - static void BuildGlyphMap(FT_Face ft_face, int size, FontGlyphMap& glyphs, const float bitmap_scaling_factor, const bool load_default_glyphs) { if (load_default_glyphs) @@ -293,10 +278,10 @@ static void BuildGlyphMap(FT_Face ft_face, int size, FontGlyphMap& glyphs, const if (it == glyphs.end()) { FontGlyph glyph; - glyph.dimensions = { size / 3, (size * 2) / 3 }; + glyph.dimensions = {size / 3, (size * 2) / 3}; glyph.bitmap_dimensions = glyph.dimensions; glyph.advance = glyph.dimensions.x + 2; - glyph.bearing = { 1, glyph.dimensions.y }; + glyph.bearing = {1, glyph.dimensions.y}; glyph.bitmap_owned_data.reset(new byte[glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y]); glyph.bitmap_data = glyph.bitmap_owned_data.get(); @@ -325,21 +310,24 @@ static bool BuildGlyph(FT_Face ft_face, const Character character, FontGlyphMap& FT_Error error = FT_Load_Glyph(ft_face, index, FT_LOAD_COLOR); if (error != 0) { - Log::Message(Log::LT_WARNING, "Unable to load glyph for character '%u' on the font face '%s %s'; error code: %d.", (unsigned int)character, ft_face->family_name, ft_face->style_name, error); + Log::Message(Log::LT_WARNING, "Unable to load glyph for character '%u' on the font face '%s %s'; error code: %d.", (unsigned int)character, + ft_face->family_name, ft_face->style_name, error); return false; } error = FT_Render_Glyph(ft_face->glyph, FT_RENDER_MODE_NORMAL); if (error != 0) { - Log::Message(Log::LT_WARNING, "Unable to render glyph for character '%u' on the font face '%s %s'; error code: %d.", (unsigned int)character, ft_face->family_name, ft_face->style_name, error); + Log::Message(Log::LT_WARNING, "Unable to render glyph for character '%u' on the font face '%s %s'; error code: %d.", (unsigned int)character, + ft_face->family_name, ft_face->style_name, error); return false; } auto result = glyphs.emplace(character, FontGlyph{}); if (!result.second) { - Log::Message(Log::LT_WARNING, "Glyph character '%u' is already loaded in the font face '%s %s'.", (unsigned int)character, ft_face->family_name, ft_face->style_name); + Log::Message(Log::LT_WARNING, "Glyph character '%u' is already loaded in the font face '%s %s'.", (unsigned int)character, + ft_face->family_name, ft_face->style_name); return false; } diff --git a/Source/Core/FontEngineDefault/FreeTypeInterface.h b/Source/Core/FontEngineDefault/FreeTypeInterface.h index 302282b7f..42032a7be 100644 --- a/Source/Core/FontEngineDefault/FreeTypeInterface.h +++ b/Source/Core/FontEngineDefault/FreeTypeInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,43 +29,43 @@ #ifndef RMLUI_CORE_FONTENGINEDEFAULT_FREETYPEINTERFACE_H #define RMLUI_CORE_FONTENGINEDEFAULT_FREETYPEINTERFACE_H -#include "FontTypes.h" #include "../../../Include/RmlUi/Core/FontMetrics.h" +#include "FontTypes.h" namespace Rml { namespace FreeType { -// Initialize FreeType library. -bool Initialise(); -// Shutdown FreeType library. -void Shutdown(); + // Initialize FreeType library. + bool Initialise(); + // Shutdown FreeType library. + void Shutdown(); -// Returns a sorted list of available font variations for the font face located in memory. -bool GetFaceVariations(const byte* data, int data_length, Vector& out_face_variations); + // Returns a sorted list of available font variations for the font face located in memory. + bool GetFaceVariations(const byte* data, int data_length, Vector& out_face_variations); -// Loads a FreeType face from memory, 'source' is only used for logging. -FontFaceHandleFreetype LoadFace(const byte* data, int data_length, const String& source, int named_instance_index = 0); + // Loads a FreeType face from memory, 'source' is only used for logging. + FontFaceHandleFreetype LoadFace(const byte* data, int data_length, const String& source, int named_instance_index = 0); -// Releases the FreeType face. -bool ReleaseFace(FontFaceHandleFreetype face); + // Releases the FreeType face. + bool ReleaseFace(FontFaceHandleFreetype face); -// Retrieves the font family, style and weight of the given font face. Use nullptr to ignore a property. -void GetFaceStyle(FontFaceHandleFreetype face, String* font_family, Style::FontStyle* style, Style::FontWeight* weight); + // Retrieves the font family, style and weight of the given font face. Use nullptr to ignore a property. + void GetFaceStyle(FontFaceHandleFreetype face, String* font_family, Style::FontStyle* style, Style::FontWeight* weight); -// Initializes a face for a given font size. Glyphs are filled with the ASCII subset, and the font face metrics are set. -bool InitialiseFaceHandle(FontFaceHandleFreetype face, int font_size, FontGlyphMap& glyphs, FontMetrics& metrics, bool load_default_glyphs); + // Initializes a face for a given font size. Glyphs are filled with the ASCII subset, and the font face metrics are set. + bool InitialiseFaceHandle(FontFaceHandleFreetype face, int font_size, FontGlyphMap& glyphs, FontMetrics& metrics, bool load_default_glyphs); -// Build a new glyph representing the given code point and append to 'glyphs'. -bool AppendGlyph(FontFaceHandleFreetype face, int font_size, Character character, FontGlyphMap& glyphs); + // Build a new glyph representing the given code point and append to 'glyphs'. + bool AppendGlyph(FontFaceHandleFreetype face, int font_size, Character character, FontGlyphMap& glyphs); -// Returns the kerning between two characters. -// 'font_size' value of zero assumes the font size is already set on the face, and skips this step for performance reasons. -int GetKerning(FontFaceHandleFreetype face, int font_size, Character lhs, Character rhs); + // Returns the kerning between two characters. + // 'font_size' value of zero assumes the font size is already set on the face, and skips this step for performance reasons. + int GetKerning(FontFaceHandleFreetype face, int font_size, Character lhs, Character rhs); -// Returns true if the font face has kerning. -bool HasKerning(FontFaceHandleFreetype face); + // Returns true if the font face has kerning. + bool HasKerning(FontFaceHandleFreetype face); -} +} // namespace FreeType } // namespace Rml #endif diff --git a/Source/Core/FontEngineInterface.cpp b/Source/Core/FontEngineInterface.cpp index 257ec0bd7..138342ed4 100644 --- a/Source/Core/FontEngineInterface.cpp +++ b/Source/Core/FontEngineInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Geometry.cpp b/Source/Core/Geometry.cpp index c60bf7a37..a67739549 100644 --- a/Source/Core/Geometry.cpp +++ b/Source/Core/Geometry.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,7 +35,6 @@ #include "GeometryDatabase.h" #include - namespace Rml { Geometry::Geometry(Element* host_element) : host_element(host_element) @@ -82,7 +81,6 @@ Geometry::~Geometry() Release(); } -// Set the host element for this geometry; this should be passed in the constructor if possible. void Geometry::SetHostElement(Element* _host_element) { if (host_element == _host_element) @@ -115,8 +113,7 @@ void Geometry::Render(Vector2f translation) // immediate mode. else { - if (vertices.empty() || - indices.empty()) + if (vertices.empty() || indices.empty()) return; RMLUI_ZoneScopedN("RenderGeometry"); @@ -124,12 +121,13 @@ void Geometry::Render(Vector2f translation) if (!compile_attempted) { compile_attempted = true; - compiled_geometry = render_interface->CompileGeometry(&vertices[0], (int)vertices.size(), &indices[0], (int)indices.size(), texture ? texture->GetHandle(render_interface) : 0); + compiled_geometry = render_interface->CompileGeometry(&vertices[0], (int)vertices.size(), &indices[0], (int)indices.size(), + texture ? texture->GetHandle(render_interface) : 0); // If we managed to compile the geometry, we can clear the local copy of vertices and indices and // immediately render the compiled version. if (compiled_geometry) - { + { render_interface->RenderCompiledGeometry(compiled_geometry, translation); return; } @@ -137,29 +135,26 @@ void Geometry::Render(Vector2f translation) // Either we've attempted to compile before (and failed), or the compile we just attempted failed; either way, // render the uncompiled version. - render_interface->RenderGeometry(&vertices[0], (int)vertices.size(), &indices[0], (int)indices.size(), texture ? texture->GetHandle(GetRenderInterface()) : 0, translation); + render_interface->RenderGeometry(&vertices[0], (int)vertices.size(), &indices[0], (int)indices.size(), + texture ? texture->GetHandle(GetRenderInterface()) : 0, translation); } } -// Returns the geometry's vertices. If these are written to, Release() should be called to force a recompile. -Vector< Vertex >& Geometry::GetVertices() +Vector& Geometry::GetVertices() { return vertices; } -// Returns the geometry's indices. If these are written to, Release() should be called to force a recompile. -Vector< int >& Geometry::GetIndices() +Vector& Geometry::GetIndices() { return indices; } -// Gets the geometry's texture. const Texture* Geometry::GetTexture() const { return texture; } -// Sets the geometry's texture. void Geometry::SetTexture(const Texture* _texture) { texture = _texture; @@ -188,7 +183,6 @@ Geometry::operator bool() const return !indices.empty(); } -// Returns the host context's render interface. RenderInterface* Geometry::GetRenderInterface() { if (!host_context) diff --git a/Source/Core/GeometryBackgroundBorder.cpp b/Source/Core/GeometryBackgroundBorder.cpp index a79fb6fe4..528be1c08 100644 --- a/Source/Core/GeometryBackgroundBorder.cpp +++ b/Source/Core/GeometryBackgroundBorder.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,10 +34,10 @@ namespace Rml { -GeometryBackgroundBorder::GeometryBackgroundBorder(Vector& vertices, Vector& indices) : vertices(vertices), indices(indices) -{} +GeometryBackgroundBorder::GeometryBackgroundBorder(Vector& vertices, Vector& indices) : vertices(vertices), indices(indices) {} -void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indices, CornerSizes radii, const Box& box, const Vector2f offset, const Colourb background_color, const Colourb* border_colors) +void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indices, CornerSizes radii, const Box& box, const Vector2f offset, + const Colourb background_color, const Colourb* border_colors) { using Edge = Box::Edge; @@ -69,14 +69,15 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic const Vector2f border_position = offset.Round(); const Vector2f padding_position = border_position + Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]); - const Vector2f border_size = padding_size + Vector2f(border_widths[Edge::LEFT] + border_widths[Edge::RIGHT], border_widths[Edge::TOP] + border_widths[Edge::BOTTOM]); + const Vector2f border_size = + padding_size + Vector2f(border_widths[Edge::LEFT] + border_widths[Edge::RIGHT], border_widths[Edge::TOP] + border_widths[Edge::BOTTOM]); // Border edge positions CornerPositions positions_outer = { border_position, border_position + Vector2f(border_size.x, 0), border_position + border_size, - border_position + Vector2f(0, border_size.y) + border_position + Vector2f(0, border_size.y), }; // Padding edge positions @@ -84,10 +85,9 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic padding_position, padding_position + Vector2f(padding_size.x, 0), padding_position + padding_size, - padding_position + Vector2f(0, padding_size.y) + padding_position + Vector2f(0, padding_size.y), }; - // -- For curved borders, find the positions to draw ellipses around, and the scaled outer and inner radii -- const float sum_radius = (radii[TOP_LEFT] + radii[TOP_RIGHT] + radii[BOTTOM_RIGHT] + radii[BOTTOM_LEFT]); @@ -117,17 +117,17 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic // Place the circle/ellipse centers positions_circle_center = { - positions_outer[TOP_LEFT] + Vector2f(1, 1) * radii[TOP_LEFT], - positions_outer[TOP_RIGHT] + Vector2f(-1, 1) * radii[TOP_RIGHT], + positions_outer[TOP_LEFT] + Vector2f(1, 1) * radii[TOP_LEFT], + positions_outer[TOP_RIGHT] + Vector2f(-1, 1) * radii[TOP_RIGHT], positions_outer[BOTTOM_RIGHT] + Vector2f(-1, -1) * radii[BOTTOM_RIGHT], - positions_outer[BOTTOM_LEFT] + Vector2f(1, -1) * radii[BOTTOM_LEFT] + positions_outer[BOTTOM_LEFT] + Vector2f(1, -1) * radii[BOTTOM_LEFT], }; inner_radii = { - Vector2f(radii[TOP_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]), - Vector2f(radii[TOP_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::TOP]), + Vector2f(radii[TOP_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]), + Vector2f(radii[TOP_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::TOP]), Vector2f(radii[BOTTOM_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::BOTTOM]), - Vector2f(radii[BOTTOM_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::BOTTOM]) + Vector2f(radii[BOTTOM_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::BOTTOM]), }; } @@ -150,7 +150,8 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic const int offset_vertices = (int)vertices.size(); for (int corner = 0; corner < 4; corner++) - geometry.DrawBackgroundCorner(Corner(corner), positions_inner[corner], positions_circle_center[corner], radii[corner], inner_radii[corner], background_color); + geometry.DrawBackgroundCorner(Corner(corner), positions_inner[corner], positions_circle_center[corner], radii[corner], + inner_radii[corner], background_color); geometry.FillBackground(offset_vertices); } @@ -165,14 +166,14 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic border_widths[Edge::TOP] > 0 && border_colors[Edge::TOP].alpha > 0, border_widths[Edge::RIGHT] > 0 && border_colors[Edge::RIGHT].alpha > 0, border_widths[Edge::BOTTOM] > 0 && border_colors[Edge::BOTTOM].alpha > 0, - border_widths[Edge::LEFT] > 0 && border_colors[Edge::LEFT].alpha > 0 + border_widths[Edge::LEFT] > 0 && border_colors[Edge::LEFT].alpha > 0, }; const bool draw_corner[4] = { draw_edge[Edge::TOP] || draw_edge[Edge::LEFT], draw_edge[Edge::TOP] || draw_edge[Edge::RIGHT], draw_edge[Edge::BOTTOM] || draw_edge[Edge::RIGHT], - draw_edge[Edge::BOTTOM] || draw_edge[Edge::LEFT] + draw_edge[Edge::BOTTOM] || draw_edge[Edge::LEFT], }; for (int corner = 0; corner < 4; corner++) @@ -186,7 +187,8 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic if (draw_edge[edge1]) { - RMLUI_ASSERTMSG(draw_corner[corner] && draw_corner[(corner + 1) % 4], "Border edges can only be drawn if both of its connected corners are drawn."); + RMLUI_ASSERTMSG(draw_corner[corner] && draw_corner[(corner + 1) % 4], + "Border edges can only be drawn if both of its connected corners are drawn."); geometry.FillEdge(edge1 == Edge::LEFT ? offset_vertices : (int)vertices.size()); } } @@ -218,8 +220,6 @@ void GeometryBackgroundBorder::Draw(Vector& vertices, Vector& indic #endif } - - void GeometryBackgroundBorder::DrawBackgroundCorner(Corner corner, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color) { if (R == 0 || r.x <= 0 || r.y <= 0) @@ -283,7 +283,8 @@ void GeometryBackgroundBorder::FillBackground(int index_start) } } -void GeometryBackgroundBorder::DrawBorderCorner(Corner corner, Vector2f pos_outer, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color0, Colourb color1) +void GeometryBackgroundBorder::DrawBorderCorner(Corner corner, Vector2f pos_outer, Vector2f pos_inner, Vector2f pos_circle_center, float R, + Vector2f r, Colourb color0, Colourb color1) { const float a0 = float((int)corner + 2) * 0.5f * Math::RMLUI_PI; const float a1 = float((int)corner + 3) * 0.5f * Math::RMLUI_PI; @@ -318,7 +319,8 @@ void GeometryBackgroundBorder::DrawPointPoint(Vector2f pos_outer, Vector2f pos_i } } -void GeometryBackgroundBorder::DrawArcArc(Vector2f pos_center, float R, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, int num_points) +void GeometryBackgroundBorder::DrawArcArc(Vector2f pos_center, float R, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, + int num_points) { RMLUI_ASSERT(num_points >= 2 && R > 0 && r.x > 0 && r.y > 0); @@ -356,7 +358,8 @@ void GeometryBackgroundBorder::DrawArcArc(Vector2f pos_center, float R, Vector2f } } -void GeometryBackgroundBorder::DrawArcPoint(Vector2f pos_center, Vector2f pos_inner, float R, float a0, float a1, Colourb color0, Colourb color1, int num_points) +void GeometryBackgroundBorder::DrawArcPoint(Vector2f pos_center, Vector2f pos_inner, float R, float a0, float a1, Colourb color0, Colourb color1, + int num_points) { RMLUI_ASSERT(R > 0 && num_points >= 2); @@ -370,7 +373,8 @@ void GeometryBackgroundBorder::DrawArcPoint(Vector2f pos_center, Vector2f pos_in RMLUI_ASSERT((int)vertices.size() - offset_vertices == num_points + 2); - // Swap the last two vertices such that the outer edge vertex is last, see the comment for the border drawing functions. Their colors should already be the same. + // Swap the last two vertices such that the outer edge vertex is last, see the comment for the border drawing functions. Their colors should + // already be the same. const int last_vertex = (int)vertices.size() - 1; std::swap(vertices[last_vertex - 1].position, vertices[last_vertex].position); diff --git a/Source/Core/GeometryBackgroundBorder.h b/Source/Core/GeometryBackgroundBorder.h index 40cf7b197..d4fbebe26 100644 --- a/Source/Core/GeometryBackgroundBorder.h +++ b/Source/Core/GeometryBackgroundBorder.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,10 +44,8 @@ using CornerSizes = Array; using CornerSizes2 = Array; using CornerPositions = Array; - class GeometryBackgroundBorder { public: - /// Generate geometry for background and borders. /// @param[out] vertices Destination vector for generated vertices. /// @param[out] indices Destination vector for generated indices. @@ -56,7 +54,8 @@ class GeometryBackgroundBorder { /// @param[in] offset Offset the position of the generated vertices. /// @param[in] background_color Color of the background, set alpha to zero to not generate a background. /// @param[in] border_colors Pointer to a four-element array of border colors in top-right-bottom-left order, or nullptr to not generate borders. - static void Draw(Vector& vertices, Vector& indices, CornerSizes radii, const Box& box, Vector2f offset, Colourb background_color, const Colourb* border_colors); + static void Draw(Vector& vertices, Vector& indices, CornerSizes radii, const Box& box, Vector2f offset, Colourb background_color, + const Colourb* border_colors); private: enum Corner { TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT }; @@ -72,13 +71,13 @@ class GeometryBackgroundBorder { // Add a single point. void DrawPoint(Vector2f pos, Colourb color); - // Draw an arc by placing vertices along the ellipse formed by the two-axis radius r, spaced evenly between angles a0,a1 (inclusive). Colors are interpolated. + // Draw an arc by placing vertices along the ellipse formed by the two-axis radius r, spaced evenly between angles a0,a1 (inclusive). Colors are + // interpolated. void DrawArc(Vector2f pos_center, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, int num_points); // Generates triangles by connecting the added vertices. void FillBackground(int index_start); - // -- Border -- // All draw operations place the first and last vertices in the following manner. // Let N be the number of vertices placed, and the numbers be indices into the newly placed vertices: @@ -89,7 +88,8 @@ class GeometryBackgroundBorder { // Where 'next' corner means along the clockwise direction. This way we can easily fill the triangles of the edges in FillEdge(). // Draw the corner, delegate to the specific corner shape drawing function. - void DrawBorderCorner(Corner corner, Vector2f pos_outer, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color0, Colourb color1); + void DrawBorderCorner(Corner corner, Vector2f pos_outer, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color0, + Colourb color1); // Draw a sharp border corner, ie. no border-radius. Does not produce any triangles. void DrawPointPoint(Vector2f pos_outer, Vector2f pos_inner, Colourb color0, Colourb color1); @@ -104,7 +104,6 @@ class GeometryBackgroundBorder { // Add triangles between the previous corner to another one specified by the index (possibly yet-to-be-drawn). void FillEdge(int index_next_corner); - // -- Tools -- int GetNumPoints(float R) const; diff --git a/Source/Core/GeometryDatabase.cpp b/Source/Core/GeometryDatabase.cpp index b4a9160e0..8d29352cc 100644 --- a/Source/Core/GeometryDatabase.cpp +++ b/Source/Core/GeometryDatabase.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,134 +30,127 @@ #include "../../Include/RmlUi/Core/Geometry.h" #include - namespace Rml { namespace GeometryDatabase { -class Database { -public: - Database() { - constexpr size_t reserve_size = 512; - geometry_list.reserve(reserve_size); - free_list.reserve(reserve_size); - } - - ~Database() { -#ifdef RMLUI_TESTS_ENABLED - RMLUI_ASSERT(geometry_list.size() == free_list.size()); - std::sort(free_list.begin(), free_list.end()); - for (size_t i = 0; i < free_list.size(); i++) + class Database { + public: + Database() { - RMLUI_ASSERT(i == free_list[i]); + constexpr size_t reserve_size = 512; + geometry_list.reserve(reserve_size); + free_list.reserve(reserve_size); } -#endif - } - GeometryDatabaseHandle insert(Geometry* value) - { - GeometryDatabaseHandle handle; - if (free_list.empty()) + ~Database() { - handle = GeometryDatabaseHandle(geometry_list.size()); - geometry_list.push_back(value); +#ifdef RMLUI_TESTS_ENABLED + RMLUI_ASSERT(geometry_list.size() == free_list.size()); + std::sort(free_list.begin(), free_list.end()); + for (size_t i = 0; i < free_list.size(); i++) + { + RMLUI_ASSERT(i == free_list[i]); + } +#endif } - else + + GeometryDatabaseHandle insert(Geometry* value) { - handle = free_list.back(); - free_list.pop_back(); - geometry_list[handle] = value; + GeometryDatabaseHandle handle; + if (free_list.empty()) + { + handle = GeometryDatabaseHandle(geometry_list.size()); + geometry_list.push_back(value); + } + else + { + handle = free_list.back(); + free_list.pop_back(); + geometry_list[handle] = value; + } + return handle; } - return handle; - } - - int size() const - { - return (int)geometry_list.size() - (int)free_list.size(); - } - - void clear() { - geometry_list.clear(); - free_list.clear(); - } - void erase(GeometryDatabaseHandle handle) - { - free_list.push_back(handle); - } - // Iterate over every item in the database, skipping free slots. - template - void for_each(Func&& func) - { - std::sort(free_list.begin(), free_list.end()); + int size() const { return (int)geometry_list.size() - (int)free_list.size(); } - size_t i_begin_next = 0; - for (GeometryDatabaseHandle freelist_entry : free_list) + void clear() { - const size_t i_end = size_t(freelist_entry); - const size_t i_begin = i_begin_next; - i_begin_next = i_end + 1; - - for (size_t i = i_begin; i < i_end; i++) - func(geometry_list[i]); + geometry_list.clear(); + free_list.clear(); } + void erase(GeometryDatabaseHandle handle) { free_list.push_back(handle); } - for (size_t i = i_begin_next; i < geometry_list.size(); i++) - func(geometry_list[i]); - } + // Iterate over every item in the database, skipping free slots. + template + void for_each(Func&& func) + { + std::sort(free_list.begin(), free_list.end()); -private: - // List of all active geometry, in addition to free slots. - // Free slots (as defined by the 'free_list') may contain dangling pointers and must not be dereferenced. - Vector geometry_list; - // Declares free slots in the 'geometry_list' as indices. - Vector free_list; -}; + size_t i_begin_next = 0; + for (GeometryDatabaseHandle freelist_entry : free_list) + { + const size_t i_end = size_t(freelist_entry); + const size_t i_begin = i_begin_next; + i_begin_next = i_end + 1; + for (size_t i = i_begin; i < i_end; i++) + func(geometry_list[i]); + } -static Database geometry_database; + for (size_t i = i_begin_next; i < geometry_list.size(); i++) + func(geometry_list[i]); + } -GeometryDatabaseHandle Insert(Geometry* geometry) -{ - return geometry_database.insert(geometry); -} + private: + // List of all active geometry, in addition to free slots. + // Free slots (as defined by the 'free_list') may contain dangling pointers and must not be dereferenced. + Vector geometry_list; + // Declares free slots in the 'geometry_list' as indices. + Vector free_list; + }; -void Erase(GeometryDatabaseHandle handle) -{ - geometry_database.erase(handle); -} + static Database geometry_database; -void ReleaseAll() -{ - geometry_database.for_each([](Geometry* geometry) { - geometry->Release(); - }); -} + GeometryDatabaseHandle Insert(Geometry* geometry) + { + return geometry_database.insert(geometry); + } + void Erase(GeometryDatabaseHandle handle) + { + geometry_database.erase(handle); + } + + void ReleaseAll() + { + geometry_database.for_each([](Geometry* geometry) { geometry->Release(); }); + } #ifdef RMLUI_TESTS_ENABLED -bool PrepareForTests() -{ - if (geometry_database.size() > 0) - return false; + bool PrepareForTests() + { + if (geometry_database.size() > 0) + return false; - // Even with size()==0 we can have items in the geometry list which should all be duplicated by the free list. We want to clear them for the tests. - geometry_database.clear(); + // Even with size()==0 we can have items in the geometry list which should all be duplicated by the free list. + // We want to clear them for the tests. + geometry_database.clear(); - return true; -} + return true; + } -bool ListMatchesDatabase(const Vector& geometry_list) -{ - Vector geometry_list_ptrs; - std::for_each(geometry_list.begin(), geometry_list.end(), [&](const Geometry& geometry) { geometry_list_ptrs.push_back(&geometry); }); + bool ListMatchesDatabase(const Vector& geometry_list) + { + Vector geometry_list_ptrs; + std::for_each(geometry_list.begin(), geometry_list.end(), [&](const Geometry& geometry) { geometry_list_ptrs.push_back(&geometry); }); - Vector database_ptrs; - geometry_database.for_each([&](const Geometry* geometry) { database_ptrs.push_back(geometry); }); + Vector database_ptrs; + geometry_database.for_each([&](const Geometry* geometry) { database_ptrs.push_back(geometry); }); - const bool result = std::is_permutation(geometry_list_ptrs.begin(), geometry_list_ptrs.end(), database_ptrs.begin(), database_ptrs.end()); - return result; -} + const bool result = std::is_permutation(geometry_list_ptrs.begin(), geometry_list_ptrs.end(), database_ptrs.begin(), database_ptrs.end()); + return result; + } #endif // RMLUI_TESTS_ENABLED diff --git a/Source/Core/GeometryDatabase.h b/Source/Core/GeometryDatabase.h index 6b43f5c00..ebedf6a6d 100644 --- a/Source/Core/GeometryDatabase.h +++ b/Source/Core/GeometryDatabase.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_GEOMETRYDATABASE_H #define RMLUI_CORE_GEOMETRYDATABASE_H -#include #include "../../Include/RmlUi/Core/Types.h" +#include namespace Rml { @@ -48,16 +48,16 @@ using GeometryDatabaseHandle = uint32_t; namespace GeometryDatabase { - GeometryDatabaseHandle Insert(Geometry* geometry); - void Erase(GeometryDatabaseHandle handle); + GeometryDatabaseHandle Insert(Geometry* geometry); + void Erase(GeometryDatabaseHandle handle); - void ReleaseAll(); + void ReleaseAll(); #ifdef RMLUI_TESTS_ENABLED - bool PrepareForTests(); - bool ListMatchesDatabase(const Vector& geometry_list); + bool PrepareForTests(); + bool ListMatchesDatabase(const Vector& geometry_list); #endif -} +} // namespace GeometryDatabase } // namespace Rml #endif diff --git a/Source/Core/GeometryUtilities.cpp b/Source/Core/GeometryUtilities.cpp index ea68dcb76..511868398 100644 --- a/Source/Core/GeometryUtilities.cpp +++ b/Source/Core/GeometryUtilities.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,22 +35,17 @@ namespace Rml { -GeometryUtilities::GeometryUtilities() -{ -} +GeometryUtilities::GeometryUtilities() {} -GeometryUtilities::~GeometryUtilities() -{ -} +GeometryUtilities::~GeometryUtilities() {} -// Generates a quad from a position, size and colour. void GeometryUtilities::GenerateQuad(Vertex* vertices, int* indices, Vector2f origin, Vector2f dimensions, Colourb colour, int index_offset) { GenerateQuad(vertices, indices, origin, dimensions, colour, Vector2f(0, 0), Vector2f(1, 1), index_offset); } -// Generates a quad from a position, size, colour and texture coordinates. -void GeometryUtilities::GenerateQuad(Vertex* vertices, int* indices, Vector2f origin, Vector2f dimensions, Colourb colour, Vector2f top_left_texcoord, Vector2f bottom_right_texcoord, int index_offset) +void GeometryUtilities::GenerateQuad(Vertex* vertices, int* indices, Vector2f origin, Vector2f dimensions, Colourb colour, Vector2f top_left_texcoord, + Vector2f bottom_right_texcoord, int index_offset) { vertices[0].position = origin; vertices[0].colour = colour; @@ -93,12 +88,13 @@ void GeometryUtilities::GenerateLine(Geometry* geometry, Vector2f position, Vect GeometryUtilities::GenerateQuad(line_vertices.data() + vertices_i0, line_indices.data() + indices_i0, position, size, color, vertices_i0); } -void GeometryUtilities::GenerateBackgroundBorder(Geometry* geometry, const Box& box, Vector2f offset, Vector4f border_radius, Colourb background_colour, const Colourb* border_colours) +void GeometryUtilities::GenerateBackgroundBorder(Geometry* geometry, const Box& box, Vector2f offset, Vector4f border_radius, + Colourb background_colour, const Colourb* border_colours) { Vector& vertices = geometry->GetVertices(); Vector& indices = geometry->GetIndices(); - CornerSizes corner_sizes{ border_radius.x, border_radius.y, border_radius.z, border_radius.w }; + CornerSizes corner_sizes{border_radius.x, border_radius.y, border_radius.z, border_radius.w}; GeometryBackgroundBorder::Draw(vertices, indices, corner_sizes, box, offset, background_colour, border_colours); } diff --git a/Source/Core/IdNameMap.h b/Source/Core/IdNameMap.h index ab7190677..dcedecf9c 100644 --- a/Source/Core/IdNameMap.h +++ b/Source/Core/IdNameMap.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,11 +37,12 @@ namespace Rml { template class IdNameMap { - Vector name_map; // IDs are indices into the name_map + Vector name_map; // IDs are indices into the name_map UnorderedMap reverse_map; protected: - IdNameMap(size_t num_ids_to_reserve) { + IdNameMap(size_t num_ids_to_reserve) + { static_assert((int)ID::Invalid == 0, "Invalid id must be zero"); name_map.reserve(num_ids_to_reserve); reverse_map.reserve(num_ids_to_reserve); diff --git a/Source/Core/Layout/BlockContainer.cpp b/Source/Core/Layout/BlockContainer.cpp index 08feaa46e..91db0fc78 100644 --- a/Source/Core/Layout/BlockContainer.cpp +++ b/Source/Core/Layout/BlockContainer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/BlockContainer.h b/Source/Core/Layout/BlockContainer.h index 17f73ecc6..e0f5e0b0f 100644 --- a/Source/Core/Layout/BlockContainer.h +++ b/Source/Core/Layout/BlockContainer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/BlockFormattingContext.cpp b/Source/Core/Layout/BlockFormattingContext.cpp index 75cd88f3b..b52b36dc9 100644 --- a/Source/Core/Layout/BlockFormattingContext.cpp +++ b/Source/Core/Layout/BlockFormattingContext.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/BlockFormattingContext.h b/Source/Core/Layout/BlockFormattingContext.h index 170ad4179..dc4b6821f 100644 --- a/Source/Core/Layout/BlockFormattingContext.h +++ b/Source/Core/Layout/BlockFormattingContext.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/ContainerBox.cpp b/Source/Core/Layout/ContainerBox.cpp index cf6fd2eac..59e0e8cd0 100644 --- a/Source/Core/Layout/ContainerBox.cpp +++ b/Source/Core/Layout/ContainerBox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/ContainerBox.h b/Source/Core/Layout/ContainerBox.h index ba1e30933..3fe0e9fd6 100644 --- a/Source/Core/Layout/ContainerBox.h +++ b/Source/Core/Layout/ContainerBox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/FlexFormattingContext.cpp b/Source/Core/Layout/FlexFormattingContext.cpp index 09c121d65..6a3252b3a 100644 --- a/Source/Core/Layout/FlexFormattingContext.cpp +++ b/Source/Core/Layout/FlexFormattingContext.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -135,7 +135,7 @@ struct FlexItem { Size cross; float flex_shrink_factor; float flex_grow_factor; - Style::AlignSelf align_self; // 'Auto' is replaced by container's 'align-items' value + Style::AlignSelf align_self; // 'Auto' is replaced by container's 'align-items' value float inner_flex_base_size; // Inner size float flex_base_size; // Outer size diff --git a/Source/Core/Layout/FlexFormattingContext.h b/Source/Core/Layout/FlexFormattingContext.h index 3034c2c25..30897846b 100644 --- a/Source/Core/Layout/FlexFormattingContext.h +++ b/Source/Core/Layout/FlexFormattingContext.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/FloatedBoxSpace.cpp b/Source/Core/Layout/FloatedBoxSpace.cpp index fcac7dfc9..d86beed93 100644 --- a/Source/Core/Layout/FloatedBoxSpace.cpp +++ b/Source/Core/Layout/FloatedBoxSpace.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/FloatedBoxSpace.h b/Source/Core/Layout/FloatedBoxSpace.h index baaf638d1..df9d17ba1 100644 --- a/Source/Core/Layout/FloatedBoxSpace.h +++ b/Source/Core/Layout/FloatedBoxSpace.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/FormattingContext.cpp b/Source/Core/Layout/FormattingContext.cpp index 373c4459f..990339bd6 100644 --- a/Source/Core/Layout/FormattingContext.cpp +++ b/Source/Core/Layout/FormattingContext.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/FormattingContext.h b/Source/Core/Layout/FormattingContext.h index 992d910ec..9d7b3ff45 100644 --- a/Source/Core/Layout/FormattingContext.h +++ b/Source/Core/Layout/FormattingContext.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineBox.cpp b/Source/Core/Layout/InlineBox.cpp index 2bed92f54..d8f1fdb55 100644 --- a/Source/Core/Layout/InlineBox.cpp +++ b/Source/Core/Layout/InlineBox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineBox.h b/Source/Core/Layout/InlineBox.h index d8f2dfe77..740054fc6 100644 --- a/Source/Core/Layout/InlineBox.h +++ b/Source/Core/Layout/InlineBox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineContainer.cpp b/Source/Core/Layout/InlineContainer.cpp index 8a92cefbc..40a82a9b0 100644 --- a/Source/Core/Layout/InlineContainer.cpp +++ b/Source/Core/Layout/InlineContainer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineContainer.h b/Source/Core/Layout/InlineContainer.h index 093a6821e..a2e4edab8 100644 --- a/Source/Core/Layout/InlineContainer.h +++ b/Source/Core/Layout/InlineContainer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineLevelBox.cpp b/Source/Core/Layout/InlineLevelBox.cpp index 1c84782cf..270e74642 100644 --- a/Source/Core/Layout/InlineLevelBox.cpp +++ b/Source/Core/Layout/InlineLevelBox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineLevelBox.h b/Source/Core/Layout/InlineLevelBox.h index a647739b1..06cd67d75 100644 --- a/Source/Core/Layout/InlineLevelBox.h +++ b/Source/Core/Layout/InlineLevelBox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/InlineTypes.h b/Source/Core/Layout/InlineTypes.h index da58e137e..7d47f6bcf 100644 --- a/Source/Core/Layout/InlineTypes.h +++ b/Source/Core/Layout/InlineTypes.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutBox.cpp b/Source/Core/Layout/LayoutBox.cpp index 564684139..a26147607 100644 --- a/Source/Core/Layout/LayoutBox.cpp +++ b/Source/Core/Layout/LayoutBox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutBox.h b/Source/Core/Layout/LayoutBox.h index 9e08847fb..a1532afea 100644 --- a/Source/Core/Layout/LayoutBox.h +++ b/Source/Core/Layout/LayoutBox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutDetails.cpp b/Source/Core/Layout/LayoutDetails.cpp index 4d58ceb8f..708e0a68f 100644 --- a/Source/Core/Layout/LayoutDetails.cpp +++ b/Source/Core/Layout/LayoutDetails.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -49,7 +49,6 @@ static inline float BorderSizeToContentSize(float border_size, float border_padd return Math::Max(0.0f, border_size - border_padding_edges_size); } -// Generates the box for an element. void LayoutDetails::BuildBox(Box& box, Vector2f containing_block, Element* element, BuildBoxMode box_context) { if (!element) @@ -401,7 +400,6 @@ Vector2f LayoutDetails::CalculateSizeForReplacedElement(const Vector2f specified return content_size; } -// Builds the block-specific width and horizontal margins of a Box. void LayoutDetails::BuildBoxWidth(Box& box, const ComputedValues& computed, float min_width, float max_width, Vector2f containing_block, Element* element, bool replaced_element, float override_shrink_to_fit_width) { @@ -491,7 +489,6 @@ void LayoutDetails::BuildBoxWidth(Box& box, const ComputedValues& computed, floa box.SetContent(content_area); } -// Builds the block-specific height and vertical margins of a Box. void LayoutDetails::BuildBoxHeight(Box& box, const ComputedValues& computed, float min_height, float max_height, float containing_block_height) { RMLUI_ZoneScoped; diff --git a/Source/Core/Layout/LayoutDetails.h b/Source/Core/Layout/LayoutDetails.h index 9cf83c8b1..c022c8132 100644 --- a/Source/Core/Layout/LayoutDetails.h +++ b/Source/Core/Layout/LayoutDetails.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutEngine.cpp b/Source/Core/Layout/LayoutEngine.cpp index 32bbd04a9..ae4bc3e2a 100644 --- a/Source/Core/Layout/LayoutEngine.cpp +++ b/Source/Core/Layout/LayoutEngine.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutEngine.h b/Source/Core/Layout/LayoutEngine.h index 1234cd5b2..e9940daa7 100644 --- a/Source/Core/Layout/LayoutEngine.h +++ b/Source/Core/Layout/LayoutEngine.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutPools.cpp b/Source/Core/Layout/LayoutPools.cpp index f95d8997f..bd29e43b3 100644 --- a/Source/Core/Layout/LayoutPools.cpp +++ b/Source/Core/Layout/LayoutPools.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LayoutPools.h b/Source/Core/Layout/LayoutPools.h index ff72c0678..e6b586282 100644 --- a/Source/Core/Layout/LayoutPools.h +++ b/Source/Core/Layout/LayoutPools.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -34,7 +34,7 @@ namespace Rml { namespace LayoutPools { - + void* AllocateLayoutChunk(size_t size); void DeallocateLayoutChunk(void* chunk, size_t size); diff --git a/Source/Core/Layout/LineBox.cpp b/Source/Core/Layout/LineBox.cpp index cc025de54..64c0f297f 100644 --- a/Source/Core/Layout/LineBox.cpp +++ b/Source/Core/Layout/LineBox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/LineBox.h b/Source/Core/Layout/LineBox.h index 3fd25aa18..01e4a1e83 100644 --- a/Source/Core/Layout/LineBox.h +++ b/Source/Core/Layout/LineBox.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/ReplacedFormattingContext.cpp b/Source/Core/Layout/ReplacedFormattingContext.cpp index 7114b9a4d..d8bdf4fed 100644 --- a/Source/Core/Layout/ReplacedFormattingContext.cpp +++ b/Source/Core/Layout/ReplacedFormattingContext.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/ReplacedFormattingContext.h b/Source/Core/Layout/ReplacedFormattingContext.h index e5f0a5094..56e5e5e74 100644 --- a/Source/Core/Layout/ReplacedFormattingContext.h +++ b/Source/Core/Layout/ReplacedFormattingContext.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/TableFormattingContext.cpp b/Source/Core/Layout/TableFormattingContext.cpp index 3e38bd563..b654fe980 100644 --- a/Source/Core/Layout/TableFormattingContext.cpp +++ b/Source/Core/Layout/TableFormattingContext.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/TableFormattingContext.h b/Source/Core/Layout/TableFormattingContext.h index ae44d0d61..2b5788ffe 100644 --- a/Source/Core/Layout/TableFormattingContext.h +++ b/Source/Core/Layout/TableFormattingContext.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/TableFormattingDetails.cpp b/Source/Core/Layout/TableFormattingDetails.cpp index 6fbae98a9..5308afd99 100644 --- a/Source/Core/Layout/TableFormattingDetails.cpp +++ b/Source/Core/Layout/TableFormattingDetails.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Layout/TableFormattingDetails.h b/Source/Core/Layout/TableFormattingDetails.h index e1b301359..6f63009ac 100644 --- a/Source/Core/Layout/TableFormattingDetails.h +++ b/Source/Core/Layout/TableFormattingDetails.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Log.cpp b/Source/Core/Log.cpp index 3121e5198..937c2bf11 100644 --- a/Source/Core/Log.cpp +++ b/Source/Core/Log.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,24 +30,18 @@ #include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/StringUtilities.h" #include "../../Include/RmlUi/Core/SystemInterface.h" - #include #include namespace Rml { -// Initialises the logging interface. bool Log::Initialise() { return true; } -// Shutdown the log interface. -void Log::Shutdown() -{ -} +void Log::Shutdown() {} -// Log the specified message via the registered log interface void Log::Message(Log::Type type, const char* fmt, ...) { const int buffer_size = 1024; @@ -56,11 +50,11 @@ void Log::Message(Log::Type type, const char* fmt, ...) // Print the message to the buffer. va_start(argument_list, fmt); - int len = vsnprintf(buffer, buffer_size - 2, fmt, argument_list); - if (len < 0 || len > buffer_size - 2) + int len = vsnprintf(buffer, buffer_size - 2, fmt, argument_list); + if (len < 0 || len > buffer_size - 2) { len = buffer_size - 2; - } + } buffer[len] = '\0'; va_end(argument_list); @@ -70,7 +64,6 @@ void Log::Message(Log::Type type, const char* fmt, ...) puts(buffer); } -// Log a parse error on the specified file and line number. void Log::ParseError(const String& filename, int line_number, const char* fmt, ...) { const int buffer_size = 1024; @@ -79,11 +72,11 @@ void Log::ParseError(const String& filename, int line_number, const char* fmt, . // Print the message to the buffer. va_start(argument_list, fmt); - int len = vsnprintf(buffer, buffer_size - 2, fmt, argument_list); - if (len < 0 || len > buffer_size - 2) + int len = vsnprintf(buffer, buffer_size - 2, fmt, argument_list); + if (len < 0 || len > buffer_size - 2) { len = buffer_size - 2; - } + } buffer[len] = '\0'; va_end(argument_list); diff --git a/Source/Core/Math.cpp b/Source/Core/Math.cpp index 04933d4a7..97c85bcfa 100644 --- a/Source/Core/Math.cpp +++ b/Source/Core/Math.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,298 +28,266 @@ #include "../../Include/RmlUi/Core/Math.h" #include "../../Include/RmlUi/Core/Types.h" -#include #include #include +#include namespace Rml { namespace Math { -static constexpr float FZERO = 0.0001f; - -// Evaluates if a number is, or close to, zero. -RMLUICORE_API bool IsZero(float value) -{ - return AbsoluteValue(value) < FZERO; -} - -// Evaluates if two floating-point numbers are equal, or so similar that they could be considered -// so. -RMLUICORE_API bool AreEqual(float value_0, float value_1) -{ - return IsZero(value_1 - value_0); -} - -// Calculates the absolute value of a number. -RMLUICORE_API float AbsoluteValue(float value) -{ - return fabsf(value); -} - -RMLUICORE_API int AbsoluteValue(int value) -{ - return abs(value); -} - -RMLUICORE_API Vector2f AbsoluteValue(Vector2f value) -{ - return {fabsf(value.x), fabsf(value.y)}; -} - -// Calculates the cosine of an angle. -RMLUICORE_API float Cos(float angle) -{ - return cosf(angle); -} - -// Calculates the arc-cosine of an value. -RMLUICORE_API float ACos(float value) -{ - return acosf(value); -} - -// Calculates the sine of an angle. -RMLUICORE_API float Sin(float angle) -{ - return sinf(angle); -} - -// Calculates the arc-sine of an value. -RMLUICORE_API float ASin(float angle) -{ - return asinf(angle); -} - -// Calculates the tangent of an angle. -RMLUICORE_API float Tan(float angle) -{ - return tanf(angle); -} - -// Calculates the angle of a two-dimensional line. -RMLUICORE_API float ATan2(float y, float x) -{ - return atan2f(y, x); -} - -// Evaluates the natural exponential function on a value. -RMLUICORE_API float Exp(float value) -{ - return expf(value); -} - -// Evaluates the base-2 logarithm of an integer. -RMLUICORE_API int Log2(int value) -{ - int result = 0; - while (value > 1) - { - value >>= 1; - result++; - } - return result; -} - -// Converts an angle from radians to degrees. -RMLUICORE_API float RadiansToDegrees(float angle) -{ - return angle * (180.0f / RMLUI_PI); -} - -// Converts an angle from degrees to radians. -RMLUICORE_API float DegreesToRadians(float angle) -{ - return angle * (RMLUI_PI / 180.0f); -} - -// Normalises an angle in radians -RMLUICORE_API float NormaliseAngle(float angle) -{ - return fmodf(angle, RMLUI_PI * 2.0f); -} - -// Calculates the square root of a value. -RMLUICORE_API float SquareRoot(float value) -{ - return sqrtf(value); -} - -// Rounds a floating-point value to the nearest integer. -RMLUICORE_API float RoundFloat(float value) -{ - return roundf(value); -} - -// Rounds a floating-point value to the nearest integer. -RMLUICORE_API double RoundFloat(double value) -{ - return round(value); -} - -RMLUICORE_API float RoundUpFloat(float value) -{ - return ceilf(value); -} - -RMLUICORE_API float RoundDownFloat(float value) -{ - return floorf(value); -} - -// Rounds a floating-point value to the nearest integer. -RMLUICORE_API int RoundToInteger(float value) -{ - if (value > 0.0f) - return RealToInteger(value + 0.5f); - - return RealToInteger(value - 0.5f); -} - -// Rounds a floating-point value up to the nearest integer. -RMLUICORE_API int RoundUpToInteger(float value) -{ - return RealToInteger(ceilf(value)); -} - -// Rounds a floating-point value down to the nearest integer. -RMLUICORE_API int RoundDownToInteger(float value) -{ - return RealToInteger(floorf(value)); -} - -RMLUICORE_API float DecomposeFractionalIntegral(float value, float* integral) -{ - return modff(value, integral); -} - -// Efficiently truncates a floating-point value into an integer. -RMLUICORE_API int RealToInteger(float value) -{ - return int(value); -} - -RMLUICORE_API void SnapToPixelGrid(float& offset, float& width) -{ - const float right_edge = offset + width; - offset = Math::RoundFloat(offset); - width = Math::RoundFloat(right_edge) - offset; -} - -RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size) -{ - const Vector2f bottom_right = position + size; - position = position.Round(); - size = bottom_right.Round() - position; -} - -RMLUICORE_API void ExpandToPixelGrid(Vector2f& position, Vector2f& size) -{ - const Vector2f bottom_right = position + size; - position = Vector2f(std::floor(position.x), std::floor(position.y)); - size = Vector2f(std::ceil(bottom_right.x), std::ceil(bottom_right.y)) - position; -} - -// Converts the given number to a power of two, rounding up if necessary. -RMLUICORE_API int ToPowerOfTwo(int number) -{ - // Check if the number is already a power of two. - if ((number & (number - 1)) == 0) - return number; - - // Assuming 31 useful bits in an int here ... ! - for (int i = 31; i >= 0; i--) - { - if (number & (1 << i)) + static constexpr float FZERO = 0.0001f; + + RMLUICORE_API bool IsZero(float value) + { + return AbsoluteValue(value) < FZERO; + } + + RMLUICORE_API bool AreEqual(float value_0, float value_1) + { + return IsZero(value_1 - value_0); + } + + RMLUICORE_API float AbsoluteValue(float value) + { + return fabsf(value); + } + + RMLUICORE_API int AbsoluteValue(int value) + { + return abs(value); + } + + RMLUICORE_API Vector2f AbsoluteValue(Vector2f value) + { + return {fabsf(value.x), fabsf(value.y)}; + } + + RMLUICORE_API float Cos(float angle) + { + return cosf(angle); + } + + RMLUICORE_API float ACos(float value) + { + return acosf(value); + } + + RMLUICORE_API float Sin(float angle) + { + return sinf(angle); + } + + RMLUICORE_API float ASin(float angle) + { + return asinf(angle); + } + + RMLUICORE_API float Tan(float angle) + { + return tanf(angle); + } + + RMLUICORE_API float ATan2(float y, float x) + { + return atan2f(y, x); + } + + RMLUICORE_API float Exp(float value) + { + return expf(value); + } + + RMLUICORE_API int Log2(int value) + { + int result = 0; + while (value > 1) { - if (i == 31) - return 1 << 31; - else - return 1 << (i + 1); + value >>= 1; + result++; } + return result; + } + + RMLUICORE_API float RadiansToDegrees(float angle) + { + return angle * (180.0f / RMLUI_PI); + } + + RMLUICORE_API float DegreesToRadians(float angle) + { + return angle * (RMLUI_PI / 180.0f); + } + + RMLUICORE_API float NormaliseAngle(float angle) + { + return fmodf(angle, RMLUI_PI * 2.0f); + } + + RMLUICORE_API float SquareRoot(float value) + { + return sqrtf(value); + } + + RMLUICORE_API float RoundFloat(float value) + { + return roundf(value); + } + + RMLUICORE_API double RoundFloat(double value) + { + return round(value); + } + + RMLUICORE_API float RoundUpFloat(float value) + { + return ceilf(value); + } + + RMLUICORE_API float RoundDownFloat(float value) + { + return floorf(value); + } + + RMLUICORE_API int RoundToInteger(float value) + { + if (value > 0.0f) + return RealToInteger(value + 0.5f); + + return RealToInteger(value - 0.5f); + } + + RMLUICORE_API int RoundUpToInteger(float value) + { + return RealToInteger(ceilf(value)); + } + + RMLUICORE_API int RoundDownToInteger(float value) + { + return RealToInteger(floorf(value)); + } + + RMLUICORE_API float DecomposeFractionalIntegral(float value, float* integral) + { + return modff(value, integral); + } + + RMLUICORE_API int RealToInteger(float value) + { + return int(value); + } + + RMLUICORE_API void SnapToPixelGrid(float& offset, float& width) + { + const float right_edge = offset + width; + offset = Math::RoundFloat(offset); + width = Math::RoundFloat(right_edge) - offset; + } + + RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size) + { + const Vector2f bottom_right = position + size; + position = position.Round(); + size = bottom_right.Round() - position; + } + + RMLUICORE_API void ExpandToPixelGrid(Vector2f& position, Vector2f& size) + { + const Vector2f bottom_right = position + size; + position = Vector2f(std::floor(position.x), std::floor(position.y)); + size = Vector2f(std::ceil(bottom_right.x), std::ceil(bottom_right.y)) - position; + } + + RMLUICORE_API int ToPowerOfTwo(int number) + { + // Check if the number is already a power of two. + if ((number & (number - 1)) == 0) + return number; + + // Assuming 31 useful bits in an int here ... ! + for (int i = 31; i >= 0; i--) + { + if (number & (1 << i)) + { + if (i == 31) + return 1 << 31; + else + return 1 << (i + 1); + } + } + + return 0; + } + + RMLUICORE_API int HexToDecimal(char hex_digit) + { + if (hex_digit >= '0' && hex_digit <= '9') + return hex_digit - '0'; + else if (hex_digit >= 'a' && hex_digit <= 'f') + return 10 + (hex_digit - 'a'); + else if (hex_digit >= 'A' && hex_digit <= 'F') + return 10 + (hex_digit - 'A'); + + return -1; + } + + RMLUICORE_API float RandomReal(float max_value) + { + return (rand() / (float)RAND_MAX) * max_value; + } + + RMLUICORE_API int RandomInteger(int max_value) + { + return (rand() % max_value); + } + + RMLUICORE_API bool RandomBool() + { + return RandomInteger(2) == 1; + } + + template <> + Vector2f Max(Vector2f a, Vector2f b) + { + return Vector2f(Max(a.x, b.x), Max(a.y, b.y)); + } + template <> + Vector2i Max(Vector2i a, Vector2i b) + { + return Vector2i(Max(a.x, b.x), Max(a.y, b.y)); + } + + template <> + Vector2f Min(Vector2f a, Vector2f b) + { + return Vector2f(Min(a.x, b.x), Min(a.y, b.y)); + } + template <> + Vector2i Min(Vector2i a, Vector2i b) + { + return Vector2i(Min(a.x, b.x), Min(a.y, b.y)); + } + + template <> + Vector2f Clamp(Vector2f value, Vector2f min, Vector2f max) + { + return Vector2f(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y)); + } + template <> + Vector2i Clamp(Vector2i value, Vector2i min, Vector2i max) + { + return Vector2i(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y)); + } + + Colourb RoundedLerp(float t, Colourb v0, Colourb v1) + { + return Colourb{ + static_cast(RoundToInteger(Lerp(t, static_cast(v0[0]), static_cast(v1[0])))), + static_cast(RoundToInteger(Lerp(t, static_cast(v0[1]), static_cast(v1[1])))), + static_cast(RoundToInteger(Lerp(t, static_cast(v0[2]), static_cast(v1[2])))), + static_cast(RoundToInteger(Lerp(t, static_cast(v0[3]), static_cast(v1[3])))), + }; } - return 0; -} - -// Converts from a hexadecimal digit to decimal. -RMLUICORE_API int HexToDecimal(char hex_digit) -{ - if (hex_digit >= '0' && hex_digit <= '9') - return hex_digit - '0'; - else if (hex_digit >= 'a' && hex_digit <= 'f') - return 10 + (hex_digit - 'a'); - else if (hex_digit >= 'A' && hex_digit <= 'F') - return 10 + (hex_digit - 'A'); - - return -1; -} - -// Generates a random floating-point value between 0 and a user-specified value. -RMLUICORE_API float RandomReal(float max_value) -{ - return (rand() / (float) RAND_MAX) * max_value; -} - -// Generates a random integer value between 0 and a user-specified value. -RMLUICORE_API int RandomInteger(int max_value) -{ - return (rand() % max_value); -} - -// Generates a random boolean value, with equal chance of true or false. -RMLUICORE_API bool RandomBool() -{ - return RandomInteger(2) == 1; -} - -template <> -Vector2f Max(Vector2f a, Vector2f b) -{ - return Vector2f(Max(a.x, b.x), Max(a.y, b.y)); -} -template <> -Vector2i Max(Vector2i a, Vector2i b) -{ - return Vector2i(Max(a.x, b.x), Max(a.y, b.y)); -} - -template <> -Vector2f Min(Vector2f a, Vector2f b) -{ - return Vector2f(Min(a.x, b.x), Min(a.y, b.y)); -} -template <> -Vector2i Min(Vector2i a, Vector2i b) -{ - return Vector2i(Min(a.x, b.x), Min(a.y, b.y)); -} - -template <> -Vector2f Clamp(Vector2f value, Vector2f min, Vector2f max) -{ - return Vector2f(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y)); -} -template <> -Vector2i Clamp(Vector2i value, Vector2i min, Vector2i max) -{ - return Vector2i(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y)); -} - - -Colourb RoundedLerp(float t, Colourb v0, Colourb v1) -{ - return Colourb{ - static_cast(RoundToInteger(Lerp(t, - static_cast(v0[0]), static_cast(v1[0])))), - static_cast(RoundToInteger(Lerp(t, - static_cast(v0[1]), static_cast(v1[1])))), - static_cast(RoundToInteger(Lerp(t, - static_cast(v0[2]), static_cast(v1[2])))), - static_cast(RoundToInteger(Lerp(t, - static_cast(v0[3]), static_cast(v1[3])))) - }; -} - -} +} // namespace Math } // namespace Rml diff --git a/Source/Core/Memory.cpp b/Source/Core/Memory.cpp index 407c1c1f2..47f42cfa1 100644 --- a/Source/Core/Memory.cpp +++ b/Source/Core/Memory.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,70 +28,70 @@ #include "Memory.h" #include -#include #include +#include namespace Rml { namespace Detail { -inline void* rmlui_align(size_t alignment, size_t size, void*& ptr, size_t& space) -{ + inline void* rmlui_align(size_t alignment, size_t size, void*& ptr, size_t& space) + { #if defined(_MSC_VER) - return std::align(alignment, size, ptr, space); + return std::align(alignment, size, ptr, space); #else - // std::align replacement to support compilers missing this feature. - // From https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57350 + // std::align replacement to support compilers missing this feature. + // From https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57350 - uintptr_t pn = reinterpret_cast(ptr); - uintptr_t aligned = (pn + alignment - 1) & -alignment; - size_t padding = aligned - pn; - if (space < size + padding) - return nullptr; - space -= padding; - return ptr = reinterpret_cast(aligned); + uintptr_t pn = reinterpret_cast(ptr); + uintptr_t aligned = (pn + alignment - 1) & -alignment; + size_t padding = aligned - pn; + if (space < size + padding) + return nullptr; + space -= padding; + return ptr = reinterpret_cast(aligned); #endif -} + } -BasicStackAllocator::BasicStackAllocator(size_t N) : N(N), data((byte*)malloc(N)), p(data) -{} + BasicStackAllocator::BasicStackAllocator(size_t N) : N(N), data((byte*)malloc(N)), p(data) {} -BasicStackAllocator::~BasicStackAllocator() noexcept { - RMLUI_ASSERT(p == data); - free(data); -} + BasicStackAllocator::~BasicStackAllocator() noexcept + { + RMLUI_ASSERT(p == data); + free(data); + } -void* BasicStackAllocator::allocate(size_t alignment, size_t byte_size) -{ - size_t available_space = N - ((byte*)p - data); + void* BasicStackAllocator::allocate(size_t alignment, size_t byte_size) + { + size_t available_space = N - ((byte*)p - data); - if (rmlui_align(alignment, byte_size, p, available_space)) - { - void* result = p; - p = (byte*)p + byte_size; - return result; - } + if (rmlui_align(alignment, byte_size, p, available_space)) + { + void* result = p; + p = (byte*)p + byte_size; + return result; + } - // Fall back to malloc - return malloc(byte_size); -} + // Fall back to malloc + return malloc(byte_size); + } -void BasicStackAllocator::deallocate(void* obj) noexcept -{ - if (obj < data || obj >= data + N) - { - free(obj); - return; - } - p = obj; -} + void BasicStackAllocator::deallocate(void* obj) noexcept + { + if (obj < data || obj >= data + N) + { + free(obj); + return; + } + p = obj; + } -BasicStackAllocator& GetGlobalBasicStackAllocator() -{ - static BasicStackAllocator stack_allocator(10 * 1024); - return stack_allocator; -} + BasicStackAllocator& GetGlobalBasicStackAllocator() + { + static BasicStackAllocator stack_allocator(10 * 1024); + return stack_allocator; + } -} +} // namespace Detail } // namespace Rml diff --git a/Source/Core/Memory.h b/Source/Core/Memory.h index 0201feb6e..e5a22b959 100644 --- a/Source/Core/Memory.h +++ b/Source/Core/Memory.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,26 +29,24 @@ #ifndef RMLUI_CORE_MEMORY_H #define RMLUI_CORE_MEMORY_H - -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/Traits.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { namespace Detail { /** - Basic stack allocator. - - A very cheap allocator which only moves a pointer up and down during allocation and deallocation, respectively. - The allocator is initialized with some fixed memory. If it runs out, it falls back to malloc. - - Warning: Using this is dangerous as deallocation must happen in exact reverse order of allocation. - - Do not use this class directly. + Basic stack allocator. + + A very cheap allocator which only moves a pointer up and down during allocation and deallocation, respectively. + The allocator is initialized with some fixed memory. If it runs out, it falls back to malloc. + + Warning: Using this is dangerous as deallocation must happen in exact reverse order of allocation. + + Do not use this class directly. */ - class BasicStackAllocator - { + class BasicStackAllocator { public: BasicStackAllocator(size_t N); ~BasicStackAllocator() noexcept; @@ -62,65 +60,65 @@ namespace Detail { void* p; }; - BasicStackAllocator& GetGlobalBasicStackAllocator(); } /* namespace Detail */ - - /** - Global stack allocator. + Global stack allocator. - Can very cheaply allocate memory using the global stack allocator. Memory will be allocated from the - heap on the very first construction of a global stack allocator, and will persist and be re-used after. - Falls back to malloc if there is not enough space left. + Can very cheaply allocate memory using the global stack allocator. Memory will be allocated from the + heap on the very first construction of a global stack allocator, and will persist and be re-used after. + Falls back to malloc if there is not enough space left. - Warning: Using this is dangerous as deallocation must happen in exact reverse order of allocation. - Memory is shared between different global stack allocators. Should only be used for highly localized code, - where memory is allocated and then quickly thrown away. + Warning: Using this is dangerous as deallocation must happen in exact reverse order of allocation. + Memory is shared between different global stack allocators. Should only be used for highly localized code, + where memory is allocated and then quickly thrown away. */ template -class GlobalStackAllocator -{ +class GlobalStackAllocator { public: using value_type = T; GlobalStackAllocator() = default; - template constexpr GlobalStackAllocator(const GlobalStackAllocator&) noexcept {} + template + constexpr GlobalStackAllocator(const GlobalStackAllocator&) noexcept + {} - T* allocate(size_t num_objects) { - return static_cast(Detail::GetGlobalBasicStackAllocator().allocate(alignof(T), num_objects * sizeof(T))); - } + T* allocate(size_t num_objects) { return static_cast(Detail::GetGlobalBasicStackAllocator().allocate(alignof(T), num_objects * sizeof(T))); } - void deallocate(T* ptr, size_t) noexcept { - Detail::GetGlobalBasicStackAllocator().deallocate(ptr); - } + void deallocate(T* ptr, size_t) noexcept { Detail::GetGlobalBasicStackAllocator().deallocate(ptr); } }; template -bool operator==(const GlobalStackAllocator&, const GlobalStackAllocator&) { return true; } +bool operator==(const GlobalStackAllocator&, const GlobalStackAllocator&) +{ + return true; +} template -bool operator!=(const GlobalStackAllocator&, const GlobalStackAllocator&) { return false; } - - +bool operator!=(const GlobalStackAllocator&, const GlobalStackAllocator&) +{ + return false; +} /** - A poor man's dynamic array. + A poor man's dynamic array. - Constructs N objects on initialization which are default initialized. Can not be resized. + Constructs N objects on initialization which are default initialized. Can not be resized. */ template class DynamicArray : Alloc, NonCopyMoveable { public: - DynamicArray(size_t N) : N(N) { + DynamicArray(size_t N) : N(N) + { p = Alloc::allocate(N); for (size_t i = 0; i < N; i++) new (p + i) T; } - ~DynamicArray() noexcept { + ~DynamicArray() noexcept + { for (size_t i = 0; i < N; i++) p[i].~T(); Alloc::deallocate(p, N); diff --git a/Source/Core/ObserverPtr.cpp b/Source/Core/ObserverPtr.cpp index 6c67d0226..68b99be21 100644 --- a/Source/Core/ObserverPtr.cpp +++ b/Source/Core/ObserverPtr.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,7 +44,6 @@ static Pool& GetPool() return *observerPtrBlockPool; } - void DeallocateObserverPtrBlockIfEmpty(ObserverPtrBlock* block) { RMLUI_ASSERT(block->num_observers >= 0); @@ -59,6 +58,4 @@ ObserverPtrBlock* AllocateObserverPtrBlock() return GetPool().AllocateAndConstruct(); } - - } // namespace Rml diff --git a/Source/Core/Plugin.cpp b/Source/Core/Plugin.cpp index 9c3e49398..e5ea3dd67 100644 --- a/Source/Core/Plugin.cpp +++ b/Source/Core/Plugin.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,65 +30,29 @@ namespace Rml { -Plugin::~Plugin() -{ -} +Plugin::~Plugin() {} int Plugin::GetEventClasses() { return EVT_ALL; } -void Plugin::OnInitialise() -{ -} +void Plugin::OnInitialise() {} -void Plugin::OnShutdown() -{ -} +void Plugin::OnShutdown() {} -// Called when a new context is created. -void Plugin::OnContextCreate(Context* RMLUI_UNUSED_PARAMETER(context)) -{ - RMLUI_UNUSED(context); -} +void Plugin::OnContextCreate(Context* /*context*/) {} -// Called when a context is destroyed. -void Plugin::OnContextDestroy(Context* RMLUI_UNUSED_PARAMETER(context)) -{ - RMLUI_UNUSED(context); -} +void Plugin::OnContextDestroy(Context* /*context*/) {} -// Called when a document load request occurs, before the document's file is opened. -void Plugin::OnDocumentOpen(Context* RMLUI_UNUSED_PARAMETER(context), const String& RMLUI_UNUSED_PARAMETER(document_path)) -{ - RMLUI_UNUSED(context); - RMLUI_UNUSED(document_path); -} +void Plugin::OnDocumentOpen(Context* /*context*/, const String& /*document_path*/) {} -// Called when a document is successfully loaded from file or instanced, initialised and added to -// its context. -void Plugin::OnDocumentLoad(ElementDocument* RMLUI_UNUSED_PARAMETER(document)) -{ - RMLUI_UNUSED(document); -} +void Plugin::OnDocumentLoad(ElementDocument* /*document*/) {} -// Called when a document is unloaded from its context. -void Plugin::OnDocumentUnload(ElementDocument* RMLUI_UNUSED_PARAMETER(document)) -{ - RMLUI_UNUSED(document); -} +void Plugin::OnDocumentUnload(ElementDocument* /*document*/) {} -// Called when a new element is created. -void Plugin::OnElementCreate(Element* RMLUI_UNUSED_PARAMETER(element)) -{ - RMLUI_UNUSED(element); -} +void Plugin::OnElementCreate(Element* /*element*/) {} -// Called when an element is destroyed. -void Plugin::OnElementDestroy(Element* RMLUI_UNUSED_PARAMETER(element)) -{ - RMLUI_UNUSED(element); -} +void Plugin::OnElementDestroy(Element* /*element*/) {} } // namespace Rml diff --git a/Source/Core/PluginRegistry.cpp b/Source/Core/PluginRegistry.cpp index 682e1b0ae..343466839 100644 --- a/Source/Core/PluginRegistry.cpp +++ b/Source/Core/PluginRegistry.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,14 +32,12 @@ namespace Rml { -typedef Vector< Plugin* > PluginList; +typedef Vector PluginList; static PluginList basic_plugins; static PluginList document_plugins; static PluginList element_plugins; -PluginRegistry::PluginRegistry() -{ -} +PluginRegistry::PluginRegistry() {} void PluginRegistry::RegisterPlugin(Plugin* plugin) { @@ -57,22 +55,20 @@ void PluginRegistry::UnregisterPlugin(Plugin* plugin) { int event_classes = plugin->GetEventClasses(); - if(event_classes & Plugin::EVT_BASIC) + if (event_classes & Plugin::EVT_BASIC) basic_plugins.erase(std::remove(basic_plugins.begin(), basic_plugins.end(), plugin), basic_plugins.end()); - if(event_classes & Plugin::EVT_DOCUMENT) + if (event_classes & Plugin::EVT_DOCUMENT) document_plugins.erase(std::remove(document_plugins.begin(), document_plugins.end(), plugin), document_plugins.end()); - if(event_classes & Plugin::EVT_ELEMENT) + if (event_classes & Plugin::EVT_ELEMENT) element_plugins.erase(std::remove(element_plugins.begin(), element_plugins.end(), plugin), element_plugins.end()); } -// Calls OnInitialise() on all plugins. void PluginRegistry::NotifyInitialise() { for (size_t i = 0; i < basic_plugins.size(); ++i) basic_plugins[i]->OnInitialise(); } -// Calls OnShutdown() on all plugins. void PluginRegistry::NotifyShutdown() { while (!basic_plugins.empty()) @@ -85,49 +81,42 @@ void PluginRegistry::NotifyShutdown() element_plugins.clear(); } -// Calls OnContextCreate() on all plugins. void PluginRegistry::NotifyContextCreate(Context* context) { for (size_t i = 0; i < basic_plugins.size(); ++i) basic_plugins[i]->OnContextCreate(context); } -// Calls OnContextDestroy() on all plugins. void PluginRegistry::NotifyContextDestroy(Context* context) { for (size_t i = 0; i < basic_plugins.size(); ++i) basic_plugins[i]->OnContextDestroy(context); } -// Calls OnDocumentOpen() on all plugins. void PluginRegistry::NotifyDocumentOpen(Context* context, const String& document_path) { for (size_t i = 0; i < document_plugins.size(); ++i) document_plugins[i]->OnDocumentOpen(context, document_path); } -// Calls OnDocumentLoad() on all plugins. void PluginRegistry::NotifyDocumentLoad(ElementDocument* document) { for (size_t i = 0; i < document_plugins.size(); ++i) document_plugins[i]->OnDocumentLoad(document); } -// Calls OnDocumentUnload() on all plugins. void PluginRegistry::NotifyDocumentUnload(ElementDocument* document) { for (size_t i = 0; i < document_plugins.size(); ++i) document_plugins[i]->OnDocumentUnload(document); } -// Calls OnElementCreate() on all plugins. void PluginRegistry::NotifyElementCreate(Element* element) { for (size_t i = 0; i < element_plugins.size(); ++i) element_plugins[i]->OnElementCreate(element); } -// Calls OnElementDestroy() on all plugins. void PluginRegistry::NotifyElementDestroy(Element* element) { for (size_t i = 0; i < element_plugins.size(); ++i) diff --git a/Source/Core/PluginRegistry.h b/Source/Core/PluginRegistry.h index 4256fddb2..484ac6859 100644 --- a/Source/Core/PluginRegistry.h +++ b/Source/Core/PluginRegistry.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,11 +39,10 @@ class ElementDocument; class Plugin; /** - @author Peter Curry + @author Peter Curry */ -class PluginRegistry -{ +class PluginRegistry { public: static void RegisterPlugin(Plugin* plugin); static void UnregisterPlugin(Plugin* plugin); diff --git a/Source/Core/Pool.h b/Source/Core/Pool.h index e030f1158..cde87bd52 100644 --- a/Source/Core/Pool.h +++ b/Source/Core/Pool.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,30 +29,27 @@ #ifndef RMLUI_CORE_POOL_H #define RMLUI_CORE_POOL_H -#include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Debug.h" +#include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Traits.h" #include "../../Include/RmlUi/Core/Types.h" namespace Rml { -template < typename PoolType > -class Pool -{ +template +class Pool { private: static constexpr size_t N = sizeof(PoolType); static constexpr size_t A = alignof(PoolType); - class PoolNode : public NonCopyMoveable - { + class PoolNode : public NonCopyMoveable { public: alignas(A) unsigned char object[N]; PoolNode* previous; PoolNode* next; }; - class PoolChunk : public NonCopyMoveable - { + class PoolChunk : public NonCopyMoveable { public: PoolNode* chunk; PoolChunk* next; @@ -60,14 +57,13 @@ class Pool public: /** - Iterator objects are used for safe traversal of the allocated - members of a pool. + Iterator objects are used for safe traversal of the allocated + members of a pool. */ - class Iterator - { - friend class Rml::Pool< PoolType >; + class Iterator { + friend class Rml::Pool; - public : + public: /// Increments the iterator to reference the next node in the /// linked list. It is an error to call this function if the /// node this iterator references is invalid. @@ -78,30 +74,18 @@ class Pool } /// Returns true if it is OK to deference or increment this /// iterator. - explicit inline operator bool() - { - return (node != nullptr); - } + explicit inline operator bool() { return (node != nullptr); } /// Returns the object referenced by the iterator's current /// node. - inline PoolType& operator*() - { - return *reinterpret_cast(node->object); - } + inline PoolType& operator*() { return *reinterpret_cast(node->object); } /// Returns a pointer to the object referenced by the /// iterator's current node. - inline PoolType* operator->() - { - return reinterpret_cast(node->object); - } + inline PoolType* operator->() { return reinterpret_cast(node->object); } private: // Constructs an iterator referencing the given node. - inline Iterator(PoolNode* node) - { - this->node = node; - } + inline Iterator(PoolNode* node) { this->node = node; } PoolNode* node; }; @@ -118,7 +102,7 @@ class Pool /// Attempts to allocate an object into a free slot in the memory pool and construct it using the given arguments. /// If the process is successful, the newly constructed object is returned. Otherwise, if the process fails due to /// no free objects being available, nullptr is returned. - template + template inline PoolType* AllocateAndConstruct(Args&&... args); /// Deallocates the object pointed to by the given iterator. diff --git a/Source/Core/Pool.inl b/Source/Core/Pool.inl index e670ffaa4..e2366b30a 100644 --- a/Source/Core/Pool.inl +++ b/Source/Core/Pool.inl @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Profiling.cpp b/Source/Core/Profiling.cpp index 823fb0007..ed4933f7a 100644 --- a/Source/Core/Profiling.cpp +++ b/Source/Core/Profiling.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,16 +26,15 @@ * */ - #include "../../Include/RmlUi/Core/Profiling.h" #ifdef RMLUI_ENABLE_PROFILING -#include -#include + #include + #include -// Overload global new and delete for memory inspection void* operator new(std::size_t n) { + // Overload global new and delete for memory inspection void* ptr = malloc(n); TracyAlloc(ptr, n); return ptr; @@ -46,5 +45,4 @@ void operator delete(void* ptr) noexcept free(ptr); } - #endif diff --git a/Source/Core/PropertiesIterator.h b/Source/Core/PropertiesIterator.h index 9fd6044c6..6b7b38bc0 100644 --- a/Source/Core/PropertiesIterator.h +++ b/Source/Core/PropertiesIterator.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,8 +28,8 @@ #ifndef RMLUI_CORE_PROPERTIESITERATOR_H #define RMLUI_CORE_PROPERTIESITERATOR_H -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/PropertyIdSet.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { @@ -40,13 +40,14 @@ class PropertiesIterator { using ValueType = Pair; using PropertyIt = PropertyMap::const_iterator; - PropertiesIterator(PropertyIt it_style, PropertyIt it_style_end, PropertyIt it_definition, PropertyIt it_definition_end) - : it_style(it_style), it_style_end(it_style_end), it_definition(it_definition), it_definition_end(it_definition_end) + PropertiesIterator(PropertyIt it_style, PropertyIt it_style_end, PropertyIt it_definition, PropertyIt it_definition_end) : + it_style(it_style), it_style_end(it_style_end), it_definition(it_definition), it_definition_end(it_definition_end) { ProceedToNextValid(); } - PropertiesIterator& operator++() { + PropertiesIterator& operator++() + { if (it_style != it_style_end) // We iterate over the local style properties first ++it_style; @@ -61,13 +62,11 @@ class PropertiesIterator { ValueType operator*() const { if (it_style != it_style_end) - return { it_style->first, it_style->second }; - return { it_definition->first, it_definition->second }; + return {it_style->first, it_style->second}; + return {it_definition->first, it_definition->second}; } - bool AtEnd() const { - return at_end; - } + bool AtEnd() const { return at_end; } private: PropertyIdSet iterated_properties; @@ -85,7 +84,7 @@ class PropertiesIterator { return false; } - inline void ProceedToNextValid() + inline void ProceedToNextValid() { for (; it_style != it_style_end; ++it_style) { @@ -104,6 +103,5 @@ class PropertiesIterator { } }; - } // namespace Rml -#endif \ No newline at end of file +#endif diff --git a/Source/Core/PropertiesIteratorView.cpp b/Source/Core/PropertiesIteratorView.cpp index 8353317bc..c1951ce1e 100644 --- a/Source/Core/PropertiesIteratorView.cpp +++ b/Source/Core/PropertiesIteratorView.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,8 +42,7 @@ PropertiesIteratorView& PropertiesIteratorView::operator=(PropertiesIteratorView return *this; } -PropertiesIteratorView::~PropertiesIteratorView() -{} +PropertiesIteratorView::~PropertiesIteratorView() {} PropertiesIteratorView& PropertiesIteratorView::operator++() { @@ -66,7 +65,8 @@ const Property& PropertiesIteratorView::GetProperty() const return (*(*ptr)).second; } -bool PropertiesIteratorView::AtEnd() const { +bool PropertiesIteratorView::AtEnd() const +{ return ptr->AtEnd(); } diff --git a/Source/Core/Property.cpp b/Source/Core/Property.cpp index edcce6c09..afdeb71b3 100644 --- a/Source/Core/Property.cpp +++ b/Source/Core/Property.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -40,7 +40,7 @@ Property::Property() : unit(UNKNOWN), specificity(-1) String Property::ToString() const { if (!definition) - return value.Get< String >(); + return value.Get(); String string; definition->GetValue(string, *this); diff --git a/Source/Core/PropertyDefinition.cpp b/Source/Core/PropertyDefinition.cpp index aa6514a7c..b600aad72 100644 --- a/Source/Core/PropertyDefinition.cpp +++ b/Source/Core/PropertyDefinition.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,19 +32,16 @@ namespace Rml { -PropertyDefinition::PropertyDefinition(PropertyId id, const String& _default_value, bool _inherited, bool _forces_layout) - : id(id), default_value(_default_value, Property::UNKNOWN), relative_target(RelativeTarget::None) +PropertyDefinition::PropertyDefinition(PropertyId id, const String& _default_value, bool _inherited, bool _forces_layout) : + id(id), default_value(_default_value, Property::UNKNOWN), relative_target(RelativeTarget::None) { inherited = _inherited; forces_layout = _forces_layout; default_value.definition = this; } -PropertyDefinition::~PropertyDefinition() -{ -} +PropertyDefinition::~PropertyDefinition() {} -// Registers a parser to parse values for this definition. PropertyDefinition& PropertyDefinition::AddParser(const String& parser_name, const String& parser_parameters) { ParserState new_parser; @@ -88,7 +85,7 @@ PropertyDefinition& PropertyDefinition::AddParser(const String& parser_name, con // If the default value has not been parsed successfully yet, run it through the new parser. if (default_value.unit == Property::UNKNOWN) { - String unparsed_value = default_value.value.Get< String >(); + String unparsed_value = default_value.value.Get(); if (new_parser.parser->ParseValue(default_value, unparsed_value, new_parser.parameters)) { default_value.parser_index = parser_index; @@ -103,7 +100,6 @@ PropertyDefinition& PropertyDefinition::AddParser(const String& parser_name, con return *this; } -// Called when parsing a RCSS declaration. bool PropertyDefinition::ParseValue(Property& property, const String& value) const { for (size_t i = 0; i < parsers.size(); i++) @@ -111,7 +107,7 @@ bool PropertyDefinition::ParseValue(Property& property, const String& value) con if (parsers[i].parser->ParseValue(property, value, parsers[i].parameters)) { property.definition = this; - property.parser_index = (int) i; + property.parser_index = (int)i; return true; } } @@ -120,94 +116,90 @@ bool PropertyDefinition::ParseValue(Property& property, const String& value) con return false; } -// Called to convert a parsed property back into a value. bool PropertyDefinition::GetValue(String& value, const Property& property) const { - value = property.value.Get< String >(); + value = property.value.Get(); switch (property.unit) { - case Property::KEYWORD: + case Property::KEYWORD: + { + int parser_index = property.parser_index; + if (parser_index < 0 || parser_index >= (int)parsers.size()) { - int parser_index = property.parser_index; - if (parser_index < 0 || parser_index >= (int)parsers.size()) + // Look for the keyword parser in the property's list of parsers + const auto* keyword_parser = StyleSheetSpecification::GetParser("keyword"); + for (int i = 0; i < (int)parsers.size(); i++) { - // Look for the keyword parser in the property's list of parsers - const auto* keyword_parser = StyleSheetSpecification::GetParser("keyword"); - for(int i = 0; i < (int)parsers.size(); i++) + if (parsers[i].parser == keyword_parser) { - if (parsers[i].parser == keyword_parser) - { - parser_index = i; - break; - } - } - // If we couldn't find it, exit now - if (parser_index < 0 || parser_index >= (int)parsers.size()) - return false; - } - - int keyword = property.value.Get(); - for (const auto& name_keyword : parsers[parser_index].parameters) - { - if (name_keyword.second == keyword) - { - value = name_keyword.first; + parser_index = i; break; } } - - return false; + // If we couldn't find it, exit now + if (parser_index < 0 || parser_index >= (int)parsers.size()) + return false; } - break; - case Property::COLOUR: + int keyword = property.value.Get(); + for (const auto& name_keyword : parsers[parser_index].parameters) { - Colourb colour = property.value.Get< Colourb >(); - value = CreateString(32, "rgba(%d,%d,%d,%d)", colour.red, colour.green, colour.blue, colour.alpha); + if (name_keyword.second == keyword) + { + value = name_keyword.first; + break; + } } - break; - - case Property::PX: value += "px"; break; - case Property::VW: value += "vw"; break; - case Property::VH: value += "vh"; break; - case Property::DEG: value += "deg"; break; - case Property::RAD: value += "rad"; break; - case Property::DP: value += "dp"; break; - case Property::EM: value += "em"; break; - case Property::REM: value += "rem"; break; - case Property::PERCENT: value += "%"; break; - case Property::INCH: value += "in"; break; - case Property::CM: value += "cm"; break; - case Property::MM: value += "mm"; break; - case Property::PT: value += "pt"; break; - case Property::PC: value += "pc"; break; - default: break; + + return false; + } + break; + + case Property::COLOUR: + { + Colourb colour = property.value.Get(); + value = CreateString(32, "rgba(%d,%d,%d,%d)", colour.red, colour.green, colour.blue, colour.alpha); + } + break; + + // clang-format off + case Property::PX: value += "px"; break; + case Property::VW: value += "vw"; break; + case Property::VH: value += "vh"; break; + case Property::DEG: value += "deg"; break; + case Property::RAD: value += "rad"; break; + case Property::DP: value += "dp"; break; + case Property::EM: value += "em"; break; + case Property::REM: value += "rem"; break; + case Property::PERCENT: value += "%"; break; + case Property::INCH: value += "in"; break; + case Property::CM: value += "cm"; break; + case Property::MM: value += "mm"; break; + case Property::PT: value += "pt"; break; + case Property::PC: value += "pc"; break; + // clang-format on + default: break; } return true; } -// Returns true if this property is inherited from a parent to child elements. bool PropertyDefinition::IsInherited() const { return inherited; } -// Returns true if this property forces a re-layout when changed. bool PropertyDefinition::IsLayoutForced() const { return forces_layout; } -// Returns the default for this property. const Property* PropertyDefinition::GetDefaultValue() const { return &default_value; } -/// Returns the default defined for this property. - RelativeTarget PropertyDefinition::GetRelativeTarget() const { return relative_target; @@ -218,9 +210,7 @@ PropertyId PropertyDefinition::GetId() const return id; } -/// Set target for units with scaling percentages - -PropertyDefinition & PropertyDefinition::SetRelativeTarget(RelativeTarget relative_target) +PropertyDefinition& PropertyDefinition::SetRelativeTarget(RelativeTarget relative_target) { this->relative_target = relative_target; return *this; diff --git a/Source/Core/PropertyDictionary.cpp b/Source/Core/PropertyDictionary.cpp index 9f8eecac1..de01a979e 100644 --- a/Source/Core/PropertyDictionary.cpp +++ b/Source/Core/PropertyDictionary.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,25 +31,20 @@ namespace Rml { -PropertyDictionary::PropertyDictionary() -{ -} +PropertyDictionary::PropertyDictionary() {} -// Sets a property on the dictionary. Any existing property with a similar name will be overwritten. void PropertyDictionary::SetProperty(PropertyId id, const Property& property) { RMLUI_ASSERT(id != PropertyId::Invalid); properties[id] = property; } -// Removes a property from the dictionary, if it exists. void PropertyDictionary::RemoveProperty(PropertyId id) { RMLUI_ASSERT(id != PropertyId::Invalid); properties.erase(id); } -// Returns the value of the property with the requested name, if one exists. const Property* PropertyDictionary::GetProperty(PropertyId id) const { PropertyMap::const_iterator iterator = properties.find(id); @@ -59,19 +54,16 @@ const Property* PropertyDictionary::GetProperty(PropertyId id) const return &(*iterator).second; } -// Returns the number of properties in the dictionary. int PropertyDictionary::GetNumProperties() const { return (int)properties.size(); } -// Returns the map of properties in the dictionary. const PropertyMap& PropertyDictionary::GetProperties() const { return properties; } -// Imports potentially un-specified properties into the dictionary. void PropertyDictionary::Import(const PropertyDictionary& other, int property_specificity) { for (const auto& pair : other.properties) @@ -82,7 +74,6 @@ void PropertyDictionary::Import(const PropertyDictionary& other, int property_sp } } -// Merges the contents of another fully-specified property dictionary with this one. void PropertyDictionary::Merge(const PropertyDictionary& other, int specificity_offset) { for (const auto& pair : other.properties) @@ -99,12 +90,10 @@ void PropertyDictionary::SetSourceOfAllProperties(const SharedPtrsecond.specificity > specificity) + if (iterator != properties.end() && iterator->second.specificity > specificity) return; Property& new_property = (properties[id] = property); diff --git a/Source/Core/PropertyParserAnimation.cpp b/Source/Core/PropertyParserAnimation.cpp index fa34fdf9f..efe6b2e3e 100644 --- a/Source/Core/PropertyParserAnimation.cpp +++ b/Source/Core/PropertyParserAnimation.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,14 +26,12 @@ * */ - #include "PropertyParserAnimation.h" -#include "PropertyShorthandDefinition.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" #include "../../Include/RmlUi/Core/PropertyIdSet.h" #include "../../Include/RmlUi/Core/StringUtilities.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" - +#include "PropertyShorthandDefinition.h" namespace Rml { @@ -53,68 +51,61 @@ struct Keyword { } }; - static const UnorderedMap keywords = { - {"none", {KeywordType::None} }, - {"all", {KeywordType::All}}, - {"alternate", {KeywordType::Alternate}}, - {"infinite", {KeywordType::Infinite}}, - {"paused", {KeywordType::Paused}}, - - {"back-in", {Tween{Tween::Back, Tween::In}}}, - {"back-out", {Tween{Tween::Back, Tween::Out}}}, - {"back-in-out", {Tween{Tween::Back, Tween::InOut}}}, - - {"bounce-in", {Tween{Tween::Bounce, Tween::In}}}, - {"bounce-out", {Tween{Tween::Bounce, Tween::Out}}}, - {"bounce-in-out", {Tween{Tween::Bounce, Tween::InOut}}}, - - {"circular-in", {Tween{Tween::Circular, Tween::In}}}, - {"circular-out", {Tween{Tween::Circular, Tween::Out}}}, - {"circular-in-out", {Tween{Tween::Circular, Tween::InOut}}}, - - {"cubic-in", {Tween{Tween::Cubic, Tween::In}}}, - {"cubic-out", {Tween{Tween::Cubic, Tween::Out}}}, - {"cubic-in-out", {Tween{Tween::Cubic, Tween::InOut}}}, - - {"elastic-in", {Tween{Tween::Elastic, Tween::In}}}, - {"elastic-out", {Tween{Tween::Elastic, Tween::Out}}}, - {"elastic-in-out", {Tween{Tween::Elastic, Tween::InOut}}}, - - {"exponential-in", {Tween{Tween::Exponential, Tween::In}}}, - {"exponential-out", {Tween{Tween::Exponential, Tween::Out}}}, - {"exponential-in-out", {Tween{Tween::Exponential, Tween::InOut}}}, - - {"linear-in", {Tween{Tween::Linear, Tween::In}}}, - {"linear-out", {Tween{Tween::Linear, Tween::Out}}}, - {"linear-in-out", {Tween{Tween::Linear, Tween::InOut}}}, - - {"quadratic-in", {Tween{Tween::Quadratic, Tween::In}}}, - {"quadratic-out", {Tween{Tween::Quadratic, Tween::Out}}}, - {"quadratic-in-out", {Tween{Tween::Quadratic, Tween::InOut}}}, - - {"quartic-in", {Tween{Tween::Quartic, Tween::In}}}, - {"quartic-out", {Tween{Tween::Quartic, Tween::Out}}}, - {"quartic-in-out", {Tween{Tween::Quartic, Tween::InOut}}}, - - {"quintic-in", {Tween{Tween::Quintic, Tween::In}}}, - {"quintic-out", {Tween{Tween::Quintic, Tween::Out}}}, - {"quintic-in-out", {Tween{Tween::Quintic, Tween::InOut}}}, - - {"sine-in", {Tween{Tween::Sine, Tween::In}}}, - {"sine-out", {Tween{Tween::Sine, Tween::Out}}}, - {"sine-in-out", {Tween{Tween::Sine, Tween::InOut}}}, + {"none", {KeywordType::None}}, + {"all", {KeywordType::All}}, + {"alternate", {KeywordType::Alternate}}, + {"infinite", {KeywordType::Infinite}}, + {"paused", {KeywordType::Paused}}, + + {"back-in", {Tween{Tween::Back, Tween::In}}}, + {"back-out", {Tween{Tween::Back, Tween::Out}}}, + {"back-in-out", {Tween{Tween::Back, Tween::InOut}}}, + + {"bounce-in", {Tween{Tween::Bounce, Tween::In}}}, + {"bounce-out", {Tween{Tween::Bounce, Tween::Out}}}, + {"bounce-in-out", {Tween{Tween::Bounce, Tween::InOut}}}, + + {"circular-in", {Tween{Tween::Circular, Tween::In}}}, + {"circular-out", {Tween{Tween::Circular, Tween::Out}}}, + {"circular-in-out", {Tween{Tween::Circular, Tween::InOut}}}, + + {"cubic-in", {Tween{Tween::Cubic, Tween::In}}}, + {"cubic-out", {Tween{Tween::Cubic, Tween::Out}}}, + {"cubic-in-out", {Tween{Tween::Cubic, Tween::InOut}}}, + + {"elastic-in", {Tween{Tween::Elastic, Tween::In}}}, + {"elastic-out", {Tween{Tween::Elastic, Tween::Out}}}, + {"elastic-in-out", {Tween{Tween::Elastic, Tween::InOut}}}, + + {"exponential-in", {Tween{Tween::Exponential, Tween::In}}}, + {"exponential-out", {Tween{Tween::Exponential, Tween::Out}}}, + {"exponential-in-out", {Tween{Tween::Exponential, Tween::InOut}}}, + + {"linear-in", {Tween{Tween::Linear, Tween::In}}}, + {"linear-out", {Tween{Tween::Linear, Tween::Out}}}, + {"linear-in-out", {Tween{Tween::Linear, Tween::InOut}}}, + + {"quadratic-in", {Tween{Tween::Quadratic, Tween::In}}}, + {"quadratic-out", {Tween{Tween::Quadratic, Tween::Out}}}, + {"quadratic-in-out", {Tween{Tween::Quadratic, Tween::InOut}}}, + + {"quartic-in", {Tween{Tween::Quartic, Tween::In}}}, + {"quartic-out", {Tween{Tween::Quartic, Tween::Out}}}, + {"quartic-in-out", {Tween{Tween::Quartic, Tween::InOut}}}, + + {"quintic-in", {Tween{Tween::Quintic, Tween::In}}}, + {"quintic-out", {Tween{Tween::Quintic, Tween::Out}}}, + {"quintic-in-out", {Tween{Tween::Quintic, Tween::InOut}}}, + + {"sine-in", {Tween{Tween::Sine, Tween::In}}}, + {"sine-out", {Tween{Tween::Sine, Tween::Out}}}, + {"sine-in-out", {Tween{Tween::Sine, Tween::InOut}}}, }; +PropertyParserAnimation::PropertyParserAnimation(Type type) : type(type) {} - - -PropertyParserAnimation::PropertyParserAnimation(Type type) : type(type) -{ -} - - -static bool ParseAnimation(Property & property, const StringList& animation_values) +static bool ParseAnimation(Property& property, const StringList& animation_values) { AnimationList animation_list; @@ -135,7 +126,7 @@ static bool ParseAnimation(Property & property, const StringList& animation_valu continue; // See if we have a or specifier as defined in keywords - auto it = keywords.find(argument); + auto it = keywords.find(argument); if (it != keywords.end() && it->second.ValidAnimation()) { switch (it->second.type) @@ -144,27 +135,20 @@ static bool ParseAnimation(Property & property, const StringList& animation_valu { if (animation_list.size() > 0) // The none keyword can not be part of multiple definitions return false; - property = Property{ AnimationList{}, Property::ANIMATION }; + property = Property{AnimationList{}, Property::ANIMATION}; return true; } break; - case KeywordType::Tween: - animation.tween = it->second.tween; - break; - case KeywordType::Alternate: - animation.alternate = true; - break; + case KeywordType::Tween: animation.tween = it->second.tween; break; + case KeywordType::Alternate: animation.alternate = true; break; case KeywordType::Infinite: if (num_iterations_found) return false; animation.num_iterations = -1; num_iterations_found = true; break; - case KeywordType::Paused: - animation.paused = true; - break; - default: - break; + case KeywordType::Paused: animation.paused = true; break; + default: break; } } else @@ -227,21 +211,18 @@ static bool ParseAnimation(Property & property, const StringList& animation_valu return true; } - -static bool ParseTransition(Property & property, const StringList& transition_values) +static bool ParseTransition(Property& property, const StringList& transition_values) { - TransitionList transition_list{ false, false, {} }; + TransitionList transition_list{false, false, {}}; for (const String& single_transition_value : transition_values) { - Transition transition; PropertyIdSet target_property_ids; StringList arguments; StringUtilities::ExpandString(arguments, single_transition_value, ' '); - bool duration_found = false; bool delay_found = false; bool reverse_adjustment_factor_found = false; @@ -259,7 +240,7 @@ static bool ParseTransition(Property & property, const StringList& transition_va { if (transition_list.transitions.size() > 0) // The none keyword can not be part of multiple definitions return false; - property = Property{ TransitionList{true, false, {}}, Property::TRANSITION }; + property = Property{TransitionList{true, false, {}}, Property::TRANSITION}; return true; } else if (it->second.type == KeywordType::All) @@ -333,12 +314,12 @@ static bool ParseTransition(Property & property, const StringList& transition_va } // Validate the parsed transition - if ((transition_list.all && !target_property_ids.Empty()) - || (!transition_list.all && target_property_ids.Empty()) - || transition.duration <= 0.0f - || transition.reverse_adjustment_factor < 0.0f - || transition.reverse_adjustment_factor > 1.0f - ) + if ((transition_list.all && !target_property_ids.Empty()) // + || (!transition_list.all && target_property_ids.Empty()) // + || transition.duration <= 0.0f // + || transition.reverse_adjustment_factor < 0.0f // + || transition.reverse_adjustment_factor > 1.0f // + ) { return false; } @@ -364,8 +345,7 @@ static bool ParseTransition(Property & property, const StringList& transition_va return true; } - -bool PropertyParserAnimation::ParseValue(Property & property, const String & value, const ParameterMap & /*parameters*/) const +bool PropertyParserAnimation::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const { StringList list_of_values; { diff --git a/Source/Core/PropertyParserAnimation.h b/Source/Core/PropertyParserAnimation.h index c5e82d4d3..24117bfb4 100644 --- a/Source/Core/PropertyParserAnimation.h +++ b/Source/Core/PropertyParserAnimation.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2018 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,12 +26,9 @@ * */ - - #ifndef RMLUI_CORE_PROPERTYPARSERANIMATION_H #define RMLUI_CORE_PROPERTYPARSERANIMATION_H - #include "../../Include/RmlUi/Core/PropertyParser.h" namespace Rml { @@ -40,15 +37,13 @@ namespace Rml { Parses the RCSS 'animation' and 'transition' property specifications. */ -class PropertyParserAnimation : public PropertyParser -{ +class PropertyParserAnimation : public PropertyParser { public: enum Type { ANIMATION_PARSER, TRANSITION_PARSER } type; /// Constructs the parser for either the animation or the transition type. PropertyParserAnimation(Type type); - /// Called to parse a RCSS animation or transition declaration. /// @param[out] property The property to set the parsed value on. /// @param[in] value The raw value defined for this property. @@ -57,7 +52,5 @@ class PropertyParserAnimation : public PropertyParser bool ParseValue(Property& property, const String& value, const ParameterMap& parameters) const override; }; - - } // namespace Rml -#endif \ No newline at end of file +#endif diff --git a/Source/Core/PropertyParserColour.cpp b/Source/Core/PropertyParserColour.cpp index 9efb499a3..f9cff3e16 100644 --- a/Source/Core/PropertyParserColour.cpp +++ b/Source/Core/PropertyParserColour.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,27 +42,22 @@ PropertyParserColour::PropertyParserColour() html_colours["red"] = Colourb(255, 0, 0); html_colours["orange"] = Colourb(255, 165, 0); html_colours["purple"] = Colourb(128, 0, 128); - html_colours["fuchsia"] = Colourb(255, 0, 255); - html_colours["green"] = Colourb(0, 128, 0); - html_colours["lime"] = Colourb(0, 255, 0); - html_colours["olive"] = Colourb(128, 128, 0); - html_colours["yellow"] = Colourb(255, 255, 0); - html_colours["navy"] = Colourb(0, 0, 128); - html_colours["blue"] = Colourb(0, 0, 255); - html_colours["teal"] = Colourb(0, 128, 128); + html_colours["fuchsia"] = Colourb(255, 0, 255); + html_colours["green"] = Colourb(0, 128, 0); + html_colours["lime"] = Colourb(0, 255, 0); + html_colours["olive"] = Colourb(128, 128, 0); + html_colours["yellow"] = Colourb(255, 255, 0); + html_colours["navy"] = Colourb(0, 0, 128); + html_colours["blue"] = Colourb(0, 0, 255); + html_colours["teal"] = Colourb(0, 128, 128); html_colours["aqua"] = Colourb(0, 255, 255); html_colours["transparent"] = Colourb(0, 0, 0, 0); } -PropertyParserColour::~PropertyParserColour() -{ -} +PropertyParserColour::~PropertyParserColour() {} -// Called to parse a RCSS colour declaration. -bool PropertyParserColour::ParseValue(Property& property, const String& value, const ParameterMap& RMLUI_UNUSED_PARAMETER(parameters)) const +bool PropertyParserColour::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const { - RMLUI_UNUSED(parameters); - if (value.empty()) return false; @@ -71,32 +66,30 @@ bool PropertyParserColour::ParseValue(Property& property, const String& value, c // Check for a hex colour. if (value[0] == '#') { - char hex_values[4][2] = { {'f', 'f'}, - {'f', 'f'}, - {'f', 'f'}, - {'f', 'f'} }; + char hex_values[4][2] = {{'f', 'f'}, {'f', 'f'}, {'f', 'f'}, {'f', 'f'}}; switch (value.size()) { - // Single hex digit per channel, RGB and alpha. - case 5: hex_values[3][0] = hex_values[3][1] = value[4]; - //-fallthrough - // Single hex digit per channel, RGB only. - case 4: hex_values[0][0] = hex_values[0][1] = value[1]; - hex_values[1][0] = hex_values[1][1] = value[2]; - hex_values[2][0] = hex_values[2][1] = value[3]; - break; - - // Two hex digits per channel, RGB and alpha. - case 9: hex_values[3][0] = value[7]; - hex_values[3][1] = value[8]; - //-fallthrough - // Two hex digits per channel, RGB only. - case 7: memcpy(hex_values, &value.c_str()[1], sizeof(char) * 6); - break; - - default: - return false; + // Single hex digit per channel, RGB and alpha. + case 5: + hex_values[3][0] = hex_values[3][1] = value[4]; + //-fallthrough + // Single hex digit per channel, RGB only. + case 4: + hex_values[0][0] = hex_values[0][1] = value[1]; + hex_values[1][0] = hex_values[1][1] = value[2]; + hex_values[2][0] = hex_values[2][1] = value[3]; + break; + + // Two hex digits per channel, RGB and alpha. + case 9: + hex_values[3][0] = value[7]; + hex_values[3][1] = value[8]; + //-fallthrough + // Two hex digits per channel, RGB only. + case 7: memcpy(hex_values, &value.c_str()[1], sizeof(char) * 6); break; + + default: return false; } // Parse each of the colour elements. @@ -104,11 +97,10 @@ bool PropertyParserColour::ParseValue(Property& property, const String& value, c { int tens = Math::HexToDecimal(hex_values[i][0]); int ones = Math::HexToDecimal(hex_values[i][1]); - if (tens == -1 || - ones == -1) + if (tens == -1 || ones == -1) return false; - colour[i] = (byte) (tens * 16 + ones); + colour[i] = (byte)(tens * 16 + ones); } } else if (value.substr(0, 3) == "rgb") @@ -145,12 +137,12 @@ bool PropertyParserColour::ParseValue(Property& property, const String& value, c // We're parsing a percentage value. if (values[i].size() > 0 && values[i][values[i].size() - 1] == '%') - component = Math::RealToInteger((float) (atof(values[i].substr(0, values[i].size() - 1).c_str()) / 100.0f) * 255.0f); + component = Math::RealToInteger((float)(atof(values[i].substr(0, values[i].size() - 1).c_str()) / 100.0f) * 255.0f); // We're parsing a 0 -> 255 integer value. else component = atoi(values[i].c_str()); - colour[i] = (byte) (Math::Clamp(component, 0, 255)); + colour[i] = (byte)(Math::Clamp(component, 0, 255)); } } else diff --git a/Source/Core/PropertyParserColour.h b/Source/Core/PropertyParserColour.h index fe21ed870..621f2133b 100644 --- a/Source/Core/PropertyParserColour.h +++ b/Source/Core/PropertyParserColour.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,13 +35,12 @@ namespace Rml { /** - A property parser that parses a colour value. + A property parser that parses a colour value. - @author Peter Curry + @author Peter Curry */ -class PropertyParserColour : public PropertyParser -{ +class PropertyParserColour : public PropertyParser { public: PropertyParserColour(); virtual ~PropertyParserColour(); @@ -54,7 +53,7 @@ class PropertyParserColour : public PropertyParser bool ParseValue(Property& property, const String& value, const ParameterMap& parameters) const override; private: - using ColourMap = UnorderedMap< String, Colourb>; + using ColourMap = UnorderedMap; ColourMap html_colours; }; diff --git a/Source/Core/PropertyParserDecorator.cpp b/Source/Core/PropertyParserDecorator.cpp index a1423b463..269543cc6 100644 --- a/Source/Core/PropertyParserDecorator.cpp +++ b/Source/Core/PropertyParserDecorator.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,17 +29,15 @@ #include "PropertyParserDecorator.h" #include "../../Include/RmlUi/Core/DecoratorInstancer.h" #include "../../Include/RmlUi/Core/Factory.h" -#include "../../Include/RmlUi/Core/PropertySpecification.h" #include "../../Include/RmlUi/Core/Profiling.h" +#include "../../Include/RmlUi/Core/PropertySpecification.h" #include "../../Include/RmlUi/Core/StyleSheetTypes.h" namespace Rml { -PropertyParserDecorator::PropertyParserDecorator() -{} +PropertyParserDecorator::PropertyParserDecorator() {} -PropertyParserDecorator::~PropertyParserDecorator() -{} +PropertyParserDecorator::~PropertyParserDecorator() {} bool PropertyParserDecorator::ParseValue(Property& property, const String& decorator_string_value, const ParameterMap& /*parameters*/) const { @@ -77,7 +75,7 @@ bool PropertyParserDecorator::ParseValue(Property& property, const String& decor if (invalid_parenthesis) { // We found no parenthesis, that means the value must be a name of a @decorator rule. - decorators.list.emplace_back(DecoratorDeclaration{ decorator_string, nullptr, {} }); + decorators.list.emplace_back(DecoratorDeclaration{decorator_string, nullptr, {}}); } else { @@ -107,7 +105,7 @@ bool PropertyParserDecorator::ParseValue(Property& property, const String& decor // Set unspecified values to their defaults specification.SetPropertyDefaults(properties); - decorators.list.emplace_back(DecoratorDeclaration{ type, instancer, std::move(properties) }); + decorators.list.emplace_back(DecoratorDeclaration{type, instancer, std::move(properties)}); } } diff --git a/Source/Core/PropertyParserDecorator.h b/Source/Core/PropertyParserDecorator.h index 649a8c3b5..c01865a0b 100644 --- a/Source/Core/PropertyParserDecorator.h +++ b/Source/Core/PropertyParserDecorator.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - A property parser for the decorator property. + A property parser for the decorator property. */ -class PropertyParserDecorator : public PropertyParser -{ +class PropertyParserDecorator : public PropertyParser { public: PropertyParserDecorator(); virtual ~PropertyParserDecorator(); diff --git a/Source/Core/PropertyParserFontEffect.cpp b/Source/Core/PropertyParserFontEffect.cpp index 2b547696d..4a6615c13 100644 --- a/Source/Core/PropertyParserFontEffect.cpp +++ b/Source/Core/PropertyParserFontEffect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,18 +30,16 @@ #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/FontEffect.h" #include "../../Include/RmlUi/Core/FontEffectInstancer.h" -#include "../../Include/RmlUi/Core/PropertySpecification.h" #include "../../Include/RmlUi/Core/Profiling.h" +#include "../../Include/RmlUi/Core/PropertySpecification.h" #include "../../Include/RmlUi/Core/Utilities.h" #include namespace Rml { -PropertyParserFontEffect::PropertyParserFontEffect() -{} +PropertyParserFontEffect::PropertyParserFontEffect() {} -PropertyParserFontEffect::~PropertyParserFontEffect() -{} +PropertyParserFontEffect::~PropertyParserFontEffect() {} bool PropertyParserFontEffect::ParseValue(Property& property, const String& font_effect_string_value, const ParameterMap& /*parameters*/) const { @@ -138,8 +136,7 @@ bool PropertyParserFontEffect::ParseValue(Property& property, const String& font // Partition the list such that the back layer effects appear before the front layer effects std::stable_partition(font_effects.list.begin(), font_effects.list.end(), - [](const SharedPtr& effect) { return effect->GetLayer() == FontEffect::Layer::Back; } - ); + [](const SharedPtr& effect) { return effect->GetLayer() == FontEffect::Layer::Back; }); property.value = Variant(MakeShared(std::move(font_effects))); property.unit = Property::FONTEFFECT; diff --git a/Source/Core/PropertyParserFontEffect.h b/Source/Core/PropertyParserFontEffect.h index 11f16679f..8dfbb73c2 100644 --- a/Source/Core/PropertyParserFontEffect.h +++ b/Source/Core/PropertyParserFontEffect.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,11 +34,10 @@ namespace Rml { /** - A property parser for the font-effect property. + A property parser for the font-effect property. */ -class PropertyParserFontEffect : public PropertyParser -{ +class PropertyParserFontEffect : public PropertyParser { public: PropertyParserFontEffect(); virtual ~PropertyParserFontEffect(); diff --git a/Source/Core/PropertyParserKeyword.cpp b/Source/Core/PropertyParserKeyword.cpp index adac8bc4a..baa21f5cb 100644 --- a/Source/Core/PropertyParserKeyword.cpp +++ b/Source/Core/PropertyParserKeyword.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,15 +30,10 @@ namespace Rml { -PropertyParserKeyword::PropertyParserKeyword() -{ -} +PropertyParserKeyword::PropertyParserKeyword() {} -PropertyParserKeyword::~PropertyParserKeyword() -{ -} +PropertyParserKeyword::~PropertyParserKeyword() {} -// Called to parse a RCSS keyword declaration. bool PropertyParserKeyword::ParseValue(Property& property, const String& value, const ParameterMap& parameters) const { ParameterMap::const_iterator iterator = parameters.find(StringUtilities::ToLower(value)); diff --git a/Source/Core/PropertyParserKeyword.h b/Source/Core/PropertyParserKeyword.h index 77578ab4c..85f3b7f13 100644 --- a/Source/Core/PropertyParserKeyword.h +++ b/Source/Core/PropertyParserKeyword.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A property parser that validates a value is part of a specified list of keywords. + A property parser that validates a value is part of a specified list of keywords. - @author Peter Curry + @author Peter Curry */ -class PropertyParserKeyword : public PropertyParser -{ +class PropertyParserKeyword : public PropertyParser { public: PropertyParserKeyword(); virtual ~PropertyParserKeyword(); diff --git a/Source/Core/PropertyParserNumber.cpp b/Source/Core/PropertyParserNumber.cpp index 2a106c3c4..22bb716bc 100644 --- a/Source/Core/PropertyParserNumber.cpp +++ b/Source/Core/PropertyParserNumber.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,8 +31,7 @@ namespace Rml { -static const UnorderedMap g_property_unit_string_map = -{ +static const UnorderedMap g_property_unit_string_map = { {"", Property::NUMBER}, {"%", Property::PERCENT}, {"px", Property::PX}, @@ -51,18 +50,12 @@ static const UnorderedMap g_property_unit_string_map = {"rad", Property::RAD}, }; -PropertyParserNumber::PropertyParserNumber(int units, Property::Unit zero_unit) - : units(units), zero_unit(zero_unit) -{} +PropertyParserNumber::PropertyParserNumber(int units, Property::Unit zero_unit) : units(units), zero_unit(zero_unit) {} -PropertyParserNumber::~PropertyParserNumber() -{} +PropertyParserNumber::~PropertyParserNumber() {} -// Called to parse a RCSS number declaration. -bool PropertyParserNumber::ParseValue(Property& property, const String& value, const ParameterMap& RMLUI_UNUSED_PARAMETER(parameters)) const +bool PropertyParserNumber::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const { - RMLUI_UNUSED(parameters); - // Find the beginning of the unit string in 'value'. size_t unit_pos = 0; for (size_t i = value.size(); i--;) diff --git a/Source/Core/PropertyParserNumber.h b/Source/Core/PropertyParserNumber.h index 98f6d02b6..26b4bf3bd 100644 --- a/Source/Core/PropertyParserNumber.h +++ b/Source/Core/PropertyParserNumber.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A property parser that parses a floating-point number with an optional unit. + A property parser that parses a floating-point number with an optional unit. - @author Peter Curry + @author Peter Curry */ -class PropertyParserNumber : public PropertyParser -{ +class PropertyParserNumber : public PropertyParser { public: PropertyParserNumber(int units, Property::Unit zero_unit = Property::UNKNOWN); virtual ~PropertyParserNumber(); diff --git a/Source/Core/PropertyParserRatio.cpp b/Source/Core/PropertyParserRatio.cpp index d8484ea66..dfcc83507 100644 --- a/Source/Core/PropertyParserRatio.cpp +++ b/Source/Core/PropertyParserRatio.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,23 +30,16 @@ namespace Rml { -PropertyParserRatio::PropertyParserRatio() -{ -} +PropertyParserRatio::PropertyParserRatio() {} -PropertyParserRatio::~PropertyParserRatio() -{ -} +PropertyParserRatio::~PropertyParserRatio() {} -// Called to parse a RCSS string declaration. -bool PropertyParserRatio::ParseValue(Property& property, const String& value, const ParameterMap& RMLUI_UNUSED_PARAMETER(parameters)) const +bool PropertyParserRatio::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const { - RMLUI_UNUSED(parameters); - StringList parts; StringUtilities::ExpandString(parts, value, '/'); - if(parts.size() != 2) + if (parts.size() != 2) { return false; } @@ -57,7 +50,7 @@ bool PropertyParserRatio::ParseValue(Property& property, const String& value, co // Number conversion failed return false; } - + float second_value = 0; if (!TypeConverter::Convert(parts[1], second_value)) { diff --git a/Source/Core/PropertyParserRatio.h b/Source/Core/PropertyParserRatio.h index 3658ef32f..a1791e588 100644 --- a/Source/Core/PropertyParserRatio.h +++ b/Source/Core/PropertyParserRatio.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A property parser that parses an ratio in the format of x/y, like 16/9. + A property parser that parses an ratio in the format of x/y, like 16/9. - @author Maximilian Stark + @author Maximilian Stark */ -class PropertyParserRatio : public PropertyParser -{ +class PropertyParserRatio : public PropertyParser { public: PropertyParserRatio(); virtual ~PropertyParserRatio(); diff --git a/Source/Core/PropertyParserString.cpp b/Source/Core/PropertyParserString.cpp index 4cc3223d9..0cc4ac9c0 100644 --- a/Source/Core/PropertyParserString.cpp +++ b/Source/Core/PropertyParserString.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,19 +30,12 @@ namespace Rml { -PropertyParserString::PropertyParserString() -{ -} +PropertyParserString::PropertyParserString() {} -PropertyParserString::~PropertyParserString() -{ -} +PropertyParserString::~PropertyParserString() {} -// Called to parse a RCSS string declaration. -bool PropertyParserString::ParseValue(Property& property, const String& value, const ParameterMap& RMLUI_UNUSED_PARAMETER(parameters)) const +bool PropertyParserString::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const { - RMLUI_UNUSED(parameters); - property.value = Variant(value); property.unit = Property::STRING; diff --git a/Source/Core/PropertyParserString.h b/Source/Core/PropertyParserString.h index 15c4bb987..d01ffc560 100644 --- a/Source/Core/PropertyParserString.h +++ b/Source/Core/PropertyParserString.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A passthrough property parser that parses a string. + A passthrough property parser that parses a string. - @author Peter Curry + @author Peter Curry */ -class PropertyParserString : public PropertyParser -{ +class PropertyParserString : public PropertyParser { public: PropertyParserString(); virtual ~PropertyParserString(); diff --git a/Source/Core/PropertyParserTransform.cpp b/Source/Core/PropertyParserTransform.cpp index 426991ec6..a02df069d 100644 --- a/Source/Core/PropertyParserTransform.cpp +++ b/Source/Core/PropertyParserTransform.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,27 +27,21 @@ */ #include "PropertyParserTransform.h" -#include "../../Include/RmlUi/Core/TransformPrimitive.h" #include "../../Include/RmlUi/Core/Transform.h" +#include "../../Include/RmlUi/Core/TransformPrimitive.h" #include namespace Rml { -PropertyParserTransform::PropertyParserTransform() - : number(Property::NUMBER), - length(Property::LENGTH_PERCENT, Property::PX), - angle(Property::ANGLE, Property::RAD) -{ -} +PropertyParserTransform::PropertyParserTransform() : + number(Property::NUMBER), length(Property::LENGTH_PERCENT, Property::PX), angle(Property::ANGLE, Property::RAD) +{} -PropertyParserTransform::~PropertyParserTransform() -{ -} +PropertyParserTransform::~PropertyParserTransform() {} -// Called to parse a RCSS transform declaration. bool PropertyParserTransform::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const { - if(value == "none") + if (value == "none") { property.value = Variant(TransformPtr()); property.unit = Property::TRANSFORM; @@ -60,17 +54,18 @@ bool PropertyParserTransform::ParseValue(Property& property, const String& value Transforms::NumericValue args[16]; - const PropertyParser* angle1[] = { &angle }; - const PropertyParser* angle2[] = { &angle, &angle }; - const PropertyParser* length1[] = { &length }; - const PropertyParser* length2[] = { &length, &length }; - const PropertyParser* length3[] = { &length, &length, &length }; - const PropertyParser* number3angle1[] = { &number, &number, &number, &angle }; - const PropertyParser* number1[] = { &number }; - const PropertyParser* number2[] = { &number, &number }; - const PropertyParser* number3[] = { &number, &number, &number }; - const PropertyParser* number6[] = { &number, &number, &number, &number, &number, &number }; - const PropertyParser* number16[] = { &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number }; + const PropertyParser* angle1[] = {&angle}; + const PropertyParser* angle2[] = {&angle, &angle}; + const PropertyParser* length1[] = {&length}; + const PropertyParser* length2[] = {&length, &length}; + const PropertyParser* length3[] = {&length, &length, &length}; + const PropertyParser* number3angle1[] = {&number, &number, &number, &angle}; + const PropertyParser* number1[] = {&number}; + const PropertyParser* number2[] = {&number, &number}; + const PropertyParser* number3[] = {&number, &number, &number}; + const PropertyParser* number6[] = {&number, &number, &number, &number, &number, &number}; + const PropertyParser* number16[] = {&number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, &number, + &number, &number, &number, &number}; while (*next) { @@ -79,92 +74,92 @@ bool PropertyParserTransform::ParseValue(Property& property, const String& value if (Scan(bytes_read, next, "perspective", length1, args, 1)) { - transform->AddPrimitive({ Perspective(args) }); + transform->AddPrimitive({Perspective(args)}); } else if (Scan(bytes_read, next, "matrix", number6, args, 6)) { - transform->AddPrimitive({ Matrix2D(args) }); + transform->AddPrimitive({Matrix2D(args)}); } else if (Scan(bytes_read, next, "matrix3d", number16, args, 16)) { - transform->AddPrimitive({ Matrix3D(args) }); + transform->AddPrimitive({Matrix3D(args)}); } else if (Scan(bytes_read, next, "translateX", length1, args, 1)) { - transform->AddPrimitive({ TranslateX(args) }); + transform->AddPrimitive({TranslateX(args)}); } else if (Scan(bytes_read, next, "translateY", length1, args, 1)) { - transform->AddPrimitive({ TranslateY(args) }); + transform->AddPrimitive({TranslateY(args)}); } else if (Scan(bytes_read, next, "translateZ", length1, args, 1)) { - transform->AddPrimitive({ TranslateZ(args) }); + transform->AddPrimitive({TranslateZ(args)}); } else if (Scan(bytes_read, next, "translate", length2, args, 2)) { - transform->AddPrimitive({ Translate2D(args) }); + transform->AddPrimitive({Translate2D(args)}); } else if (Scan(bytes_read, next, "translate3d", length3, args, 3)) { - transform->AddPrimitive({ Translate3D(args) }); + transform->AddPrimitive({Translate3D(args)}); } else if (Scan(bytes_read, next, "scaleX", number1, args, 1)) { - transform->AddPrimitive({ ScaleX(args) }); + transform->AddPrimitive({ScaleX(args)}); } else if (Scan(bytes_read, next, "scaleY", number1, args, 1)) { - transform->AddPrimitive({ ScaleY(args) }); + transform->AddPrimitive({ScaleY(args)}); } else if (Scan(bytes_read, next, "scaleZ", number1, args, 1)) { - transform->AddPrimitive({ ScaleZ(args) }); + transform->AddPrimitive({ScaleZ(args)}); } else if (Scan(bytes_read, next, "scale", number2, args, 2)) { - transform->AddPrimitive({ Scale2D(args) }); + transform->AddPrimitive({Scale2D(args)}); } else if (Scan(bytes_read, next, "scale", number1, args, 1)) { args[1] = args[0]; - transform->AddPrimitive({ Scale2D(args) }); + transform->AddPrimitive({Scale2D(args)}); } else if (Scan(bytes_read, next, "scale3d", number3, args, 3)) { - transform->AddPrimitive({ Scale3D(args) }); + transform->AddPrimitive({Scale3D(args)}); } else if (Scan(bytes_read, next, "rotateX", angle1, args, 1)) { - transform->AddPrimitive({ RotateX(args) }); + transform->AddPrimitive({RotateX(args)}); } else if (Scan(bytes_read, next, "rotateY", angle1, args, 1)) { - transform->AddPrimitive({ RotateY(args) }); + transform->AddPrimitive({RotateY(args)}); } else if (Scan(bytes_read, next, "rotateZ", angle1, args, 1)) { - transform->AddPrimitive({ RotateZ(args) }); + transform->AddPrimitive({RotateZ(args)}); } else if (Scan(bytes_read, next, "rotate", angle1, args, 1)) { - transform->AddPrimitive({ Rotate2D(args) }); + transform->AddPrimitive({Rotate2D(args)}); } else if (Scan(bytes_read, next, "rotate3d", number3angle1, args, 4)) { - transform->AddPrimitive({ Rotate3D(args) }); + transform->AddPrimitive({Rotate3D(args)}); } else if (Scan(bytes_read, next, "skewX", angle1, args, 1)) { - transform->AddPrimitive({ SkewX(args) }); + transform->AddPrimitive({SkewX(args)}); } else if (Scan(bytes_read, next, "skewY", angle1, args, 1)) { - transform->AddPrimitive({ SkewY(args) }); + transform->AddPrimitive({SkewY(args)}); } else if (Scan(bytes_read, next, "skew", angle2, args, 2)) { - transform->AddPrimitive({ Skew2D(args) }); + transform->AddPrimitive({Skew2D(args)}); } if (bytes_read > 0) @@ -176,15 +171,15 @@ bool PropertyParserTransform::ParseValue(Property& property, const String& value return false; } } - + property.value = Variant(std::move(transform)); property.unit = Property::TRANSFORM; return true; } -// Scan a string for a parameterized keyword with a certain number of numeric arguments. -bool PropertyParserTransform::Scan(int& out_bytes_read, const char* str, const char* keyword, const PropertyParser** parsers, Transforms::NumericValue* args, int nargs) const +bool PropertyParserTransform::Scan(int& out_bytes_read, const char* str, const char* keyword, const PropertyParser** parsers, + Transforms::NumericValue* args, int nargs) const { out_bytes_read = 0; int total_bytes_read = 0, bytes_read = 0; @@ -245,8 +240,7 @@ bool PropertyParserTransform::Scan(int& out_bytes_read, const char* str, const c Property prop; bytes_read = 0; - if (sscanf(str, " %[^,)] %n", arg, &bytes_read), bytes_read - && parsers[i]->ParseValue(prop, String(arg), ParameterMap())) + if (sscanf(str, " %[^,)] %n", arg, &bytes_read), bytes_read && parsers[i]->ParseValue(prop, String(arg), ParameterMap())) { args[i].number = prop.value.Get(); args[i].unit = prop.unit; diff --git a/Source/Core/PropertyParserTransform.h b/Source/Core/PropertyParserTransform.h index eb29a22ff..39cb2ff7a 100644 --- a/Source/Core/PropertyParserTransform.h +++ b/Source/Core/PropertyParserTransform.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,16 +34,16 @@ namespace Rml { -namespace Transforms { struct NumericValue; } - +namespace Transforms { + struct NumericValue; +} /** - A property parser that parses a RCSS transform property specification. + A property parser that parses a RCSS transform property specification. - @author Markus Schöngart + @author Markus Schöngart */ -class PropertyParserTransform : public PropertyParser -{ +class PropertyParserTransform : public PropertyParser { public: PropertyParserTransform(); virtual ~PropertyParserTransform(); @@ -64,7 +64,8 @@ class PropertyParserTransform : public PropertyParser /// @param[out] args The numeric arguments encountered /// @param[in] nargs The number of numeric arguments expected /// @return True if parsed successfully, false otherwise. - bool Scan(int& out_bytes_read, const char* str, const char* keyword, const PropertyParser** parsers, Transforms::NumericValue* args, int nargs) const; + bool Scan(int& out_bytes_read, const char* str, const char* keyword, const PropertyParser** parsers, Transforms::NumericValue* args, + int nargs) const; PropertyParserNumber number, length, angle; }; diff --git a/Source/Core/PropertyShorthandDefinition.h b/Source/Core/PropertyShorthandDefinition.h index 4e67a29bb..f830644cb 100644 --- a/Source/Core/PropertyShorthandDefinition.h +++ b/Source/Core/PropertyShorthandDefinition.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -42,8 +42,12 @@ enum class ShorthandItemType { Invalid, Property, Shorthand }; // Each entry in a shorthand points either to another shorthand or a property struct ShorthandItem { ShorthandItem() : type(ShorthandItemType::Invalid), property_id(PropertyId::Invalid), property_definition(nullptr), optional(false) {} - ShorthandItem(PropertyId id, const PropertyDefinition* definition, bool optional) : type(ShorthandItemType::Property), property_id(id), property_definition(definition), optional(optional) {} - ShorthandItem(ShorthandId id, const ShorthandDefinition* definition, bool optional) : type(ShorthandItemType::Shorthand), shorthand_id(id), shorthand_definition(definition), optional(optional) {} + ShorthandItem(PropertyId id, const PropertyDefinition* definition, bool optional) : + type(ShorthandItemType::Property), property_id(id), property_definition(definition), optional(optional) + {} + ShorthandItem(ShorthandId id, const ShorthandDefinition* definition, bool optional) : + type(ShorthandItemType::Shorthand), shorthand_id(id), shorthand_definition(definition), optional(optional) + {} ShorthandItemType type; union { @@ -58,12 +62,11 @@ struct ShorthandItem { }; // A list of shorthands or properties -using ShorthandItemList = Vector< ShorthandItem >; +using ShorthandItemList = Vector; -struct ShorthandDefinition -{ +struct ShorthandDefinition { ShorthandId id; - ShorthandItemList items; + ShorthandItemList items; ShorthandType type; }; diff --git a/Source/Core/PropertySpecification.cpp b/Source/Core/PropertySpecification.cpp index 5545b0fe7..8ed590c2f 100644 --- a/Source/Core/PropertySpecification.cpp +++ b/Source/Core/PropertySpecification.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,15 +44,12 @@ PropertySpecification::PropertySpecification(size_t reserve_num_properties, size // Increment reserve numbers by one because the 'invalid' property occupies the first element properties(reserve_num_properties + 1), shorthands(reserve_num_shorthands + 1), property_map(MakeUnique(reserve_num_properties + 1)), shorthand_map(MakeUnique(reserve_num_shorthands + 1)) -{ -} +{} -PropertySpecification::~PropertySpecification() -{ -} +PropertySpecification::~PropertySpecification() {} -// Registers a property with a new definition. -PropertyDefinition& PropertySpecification::RegisterProperty(const String& property_name, const String& default_value, bool inherited, bool forces_layout, PropertyId id) +PropertyDefinition& PropertySpecification::RegisterProperty(const String& property_name, const String& default_value, bool inherited, + bool forces_layout, PropertyId id) { if (id == PropertyId::Invalid) id = property_map->GetOrCreateId(property_name); @@ -63,7 +60,9 @@ PropertyDefinition& PropertySpecification::RegisterProperty(const String& proper if (index >= size_t(PropertyId::MaxNumIds)) { - Log::Message(Log::LT_ERROR, "Fatal error while registering property '%s': Maximum number of allowed properties exceeded. Continuing execution may lead to crash.", property_name.c_str()); + Log::Message(Log::LT_ERROR, + "Fatal error while registering property '%s': Maximum number of allowed properties exceeded. Continuing execution may lead to crash.", + property_name.c_str()); RMLUI_ERROR; return *properties[0]; } @@ -80,7 +79,7 @@ PropertyDefinition& PropertySpecification::RegisterProperty(const String& proper else { // Resize vector to hold the new index - properties.resize((index*3)/2 + 1); + properties.resize((index * 3) / 2 + 1); } // Create and insert the new property @@ -94,7 +93,6 @@ PropertyDefinition& PropertySpecification::RegisterProperty(const String& proper return *properties[index]; } -// Returns a property definition. const PropertyDefinition* PropertySpecification::GetProperty(PropertyId id) const { if (id == PropertyId::Invalid || (size_t)id >= properties.size()) @@ -108,13 +106,11 @@ const PropertyDefinition* PropertySpecification::GetProperty(const String& prope return GetProperty(property_map->GetId(property_name)); } -// Fetches a list of the names of all registered property definitions. const PropertyIdSet& PropertySpecification::GetRegisteredProperties() const { return property_ids; } -// Fetches a list of the names of all registered property definitions. const PropertyIdSet& PropertySpecification::GetRegisteredInheritedProperties() const { return property_ids_inherited; @@ -125,7 +121,6 @@ const PropertyIdSet& PropertySpecification::GetRegisteredPropertiesForcingLayout return property_ids_forcing_layout; } -// Registers a shorthand property definition. ShorthandId PropertySpecification::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type, ShorthandId id) { if (id == ShorthandId::Invalid) @@ -166,7 +161,7 @@ ShorthandId PropertySpecification::RegisterShorthand(const String& shorthand_nam // Test for valid shorthand id. The recursive types (and only those) can hold other shorthands. if (shorthand_id != ShorthandId::Invalid && (type == ShorthandType::RecursiveRepeat || type == ShorthandType::RecursiveCommaSeparated)) { - if (const ShorthandDefinition * shorthand = GetShorthand(shorthand_id)) + if (const ShorthandDefinition* shorthand = GetShorthand(shorthand_id)) item = ShorthandItem(shorthand_id, shorthand, optional); } } @@ -209,7 +204,6 @@ ShorthandId PropertySpecification::RegisterShorthand(const String& shorthand_nam return id; } -// Returns a shorthand definition. const ShorthandDefinition* PropertySpecification::GetShorthand(ShorthandId id) const { if (id == ShorthandId::Invalid || (size_t)id >= shorthands.size()) @@ -254,12 +248,11 @@ bool PropertySpecification::ParsePropertyDeclaration(PropertyDictionary& diction Property new_property; if (!property_definition->ParseValue(new_property, property_values[0])) return false; - + dictionary.SetProperty(property_id, new_property); return true; } -// Parses a property declaration, setting any parsed and validated properties on the given dictionary. bool PropertySpecification::ParseShorthandDeclaration(PropertyDictionary& dictionary, ShorthandId shorthand_id, const String& property_value) const { StringList property_values; @@ -299,30 +292,27 @@ bool PropertySpecification::ParseShorthandDeclaration(PropertyDictionary& dictio // If this definition is a 'box'-style shorthand (x-top, x-right, x-bottom, x-left, etc) and there are fewer // than four values - if (shorthand_definition->type == ShorthandType::Box && - property_values.size() < 4) + if (shorthand_definition->type == ShorthandType::Box && property_values.size() < 4) { // This array tells which property index each side is parsed from - Array box_side_to_value_index = { 0,0,0,0 }; + Array box_side_to_value_index = {0, 0, 0, 0}; switch (property_values.size()) { case 1: // Only one value is defined, so it is parsed onto all four sides. - box_side_to_value_index = { 0,0,0,0 }; + box_side_to_value_index = {0, 0, 0, 0}; break; case 2: // Two values are defined, so the first one is parsed onto the top and bottom value, the second onto // the left and right. - box_side_to_value_index = { 0,1,0,1 }; + box_side_to_value_index = {0, 1, 0, 1}; break; case 3: // Three values are defined, so the first is parsed into the top value, the second onto the left and // right, and the third onto the bottom. - box_side_to_value_index = { 0,1,2,1 }; - break; - default: - RMLUI_ERROR; + box_side_to_value_index = {0, 1, 2, 1}; break; + default: RMLUI_ERROR; break; } for (int i = 0; i < 4; i++) @@ -414,8 +404,7 @@ bool PropertySpecification::ParseShorthandDeclaration(PropertyDictionary& dictio dictionary.SetProperty(shorthand_definition->items[property_index].property_id, new_property); // Increment the value index, unless we're replicating the last value and we're up to the last value. - if (shorthand_definition->type != ShorthandType::Replicate || - value_index < property_values.size() - 1) + if (shorthand_definition->type != ShorthandType::Replicate || value_index < property_values.size() - 1) value_index++; } } @@ -423,7 +412,6 @@ bool PropertySpecification::ParseShorthandDeclaration(PropertyDictionary& dictio return true; } -// Sets all undefined properties in the dictionary to their defaults. void PropertySpecification::SetPropertyDefaults(PropertyDictionary& dictionary) const { for (const auto& property : properties) @@ -460,7 +448,6 @@ String PropertySpecification::PropertiesToString(const PropertyDictionary& dicti return result; } - bool PropertySpecification::ParsePropertyValues(StringList& values_list, const String& values, bool split_values) const { String value; @@ -482,9 +469,20 @@ bool PropertySpecification::ParsePropertyValues(StringList& values_list, const S switch (state) { - case VALUE: + case VALUE: + { + if (character == ';') { - if (character == ';') + value = StringUtilities::StripWhitespace(value); + if (value.size() > 0) + { + values_list.push_back(value); + value.clear(); + } + } + else if (StringUtilities::IsWhitespace(character)) + { + if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.size() > 0) @@ -493,133 +491,122 @@ bool PropertySpecification::ParsePropertyValues(StringList& values_list, const S value.clear(); } } - else if (StringUtilities::IsWhitespace(character)) + else + value += character; + } + else if (character == '"') + { + if (split_values) { - if (split_values) + value = StringUtilities::StripWhitespace(value); + if (value.size() > 0) { - value = StringUtilities::StripWhitespace(value); - if (value.size() > 0) - { - values_list.push_back(value); - value.clear(); - } + values_list.push_back(value); + value.clear(); } - else - value += character; + state = VALUE_QUOTE; } - else if (character == '"') + else { - if (split_values) - { - value = StringUtilities::StripWhitespace(value); - if (value.size() > 0) - { - values_list.push_back(value); - value.clear(); - } - state = VALUE_QUOTE; - } - else - { - value += ' '; - state = VALUE_QUOTE; - } + value += ' '; + state = VALUE_QUOTE; } - else if (character == '(') + } + else if (character == '(') + { + open_parentheses = 1; + value += character; + state = VALUE_PARENTHESIS; + } + else + { + value += character; + } + } + break; + + case VALUE_PARENTHESIS: + { + if (escape_character) + { + if (character == ')' || character == '(' || character == '\\') { - open_parentheses = 1; value += character; - state = VALUE_PARENTHESIS; } else { + value += '\\'; value += character; } } - break; - - case VALUE_PARENTHESIS: + else { - if (escape_character) + if (character == '(') { - if (character == ')' || character == '(' || character == '\\') - { - value += character; - } - else - { - value += '\\'; - value += character; - } + open_parentheses++; + value += character; + } + else if (character == ')') + { + open_parentheses--; + value += character; + if (open_parentheses == 0) + state = VALUE; + } + else if (character == '\\') + { + escape_next = true; } else { - if (character == '(') - { - open_parentheses++; - value += character; - } - else if (character == ')') - { - open_parentheses--; - value += character; - if (open_parentheses == 0) - state = VALUE; - } - else if (character == '\\') - { - escape_next = true; - } - else - { - value += character; - } + value += character; } } - break; + } + break; - case VALUE_QUOTE: + case VALUE_QUOTE: + { + if (escape_character) { - if (escape_character) + if (character == '"' || character == '\\') { - if (character == '"' || character == '\\') - { - value += character; - } - else - { - value += '\\'; - value += character; - } + value += character; } else { - if (character == '"') + value += '\\'; + value += character; + } + } + else + { + if (character == '"') + { + if (split_values) { - if (split_values) + value = StringUtilities::StripWhitespace(value); + if (value.size() > 0) { - value = StringUtilities::StripWhitespace(value); - if (value.size() > 0) - { - values_list.push_back(value); - value.clear(); - } + values_list.push_back(value); + value.clear(); } - else - value += ' '; - state = VALUE; - } - else if (character == '\\') - { - escape_next = true; } else - { - value += character; - } + value += ' '; + state = VALUE; + } + else if (character == '\\') + { + escape_next = true; + } + else + { + value += character; } } } + } } if (state == VALUE) diff --git a/Source/Core/RenderInterface.cpp b/Source/Core/RenderInterface.cpp index 78c363c3e..319fb98f4 100644 --- a/Source/Core/RenderInterface.cpp +++ b/Source/Core/RenderInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -46,45 +46,30 @@ RenderInterface::~RenderInterface() "destroyed and a subsequent call has been made to Rml::ReleaseTextures before the render interface is destroyed."); } -// Called by RmlUi when it wants to compile geometry it believes will be static for the forseeable future. -CompiledGeometryHandle RenderInterface::CompileGeometry(Vertex* /*vertices*/, int /*num_vertices*/, int* /*indices*/, int /*num_indices*/, TextureHandle /*texture*/) +CompiledGeometryHandle RenderInterface::CompileGeometry(Vertex* /*vertices*/, int /*num_vertices*/, int* /*indices*/, int /*num_indices*/, + TextureHandle /*texture*/) { return 0; } -// Called by RmlUi when it wants to render application-compiled geometry. -void RenderInterface::RenderCompiledGeometry(CompiledGeometryHandle /*geometry*/, const Vector2f& /*translation*/) -{ -} +void RenderInterface::RenderCompiledGeometry(CompiledGeometryHandle /*geometry*/, const Vector2f& /*translation*/) {} -// Called by RmlUi when it wants to release application-compiled geometry. -void RenderInterface::ReleaseCompiledGeometry(CompiledGeometryHandle /*geometry*/) -{ -} +void RenderInterface::ReleaseCompiledGeometry(CompiledGeometryHandle /*geometry*/) {} -// Called by RmlUi when a texture is required by the library. bool RenderInterface::LoadTexture(TextureHandle& /*texture_handle*/, Vector2i& /*texture_dimensions*/, const String& /*source*/) { return false; } -// Called by RmlUi when a texture is required to be built from an internally-generated sequence of pixels. bool RenderInterface::GenerateTexture(TextureHandle& /*texture_handle*/, const byte* /*source*/, const Vector2i& /*source_dimensions*/) { return false; } -// Called by RmlUi when a loaded texture is no longer required. -void RenderInterface::ReleaseTexture(TextureHandle /*texture*/) -{ -} +void RenderInterface::ReleaseTexture(TextureHandle /*texture*/) {} -// Called by RmlUi when it wants to change the current transform matrix to a new matrix. -void RenderInterface::SetTransform(const Matrix4f* /*transform*/) -{ -} +void RenderInterface::SetTransform(const Matrix4f* /*transform*/) {} -// Get the context currently being rendered. Context* RenderInterface::GetContext() const { return context; diff --git a/Source/Core/ScrollController.cpp b/Source/Core/ScrollController.cpp index 4bf12dc32..f99fe1adf 100644 --- a/Source/Core/ScrollController.cpp +++ b/Source/Core/ScrollController.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -34,7 +34,7 @@ namespace Rml { static constexpr float AUTOSCROLL_SPEED_FACTOR = 0.09f; -static constexpr float AUTOSCROLL_DEADZONE = 10.0f; // [dp] +static constexpr float AUTOSCROLL_DEADZONE = 10.0f; // [dp] static constexpr float SMOOTHSCROLL_WINDOW_SIZE = 50.f; // The window where smoothing is applied, as a distance from scroll start and end. [dp] static constexpr float SMOOTHSCROLL_MAX_VELOCITY = 10'000.f; // [dp/s] @@ -128,7 +128,7 @@ bool ScrollController::Update(Vector2i mouse_position, float dp_ratio) UpdateAutoscroll(mouse_position, dp_ratio); else if (mode == Mode::Smoothscroll) UpdateSmoothscroll(dp_ratio); - + return mode != Mode::None; } diff --git a/Source/Core/ScrollController.h b/Source/Core/ScrollController.h index 67dd9548f..3e61bd2dd 100644 --- a/Source/Core/ScrollController.h +++ b/Source/Core/ScrollController.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Spritesheet.cpp b/Source/Core/Spritesheet.cpp index 5501cdf45..09a133371 100644 --- a/Source/Core/Spritesheet.cpp +++ b/Source/Core/Spritesheet.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2019 Michael R. P. Ragazzon - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,19 +27,20 @@ */ #include "../../Include/RmlUi/Core/Spritesheet.h" -#include "../../Include/RmlUi/Core/StringUtilities.h" #include "../../Include/RmlUi/Core/Log.h" +#include "../../Include/RmlUi/Core/StringUtilities.h" namespace Rml { - -Spritesheet::Spritesheet(const String& name, const String& image_source, const String& definition_source, - int definition_line_number, float display_scale, const Texture& texture) - : name(name), image_source(image_source), definition_source(definition_source), - definition_line_number(definition_line_number), display_scale(display_scale), texture(texture) +Spritesheet::Spritesheet(const String& name, const String& image_source, const String& definition_source, int definition_line_number, + float display_scale, const Texture& texture) : + name(name), + image_source(image_source), definition_source(definition_source), definition_line_number(definition_line_number), display_scale(display_scale), + texture(texture) {} -bool SpritesheetList::AddSpriteSheet(const String& name, const String& image_source, const String& definition_source, int definition_line_number, float display_scale, const SpriteDefinitionList& sprite_definitions) +bool SpritesheetList::AddSpriteSheet(const String& name, const String& image_source, const String& definition_source, int definition_line_number, + float display_scale, const SpriteDefinitionList& sprite_definitions) { // Load the texture Texture texture; @@ -61,17 +62,16 @@ bool SpritesheetList::AddSpriteSheet(const String& name, const String& image_sou if (new_sprite.sprite_sheet) { Log::Message(Log::LT_WARNING, "Sprite '%s' was overwritten due to duplicate names at the same block scope. Declared at %s:%d and %s:%d", - sprite_name.c_str(), new_sprite.sprite_sheet->definition_source.c_str(), new_sprite.sprite_sheet->definition_line_number, definition_source.c_str(), definition_line_number); + sprite_name.c_str(), new_sprite.sprite_sheet->definition_source.c_str(), new_sprite.sprite_sheet->definition_line_number, + definition_source.c_str(), definition_line_number); } - new_sprite = Sprite{ sprite_rectangle, sprite_sheet }; + new_sprite = Sprite{sprite_rectangle, sprite_sheet}; } return true; } - - const Sprite* SpritesheetList::GetSprite(const String& name) const { auto it = sprite_map.find(name); @@ -80,7 +80,6 @@ const Sprite* SpritesheetList::GetSprite(const String& name) const return nullptr; } - void SpritesheetList::Merge(const SpritesheetList& other) { spritesheets.insert(spritesheets.end(), other.spritesheets.begin(), other.spritesheets.end()); @@ -96,19 +95,19 @@ void SpritesheetList::Merge(const SpritesheetList& other) } } -void SpritesheetList::Reserve(size_t size_sprite_sheets, size_t size_sprites) -{ +void SpritesheetList::Reserve(size_t size_sprite_sheets, size_t size_sprites) +{ spritesheets.reserve(size_sprite_sheets); sprite_map.reserve(size_sprites); } -size_t SpritesheetList::NumSpriteSheets() const +size_t SpritesheetList::NumSpriteSheets() const { return spritesheets.size(); } -size_t SpritesheetList::NumSprites() const -{ +size_t SpritesheetList::NumSprites() const +{ return sprite_map.size(); } diff --git a/Source/Core/Stream.cpp b/Source/Core/Stream.cpp index 7a1b28e2f..eb060ac8e 100644 --- a/Source/Core/Stream.cpp +++ b/Source/Core/Stream.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -49,13 +49,11 @@ void Stream::Close() stream_mode = 0; } -// Returns the mode the stream was opened in. int Stream::GetStreamMode() const { return stream_mode; } -// Returns the source url (if available) const URL& Stream::GetSourceURL() const { return url; @@ -69,15 +67,14 @@ bool Stream::IsEOS() const size_t Stream::Peek(void* buffer, size_t bytes) const { size_t pos = Tell(); - size_t read = Read( buffer, bytes ); - Seek( (long)pos, SEEK_SET ); + size_t read = Read(buffer, bytes); + Seek((long)pos, SEEK_SET); return read; } -// Read from one stream into another size_t Stream::Read(Stream* stream, size_t bytes) const { - byte buffer[ READ_BLOCK_SIZE ]; + byte buffer[READ_BLOCK_SIZE]; size_t total_bytes_read = 0; while (total_bytes_read < bytes) { @@ -90,7 +87,6 @@ size_t Stream::Read(Stream* stream, size_t bytes) const return total_bytes_read; } -// Read from one stream into another size_t Stream::Read(String& string, size_t bytes) const { size_t string_size = string.size(); @@ -101,7 +97,6 @@ size_t Stream::Read(String& string, size_t bytes) const return read; } -/// Write to this stream from another stream size_t Stream::Write(const Stream* stream, size_t bytes) { return stream->Read(this, bytes); @@ -117,19 +112,14 @@ size_t Stream::Write(const String& string) return Write(string.c_str(), string.size()); } -// Push onto the front of the stream -size_t Stream::PushFront(const void* RMLUI_UNUSED_PARAMETER(buffer), size_t RMLUI_UNUSED_PARAMETER(bytes)) +size_t Stream::PushFront(const void* /*buffer*/, size_t /*bytes*/) { - RMLUI_UNUSED(buffer); - RMLUI_UNUSED(bytes); - RMLUI_ERRORMSG("No generic way to PushFront to a stream."); return false; } -// Push onto the back of the stream size_t Stream::PushBack(const void* buffer, size_t bytes) -{ +{ size_t pos = Tell(); Seek(0, SEEK_END); size_t wrote = Write(buffer, bytes); @@ -137,22 +127,17 @@ size_t Stream::PushBack(const void* buffer, size_t bytes) return wrote; } -// Push onto the front of the stream -size_t Stream::PopFront(size_t RMLUI_UNUSED_PARAMETER(bytes)) +size_t Stream::PopFront(size_t /*bytes*/) { - RMLUI_UNUSED(bytes); - RMLUI_ERRORMSG("No generic way to PopFront from a stream."); return 0; } -// Push onto the back of the stream size_t Stream::PopBack(size_t bytes) { return Truncate(Length() - bytes); } -// Sets the mode on the stream; should be called by a stream when it is opened. void Stream::SetStreamDetails(const URL& _url, int _stream_mode) { url = _url; diff --git a/Source/Core/StreamFile.cpp b/Source/Core/StreamFile.cpp index 437478457..b1d13b483 100644 --- a/Source/Core/StreamFile.cpp +++ b/Source/Core/StreamFile.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -45,7 +45,6 @@ StreamFile::~StreamFile() StreamFile::Close(); } -/// Attempts to open the stream pointing at a given URL. bool StreamFile::Open(const String& path) { String url_safe_path = StringUtilities::Replace(path, ':', '|'); @@ -68,7 +67,6 @@ bool StreamFile::Open(const String& path) return true; } -// Closes the stream. void StreamFile::Close() { if (file_handle) @@ -81,61 +79,47 @@ void StreamFile::Close() Stream::Close(); } -/// Returns the size of this stream (in bytes). size_t StreamFile::Length() const { return length; } -// Returns the position of the stream pointer (in bytes). size_t StreamFile::Tell() const { return GetFileInterface()->Tell(file_handle); } -// Sets the stream position (in bytes). bool StreamFile::Seek(long offset, int origin) const { return GetFileInterface()->Seek(file_handle, offset, origin); } -// Read from the stream. size_t StreamFile::Read(void* buffer, size_t bytes) const { return GetFileInterface()->Read(buffer, bytes, file_handle); } -// Write to the stream at the current position. -size_t StreamFile::Write(const void* RMLUI_UNUSED_PARAMETER(buffer), size_t RMLUI_UNUSED_PARAMETER(bytes)) +size_t StreamFile::Write(const void* /*buffer*/, size_t /*bytes*/) { - RMLUI_UNUSED(buffer); - RMLUI_UNUSED(bytes); - RMLUI_ERROR; return 0; } -// Truncate the stream to the specified length. -size_t StreamFile::Truncate(size_t RMLUI_UNUSED_PARAMETER(bytes)) +size_t StreamFile::Truncate(size_t /*bytes*/) { - RMLUI_UNUSED(bytes); - RMLUI_ERROR; return 0; } -// Returns true if the stream is ready for reading, false otherwise. bool StreamFile::IsReadReady() { return Tell() < Length(); } -// Returns true if the stream is ready for writing, false otherwise. bool StreamFile::IsWriteReady() { return false; } -// Determines the length of the stream. void StreamFile::GetLength() { length = GetFileInterface()->Length(file_handle); diff --git a/Source/Core/StreamFile.h b/Source/Core/StreamFile.h index 8c21e255a..0b78b6589 100644 --- a/Source/Core/StreamFile.h +++ b/Source/Core/StreamFile.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,11 +35,10 @@ namespace Rml { /** - @author Peter Curry + @author Peter Curry */ -class StreamFile final : public Stream -{ +class StreamFile final : public Stream { public: StreamFile(); virtual ~StreamFile(); diff --git a/Source/Core/StreamMemory.cpp b/Source/Core/StreamMemory.cpp index e53bb8366..d1f80087a 100644 --- a/Source/Core/StreamMemory.cpp +++ b/Source/Core/StreamMemory.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,15 +27,15 @@ */ #include "../../Include/RmlUi/Core/StreamMemory.h" -#include #include +#include namespace Rml { const int DEFAULT_BUFFER_SIZE = 256; const int BUFFER_INCREMENTS = 256; -StreamMemory::StreamMemory() +StreamMemory::StreamMemory() { buffer = nullptr; buffer_ptr = nullptr; @@ -61,40 +61,38 @@ StreamMemory::StreamMemory(const byte* _buffer, size_t _buffer_size) buffer_size = _buffer_size; buffer_used = _buffer_size; owns_buffer = false; - buffer_ptr = buffer; + buffer_ptr = buffer; } -StreamMemory::~StreamMemory() +StreamMemory::~StreamMemory() { - if ( owns_buffer ) - free( buffer ); + if (owns_buffer) + free(buffer); } -void StreamMemory::Close() +void StreamMemory::Close() { Stream::Close(); } -bool StreamMemory::IsEOS() const +bool StreamMemory::IsEOS() const { return buffer_ptr >= buffer + buffer_used; } -// Get current offset -size_t StreamMemory::Tell() const +size_t StreamMemory::Tell() const { return buffer_ptr - buffer; } -size_t StreamMemory::Length() const +size_t StreamMemory::Length() const { return buffer_used; } -// Read bytes from the buffer, advancing the internal pointer -size_t StreamMemory::Read(void *_buffer, size_t bytes) const +size_t StreamMemory::Read(void* _buffer, size_t bytes) const { - bytes = Math::ClampUpper(bytes, (size_t) (buffer + buffer_used - buffer_ptr)); + bytes = Math::ClampUpper(bytes, (size_t)(buffer + buffer_used - buffer_ptr)); memcpy(_buffer, buffer_ptr, bytes); @@ -103,35 +101,32 @@ size_t StreamMemory::Read(void *_buffer, size_t bytes) const return bytes; } -// Read bytes from the buffer, not advancing the internal pointer -size_t StreamMemory::Peek( void *_buffer, size_t bytes ) const +size_t StreamMemory::Peek(void* _buffer, size_t bytes) const { - bytes = Math::ClampUpper(bytes, (size_t) (buffer + buffer_used - buffer_ptr)); + bytes = Math::ClampUpper(bytes, (size_t)(buffer + buffer_used - buffer_ptr)); memcpy(_buffer, buffer_ptr, bytes); return bytes; } -// Read bytes from the buffer, advancing the internal pointer -size_t StreamMemory::Write( const void *_buffer, size_t bytes ) +size_t StreamMemory::Write(const void* _buffer, size_t bytes) { - if ( buffer_ptr + bytes > buffer + buffer_size ) - if ( !Reallocate( bytes + BUFFER_INCREMENTS ) ) + if (buffer_ptr + bytes > buffer + buffer_size) + if (!Reallocate(bytes + BUFFER_INCREMENTS)) return 0; - - memcpy( buffer_ptr, _buffer, bytes ); + + memcpy(buffer_ptr, _buffer, bytes); buffer_ptr += bytes; - buffer_used = Math::Max( (size_t)(buffer_ptr - buffer), buffer_used ); - + buffer_used = Math::Max((size_t)(buffer_ptr - buffer), buffer_used); + return bytes; } -// Truncate the stream to the specified length -size_t StreamMemory::Truncate( size_t bytes ) +size_t StreamMemory::Truncate(size_t bytes) { - if ( bytes > buffer_used ) + if (bytes > buffer_used) return 0; size_t old_size = buffer_used; @@ -140,63 +135,57 @@ size_t StreamMemory::Truncate( size_t bytes ) return old_size - buffer_used; } -// Set pointer to the specified offset -bool StreamMemory::Seek( long offset, int origin ) const +bool StreamMemory::Seek(long offset, int origin) const { byte* new_ptr = nullptr; - switch ( origin ) + switch (origin) { - case SEEK_SET: - new_ptr = buffer + offset; - break; - case SEEK_END: - new_ptr = buffer + ( buffer_used - offset ); - break; - case SEEK_CUR: - new_ptr = buffer_ptr + offset; + case SEEK_SET: new_ptr = buffer + offset; break; + case SEEK_END: new_ptr = buffer + (buffer_used - offset); break; + case SEEK_CUR: new_ptr = buffer_ptr + offset; } // Check of overruns - if ( new_ptr < buffer || new_ptr > buffer + buffer_used ) + if (new_ptr < buffer || new_ptr > buffer + buffer_used) return false; buffer_ptr = new_ptr; - + return true; } -size_t StreamMemory::PushFront( const void* _buffer, size_t bytes ) +size_t StreamMemory::PushFront(const void* _buffer, size_t bytes) { - if ( buffer_used + bytes > buffer_size ) - if ( !Reallocate( bytes + BUFFER_INCREMENTS ) ) + if (buffer_used + bytes > buffer_size) + if (!Reallocate(bytes + BUFFER_INCREMENTS)) return 0; - memmove( &buffer[ bytes ], &buffer[ 0 ], buffer_used ); - memcpy( buffer, _buffer, bytes ); + memmove(&buffer[bytes], &buffer[0], buffer_used); + memcpy(buffer, _buffer, bytes); buffer_used += bytes; buffer_ptr += bytes; return bytes; } -size_t StreamMemory::PopFront( size_t bytes ) +size_t StreamMemory::PopFront(size_t bytes) { - Erase( 0, bytes ); + Erase(0, bytes); buffer_ptr -= bytes; buffer_ptr = Math::ClampLower(buffer_ptr, buffer); return bytes; } -const byte* StreamMemory::RawStream() const +const byte* StreamMemory::RawStream() const { return buffer; } -void StreamMemory::Erase( size_t offset, size_t bytes ) +void StreamMemory::Erase(size_t offset, size_t bytes) { bytes = Math::ClampUpper(bytes, buffer_used - offset); memmove(&buffer[offset], &buffer[offset + bytes], buffer_used - offset - bytes); - buffer_used -= bytes; + buffer_used -= bytes; } bool StreamMemory::IsReadReady() @@ -214,22 +203,21 @@ void StreamMemory::SetSourceURL(const URL& url) SetStreamDetails(url, Stream::MODE_READ | (owns_buffer ? Stream::MODE_WRITE : 0)); } -// Resize the buffer -bool StreamMemory::Reallocate( size_t size ) -{ - RMLUI_ASSERT( owns_buffer ); - if ( !owns_buffer ) +bool StreamMemory::Reallocate(size_t size) +{ + RMLUI_ASSERT(owns_buffer); + if (!owns_buffer) return false; - - byte *new_buffer = (byte*)realloc( buffer, buffer_size + size ); - if ( new_buffer == nullptr ) + + byte* new_buffer = (byte*)realloc(buffer, buffer_size + size); + if (new_buffer == nullptr) return false; - buffer_ptr = new_buffer + ( buffer_ptr - buffer ); + buffer_ptr = new_buffer + (buffer_ptr - buffer); buffer = new_buffer; buffer_size += size; - + return true; } diff --git a/Source/Core/StringUtilities.cpp b/Source/Core/StringUtilities.cpp index 33f7925e1..5053ff791 100644 --- a/Source/Core/StringUtilities.cpp +++ b/Source/Core/StringUtilities.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,10 +29,10 @@ #include "../../Include/RmlUi/Core/StringUtilities.h" #include "../../Include/RmlUi/Core/Log.h" #include -#include +#include #include +#include #include -#include namespace Rml { @@ -81,13 +81,15 @@ String CreateString(size_t max_size, const char* format, ...) return result; } -static inline char CharToLower(char c) { +static inline char CharToLower(char c) +{ if (c >= 'A' && c <= 'Z') c += char('a' - 'A'); return c; } -String StringUtilities::ToLower(String string) { +String StringUtilities::ToLower(String string) +{ std::transform(string.begin(), string.end(), string.begin(), &CharToLower); return string; } @@ -98,8 +100,7 @@ String StringUtilities::ToUpper(String string) if (c >= 'a' && c <= 'z') c -= char('a' - 'A'); return c; - } - ); + }); return string; } @@ -129,44 +130,44 @@ String StringUtilities::DecodeRml(const String& s) { if (s[i] == '&') { - if (s[i+1] == 'l' && s[i+2] == 't' && s[i+3] == ';') + if (s[i + 1] == 'l' && s[i + 2] == 't' && s[i + 3] == ';') { result += "<"; i += 4; continue; } - else if (s[i+1] == 'g' && s[i+2] == 't' && s[i+3] == ';') + else if (s[i + 1] == 'g' && s[i + 2] == 't' && s[i + 3] == ';') { result += ">"; i += 4; continue; } - else if (s[i+1] == 'a' && s[i+2] == 'm' && s[i+3] == 'p' && s[i+4] == ';') + else if (s[i + 1] == 'a' && s[i + 2] == 'm' && s[i + 3] == 'p' && s[i + 4] == ';') { result += "&"; i += 5; continue; } - else if (s[i+1] == 'q' && s[i+2] == 'u' && s[i+3] == 'o' && s[i+4] == 't' && s[i+5] == ';') + else if (s[i + 1] == 'q' && s[i + 2] == 'u' && s[i + 3] == 'o' && s[i + 4] == 't' && s[i + 5] == ';') { result += "\""; i += 6; continue; } - else if (s[i+1] == '#') + else if (s[i + 1] == '#') { size_t start = i + 2; - if (s[i+2] == 'x') + if (s[i + 2] == 'x') { start++; size_t j = 0; - for(; j < 8; j++) + for (; j < 8; j++) { auto const& c = s[start + j]; if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) break; } - + if (j > 0 && s[start + j] == ';') { String tmp = s.substr(start, j); @@ -183,13 +184,13 @@ String StringUtilities::DecodeRml(const String& s) else { size_t j = 0; - for(; j < 8; j++) + for (; j < 8; j++) { auto const& c = s[start + j]; if (!(c >= '0' && c <= '9')) break; } - + if (j > 0 && s[start + j] == ';') { String tmp = s.substr(start, j); @@ -203,7 +204,6 @@ String StringUtilities::DecodeRml(const String& s) } } } - } } result += s[i]; @@ -215,7 +215,8 @@ String StringUtilities::DecodeRml(const String& s) String StringUtilities::Replace(String subject, const String& search, const String& replace) { size_t pos = 0; - while ((pos = subject.find(search, pos)) != String::npos) { + while ((pos = subject.find(search, pos)) != String::npos) + { subject.replace(pos, search.length(), replace); pos += replace.length(); } @@ -233,10 +234,8 @@ String StringUtilities::Replace(String subject, char search, char replace) return subject; } - -// Expands character-delimited list of values in a single string to a whitespace-trimmed list of values. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter) -{ +{ char quote = 0; bool last_char_delimiter = true; const char* ptr = string.c_str(); @@ -256,11 +255,11 @@ void StringUtilities::ExpandString(StringList& string_list, const String& string // Switch into quote mode if the last char was a delimeter ( excluding whitespace ) // and we're not already in quote mode if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\'')) - { + { quote = *ptr; } // Switch out of quote mode if we encounter a quote that hasn't been escaped - else if (*ptr == quote && *(ptr-1) != '\\') + else if (*ptr == quote && *(ptr - 1) != '\\') { quote = 0; } @@ -291,8 +290,8 @@ void StringUtilities::ExpandString(StringList& string_list, const String& string string_list.emplace_back(start_ptr, end_ptr + 1); } - -void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, bool ignore_repeated_delimiters) +void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, + bool ignore_repeated_delimiters) { int quote_mode_depth = 0; const char* ptr = string.c_str(); @@ -317,7 +316,7 @@ void StringUtilities::ExpandString(StringList& string_list, const String& string { if (start_ptr) string_list.emplace_back(start_ptr, end_ptr + 1); - else if(!ignore_repeated_delimiters) + else if (!ignore_repeated_delimiters) string_list.emplace_back(); start_ptr = nullptr; } @@ -337,7 +336,6 @@ void StringUtilities::ExpandString(StringList& string_list, const String& string string_list.emplace_back(start_ptr, end_ptr + 1); } -// Joins a list of string values into a single string separated by a character delimiter. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter) { for (size_t i = 0; i < string_list.size(); i++) @@ -361,7 +359,7 @@ RMLUICORE_API String StringUtilities::StripWhitespace(StringView string) while (start < end && IsWhitespace(*start)) start++; - while (end > start&& IsWhitespace(*(end - 1))) + while (end > start && IsWhitespace(*(end - 1))) end--; if (start < end) @@ -489,11 +487,11 @@ String StringUtilities::ToUTF8(const Character* characters, int num_characters) if (c < 0x80) result += (char)c; else if (c < 0x800) - result += { char(((c >> 6) & l5) | h2), char((c & l6) | h1) }; + result += {char(((c >> 6) & l5) | h2), char((c & l6) | h1)}; else if (c < 0x10000) - result += { char(((c >> 12) & l4) | h3), char(((c >> 6) & l6) | h1), char((c & l6) | h1) }; + result += {char(((c >> 12) & l4) | h3), char(((c >> 6) & l6) | h1), char((c & l6) | h1)}; else if (c <= 0x10FFFF) - result += { char(((c >> 18) & l3) | h4), char(((c >> 12) & l6) | h1), char(((c >> 6) & l6) | h1), char((c & l6) | h1) }; + result += {char(((c >> 18) & l3) | h4), char(((c >> 12) & l6) | h1), char(((c >> 6) & l6) | h1), char((c & l6) | h1)}; else invalid_character = true; } @@ -534,43 +532,42 @@ StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin { RMLUI_ASSERT(p_end >= p_begin); } -StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size()) -{} -StringView::StringView(const String& string, size_t offset) : p_begin(string.data() + offset), p_end(string.data() + string.size()) -{} -StringView::StringView(const String& string, size_t offset, size_t count) : p_begin(string.data() + offset), p_end(string.data() + std::min(offset + count, string.size())) +StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size()) {} +StringView::StringView(const String& string, size_t offset) : p_begin(string.data() + offset), p_end(string.data() + string.size()) {} +StringView::StringView(const String& string, size_t offset, size_t count) : + p_begin(string.data() + offset), p_end(string.data() + std::min(offset + count, string.size())) {} -bool StringView::operator==(const StringView& other) const { - return size() == other.size() && strncmp(p_begin, other.p_begin, size()) == 0; +bool StringView::operator==(const StringView& other) const +{ + return size() == other.size() && strncmp(p_begin, other.p_begin, size()) == 0; } - -StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p) -{} -StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data()) -{} -StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset) -{} -StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset) -{} -StringIteratorU8& StringIteratorU8::operator++() { +StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p) {} +StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data()) {} +StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset) {} +StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset) {} +StringIteratorU8& StringIteratorU8::operator++() +{ RMLUI_ASSERT(p < view.end()); ++p; SeekForward(); return *this; } -StringIteratorU8& StringIteratorU8::operator--() { +StringIteratorU8& StringIteratorU8::operator--() +{ RMLUI_ASSERT(p >= view.begin()); --p; SeekBack(); return *this; } -inline void StringIteratorU8::SeekBack() { +inline void StringIteratorU8::SeekBack() +{ p = StringUtilities::SeekBackwardUTF8(p, view.begin()); } -inline void StringIteratorU8::SeekForward() { +inline void StringIteratorU8::SeekForward() +{ p = StringUtilities::SeekForwardUTF8(p, view.end()); } diff --git a/Source/Core/StyleSheet.cpp b/Source/Core/StyleSheet.cpp index ba248ae28..a8af7cca5 100644 --- a/Source/Core/StyleSheet.cpp +++ b/Source/Core/StyleSheet.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -45,17 +45,14 @@ StyleSheet::StyleSheet() specificity_offset = 0; } -StyleSheet::~StyleSheet() -{ -} +StyleSheet::~StyleSheet() {} -/// Combines this style sheet with another one, producing a new sheet UniquePtr StyleSheet::CombineStyleSheet(const StyleSheet& other_sheet) const { RMLUI_ZoneScoped; UniquePtr new_sheet = UniquePtr(new StyleSheet()); - + new_sheet->root = root->DeepCopy(); new_sheet->specificity_offset = specificity_offset; new_sheet->keyframes = keyframes; @@ -88,14 +85,11 @@ void StyleSheet::MergeStyleSheet(const StyleSheet& other_sheet) decorator_map[other_decorator.first] = other_decorator.second; } - spritesheet_list.Reserve( - spritesheet_list.NumSpriteSheets() + other_sheet.spritesheet_list.NumSpriteSheets(), - spritesheet_list.NumSprites() + other_sheet.spritesheet_list.NumSprites() - ); + spritesheet_list.Reserve(spritesheet_list.NumSpriteSheets() + other_sheet.spritesheet_list.NumSpriteSheets(), + spritesheet_list.NumSprites() + other_sheet.spritesheet_list.NumSprites()); spritesheet_list.Merge(other_sheet.spritesheet_list); } -// Builds the node index for a combined style sheet. void StyleSheet::BuildNodeIndex() { RMLUI_ZoneScoped; @@ -111,8 +105,7 @@ const DecoratorSpecification* StyleSheet::GetDecoratorSpecification(const String return nullptr; } -// Returns the Keyframes of the given name, or null if it does not exist. -const Keyframes* StyleSheet::GetKeyframes(const String & name) const +const Keyframes* StyleSheet::GetKeyframes(const String& name) const { auto it = keyframes.find(name); if (it != keyframes.end()) @@ -195,13 +188,12 @@ const Sprite* StyleSheet::GetSprite(const String& name) const return spritesheet_list.GetSprite(name); } -// Returns the compiled element definition for a given element hierarchy. SharedPtr StyleSheet::GetElementDefinition(const Element* element) const { RMLUI_ASSERT_NONRECURSIVE; // Using static to avoid allocations. Make sure we don't call this function recursively. - static Vector< const StyleSheetNode* > applicable_nodes; + static Vector applicable_nodes; applicable_nodes.clear(); auto AddApplicableNodes = [element](const StyleSheetIndex::NodeIndex& node_index, const String& key) { @@ -230,7 +222,7 @@ SharedPtr StyleSheet::GetElementDefinition(const Elemen if (tag == "#text") return nullptr; - // First, look up the indexed requirements. + // First, look up the indexed requirements. if (!id.empty()) AddApplicableNodes(styled_node_index.ids, id); diff --git a/Source/Core/StyleSheetContainer.cpp b/Source/Core/StyleSheetContainer.cpp index 5a0e8e46a..e69d0efe0 100644 --- a/Source/Core/StyleSheetContainer.cpp +++ b/Source/Core/StyleSheetContainer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,13 +38,9 @@ namespace Rml { -StyleSheetContainer::StyleSheetContainer() -{ -} +StyleSheetContainer::StyleSheetContainer() {} -StyleSheetContainer::~StyleSheetContainer() -{ -} +StyleSheetContainer::~StyleSheetContainer() {} bool StyleSheetContainer::LoadStyleSheetContainer(Stream* stream, int begin_line_number) { @@ -128,7 +124,7 @@ bool StyleSheetContainer::UpdateCompiledStyleSheet(const Context* context) all_match = false; break; case MediaQueryId::Orientation: - // Landscape (x > y) = 0 + // Landscape (x > y) = 0 // Portrait (x <= y) = 1 if ((vp_dimensions.x <= vp_dimensions.y) != property.second.Get()) all_match = false; @@ -139,8 +135,7 @@ bool StyleSheetContainer::UpdateCompiledStyleSheet(const Context* context) break; // Invalid properties case MediaQueryId::Invalid: - case MediaQueryId::NumDefinedIds: - break; + case MediaQueryId::NumDefinedIds: break; } if (!all_match) diff --git a/Source/Core/StyleSheetFactory.cpp b/Source/Core/StyleSheetFactory.cpp index 3c78cc350..6fe9d7342 100644 --- a/Source/Core/StyleSheetFactory.cpp +++ b/Source/Core/StyleSheetFactory.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -89,13 +89,11 @@ const StyleSheetContainer* StyleSheetFactory::GetStyleSheetContainer(const Strin return result; } -// Clear the style sheet cache. void StyleSheetFactory::ClearStyleSheetCache() { instance->stylesheets.clear(); } -// Returns one of the available node selectors. StructuralSelector StyleSheetFactory::GetSelector(const String& name) { SelectorMap::const_iterator it; @@ -118,11 +116,8 @@ StructuralSelector StyleSheetFactory::GetSelector(const String& name) case StructuralSelectorType::Nth_Last_Child: case StructuralSelectorType::Nth_Of_Type: case StructuralSelectorType::Nth_Last_Of_Type: - case StructuralSelectorType::Not: - requires_parameter = true; - break; - default: - break; + case StructuralSelectorType::Not: requires_parameter = true; break; + default: break; } const size_t parameter_end = name.rfind(')'); diff --git a/Source/Core/StyleSheetFactory.h b/Source/Core/StyleSheetFactory.h index fe924a0ea..ce50716b1 100644 --- a/Source/Core/StyleSheetFactory.h +++ b/Source/Core/StyleSheetFactory.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/StyleSheetNode.cpp b/Source/Core/StyleSheetNode.cpp index 80067a5bd..71f9996fa 100644 --- a/Source/Core/StyleSheetNode.cpp +++ b/Source/Core/StyleSheetNode.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -93,7 +93,6 @@ StyleSheetNode* StyleSheetNode::GetOrCreateChildNode(CompoundSelector&& other) return result; } -// Merges an entire tree hierarchy into our hierarchy. void StyleSheetNode::MergeHierarchy(StyleSheetNode* node, int specificity_offset) { RMLUI_ZoneScoped; @@ -125,7 +124,6 @@ UniquePtr StyleSheetNode::DeepCopy(StyleSheetNode* in_parent) co return node; } -// Builds up a style sheet's index recursively. void StyleSheetNode::BuildIndex(StyleSheetIndex& styled_node_index) const { // If this has properties defined, then we insert it into the styled node index. @@ -164,20 +162,16 @@ void StyleSheetNode::BuildIndex(StyleSheetIndex& styled_node_index) const child->BuildIndex(styled_node_index); } -// Returns the specificity of this node. int StyleSheetNode::GetSpecificity() const { return specificity; } -// Imports properties from a single rule definition (ie, with a shared specificity) into the node's -// properties. void StyleSheetNode::ImportProperties(const PropertyDictionary& _properties, int rule_specificity) { properties.Import(_properties, specificity + rule_specificity); } -// Returns the node's default properties. const PropertyDictionary& StyleSheetNode::GetProperties() const { return properties; diff --git a/Source/Core/StyleSheetNode.h b/Source/Core/StyleSheetNode.h index 3c9ff7db9..66c33e32e 100644 --- a/Source/Core/StyleSheetNode.h +++ b/Source/Core/StyleSheetNode.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/StyleSheetParser.cpp b/Source/Core/StyleSheetParser.cpp index a47737b57..314842707 100644 --- a/Source/Core/StyleSheetParser.cpp +++ b/Source/Core/StyleSheetParser.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,9 +27,6 @@ */ #include "StyleSheetParser.h" -#include "ComputeProperty.h" -#include "StyleSheetFactory.h" -#include "StyleSheetNode.h" #include "../../Include/RmlUi/Core/DecoratorInstancer.h" #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Log.h" @@ -40,6 +37,9 @@ #include "../../Include/RmlUi/Core/StyleSheet.h" #include "../../Include/RmlUi/Core/StyleSheetContainer.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" +#include "ComputeProperty.h" +#include "StyleSheetFactory.h" +#include "StyleSheetNode.h" #include #include @@ -56,7 +56,7 @@ class AbstractPropertyParser : NonCopyMoveable { /* * PropertySpecificationParser just passes the parsing to a property specification. Usually * the main stylesheet specification, except for e.g. @decorator blocks. -*/ + */ class PropertySpecificationParser final : public AbstractPropertyParser { private: // The dictionary to store the properties in. @@ -66,19 +66,18 @@ class PropertySpecificationParser final : public AbstractPropertyParser { const PropertySpecification& specification; public: - PropertySpecificationParser(PropertyDictionary& properties, const PropertySpecification& specification) : properties(properties), specification(specification) {} + PropertySpecificationParser(PropertyDictionary& properties, const PropertySpecification& specification) : + properties(properties), specification(specification) + {} - bool Parse(const String& name, const String& value) override - { - return specification.ParsePropertyDeclaration(properties, name, value); - } + bool Parse(const String& name, const String& value) override { return specification.ParsePropertyDeclaration(properties, name, value); } }; /* * Spritesheets need a special parser because its property names are arbitrary keys, * while its values are always rectangles. Thus, it must be parsed with a special "rectangle" parser * for every name-value pair. We can probably optimize this for @performance. -*/ + */ class SpritesheetPropertyParser final : public AbstractPropertyParser { private: String image_source; @@ -91,7 +90,7 @@ class SpritesheetPropertyParser final : public AbstractPropertyParser { ShorthandId id_rectangle; public: - SpritesheetPropertyParser() : specification(4, 1) + SpritesheetPropertyParser() : specification(4, 1) { id_rx = specification.RegisterProperty("rectangle-x", "", false, false).AddParser("length").GetId(); id_ry = specification.RegisterProperty("rectangle-y", "", false, false).AddParser("length").GetId(); @@ -101,20 +100,12 @@ class SpritesheetPropertyParser final : public AbstractPropertyParser { id_resolution = specification.RegisterProperty("resolution", "", false, false).AddParser("resolution").GetId(); } - const String& GetImageSource() const - { - return image_source; - } - const SpriteDefinitionList& GetSpriteDefinitions() const - { - return sprite_definitions; - } - float GetImageResolutionFactor() const - { - return image_resolution_factor; - } + const String& GetImageSource() const { return image_source; } + const SpriteDefinitionList& GetSpriteDefinitions() const { return sprite_definitions; } + float GetImageResolutionFactor() const { return image_resolution_factor; } - void Clear() { + void Clear() + { image_resolution_factor = 1.f; image_source.clear(); sprite_definitions.clear(); @@ -159,27 +150,23 @@ class SpritesheetPropertyParser final : public AbstractPropertyParser { } }; - static UniquePtr spritesheet_property_parser; /* - * Media queries need a special parser because they have unique properties that + * Media queries need a special parser because they have unique properties that * aren't admissible in other property declaration contexts and the syntax of -*/ + */ class MediaQueryPropertyParser final : public AbstractPropertyParser { private: // The dictionary to store the properties in. PropertyDictionary* properties = nullptr; PropertySpecification specification; - static PropertyId CastId(MediaQueryId id) - { - return static_cast(id); - } + static PropertyId CastId(MediaQueryId id) { return static_cast(id); } public: - MediaQueryPropertyParser() : specification(14, 0) - { + MediaQueryPropertyParser() : specification(14, 0) + { specification.RegisterProperty("width", "", false, false, CastId(MediaQueryId::Width)).AddParser("length"); specification.RegisterProperty("min-width", "", false, false, CastId(MediaQueryId::MinWidth)).AddParser("length"); specification.RegisterProperty("max-width", "", false, false, CastId(MediaQueryId::MaxWidth)).AddParser("length"); @@ -196,19 +183,15 @@ class MediaQueryPropertyParser final : public AbstractPropertyParser { specification.RegisterProperty("min-resolution", "", false, false, CastId(MediaQueryId::MinResolution)).AddParser("resolution"); specification.RegisterProperty("max-resolution", "", false, false, CastId(MediaQueryId::MaxResolution)).AddParser("resolution"); - specification.RegisterProperty("orientation", "", false, false, CastId(MediaQueryId::Orientation)).AddParser("keyword", "landscape, portrait"); + specification.RegisterProperty("orientation", "", false, false, CastId(MediaQueryId::Orientation)) + .AddParser("keyword", "landscape, portrait"); specification.RegisterProperty("theme", "", false, false, CastId(MediaQueryId::Theme)).AddParser("string"); } - void SetTargetProperties(PropertyDictionary* _properties) - { - properties = _properties; - } + void SetTargetProperties(PropertyDictionary* _properties) { properties = _properties; } - void Clear() { - properties = nullptr; - } + void Clear() { properties = nullptr; } bool Parse(const String& name, const String& value) override { @@ -217,10 +200,8 @@ class MediaQueryPropertyParser final : public AbstractPropertyParser { } }; - static UniquePtr media_query_property_parser; - StyleSheetParser::StyleSheetParser() { line_number = 0; @@ -228,9 +209,7 @@ StyleSheetParser::StyleSheetParser() parse_buffer_pos = 0; } -StyleSheetParser::~StyleSheetParser() -{ -} +StyleSheetParser::~StyleSheetParser() {} void StyleSheetParser::Initialise() { @@ -252,13 +231,7 @@ static bool IsValidIdentifier(const String& str) for (size_t i = 0; i < str.size(); i++) { char c = str[i]; - bool valid = ( - (c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || (c == '-') - || (c == '_') - ); + bool valid = ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_')); if (!valid) return false; } @@ -266,7 +239,6 @@ static bool IsValidIdentifier(const String& str) return true; } - static void PostprocessKeyframes(KeyframesMap& keyframes_map) { for (auto& keyframes_pair : keyframes_map) @@ -279,8 +251,9 @@ static void PostprocessKeyframes(KeyframesMap& keyframes_map) std::sort(blocks.begin(), blocks.end(), [](const KeyframeBlock& a, const KeyframeBlock& b) { return a.normalized_time < b.normalized_time; }); // Add all property names specified by any block - if(blocks.size() > 0) property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties()); - for(auto& block : blocks) + if (blocks.size() > 0) + property_ids.reserve(blocks.size() * blocks[0].properties.GetNumProperties()); + for (auto& block : blocks) { for (auto& property : block.properties.GetProperties()) property_ids.push_back(property.first); @@ -290,11 +263,10 @@ static void PostprocessKeyframes(KeyframesMap& keyframes_map) property_ids.erase(std::unique(property_ids.begin(), property_ids.end()), property_ids.end()); property_ids.shrink_to_fit(); } - } - -bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties) +bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, + const PropertyDictionary& properties) { if (!IsValidIdentifier(identifier)) { @@ -319,8 +291,8 @@ bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const Str rule_values.push_back(0.0f); else if (rule == "to") rule_values.push_back(1.0f); - else if(sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1) - if(count > 0 && value >= 0.0f && value <= 100.0f) + else if (sscanf(rule.c_str(), "%f%%%n", &value, &count) == 1) + if (count > 0 && value >= 0.0f && value <= 100.0f) rule_values.push_back(0.01f * value); } @@ -332,9 +304,10 @@ bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const Str Keyframes& keyframes = keyframes_map[identifier]; - for(float selector : rule_values) + for (float selector : rule_values) { - auto it = std::find_if(keyframes.blocks.begin(), keyframes.blocks.end(), [selector](const KeyframeBlock& keyframe_block) { return Math::AbsoluteValue(keyframe_block.normalized_time - selector) < 0.0001f; }); + auto it = std::find_if(keyframes.blocks.begin(), keyframes.blocks.end(), + [selector](const KeyframeBlock& keyframe_block) { return Math::AbsoluteValue(keyframe_block.normalized_time - selector) < 0.0001f; }); if (it == keyframes.blocks.end()) { keyframes.blocks.emplace_back(selector); @@ -352,14 +325,16 @@ bool StyleSheetParser::ParseKeyframeBlock(KeyframesMap& keyframes_map, const Str return true; } -bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, const SharedPtr& source) +bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, + const SharedPtr& source) { StringList name_type; StringUtilities::ExpandString(name_type, at_name, ':'); if (name_type.size() != 2 || name_type[0].empty() || name_type[1].empty()) { - Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Decorator syntax error at %s:%d. Use syntax: '@decorator name : type { ... }'.", stream_file_name.c_str(), + line_number); return false; } @@ -369,7 +344,8 @@ bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpeci auto it_find = decorator_map.find(name); if (it_find != decorator_map.end()) { - Log::Message(Log::LT_WARNING, "Decorator with name '%s' already declared, ignoring decorator at %s:%d.", name.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Decorator with name '%s' already declared, ignoring decorator at %s:%d.", name.c_str(), + stream_file_name.c_str(), line_number); return false; } @@ -377,7 +353,7 @@ bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpeci DecoratorInstancer* decorator_instancer = Factory::GetDecoratorInstancer(decorator_type); PropertyDictionary properties; - if(!decorator_instancer) + if (!decorator_instancer) { // Type is not a declared decorator type, instead, see if it is another decorator name, then we inherit its properties. auto it = decorator_map.find(decorator_type); @@ -392,7 +368,8 @@ bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpeci // If we still don't have an instancer, we cannot continue. if (!decorator_instancer) { - Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Invalid decorator type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), + line_number); return false; } } @@ -407,19 +384,21 @@ bool StyleSheetParser::ParseDecoratorBlock(const String& at_name, DecoratorSpeci property_specification.SetPropertyDefaults(properties); properties.SetSourceOfAllProperties(source); - SharedPtr decorator = decorator_instancer->InstanceDecorator(decorator_type, properties, DecoratorInstancerInterface(style_sheet, source.get())); + SharedPtr decorator = + decorator_instancer->InstanceDecorator(decorator_type, properties, DecoratorInstancerInterface(style_sheet, source.get())); if (!decorator) { - Log::Message(Log::LT_WARNING, "Could not instance decorator of type '%s' declared at %s:%d.", decorator_type.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Could not instance decorator of type '%s' declared at %s:%d.", decorator_type.c_str(), + stream_file_name.c_str(), line_number); return false; } - decorator_map.emplace(name, DecoratorSpecification{ std::move(decorator_type), std::move(properties), std::move(decorator) }); + decorator_map.emplace(name, DecoratorSpecification{std::move(decorator_type), std::move(properties), std::move(decorator)}); return true; } -bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, const String & rules) +bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, const String& rules) { media_query_property_parser->SetTargetProperties(&properties); @@ -434,11 +413,11 @@ bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, cons String current_string; - while(cursor++ < rules.length()) + while (cursor++ < rules.length()) { character = rules[cursor]; - switch(character) + switch (character) { case '(': { @@ -452,7 +431,8 @@ bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, cons if (current_string != "and") { - Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Unexpected '%s' in @media query list at %s:%d. Expected 'and'.", current_string.c_str(), + stream_file_name.c_str(), line_number); return false; } @@ -470,8 +450,9 @@ bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, cons current_string = StringUtilities::StripWhitespace(current_string); - if(!media_query_property_parser->Parse(name, current_string)) - Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(), current_string.c_str(), stream_file_name.c_str(), line_number); + if (!media_query_property_parser->Parse(name, current_string)) + Log::Message(Log::LT_WARNING, "Syntax error parsing media-query property declaration '%s: %s;' in %s: %d.", name.c_str(), + current_string.c_str(), stream_file_name.c_str(), line_number); current_string.clear(); state = Global; @@ -489,7 +470,8 @@ bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, cons if (!IsValidIdentifier(current_string)) { - Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Malformed property name '%s' in @media query list at %s:%d.", current_string.c_str(), + stream_file_name.c_str(), line_number); return false; } @@ -499,8 +481,7 @@ bool StyleSheetParser::ParseMediaFeatureMap(PropertyDictionary& properties, cons state = Value; } break; - default: - current_string += character; + default: current_string += character; } } @@ -524,7 +505,6 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int enum class State { Global, AtRuleIdentifier, KeyframeBlock, Invalid }; State state = State::Global; - MediaBlock current_block = {}; // Need to track whether currently inside a nested media block or not, since the default scope is also a media block @@ -537,7 +517,7 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int while (FillBuffer()) { String pre_token_str; - + while (char token = FindToken(pre_token_str, "{@}", true)) { switch (state) @@ -553,7 +533,7 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int } const int rule_line_number = line_number; - + // Read the attributes PropertyDictionary properties; PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification()); @@ -594,14 +574,15 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int } else { - Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing stylesheet at %s:%d. Trying to proceed.", token, stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing stylesheet at %s:%d. Trying to proceed.", token, + stream_file_name.c_str(), line_number); } } break; case State::AtRuleIdentifier: { if (token == '{') - { + { // Initialize current block if not present if (!current_block.stylesheet) { @@ -619,7 +600,7 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int { auto source = MakeShared(stream_file_name, (int)line_number, pre_token_str); ParseDecoratorBlock(at_rule_name, current_block.stylesheet->decorator_map, *current_block.stylesheet, source); - + at_rule_name.clear(); state = State::Global; } @@ -631,23 +612,29 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int const String& image_source = spritesheet_property_parser->GetImageSource(); const SpriteDefinitionList& sprite_definitions = spritesheet_property_parser->GetSpriteDefinitions(); const float image_resolution_factor = spritesheet_property_parser->GetImageResolutionFactor(); - + if (sprite_definitions.empty()) { - Log::Message(Log::LT_WARNING, "Spritesheet '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Spritesheet '%s' has no sprites defined, ignored. At %s:%d", at_rule_name.c_str(), + stream_file_name.c_str(), line_number); } else if (image_source.empty()) { - Log::Message(Log::LT_WARNING, "No image source (property 'src') specified for spritesheet '%s'. At %s:%d", at_rule_name.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "No image source (property 'src') specified for spritesheet '%s'. At %s:%d", + at_rule_name.c_str(), stream_file_name.c_str(), line_number); } else if (image_resolution_factor <= 0.0f || image_resolution_factor >= 100.f) { - Log::Message(Log::LT_WARNING, "Spritesheet resolution (property 'resolution') value must be larger than 0.0 and smaller than 100.0, given %g. In spritesheet '%s'. At %s:%d", image_resolution_factor, at_rule_name.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, + "Spritesheet resolution (property 'resolution') value must be larger than 0.0 and smaller than 100.0, given %g. In " + "spritesheet '%s'. At %s:%d", + image_resolution_factor, at_rule_name.c_str(), stream_file_name.c_str(), line_number); } else { const float display_scale = 1.0f / image_resolution_factor; - current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number, display_scale, sprite_definitions); + current_block.stylesheet->spritesheet_list.AddSpriteSheet(at_rule_name, image_source, stream_file_name, (int)line_number, + display_scale, sprite_definitions); } spritesheet_property_parser->Clear(); @@ -678,13 +665,14 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int // Invalid identifier, should ignore at_rule_name.clear(); state = State::Global; - Log::Message(Log::LT_WARNING, "Invalid at-rule identifier '%s' found in stylesheet at %s:%d", at_rule_identifier.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Invalid at-rule identifier '%s' found in stylesheet at %s:%d", at_rule_identifier.c_str(), + stream_file_name.c_str(), line_number); } - } else { - Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing at-rule identifier in stylesheet at %s:%d", token, stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing at-rule identifier in stylesheet at %s:%d", token, + stream_file_name.c_str(), line_number); state = State::Invalid; } } @@ -692,7 +680,7 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int case State::KeyframeBlock: { if (token == '{') - { + { // Initialize current block if not present if (!current_block.stylesheet) { @@ -702,7 +690,7 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int // Each keyframe in keyframes has its own block which is processed here PropertyDictionary properties; PropertySpecificationParser parser(properties, StyleSheetSpecification::GetPropertySpecification()); - if(!ReadProperties(parser)) + if (!ReadProperties(parser)) continue; if (!ParseKeyframeBlock(current_block.stylesheet->keyframes, at_rule_name, pre_token_str, properties)) @@ -715,7 +703,8 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int } else { - Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframe block in stylesheet at %s:%d", token, stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Invalid character '%c' found while parsing keyframe block in stylesheet at %s:%d", token, + stream_file_name.c_str(), line_number); state = State::Invalid; } } @@ -732,7 +721,7 @@ bool StyleSheetParser::Parse(MediaBlockList& style_sheets, Stream* _stream, int if (state == State::Invalid) break; - } + } // Complete last block if present if (current_block.stylesheet) @@ -796,67 +785,70 @@ bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser) switch (state) { - case NAME: + case NAME: + { + if (character == ';') { - if (character == ';') + name = StringUtilities::StripWhitespace(name); + if (!name.empty()) { - name = StringUtilities::StripWhitespace(name); - if (!name.empty()) - { - Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(), stream_file_name.c_str(), line_number); - name.clear(); - } - } - else if (character == '}') - { - name = StringUtilities::StripWhitespace(name); - if (!name.empty()) - Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(), stream_file_name.c_str(), line_number); - return true; - } - else if (character == ':') - { - name = StringUtilities::StripWhitespace(name); - state = VALUE; + Log::Message(Log::LT_WARNING, "Found name with no value while parsing property declaration '%s' at %s:%d", name.c_str(), + stream_file_name.c_str(), line_number); + name.clear(); } - else - name += character; } - break; - - case VALUE: + else if (character == '}') { - if (character == ';') - { - value = StringUtilities::StripWhitespace(value); + name = StringUtilities::StripWhitespace(name); + if (!name.empty()) + Log::Message(Log::LT_WARNING, "End of rule encountered while parsing property declaration '%s' at %s:%d", name.c_str(), + stream_file_name.c_str(), line_number); + return true; + } + else if (character == ':') + { + name = StringUtilities::StripWhitespace(name); + state = VALUE; + } + else + name += character; + } + break; - if (!property_parser.Parse(name, value)) - Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(), stream_file_name.c_str(), line_number); + case VALUE: + { + if (character == ';') + { + value = StringUtilities::StripWhitespace(value); - name.clear(); - value.clear(); - state = NAME; - } - else if (character == '}') - { - break; - } - else - { - value += character; - if (character == '"') - state = QUOTE; - } - } - break; + if (!property_parser.Parse(name, value)) + Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(), + stream_file_name.c_str(), line_number); - case QUOTE: + name.clear(); + value.clear(); + state = NAME; + } + else if (character == '}') + { + break; + } + else { value += character; - if (character == '"' && previous_character != '\\') - state = VALUE; + if (character == '"') + state = QUOTE; } - break; + } + break; + + case QUOTE: + { + value += character; + if (character == '"' && previous_character != '\\') + state = VALUE; + } + break; } if (character == '}') @@ -869,13 +861,15 @@ bool StyleSheetParser::ReadProperties(AbstractPropertyParser& property_parser) value = StringUtilities::StripWhitespace(value); if (!property_parser.Parse(name, value)) - Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Syntax error parsing property declaration '%s: %s;' in %s: %d.", name.c_str(), value.c_str(), + stream_file_name.c_str(), line_number); } else if (!StringUtilities::StripWhitespace(name).empty() || !value.empty()) { - Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(), line_number); + Log::Message(Log::LT_WARNING, "Invalid property declaration '%s':'%s' at %s:%d", name.c_str(), value.c_str(), stream_file_name.c_str(), + line_number); } - + return true; } @@ -1043,7 +1037,6 @@ char StyleSheetParser::FindToken(String& buffer, const char* tokens, bool remove return 0; } -// Attempts to find the next character in the active stream. bool StyleSheetParser::ReadCharacter(char& buffer) { bool comment = false; @@ -1087,7 +1080,7 @@ bool StyleSheetParser::ReadCharacter(char& buffer) return true; } } - + if (parse_buffer[parse_buffer_pos] == '*') comment = true; else @@ -1111,13 +1104,11 @@ bool StyleSheetParser::ReadCharacter(char& buffer) parse_buffer_pos++; } - } - while (FillBuffer()); + } while (FillBuffer()); return false; } -// Fills the internal buffer with more content bool StyleSheetParser::FillBuffer() { // If theres no data to process, abort diff --git a/Source/Core/StyleSheetParser.h b/Source/Core/StyleSheetParser.h index 7d88d0fb1..6665d5a3d 100644 --- a/Source/Core/StyleSheetParser.h +++ b/Source/Core/StyleSheetParser.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,8 +29,8 @@ #ifndef RMLUI_CORE_STYLESHEETPARSER_H #define RMLUI_CORE_STYLESHEETPARSER_H -#include "../../Include/RmlUi/Core/Types.h" #include "../../Include/RmlUi/Core/StyleSheetTypes.h" +#include "../../Include/RmlUi/Core/Types.h" namespace Rml { @@ -42,13 +42,12 @@ struct PropertySource; using StyleSheetNodeListRaw = Vector; /** - Helper class for parsing a style sheet into its memory representation. + Helper class for parsing a style sheet into its memory representation. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class StyleSheetParser -{ +class StyleSheetParser { public: StyleSheetParser(); ~StyleSheetParser(); @@ -103,10 +102,11 @@ class StyleSheetParser static StyleSheetNode* ImportProperties(StyleSheetNode* node, const String& rule, const PropertyDictionary& properties, int rule_specificity); // Attempts to parse a @keyframes block - bool ParseKeyframeBlock(KeyframesMap & keyframes_map, const String & identifier, const String & rules, const PropertyDictionary & properties); + bool ParseKeyframeBlock(KeyframesMap& keyframes_map, const String& identifier, const String& rules, const PropertyDictionary& properties); // Attempts to parse a @decorator block - bool ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, const SharedPtr& source); + bool ParseDecoratorBlock(const String& at_name, DecoratorSpecificationMap& decorator_map, const StyleSheet& style_sheet, + const SharedPtr& source); // Attempts to parse the properties of a @media query bool ParseMediaFeatureMap(PropertyDictionary& properties, const String& rules); diff --git a/Source/Core/StyleSheetSelector.cpp b/Source/Core/StyleSheetSelector.cpp index 34c191361..6a4b56db8 100644 --- a/Source/Core/StyleSheetSelector.cpp +++ b/Source/Core/StyleSheetSelector.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/StyleSheetSelector.h b/Source/Core/StyleSheetSelector.h index ee4c427be..e84223393 100644 --- a/Source/Core/StyleSheetSelector.h +++ b/Source/Core/StyleSheetSelector.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/StyleSheetSpecification.cpp b/Source/Core/StyleSheetSpecification.cpp index b5d7599c8..be343cbbb 100644 --- a/Source/Core/StyleSheetSpecification.cpp +++ b/Source/Core/StyleSheetSpecification.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,25 +27,24 @@ */ #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" -#include "../../Include/RmlUi/Core/PropertyIdSet.h" #include "../../Include/RmlUi/Core/PropertyDefinition.h" -#include "PropertyParserNumber.h" +#include "../../Include/RmlUi/Core/PropertyIdSet.h" +#include "IdNameMap.h" #include "PropertyParserAnimation.h" -#include "PropertyParserRatio.h" #include "PropertyParserColour.h" #include "PropertyParserDecorator.h" #include "PropertyParserFontEffect.h" #include "PropertyParserKeyword.h" +#include "PropertyParserNumber.h" +#include "PropertyParserRatio.h" #include "PropertyParserString.h" #include "PropertyParserTransform.h" #include "PropertyShorthandDefinition.h" -#include "IdNameMap.h" namespace Rml { static StyleSheetSpecification* instance = nullptr; - struct DefaultStyleSheetParsers { PropertyParserNumber number = PropertyParserNumber(Property::NUMBER); PropertyParserNumber length = PropertyParserNumber(Property::LENGTH, Property::PX); @@ -64,7 +63,7 @@ struct DefaultStyleSheetParsers { PropertyParserNumber resolution = PropertyParserNumber(Property::X); }; -StyleSheetSpecification::StyleSheetSpecification() : +StyleSheetSpecification::StyleSheetSpecification() : // Reserve space for all defined ids and some more for custom properties properties((size_t)PropertyId::MaxNumIds, 2 * (size_t)ShorthandId::NumDefinedIds) { @@ -80,7 +79,8 @@ StyleSheetSpecification::~StyleSheetSpecification() instance = nullptr; } -PropertyDefinition& StyleSheetSpecification::RegisterProperty(PropertyId id, const String& property_name, const String& default_value, bool inherited, bool forces_layout) +PropertyDefinition& StyleSheetSpecification::RegisterProperty(PropertyId id, const String& property_name, const String& default_value, bool inherited, + bool forces_layout) { return properties.RegisterProperty(property_name, default_value, inherited, forces_layout, id); } @@ -111,7 +111,6 @@ void StyleSheetSpecification::Shutdown() } } -// Registers a parser for use in property definitions. bool StyleSheetSpecification::RegisterParser(const String& parser_name, PropertyParser* parser) { ParserMap::iterator iterator = instance->parsers.find(parser_name); @@ -125,7 +124,6 @@ bool StyleSheetSpecification::RegisterParser(const String& parser_name, Property return true; } -// Returns the parser registered with a specific name. PropertyParser* StyleSheetSpecification::GetParser(const String& parser_name) { ParserMap::iterator iterator = instance->parsers.find(parser_name); @@ -135,14 +133,14 @@ PropertyParser* StyleSheetSpecification::GetParser(const String& parser_name) return (*iterator).second; } -// Registers a property with a new definition. -PropertyDefinition& StyleSheetSpecification::RegisterProperty(const String& property_name, const String& default_value, bool inherited, bool forces_layout) +PropertyDefinition& StyleSheetSpecification::RegisterProperty(const String& property_name, const String& default_value, bool inherited, + bool forces_layout) { - RMLUI_ASSERTMSG((size_t)instance->properties.property_map->GetId(property_name) < (size_t)PropertyId::FirstCustomId, "Custom property name matches an internal property, please make a unique name for the given property."); - return instance->RegisterProperty(PropertyId::Invalid, property_name, default_value, inherited, forces_layout); + RMLUI_ASSERTMSG((size_t)instance->properties.property_map->GetId(property_name) < (size_t)PropertyId::FirstCustomId, + "Custom property name matches an internal property, please make a unique name for the given property."); + return instance->RegisterProperty(PropertyId::Invalid, property_name, default_value, inherited, forces_layout); } -// Returns a property definition. const PropertyDefinition* StyleSheetSpecification::GetProperty(const String& property_name) { return instance->properties.GetProperty(property_name); @@ -158,7 +156,7 @@ const PropertyIdSet& StyleSheetSpecification::GetRegisteredProperties() return instance->properties.GetRegisteredProperties(); } -const PropertyIdSet & StyleSheetSpecification::GetRegisteredInheritedProperties() +const PropertyIdSet& StyleSheetSpecification::GetRegisteredInheritedProperties() { return instance->properties.GetRegisteredInheritedProperties(); } @@ -168,15 +166,15 @@ const PropertyIdSet& StyleSheetSpecification::GetRegisteredPropertiesForcingLayo return instance->properties.GetRegisteredPropertiesForcingLayout(); } -// Registers a shorthand property definition. ShorthandId StyleSheetSpecification::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type) { - RMLUI_ASSERTMSG(instance->properties.property_map->GetId(shorthand_name) == PropertyId::Invalid, "Custom shorthand name matches a property name, please make a unique name."); - RMLUI_ASSERTMSG((size_t)instance->properties.shorthand_map->GetId(shorthand_name) < (size_t)ShorthandId::FirstCustomId, "Custom shorthand name matches an internal shorthand, please make a unique name for the given shorthand property."); + RMLUI_ASSERTMSG(instance->properties.property_map->GetId(shorthand_name) == PropertyId::Invalid, + "Custom shorthand name matches a property name, please make a unique name."); + RMLUI_ASSERTMSG((size_t)instance->properties.shorthand_map->GetId(shorthand_name) < (size_t)ShorthandId::FirstCustomId, + "Custom shorthand name matches an internal shorthand, please make a unique name for the given shorthand property."); return instance->properties.RegisterShorthand(shorthand_name, property_names, type); } -// Returns a shorthand definition. const ShorthandDefinition* StyleSheetSpecification::GetShorthand(const String& shorthand_name) { return instance->properties.GetShorthand(shorthand_name); @@ -187,7 +185,6 @@ const ShorthandDefinition* StyleSheetSpecification::GetShorthand(ShorthandId id) return instance->properties.GetShorthand(id); } -// Parses a property declaration, setting any parsed and validated properties on the given dictionary. bool StyleSheetSpecification::ParsePropertyDeclaration(PropertyDictionary& dictionary, const String& property_name, const String& property_value) { return instance->properties.ParsePropertyDeclaration(dictionary, property_name, property_value); @@ -240,7 +237,6 @@ const PropertySpecification& StyleSheetSpecification::GetPropertySpecification() return instance->properties; } -// Registers RmlUi's default parsers. void StyleSheetSpecification::RegisterDefaultParsers() { RegisterParser("number", &default_parsers->number); @@ -260,21 +256,20 @@ void StyleSheetSpecification::RegisterDefaultParsers() RegisterParser("resolution", &default_parsers->resolution); } - -// Registers RmlUi's default style properties. void StyleSheetSpecification::RegisterDefaultProperties() { - /* - Style property specifications (ala RCSS). + /* + Style property specifications (ala RCSS). - Note: Whenever keywords or default values are changed, make sure its computed value is - changed correspondingly, see `ComputedValues.h`. + Note: Whenever keywords or default values are changed, make sure its computed value is + changed correspondingly, see `ComputedValues.h`. - When adding new properties, it may be desirable to add it to the computed values as well. - Then, make sure to resolve it as appropriate in `ElementStyle.cpp`. + When adding new properties, it may be desirable to add it to the computed values as well. + Then, make sure to resolve it as appropriate in `ElementStyle.cpp`. */ + // clang-format off RegisterProperty(PropertyId::MarginTop, "margin-top", "0px", false, true) .AddParser("keyword", "auto") .AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); @@ -322,27 +317,17 @@ void StyleSheetSpecification::RegisterDefaultProperties() RegisterProperty(PropertyId::Display, "display", "inline", false, true) .AddParser("keyword", "none, block, inline, inline-block, flow-root, flex, inline-flex, table, inline-table, table-row, table-row-group, table-column, table-column-group, table-cell"); RegisterProperty(PropertyId::Position, "position", "static", false, true).AddParser("keyword", "static, relative, absolute, fixed"); - RegisterProperty(PropertyId::Top, "top", "auto", false, false) - .AddParser("keyword", "auto") - .AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight); - RegisterProperty(PropertyId::Right, "right", "auto", false, false) - .AddParser("keyword", "auto") - .AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); - RegisterProperty(PropertyId::Bottom, "bottom", "auto", false, false) - .AddParser("keyword", "auto") - .AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight); - RegisterProperty(PropertyId::Left, "left", "auto", false, false) - .AddParser("keyword", "auto") - .AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); + RegisterProperty(PropertyId::Top, "top", "auto", false, false).AddParser("keyword", "auto").AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight); + RegisterProperty(PropertyId::Right, "right", "auto", false, false).AddParser("keyword", "auto").AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); + RegisterProperty(PropertyId::Bottom, "bottom", "auto", false, false).AddParser("keyword", "auto").AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight); + RegisterProperty(PropertyId::Left, "left", "auto", false, false).AddParser("keyword", "auto").AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); RegisterProperty(PropertyId::Float, "float", "none", false, true).AddParser("keyword", "none, left, right"); RegisterProperty(PropertyId::Clear, "clear", "none", false, true).AddParser("keyword", "none, left, right, both"); RegisterProperty(PropertyId::BoxSizing, "box-sizing", "content-box", false, true).AddParser("keyword", "content-box, border-box"); - RegisterProperty(PropertyId::ZIndex, "z-index", "auto", false, false) - .AddParser("keyword", "auto") - .AddParser("number"); + RegisterProperty(PropertyId::ZIndex, "z-index", "auto", false, false).AddParser("keyword", "auto").AddParser("number"); RegisterProperty(PropertyId::Width, "width", "auto", false, true).AddParser("keyword", "auto").AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); RegisterProperty(PropertyId::MinWidth, "min-width", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth); @@ -440,6 +425,7 @@ void StyleSheetSpecification::RegisterDefaultProperties() RMLUI_ASSERTMSG(instance->properties.shorthand_map->AssertAllInserted(ShorthandId::NumDefinedIds), "Missing specification for one or more Shorthand IDs."); RMLUI_ASSERTMSG(instance->properties.property_map->AssertAllInserted(PropertyId::NumDefinedIds), "Missing specification for one or more Property IDs."); + // clang-format on } } // namespace Rml diff --git a/Source/Core/SystemInterface.cpp b/Source/Core/SystemInterface.cpp index 74efc9e51..72456adb8 100644 --- a/Source/Core/SystemInterface.cpp +++ b/Source/Core/SystemInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,37 +32,33 @@ #include "../../Include/RmlUi/Core/URL.h" #ifdef RMLUI_PLATFORM_WIN32 -#include + #include #else -#include + #include #endif namespace Rml { static String clipboard_text; -SystemInterface::SystemInterface() -{ -} +SystemInterface::SystemInterface() {} -SystemInterface::~SystemInterface() -{ -} +SystemInterface::~SystemInterface() {} #ifdef RMLUI_PLATFORM_WIN32 bool SystemInterface::LogMessage(Log::Type logtype, const String& message) { // By default we just send a platform message -#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) + #if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) if (logtype == Log::LT_ASSERT) { - String message_user = CreateString(1024, "%s\nWould you like to interrupt execution?", message.c_str()); + String message_user = CreateString(1024, "%s\nWould you like to interrupt execution?", message.c_str()); // Return TRUE if the user presses NO (continue execution) return (IDNO == MessageBoxA(nullptr, message_user.c_str(), "Assertion Failure", MB_YESNO | MB_ICONSTOP | MB_DEFBUTTON2 | MB_TASKMODAL)); } else -#endif + #endif { OutputDebugStringA(message.c_str()); OutputDebugStringA("\r\n"); @@ -72,18 +68,16 @@ bool SystemInterface::LogMessage(Log::Type logtype, const String& message) #else bool SystemInterface::LogMessage(Log::Type /*logtype*/, const String& message) { -#ifdef RMLUI_PLATFORM_EMSCRIPTEN + #ifdef RMLUI_PLATFORM_EMSCRIPTEN puts(message.c_str()); -#else + #else fprintf(stderr, "%s\n", message.c_str()); -#endif + #endif return true; } -#endif +#endif -void SystemInterface::SetMouseCursor(const String& /*cursor_name*/) -{ -} +void SystemInterface::SetMouseCursor(const String& /*cursor_name*/) {} void SystemInterface::SetClipboardText(const String& text) { @@ -114,8 +108,7 @@ void SystemInterface::JoinPath(String& translated_path, const String& document_p // If the path is a Windows-style absolute path, return it directly. size_t drive_pos = path.find(':'); size_t slash_pos = Math::Min(path.find('/'), path.find('\\')); - if (drive_pos != String::npos && - drive_pos < slash_pos) + if (drive_pos != String::npos && drive_pos < slash_pos) { translated_path = path; return; diff --git a/Source/Core/Template.cpp b/Source/Core/Template.cpp index 163e3b28b..afc7d5db6 100644 --- a/Source/Core/Template.cpp +++ b/Source/Core/Template.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,20 +27,16 @@ */ #include "Template.h" -#include "XMLParseTools.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" #include "../../Include/RmlUi/Core/XMLParser.h" +#include "XMLParseTools.h" #include namespace Rml { -Template::Template() -{ -} +Template::Template() {} -Template::~Template() -{ -} +Template::~Template() {} const String& Template::GetName() const { @@ -51,25 +47,25 @@ bool Template::Load(Stream* stream) { // Load the entire template into memory so we can pull out // the header and body tags - String buffer; + String buffer; stream->Read(buffer, stream->Length()); // Pull out the header const char* head_start = XMLParseTools::FindTag("head", buffer.c_str()); - if (!head_start) + if (!head_start) return false; const char* head_end = XMLParseTools::FindTag("head", head_start, true); - if (!head_end) + if (!head_end) return false; // Advance to the end of the tag head_end = strchr(head_end, '>') + 1; - // Pull out the body + // Pull out the body const char* body_start = XMLParseTools::FindTag("body", head_end); - if (!body_start) + if (!body_start) return false; - + const char* body_end = XMLParseTools::FindTag("body", body_start, true); if (!body_end) return false; @@ -93,7 +89,7 @@ bool Template::Load(Stream* stream) } // Create a stream around the header, parse it and store it - auto header_stream = MakeUnique((const byte*) head_start,head_end - head_start); + auto header_stream = MakeUnique((const byte*)head_start, head_end - head_start); header_stream->SetSourceURL(stream->GetSourceURL()); XMLParser parser(nullptr); @@ -104,7 +100,7 @@ bool Template::Load(Stream* stream) header = *parser.GetDocumentHeader(); // Store the body in stream form - body = MakeUnique(body_end - body_start); + body = MakeUnique(body_end - body_start); body->SetSourceURL(stream->GetSourceURL()); body->PushBack(body_start, body_end - body_start); @@ -118,7 +114,7 @@ Element* Template::ParseTemplate(Element* element) XMLParser parser(element); parser.Parse(body.get()); - // If theres an inject attribute on the template, + // If theres an inject attribute on the template, // attempt to find the required element if (!content.empty()) { diff --git a/Source/Core/Template.h b/Source/Core/Template.h index d86741856..dbc5e1833 100644 --- a/Source/Core/Template.h +++ b/Source/Core/Template.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ namespace Rml { class Element; /** - Contains a RML template. The Header is stored in parsed form, body in an unparsed stream. + Contains a RML template. The Header is stored in parsed form, body in an unparsed stream. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class Template -{ +class Template { public: Template(); ~Template(); diff --git a/Source/Core/TemplateCache.cpp b/Source/Core/TemplateCache.cpp index b93ba75c7..d9699f7d8 100644 --- a/Source/Core/TemplateCache.cpp +++ b/Source/Core/TemplateCache.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,9 +27,9 @@ */ #include "TemplateCache.h" +#include "../../Include/RmlUi/Core/Log.h" #include "StreamFile.h" #include "Template.h" -#include "../../Include/RmlUi/Core/Log.h" namespace Rml { @@ -96,7 +96,7 @@ Template* TemplateCache::LoadTemplate(const String& name) } else { - Log::Message(Log::LT_ERROR, "Failed to open template file %s.", name.c_str()); + Log::Message(Log::LT_ERROR, "Failed to open template file %s.", name.c_str()); } return new_template; diff --git a/Source/Core/TemplateCache.h b/Source/Core/TemplateCache.h index bf1124ad9..ed0d5b1aa 100644 --- a/Source/Core/TemplateCache.h +++ b/Source/Core/TemplateCache.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,12 @@ namespace Rml { class Template; /** - Manages requests for loading templates, caching as it goes. + Manages requests for loading templates, caching as it goes. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class TemplateCache -{ +class TemplateCache { public: /// Initialisation and Shutdown static bool Initialise(); diff --git a/Source/Core/Texture.cpp b/Source/Core/Texture.cpp index 01c5a11f8..2f4203fb0 100644 --- a/Source/Core/Texture.cpp +++ b/Source/Core/Texture.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,7 +32,6 @@ namespace Rml { -// Attempts to load a texture. void Texture::Set(const String& source, const String& source_path) { resource = TextureDatabase::Fetch(source, source_path); @@ -44,7 +43,6 @@ void Texture::Set(const String& name, const TextureCallback& callback) resource->Set(name, callback); } -// Returns the texture's source name. This is usually the name of the file the texture was loaded from. const String& Texture::GetSource() const { static String empty_string; @@ -54,7 +52,6 @@ const String& Texture::GetSource() const return resource->GetSource(); } -// Returns the texture's handle. TextureHandle Texture::GetHandle(RenderInterface* render_interface) const { if (!resource) @@ -63,7 +60,6 @@ TextureHandle Texture::GetHandle(RenderInterface* render_interface) const return resource->GetHandle(render_interface); } -// Returns the texture's dimensions. Vector2i Texture::GetDimensions(RenderInterface* render_interface) const { if (!resource) diff --git a/Source/Core/TextureDatabase.cpp b/Source/Core/TextureDatabase.cpp index 9111ccc1f..8319466b5 100644 --- a/Source/Core/TextureDatabase.cpp +++ b/Source/Core/TextureDatabase.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/TextureDatabase.h b/Source/Core/TextureDatabase.h index 8ac85e4a8..d2daa49a9 100644 --- a/Source/Core/TextureDatabase.h +++ b/Source/Core/TextureDatabase.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/TextureLayout.cpp b/Source/Core/TextureLayout.cpp index ddb0b508b..cf3f60882 100644 --- a/Source/Core/TextureLayout.cpp +++ b/Source/Core/TextureLayout.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,29 +33,22 @@ namespace Rml { -struct RectangleSort -{ +struct RectangleSort { bool operator()(const TextureLayoutRectangle& lhs, const TextureLayoutRectangle& rhs) const { return lhs.GetDimensions().y > rhs.GetDimensions().y; } }; -TextureLayout::TextureLayout() -{ -} +TextureLayout::TextureLayout() {} -TextureLayout::~TextureLayout() -{ -} +TextureLayout::~TextureLayout() {} -// Adds a rectangle to the list of rectangles to be laid out. void TextureLayout::AddRectangle(int id, Vector2i dimensions) { rectangles.push_back(TextureLayoutRectangle(id, dimensions)); } -// Returns one of the layout's rectangles. TextureLayoutRectangle& TextureLayout::GetRectangle(int index) { RMLUI_ASSERT(index >= 0); @@ -64,13 +57,11 @@ TextureLayoutRectangle& TextureLayout::GetRectangle(int index) return rectangles[index]; } -// Returns the number of rectangles in the layout. int TextureLayout::GetNumRectangles() const { - return (int) rectangles.size(); + return (int)rectangles.size(); } -// Returns one of the layout's textures. TextureLayoutTexture& TextureLayout::GetTexture(int index) { RMLUI_ASSERT(index >= 0); @@ -79,13 +70,11 @@ TextureLayoutTexture& TextureLayout::GetTexture(int index) return textures[index]; } -// Returns the number of textures in the layout. int TextureLayout::GetNumTextures() const { - return (int) textures.size(); + return (int)textures.size(); } -// Attempts to generate an efficient texture layout for the rectangles. bool TextureLayout::GenerateLayout(int max_texture_dimensions) { // Sort the rectangles by height. diff --git a/Source/Core/TextureLayout.h b/Source/Core/TextureLayout.h index 63da9940b..2db0f8f96 100644 --- a/Source/Core/TextureLayout.h +++ b/Source/Core/TextureLayout.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,14 +35,13 @@ namespace Rml { /** - A texture layout generates and stores a layout of rectangles within a series of textures. It is - used primarily by the font system for generating font textures. + A texture layout generates and stores a layout of rectangles within a series of textures. It is + used primarily by the font system for generating font textures. - @author Peter + @author Peter */ -class TextureLayout -{ +class TextureLayout { public: TextureLayout(); ~TextureLayout(); @@ -75,8 +74,8 @@ class TextureLayout bool GenerateLayout(int max_texture_dimensions); private: - using RectangleList = Vector< TextureLayoutRectangle >; - using TextureList = Vector< TextureLayoutTexture >; + using RectangleList = Vector; + using TextureList = Vector; TextureList textures; RectangleList rectangles; diff --git a/Source/Core/TextureLayoutRectangle.cpp b/Source/Core/TextureLayoutRectangle.cpp index 1b72df972..7f0579b7c 100644 --- a/Source/Core/TextureLayoutRectangle.cpp +++ b/Source/Core/TextureLayoutRectangle.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,67 +39,55 @@ TextureLayoutRectangle::TextureLayoutRectangle(const int _id, const Vector2i dim texture_stride = 0; } -TextureLayoutRectangle::~TextureLayoutRectangle() -{ -} +TextureLayoutRectangle::~TextureLayoutRectangle() {} -// Returns the rectangle's id. int TextureLayoutRectangle::GetId() const { return id; } -// Returns the rectangle's position; this is only valid if it has been placed. Vector2i TextureLayoutRectangle::GetPosition() const { return texture_position; } -// Returns the rectangle's dimensions. Vector2i TextureLayoutRectangle::GetDimensions() const { return dimensions; } -// Places the rectangle within a texture. void TextureLayoutRectangle::Place(const int _texture_index, const Vector2i position) { texture_index = _texture_index; texture_position = position; } -// Unplaces the rectangle. void TextureLayoutRectangle::Unplace() { texture_index = -1; } -// Returns the rectangle's placed state. bool TextureLayoutRectangle::IsPlaced() const { return texture_index > -1; } -// Sets the rectangle's texture data and stride. void TextureLayoutRectangle::Allocate(byte* _texture_data, int _texture_stride) { texture_data = _texture_data + ((texture_position.y * _texture_stride) + texture_position.x * 4); texture_stride = _texture_stride; } -// Returns the index of the texture this rectangle is placed on. int TextureLayoutRectangle::GetTextureIndex() { return texture_index; } -// Returns the rectangle's allocated texture data. byte* TextureLayoutRectangle::GetTextureData() { return texture_data; } -// Returns the stride of the rectangle's texture data. int TextureLayoutRectangle::GetTextureStride() const { return texture_stride; diff --git a/Source/Core/TextureLayoutRectangle.h b/Source/Core/TextureLayoutRectangle.h index 82979d448..b6a728154 100644 --- a/Source/Core/TextureLayoutRectangle.h +++ b/Source/Core/TextureLayoutRectangle.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - A texture layout rectangle is an area positioned with a texture layout. + A texture layout rectangle is an area positioned with a texture layout. - @author Peter + @author Peter */ -class TextureLayoutRectangle -{ +class TextureLayoutRectangle { public: TextureLayoutRectangle(int id, Vector2i dimensions); ~TextureLayoutRectangle(); diff --git a/Source/Core/TextureLayoutRow.cpp b/Source/Core/TextureLayoutRow.cpp index 860c92bbc..48b1e75f1 100644 --- a/Source/Core/TextureLayoutRow.cpp +++ b/Source/Core/TextureLayoutRow.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,11 +36,8 @@ TextureLayoutRow::TextureLayoutRow() height = 0; } -TextureLayoutRow::~TextureLayoutRow() -{ -} +TextureLayoutRow::~TextureLayoutRow() {} -// Attempts to position unplaced rectangles from the layout into this row. int TextureLayoutRow::Generate(TextureLayout& layout, int max_width, int y) { int width = 1; @@ -85,20 +82,17 @@ int TextureLayoutRow::Generate(TextureLayout& layout, int max_width, int y) return placed_rectangles; } -// Assigns allocated texture data to all rectangles in this row. void TextureLayoutRow::Allocate(byte* texture_data, int stride) { for (size_t i = 0; i < rectangles.size(); ++i) rectangles[i]->Allocate(texture_data, stride); } -// Returns the height of the row. int TextureLayoutRow::GetHeight() const { return height; } -// Resets the placed status for all of the rectangles within this row. void TextureLayoutRow::Unplace() { for (size_t i = 0; i < rectangles.size(); ++i) diff --git a/Source/Core/TextureLayoutRow.h b/Source/Core/TextureLayoutRow.h index ff852781a..ba2b50f58 100644 --- a/Source/Core/TextureLayoutRow.h +++ b/Source/Core/TextureLayoutRow.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,12 @@ namespace Rml { class TextureLayout; /** - A texture layout row is a single row of rectangles positioned vertically within a texture. + A texture layout row is a single row of rectangles positioned vertically within a texture. - @author Peter + @author Peter */ -class TextureLayoutRow -{ +class TextureLayoutRow { public: TextureLayoutRow(); ~TextureLayoutRow(); @@ -67,7 +66,7 @@ class TextureLayoutRow void Unplace(); private: - using RectangleList = Vector< TextureLayoutRectangle* >; + using RectangleList = Vector; int height; RectangleList rectangles; diff --git a/Source/Core/TextureLayoutTexture.cpp b/Source/Core/TextureLayoutTexture.cpp index 5b6f30cb8..7135eb5e0 100644 --- a/Source/Core/TextureLayoutTexture.cpp +++ b/Source/Core/TextureLayoutTexture.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,21 +32,18 @@ namespace Rml { -TextureLayoutTexture::TextureLayoutTexture() : dimensions(0, 0) -{} +TextureLayoutTexture::TextureLayoutTexture() : dimensions(0, 0) {} TextureLayoutTexture::~TextureLayoutTexture() { // Don't free texture data; freed in the texture loader. } -// Returns the texture's dimensions. This is only valid after the texture has been generated. Vector2i TextureLayoutTexture::GetDimensions() const { return dimensions; } -// Attempts to position unplaced rectangles from the layout into this texture. int TextureLayoutTexture::Generate(TextureLayout& layout, int maximum_dimensions) { // Come up with an estimate for how big a texture we need. Calculate the total square pixels @@ -64,12 +61,12 @@ int TextureLayoutTexture::Generate(TextureLayout& layout, int maximum_dimensions int x = rectangle.GetDimensions().x + 1; int y = rectangle.GetDimensions().y + 1; - square_pixels += x*y; + square_pixels += x * y; ++unplaced_rectangles; } } - int texture_width = Math::RealToInteger(Math::SquareRoot((float) square_pixels)); + int texture_width = Math::RealToInteger(Math::SquareRoot((float)square_pixels)); dimensions.y = Math::ToPowerOfTwo(texture_width); dimensions.x = dimensions.y >> 1; @@ -135,14 +132,12 @@ int TextureLayoutTexture::Generate(TextureLayout& layout, int maximum_dimensions } } -// Allocates the texture. UniquePtr TextureLayoutTexture::AllocateTexture() { // Note: this object does not free this texture data. It is freed in the font texture loader. UniquePtr texture_data; - if (dimensions.x > 0 && - dimensions.y > 0) + if (dimensions.x > 0 && dimensions.y > 0) { texture_data.reset(new byte[dimensions.x * dimensions.y * 4]); diff --git a/Source/Core/TextureLayoutTexture.h b/Source/Core/TextureLayoutTexture.h index ac00debc3..e5c3b9e2a 100644 --- a/Source/Core/TextureLayoutTexture.h +++ b/Source/Core/TextureLayoutTexture.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,14 +38,13 @@ class TextureLayout; class TextureResource; /** - A texture layout texture is a single rectangular area which sub-rectangles are placed on within - a complete texture layout. + A texture layout texture is a single rectangular area which sub-rectangles are placed on within + a complete texture layout. - @author Peter + @author Peter */ -class TextureLayoutTexture -{ +class TextureLayoutTexture { public: TextureLayoutTexture(); ~TextureLayoutTexture(); @@ -57,7 +56,8 @@ class TextureLayoutTexture /// Attempts to position unplaced rectangles from the layout into this texture. The size of /// this texture will be determined by its contents. /// @param[in] layout The layout to position rectangles from. - /// @param[in] maximum_dimensions The maximum dimensions of this texture. If this is not big enough to place all the rectangles, then as many will be placed as possible. + /// @param[in] maximum_dimensions The maximum dimensions of this texture. If this is not big enough to place all the rectangles, then as many will + /// be placed as possible. /// @return The number of placed rectangles. int Generate(TextureLayout& layout, int maximum_dimensions); @@ -66,7 +66,7 @@ class TextureLayoutTexture UniquePtr AllocateTexture(); private: - using RowList = Vector< TextureLayoutRow >; + using RowList = Vector; Vector2i dimensions; RowList rows; diff --git a/Source/Core/TextureResource.cpp b/Source/Core/TextureResource.cpp index 6b6d8c80c..a8126caf6 100644 --- a/Source/Core/TextureResource.cpp +++ b/Source/Core/TextureResource.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,16 +27,14 @@ */ #include "TextureResource.h" -#include "TextureDatabase.h" #include "../../Include/RmlUi/Core/Log.h" -#include "../../Include/RmlUi/Core/RenderInterface.h" #include "../../Include/RmlUi/Core/Profiling.h" +#include "../../Include/RmlUi/Core/RenderInterface.h" +#include "TextureDatabase.h" namespace Rml { -TextureResource::TextureResource() -{ -} +TextureResource::TextureResource() {} TextureResource::~TextureResource() { @@ -70,7 +68,6 @@ void TextureResource::Reset() source.clear(); } -// Returns the resource's underlying texture. TextureHandle TextureResource::GetHandle(RenderInterface* render_interface) { auto texture_iterator = texture_data.find(render_interface); @@ -83,7 +80,6 @@ TextureHandle TextureResource::GetHandle(RenderInterface* render_interface) return texture_iterator->second.first; } -// Returns the dimensions of the resource's texture. Vector2i TextureResource::GetDimensions(RenderInterface* render_interface) { auto texture_iterator = texture_data.find(render_interface); @@ -96,13 +92,11 @@ Vector2i TextureResource::GetDimensions(RenderInterface* render_interface) return texture_iterator->second.second; } -// Returns the resource's source. const String& TextureResource::GetSource() const { return source; } -// Releases the texture's handle. void TextureResource::Release(RenderInterface* render_interface) { if (!render_interface) diff --git a/Source/Core/TextureResource.h b/Source/Core/TextureResource.h index 727b79fc7..b8e875a1e 100644 --- a/Source/Core/TextureResource.h +++ b/Source/Core/TextureResource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Source/Core/Transform.cpp b/Source/Core/Transform.cpp index a6350f9c4..8c33c788d 100644 --- a/Source/Core/Transform.cpp +++ b/Source/Core/Transform.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,21 +27,15 @@ */ #include "../../Include/RmlUi/Core/Transform.h" +#include "../../Include/RmlUi/Core/Property.h" #include "../../Include/RmlUi/Core/StyleSheetSpecification.h" #include "../../Include/RmlUi/Core/TransformPrimitive.h" -#include "../../Include/RmlUi/Core/Property.h" namespace Rml { -// Default constructor, initializes an identity transform -Transform::Transform() -{ -} +Transform::Transform() {} -Transform::Transform(PrimitiveList primitives) - : primitives(std::move(primitives)) -{ -} +Transform::Transform(PrimitiveList primitives) : primitives(std::move(primitives)) {} Property Transform::MakeProperty(PrimitiveList primitives) { @@ -50,22 +44,22 @@ Property Transform::MakeProperty(PrimitiveList primitives) return p; } -void Transform::ClearPrimitives() +void Transform::ClearPrimitives() { primitives.clear(); } -void Transform::AddPrimitive(const TransformPrimitive & p) +void Transform::AddPrimitive(const TransformPrimitive& p) { primitives.push_back(p); } -int Transform::GetNumPrimitives() const noexcept +int Transform::GetNumPrimitives() const noexcept { return (int)primitives.size(); } -const TransformPrimitive & Transform::GetPrimitive(int i) const noexcept +const TransformPrimitive& Transform::GetPrimitive(int i) const noexcept { return primitives[i]; } diff --git a/Source/Core/TransformPrimitive.cpp b/Source/Core/TransformPrimitive.cpp index d47cab05b..8c5d1ad58 100644 --- a/Source/Core/TransformPrimitive.cpp +++ b/Source/Core/TransformPrimitive.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,150 +33,148 @@ namespace Rml { namespace Transforms { - -/// Returns the numeric value converted to 'base_unit'. Only accepts base units of 'Number' or 'Rad': -/// 'Number' will pass-through the provided value. -/// 'Rad' will convert {Rad, Deg, %} -> Rad. -static float ResolvePrimitiveAbsoluteValue(NumericValue value, Property::Unit base_unit) noexcept -{ - RMLUI_ASSERT(base_unit == Property::RAD || base_unit == Property::NUMBER); - - if (base_unit == Property::RAD) + /// Returns the numeric value converted to 'base_unit'. Only accepts base units of 'Number' or 'Rad': + /// 'Number' will pass-through the provided value. + /// 'Rad' will convert {Rad, Deg, %} -> Rad. + static float ResolvePrimitiveAbsoluteValue(NumericValue value, Property::Unit base_unit) noexcept { - switch (value.unit) + RMLUI_ASSERT(base_unit == Property::RAD || base_unit == Property::NUMBER); + + if (base_unit == Property::RAD) + { + switch (value.unit) + { + case Property::RAD: return value.number; + case Property::DEG: return Math::DegreesToRadians(value.number); + case Property::PERCENT: return value.number * 0.01f * 2.0f * Math::RMLUI_PI; + default: Log::Message(Log::LT_WARNING, "Trying to pass a non-angle unit to a property expecting an angle."); + } + } + else if (base_unit == Property::NUMBER && value.unit != Property::NUMBER) { - case Property::RAD: - return value.number; - case Property::DEG: - return Math::DegreesToRadians(value.number); - case Property::PERCENT: - return value.number * 0.01f * 2.0f * Math::RMLUI_PI; - default: - Log::Message(Log::LT_WARNING, "Trying to pass a non-angle unit to a property expecting an angle."); + Log::Message(Log::LT_WARNING, "A unit was passed to a property which expected a unit-less number."); } + + return value.number; } - else if (base_unit == Property::NUMBER && value.unit != Property::NUMBER) + + template + inline ResolvedPrimitive::ResolvedPrimitive(const float* values) noexcept { - Log::Message(Log::LT_WARNING, "A unit was passed to a property which expected a unit-less number."); + for (size_t i = 0; i < N; ++i) + this->values[i] = values[i]; } - return value.number; -} - - -template -inline ResolvedPrimitive::ResolvedPrimitive(const float* values) noexcept -{ - for (size_t i = 0; i < N; ++i) - this->values[i] = values[i]; -} - -template -inline ResolvedPrimitive::ResolvedPrimitive(const NumericValue* values) noexcept -{ - for (size_t i = 0; i < N; ++i) - this->values[i] = values[i].number; -} - -template -inline ResolvedPrimitive::ResolvedPrimitive(const NumericValue* values, Array base_units) noexcept -{ - for (size_t i = 0; i < N; ++i) - this->values[i] = ResolvePrimitiveAbsoluteValue(values[i], base_units[i]); -} - -template -inline ResolvedPrimitive::ResolvedPrimitive(Array values, Array base_units) noexcept -{ - for (size_t i = 0; i < N; ++i) - this->values[i] = ResolvePrimitiveAbsoluteValue(values[i], base_units[i]); -} + template + inline ResolvedPrimitive::ResolvedPrimitive(const NumericValue* values) noexcept + { + for (size_t i = 0; i < N; ++i) + this->values[i] = values[i].number; + } -template -inline ResolvedPrimitive::ResolvedPrimitive(Array values) noexcept : values(values) { } + template + inline ResolvedPrimitive::ResolvedPrimitive(const NumericValue* values, Array base_units) noexcept + { + for (size_t i = 0; i < N; ++i) + this->values[i] = ResolvePrimitiveAbsoluteValue(values[i], base_units[i]); + } -template -inline UnresolvedPrimitive::UnresolvedPrimitive(const NumericValue* values) noexcept -{ - for (size_t i = 0; i < N; ++i) - this->values[i] = values[i]; -} + template + inline ResolvedPrimitive::ResolvedPrimitive(Array values, Array base_units) noexcept + { + for (size_t i = 0; i < N; ++i) + this->values[i] = ResolvePrimitiveAbsoluteValue(values[i], base_units[i]); + } -template -inline UnresolvedPrimitive::UnresolvedPrimitive(Array values) noexcept : values(values) { } + template + inline ResolvedPrimitive::ResolvedPrimitive(Array values) noexcept : values(values) + {} + template + inline UnresolvedPrimitive::UnresolvedPrimitive(const NumericValue* values) noexcept + { + for (size_t i = 0; i < N; ++i) + this->values[i] = values[i]; + } -Matrix2D::Matrix2D(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } + template + inline UnresolvedPrimitive::UnresolvedPrimitive(Array values) noexcept : values(values) + {} -Matrix3D::Matrix3D(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } -Matrix3D::Matrix3D(const Matrix4f& matrix) noexcept : ResolvedPrimitive(matrix.data()) { } + Matrix2D::Matrix2D(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} -TranslateX::TranslateX(const NumericValue* values) noexcept : UnresolvedPrimitive(values) { } -TranslateX::TranslateX(float x, Property::Unit unit) noexcept : UnresolvedPrimitive({ NumericValue(x, unit) }) { } + Matrix3D::Matrix3D(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} + Matrix3D::Matrix3D(const Matrix4f& matrix) noexcept : ResolvedPrimitive(matrix.data()) {} -TranslateY::TranslateY(const NumericValue* values) noexcept : UnresolvedPrimitive(values) { } -TranslateY::TranslateY(float y, Property::Unit unit) noexcept : UnresolvedPrimitive({ NumericValue(y, unit) }) { } + TranslateX::TranslateX(const NumericValue* values) noexcept : UnresolvedPrimitive(values) {} + TranslateX::TranslateX(float x, Property::Unit unit) noexcept : UnresolvedPrimitive({NumericValue(x, unit)}) {} -TranslateZ::TranslateZ(const NumericValue* values) noexcept : UnresolvedPrimitive(values) { } -TranslateZ::TranslateZ(float z, Property::Unit unit) noexcept : UnresolvedPrimitive({ NumericValue(z, unit) }) { } + TranslateY::TranslateY(const NumericValue* values) noexcept : UnresolvedPrimitive(values) {} + TranslateY::TranslateY(float y, Property::Unit unit) noexcept : UnresolvedPrimitive({NumericValue(y, unit)}) {} -Translate2D::Translate2D(const NumericValue* values) noexcept : UnresolvedPrimitive(values) { } -Translate2D::Translate2D(float x, float y, Property::Unit units) noexcept : UnresolvedPrimitive({ NumericValue(x, units), NumericValue(y, units) }) { } + TranslateZ::TranslateZ(const NumericValue* values) noexcept : UnresolvedPrimitive(values) {} + TranslateZ::TranslateZ(float z, Property::Unit unit) noexcept : UnresolvedPrimitive({NumericValue(z, unit)}) {} -Translate3D::Translate3D(const NumericValue* values) noexcept : UnresolvedPrimitive(values) { } -Translate3D::Translate3D(NumericValue x, NumericValue y, NumericValue z) noexcept : UnresolvedPrimitive({ x, y, z }) { } -Translate3D::Translate3D(float x, float y, float z, Property::Unit units) noexcept - : UnresolvedPrimitive({ NumericValue(x, units), NumericValue(y, units), NumericValue(z, units) }) { } + Translate2D::Translate2D(const NumericValue* values) noexcept : UnresolvedPrimitive(values) {} + Translate2D::Translate2D(float x, float y, Property::Unit units) noexcept : UnresolvedPrimitive({NumericValue(x, units), NumericValue(y, units)}) + {} -ScaleX::ScaleX(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } -ScaleX::ScaleX(float value) noexcept : ResolvedPrimitive({ value }) { } + Translate3D::Translate3D(const NumericValue* values) noexcept : UnresolvedPrimitive(values) {} + Translate3D::Translate3D(NumericValue x, NumericValue y, NumericValue z) noexcept : UnresolvedPrimitive({x, y, z}) {} + Translate3D::Translate3D(float x, float y, float z, Property::Unit units) noexcept : + UnresolvedPrimitive({NumericValue(x, units), NumericValue(y, units), NumericValue(z, units)}) + {} -ScaleY::ScaleY(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } -ScaleY::ScaleY(float value) noexcept : ResolvedPrimitive({ value }) { } + ScaleX::ScaleX(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} + ScaleX::ScaleX(float value) noexcept : ResolvedPrimitive({value}) {} -ScaleZ::ScaleZ(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } -ScaleZ::ScaleZ(float value) noexcept : ResolvedPrimitive({ value }) { } + ScaleY::ScaleY(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} + ScaleY::ScaleY(float value) noexcept : ResolvedPrimitive({value}) {} -Scale2D::Scale2D(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } -Scale2D::Scale2D(float xy) noexcept : ResolvedPrimitive({ xy, xy }) { } -Scale2D::Scale2D(float x, float y) noexcept : ResolvedPrimitive({ x, y }) { } + ScaleZ::ScaleZ(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} + ScaleZ::ScaleZ(float value) noexcept : ResolvedPrimitive({value}) {} -Scale3D::Scale3D(const NumericValue* values) noexcept : ResolvedPrimitive(values) { } -Scale3D::Scale3D(float xyz) noexcept : ResolvedPrimitive({ xyz, xyz, xyz }) { } -Scale3D::Scale3D(float x, float y, float z) noexcept : ResolvedPrimitive({ x, y, z }) { } + Scale2D::Scale2D(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} + Scale2D::Scale2D(float xy) noexcept : ResolvedPrimitive({xy, xy}) {} + Scale2D::Scale2D(float x, float y) noexcept : ResolvedPrimitive({x, y}) {} -RotateX::RotateX(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD }) { } -RotateX::RotateX(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({ NumericValue{ angle, unit } }, { Property::RAD }) { } + Scale3D::Scale3D(const NumericValue* values) noexcept : ResolvedPrimitive(values) {} + Scale3D::Scale3D(float xyz) noexcept : ResolvedPrimitive({xyz, xyz, xyz}) {} + Scale3D::Scale3D(float x, float y, float z) noexcept : ResolvedPrimitive({x, y, z}) {} -RotateY::RotateY(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD }) {} -RotateY::RotateY(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({ NumericValue{ angle, unit } }, { Property::RAD }) { } + RotateX::RotateX(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD}) {} + RotateX::RotateX(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({NumericValue{angle, unit}}, {Property::RAD}) {} -RotateZ::RotateZ(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD }) { } -RotateZ::RotateZ(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({ NumericValue{ angle, unit } }, { Property::RAD }) { } + RotateY::RotateY(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD}) {} + RotateY::RotateY(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({NumericValue{angle, unit}}, {Property::RAD}) {} -Rotate2D::Rotate2D(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD }) { } -Rotate2D::Rotate2D(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({ NumericValue{ angle, unit } }, { Property::RAD }) { } + RotateZ::RotateZ(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD}) {} + RotateZ::RotateZ(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({NumericValue{angle, unit}}, {Property::RAD}) {} -Rotate3D::Rotate3D(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::NUMBER, Property::NUMBER, Property::NUMBER, Property::RAD }) { } -Rotate3D::Rotate3D(float x, float y, float z, float angle, Property::Unit angle_unit) noexcept - : ResolvedPrimitive( - { NumericValue{x, Property::NUMBER}, NumericValue{y, Property::NUMBER}, NumericValue{z, Property::NUMBER}, NumericValue{angle, angle_unit} }, - { Property::NUMBER, Property::NUMBER, Property::NUMBER, Property::RAD } - ) -{ } + Rotate2D::Rotate2D(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD}) {} + Rotate2D::Rotate2D(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({NumericValue{angle, unit}}, {Property::RAD}) {} -SkewX::SkewX(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD }) { } -SkewX::SkewX(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({ NumericValue{ angle, unit } }, { Property::RAD }) { } + Rotate3D::Rotate3D(const NumericValue* values) noexcept : + ResolvedPrimitive(values, {Property::NUMBER, Property::NUMBER, Property::NUMBER, Property::RAD}) + {} + Rotate3D::Rotate3D(float x, float y, float z, float angle, Property::Unit angle_unit) noexcept : + ResolvedPrimitive({NumericValue{x, Property::NUMBER}, NumericValue{y, Property::NUMBER}, NumericValue{z, Property::NUMBER}, + NumericValue{angle, angle_unit}}, + {Property::NUMBER, Property::NUMBER, Property::NUMBER, Property::RAD}) + {} -SkewY::SkewY(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD }) { } -SkewY::SkewY(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({ NumericValue{ angle, unit } }, { Property::RAD }) { } + SkewX::SkewX(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD}) {} + SkewX::SkewX(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({NumericValue{angle, unit}}, {Property::RAD}) {} -Skew2D::Skew2D(const NumericValue* values) noexcept : ResolvedPrimitive(values, { Property::RAD, Property::RAD }) { } -Skew2D::Skew2D(float x, float y, Property::Unit unit) noexcept - : ResolvedPrimitive({ NumericValue{ x, unit }, { NumericValue{ y, unit }} }, { Property::RAD, Property::RAD }) { } + SkewY::SkewY(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD}) {} + SkewY::SkewY(float angle, Property::Unit unit) noexcept : ResolvedPrimitive({NumericValue{angle, unit}}, {Property::RAD}) {} -Perspective::Perspective(const NumericValue* values) noexcept : UnresolvedPrimitive(values) { } + Skew2D::Skew2D(const NumericValue* values) noexcept : ResolvedPrimitive(values, {Property::RAD, Property::RAD}) {} + Skew2D::Skew2D(float x, float y, Property::Unit unit) noexcept : + ResolvedPrimitive({NumericValue{x, unit}, {NumericValue{y, unit}}}, {Property::RAD, Property::RAD}) + {} + Perspective::Perspective(const NumericValue* values) noexcept : UnresolvedPrimitive(values) {} -} -} // namespace Rml \ No newline at end of file +} // namespace Transforms +} // namespace Rml diff --git a/Source/Core/TransformState.cpp b/Source/Core/TransformState.cpp index 7f5db5722..a230a6b23 100644 --- a/Source/Core/TransformState.cpp +++ b/Source/Core/TransformState.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -41,7 +41,7 @@ bool TransformState::SetTransform(const Matrix4f* in_transform) } else have_transform = false; - + if (is_changed) dirty_inverse_transform = true; diff --git a/Source/Core/TransformState.h b/Source/Core/TransformState.h index a6cb90d8d..1b09925f0 100644 --- a/Source/Core/TransformState.h +++ b/Source/Core/TransformState.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,10 +34,8 @@ namespace Rml { -class TransformState -{ +class TransformState { public: - // Returns true if transform was changed. bool SetTransform(const Matrix4f* in_transform); @@ -50,7 +48,6 @@ class TransformState // Returns a nullptr if there is no transform set, or the transform is singular. const Matrix4f* GetInverseTransform() const; - private: bool have_transform = false; bool have_perspective = false; diff --git a/Source/Core/TransformUtilities.cpp b/Source/Core/TransformUtilities.cpp index f89b142b3..17c3d0243 100644 --- a/Source/Core/TransformUtilities.cpp +++ b/Source/Core/TransformUtilities.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -43,7 +43,6 @@ static Vector3f Combine(const Vector3f a, const Vector3f b, float a_scale, float return result; } - // Interpolate two quaternions a, b with weight alpha [0, 1] static Vector4f QuaternionSlerp(const Vector4f a, const Vector4f b, float alpha) { @@ -82,21 +81,24 @@ static inline float ResolveLengthPercentage(NumericValue value, Element& e, floa /// Resolve a numeric property value with the element's width as relative base value. static inline float ResolveWidth(NumericValue value, Element& e) noexcept { - if (value.unit & (Property::PX | Property::NUMBER)) return value.number; + if (value.unit & (Property::PX | Property::NUMBER)) + return value.number; return ResolveLengthPercentage(value, e, e.GetBox().GetSize(Box::BORDER).x); } /// Resolve a numeric property value with the element's height as relative base value. static inline float ResolveHeight(NumericValue value, Element& e) noexcept { - if (value.unit & (Property::PX | Property::NUMBER)) return value.number; + if (value.unit & (Property::PX | Property::NUMBER)) + return value.number; return ResolveLengthPercentage(value, e, e.GetBox().GetSize(Box::BORDER).y); } /// Resolve a numeric property value with the element's depth as relative base value. static inline float ResolveDepth(NumericValue value, Element& e) noexcept { - if (value.unit & (Property::PX | Property::NUMBER)) return value.number; + if (value.unit & (Property::PX | Property::NUMBER)) + return value.number; Vector2f size = e.GetBox().GetSize(Box::BORDER); return ResolveLengthPercentage(value, e, Math::Max(size.x, size.y)); } @@ -109,8 +111,7 @@ static inline String ToString(NumericValue value) noexcept return prop.ToString(); } -struct SetIdentityVisitor -{ +struct SetIdentityVisitor { template void operator()(Transforms::ResolvedPrimitive& p) { @@ -133,26 +134,11 @@ struct SetIdentityVisitor for (int i = 0; i < 16; i++) p.values[i] = ((i % 5) == 0 ? 1.0f : 0.0f); } - void operator()(Transforms::ScaleX& p) - { - p.values[0] = 1; - } - void operator()(Transforms::ScaleY& p) - { - p.values[0] = 1; - } - void operator()(Transforms::ScaleZ& p) - { - p.values[0] = 1; - } - void operator()(Transforms::Scale2D& p) - { - p.values[0] = p.values[1] = 1; - } - void operator()(Transforms::Scale3D& p) - { - p.values[0] = p.values[1] = p.values[2] = 1; - } + void operator()(Transforms::ScaleX& p) { p.values[0] = 1; } + void operator()(Transforms::ScaleY& p) { p.values[0] = 1; } + void operator()(Transforms::ScaleZ& p) { p.values[0] = 1; } + void operator()(Transforms::Scale2D& p) { p.values[0] = p.values[1] = 1; } + void operator()(Transforms::Scale3D& p) { p.values[0] = p.values[1] = p.values[2] = 1; } void operator()(Transforms::DecomposedMatrix4& p) { p.perspective = Vector4f(0, 0, 0, 1); @@ -162,7 +148,6 @@ struct SetIdentityVisitor p.skew = Vector3f(0, 0, 0); } - void run(TransformPrimitive& primitive) { switch (primitive.type) @@ -198,139 +183,49 @@ void TransformUtilities::SetIdentity(TransformPrimitive& p) noexcept SetIdentityVisitor{}.run(p); } - -struct ResolveTransformVisitor -{ +struct ResolveTransformVisitor { Matrix4f& m; Element& e; void operator()(const Transforms::Matrix2D& p) { - m = Matrix4f::FromRows( - Vector4f(p.values[0], p.values[2], 0, p.values[4]), - Vector4f(p.values[1], p.values[3], 0, p.values[5]), - Vector4f(0, 0, 1, 0), - Vector4f(0, 0, 0, 1) - ); + m = Matrix4f::FromRows(Vector4f(p.values[0], p.values[2], 0, p.values[4]), Vector4f(p.values[1], p.values[3], 0, p.values[5]), + Vector4f(0, 0, 1, 0), Vector4f(0, 0, 0, 1)); } - void operator()(const Transforms::Matrix3D& p) { - m = Matrix4f::FromColumns( - Vector4f(p.values[0], p.values[1], p.values[2], p.values[3]), - Vector4f(p.values[4], p.values[5], p.values[6], p.values[7]), - Vector4f(p.values[8], p.values[9], p.values[10], p.values[11]), - Vector4f(p.values[12], p.values[13], p.values[14], p.values[15]) - ); - } - - void operator()(const Transforms::TranslateX& p) - { - m = Matrix4f::TranslateX(ResolveWidth(p.values[0], e)); - } - - void operator()(const Transforms::TranslateY& p) - { - m = Matrix4f::TranslateY(ResolveHeight(p.values[0], e)); - } - - void operator()(const Transforms::TranslateZ& p) - { - m = Matrix4f::TranslateZ(ResolveDepth(p.values[0], e)); - } - - void operator()(const Transforms::Translate2D& p) - { - m = Matrix4f::Translate( - ResolveWidth(p.values[0], e), - ResolveHeight(p.values[1], e), - 0 - ); + m = Matrix4f::FromColumns(Vector4f(p.values[0], p.values[1], p.values[2], p.values[3]), + Vector4f(p.values[4], p.values[5], p.values[6], p.values[7]), Vector4f(p.values[8], p.values[9], p.values[10], p.values[11]), + Vector4f(p.values[12], p.values[13], p.values[14], p.values[15])); } + void operator()(const Transforms::TranslateX& p) { m = Matrix4f::TranslateX(ResolveWidth(p.values[0], e)); } + void operator()(const Transforms::TranslateY& p) { m = Matrix4f::TranslateY(ResolveHeight(p.values[0], e)); } + void operator()(const Transforms::TranslateZ& p) { m = Matrix4f::TranslateZ(ResolveDepth(p.values[0], e)); } + void operator()(const Transforms::Translate2D& p) { m = Matrix4f::Translate(ResolveWidth(p.values[0], e), ResolveHeight(p.values[1], e), 0); } void operator()(const Transforms::Translate3D& p) { - m = Matrix4f::Translate( - ResolveWidth(p.values[0], e), - ResolveHeight(p.values[1], e), - ResolveDepth(p.values[2], e) - ); - } - - void operator()(const Transforms::ScaleX& p) - { - m = Matrix4f::ScaleX(p.values[0]); - } - - void operator()(const Transforms::ScaleY& p) - { - m = Matrix4f::ScaleY(p.values[0]); - } - - void operator()(const Transforms::ScaleZ& p) - { - m = Matrix4f::ScaleZ(p.values[0]); - } - - void operator()(const Transforms::Scale2D& p) - { - m = Matrix4f::Scale(p.values[0], p.values[1], 1); + m = Matrix4f::Translate(ResolveWidth(p.values[0], e), ResolveHeight(p.values[1], e), ResolveDepth(p.values[2], e)); } - void operator()(const Transforms::Scale3D& p) - { - m = Matrix4f::Scale(p.values[0], p.values[1], p.values[2]); - } + void operator()(const Transforms::ScaleX& p) { m = Matrix4f::ScaleX(p.values[0]); } + void operator()(const Transforms::ScaleY& p) { m = Matrix4f::ScaleY(p.values[0]); } + void operator()(const Transforms::ScaleZ& p) { m = Matrix4f::ScaleZ(p.values[0]); } + void operator()(const Transforms::Scale2D& p) { m = Matrix4f::Scale(p.values[0], p.values[1], 1); } + void operator()(const Transforms::Scale3D& p) { m = Matrix4f::Scale(p.values[0], p.values[1], p.values[2]); } - void operator()(const Transforms::RotateX& p) - { - m = Matrix4f::RotateX(p.values[0]); - } + void operator()(const Transforms::RotateX& p) { m = Matrix4f::RotateX(p.values[0]); } + void operator()(const Transforms::RotateY& p) { m = Matrix4f::RotateY(p.values[0]); } + void operator()(const Transforms::RotateZ& p) { m = Matrix4f::RotateZ(p.values[0]); } + void operator()(const Transforms::Rotate2D& p) { m = Matrix4f::RotateZ(p.values[0]); } + void operator()(const Transforms::Rotate3D& p) { m = Matrix4f::Rotate(Vector3f(p.values[0], p.values[1], p.values[2]), p.values[3]); } - void operator()(const Transforms::RotateY& p) - { - m = Matrix4f::RotateY(p.values[0]); - } - - void operator()(const Transforms::RotateZ& p) - { - m = Matrix4f::RotateZ(p.values[0]); - } - - void operator()(const Transforms::Rotate2D& p) - { - m = Matrix4f::RotateZ(p.values[0]); - } - - void operator()(const Transforms::Rotate3D& p) - { - m = Matrix4f::Rotate(Vector3f(p.values[0], p.values[1], p.values[2]), p.values[3]); - } - - void operator()(const Transforms::SkewX& p) - { - m = Matrix4f::SkewX(p.values[0]); - } - - void operator()(const Transforms::SkewY& p) - { - m = Matrix4f::SkewY(p.values[0]); - } - - void operator()(const Transforms::Skew2D& p) - { - m = Matrix4f::Skew(p.values[0], p.values[1]); - } - - void operator()(const Transforms::DecomposedMatrix4& p) - { - m = Matrix4f::Compose(p.translation, p.scale, p.skew, p.perspective, p.quaternion); - } - void operator()(const Transforms::Perspective& p) - { - m = Matrix4f::Perspective(ResolveDepth(p.values[0], e)); - } + void operator()(const Transforms::SkewX& p) { m = Matrix4f::SkewX(p.values[0]); } + void operator()(const Transforms::SkewY& p) { m = Matrix4f::SkewY(p.values[0]); } + void operator()(const Transforms::Skew2D& p) { m = Matrix4f::Skew(p.values[0], p.values[1]); } + void operator()(const Transforms::DecomposedMatrix4& p) { m = Matrix4f::Compose(p.translation, p.scale, p.skew, p.perspective, p.quaternion); } + void operator()(const Transforms::Perspective& p) { m = Matrix4f::Perspective(ResolveDepth(p.values[0], e)); } void run(const TransformPrimitive& primitive) { @@ -365,44 +260,40 @@ struct ResolveTransformVisitor Matrix4f TransformUtilities::ResolveTransform(const TransformPrimitive& p, Element& e) noexcept { Matrix4f m; - ResolveTransformVisitor visitor{ m, e }; + ResolveTransformVisitor visitor{m, e}; visitor.run(p); return m; } - - - -struct PrepareVisitor -{ +struct PrepareVisitor { Element& e; bool operator()(TranslateX& p) { - p.values[0] = NumericValue{ ResolveWidth(p.values[0], e), Property::PX }; + p.values[0] = NumericValue{ResolveWidth(p.values[0], e), Property::PX}; return true; } bool operator()(TranslateY& p) { - p.values[0] = NumericValue{ ResolveHeight(p.values[0], e), Property::PX }; + p.values[0] = NumericValue{ResolveHeight(p.values[0], e), Property::PX}; return true; } bool operator()(TranslateZ& p) { - p.values[0] = NumericValue{ ResolveDepth(p.values[0], e), Property::PX }; + p.values[0] = NumericValue{ResolveDepth(p.values[0], e), Property::PX}; return true; } bool operator()(Translate2D& p) { - p.values[0] = NumericValue{ ResolveWidth(p.values[0], e), Property::PX }; - p.values[1] = NumericValue{ ResolveHeight(p.values[1], e), Property::PX }; + p.values[0] = NumericValue{ResolveWidth(p.values[0], e), Property::PX}; + p.values[1] = NumericValue{ResolveHeight(p.values[1], e), Property::PX}; return true; } bool operator()(Translate3D& p) { - p.values[0] = NumericValue{ ResolveWidth(p.values[0], e), Property::PX }; - p.values[1] = NumericValue{ ResolveHeight(p.values[1], e), Property::PX }; - p.values[2] = NumericValue{ ResolveDepth(p.values[2], e), Property::PX }; + p.values[0] = NumericValue{ResolveWidth(p.values[0], e), Property::PX}; + p.values[1] = NumericValue{ResolveHeight(p.values[1], e), Property::PX}; + p.values[2] = NumericValue{ResolveDepth(p.values[2], e), Property::PX}; return true; } template @@ -411,10 +302,7 @@ struct PrepareVisitor // No conversion needed for resolved transforms (with some exceptions below) return true; } - bool operator()(DecomposedMatrix4& /*p*/) - { - return true; - } + bool operator()(DecomposedMatrix4& /*p*/) { return true; } bool operator()(Rotate3D& p) { // Rotate3D can be interpolated if and only if their rotation axes point in the same direction. @@ -476,16 +364,12 @@ struct PrepareVisitor bool TransformUtilities::PrepareForInterpolation(TransformPrimitive& p, Element& e) noexcept { - return PrepareVisitor{ e }.run(p); + return PrepareVisitor{e}.run(p); } - - - enum class GenericType { None, Scale3D, Translate3D, Rotate3D }; -struct GetGenericTypeVisitor -{ +struct GetGenericTypeVisitor { GenericType run(const TransformPrimitive& primitive) { switch (primitive.type) @@ -521,28 +405,31 @@ struct GetGenericTypeVisitor } }; - -struct ConvertToGenericTypeVisitor -{ - Translate3D operator()(const TranslateX& p) { return Translate3D{ p.values[0], {0.0f, Property::PX}, {0.0f, Property::PX} }; } - Translate3D operator()(const TranslateY& p) { return Translate3D{ {0.0f, Property::PX}, p.values[0], {0.0f, Property::PX} }; } - Translate3D operator()(const TranslateZ& p) { return Translate3D{ {0.0f, Property::PX}, {0.0f, Property::PX}, p.values[0] }; } - Translate3D operator()(const Translate2D& p) { return Translate3D{ p.values[0], p.values[1], {0.0f, Property::PX} }; } - Scale3D operator()(const ScaleX& p) { return Scale3D{ p.values[0], 1.0f, 1.0f }; } - Scale3D operator()(const ScaleY& p) { return Scale3D{ 1.0f, p.values[0], 1.0f }; } - Scale3D operator()(const ScaleZ& p) { return Scale3D{ 1.0f, 1.0f, p.values[0] }; } - Scale3D operator()(const Scale2D& p) { return Scale3D{ p.values[0], p.values[1], 1.0f }; } - Rotate3D operator()(const RotateX& p) { return Rotate3D{ 1, 0, 0, p.values[0], Property::RAD }; } - Rotate3D operator()(const RotateY& p) { return Rotate3D{ 0, 1, 0, p.values[0], Property::RAD }; } - Rotate3D operator()(const RotateZ& p) { return Rotate3D{ 0, 0, 1, p.values[0], Property::RAD }; } - Rotate3D operator()(const Rotate2D& p) { return Rotate3D{ 0, 0, 1, p.values[0], Property::RAD }; } +struct ConvertToGenericTypeVisitor { + Translate3D operator()(const TranslateX& p) { return Translate3D{p.values[0], {0.0f, Property::PX}, {0.0f, Property::PX}}; } + Translate3D operator()(const TranslateY& p) { return Translate3D{{0.0f, Property::PX}, p.values[0], {0.0f, Property::PX}}; } + Translate3D operator()(const TranslateZ& p) { return Translate3D{{0.0f, Property::PX}, {0.0f, Property::PX}, p.values[0]}; } + Translate3D operator()(const Translate2D& p) { return Translate3D{p.values[0], p.values[1], {0.0f, Property::PX}}; } + Scale3D operator()(const ScaleX& p) { return Scale3D{p.values[0], 1.0f, 1.0f}; } + Scale3D operator()(const ScaleY& p) { return Scale3D{1.0f, p.values[0], 1.0f}; } + Scale3D operator()(const ScaleZ& p) { return Scale3D{1.0f, 1.0f, p.values[0]}; } + Scale3D operator()(const Scale2D& p) { return Scale3D{p.values[0], p.values[1], 1.0f}; } + Rotate3D operator()(const RotateX& p) { return Rotate3D{1, 0, 0, p.values[0], Property::RAD}; } + Rotate3D operator()(const RotateY& p) { return Rotate3D{0, 1, 0, p.values[0], Property::RAD}; } + Rotate3D operator()(const RotateZ& p) { return Rotate3D{0, 0, 1, p.values[0], Property::RAD}; } + Rotate3D operator()(const Rotate2D& p) { return Rotate3D{0, 0, 1, p.values[0], Property::RAD}; } template - TransformPrimitive operator()(const T& p) { RMLUI_ERROR; return p; } + TransformPrimitive operator()(const T& p) + { + RMLUI_ERROR; + return p; + } TransformPrimitive run(const TransformPrimitive& primitive) { TransformPrimitive result = primitive; + // clang-format off switch (primitive.type) { case TransformPrimitive::TRANSLATEX: result.type = TransformPrimitive::TRANSLATE3D; result.translate_3d = this->operator()(primitive.translate_x); break; @@ -560,10 +447,9 @@ struct ConvertToGenericTypeVisitor case TransformPrimitive::ROTATEZ: result.type = TransformPrimitive::ROTATE3D; result.rotate_3d = this->operator()(primitive.rotate_z); break; case TransformPrimitive::ROTATE2D: result.type = TransformPrimitive::ROTATE3D; result.rotate_3d = this->operator()(primitive.rotate_2d); break; case TransformPrimitive::ROTATE3D: break; - default: - RMLUI_ASSERT(false); - break; + default: RMLUI_ASSERT(false); break; } + // clang-format on return result; } }; @@ -577,7 +463,6 @@ static bool CanInterpolateRotate3D(const Rotate3D& p0, const Rotate3D& p1) return v0[0] == v1[0] && v0[1] == v1[1] && v0[2] == v1[2]; } - bool TransformUtilities::TryConvertToMatchingGenericType(TransformPrimitive& p0, TransformPrimitive& p1) noexcept { if (p0.type == p1.type) @@ -610,12 +495,7 @@ bool TransformUtilities::TryConvertToMatchingGenericType(TransformPrimitive& p0, return false; } - - - - -struct InterpolateVisitor -{ +struct InterpolateVisitor { const TransformPrimitive& other_variant; float alpha; @@ -637,15 +517,27 @@ struct InterpolateVisitor bool Interpolate(Rotate3D& p0, const Rotate3D& p1) { RMLUI_ASSERT(CanInterpolateRotate3D(p0, p1)); - // We can only interpolate rotate3d if their rotation axes align. That should be the case if we get here, + // We can only interpolate rotate3d if their rotation axes align. That should be the case if we get here, // otherwise the generic type matching should decompose them. Thus, we only need to interpolate // the angle value here. p0.values[3] = p0.values[3] * (1.0f - alpha) + p1.values[3] * alpha; return true; } - bool Interpolate(Matrix2D& /*p0*/, const Matrix2D& /*p1*/) { RMLUI_ERROR; return false; /* Error if we get here, see PrepareForInterpolation() */ } - bool Interpolate(Matrix3D& /*p0*/, const Matrix3D& /*p1*/) { RMLUI_ERROR; return false; /* Error if we get here, see PrepareForInterpolation() */ } - bool Interpolate(Perspective& /*p0*/, const Perspective& /*p1*/) { RMLUI_ERROR; return false; /* Error if we get here, see PrepareForInterpolation() */ } + bool Interpolate(Matrix2D& /*p0*/, const Matrix2D& /*p1*/) + { + RMLUI_ERROR; + return false; /* Error if we get here, see PrepareForInterpolation() */ + } + bool Interpolate(Matrix3D& /*p0*/, const Matrix3D& /*p1*/) + { + RMLUI_ERROR; + return false; /* Error if we get here, see PrepareForInterpolation() */ + } + bool Interpolate(Perspective& /*p0*/, const Perspective& /*p1*/) + { + RMLUI_ERROR; + return false; /* Error if we get here, see PrepareForInterpolation() */ + } bool Interpolate(DecomposedMatrix4& p0, const DecomposedMatrix4& p1) { @@ -695,12 +587,11 @@ bool TransformUtilities::InterpolateWith(TransformPrimitive& target, const Trans if (target.type != other.type) return false; - bool result = InterpolateVisitor{ other, alpha }.run(target); + bool result = InterpolateVisitor{other, alpha}.run(target); return result; } - -template +template static String ToString(const Transforms::ResolvedPrimitive& p, const String& unit, bool rad_to_deg = false, bool only_unit_on_last_value = false) noexcept { @@ -727,8 +618,9 @@ static String ToString(const Transforms::ResolvedPrimitive& p, const String& return result; } -template -static inline String ToString(const Transforms::UnresolvedPrimitive& p) noexcept { +template +static inline String ToString(const Transforms::UnresolvedPrimitive& p) noexcept +{ String result = "("; for (size_t i = 0; i < N; i++) { @@ -740,26 +632,21 @@ static inline String ToString(const Transforms::UnresolvedPrimitive& p) noexc return result; } -static inline String ToString(const Transforms::DecomposedMatrix4& p) noexcept { - static const Transforms::DecomposedMatrix4 d{ - Vector4f(0, 0, 0, 1), - Vector4f(0, 0, 0, 1), - Vector3f(0, 0, 0), - Vector3f(1, 1, 1), - Vector3f(0, 0, 0) - }; +static inline String ToString(const Transforms::DecomposedMatrix4& p) noexcept +{ + static const Transforms::DecomposedMatrix4 d{Vector4f(0, 0, 0, 1), Vector4f(0, 0, 0, 1), Vector3f(0, 0, 0), Vector3f(1, 1, 1), Vector3f(0, 0, 0)}; String tmp; String result; - if (p.perspective != d.perspective && TypeConverter< Vector4f, String >::Convert(p.perspective, tmp)) + if (p.perspective != d.perspective && TypeConverter::Convert(p.perspective, tmp)) result += "perspective(" + tmp + "), "; - if (p.quaternion != d.quaternion && TypeConverter< Vector4f, String >::Convert(p.quaternion, tmp)) + if (p.quaternion != d.quaternion && TypeConverter::Convert(p.quaternion, tmp)) result += "quaternion(" + tmp + "), "; - if (p.translation != d.translation && TypeConverter< Vector3f, String >::Convert(p.translation, tmp)) + if (p.translation != d.translation && TypeConverter::Convert(p.translation, tmp)) result += "translation(" + tmp + "), "; - if (p.scale != d.scale && TypeConverter< Vector3f, String >::Convert(p.scale, tmp)) + if (p.scale != d.scale && TypeConverter::Convert(p.scale, tmp)) result += "scale(" + tmp + "), "; - if (p.skew != d.skew && TypeConverter< Vector3f, String >::Convert(p.skew, tmp)) + if (p.skew != d.skew && TypeConverter::Convert(p.skew, tmp)) result += "skew(" + tmp + "), "; if (result.size() > 2) @@ -770,30 +657,31 @@ static inline String ToString(const Transforms::DecomposedMatrix4& p) noexcept { return result; } -static inline String ToString(const Transforms::Matrix2D& p) noexcept { return "matrix" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::Matrix3D& p) noexcept { return "matrix3d" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::TranslateX& p) noexcept { return "translateX" + ToString(static_cast&>(p)); } -static inline String ToString(const Transforms::TranslateY& p) noexcept { return "translateY" + ToString(static_cast&>(p)); } -static inline String ToString(const Transforms::TranslateZ& p) noexcept { return "translateZ" + ToString(static_cast&>(p)); } -static inline String ToString(const Transforms::Translate2D& p) noexcept { return "translate" + ToString(static_cast&>(p)); } +// clang-format off +static inline String ToString(const Transforms::Matrix2D& p) noexcept { return "matrix" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::Matrix3D& p) noexcept { return "matrix3d" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::TranslateX& p) noexcept { return "translateX" + ToString(static_cast&>(p)); } +static inline String ToString(const Transforms::TranslateY& p) noexcept { return "translateY" + ToString(static_cast&>(p)); } +static inline String ToString(const Transforms::TranslateZ& p) noexcept { return "translateZ" + ToString(static_cast&>(p)); } +static inline String ToString(const Transforms::Translate2D& p) noexcept { return "translate" + ToString(static_cast&>(p)); } static inline String ToString(const Transforms::Translate3D& p) noexcept { return "translate3d" + ToString(static_cast&>(p)); } -static inline String ToString(const Transforms::ScaleX& p) noexcept { return "scaleX" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::ScaleY& p) noexcept { return "scaleY" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::ScaleZ& p) noexcept { return "scaleZ" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::Scale2D& p) noexcept { return "scale" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::Scale3D& p) noexcept { return "scale3d" + ToString(static_cast&>(p), ""); } -static inline String ToString(const Transforms::RotateX& p) noexcept { return "rotateX" + ToString(static_cast&>(p), "deg", true); } -static inline String ToString(const Transforms::RotateY& p) noexcept { return "rotateY" + ToString(static_cast&>(p), "deg", true); } -static inline String ToString(const Transforms::RotateZ& p) noexcept { return "rotateZ" + ToString(static_cast&>(p), "deg", true); } -static inline String ToString(const Transforms::Rotate2D& p) noexcept { return "rotate" + ToString(static_cast&>(p), "deg", true); } -static inline String ToString(const Transforms::Rotate3D& p) noexcept { return "rotate3d" + ToString(static_cast&>(p), "deg", true, true); } -static inline String ToString(const Transforms::SkewX& p) noexcept { return "skewX" + ToString(static_cast&>(p), "deg", true); } -static inline String ToString(const Transforms::SkewY& p) noexcept { return "skewY" + ToString(static_cast&>(p), "deg", true); } -static inline String ToString(const Transforms::Skew2D& p) noexcept { return "skew" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::ScaleX& p) noexcept { return "scaleX" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::ScaleY& p) noexcept { return "scaleY" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::ScaleZ& p) noexcept { return "scaleZ" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::Scale2D& p) noexcept { return "scale" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::Scale3D& p) noexcept { return "scale3d" + ToString(static_cast&>(p), ""); } +static inline String ToString(const Transforms::RotateX& p) noexcept { return "rotateX" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::RotateY& p) noexcept { return "rotateY" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::RotateZ& p) noexcept { return "rotateZ" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::Rotate2D& p) noexcept { return "rotate" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::Rotate3D& p) noexcept { return "rotate3d" + ToString(static_cast&>(p), "deg", true, true); } +static inline String ToString(const Transforms::SkewX& p) noexcept { return "skewX" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::SkewY& p) noexcept { return "skewY" + ToString(static_cast&>(p), "deg", true); } +static inline String ToString(const Transforms::Skew2D& p) noexcept { return "skew" + ToString(static_cast&>(p), "deg", true); } static inline String ToString(const Transforms::Perspective& p) noexcept { return "perspective" + ToString(static_cast&>(p)); } +// clang-format on -struct ToStringVisitor -{ +struct ToStringVisitor { String run(const TransformPrimitive& variant) { switch (variant.type) @@ -832,7 +720,6 @@ String TransformUtilities::ToString(const TransformPrimitive& p) noexcept return result; } - bool TransformUtilities::Decompose(Transforms::DecomposedMatrix4& d, const Matrix4f& m) noexcept { // Follows the procedure given in https://drafts.csswg.org/css-transforms-2/#interpolation-of-3d-matrices @@ -842,7 +729,6 @@ bool TransformUtilities::Decompose(Transforms::DecomposedMatrix4& d, const Matri if (Math::AbsoluteValue(m[3][3]) < eps) return false; - // Perspective matrix Matrix4f p = m; diff --git a/Source/Core/TransformUtilities.h b/Source/Core/TransformUtilities.h index 1812e86f9..2a643751d 100644 --- a/Source/Core/TransformUtilities.h +++ b/Source/Core/TransformUtilities.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2014 Markus Schöngart - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,17 +35,17 @@ namespace Rml { struct TransformPrimitive; -namespace Transforms { struct DecomposedMatrix4; } - +namespace Transforms { + struct DecomposedMatrix4; +} -namespace TransformUtilities -{ +namespace TransformUtilities { // Set the primitive to its identity value. void SetIdentity(TransformPrimitive& primitive) noexcept; // Resolve the primitive into a transformation matrix, given the current element properties and layout. Matrix4f ResolveTransform(const TransformPrimitive& primitive, Element& e) noexcept; - + // Prepares the primitive for interpolation. This must be done before calling InterpolateWith(). // Promote units to basic types which can be interpolated, that is, convert 'length -> pixel' for unresolved primitives. // Returns false if the owning transform must to be converted to a DecomposedMatrix4 primitive. @@ -64,8 +64,7 @@ namespace TransformUtilities bool Decompose(Transforms::DecomposedMatrix4& decomposed_matrix, const Matrix4f& matrix) noexcept; String ToString(const TransformPrimitive& primitive) noexcept; -} - +} // namespace TransformUtilities } // namespace Rml #endif diff --git a/Source/Core/Tween.cpp b/Source/Core/Tween.cpp index 355ff9788..0ece1157a 100644 --- a/Source/Core/Tween.cpp +++ b/Source/Core/Tween.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -34,89 +34,101 @@ namespace Rml { namespace TweenFunctions { -// Tweening functions below. -// Partly based on http://libclaw.sourceforge.net/tweeners.html + /** + Tweening functions below. + Partly based on http://libclaw.sourceforge.net/tweeners.html + */ -static inline float square(float t) { - return t * t; -} + static inline float square(float t) + { + return t * t; + } -static float back(float t) -{ - return t * t * (2.70158f * t - 1.70158f); -} + static float back(float t) + { + return t * t * (2.70158f * t - 1.70158f); + } -static float bounce(float t) -{ - if (t > 1.f - 1.f / 2.75f) - return 1.f - 7.5625f * square(1.f - t); - else if (t > 1.f - 2.f / 2.75f) - return 1.0f - (7.5625f * square(1.f - t - 1.5f / 2.75f) + 0.75f); - else if (t > 1.f - 2.5f / 2.75f) - return 1.0f - (7.5625f * square(1.f - t - 2.25f / 2.75f) + 0.9375f); - return 1.0f - (7.5625f * square(1.f - t - 2.625f / 2.75f) + 0.984375f); -} + static float bounce(float t) + { + if (t > 1.f - 1.f / 2.75f) + return 1.f - 7.5625f * square(1.f - t); + else if (t > 1.f - 2.f / 2.75f) + return 1.0f - (7.5625f * square(1.f - t - 1.5f / 2.75f) + 0.75f); + else if (t > 1.f - 2.5f / 2.75f) + return 1.0f - (7.5625f * square(1.f - t - 2.25f / 2.75f) + 0.9375f); + return 1.0f - (7.5625f * square(1.f - t - 2.625f / 2.75f) + 0.984375f); + } -static float circular(float t) -{ - return 1.f - Math::SquareRoot(1.f - t * t); -} + static float circular(float t) + { + return 1.f - Math::SquareRoot(1.f - t * t); + } -static float cubic(float t) -{ - return t * t * t; -} + static float cubic(float t) + { + return t * t * t; + } -static float elastic(float t) -{ - if (t == 0) return t; - if (t == 1) return t; - return -Math::Exp(7.24f * (t - 1.f)) * Math::Sin((t - 1.1f) * 2.f * Math::RMLUI_PI / 0.4f); -} + static float elastic(float t) + { + if (t == 0) + return t; + if (t == 1) + return t; + return -Math::Exp(7.24f * (t - 1.f)) * Math::Sin((t - 1.1f) * 2.f * Math::RMLUI_PI / 0.4f); + } -static float exponential(float t) -{ - if (t == 0) return t; - if (t == 1) return t; - return Math::Exp(7.24f * (t - 1.f)); -} + static float exponential(float t) + { + if (t == 0) + return t; + if (t == 1) + return t; + return Math::Exp(7.24f * (t - 1.f)); + } -static float linear(float t) -{ - return t; -} + static float linear(float t) + { + return t; + } -static float quadratic(float t) -{ - return t * t; -} + static float quadratic(float t) + { + return t * t; + } -static float quartic(float t) -{ - return t * t * t * t; -} + static float quartic(float t) + { + return t * t * t * t; + } -static float quintic(float t) -{ - return t * t * t * t * t; -} + static float quintic(float t) + { + return t * t * t * t * t; + } -static float sine(float t) -{ - return 1.f - Math::Cos(t * Math::RMLUI_PI * 0.5f); -} + static float sine(float t) + { + return 1.f - Math::Cos(t * Math::RMLUI_PI * 0.5f); + } } // namespace TweenFunctions - -Tween::Tween(Type type, Direction direction) { - if (direction & In) type_in = type; - if (direction & Out) type_out = type; +Tween::Tween(Type type, Direction direction) +{ + if (direction & In) + type_in = type; + if (direction & Out) + type_out = type; } Tween::Tween(Type type_in, Type type_out) : type_in(type_in), type_out(type_out) {} -Tween::Tween(CallbackFnc callback, Direction direction) : callback(callback) { - if (direction & In) type_in = Callback; - if (direction & Out) type_out = Callback; +Tween::Tween(CallbackFnc callback, Direction direction) : callback(callback) +{ + if (direction & In) + type_in = Callback; + if (direction & Out) + type_out = Callback; } float Tween::operator()(float t) const { @@ -143,7 +155,7 @@ void Tween::reverse() bool Tween::operator==(const Tween& other) const { return type_in == other.type_in && type_out == other.type_out && callback == other.callback; -} +} bool Tween::operator!=(const Tween& other) const { @@ -152,7 +164,8 @@ bool Tween::operator!=(const Tween& other) const String Tween::to_string() const { - static const Array type_str = { { "none", "back", "bounce", "circular", "cubic", "elastic", "exponential", "linear", "quadratic", "quartic", "quintic", "sine", "callback" } }; + static const Array type_str = { + {"none", "back", "bounce", "circular", "cubic", "elastic", "exponential", "linear", "quadratic", "quartic", "quintic", "sine", "callback"}}; if (size_t(type_in) < type_str.size() && size_t(type_out) < type_str.size()) { @@ -186,34 +199,22 @@ float Tween::tween(Type type, float t) const switch (type) { - case Back: - return back(t); - case Bounce: - return bounce(t); - case Circular: - return circular(t); - case Cubic: - return cubic(t); - case Elastic: - return elastic(t); - case Exponential: - return exponential(t); - case Linear: - return linear(t); - case Quadratic: - return quadratic(t); - case Quartic: - return quartic(t); - case Quintic: - return quintic(t); - case Sine: - return sine(t); + case Back: return back(t); + case Bounce: return bounce(t); + case Circular: return circular(t); + case Cubic: return cubic(t); + case Elastic: return elastic(t); + case Exponential: return exponential(t); + case Linear: return linear(t); + case Quadratic: return quadratic(t); + case Quartic: return quartic(t); + case Quintic: return quintic(t); + case Sine: return sine(t); case Callback: if (callback) return (*callback)(t); break; - default: - break; + default: break; } return t; } diff --git a/Source/Core/TypeConverter.cpp b/Source/Core/TypeConverter.cpp index 6f9580ea1..c9192539f 100644 --- a/Source/Core/TypeConverter.cpp +++ b/Source/Core/TypeConverter.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,14 +27,14 @@ */ #include "../../Include/RmlUi/Core/TypeConverter.h" -#include "../../Include/RmlUi/Core/StyleSheetSpecification.h" -#include "../../Include/RmlUi/Core/StyleSheetTypes.h" #include "../../Include/RmlUi/Core/Animation.h" #include "../../Include/RmlUi/Core/DecoratorInstancer.h" -#include "../../Include/RmlUi/Core/Transform.h" +#include "../../Include/RmlUi/Core/PropertyDictionary.h" #include "../../Include/RmlUi/Core/PropertySpecification.h" +#include "../../Include/RmlUi/Core/StyleSheetSpecification.h" +#include "../../Include/RmlUi/Core/StyleSheetTypes.h" +#include "../../Include/RmlUi/Core/Transform.h" #include "../../Include/RmlUi/Core/TransformPrimitive.h" -#include "../../Include/RmlUi/Core/PropertyDictionary.h" #include "TransformUtilities.h" namespace Rml { @@ -54,11 +54,11 @@ bool TypeConverter::Convert(const TransformPtr& src, Strin for (size_t i = 0; i < primitives.size(); i++) { dest += TransformUtilities::ToString(primitives[i]); - if (i != primitives.size() - 1) + if (i != primitives.size() - 1) dest += ' '; } } - else + else { dest = "none"; } @@ -84,11 +84,16 @@ bool TypeConverter::Convert(const TransitionList& src, S const Transition& t = src.transitions[i]; dest += StyleSheetSpecification::GetPropertyName(t.id) + ' '; dest += t.tween.to_string() + ' '; - if (TypeConverter< float, String >::Convert(t.duration, tmp)) dest += tmp + "s "; - if (t.delay > 0.0f && TypeConverter< float, String >::Convert(t.delay, tmp)) dest += tmp + "s "; - if (t.reverse_adjustment_factor > 0.0f && TypeConverter< float, String >::Convert(t.reverse_adjustment_factor, tmp)) dest += tmp + ' '; - if (dest.size() > 0) dest.resize(dest.size() - 1); - if (i != src.transitions.size() - 1) dest += ", "; + if (TypeConverter::Convert(t.duration, tmp)) + dest += tmp + "s "; + if (t.delay > 0.0f && TypeConverter::Convert(t.delay, tmp)) + dest += tmp + "s "; + if (t.reverse_adjustment_factor > 0.0f && TypeConverter::Convert(t.reverse_adjustment_factor, tmp)) + dest += tmp + ' '; + if (dest.size() > 0) + dest.resize(dest.size() - 1); + if (i != src.transitions.size() - 1) + dest += ", "; } return true; } @@ -105,15 +110,22 @@ bool TypeConverter::Convert(const AnimationList& src, Str for (size_t i = 0; i < src.size(); i++) { const Animation& a = src[i]; - if (TypeConverter< float, String >::Convert(a.duration, tmp)) dest += tmp + "s "; + if (TypeConverter::Convert(a.duration, tmp)) + dest += tmp + "s "; dest += a.tween.to_string() + " "; - if (a.delay > 0.0f && TypeConverter< float, String >::Convert(a.delay, tmp)) dest += tmp + "s "; - if (a.alternate) dest += "alternate "; - if (a.paused) dest += "paused "; - if (a.num_iterations == -1) dest += "infinite "; - else if (TypeConverter< int, String >::Convert(a.num_iterations, tmp)) dest += tmp + " "; + if (a.delay > 0.0f && TypeConverter::Convert(a.delay, tmp)) + dest += tmp + "s "; + if (a.alternate) + dest += "alternate "; + if (a.paused) + dest += "paused "; + if (a.num_iterations == -1) + dest += "infinite "; + else if (TypeConverter::Convert(a.num_iterations, tmp)) + dest += tmp + " "; dest += a.name; - if (i != src.size() - 1) dest += ", "; + if (i != src.size() - 1) + dest += ", "; } return true; } @@ -124,7 +136,6 @@ bool TypeConverter::Convert(const DecoratorsPtr& s return true; } - bool TypeConverter::Convert(const DecoratorsPtr& src, String& dest) { if (!src || src->list.empty()) @@ -149,14 +160,12 @@ bool TypeConverter::Convert(const DecoratorsPtr& src, Str return true; } - bool TypeConverter::Convert(const FontEffectsPtr& src, FontEffectsPtr& dest) { dest = src; return true; } - bool TypeConverter::Convert(const FontEffectsPtr& src, String& dest) { if (!src || src->list.empty()) @@ -166,7 +175,4 @@ bool TypeConverter::Convert(const FontEffectsPtr& src, S return true; } - - - } // namespace Rml diff --git a/Source/Core/URL.cpp b/Source/Core/URL.cpp index 1c52b1107..853479b8a 100644 --- a/Source/Core/URL.cpp +++ b/Source/Core/URL.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,43 +26,36 @@ * */ +#include "../../Include/RmlUi/Core/URL.h" #include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/StringUtilities.h" -#include "../../Include/RmlUi/Core/URL.h" -#include #include +#include namespace Rml { const char* DEFAULT_PROTOCOL = "file"; -// Constructs an Empty URL. URL::URL() { port = 0; url_dirty = false; } -// Constructs a new URL from the given string. URL::URL(const String& _url) { port = 0; RMLUI_VERIFY(SetURL(_url)); } -// Constructs a new URL from the given string. URL::URL(const char* _url) { port = 0; RMLUI_VERIFY(SetURL(_url)); } -// Destroys the URL. -URL::~URL() -{ -} +URL::~URL() {} -// Assigns a new URL to the object. bool URL::SetURL(const String& _url) { url_dirty = false; @@ -93,7 +86,8 @@ bool URL::SetURL(const String& _url) { char malformed_terminator[4] = {0, 0, 0, 0}; strncpy(malformed_terminator, host_begin, 3); - Log::Message(Log::LT_ERROR, "Malformed protocol identifier found in URL %s; expected %s://, found %s%s.\n", _url.c_str(), protocol.c_str(), protocol.c_str(), malformed_terminator); + Log::Message(Log::LT_ERROR, "Malformed protocol identifier found in URL %s; expected %s://, found %s%s.\n", _url.c_str(), + protocol.c_str(), protocol.c_str(), malformed_terminator); return false; } @@ -105,28 +99,27 @@ bool URL::SetURL(const String& _url) host_begin = _url.c_str(); } - // We only want to look for a host if a protocol was specified. const char* path_begin; if (host_begin != _url.c_str()) { // Find the host. This is the string appearing after the protocol or after - // the username:password combination, and terminated either with a colon, + // the username:password combination, and terminated either with a colon, // if a port is specified, or a forward slash if there is no port. // Check for a login pair - const char* at_symbol = strchr( host_begin, '@' ); - if ( at_symbol ) + const char* at_symbol = strchr(host_begin, '@'); + if (at_symbol) { String login_password; - login_password = String( host_begin, at_symbol ); + login_password = String(host_begin, at_symbol); host_begin = at_symbol + 1; - const char* password_ptr = strchr( login_password.c_str(), ':' ); - if ( password_ptr ) + const char* password_ptr = strchr(login_password.c_str(), ':'); + if (password_ptr) { - login = String( login_password.c_str(), password_ptr ); - password = String( password_ptr + 1 ); + login = String(login_password.c_str(), password_ptr); + password = String(password_ptr + 1); } else { @@ -179,34 +172,33 @@ bool URL::SetURL(const String& _url) { path_begin = _url.c_str(); } - + // Check for parameters String path_segment; const char* parameters = strchr(path_begin, '?'); - if ( parameters ) + if (parameters) { // Pull the path segment out, so further processing doesn't read the parameters path_segment = String(path_begin, parameters); path_begin = path_segment.c_str(); - + // Loop through all parameters, loading them StringList parameter_list; - StringUtilities::ExpandString( parameter_list, parameters + 1, '&' ); - for ( size_t i = 0; i < parameter_list.size(); i++ ) + StringUtilities::ExpandString(parameter_list, parameters + 1, '&'); + for (size_t i = 0; i < parameter_list.size(); i++) { // Split into key and value StringList key_value; - StringUtilities::ExpandString( key_value, parameter_list[i], '=' ); + StringUtilities::ExpandString(key_value, parameter_list[i], '='); key_value[0] = UrlDecode(key_value[0]); - if ( key_value.size() == 2 ) + if (key_value.size() == 2) this->parameters[key_value[0]] = UrlDecode(key_value[1]); else this->parameters[key_value[0]] = ""; } } - // Find the path. This is the string appearing after the host, terminated // by the last forward slash. const char* file_name_begin = strrchr(path_begin, '/'); @@ -240,7 +232,6 @@ bool URL::SetURL(const String& _url) } } - // Find the file name. This is the string after the trailing slash of the // path, and just before the extension. const char* extension_begin = strrchr(file_name_begin, '.'); @@ -254,20 +245,18 @@ bool URL::SetURL(const String& _url) file_name = String(file_name_begin, extension_begin); extension = extension_begin + 1; } - + return true; } -// Returns the entire URL. const String& URL::GetURL() const { if (url_dirty) ConstructURL(); - + return url; } -// Sets the URL's protocol. bool URL::SetProtocol(const String& _protocol) { protocol = _protocol; @@ -276,27 +265,23 @@ bool URL::SetProtocol(const String& _protocol) return true; } -// Returns the protocol this URL is utilising. const String& URL::GetProtocol() const { return protocol; } -/// Sets the URL's login -bool URL::SetLogin( const String& _login ) +bool URL::SetLogin(const String& _login) { login = _login; url_dirty = true; return true; } -/// Returns the URL's login const String& URL::GetLogin() const { return login; } -/// Sets the URL's password bool URL::SetPassword(const String& _password) { password = _password; @@ -304,13 +289,11 @@ bool URL::SetPassword(const String& _password) return true; } -/// Returns the URL's password const String& URL::GetPassword() const { return password; } -// Sets the URL's host. bool URL::SetHost(const String& _host) { host = _host; @@ -319,13 +302,11 @@ bool URL::SetHost(const String& _host) return true; } -// Returns the URL's host. const String& URL::GetHost() const { return host; } -// Sets the URL's port number. bool URL::SetPort(int _port) { port = _port; @@ -334,13 +315,11 @@ bool URL::SetPort(int _port) return true; } -// Returns the URL's port number. int URL::GetPort() const { return port; } -// Sets the URL's path. bool URL::SetPath(const String& _path) { path = _path; @@ -349,12 +328,10 @@ bool URL::SetPath(const String& _path) return true; } -// Prefixes the URL's existing path with the given prefix. bool URL::PrefixPath(const String& prefix) { // If there's no trailing slash on the end of the prefix, add one. - if (!prefix.empty() && - prefix[prefix.size() - 1] != '/') + if (!prefix.empty() && prefix[prefix.size() - 1] != '/') path = prefix + "/" + path; else path = prefix + path; @@ -364,13 +341,11 @@ bool URL::PrefixPath(const String& prefix) return true; } -// Returns the URL's path. const String& URL::GetPath() const { return path; } -// Sets the URL's file name. bool URL::SetFileName(const String& _file_name) { file_name = _file_name; @@ -379,13 +354,11 @@ bool URL::SetFileName(const String& _file_name) return true; } -// Returns the URL's file name. const String& URL::GetFileName() const { return file_name; } -// Sets the URL's file extension. bool URL::SetExtension(const String& _extension) { extension = _extension; @@ -394,83 +367,76 @@ bool URL::SetExtension(const String& _extension) return true; } -// Returns the URL's file extension. const String& URL::GetExtension() const { return extension; } -// Gets the current parameters const URL::Parameters& URL::GetParameters() const { return parameters; } -// Set an individual parameter void URL::SetParameter(const String& key, const String& value) { parameters[key] = value; url_dirty = true; } -// Set all parameters void URL::SetParameters(const Parameters& _parameters) { parameters = _parameters; url_dirty = true; } -// Clear the parameters void URL::ClearParameters() { parameters.clear(); } -// Returns the URL's path, file name and extension. String URL::GetPathedFileName() const { String pathed_file_name = path; - + // Append the file name. pathed_file_name += file_name; - + // Append the extension. if (!extension.empty()) { pathed_file_name += "."; pathed_file_name += extension; } - + return pathed_file_name; } String URL::GetQueryString() const { String query_string; - + int count = 0; - for ( Parameters::const_iterator itr = parameters.begin(); itr != parameters.end(); ++itr ) + for (Parameters::const_iterator itr = parameters.begin(); itr != parameters.end(); ++itr) { - query_string += ( count == 0 ) ? "" : "&"; - + query_string += (count == 0) ? "" : "&"; + query_string += UrlEncode((*itr).first); query_string += "="; query_string += UrlEncode((*itr).second); - + count++; } - + return query_string; } -// Less-than operator for use as a key in STL containers. bool URL::operator<(const URL& rhs) const { if (url_dirty) ConstructURL(); if (rhs.url_dirty) rhs.ConstructURL(); - + return url < rhs.url; } @@ -479,7 +445,7 @@ void URL::ConstructURL() const url = ""; // Append the protocol. - if (!protocol.empty() && !host.empty()) + if (!protocol.empty() && !host.empty()) { url = protocol; url += "://"; @@ -488,25 +454,25 @@ void URL::ConstructURL() const // Append login and password if (!login.empty()) { - url += login ; + url += login; if (!password.empty()) - { - url += ":" ; - url += password ; + { + url += ":"; + url += password; } - url += "@" ; + url += "@"; } - RMLUI_ASSERTMSG( password.empty() || ( !password.empty() && !login.empty() ), "Can't have a password without a login!" ); + RMLUI_ASSERTMSG(password.empty() || (!password.empty() && !login.empty()), "Can't have a password without a login!"); // Append the host. url += host; - + // Only check ports if there is some host/protocol part - if ( !url.empty() ) - { + if (!url.empty()) + { if (port > 0) { - RMLUI_ASSERTMSG( !host.empty(), "Can't have a port without a host!" ); + RMLUI_ASSERTMSG(!host.empty(), "Can't have a port without a host!"); constexpr size_t port_buffer_size = 16; char port_string[port_buffer_size]; snprintf(port_string, port_buffer_size, ":%d/", port); @@ -533,18 +499,18 @@ void URL::ConstructURL() const url += "."; url += extension; } - + // Append parameters if (!parameters.empty()) { url += "?"; - url += GetQueryString(); + url += GetQueryString(); } - + url_dirty = false; } -String URL::UrlEncode(const String &value) +String URL::UrlEncode(const String& value) { String encoded; constexpr size_t hex_buffer_size = 4; @@ -552,8 +518,8 @@ String URL::UrlEncode(const String &value) encoded.clear(); - const char *value_c = value.c_str(); - for (String::size_type i = 0; value_c[i]; i++) + const char* value_c = value.c_str(); + for (String::size_type i = 0; value_c[i]; i++) { char c = value_c[i]; if (IsUnreservedChar(c)) @@ -568,15 +534,15 @@ String URL::UrlEncode(const String &value) return encoded; } -String URL::UrlDecode(const String &value) +String URL::UrlDecode(const String& value) { String decoded; decoded.clear(); - const char *value_c = value.c_str(); + const char* value_c = value.c_str(); String::size_type value_len = value.size(); - for (String::size_type i = 0; i < value_len; i++) + for (String::size_type i = 0; i < value_len; i++) { char c = value_c[i]; if (c == '+') @@ -585,8 +551,8 @@ String URL::UrlDecode(const String &value) } else if (c == '%') { - char *endp; - String t = value.substr(i+1, 2); + char* endp; + String t = value.substr(i + 1, 2); int ch = strtol(t.c_str(), &endp, 16); if (*endp == '\0') decoded += char(ch); @@ -607,22 +573,73 @@ bool URL::IsUnreservedChar(const char in) { switch (in) { - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - case 'a': case 'b': case 'c': case 'd': case 'e': - case 'f': case 'g': case 'h': case 'i': case 'j': - case 'k': case 'l': case 'm': case 'n': case 'o': - case 'p': case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': - case 'A': case 'B': case 'C': case 'D': case 'E': - case 'F': case 'G': case 'H': case 'I': case 'J': - case 'K': case 'L': case 'M': case 'N': case 'O': - case 'P': case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': - case '-': case '.': case '_': case '~': - return true; - default: - break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '-': + case '.': + case '_': + case '~': return true; + default: break; } return false; } diff --git a/Source/Core/Variant.cpp b/Source/Core/Variant.cpp index 3c5a2a8a7..f0156c1fc 100644 --- a/Source/Core/Variant.cpp +++ b/Source/Core/Variant.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -55,7 +55,7 @@ Variant::Variant(Variant&& other) noexcept Set(std::move(other)); } -Variant::~Variant() +Variant::~Variant() { Clear(); } @@ -63,60 +63,53 @@ Variant::~Variant() void Variant::Clear() { // Free any allocated types. - switch (type) - { - case STRING: - { - // Clean up the string. - String* string = (String*)data; - string->~String(); - } - break; - case TRANSFORMPTR: - { - // Clean up the transform. - TransformPtr* transform = (TransformPtr*)data; - transform->~TransformPtr(); - } - break; - case TRANSITIONLIST: - { - // Clean up the transition list. - TransitionList* transition_list = (TransitionList*)data; - transition_list->~TransitionList(); - } - break; - case ANIMATIONLIST: - { - // Clean up the transition list. - AnimationList* animation_list = (AnimationList*)data; - animation_list->~AnimationList(); - } - break; - case DECORATORSPTR: - { - DecoratorsPtr* decorators = (DecoratorsPtr*)data; - decorators->~DecoratorsPtr(); - } - break; - case FONTEFFECTSPTR: - { - FontEffectsPtr* font_effects = (FontEffectsPtr*)data; - font_effects->~shared_ptr(); - } - break; - default: - break; + switch (type) + { + case STRING: + { + // Clean up the string. + String* string = (String*)data; + string->~String(); + } + break; + case TRANSFORMPTR: + { + // Clean up the transform. + TransformPtr* transform = (TransformPtr*)data; + transform->~TransformPtr(); + } + break; + case TRANSITIONLIST: + { + // Clean up the transition list. + TransitionList* transition_list = (TransitionList*)data; + transition_list->~TransitionList(); + } + break; + case ANIMATIONLIST: + { + // Clean up the transition list. + AnimationList* animation_list = (AnimationList*)data; + animation_list->~AnimationList(); + } + break; + case DECORATORSPTR: + { + DecoratorsPtr* decorators = (DecoratorsPtr*)data; + decorators->~DecoratorsPtr(); + } + break; + case FONTEFFECTSPTR: + { + FontEffectsPtr* font_effects = (FontEffectsPtr*)data; + font_effects->~shared_ptr(); + } + break; + default: break; } type = NONE; } - - -////////////////////////////////////////////////// -// Set methods -////////////////////////////////////////////////// - #define SET_VARIANT(type) *((type*)data) = value; void Variant::Set(const Variant& copy) @@ -209,12 +202,12 @@ void Variant::Set(const uint64_t value) SET_VARIANT(uint64_t); } -void Variant::Set(const char* value) +void Variant::Set(const char* value) { Set(String(value)); } -void Variant::Set(void* voidptr) +void Variant::Set(void* voidptr) { type = VOIDPTR; memcpy(data, &voidptr, sizeof(void*)); @@ -256,7 +249,6 @@ void Variant::Set(ScriptInterface* value) memcpy(data, &value, sizeof(ScriptInterface*)); } - void Variant::Set(const String& value) { if (type == STRING) @@ -266,7 +258,7 @@ void Variant::Set(const String& value) else { type = STRING; - new(data) String(value); + new (data) String(value); } } void Variant::Set(String&& value) @@ -278,11 +270,10 @@ void Variant::Set(String&& value) else { type = STRING; - new(data) String(std::move(value)); + new (data) String(std::move(value)); } } - void Variant::Set(const TransformPtr& value) { if (type == TRANSFORMPTR) @@ -292,7 +283,7 @@ void Variant::Set(const TransformPtr& value) else { type = TRANSFORMPTR; - new(data) TransformPtr(value); + new (data) TransformPtr(value); } } void Variant::Set(TransformPtr&& value) @@ -304,7 +295,7 @@ void Variant::Set(TransformPtr&& value) else { type = TRANSFORMPTR; - new(data) TransformPtr(std::move(value)); + new (data) TransformPtr(std::move(value)); } } @@ -317,7 +308,7 @@ void Variant::Set(const TransitionList& value) else { type = TRANSITIONLIST; - new(data) TransitionList(value); + new (data) TransitionList(value); } } void Variant::Set(TransitionList&& value) @@ -329,7 +320,7 @@ void Variant::Set(TransitionList&& value) else { type = TRANSITIONLIST; - new(data) TransitionList(std::move(value)); + new (data) TransitionList(std::move(value)); } } @@ -342,7 +333,7 @@ void Variant::Set(const AnimationList& value) else { type = ANIMATIONLIST; - new(data) AnimationList(value); + new (data) AnimationList(value); } } void Variant::Set(AnimationList&& value) @@ -354,7 +345,7 @@ void Variant::Set(AnimationList&& value) else { type = ANIMATIONLIST; - new(data) AnimationList(std::move(value)); + new (data) AnimationList(std::move(value)); } } @@ -367,7 +358,7 @@ void Variant::Set(const DecoratorsPtr& value) else { type = DECORATORSPTR; - new(data) DecoratorsPtr(value); + new (data) DecoratorsPtr(value); } } void Variant::Set(DecoratorsPtr&& value) @@ -379,7 +370,7 @@ void Variant::Set(DecoratorsPtr&& value) else { type = DECORATORSPTR; - new(data) DecoratorsPtr(std::move(value)); + new (data) DecoratorsPtr(std::move(value)); } } void Variant::Set(const FontEffectsPtr& value) @@ -391,7 +382,7 @@ void Variant::Set(const FontEffectsPtr& value) else { type = FONTEFFECTSPTR; - new(data) FontEffectsPtr(value); + new (data) FontEffectsPtr(value); } } void Variant::Set(FontEffectsPtr&& value) @@ -403,7 +394,7 @@ void Variant::Set(FontEffectsPtr&& value) else { type = FONTEFFECTSPTR; - new(data) FontEffectsPtr(std::move(value)); + new (data) FontEffectsPtr(std::move(value)); } } @@ -429,7 +420,7 @@ Variant& Variant::operator=(Variant&& other) noexcept #define DEFAULT_VARIANT_COMPARE(TYPE) static_cast(*(TYPE*)data) == static_cast(*(TYPE*)other.data) -bool Variant::operator==(const Variant & other) const +bool Variant::operator==(const Variant& other) const { if (type != other.type) return false; diff --git a/Source/Core/WidgetScroll.cpp b/Source/Core/WidgetScroll.cpp index 0107eb044..1114cdc71 100644 --- a/Source/Core/WidgetScroll.cpp +++ b/Source/Core/WidgetScroll.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,12 +28,12 @@ #include "WidgetScroll.h" #include "../../Include/RmlUi/Core/ComputedValues.h" +#include "../../Include/RmlUi/Core/Context.h" #include "../../Include/RmlUi/Core/Element.h" #include "../../Include/RmlUi/Core/ElementUtilities.h" #include "../../Include/RmlUi/Core/Event.h" #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Property.h" -#include "../../Include/RmlUi/Core/Context.h" #include "Clock.h" #include "Layout/LayoutDetails.h" @@ -89,7 +89,6 @@ WidgetScroll::~WidgetScroll() } } -// Initialises the slider to a given orientation. bool WidgetScroll::Initialise(Orientation _orientation) { // Check that we haven't already been successfully initialised. @@ -100,8 +99,7 @@ bool WidgetScroll::Initialise(Orientation _orientation) } // Check that a valid orientation has been passed in. - if (_orientation != HORIZONTAL && - _orientation != VERTICAL) + if (_orientation != HORIZONTAL && _orientation != VERTICAL) { RMLUI_ERROR; return false; @@ -144,7 +142,6 @@ bool WidgetScroll::Initialise(Orientation _orientation) return true; } -// Updates the key repeats for the increment / decrement arrows. void WidgetScroll::Update() { for (int i = 0; i < 2; i++) @@ -171,43 +168,44 @@ void WidgetScroll::Update() ScrollLineDown(); } - if(Context* ctx = parent->GetContext()) + if (Context* ctx = parent->GetContext()) ctx->RequestNextUpdate(arrow_timers[i]); } } } -// Sets the position of the bar. void WidgetScroll::SetBarPosition(float _bar_position) { bar_position = Math::Clamp(_bar_position, 0.0f, 1.0f); PositionBar(); } -// Returns the current position of the bar. float WidgetScroll::GetBarPosition() const { return bar_position; } -// Returns the slider's orientation. WidgetScroll::Orientation WidgetScroll::GetOrientation() const { return orientation; } -// Sets the dimensions to the size of the slider. void WidgetScroll::GetDimensions(Vector2f& dimensions) const { switch (orientation) { - RMLUI_UNUSED_SWITCH_ENUM(UNKNOWN); - case VERTICAL: dimensions.x = 16; dimensions.y = 256; break; - case HORIZONTAL: dimensions.x = 256; dimensions.y = 16; break; + case VERTICAL: + dimensions.x = 16; + dimensions.y = 256; + break; + case HORIZONTAL: + dimensions.x = 256; + dimensions.y = 16; + break; + case UNKNOWN: break; } } -// Lays out and resizes the internal elements. void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_element, float slider_length, float bar_length) { int length_axis = orientation == VERTICAL ? 1 : 0; @@ -215,8 +213,9 @@ void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_e // Build the box for the containing slider element. Box parent_box; LayoutDetails::BuildBox(parent_box, containing_block, parent); - slider_length -= orientation == VERTICAL ? (parent_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + parent_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)) : - (parent_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + parent_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); + slider_length -= orientation == VERTICAL + ? (parent_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + parent_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)) + : (parent_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + parent_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); // Set the length of the slider. Vector2f content = parent_box.GetSize(); @@ -230,12 +229,12 @@ void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_e Box track_box; LayoutDetails::BuildBox(track_box, parent_box.GetSize(), track); content = track_box.GetSize(); - content[length_axis] = slider_length -= orientation == VERTICAL ? (track_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + track_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)) : - (track_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + track_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); + content[length_axis] = slider_length -= orientation == VERTICAL + ? (track_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + track_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)) + : (track_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + track_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); // If no height has been explicitly specified for the track, it'll be initialised to -1 as per normal block // elements. We'll fix that up here. - if (orientation == HORIZONTAL && - content.y < 0) + if (orientation == HORIZONTAL && content.y < 0) content.y = parent_box.GetSize().y; // Now we size the arrows. @@ -246,8 +245,7 @@ void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_e // Clamp the size to (0, 0). Vector2f arrow_size = arrow_box.GetSize(); - if (arrow_size.x < 0 || - arrow_size.y < 0) + if (arrow_size.x < 0 || arrow_size.y < 0) arrow_box.SetContent(Vector2f(0, 0)); arrows[i]->SetBox(arrow_box); @@ -266,11 +264,13 @@ void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_e arrows[0]->SetOffset(offset, parent); offset.x = track->GetBox().GetEdge(Box::MARGIN, Box::LEFT); - offset.y += arrows[0]->GetBox().GetSize(Box::BORDER).y + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + track->GetBox().GetEdge(Box::MARGIN, Box::TOP); + offset.y += arrows[0]->GetBox().GetSize(Box::BORDER).y + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + + track->GetBox().GetEdge(Box::MARGIN, Box::TOP); track->SetOffset(offset, parent); offset.x = arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::LEFT); - offset.y += track->GetBox().GetSize(Box::BORDER).y + track->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::TOP); + offset.y += track->GetBox().GetSize(Box::BORDER).y + track->GetBox().GetEdge(Box::MARGIN, Box::BOTTOM) + + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::TOP); arrows[1]->SetOffset(offset, parent); } else @@ -278,11 +278,13 @@ void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_e Vector2f offset(arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::LEFT), arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::TOP)); arrows[0]->SetOffset(offset, parent); - offset.x += arrows[0]->GetBox().GetSize(Box::BORDER).x + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + track->GetBox().GetEdge(Box::MARGIN, Box::LEFT); + offset.x += arrows[0]->GetBox().GetSize(Box::BORDER).x + arrows[0]->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + + track->GetBox().GetEdge(Box::MARGIN, Box::LEFT); offset.y = track->GetBox().GetEdge(Box::MARGIN, Box::TOP); track->SetOffset(offset, parent); - offset.x += track->GetBox().GetSize(Box::BORDER).x + track->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::LEFT); + offset.x += track->GetBox().GetSize(Box::BORDER).x + track->GetBox().GetEdge(Box::MARGIN, Box::RIGHT) + + arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::LEFT); offset.y = arrows[1]->GetBox().GetEdge(Box::MARGIN, Box::TOP); arrows[1]->SetOffset(offset, parent); } @@ -290,7 +292,6 @@ void WidgetScroll::FormatElements(const Vector2f containing_block, bool resize_e FormatBar(bar_length); } -// Lays out and positions the bar element. void WidgetScroll::FormatBar(float bar_length) { Box bar_box; @@ -314,7 +315,8 @@ void WidgetScroll::FormatBar(float bar_length) if (orientation == VERTICAL) { - float track_length = track_size.y - (bar_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + bar_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)); + float track_length = + track_size.y - (bar_box.GetCumulativeEdge(Box::CONTENT, Box::TOP) + bar_box.GetCumulativeEdge(Box::CONTENT, Box::BOTTOM)); if (height.type == height.Auto) { @@ -334,7 +336,8 @@ void WidgetScroll::FormatBar(float bar_length) } else { - float track_length = track_size.x - (bar_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + bar_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); + float track_length = + track_size.x - (bar_box.GetCumulativeEdge(Box::CONTENT, Box::LEFT) + bar_box.GetCumulativeEdge(Box::CONTENT, Box::RIGHT)); if (width.type == width.Auto) { @@ -362,7 +365,6 @@ void WidgetScroll::FormatBar(float bar_length) PositionBar(); } -// Handles events coming through from the slider's components. void WidgetScroll::ProcessEvent(Event& event) { if (event.GetTargetElement() == bar) @@ -438,8 +440,7 @@ void WidgetScroll::ProcessEvent(Event& event) ScrollLineDown(); } } - else if (event == EventId::Mouseup || - event == EventId::Mouseout) + else if (event == EventId::Mouseup || event == EventId::Mouseout) { if (event.GetTargetElement() == arrows[0]) arrow_timers[0] = -1; @@ -456,28 +457,27 @@ void WidgetScroll::PositionBar() if (orientation == VERTICAL) { float traversable_track_length = track_dimensions.y - bar_dimensions.y; - bar->SetOffset(Vector2f(bar->GetBox().GetEdge(Box::MARGIN, Box::LEFT), track->GetRelativeOffset().y + traversable_track_length * bar_position), parent); + bar->SetOffset( + Vector2f(bar->GetBox().GetEdge(Box::MARGIN, Box::LEFT), track->GetRelativeOffset().y + traversable_track_length * bar_position), parent); } else { float traversable_track_length = track_dimensions.x - bar_dimensions.x; - bar->SetOffset(Vector2f(track->GetRelativeOffset().x + traversable_track_length * bar_position, bar->GetBox().GetEdge(Box::MARGIN, Box::TOP)), parent); + bar->SetOffset(Vector2f(track->GetRelativeOffset().x + traversable_track_length * bar_position, bar->GetBox().GetEdge(Box::MARGIN, Box::TOP)), + parent); } } -// Sets the length of the entire track in some arbitrary unit. void WidgetScroll::SetTrackLength(float _track_length) { track_length = _track_length; } -// Sets the length the bar represents in some arbitrary unit, relative to the track length. void WidgetScroll::SetBarLength(float _bar_length) { bar_length = _bar_length; } -// Lays out and resizes the internal elements. void WidgetScroll::FormatElements(const Vector2f containing_block, float slider_length) { float relative_bar_length; diff --git a/Source/Core/WidgetScroll.h b/Source/Core/WidgetScroll.h index 16aac8242..81a98cf92 100644 --- a/Source/Core/WidgetScroll.h +++ b/Source/Core/WidgetScroll.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,20 +37,14 @@ class Element; enum class ScrollBehavior; /** - A widget for incorporating scrolling functionality into an element. + A widget for incorporating scrolling functionality into an element. - @author Peter Curry + @author Peter Curry */ -class WidgetScroll final : public EventListener -{ +class WidgetScroll final : public EventListener { public: - enum Orientation - { - UNKNOWN, - VERTICAL, - HORIZONTAL - }; + enum Orientation { UNKNOWN, VERTICAL, HORIZONTAL }; WidgetScroll(Element* parent); virtual ~WidgetScroll(); diff --git a/Source/Core/XMLNodeHandler.cpp b/Source/Core/XMLNodeHandler.cpp index 3b91d86ab..9b964b0cb 100644 --- a/Source/Core/XMLNodeHandler.cpp +++ b/Source/Core/XMLNodeHandler.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,8 +30,6 @@ namespace Rml { -XMLNodeHandler::~XMLNodeHandler() -{ -} +XMLNodeHandler::~XMLNodeHandler() {} } // namespace Rml diff --git a/Source/Core/XMLNodeHandlerBody.cpp b/Source/Core/XMLNodeHandlerBody.cpp index 918a6d388..fa7188a9c 100644 --- a/Source/Core/XMLNodeHandlerBody.cpp +++ b/Source/Core/XMLNodeHandlerBody.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,25 +27,19 @@ */ #include "XMLNodeHandlerBody.h" -#include "XMLParseTools.h" -#include "../../Include/RmlUi/Core/XMLParser.h" #include "../../Include/RmlUi/Core/ElementDocument.h" #include "../../Include/RmlUi/Core/Factory.h" +#include "../../Include/RmlUi/Core/XMLParser.h" +#include "XMLParseTools.h" namespace Rml { -XMLNodeHandlerBody::XMLNodeHandlerBody() -{ -} +XMLNodeHandlerBody::XMLNodeHandlerBody() {} -XMLNodeHandlerBody::~XMLNodeHandlerBody() -{ -} +XMLNodeHandlerBody::~XMLNodeHandlerBody() {} -Element* XMLNodeHandlerBody::ElementStart(XMLParser* parser, const String& RMLUI_UNUSED_PARAMETER(name), const XMLAttributes& attributes) +Element* XMLNodeHandlerBody::ElementStart(XMLParser* parser, const String& /*name*/, const XMLAttributes& attributes) { - RMLUI_UNUSED(name); - Element* element = parser->GetParseFrame()->element; // Apply any attributes to the document, but only if the current element is the root of the current document, @@ -58,7 +52,8 @@ Element* XMLNodeHandlerBody::ElementStart(XMLParser* parser, const String& RMLUI Variant* attribute = document->GetAttribute(pair.first); if (attribute && *attribute != pair.second && pair.first != "template") { - Log::Message(Log::LT_WARNING, "Overriding attribute '%s' in element %s during template injection.", pair.first.c_str(), element->GetAddress().c_str()); + Log::Message(Log::LT_WARNING, "Overriding attribute '%s' in element %s during template injection.", pair.first.c_str(), + element->GetAddress().c_str()); } } @@ -74,21 +69,17 @@ Element* XMLNodeHandlerBody::ElementStart(XMLParser* parser, const String& RMLUI // Tell the parser to use the element handler for all children parser->PushDefaultHandler(); - + return element; } -bool XMLNodeHandlerBody::ElementEnd(XMLParser* RMLUI_UNUSED_PARAMETER(parser), const String& RMLUI_UNUSED_PARAMETER(name)) +bool XMLNodeHandlerBody::ElementEnd(XMLParser* /*parser*/, const String& /*name*/) { - RMLUI_UNUSED(parser); - RMLUI_UNUSED(name); - return true; } -bool XMLNodeHandlerBody::ElementData(XMLParser* parser, const String& data, XMLDataType RMLUI_UNUSED_PARAMETER(type)) +bool XMLNodeHandlerBody::ElementData(XMLParser* parser, const String& data, XMLDataType /*type*/) { - RMLUI_UNUSED(type); return Factory::InstanceElementText(parser->GetParseFrame()->element, data); } diff --git a/Source/Core/XMLNodeHandlerBody.h b/Source/Core/XMLNodeHandlerBody.h index dc3f3c83e..9f06d9dfc 100644 --- a/Source/Core/XMLNodeHandlerBody.h +++ b/Source/Core/XMLNodeHandlerBody.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - Element Node handler that processes the HEAD tag + Element Node handler that processes the HEAD tag - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class XMLNodeHandlerBody : public XMLNodeHandler -{ +class XMLNodeHandlerBody : public XMLNodeHandler { public: XMLNodeHandlerBody(); ~XMLNodeHandlerBody(); diff --git a/Source/Core/XMLNodeHandlerDefault.cpp b/Source/Core/XMLNodeHandlerDefault.cpp index 41f50c201..d8ecb80de 100644 --- a/Source/Core/XMLNodeHandlerDefault.cpp +++ b/Source/Core/XMLNodeHandlerDefault.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,27 +27,22 @@ */ #include "XMLNodeHandlerDefault.h" -#include "XMLParseTools.h" -#include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/Element.h" +#include "../../Include/RmlUi/Core/ElementUtilities.h" #include "../../Include/RmlUi/Core/Factory.h" +#include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/Profiling.h" #include "../../Include/RmlUi/Core/XMLParser.h" -#include "../../Include/RmlUi/Core/ElementUtilities.h" - +#include "XMLParseTools.h" namespace Rml { -XMLNodeHandlerDefault::XMLNodeHandlerDefault() -{ -} +XMLNodeHandlerDefault::XMLNodeHandlerDefault() {} -XMLNodeHandlerDefault::~XMLNodeHandlerDefault() -{ -} +XMLNodeHandlerDefault::~XMLNodeHandlerDefault() {} Element* XMLNodeHandlerDefault::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) -{ +{ RMLUI_ZoneScopedC(0x556B2F); // Determine the parent @@ -67,11 +62,8 @@ Element* XMLNodeHandlerDefault::ElementStart(XMLParser* parser, const String& na return result; } -bool XMLNodeHandlerDefault::ElementEnd(XMLParser* RMLUI_UNUSED_PARAMETER(parser), const String& RMLUI_UNUSED_PARAMETER(name)) +bool XMLNodeHandlerDefault::ElementEnd(XMLParser* /*parser*/, const String& /*name*/) { - RMLUI_UNUSED(parser); - RMLUI_UNUSED(name); - return true; } @@ -94,5 +86,4 @@ bool XMLNodeHandlerDefault::ElementData(XMLParser* parser, const String& data, X return Factory::InstanceElementText(parent, data); } - } // namespace Rml diff --git a/Source/Core/XMLNodeHandlerDefault.h b/Source/Core/XMLNodeHandlerDefault.h index 200d80c3d..913382387 100644 --- a/Source/Core/XMLNodeHandlerDefault.h +++ b/Source/Core/XMLNodeHandlerDefault.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,21 +35,20 @@ namespace Rml { /** - Element Node handler that creates elements + Element Node handler that creates elements - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class XMLNodeHandlerDefault : public XMLNodeHandler -{ +class XMLNodeHandlerDefault : public XMLNodeHandler { public: XMLNodeHandlerDefault(); ~XMLNodeHandlerDefault(); - + /// Called when a new element start is opened Element* ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) override; /// Called when an element is closed - bool ElementEnd(XMLParser* parser, const String& name) override; + bool ElementEnd(XMLParser* parser, const String& name) override; /// Called for element data bool ElementData(XMLParser* parser, const String& data, XMLDataType type) override; }; diff --git a/Source/Core/XMLNodeHandlerHead.cpp b/Source/Core/XMLNodeHandlerHead.cpp index 8f44b4273..ecf65d690 100644 --- a/Source/Core/XMLNodeHandlerHead.cpp +++ b/Source/Core/XMLNodeHandlerHead.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,15 +27,15 @@ */ #include "XMLNodeHandlerHead.h" -#include "DocumentHeader.h" -#include "TemplateCache.h" #include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/Element.h" #include "../../Include/RmlUi/Core/ElementDocument.h" #include "../../Include/RmlUi/Core/StringUtilities.h" #include "../../Include/RmlUi/Core/SystemInterface.h" -#include "../../Include/RmlUi/Core/XMLParser.h" #include "../../Include/RmlUi/Core/URL.h" +#include "../../Include/RmlUi/Core/XMLParser.h" +#include "DocumentHeader.h" +#include "TemplateCache.h" namespace Rml { @@ -64,13 +64,9 @@ static DocumentHeader::Resource MakeExternalResource(XMLParser* parser, const St return resource; } -XMLNodeHandlerHead::XMLNodeHandlerHead() -{ -} +XMLNodeHandlerHead::XMLNodeHandlerHead() {} -XMLNodeHandlerHead::~XMLNodeHandlerHead() -{ -} +XMLNodeHandlerHead::~XMLNodeHandlerHead() {} Element* XMLNodeHandlerHead::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) { @@ -90,8 +86,7 @@ Element* XMLNodeHandlerHead::ElementStart(XMLParser* parser, const String& name, if (!type.empty() && !href.empty()) { // If its RCSS (... or CSS!), add to the RCSS fields. - if (type == "text/rcss" || - type == "text/css") + if (type == "text/rcss" || type == "text/css") { parser->GetDocumentHeader()->rcss.push_back(MakeExternalResource(parser, href)); } @@ -129,7 +124,7 @@ Element* XMLNodeHandlerHead::ElementStart(XMLParser* parser, const String& name, } bool XMLNodeHandlerHead::ElementEnd(XMLParser* parser, const String& name) -{ +{ // When the head tag closes, inject the header into the active document if (name == "head") { @@ -144,9 +139,8 @@ bool XMLNodeHandlerHead::ElementEnd(XMLParser* parser, const String& name) return true; } -bool XMLNodeHandlerHead::ElementData(XMLParser* parser, const String& data, XMLDataType RMLUI_UNUSED_PARAMETER(type)) +bool XMLNodeHandlerHead::ElementData(XMLParser* parser, const String& data, XMLDataType /*type*/) { - RMLUI_UNUSED(type); const String& tag = parser->GetParseFrame()->tag; // Store the title diff --git a/Source/Core/XMLNodeHandlerHead.h b/Source/Core/XMLNodeHandlerHead.h index efd368fef..9dd1f4521 100644 --- a/Source/Core/XMLNodeHandlerHead.h +++ b/Source/Core/XMLNodeHandlerHead.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - Element Node handler that processes the HEAD tag + Element Node handler that processes the HEAD tag - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class XMLNodeHandlerHead : public XMLNodeHandler -{ +class XMLNodeHandlerHead : public XMLNodeHandler { public: XMLNodeHandlerHead(); ~XMLNodeHandlerHead(); diff --git a/Source/Core/XMLNodeHandlerTemplate.cpp b/Source/Core/XMLNodeHandlerTemplate.cpp index 8de62b52e..20141581c 100644 --- a/Source/Core/XMLNodeHandlerTemplate.cpp +++ b/Source/Core/XMLNodeHandlerTemplate.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,28 +27,24 @@ */ #include "XMLNodeHandlerTemplate.h" -#include "Template.h" -#include "TemplateCache.h" -#include "XMLParseTools.h" #include "../../Include/RmlUi/Core/Dictionary.h" #include "../../Include/RmlUi/Core/Element.h" #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/XMLParser.h" +#include "Template.h" +#include "TemplateCache.h" +#include "XMLParseTools.h" namespace Rml { -XMLNodeHandlerTemplate::XMLNodeHandlerTemplate() -{ -} +XMLNodeHandlerTemplate::XMLNodeHandlerTemplate() {} -XMLNodeHandlerTemplate::~XMLNodeHandlerTemplate() -{ -} +XMLNodeHandlerTemplate::~XMLNodeHandlerTemplate() {} -Element* XMLNodeHandlerTemplate::ElementStart(XMLParser* parser, const String& RMLUI_UNUSED_ASSERT_PARAMETER(name), const XMLAttributes& attributes) +Element* XMLNodeHandlerTemplate::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) { - RMLUI_UNUSED_ASSERT(name); RMLUI_ASSERT(name == "template"); + (void)name; // Tell the parser to use the default handler for all child nodes parser->PushDefaultHandler(); @@ -58,24 +54,22 @@ Element* XMLNodeHandlerTemplate::ElementStart(XMLParser* parser, const String& R if (template_name.empty()) { - Log::Message(Log::LT_WARNING, "Inline template injection requires the 'src' attribute with the target template name, but none provided. In element %s", element->GetAddress().c_str()); + Log::Message(Log::LT_WARNING, + "Inline template injection requires the 'src' attribute with the target template name, but none provided. In element %s", + element->GetAddress().c_str()); return element; } return XMLParseTools::ParseTemplate(element, template_name); } -bool XMLNodeHandlerTemplate::ElementEnd(XMLParser* RMLUI_UNUSED_PARAMETER(parser), const String& RMLUI_UNUSED_PARAMETER(name)) +bool XMLNodeHandlerTemplate::ElementEnd(XMLParser* /*parser*/, const String& /*name*/) { - RMLUI_UNUSED(parser); - RMLUI_UNUSED(name); - return true; } -bool XMLNodeHandlerTemplate::ElementData(XMLParser* parser, const String& data, XMLDataType RMLUI_UNUSED_PARAMETER(type)) -{ - RMLUI_UNUSED(type); +bool XMLNodeHandlerTemplate::ElementData(XMLParser* parser, const String& data, XMLDataType /*type*/) +{ return Factory::InstanceElementText(parser->GetParseFrame()->element, data); } diff --git a/Source/Core/XMLNodeHandlerTemplate.h b/Source/Core/XMLNodeHandlerTemplate.h index d41f04970..80d57065a 100644 --- a/Source/Core/XMLNodeHandlerTemplate.h +++ b/Source/Core/XMLNodeHandlerTemplate.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,13 +34,12 @@ namespace Rml { /** - Element Node handler that processes the custom template tags + Element Node handler that processes the custom template tags - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class XMLNodeHandlerTemplate : public XMLNodeHandler -{ +class XMLNodeHandlerTemplate : public XMLNodeHandler { public: XMLNodeHandlerTemplate(); ~XMLNodeHandlerTemplate(); diff --git a/Source/Core/XMLParseTools.cpp b/Source/Core/XMLParseTools.cpp index 58f0ace79..d6fa779cd 100644 --- a/Source/Core/XMLParseTools.cpp +++ b/Source/Core/XMLParseTools.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,19 +27,17 @@ */ #include "XMLParseTools.h" -#include "../../Include/RmlUi/Core/StreamMemory.h" #include "../../Include/RmlUi/Core/ElementDocument.h" +#include "../../Include/RmlUi/Core/StreamMemory.h" #include "../../Include/RmlUi/Core/StringUtilities.h" #include "../../Include/RmlUi/Core/Types.h" -#include "TemplateCache.h" #include "Template.h" +#include "TemplateCache.h" #include #include namespace Rml { -// Searchs a string for the specified tag -// NOTE: tag *MUST* be in lowercase const char* XMLParseTools::FindTag(const char* tag, const char* string, bool closing_tag) { const size_t length = strlen(tag); @@ -78,8 +76,8 @@ const char* XMLParseTools::FindTag(const char* tag, const char* string, bool clo return nullptr; } -bool XMLParseTools::ReadAttribute(const char* &string, String& name, String& value) -{ +bool XMLParseTools::ReadAttribute(const char*& string, String& name, String& value) +{ const char* ptr = string; name = ""; @@ -96,16 +94,15 @@ bool XMLParseTools::ReadAttribute(const char* &string, String& name, String& val if (StringUtilities::IsWhitespace(*ptr)) found_whitespace = true; else - name += *ptr; + name += *ptr; ptr++; } if (*ptr == '>') return false; - + // If we stopped on an equals, parse the value if (*ptr == '=') { - // Skip over white space, ='s and quotes bool quoted = false; while (StringUtilities::IsWhitespace(*ptr) || *ptr == '\'' || *ptr == '"' || *ptr == '=') @@ -121,7 +118,7 @@ bool XMLParseTools::ReadAttribute(const char* &string, String& name, String& val while (*ptr != '\'' && *ptr != '"' && *ptr != '>' && (*ptr != ' ' || quoted)) { value += *ptr++; - } + } if (*ptr == '>') return false; @@ -141,7 +138,7 @@ bool XMLParseTools::ReadAttribute(const char* &string, String& name, String& val } Element* XMLParseTools::ParseTemplate(Element* element, const String& template_name) -{ +{ // Load the template, and parse it Template* parse_template = TemplateCache::GetTemplate(template_name); if (!parse_template) @@ -160,7 +157,7 @@ const char* XMLParseTools::ParseDataBrackets(bool& inside_brackets, bool& inside if (c == '\'') inside_string = !inside_string; - if(!inside_string) + if (!inside_string) { if (c == '}' && previous == '}') inside_brackets = false; diff --git a/Source/Core/XMLParseTools.h b/Source/Core/XMLParseTools.h index 747fcbc14..81be5fa25 100644 --- a/Source/Core/XMLParseTools.h +++ b/Source/Core/XMLParseTools.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,13 +36,12 @@ namespace Rml { class Element; /** - Tools for aiding in parsing XML documents. + Tools for aiding in parsing XML documents. - @author Lloyd Weehuizen + @author Lloyd Weehuizen */ -class XMLParseTools -{ +class XMLParseTools { public: /// Searchs a string for the specified tag /// @param tag Tag to find, *must* be in lower case @@ -53,7 +52,7 @@ class XMLParseTools /// @param[in,out] string String to read the attribute from, pointer will be advanced passed the read /// @param[out] name Name of the attribute read /// @param[out] value Value of the attribute read - static bool ReadAttribute(const char* &string, String& name, String& value); + static bool ReadAttribute(const char*& string, String& name, String& value); /// Applies the named template to the specified element /// @param element Element to apply the template to @@ -61,12 +60,12 @@ class XMLParseTools /// @returns Element to continue the parse from static Element* ParseTemplate(Element* element, const String& template_name); - /// Determine the presence of data expression brackets inside XML data. - /// Call this for each iteration through the data string. - /// 'inside_brackets' should be initialized to false. - /// 'inside_string' should be initialized to false. - /// Returns nullptr on success, or an error string on failure. - static const char* ParseDataBrackets(bool& inside_brackets, bool& inside_string, char c, char previous); + /// Determine the presence of data expression brackets inside XML data. + /// Call this for each iteration through the data string. + /// 'inside_brackets' should be initialized to false. + /// 'inside_string' should be initialized to false. + /// Returns nullptr on success, or an error string on failure. + static const char* ParseDataBrackets(bool& inside_brackets, bool& inside_string, char c, char previous); }; } // namespace Rml diff --git a/Source/Core/XMLParser.cpp b/Source/Core/XMLParser.cpp index 7592005ad..a4d9b4268 100644 --- a/Source/Core/XMLParser.cpp +++ b/Source/Core/XMLParser.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,19 +26,19 @@ * */ -#include "DocumentHeader.h" +#include "../../Include/RmlUi/Core/XMLParser.h" +#include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/Profiling.h" #include "../../Include/RmlUi/Core/Stream.h" #include "../../Include/RmlUi/Core/Types.h" -#include "../../Include/RmlUi/Core/XMLNodeHandler.h" #include "../../Include/RmlUi/Core/URL.h" -#include "../../Include/RmlUi/Core/XMLParser.h" -#include "../../Include/RmlUi/Core/Factory.h" +#include "../../Include/RmlUi/Core/XMLNodeHandler.h" +#include "DocumentHeader.h" namespace Rml { -using NodeHandlers = UnorderedMap< String, SharedPtr >; +using NodeHandlers = UnorderedMap>; static NodeHandlers node_handlers; static SharedPtr default_node_handler; @@ -60,10 +60,8 @@ XMLParser::XMLParser(Element* root) header = MakeUnique(); } -XMLParser::~XMLParser() -{} +XMLParser::~XMLParser() {} -// Registers a custom node handler to be used to a given tag. XMLNodeHandler* XMLParser::RegisterNodeHandler(const String& _tag, SharedPtr handler) { String tag = StringUtilities::ToLower(_tag); @@ -85,11 +83,10 @@ XMLNodeHandler* XMLParser::GetNodeHandler(const String& tag) auto it = node_handlers.find(tag); if (it != node_handlers.end()) return it->second.get(); - + return nullptr; } -// Releases all registered node handlers. This is called internally. void XMLParser::ReleaseHandlers() { default_node_handler.reset(); @@ -101,7 +98,6 @@ DocumentHeader* XMLParser::GetDocumentHeader() return header.get(); } -// Pushes the default element handler onto the parse stack. void XMLParser::PushDefaultHandler() { active_handler = default_node_handler.get(); @@ -117,7 +113,6 @@ bool XMLParser::PushHandler(const String& tag) return true; } -/// Access the current parse frame const XMLParser::ParseFrame* XMLParser::GetParseFrame() const { return &stack.top(); @@ -129,7 +124,6 @@ const URL& XMLParser::GetSourceURL() const return *GetSourceURLPtr(); } -/// Called when the parser finds the beginning of an element tag. void XMLParser::HandleElementStart(const String& _name, const XMLAttributes& attributes) { RMLUI_ZoneScoped; @@ -160,7 +154,6 @@ void XMLParser::HandleElementStart(const String& _name, const XMLAttributes& att stack.push(frame); } -/// Called when the parser finds the end of an element tag. void XMLParser::HandleElementEnd(const String& _name) { RMLUI_ZoneScoped; @@ -171,22 +164,22 @@ void XMLParser::HandleElementEnd(const String& _name) // Pop the frame stack.pop(); // Restore active handler to the previous frame's child handler - active_handler = stack.top().child_handler; + active_handler = stack.top().child_handler; // Check frame names if (name != frame.tag) { - Log::Message(Log::LT_ERROR, "Closing tag '%s' mismatched on %s:%d was expecting '%s'.", name.c_str(), GetSourceURL().GetURL().c_str(), GetLineNumber(), frame.tag.c_str()); + Log::Message(Log::LT_ERROR, "Closing tag '%s' mismatched on %s:%d was expecting '%s'.", name.c_str(), GetSourceURL().GetURL().c_str(), + GetLineNumber(), frame.tag.c_str()); } // Call element end handler if (frame.node_handler) { frame.node_handler->ElementEnd(this, name); - } + } } -/// Called when the parser encounters data. void XMLParser::HandleData(const String& data, XMLDataType type) { RMLUI_ZoneScoped; diff --git a/Source/Core/precompiled.h b/Source/Core/precompiled.h index 4a9c96ab4..52386d55e 100644 --- a/Source/Core/precompiled.h +++ b/Source/Core/precompiled.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Source/Debugger/.clang-format b/Source/Debugger/.clang-format new file mode 100644 index 000000000..cbb10f54a --- /dev/null +++ b/Source/Debugger/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: InheritParentConfig +NamespaceIndentation: None diff --git a/Source/Debugger/BeaconSource.h b/Source/Debugger/BeaconSource.h index bd7dabfe1..f9a02ada6 100644 --- a/Source/Debugger/BeaconSource.h +++ b/Source/Debugger/BeaconSource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Source/Debugger/CommonSource.h b/Source/Debugger/CommonSource.h index 513035c54..3d8d9769e 100644 --- a/Source/Debugger/CommonSource.h +++ b/Source/Debugger/CommonSource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Source/Debugger/Debugger.cpp b/Source/Debugger/Debugger.cpp index 669ce6ef6..9a0b079da 100644 --- a/Source/Debugger/Debugger.cpp +++ b/Source/Debugger/Debugger.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,7 +33,6 @@ namespace Rml { namespace Debugger { -// Initialises the debug plugin. The debugger will be loaded into the given context. bool Initialise(Context* context) { if (DebuggerPlugin::GetInstance() != nullptr) @@ -57,7 +56,6 @@ bool Initialise(Context* context) return true; } -// Shuts down the debugger. void Shutdown() { DebuggerPlugin* plugin = DebuggerPlugin::GetInstance(); @@ -70,7 +68,6 @@ void Shutdown() UnregisterPlugin(plugin); } -// Sets the context to be debugged. bool SetContext(Context* context) { DebuggerPlugin* plugin = DebuggerPlugin::GetInstance(); @@ -82,7 +79,6 @@ bool SetContext(Context* context) return true; } -// Sets the visibility of the debugger. void SetVisible(bool visibility) { DebuggerPlugin* plugin = DebuggerPlugin::GetInstance(); @@ -90,7 +86,6 @@ void SetVisible(bool visibility) plugin->SetVisible(visibility); } -// Returns the visibility of the debugger. bool IsVisible() { DebuggerPlugin* plugin = DebuggerPlugin::GetInstance(); @@ -100,5 +95,5 @@ bool IsVisible() return plugin->IsVisible(); } -} +} // namespace Debugger } // namespace Rml diff --git a/Source/Debugger/DebuggerPlugin.cpp b/Source/Debugger/DebuggerPlugin.cpp index 88f2915ff..5e4e884ef 100644 --- a/Source/Debugger/DebuggerPlugin.cpp +++ b/Source/Debugger/DebuggerPlugin.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -33,13 +33,13 @@ #include "../../Include/RmlUi/Core/ElementUtilities.h" #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Types.h" +#include "DebuggerSystemInterface.h" #include "ElementContextHook.h" #include "ElementInfo.h" #include "ElementLog.h" #include "FontSource.h" #include "Geometry.h" #include "MenuSource.h" -#include "DebuggerSystemInterface.h" #include namespace Rml { @@ -70,7 +70,6 @@ DebuggerPlugin::~DebuggerPlugin() instance = nullptr; } -// Initialises the debugging tools into the given context. bool DebuggerPlugin::Initialise(Context* context) { host_context = context; @@ -82,21 +81,18 @@ bool DebuggerPlugin::Initialise(Context* context) return false; } - if (!LoadMenuElement() || - !LoadInfoElement() || - !LoadLogElement()) + if (!LoadMenuElement() || !LoadInfoElement() || !LoadLogElement()) { Log::Message(Log::LT_ERROR, "Failed to initialise debugger, error while load debugger elements."); return false; } - hook_element_instancer = MakeUnique< ElementInstancerGeneric >(); + hook_element_instancer = MakeUnique>(); Factory::RegisterElementInstancer("debug-hook", hook_element_instancer.get()); return true; } -// Sets the context to be debugged. bool DebuggerPlugin::SetContext(Context* context) { // Remove the debug hook from the old context. @@ -114,7 +110,7 @@ bool DebuggerPlugin::SetContext(Context* context) return false; RMLUI_ASSERT(!hook_element); - hook_element = rmlui_dynamic_cast< ElementContextHook* >(element); + hook_element = rmlui_dynamic_cast(element); if (!hook_element) { context->UnloadDocument(element); @@ -135,7 +131,6 @@ bool DebuggerPlugin::SetContext(Context* context) return true; } -// Sets the visibility of the debugger. void DebuggerPlugin::SetVisible(bool visibility) { if (visibility) @@ -144,13 +139,11 @@ void DebuggerPlugin::SetVisible(bool visibility) menu_element->SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden)); } -// Returns the visibility of the debugger. bool DebuggerPlugin::IsVisible() { return menu_element->IsVisible(); } -// Renders any debug elements in the debug context. void DebuggerPlugin::Render() { // Render the outlines of the debug context's elements. @@ -162,7 +155,7 @@ void DebuggerPlugin::Render() if (document->GetId().find("rmlui-debug-") == 0) continue; - Stack< Element* > element_stack; + Stack element_stack; element_stack.push(document); while (!element_stack.empty()) @@ -176,12 +169,8 @@ void DebuggerPlugin::Render() { Vector2f box_offset; const Box& box = element->GetBox(j, box_offset); - Geometry::RenderOutline( - element->GetAbsoluteOffset(Box::BORDER) + box_offset, - box.GetSize(Box::BORDER), - Colourb(255, 0, 0, 128), - 1 - ); + Geometry::RenderOutline(element->GetAbsoluteOffset(Box::BORDER) + box_offset, box.GetSize(Box::BORDER), + Colourb(255, 0, 0, 128), 1); } for (int j = 0; j < element->GetNumChildren(); ++j) @@ -199,7 +188,6 @@ void DebuggerPlugin::Render() } } -// Called when RmlUi shuts down. void DebuggerPlugin::OnShutdown() { // Release the elements before we leak track, this ensures the debugger hook has been cleared @@ -211,7 +199,6 @@ void DebuggerPlugin::OnShutdown() delete this; } -// Called whenever a RmlUi context is destroyed. void DebuggerPlugin::OnContextDestroy(Context* context) { if (context == debug_context) @@ -231,14 +218,12 @@ void DebuggerPlugin::OnContextDestroy(Context* context) } } -// Called whenever an element is destroyed. void DebuggerPlugin::OnElementDestroy(Element* element) { if (info_element) info_element->OnElementDestroy(element); } -// Event handler for events from the debugger elements. void DebuggerPlugin::ProcessEvent(Event& event) { if (event == EventId::Click) @@ -273,8 +258,10 @@ bool DebuggerPlugin::LoadFont() { const String font_family_name = "rmlui-debugger-font"; - return (LoadFontFace(courier_prime_code, sizeof(courier_prime_code)/sizeof(courier_prime_code[0]), font_family_name, Style::FontStyle::Normal, Style::FontWeight::Normal) && - LoadFontFace(courier_prime_code_italic, sizeof(courier_prime_code_italic)/sizeof(courier_prime_code_italic[0]), font_family_name, Style::FontStyle::Italic, Style::FontWeight::Normal)); + return (LoadFontFace(courier_prime_code, sizeof(courier_prime_code) / sizeof(courier_prime_code[0]), font_family_name, Style::FontStyle::Normal, + Style::FontWeight::Normal) && + LoadFontFace(courier_prime_code_italic, sizeof(courier_prime_code_italic) / sizeof(courier_prime_code_italic[0]), font_family_name, + Style::FontStyle::Italic, Style::FontWeight::Normal)); } bool DebuggerPlugin::LoadMenuElement() @@ -315,9 +302,9 @@ bool DebuggerPlugin::LoadMenuElement() bool DebuggerPlugin::LoadInfoElement() { - info_element_instancer = MakeUnique< ElementInstancerGeneric >(); + info_element_instancer = MakeUnique>(); Factory::RegisterElementInstancer("debug-info", info_element_instancer.get()); - info_element = rmlui_dynamic_cast< ElementInfo* >(host_context->CreateDocument("debug-info")); + info_element = rmlui_dynamic_cast(host_context->CreateDocument("debug-info")); if (!info_element) return false; @@ -336,9 +323,9 @@ bool DebuggerPlugin::LoadInfoElement() bool DebuggerPlugin::LoadLogElement() { - log_element_instancer = MakeUnique< ElementInstancerGeneric >(); + log_element_instancer = MakeUnique>(); Factory::RegisterElementInstancer("debug-log", log_element_instancer.get()); - log_element = rmlui_dynamic_cast< ElementLog* >(host_context->CreateDocument("debug-log")); + log_element = rmlui_dynamic_cast(host_context->CreateDocument("debug-log")); if (!log_element) return false; @@ -427,5 +414,5 @@ void DebuggerPlugin::ReleaseElements() } } -} -} +} // namespace Debugger +} // namespace Rml diff --git a/Source/Debugger/DebuggerPlugin.h b/Source/Debugger/DebuggerPlugin.h index 837f754e7..36e5d68dc 100644 --- a/Source/Debugger/DebuggerPlugin.h +++ b/Source/Debugger/DebuggerPlugin.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -45,13 +45,12 @@ class ElementContextHook; class DebuggerSystemInterface; /** - RmlUi plugin interface for the debugger. + RmlUi plugin interface for the debugger. - @author Robert Curry + @author Robert Curry */ -class DebuggerPlugin : public Rml::Plugin, public Rml::EventListener -{ +class DebuggerPlugin : public Rml::Plugin, public Rml::EventListener { public: DebuggerPlugin(); ~DebuggerPlugin(); @@ -128,7 +127,7 @@ class DebuggerPlugin : public Rml::Plugin, public Rml::EventListener static DebuggerPlugin* instance; }; -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Source/Debugger/DebuggerSystemInterface.cpp b/Source/Debugger/DebuggerSystemInterface.cpp index 0c9d1a425..3e011c81d 100644 --- a/Source/Debugger/DebuggerSystemInterface.cpp +++ b/Source/Debugger/DebuggerSystemInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -43,19 +43,16 @@ DebuggerSystemInterface::~DebuggerSystemInterface() application_interface = nullptr; } -// Get the number of seconds elapsed since the start of the application. double DebuggerSystemInterface::GetElapsedTime() { return application_interface->GetElapsedTime(); } -// Translate the input string into the translated string. int DebuggerSystemInterface::TranslateString(String& translated, const String& input) { return application_interface->TranslateString(translated, input); } -// Log the specified message. bool DebuggerSystemInterface::LogMessage(Log::Type type, const String& message) { log->AddLogMessage(type, message); @@ -63,7 +60,6 @@ bool DebuggerSystemInterface::LogMessage(Log::Type type, const String& message) return application_interface->LogMessage(type, message); } -// Set mouse cursor. void DebuggerSystemInterface::SetMouseCursor(const String& cursor_name) { application_interface->SetMouseCursor(cursor_name); @@ -84,7 +80,10 @@ void DebuggerSystemInterface::ActivateKeyboard(Rml::Vector2f caret_position, flo application_interface->ActivateKeyboard(caret_position, line_height); } -void DebuggerSystemInterface::DeactivateKeyboard() { application_interface->DeactivateKeyboard(); } +void DebuggerSystemInterface::DeactivateKeyboard() +{ + application_interface->DeactivateKeyboard(); +} } // namespace Debugger } // namespace Rml diff --git a/Source/Debugger/DebuggerSystemInterface.h b/Source/Debugger/DebuggerSystemInterface.h index 626ced580..87d2d75c8 100644 --- a/Source/Debugger/DebuggerSystemInterface.h +++ b/Source/Debugger/DebuggerSystemInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,14 +37,13 @@ namespace Debugger { class ElementLog; /** - The log interface the debugger installs into RmlUi. This is a pass-through interface, so it holds onto the - application's system interface and passes all the calls through. + The log interface the debugger installs into RmlUi. This is a pass-through interface, so it holds onto the + application's system interface and passes all the calls through. - @author Peter Curry + @author Peter Curry */ -class DebuggerSystemInterface : public Rml::SystemInterface -{ +class DebuggerSystemInterface : public Rml::SystemInterface { public: /// Instances a new debugging log interface. /// @param[in] log The logging element to send messages to. @@ -81,15 +80,16 @@ class DebuggerSystemInterface : public Rml::SystemInterface /// Activate keyboard (for touchscreen devices). void ActivateKeyboard(Rml::Vector2f caret_position, float line_height) override; - + /// Deactivate keyboard (for touchscreen devices). void DeactivateKeyboard() override; + private: Rml::SystemInterface* application_interface; ElementLog* log; }; -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Source/Debugger/ElementContextHook.cpp b/Source/Debugger/ElementContextHook.cpp index 83bf09b51..b1b452686 100644 --- a/Source/Debugger/ElementContextHook.cpp +++ b/Source/Debugger/ElementContextHook.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,9 +37,7 @@ ElementContextHook::ElementContextHook(const String& tag) : ElementDocument(tag) debugger = nullptr; } -ElementContextHook::~ElementContextHook() -{ -} +ElementContextHook::~ElementContextHook() {} void ElementContextHook::Initialise(DebuggerPlugin* _debugger) { @@ -57,5 +55,5 @@ void ElementContextHook::OnRender() debugger->Render(); } -} -} +} // namespace Debugger +} // namespace Rml diff --git a/Source/Debugger/ElementContextHook.h b/Source/Debugger/ElementContextHook.h index 1074ae126..771a54bdf 100644 --- a/Source/Debugger/ElementContextHook.h +++ b/Source/Debugger/ElementContextHook.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,13 +37,12 @@ namespace Debugger { class DebuggerPlugin; /** - An element that the debugger uses to render into a foreign context. + An element that the debugger uses to render into a foreign context. - @author Peter Curry + @author Peter Curry */ -class ElementContextHook : public ElementDocument -{ +class ElementContextHook : public ElementDocument { public: RMLUI_RTTI_DefineWithParent(ElementContextHook, ElementDocument) @@ -58,7 +57,7 @@ class ElementContextHook : public ElementDocument DebuggerPlugin* debugger; }; -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Source/Debugger/ElementInfo.cpp b/Source/Debugger/ElementInfo.cpp index 01a6fdb7e..4c22f9fe8 100644 --- a/Source/Debugger/ElementInfo.cpp +++ b/Source/Debugger/ElementInfo.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -65,7 +65,6 @@ ElementInfo::~ElementInfo() RemoveEventListener(EventId::Mouseout, this); } -// Initialises the info element. bool ElementInfo::Initialise() { SetInnerRML(info_rml); @@ -84,7 +83,6 @@ bool ElementInfo::Initialise() return true; } -// Clears the element references. void ElementInfo::Reset() { hover_element = nullptr; @@ -124,7 +122,6 @@ void ElementInfo::OnUpdate() } } -// Called when an element is destroyed. void ElementInfo::OnElementDestroy(Element* element) { if (hover_element == element) @@ -146,12 +143,7 @@ void ElementInfo::RenderHoverElement() const Box& element_box = hover_element->GetBox(i, box_offset); Vector2f size = element_box.GetSize(Box::BORDER); size = Vector2f(std::max(size.x, 2.0f), std::max(size.y, 2.0f)); - Geometry::RenderOutline( - hover_element->GetAbsoluteOffset(Box::BORDER) + box_offset, - size, - Colourb(255, 0, 0, 255), - 1 - ); + Geometry::RenderOutline(hover_element->GetAbsoluteOffset(Box::BORDER) + box_offset, size, Colourb(255, 0, 0, 255), 1); } } } @@ -172,13 +164,16 @@ void ElementInfo::RenderSourceElement() Geometry::RenderBox(border_offset + element_box.GetPosition(Box::CONTENT), element_box.GetSize(), Colourb(158, 214, 237, 128)); // Padding area: - Geometry::RenderBox(border_offset + element_box.GetPosition(Box::PADDING), element_box.GetSize(Box::PADDING), border_offset + element_box.GetPosition(Box::CONTENT), element_box.GetSize(), Colourb(135, 122, 214, 128)); + Geometry::RenderBox(border_offset + element_box.GetPosition(Box::PADDING), element_box.GetSize(Box::PADDING), + border_offset + element_box.GetPosition(Box::CONTENT), element_box.GetSize(), Colourb(135, 122, 214, 128)); // Border area: - Geometry::RenderBox(border_offset + element_box.GetPosition(Box::BORDER), element_box.GetSize(Box::BORDER), border_offset + element_box.GetPosition(Box::PADDING), element_box.GetSize(Box::PADDING), Colourb(133, 133, 133, 128)); + Geometry::RenderBox(border_offset + element_box.GetPosition(Box::BORDER), element_box.GetSize(Box::BORDER), + border_offset + element_box.GetPosition(Box::PADDING), element_box.GetSize(Box::PADDING), Colourb(133, 133, 133, 128)); // Border area: - Geometry::RenderBox(border_offset + element_box.GetPosition(Box::MARGIN), element_box.GetSize(Box::MARGIN), border_offset + element_box.GetPosition(Box::BORDER), element_box.GetSize(Box::BORDER), Colourb(240, 255, 131, 128)); + Geometry::RenderBox(border_offset + element_box.GetPosition(Box::MARGIN), element_box.GetSize(Box::MARGIN), + border_offset + element_box.GetPosition(Box::BORDER), element_box.GetSize(Box::BORDER), Colourb(240, 255, 131, 128)); } } } @@ -196,7 +191,7 @@ void ElementInfo::ProcessEvent(Event& event) if (target_element->GetOwnerDocument() == this) { const String& id = event.GetTargetElement()->GetId(); - + if (id == "close_button") { if (IsVisible()) @@ -209,18 +204,20 @@ void ElementInfo::ProcessEvent(Event& event) } else if (id == "show_source") { - show_source_element = !target_element->IsClassSet("active");; + show_source_element = !target_element->IsClassSet("active"); + ; target_element->SetClass("active", show_source_element); } else if (id == "enable_element_select") { - enable_element_select = !target_element->IsClassSet("active");; + enable_element_select = !target_element->IsClassSet("active"); + ; target_element->SetClass("active", enable_element_select); } else if (target_element->GetTagName() == "pseudo" && source_element) { const String name = target_element->GetAttribute("name", ""); - + if (!name.empty()) { bool pseudo_active = target_element->IsClassSet("active"); @@ -407,7 +404,7 @@ void ElementInfo::UpdateSourceElement() Element* grandchild = child->GetChild(j); const String grandchild_name = grandchild->GetAttribute("name", ""); bool active = (EraseFromList(list, grandchild_name) == 1); - if(!active) + if (!active) child->RemoveChild(grandchild); } // Finally, create new pseudo buttons for the rest of the active pseudo classes. @@ -433,7 +430,7 @@ void ElementInfo::UpdateSourceElement() String name; String value; - // The element's attribute list is not always synchronized with its internal values, fetch + // The element's attribute list is not always synchronized with its internal values, fetch // them manually here (see e.g. Element::OnAttributeChange for relevant attributes) { name = "id"; @@ -449,12 +446,12 @@ void ElementInfo::UpdateSourceElement() } } - for(const auto& pair : source_element->GetAttributes()) + for (const auto& pair : source_element->GetAttributes()) { auto& name = pair.first; auto& variant = pair.second; String value = StringUtilities::EncodeRml(variant.Get()); - if(name != "class" && name != "style" && name != "id") + if (name != "class" && name != "style" && name != "id") attributes += CreateString(name.size() + value.size() + 32, "%s: %s
", name.c_str(), value.c_str()); } @@ -533,13 +530,12 @@ void ElementInfo::UpdateSourceElement() const Vector2f element_offset = source_element->GetRelativeOffset(Box::BORDER); const Vector2f element_size = source_element->GetBox().GetSize(Box::BORDER); Element* offset_parent = source_element->GetOffsetParent(); - const String offset_parent_rml = (offset_parent ? StringUtilities::EncodeRml(offset_parent->GetAddress(false, false)) : String("none")); + const String offset_parent_rml = + (offset_parent ? StringUtilities::EncodeRml(offset_parent->GetAddress(false, false)) : String("none")); - position = - "left: " + ToString(element_offset.x) + "px
" + - "top: " + ToString(element_offset.y) + "px
" + - "width: " + ToString(element_size.x) + "px
" + - "height: " + ToString(element_size.y) + "px
" + + position = "left: " + ToString(element_offset.x) + "px
" + "top: " + + ToString(element_offset.y) + "px
" + "width: " + ToString(element_size.x) + "px
" + + "height: " + ToString(element_size.y) + "px
" + "offset parent:

" + offset_parent_rml + "

"; } else @@ -624,7 +620,7 @@ void ElementInfo::UpdateSourceElement() children_content->RemoveChild(children_content->GetChild(0)); children_rml.clear(); } - else if(children != children_rml) + else if (children != children_rml) { children_content->SetInnerRML(children); children_rml = std::move(children); @@ -636,7 +632,7 @@ void ElementInfo::BuildElementPropertiesRML(String& property_rml, Element* eleme { NamedPropertyList property_list; - for(auto it = element->IterateLocalProperties(); !it.AtEnd(); ++it) + for (auto it = element->IterateLocalProperties(); !it.AtEnd(); ++it) { PropertyId property_id = it.GetId(); const String& property_name = it.GetName(); @@ -646,22 +642,26 @@ void ElementInfo::BuildElementPropertiesRML(String& property_rml, Element* eleme if (primary_element->GetProperty(property_id) != prop) continue; - property_list.push_back(NamedProperty{ property_name, prop }); + property_list.push_back(NamedProperty{property_name, prop}); } - std::sort(property_list.begin(), property_list.end(), - [](const NamedProperty& a, const NamedProperty& b) { - if (a.second->source && !b.second->source) return false; - if (!a.second->source && b.second->source) return true; - if (a.second->specificity < b.second->specificity) return false; - if (a.second->specificity > b.second->specificity) return true; - if (a.second->definition && !b.second->definition) return false; - if (!a.second->definition && b.second->definition) return true; - const String& a_name = StyleSheetSpecification::GetPropertyName(a.second->definition->GetId()); - const String& b_name = StyleSheetSpecification::GetPropertyName(b.second->definition->GetId()); - return a_name < b_name; - } - ); + std::sort(property_list.begin(), property_list.end(), [](const NamedProperty& a, const NamedProperty& b) { + if (a.second->source && !b.second->source) + return false; + if (!a.second->source && b.second->source) + return true; + if (a.second->specificity < b.second->specificity) + return false; + if (a.second->specificity > b.second->specificity) + return true; + if (a.second->definition && !b.second->definition) + return false; + if (!a.second->definition && b.second->definition) + return true; + const String& a_name = StyleSheetSpecification::GetPropertyName(a.second->definition->GetId()); + const String& b_name = StyleSheetSpecification::GetPropertyName(b.second->definition->GetId()); + return a_name < b_name; + }); if (!property_list.empty()) { @@ -677,7 +677,7 @@ void ElementInfo::BuildElementPropertiesRML(String& property_rml, Element* eleme for (auto& named_property : property_list) { auto& source = named_property.second->source; - if(source.get() != previous_source || first_iteration) + if (source.get() != previous_source || first_iteration) { previous_source = source.get(); first_iteration = false; @@ -733,11 +733,10 @@ void ElementInfo::UpdateTitle() } } - bool ElementInfo::IsDebuggerElement(Element* element) { return element->GetOwnerDocument()->GetId().find("rmlui-debug-") == 0; } -} -} +} // namespace Debugger +} // namespace Rml diff --git a/Source/Debugger/ElementInfo.h b/Source/Debugger/ElementInfo.h index e90ce7b66..c6696e73a 100644 --- a/Source/Debugger/ElementInfo.h +++ b/Source/Debugger/ElementInfo.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,15 +35,14 @@ namespace Rml { namespace Debugger { -typedef Pair< String, const Property* > NamedProperty; -typedef Vector< NamedProperty > NamedPropertyList; +typedef Pair NamedProperty; +typedef Vector NamedPropertyList; /** - @author Robert Curry + @author Robert Curry */ -class ElementInfo : public ElementDocument, public EventListener -{ +class ElementInfo : public ElementDocument, public EventListener { public: RMLUI_RTTI_DefineWithParent(ElementInfo, ElementDocument) @@ -90,14 +89,14 @@ class ElementInfo : public ElementDocument, public EventListener bool update_source_element; // Forces an update to the source element during the next update loop. bool force_update_once; - + bool title_dirty; Element* hover_element; Element* source_element; }; -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Source/Debugger/ElementLog.cpp b/Source/Debugger/ElementLog.cpp index df71becae..97d3342fc 100644 --- a/Source/Debugger/ElementLog.cpp +++ b/Source/Debugger/ElementLog.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,11 +27,11 @@ */ #include "ElementLog.h" -#include "CommonSource.h" -#include "BeaconSource.h" -#include "LogSource.h" #include "../../Include/RmlUi/Core/Context.h" #include "../../Include/RmlUi/Core/Factory.h" +#include "BeaconSource.h" +#include "CommonSource.h" +#include "LogSource.h" #include namespace Rml { @@ -94,7 +94,6 @@ ElementLog::~ElementLog() } } -// Initialises the log element. bool ElementLog::Initialise() { SetInnerRML(log_rml); @@ -140,7 +139,6 @@ bool ElementLog::Initialise() return true; } -// Adds a log message to the debug log. void ElementLog::AddLogMessage(Log::Type type, const String& message) { LogMessageList& log_message_list = log_types[type].log_messages; @@ -212,10 +210,11 @@ void ElementLog::OnUpdate() int num_messages = 0; while (next_type != -1 && num_messages < MAX_LOG_MESSAGES) { - messages += CreateString(128, "
%s

", log_types[next_type].class_name.c_str(), log_types[next_type].alert_contents.c_str()); + messages += CreateString(128, "

%s

", + log_types[next_type].class_name.c_str(), log_types[next_type].alert_contents.c_str()); messages += log_types[next_type].log_messages[log_pointers[next_type]].message; messages += "

"; - + log_pointers[next_type]++; next_type = FindNextEarliestLogType(log_pointers); num_messages++; @@ -229,7 +228,7 @@ void ElementLog::OnUpdate() else auto_scroll = true; - message_content->SetInnerRML(messages); + message_content->SetInnerRML(messages); dirty_logs = false; } @@ -262,7 +261,7 @@ void ElementLog::ProcessEvent(Event& event) log_types[i].log_messages.clear(); if (!log_types[i].visible) { - if (Element * button = GetElementById(log_types[i].button_name)) + if (Element* button = GetElementById(log_types[i].button_name)) button->SetInnerRML("Off"); } } @@ -288,8 +287,7 @@ void ElementLog::ProcessEvent(Event& event) if (event == EventId::Resize && auto_scroll) { - if (message_content != nullptr && - message_content->HasChildNodes()) + if (message_content != nullptr && message_content->HasChildNodes()) message_content->GetLastChild()->ScrollIntoView(); } } @@ -317,5 +315,5 @@ int ElementLog::FindNextEarliestLogType(unsigned int log_pointers[Log::LT_MAX]) return log_channel; } -} -} +} // namespace Debugger +} // namespace Rml diff --git a/Source/Debugger/ElementLog.h b/Source/Debugger/ElementLog.h index 8abc33efd..c9c7769c7 100644 --- a/Source/Debugger/ElementLog.h +++ b/Source/Debugger/ElementLog.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,11 +39,10 @@ namespace Debugger { class DebuggerSystemInterface; /** - @author Robert Curry + @author Robert Curry */ -class ElementLog : public Rml::ElementDocument, public Rml::EventListener -{ +class ElementLog : public Rml::ElementDocument, public Rml::EventListener { public: RMLUI_RTTI_DefineWithParent(ElementLog, Rml::ElementDocument) @@ -62,15 +61,13 @@ class ElementLog : public Rml::ElementDocument, public Rml::EventListener void ProcessEvent(Event& event) override; private: - struct LogMessage - { + struct LogMessage { unsigned int index; String message; }; - using LogMessageList = Vector< LogMessage >; + using LogMessageList = Vector; - struct LogType - { + struct LogType { bool visible; String class_name; String alert_contents; @@ -89,7 +86,7 @@ class ElementLog : public Rml::ElementDocument, public Rml::EventListener int current_beacon_level; }; -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Source/Debugger/FontSource.h b/Source/Debugger/FontSource.h index 454389177..48debc5d1 100644 --- a/Source/Debugger/FontSource.h +++ b/Source/Debugger/FontSource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -30,110 +30,109 @@ #define RMLUI_DEBUGGER_FONTSOURCE_H /* - The fonts 'Courier Prime Code' and 'Courier Prime Code Italic', included - in this file, are licensed under the following terms. + The fonts 'Courier Prime Code' and 'Courier Prime Code Italic', included + in this file, are licensed under the following terms. - ----------------------------------------------------------- + ----------------------------------------------------------- - Copyright (c) 2013, Quote-Unquote Apps (http://quoteunquoteapps.com), - with Reserved Font Name Courier Prime. + Copyright (c) 2013, Quote-Unquote Apps (http://quoteunquoteapps.com), + with Reserved Font Name Courier Prime. - This Font Software is licensed under the SIL Open Font License, Version 1.1. - This license is copied below, and is also available with a FAQ at: - http://scripts.sil.org/OFL + This Font Software is licensed under the SIL Open Font License, Version 1.1. + This license is copied below, and is also available with a FAQ at: + http://scripts.sil.org/OFL - ----------------------------------------------------------- - SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 - ----------------------------------------------------------- + ----------------------------------------------------------- + SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + ----------------------------------------------------------- - PREAMBLE - The goals of the Open Font License (OFL) are to stimulate worldwide - development of collaborative font projects, to support the font creation - efforts of academic and linguistic communities, and to provide a free and - open framework in which fonts may be shared and improved in partnership - with others. + PREAMBLE + The goals of the Open Font License (OFL) are to stimulate worldwide + development of collaborative font projects, to support the font creation + efforts of academic and linguistic communities, and to provide a free and + open framework in which fonts may be shared and improved in partnership + with others. - The OFL allows the licensed fonts to be used, studied, modified and - redistributed freely as long as they are not sold by themselves. The - fonts, including any derivative works, can be bundled, embedded, - redistributed and/or sold with any software provided that any reserved - names are not used by derivative works. The fonts and derivatives, - however, cannot be released under any other type of license. The - requirement for fonts to remain under this license does not apply - to any document created using the fonts or their derivatives. + The OFL allows the licensed fonts to be used, studied, modified and + redistributed freely as long as they are not sold by themselves. The + fonts, including any derivative works, can be bundled, embedded, + redistributed and/or sold with any software provided that any reserved + names are not used by derivative works. The fonts and derivatives, + however, cannot be released under any other type of license. The + requirement for fonts to remain under this license does not apply + to any document created using the fonts or their derivatives. - DEFINITIONS - "Font Software" refers to the set of files released by the Copyright - Holder(s) under this license and clearly marked as such. This may - include source files, build scripts and documentation. + DEFINITIONS + "Font Software" refers to the set of files released by the Copyright + Holder(s) under this license and clearly marked as such. This may + include source files, build scripts and documentation. - "Reserved Font Name" refers to any names specified as such after the - copyright statement(s). + "Reserved Font Name" refers to any names specified as such after the + copyright statement(s). - "Original Version" refers to the collection of Font Software components as - distributed by the Copyright Holder(s). + "Original Version" refers to the collection of Font Software components as + distributed by the Copyright Holder(s). - "Modified Version" refers to any derivative made by adding to, deleting, - or substituting -- in part or in whole -- any of the components of the - Original Version, by changing formats or by porting the Font Software to a - new environment. + "Modified Version" refers to any derivative made by adding to, deleting, + or substituting -- in part or in whole -- any of the components of the + Original Version, by changing formats or by porting the Font Software to a + new environment. - "Author" refers to any designer, engineer, programmer, technical - writer or other person who contributed to the Font Software. + "Author" refers to any designer, engineer, programmer, technical + writer or other person who contributed to the Font Software. - PERMISSION & CONDITIONS - Permission is hereby granted, free of charge, to any person obtaining - a copy of the Font Software, to use, study, copy, merge, embed, modify, - redistribute, and sell modified and unmodified copies of the Font - Software, subject to the following conditions: + PERMISSION & CONDITIONS + Permission is hereby granted, free of charge, to any person obtaining + a copy of the Font Software, to use, study, copy, merge, embed, modify, + redistribute, and sell modified and unmodified copies of the Font + Software, subject to the following conditions: - 1) Neither the Font Software nor any of its individual components, - in Original or Modified Versions, may be sold by itself. + 1) Neither the Font Software nor any of its individual components, + in Original or Modified Versions, may be sold by itself. - 2) Original or Modified Versions of the Font Software may be bundled, - redistributed and/or sold with any software, provided that each copy - contains the above copyright notice and this license. These can be - included either as stand-alone text files, human-readable headers or - in the appropriate machine-readable metadata fields within text or - binary files as long as those fields can be easily viewed by the user. + 2) Original or Modified Versions of the Font Software may be bundled, + redistributed and/or sold with any software, provided that each copy + contains the above copyright notice and this license. These can be + included either as stand-alone text files, human-readable headers or + in the appropriate machine-readable metadata fields within text or + binary files as long as those fields can be easily viewed by the user. - 3) No Modified Version of the Font Software may use the Reserved Font - Name(s) unless explicit written permission is granted by the corresponding - Copyright Holder. This restriction only applies to the primary font name as - presented to the users. + 3) No Modified Version of the Font Software may use the Reserved Font + Name(s) unless explicit written permission is granted by the corresponding + Copyright Holder. This restriction only applies to the primary font name as + presented to the users. - 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font - Software shall not be used to promote, endorse or advertise any - Modified Version, except to acknowledge the contribution(s) of the - Copyright Holder(s) and the Author(s) or with their explicit written - permission. + 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font + Software shall not be used to promote, endorse or advertise any + Modified Version, except to acknowledge the contribution(s) of the + Copyright Holder(s) and the Author(s) or with their explicit written + permission. - 5) The Font Software, modified or unmodified, in part or in whole, - must be distributed entirely under this license, and must not be - distributed under any other license. The requirement for fonts to - remain under this license does not apply to any document created - using the Font Software. + 5) The Font Software, modified or unmodified, in part or in whole, + must be distributed entirely under this license, and must not be + distributed under any other license. The requirement for fonts to + remain under this license does not apply to any document created + using the Font Software. - TERMINATION - This license becomes null and void if any of the above conditions are - not met. + TERMINATION + This license becomes null and void if any of the above conditions are + not met. - DISCLAIMER - THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE - COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL - DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM - OTHER DEALINGS IN THE FONT SOFTWARE. + DISCLAIMER + THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE + COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL + DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM + OTHER DEALINGS IN THE FONT SOFTWARE. */ - - +// clang-format off static const unsigned char courier_prime_code[] = { 0x0,0x1,0x0,0x0,0x0,0x10,0x1,0x0,0x0,0x4,0x0,0x0,0x44,0x53,0x49,0x47,0x0,0x0,0x0,0x1,0x0,0x1,0x20,0x48,0x0,0x0,0x0,0x8,0x47,0x53, 0x55,0x42,0x1a,0x6f,0xb,0xcc,0x0,0x0,0x1,0xc,0x0,0x0,0x4,0x6e,0x4f,0x53,0x2f,0x32,0x71,0x18,0x89,0x8e,0x0,0x0,0x5,0x7c,0x0,0x0,0x0,0x60, @@ -5191,5 +5190,6 @@ static const unsigned char courier_prime_code_italic[] = { 0x44,0x59,0x59,0x59,0x59,0xb3,0xe,0x8,0x1,0xc,0x2a,0xb8,0x1,0xff,0x85,0xb0,0x4,0x8d,0xb1,0x2,0x0,0x44,0xb3,0x5,0x64,0x6,0x0,0x44,0x44,0x0, 0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0 }; +// clang-format on #endif diff --git a/Source/Debugger/Geometry.cpp b/Source/Debugger/Geometry.cpp index 17a17be79..fe4e247fb 100644 --- a/Source/Debugger/Geometry.cpp +++ b/Source/Debugger/Geometry.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,16 +36,13 @@ namespace Debugger { static Context* context; -Geometry::Geometry() -{ -} +Geometry::Geometry() {} void Geometry::SetContext(Context* _context) { context = _context; } -// Renders a one-pixel rectangular outline. void Geometry::RenderOutline(const Vector2f origin, const Vector2f dimensions, const Colourb colour, float width) { if (context == nullptr) @@ -64,7 +61,6 @@ void Geometry::RenderOutline(const Vector2f origin, const Vector2f dimensions, c render_interface->RenderGeometry(vertices, 4 * 4, indices, 6 * 4, 0, origin); } -// Renders a box. void Geometry::RenderBox(const Vector2f origin, const Vector2f dimensions, const Colourb colour) { if (context == nullptr) @@ -80,8 +76,8 @@ void Geometry::RenderBox(const Vector2f origin, const Vector2f dimensions, const render_interface->RenderGeometry(vertices, 4, indices, 6, 0, origin); } -// Renders a box with a hole in the middle. -void Geometry::RenderBox(const Vector2f origin, const Vector2f dimensions, const Vector2f hole_origin, const Vector2f hole_dimensions, const Colourb colour) +void Geometry::RenderBox(const Vector2f origin, const Vector2f dimensions, const Vector2f hole_origin, const Vector2f hole_dimensions, + const Colourb colour) { // Top box. float top_y_dimensions = hole_origin.y - origin.y; @@ -112,5 +108,5 @@ void Geometry::RenderBox(const Vector2f origin, const Vector2f dimensions, const } } -} -} +} // namespace Debugger +} // namespace Rml diff --git a/Source/Debugger/Geometry.h b/Source/Debugger/Geometry.h index 949dc2a7a..f21b4aefc 100644 --- a/Source/Debugger/Geometry.h +++ b/Source/Debugger/Geometry.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,13 +38,12 @@ class Context; namespace Debugger { /** - Helper class for generating geometry for the debugger. + Helper class for generating geometry for the debugger. - @author Peter Curry + @author Peter Curry */ -class Geometry -{ +class Geometry { public: // Set the context to render through. static void SetContext(Context* context); @@ -60,7 +59,7 @@ class Geometry Geometry(); }; -} +} // namespace Debugger } // namespace Rml #endif diff --git a/Source/Debugger/InfoSource.h b/Source/Debugger/InfoSource.h index aada036ca..da00daac4 100644 --- a/Source/Debugger/InfoSource.h +++ b/Source/Debugger/InfoSource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Source/Debugger/LogSource.h b/Source/Debugger/LogSource.h index 658ad7306..b56b9e242 100644 --- a/Source/Debugger/LogSource.h +++ b/Source/Debugger/LogSource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Source/Debugger/MenuSource.h b/Source/Debugger/MenuSource.h index 49149205a..f89ef1b40 100644 --- a/Source/Debugger/MenuSource.h +++ b/Source/Debugger/MenuSource.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -82,7 +82,6 @@ span#version-number } )RCSS"; - static const char* menu_rml = R"RML(
RmlUi
diff --git a/Source/Lottie/ElementLottie.cpp b/Source/Lottie/ElementLottie.cpp index 820d2b8d5..ea124aab6 100644 --- a/Source/Lottie/ElementLottie.cpp +++ b/Source/Lottie/ElementLottie.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,8 +28,8 @@ #include "../../Include/RmlUi/Lottie/ElementLottie.h" #include "../../Include/RmlUi/Core/ComputedValues.h" -#include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/Context.h" +#include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/ElementDocument.h" #include "../../Include/RmlUi/Core/FileInterface.h" #include "../../Include/RmlUi/Core/GeometryUtilities.h" @@ -41,14 +41,9 @@ namespace Rml { +ElementLottie::ElementLottie(const String& tag) : Element(tag), geometry(this) {} -ElementLottie::ElementLottie(const String& tag) : Element(tag), geometry(this) -{ -} - -ElementLottie::~ElementLottie() -{ -} +ElementLottie::~ElementLottie() {} bool ElementLottie::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio) { @@ -78,7 +73,8 @@ void ElementLottie::OnUpdate() double _unused; const double frame_duration = 1.0 / animation->frameRate(); const double delay = std::modf((t - time_animation_start) / frame_duration, &_unused) * frame_duration; - if(IsVisible(true)) { + if (IsVisible(true)) + { if (Context* ctx = GetContext()) ctx->RequestNextUpdate(delay); } @@ -117,8 +113,8 @@ void ElementLottie::OnPropertyChange(const PropertyIdSet& changed_properties) { Element::OnPropertyChange(changed_properties); - if (changed_properties.Contains(PropertyId::ImageColor) || - changed_properties.Contains(PropertyId::Opacity)) { + if (changed_properties.Contains(PropertyId::ImageColor) || changed_properties.Contains(PropertyId::Opacity)) + { geometry_dirty = true; } } @@ -127,15 +123,15 @@ void ElementLottie::GenerateGeometry() { geometry.Release(true); - Vector< Vertex >& vertices = geometry.GetVertices(); - Vector< int >& indices = geometry.GetIndices(); + Vector& vertices = geometry.GetVertices(); + Vector& indices = geometry.GetIndices(); vertices.resize(4); indices.resize(6); Vector2f texcoords[2] = { {0.0f, 0.0f}, - {1.0f, 1.0f} + {1.0f, 1.0f}, }; const ComputedValues& computed = GetComputedValues(); diff --git a/Source/Lottie/LottiePlugin.cpp b/Source/Lottie/LottiePlugin.cpp index 84064e435..24fe4f6af 100644 --- a/Source/Lottie/LottiePlugin.cpp +++ b/Source/Lottie/LottiePlugin.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,48 +26,39 @@ * */ - -#include "../../Include/RmlUi/Lottie/ElementLottie.h" #include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/ElementInstancer.h" #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/Plugin.h" +#include "../../Include/RmlUi/Lottie/ElementLottie.h" namespace Rml { namespace Lottie { + class LottiePlugin : public Plugin { + public: + void OnInitialise() override + { + instancer = MakeUnique>(); -class LottiePlugin : public Plugin { -public: - void OnInitialise() override - { - instancer = MakeUnique >(); - - Factory::RegisterElementInstancer("lottie", instancer.get()); - - Log::Message(Log::LT_INFO, "Lottie plugin initialised."); - } + Factory::RegisterElementInstancer("lottie", instancer.get()); - void OnShutdown() override - { - delete this; - } + Log::Message(Log::LT_INFO, "Lottie plugin initialised."); + } - int GetEventClasses() override - { - return Plugin::EVT_BASIC; - } + void OnShutdown() override { delete this; } -private: - UniquePtr> instancer; -}; + int GetEventClasses() override { return Plugin::EVT_BASIC; } + private: + UniquePtr> instancer; + }; -void Initialise() -{ - RegisterPlugin(new LottiePlugin); -} + void Initialise() + { + RegisterPlugin(new LottiePlugin); + } } // namespace Lottie } // namespace Rml diff --git a/Source/Lottie/LottiePlugin.h b/Source/Lottie/LottiePlugin.h index 4645cb521..25b7c10ca 100644 --- a/Source/Lottie/LottiePlugin.h +++ b/Source/Lottie/LottiePlugin.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,13 +29,12 @@ #ifndef RMLUI_LOTTIE_LOTTIE_PLUGIN_H #define RMLUI_LOTTIE_LOTTIE_PLUGIN_H - namespace Rml { namespace Lottie { -void Initialise(); + void Initialise(); } -} +} // namespace Rml #endif diff --git a/Source/Lua/.clang-format b/Source/Lua/.clang-format new file mode 100644 index 000000000..cbb10f54a --- /dev/null +++ b/Source/Lua/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: InheritParentConfig +NamespaceIndentation: None diff --git a/Source/Lua/Colourb.cpp b/Source/Lua/Colourb.cpp index cda03f19a..ee856a3bd 100644 --- a/Source/Lua/Colourb.cpp +++ b/Source/Lua/Colourb.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,209 +25,203 @@ * THE SOFTWARE. * */ - -#include "Colourb.h" +#include "Colourb.h" namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,Colourbnew); - lua_setfield(L,metatable_index-1,"new"); + lua_pushcfunction(L, Colourbnew); + lua_setfield(L, metatable_index - 1, "new"); - lua_pushcfunction(L,Colourb__eq); - lua_setfield(L,metatable_index,"__eq"); + lua_pushcfunction(L, Colourb__eq); + lua_setfield(L, metatable_index, "__eq"); - lua_pushcfunction(L,Colourb__add); - lua_setfield(L,metatable_index,"__add"); + lua_pushcfunction(L, Colourb__add); + lua_setfield(L, metatable_index, "__add"); - lua_pushcfunction(L,Colourb__mul); - lua_setfield(L,metatable_index,"__mul"); + lua_pushcfunction(L, Colourb__mul); + lua_setfield(L, metatable_index, "__mul"); - return; + return; } int Colourbnew(lua_State* L) { - byte red = (byte)luaL_checkinteger(L,1); - byte green = (byte)luaL_checkinteger(L,2); - byte blue = (byte)luaL_checkinteger(L,3); - byte alpha = (byte)luaL_checkinteger(L,4); + byte red = (byte)luaL_checkinteger(L, 1); + byte green = (byte)luaL_checkinteger(L, 2); + byte blue = (byte)luaL_checkinteger(L, 3); + byte alpha = (byte)luaL_checkinteger(L, 4); - Colourb* col = new Colourb(red,green,blue,alpha); + Colourb* col = new Colourb(red, green, blue, alpha); - LuaType::push(L,col,true); - return 1; + LuaType::push(L, col, true); + return 1; } int Colourb__eq(lua_State* L) { - Colourb* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Colourb* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Colourb* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Colourb* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); - return 1; + lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); + return 1; } int Colourb__add(lua_State* L) { - Colourb* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Colourb* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Colourb* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Colourb* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - Colourb* res = new Colourb((*lhs) + (*rhs)); + Colourb* res = new Colourb((*lhs) + (*rhs)); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Colourb__mul(lua_State* L) { - Colourb* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - float rhs = (float)luaL_checknumber(L,2); - - Colourb* res = new Colourb((*lhs) * rhs); - - LuaType::push(L,res,true); - return 1; -} + Colourb* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + float rhs = (float)luaL_checknumber(L, 2); + + Colourb* res = new Colourb((*lhs) * rhs); + LuaType::push(L, res, true); + return 1; +} -//getters +// getters int ColourbGetAttrred(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->red); - return 1; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->red); + return 1; } int ColourbGetAttrgreen(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->green); - return 1; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->green); + return 1; } int ColourbGetAttrblue(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->blue); - return 1; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->blue); + return 1; } int ColourbGetAttralpha(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->alpha); - return 1; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->alpha); + return 1; } int ColourbGetAttrrgba(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->red); - lua_pushinteger(L,obj->green); - lua_pushinteger(L,obj->blue); - lua_pushinteger(L,obj->alpha); - return 4; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->red); + lua_pushinteger(L, obj->green); + lua_pushinteger(L, obj->blue); + lua_pushinteger(L, obj->alpha); + return 4; } - -//setters +// setters int ColourbSetAttrred(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - byte red = (byte)luaL_checkinteger(L,2); - obj->red = red; - return 0; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + byte red = (byte)luaL_checkinteger(L, 2); + obj->red = red; + return 0; } int ColourbSetAttrgreen(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - byte green = (byte)luaL_checkinteger(L,2); - obj->green = green; - return 0; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + byte green = (byte)luaL_checkinteger(L, 2); + obj->green = green; + return 0; } int ColourbSetAttrblue(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - byte blue = (byte)luaL_checkinteger(L,2); - obj->blue = blue; - return 0; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + byte blue = (byte)luaL_checkinteger(L, 2); + obj->blue = blue; + return 0; } int ColourbSetAttralpha(lua_State* L) { - Colourb* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - byte alpha = (byte)luaL_checkinteger(L,2); - obj->alpha = alpha; - return 0; + Colourb* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + byte alpha = (byte)luaL_checkinteger(L, 2); + obj->alpha = alpha; + return 0; } int ColourbSetAttrrgba(lua_State* L) { - Colourb* obj = nullptr; - int top = lua_gettop(L); - //each of the items are optional. - if(top > 0) - { - obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - if(top > 1) - { - if(top > 2) - { - if(top > 3) - obj->alpha = (byte)luaL_checkinteger(L,4); - obj->blue = (byte)luaL_checkinteger(L,3); - } - obj->green = (byte)luaL_checkinteger(L,2); - } - obj->red = (byte)luaL_checkinteger(L,1); - } - return 0; + Colourb* obj = nullptr; + int top = lua_gettop(L); + // each of the items are optional. + if (top > 0) + { + obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + if (top > 1) + { + if (top > 2) + { + if (top > 3) + obj->alpha = (byte)luaL_checkinteger(L, 4); + obj->blue = (byte)luaL_checkinteger(L, 3); + } + obj->green = (byte)luaL_checkinteger(L, 2); + } + obj->red = (byte)luaL_checkinteger(L, 1); + } + return 0; } - -RegType ColourbMethods[] = -{ - { nullptr, nullptr }, +RegType ColourbMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ColourbGetters[] = -{ - RMLUI_LUAGETTER(Colourb,red) - RMLUI_LUAGETTER(Colourb,green) - RMLUI_LUAGETTER(Colourb,blue) - RMLUI_LUAGETTER(Colourb,alpha) - RMLUI_LUAGETTER(Colourb,rgba) - { nullptr, nullptr }, +luaL_Reg ColourbGetters[] = { + RMLUI_LUAGETTER(Colourb, red), + RMLUI_LUAGETTER(Colourb, green), + RMLUI_LUAGETTER(Colourb, blue), + RMLUI_LUAGETTER(Colourb, alpha), + RMLUI_LUAGETTER(Colourb, rgba), + {nullptr, nullptr}, }; -luaL_Reg ColourbSetters[] = -{ - RMLUI_LUASETTER(Colourb,red) - RMLUI_LUASETTER(Colourb,green) - RMLUI_LUASETTER(Colourb,blue) - RMLUI_LUASETTER(Colourb,alpha) - RMLUI_LUASETTER(Colourb,rgba) - { nullptr, nullptr }, +luaL_Reg ColourbSetters[] = { + RMLUI_LUASETTER(Colourb, red), + RMLUI_LUASETTER(Colourb, green), + RMLUI_LUASETTER(Colourb, blue), + RMLUI_LUASETTER(Colourb, alpha), + RMLUI_LUASETTER(Colourb, rgba), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Colourb) diff --git a/Source/Lua/Colourb.h b/Source/Lua/Colourb.h index a2e9fc217..e152f1787 100644 --- a/Source/Lua/Colourb.h +++ b/Source/Lua/Colourb.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,31 +25,31 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_COLOURB_H #define RMLUI_LUA_COLOURB_H -#include -#include #include +#include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int Colourbnew(lua_State* L); int Colourb__eq(lua_State* L); int Colourb__add(lua_State* L); int Colourb__mul(lua_State* L); - -//getters +// getters int ColourbGetAttrred(lua_State* L); int ColourbGetAttrgreen(lua_State* L); int ColourbGetAttrblue(lua_State* L); int ColourbGetAttralpha(lua_State* L); int ColourbGetAttrrgba(lua_State* L); -//setters +// setters int ColourbSetAttrred(lua_State* L); int ColourbSetAttrgreen(lua_State* L); int ColourbSetAttrblue(lua_State* L); diff --git a/Source/Lua/Colourf.cpp b/Source/Lua/Colourf.cpp index ebe1b13b2..0729e0b62 100644 --- a/Source/Lua/Colourf.cpp +++ b/Source/Lua/Colourf.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,184 +25,177 @@ * THE SOFTWARE. * */ - -#include "Colourf.h" +#include "Colourf.h" namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,Colourfnew); - lua_setfield(L,metatable_index-1,"new"); + lua_pushcfunction(L, Colourfnew); + lua_setfield(L, metatable_index - 1, "new"); - lua_pushcfunction(L,Colourf__eq); - lua_setfield(L,metatable_index,"__eq"); + lua_pushcfunction(L, Colourf__eq); + lua_setfield(L, metatable_index, "__eq"); - return; + return; } -//metamethods +// metamethods int Colourfnew(lua_State* L) { - float red = (float)luaL_checknumber(L,1); - float green = (float)luaL_checknumber(L,2); - float blue = (float)luaL_checknumber(L,3); - float alpha = (float)luaL_checknumber(L,4); + float red = (float)luaL_checknumber(L, 1); + float green = (float)luaL_checknumber(L, 2); + float blue = (float)luaL_checknumber(L, 3); + float alpha = (float)luaL_checknumber(L, 4); - Colourf* col = new Colourf(red,green,blue,alpha); + Colourf* col = new Colourf(red, green, blue, alpha); - LuaType::push(L,col,true); - return 1; + LuaType::push(L, col, true); + return 1; } int Colourf__eq(lua_State* L) { - Colourf* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Colourf* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Colourf* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Colourf* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); - return 1; + lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); + return 1; } - -//getters +// getters int ColourfGetAttrred(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushnumber(L,obj->red); - return 1; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushnumber(L, obj->red); + return 1; } int ColourfGetAttrgreen(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushnumber(L,obj->green); - return 1; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushnumber(L, obj->green); + return 1; } int ColourfGetAttrblue(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushnumber(L,obj->blue); - return 1; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushnumber(L, obj->blue); + return 1; } int ColourfGetAttralpha(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushnumber(L,obj->alpha); - return 1; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushnumber(L, obj->alpha); + return 1; } int ColourfGetAttrrgba(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushnumber(L,obj->red); - lua_pushnumber(L,obj->green); - lua_pushnumber(L,obj->blue); - lua_pushnumber(L,obj->alpha); - return 4; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushnumber(L, obj->red); + lua_pushnumber(L, obj->green); + lua_pushnumber(L, obj->blue); + lua_pushnumber(L, obj->alpha); + return 4; } - -//setters +// setters int ColourfSetAttrred(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - float red = (float)luaL_checknumber(L,2); - obj->red = red; - return 0; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + float red = (float)luaL_checknumber(L, 2); + obj->red = red; + return 0; } int ColourfSetAttrgreen(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - float green = (float)luaL_checknumber(L,2); - obj->green = green; - return 0; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + float green = (float)luaL_checknumber(L, 2); + obj->green = green; + return 0; } int ColourfSetAttrblue(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - float blue = (float)luaL_checknumber(L,2); - obj->blue = blue; - return 0; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + float blue = (float)luaL_checknumber(L, 2); + obj->blue = blue; + return 0; } int ColourfSetAttralpha(lua_State* L) { - Colourf* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - float alpha = (float)luaL_checknumber(L,2); - obj->alpha = alpha; - return 0; + Colourf* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + float alpha = (float)luaL_checknumber(L, 2); + obj->alpha = alpha; + return 0; } int ColourfSetAttrrgba(lua_State* L) { - Colourf* obj = nullptr; - int top = lua_gettop(L); - //each of the items are optional. - if(top > 0) - { - obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - if(top > 1) - { - if(top > 2) - { - if(top > 3) - obj->alpha = (float)luaL_checknumber(L,4); - obj->blue = (float)luaL_checknumber(L,3); - } - obj->green = (float)luaL_checknumber(L,2); - } - obj->red = (float)luaL_checknumber(L,1); - } - return 0; + Colourf* obj = nullptr; + int top = lua_gettop(L); + // each of the items are optional. + if (top > 0) + { + obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + if (top > 1) + { + if (top > 2) + { + if (top > 3) + obj->alpha = (float)luaL_checknumber(L, 4); + obj->blue = (float)luaL_checknumber(L, 3); + } + obj->green = (float)luaL_checknumber(L, 2); + } + obj->red = (float)luaL_checknumber(L, 1); + } + return 0; } - -RegType ColourfMethods[] = -{ - { nullptr, nullptr }, +RegType ColourfMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ColourfGetters[] = -{ - RMLUI_LUAGETTER(Colourf,red) - RMLUI_LUAGETTER(Colourf,green) - RMLUI_LUAGETTER(Colourf,blue) - RMLUI_LUAGETTER(Colourf,alpha) - RMLUI_LUAGETTER(Colourf,rgba) - { nullptr, nullptr }, +luaL_Reg ColourfGetters[] = { + RMLUI_LUAGETTER(Colourf, red), + RMLUI_LUAGETTER(Colourf, green), + RMLUI_LUAGETTER(Colourf, blue), + RMLUI_LUAGETTER(Colourf, alpha), + RMLUI_LUAGETTER(Colourf, rgba), + {nullptr, nullptr}, }; -luaL_Reg ColourfSetters[] = -{ - RMLUI_LUASETTER(Colourf,red) - RMLUI_LUASETTER(Colourf,green) - RMLUI_LUASETTER(Colourf,blue) - RMLUI_LUASETTER(Colourf,alpha) - RMLUI_LUASETTER(Colourf,rgba) - { nullptr, nullptr }, +luaL_Reg ColourfSetters[] = { + RMLUI_LUASETTER(Colourf, red), + RMLUI_LUASETTER(Colourf, green), + RMLUI_LUASETTER(Colourf, blue), + RMLUI_LUASETTER(Colourf, alpha), + RMLUI_LUASETTER(Colourf, rgba), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Colourf) - } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Colourf.h b/Source/Lua/Colourf.h index 809ecb2dd..fc902f14b 100644 --- a/Source/Lua/Colourf.h +++ b/Source/Lua/Colourf.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,29 +25,30 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_COLOURF_H #define RMLUI_LUA_COLOURF_H +#include #include #include -#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); -//metamethods +template <> +void ExtraInit(lua_State* L, int metatable_index); +// metamethods int Colourfnew(lua_State* L); int Colourf__eq(lua_State* L); -//getters +// getters int ColourfGetAttrred(lua_State* L); int ColourfGetAttrgreen(lua_State* L); int ColourfGetAttrblue(lua_State* L); int ColourfGetAttralpha(lua_State* L); int ColourfGetAttrrgba(lua_State* L); -//setters +// setters int ColourfSetAttrred(lua_State* L); int ColourfSetAttrgreen(lua_State* L); int ColourfSetAttrblue(lua_State* L); diff --git a/Source/Lua/Context.cpp b/Source/Lua/Context.cpp index 1a2b74690..bc2b1df1c 100644 --- a/Source/Lua/Context.cpp +++ b/Source/Lua/Context.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,113 +25,118 @@ * THE SOFTWARE. * */ - + #include "Context.h" +#include "ContextDocumentsProxy.h" +#include "LuaDataModel.h" +#include "LuaEventListener.h" #include #include #include -#include "LuaEventListener.h" -#include "ContextDocumentsProxy.h" -#include "LuaDataModel.h" namespace Rml { namespace Lua { typedef ElementDocument Document; -template<> void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) { return; } +template <> +void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) +{ + return; +} -//methods +// methods int ContextAddEventListener(lua_State* L, Context* obj) { - //need to make an EventListener for Lua before I can do anything else - const char* evt = luaL_checkstring(L,1); //event + // need to make an EventListener for Lua before I can do anything else + const char* evt = luaL_checkstring(L, 1); // event Element* element = nullptr; bool capturephase = false; - //get the rest of the stuff needed to construct the listener - if(lua_gettop(L) > 2) + // get the rest of the stuff needed to construct the listener + if (lua_gettop(L) > 2) { - if(!lua_isnoneornil(L,3)) - element = LuaType::check(L,3); - if(!lua_isnoneornil(L,4)) - capturephase = RMLUI_CHECK_BOOL(L,4); - + if (!lua_isnoneornil(L, 3)) + element = LuaType::check(L, 3); + if (!lua_isnoneornil(L, 4)) + capturephase = RMLUI_CHECK_BOOL(L, 4); } - int type = lua_type(L,2); - if(type == LUA_TFUNCTION) + int type = lua_type(L, 2); + if (type == LUA_TFUNCTION) { - if(element) - element->AddEventListener(evt, new LuaEventListener(L,2,element), capturephase); + if (element) + element->AddEventListener(evt, new LuaEventListener(L, 2, element), capturephase); else - obj->AddEventListener(evt, new LuaEventListener(L,2,nullptr), capturephase); + obj->AddEventListener(evt, new LuaEventListener(L, 2, nullptr), capturephase); } - else if(type == LUA_TSTRING) + else if (type == LUA_TSTRING) { - if(element) - element->AddEventListener(evt, new LuaEventListener(luaL_checkstring(L,2),element), capturephase); + if (element) + element->AddEventListener(evt, new LuaEventListener(luaL_checkstring(L, 2), element), capturephase); else - obj->AddEventListener(evt, new LuaEventListener(luaL_checkstring(L,2),nullptr), capturephase); + obj->AddEventListener(evt, new LuaEventListener(luaL_checkstring(L, 2), nullptr), capturephase); } else { - Log::Message(Log::LT_WARNING, "Lua Context:AddEventLisener's 2nd argument can only be a Lua function or a string, you passed in a %s", lua_typename(L,type)); + Log::Message(Log::LT_WARNING, "Lua Context:AddEventLisener's 2nd argument can only be a Lua function or a string, you passed in a %s", + lua_typename(L, type)); } - return 0; + return 0; } int ContextCreateDocument(lua_State* L, Context* obj) { - const char* tag; - if(lua_gettop(L) < 1) - tag = "body"; - else - tag = luaL_checkstring(L,1); - Document* doc = obj->CreateDocument(tag); - LuaType::push(L,doc,false); - return 1; + const char* tag; + if (lua_gettop(L) < 1) + tag = "body"; + else + tag = luaL_checkstring(L, 1); + Document* doc = obj->CreateDocument(tag); + LuaType::push(L, doc, false); + return 1; } int ContextLoadDocument(lua_State* L, Context* obj) { - const char* path = luaL_checkstring(L,1); - Document* doc = obj->LoadDocument(path); - LuaType::push(L,doc,false); - return 1; + const char* path = luaL_checkstring(L, 1); + Document* doc = obj->LoadDocument(path); + LuaType::push(L, doc, false); + return 1; } int ContextRender(lua_State* L, Context* obj) { - lua_pushboolean(L,obj->Render()); - return 1; + lua_pushboolean(L, obj->Render()); + return 1; } int ContextUnloadAllDocuments(lua_State* /*L*/, Context* obj) { - obj->UnloadAllDocuments(); - return 0; + obj->UnloadAllDocuments(); + return 0; } int ContextUnloadDocument(lua_State* L, Context* obj) { - Document* doc = LuaType::check(L,1); - obj->UnloadDocument(doc); - return 0; + Document* doc = LuaType::check(L, 1); + obj->UnloadDocument(doc); + return 0; } int ContextUpdate(lua_State* L, Context* obj) { - lua_pushboolean(L,obj->Update()); - return 1; + lua_pushboolean(L, obj->Update()); + return 1; } -int ContextOpenDataModel(lua_State *L, Context *obj) +int ContextOpenDataModel(lua_State* L, Context* obj) { - if (!OpenLuaDataModel(L, obj, 1, 2)) { + if (!OpenLuaDataModel(L, obj, 1, 2)) + { // Open fails lua_pushboolean(L, false); } return 1; } -//input +// input int ContextProcessMouseMove(lua_State* L, Context* obj) { int x = (int)luaL_checkinteger(L, 1); @@ -213,127 +218,122 @@ int ContextProcessTextInput(lua_State* L, Context* obj) return 1; } -//getters +// getters int ContextGetAttrdimensions(lua_State* L) { - Context* cont = LuaType::check(L,1); - Vector2i* dim = new Vector2i(cont->GetDimensions()); - LuaType::push(L,dim,true); - return 1; + Context* cont = LuaType::check(L, 1); + Vector2i* dim = new Vector2i(cont->GetDimensions()); + LuaType::push(L, dim, true); + return 1; } -//returns a table of everything +// returns a table of everything int ContextGetAttrdocuments(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - ContextDocumentsProxy* cdp = new ContextDocumentsProxy(); - cdp->owner = cont; - LuaType::push(L,cdp,true); //does get garbage collected (deleted) - return 1; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + ContextDocumentsProxy* cdp = new ContextDocumentsProxy(); + cdp->owner = cont; + LuaType::push(L, cdp, true); // does get garbage collected (deleted) + return 1; } int ContextGetAttrdp_ratio(lua_State* L) { - Context* cont = LuaType::check(L,1); - float dp_ratio = cont->GetDensityIndependentPixelRatio(); - lua_pushnumber(L, dp_ratio); - return 1; + Context* cont = LuaType::check(L, 1); + float dp_ratio = cont->GetDensityIndependentPixelRatio(); + lua_pushnumber(L, dp_ratio); + return 1; } int ContextGetAttrfocus_element(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - LuaType::push(L,cont->GetFocusElement()); - return 1; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + LuaType::push(L, cont->GetFocusElement()); + return 1; } int ContextGetAttrhover_element(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - LuaType::push(L,cont->GetHoverElement()); - return 1; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + LuaType::push(L, cont->GetHoverElement()); + return 1; } int ContextGetAttrname(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - lua_pushstring(L,cont->GetName().c_str()); - return 1; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + lua_pushstring(L, cont->GetName().c_str()); + return 1; } int ContextGetAttrroot_element(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - LuaType::push(L,cont->GetRootElement()); - return 1; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + LuaType::push(L, cont->GetRootElement()); + return 1; } - -//setters +// setters int ContextSetAttrdimensions(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - Vector2i* dim = LuaType::check(L,2); - cont->SetDimensions(*dim); - return 0; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + Vector2i* dim = LuaType::check(L, 2); + cont->SetDimensions(*dim); + return 0; } int ContextSetAttrdp_ratio(lua_State* L) { - Context* cont = LuaType::check(L,1); - RMLUI_CHECK_OBJ(cont); - lua_Number dp_ratio = luaL_checknumber(L,2); - cont->SetDensityIndependentPixelRatio((float)dp_ratio); - return 0; + Context* cont = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(cont); + lua_Number dp_ratio = luaL_checknumber(L, 2); + cont->SetDensityIndependentPixelRatio((float)dp_ratio); + return 0; } - -RegType ContextMethods[] = -{ - RMLUI_LUAMETHOD(Context,AddEventListener) - RMLUI_LUAMETHOD(Context,CreateDocument) - RMLUI_LUAMETHOD(Context,LoadDocument) - RMLUI_LUAMETHOD(Context,Render) - RMLUI_LUAMETHOD(Context,UnloadAllDocuments) - RMLUI_LUAMETHOD(Context,UnloadDocument) - RMLUI_LUAMETHOD(Context,Update) - RMLUI_LUAMETHOD(Context,OpenDataModel) +RegType ContextMethods[] = { + RMLUI_LUAMETHOD(Context, AddEventListener), + RMLUI_LUAMETHOD(Context, CreateDocument), + RMLUI_LUAMETHOD(Context, LoadDocument), + RMLUI_LUAMETHOD(Context, Render), + RMLUI_LUAMETHOD(Context, UnloadAllDocuments), + RMLUI_LUAMETHOD(Context, UnloadDocument), + RMLUI_LUAMETHOD(Context, Update), + RMLUI_LUAMETHOD(Context, OpenDataModel), // todo: CloseDataModel - RMLUI_LUAMETHOD(Context,ProcessMouseMove) - RMLUI_LUAMETHOD(Context,ProcessMouseButtonDown) - RMLUI_LUAMETHOD(Context,ProcessMouseButtonUp) - RMLUI_LUAMETHOD(Context,ProcessMouseWheel) - RMLUI_LUAMETHOD(Context,ProcessMouseLeave) - RMLUI_LUAMETHOD(Context,IsMouseInteracting) - RMLUI_LUAMETHOD(Context,ProcessKeyDown) - RMLUI_LUAMETHOD(Context,ProcessKeyUp) - RMLUI_LUAMETHOD(Context,ProcessTextInput) -{ nullptr, nullptr }, + RMLUI_LUAMETHOD(Context, ProcessMouseMove), + RMLUI_LUAMETHOD(Context, ProcessMouseButtonDown), + RMLUI_LUAMETHOD(Context, ProcessMouseButtonUp), + RMLUI_LUAMETHOD(Context, ProcessMouseWheel), + RMLUI_LUAMETHOD(Context, ProcessMouseLeave), + RMLUI_LUAMETHOD(Context, IsMouseInteracting), + RMLUI_LUAMETHOD(Context, ProcessKeyDown), + RMLUI_LUAMETHOD(Context, ProcessKeyUp), + RMLUI_LUAMETHOD(Context, ProcessTextInput), + {nullptr, nullptr}, }; -luaL_Reg ContextGetters[] = -{ - RMLUI_LUAGETTER(Context,dimensions) - RMLUI_LUAGETTER(Context,documents) - RMLUI_LUAGETTER(Context,dp_ratio) - RMLUI_LUAGETTER(Context,focus_element) - RMLUI_LUAGETTER(Context,hover_element) - RMLUI_LUAGETTER(Context,name) - RMLUI_LUAGETTER(Context,root_element) - { nullptr, nullptr }, +luaL_Reg ContextGetters[] = { + RMLUI_LUAGETTER(Context, dimensions), + RMLUI_LUAGETTER(Context, documents), + RMLUI_LUAGETTER(Context, dp_ratio), + RMLUI_LUAGETTER(Context, focus_element), + RMLUI_LUAGETTER(Context, hover_element), + RMLUI_LUAGETTER(Context, name), + RMLUI_LUAGETTER(Context, root_element), + {nullptr, nullptr}, }; -luaL_Reg ContextSetters[] = -{ - RMLUI_LUASETTER(Context,dimensions) - RMLUI_LUASETTER(Context,dp_ratio) - { nullptr, nullptr }, +luaL_Reg ContextSetters[] = { + RMLUI_LUASETTER(Context, dimensions), + RMLUI_LUASETTER(Context, dp_ratio), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Context) diff --git a/Source/Lua/Context.h b/Source/Lua/Context.h index 9a7092693..0d5e71844 100644 --- a/Source/Lua/Context.h +++ b/Source/Lua/Context.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,20 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_CONTEXT_H #define RMLUI_LUA_CONTEXT_H -#include -#include #include - +#include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); -//methods +// methods int ContextAddEventListener(lua_State* L, Context* obj); int ContextCreateDocument(lua_State* L, Context* obj); int ContextLoadDocument(lua_State* L, Context* obj); @@ -47,7 +47,7 @@ int ContextUnloadAllDocuments(lua_State* L, Context* obj); int ContextUnloadDocument(lua_State* L, Context* obj); int ContextUpdate(lua_State* L, Context* obj); -//getters +// getters int ContextGetAttrdimensions(lua_State* L); int ContextGetAttrdocuments(lua_State* L); int ContextGetAttrdp_ratio(lua_State* L); @@ -56,11 +56,10 @@ int ContextGetAttrhover_element(lua_State* L); int ContextGetAttrname(lua_State* L); int ContextGetAttrroot_element(lua_State* L); -//setters +// setters int ContextSetAttrdimensions(lua_State* L); int ContextSetAttrdp_ratio(lua_State* L); - extern RegType ContextMethods[]; extern luaL_Reg ContextGetters[]; extern luaL_Reg ContextSetters[]; diff --git a/Source/Lua/ContextDocumentsProxy.cpp b/Source/Lua/ContextDocumentsProxy.cpp index ecc8da090..d17a273f2 100644 --- a/Source/Lua/ContextDocumentsProxy.cpp +++ b/Source/Lua/ContextDocumentsProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,113 +25,106 @@ * THE SOFTWARE. * */ - + #include "ContextDocumentsProxy.h" #include namespace Rml { namespace Lua { typedef ElementDocument Document; -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,ContextDocumentsProxy__index); - lua_setfield(L,metatable_index,"__index"); - lua_pushcfunction(L,ContextDocumentsProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); + lua_pushcfunction(L, ContextDocumentsProxy__index); + lua_setfield(L, metatable_index, "__index"); + lua_pushcfunction(L, ContextDocumentsProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); } int ContextDocumentsProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int type = lua_type(L,2); - if(type == LUA_TNUMBER || type == LUA_TSTRING) //only valid key types - { - ContextDocumentsProxy* proxy = LuaType::check(L,1); - Document* ret = nullptr; - if(type == LUA_TSTRING) - ret = proxy->owner->GetDocument(luaL_checkstring(L,2)); - else - ret = proxy->owner->GetDocument((int)luaL_checkinteger(L,2)-1); - LuaType::push(L,ret,false); - return 1; - } - else - return LuaType::index(L); - + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int type = lua_type(L, 2); + if (type == LUA_TNUMBER || type == LUA_TSTRING) // only valid key types + { + ContextDocumentsProxy* proxy = LuaType::check(L, 1); + Document* ret = nullptr; + if (type == LUA_TSTRING) + ret = proxy->owner->GetDocument(luaL_checkstring(L, 2)); + else + ret = proxy->owner->GetDocument((int)luaL_checkinteger(L, 2) - 1); + LuaType::push(L, ret, false); + return 1; + } + else + return LuaType::index(L); } -struct ContextDocumentsProxyPairs -{ - static int next(lua_State* L) - { - ContextDocumentsProxy* obj = LuaType::check(L,1); - ContextDocumentsProxyPairs* self = static_cast(lua_touserdata(L, lua_upvalueindex(1))); - Document* doc = nullptr; - int num_docs = obj->owner->GetNumDocuments(); - //because there can be missing indexes, make sure to continue until there - //is actually a document at the index - while (self->m_cur < num_docs) - { - doc = obj->owner->GetDocument(self->m_cur++); - if (doc != nullptr) - break; - } - if (doc == nullptr) - { - return 0; - } - lua_pushstring(L,doc->GetId().c_str()); - LuaType::push(L,doc); - return 2; - } - static int destroy(lua_State* L) - { - static_cast(lua_touserdata(L, 1))->~ContextDocumentsProxyPairs(); - return 0; - } - static int constructor(lua_State* L) - { - void* storage = lua_newuserdata(L, sizeof(ContextDocumentsProxyPairs)); - if (luaL_newmetatable(L, "RmlUi::Lua::ContextDocumentsProxyPairs")) - { - static luaL_Reg mt[] = - { - {"__gc", destroy}, - {NULL, NULL}, - }; - luaL_setfuncs(L, mt, 0); - } - lua_setmetatable(L, -2); - lua_pushcclosure(L, next, 1); - new (storage) ContextDocumentsProxyPairs(); - return 1; - } - ContextDocumentsProxyPairs() - : m_cur(0) - { } - int m_cur; +struct ContextDocumentsProxyPairs { + static int next(lua_State* L) + { + ContextDocumentsProxy* obj = LuaType::check(L, 1); + ContextDocumentsProxyPairs* self = static_cast(lua_touserdata(L, lua_upvalueindex(1))); + Document* doc = nullptr; + int num_docs = obj->owner->GetNumDocuments(); + // because there can be missing indexes, make sure to continue until there + // is actually a document at the index + while (self->m_cur < num_docs) + { + doc = obj->owner->GetDocument(self->m_cur++); + if (doc != nullptr) + break; + } + if (doc == nullptr) + { + return 0; + } + lua_pushstring(L, doc->GetId().c_str()); + LuaType::push(L, doc); + return 2; + } + static int destroy(lua_State* L) + { + static_cast(lua_touserdata(L, 1))->~ContextDocumentsProxyPairs(); + return 0; + } + static int constructor(lua_State* L) + { + void* storage = lua_newuserdata(L, sizeof(ContextDocumentsProxyPairs)); + if (luaL_newmetatable(L, "RmlUi::Lua::ContextDocumentsProxyPairs")) + { + static luaL_Reg mt[] = { + {"__gc", destroy}, + {NULL, NULL}, + }; + luaL_setfuncs(L, mt, 0); + } + lua_setmetatable(L, -2); + lua_pushcclosure(L, next, 1); + new (storage) ContextDocumentsProxyPairs(); + return 1; + } + ContextDocumentsProxyPairs() : m_cur(0) {} + int m_cur; }; int ContextDocumentsProxy__pairs(lua_State* L) { - ContextDocumentsProxyPairs::constructor(L); - lua_pushvalue(L, 1); - return 2; + ContextDocumentsProxyPairs::constructor(L); + lua_pushvalue(L, 1); + return 2; } -RegType ContextDocumentsProxyMethods[] = -{ - { nullptr, nullptr }, +RegType ContextDocumentsProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ContextDocumentsProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ContextDocumentsProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ContextDocumentsProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ContextDocumentsProxySetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ContextDocumentsProxy) diff --git a/Source/Lua/ContextDocumentsProxy.h b/Source/Lua/ContextDocumentsProxy.h index ed3517955..f9e1ee968 100644 --- a/Source/Lua/ContextDocumentsProxy.h +++ b/Source/Lua/ContextDocumentsProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,23 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_CONTEXTDOCUMENTSPROXY_H #define RMLUI_LUA_CONTEXTDOCUMENTSPROXY_H -#include -#include #include +#include +#include namespace Rml { namespace Lua { -//where owner is the context that we should look information from -struct ContextDocumentsProxy { Context* owner; }; +// where owner is the context that we should look information from +struct ContextDocumentsProxy { + Context* owner; +}; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int ContextDocumentsProxy__index(lua_State* L); int ContextDocumentsProxy__pairs(lua_State* L); diff --git a/Source/Lua/Document.cpp b/Source/Lua/Document.cpp index 9f3f8da07..629429284 100644 --- a/Source/Lua/Document.cpp +++ b/Source/Lua/Document.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,44 +25,45 @@ * THE SOFTWARE. * */ - + #include "Document.h" -#include -#include #include "Element.h" +#include +#include #include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - //we will inherit from Element - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index - 1); - AddTypeToElementAsTable(L); - - //create the DocumentFocus table - lua_getglobal(L,"DocumentModal"); - if(lua_isnoneornil(L,-1)) - { - lua_pop(L,1); //pop unsucessful getglobal - lua_newtable(L); //create a table for holding the enum - lua_pushinteger(L,(int)ModalFlag::None); - lua_setfield(L,-2,"None"); - lua_pushinteger(L,(int)ModalFlag::Modal); - lua_setfield(L,-2,"Modal"); + // we will inherit from Element + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); + + // create the DocumentFocus table + lua_getglobal(L, "DocumentModal"); + if (lua_isnoneornil(L, -1)) + { + lua_pop(L, 1); // pop unsucessful getglobal + lua_newtable(L); // create a table for holding the enum + lua_pushinteger(L, (int)ModalFlag::None); + lua_setfield(L, -2, "None"); + lua_pushinteger(L, (int)ModalFlag::Modal); + lua_setfield(L, -2, "Modal"); lua_pushinteger(L, (int)ModalFlag::Keep); - lua_setfield(L,-2,"Keep"); - lua_setglobal(L,"DocumentModal"); - } + lua_setfield(L, -2, "Keep"); + lua_setglobal(L, "DocumentModal"); + } - //create the DocumentFocus table + // create the DocumentFocus table lua_getglobal(L, "DocumentFocus"); if (lua_isnoneornil(L, -1)) { - lua_pop(L, 1); //pop unsucessful getglobal - lua_newtable(L); //create a table for holding the enum + lua_pop(L, 1); // pop unsucessful getglobal + lua_newtable(L); // create a table for holding the enum lua_pushinteger(L, (int)FocusFlag::None); lua_setfield(L, -2, "None"); lua_pushinteger(L, (int)FocusFlag::Document); @@ -75,120 +76,114 @@ template<> void ExtraInit(lua_State* L, int metatable_index) } } -//methods +// methods int DocumentPullToFront(lua_State* /*L*/, Document* obj) { - obj->PullToFront(); - return 0; + obj->PullToFront(); + return 0; } int DocumentPushToBack(lua_State* /*L*/, Document* obj) { - obj->PushToBack(); - return 0; + obj->PushToBack(); + return 0; } int DocumentShow(lua_State* L, Document* obj) { - int top = lua_gettop(L); - if(top == 0) - obj->Show(); - else if(top == 1) - { - ModalFlag modal = (ModalFlag)luaL_checkinteger(L,1); - obj->Show(modal); - } + int top = lua_gettop(L); + if (top == 0) + obj->Show(); + else if (top == 1) + { + ModalFlag modal = (ModalFlag)luaL_checkinteger(L, 1); + obj->Show(modal); + } else { - ModalFlag modal = (ModalFlag)luaL_checkinteger(L,1); - FocusFlag focus = (FocusFlag)luaL_checkinteger(L,2); + ModalFlag modal = (ModalFlag)luaL_checkinteger(L, 1); + FocusFlag focus = (FocusFlag)luaL_checkinteger(L, 2); obj->Show(modal, focus); } - return 0; + return 0; } int DocumentHide(lua_State* /*L*/, Document* obj) { - obj->Hide(); - return 0; + obj->Hide(); + return 0; } int DocumentClose(lua_State* /*L*/, Document* obj) { - obj->Close(); - return 0; + obj->Close(); + return 0; } int DocumentCreateElement(lua_State* L, Document* obj) { - const char* tag = luaL_checkstring(L,1); - ElementPtr* ele = new ElementPtr( obj->CreateElement(tag) ); - LuaType::push(L,ele,true); - return 1; + const char* tag = luaL_checkstring(L, 1); + ElementPtr* ele = new ElementPtr(obj->CreateElement(tag)); + LuaType::push(L, ele, true); + return 1; } int DocumentCreateTextNode(lua_State* L, Document* obj) { - //need ElementText object first - const char* text = luaL_checkstring(L,1); - ElementPtr* et = new ElementPtr( obj->CreateTextNode(text) ); - LuaType::push(L, et, true); + // need ElementText object first + const char* text = luaL_checkstring(L, 1); + ElementPtr* et = new ElementPtr(obj->CreateTextNode(text)); + LuaType::push(L, et, true); return 1; } - -//getters +// getters int DocumentGetAttrtitle(lua_State* L) { - Document* doc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(doc); - lua_pushstring(L,doc->GetTitle().c_str()); - return 1; + Document* doc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(doc); + lua_pushstring(L, doc->GetTitle().c_str()); + return 1; } int DocumentGetAttrcontext(lua_State* L) { - Document* doc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(doc); - LuaType::push(L,doc->GetContext(),false); - return 1; + Document* doc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(doc); + LuaType::push(L, doc->GetContext(), false); + return 1; } - -//setters +// setters int DocumentSetAttrtitle(lua_State* L) { - Document* doc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(doc); - const char* title = luaL_checkstring(L,2); - doc->SetTitle(title); - return 0; + Document* doc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(doc); + const char* title = luaL_checkstring(L, 2); + doc->SetTitle(title); + return 0; } - -RegType DocumentMethods[] = -{ - RMLUI_LUAMETHOD(Document,PullToFront) - RMLUI_LUAMETHOD(Document,PushToBack) - RMLUI_LUAMETHOD(Document,Show) - RMLUI_LUAMETHOD(Document,Hide) - RMLUI_LUAMETHOD(Document,Close) - RMLUI_LUAMETHOD(Document,CreateElement) - RMLUI_LUAMETHOD(Document,CreateTextNode) - { nullptr, nullptr }, +RegType DocumentMethods[] = { + RMLUI_LUAMETHOD(Document, PullToFront), + RMLUI_LUAMETHOD(Document, PushToBack), + RMLUI_LUAMETHOD(Document, Show), + RMLUI_LUAMETHOD(Document, Hide), + RMLUI_LUAMETHOD(Document, Close), + RMLUI_LUAMETHOD(Document, CreateElement), + RMLUI_LUAMETHOD(Document, CreateTextNode), + {nullptr, nullptr}, }; -luaL_Reg DocumentGetters[] = -{ - RMLUI_LUAGETTER(Document,title) - RMLUI_LUAGETTER(Document,context) - { nullptr, nullptr }, +luaL_Reg DocumentGetters[] = { + RMLUI_LUAGETTER(Document, title), + RMLUI_LUAGETTER(Document, context), + {nullptr, nullptr}, }; -luaL_Reg DocumentSetters[] = -{ - RMLUI_LUASETTER(Document,title) - { nullptr, nullptr }, +luaL_Reg DocumentSetters[] = { + RMLUI_LUASETTER(Document, title), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Document) diff --git a/Source/Lua/Document.h b/Source/Lua/Document.h index a5ccddcee..71f525cf6 100644 --- a/Source/Lua/Document.h +++ b/Source/Lua/Document.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,22 +25,22 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_DOCUMENT_H #define RMLUI_LUA_DOCUMENT_H +#include #include #include -#include - namespace Rml { namespace Lua { typedef ElementDocument Document; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); -//methods +// methods int DocumentPullToFront(lua_State* L, Document* obj); int DocumentPushToBack(lua_State* L, Document* obj); int DocumentShow(lua_State* L, Document* obj); @@ -49,11 +49,11 @@ int DocumentClose(lua_State* L, Document* obj); int DocumentCreateElement(lua_State* L, Document* obj); int DocumentCreateTextNode(lua_State* L, Document* obj); -//getters +// getters int DocumentGetAttrtitle(lua_State* L); int DocumentGetAttrcontext(lua_State* L); -//setters +// setters int DocumentSetAttrtitle(lua_State* L); extern RegType DocumentMethods[]; diff --git a/Source/Lua/Element.cpp b/Source/Lua/Element.cpp index c619f1905..0ed15e338 100644 --- a/Source/Lua/Element.cpp +++ b/Source/Lua/Element.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,75 +25,76 @@ * THE SOFTWARE. * */ - + #include "Element.h" -#include "ElementStyleProxy.h" -#include "LuaEventListener.h" #include "ElementAttributesProxy.h" #include "ElementChildNodesProxy.h" +#include "ElementStyleProxy.h" +#include "LuaEventListener.h" #include - namespace Rml { namespace Lua { typedef ElementDocument Document; -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - int top = lua_gettop(L); - //guarantee the "Element.As" table exists - lua_getfield(L,metatable_index-1,"As"); - if(lua_isnoneornil(L,-1)) //if it doesn't exist, create it - { - lua_newtable(L); - lua_setfield(L,metatable_index-1,"As"); - } - lua_pop(L,1); //pop the result of lua_getfield - lua_pushcfunction(L,Elementnew); - lua_setfield(L,metatable_index-1,"new"); - lua_settop(L,top); + int top = lua_gettop(L); + // guarantee the "Element.As" table exists + lua_getfield(L, metatable_index - 1, "As"); + if (lua_isnoneornil(L, -1)) // if it doesn't exist, create it + { + lua_newtable(L); + lua_setfield(L, metatable_index - 1, "As"); + } + lua_pop(L, 1); // pop the result of lua_getfield + lua_pushcfunction(L, Elementnew); + lua_setfield(L, metatable_index - 1, "new"); + lua_settop(L, top); } int Elementnew(lua_State* L) { - const char* tag = luaL_checkstring(L,1); - Element* ele = new Element(tag); - LuaType::push(L,ele,true); - return 1; + const char* tag = luaL_checkstring(L, 1); + Element* ele = new Element(tag); + LuaType::push(L, ele, true); + return 1; } -//methods +// methods int ElementAddEventListener(lua_State* L, Element* obj) { - int top = lua_gettop(L); - bool capture = false; - //default false if they didn't pass it in - if (top > 2) - capture = RMLUI_CHECK_BOOL(L,3); - - const char* event = luaL_checkstring(L,1); - - LuaEventListener* listener = nullptr; - int type = lua_type(L,2); - if(type == LUA_TFUNCTION) - { - listener = new LuaEventListener(L,2,obj); - } - else if(type == LUA_TSTRING) - { - const char* code = luaL_checkstring(L,2); - listener = new LuaEventListener(code,obj); - } + int top = lua_gettop(L); + bool capture = false; + // default false if they didn't pass it in + if (top > 2) + capture = RMLUI_CHECK_BOOL(L, 3); + + const char* event = luaL_checkstring(L, 1); + + LuaEventListener* listener = nullptr; + int type = lua_type(L, 2); + if (type == LUA_TFUNCTION) + { + listener = new LuaEventListener(L, 2, obj); + } + else if (type == LUA_TSTRING) + { + const char* code = luaL_checkstring(L, 2); + listener = new LuaEventListener(code, obj); + } else { - Log::Message(Log::LT_WARNING, "Lua Context:AddEventLisener's 2nd argument can only be a Lua function or a string, you passed in a %s", lua_typename(L,type)); + Log::Message(Log::LT_WARNING, "Lua Context:AddEventLisener's 2nd argument can only be a Lua function or a string, you passed in a %s", + lua_typename(L, type)); } - if(listener != nullptr) - { - obj->AddEventListener(event,listener,capture); - } - return 0; + if (listener != nullptr) + { + obj->AddEventListener(event, listener, capture); + } + return 0; } int ElementAppendChild(lua_State* L, Element* obj) @@ -102,573 +103,558 @@ int ElementAppendChild(lua_State* L, Element* obj) if (*element) obj->AppendChild(std::move(*element)); else - Log::Message(Log::LT_WARNING, "Could not append child to element '%s', as the child was null. Was it already moved from?", obj->GetAddress().c_str()); - return 0; + Log::Message(Log::LT_WARNING, "Could not append child to element '%s', as the child was null. Was it already moved from?", + obj->GetAddress().c_str()); + return 0; } int ElementBlur(lua_State* /*L*/, Element* obj) { - obj->Blur(); - return 0; + obj->Blur(); + return 0; } int ElementClick(lua_State* /*L*/, Element* obj) { - obj->Click(); - return 0; + obj->Click(); + return 0; } int ElementDispatchEvent(lua_State* L, Element* obj) { - const char* event = luaL_checkstring(L,1); - Dictionary params; - lua_pushnil(L); //becauase lua_next pops a key from the stack first, we don't want to pop the table - while(lua_next(L,2) != 0) - { - //[-1] is value, [-2] is key - int type = lua_type(L,-1); - const char* key = luaL_checkstring(L,-2); //key HAS to be a string, or things will go bad - switch(type) - { - case LUA_TNUMBER: - params[key] = (float)lua_tonumber(L,-1); - break; - case LUA_TBOOLEAN: - params[key] = RMLUI_CHECK_BOOL(L,-1); - break; - case LUA_TSTRING: - params[key] = luaL_checkstring(L,-1); - break; - case LUA_TUSERDATA: - case LUA_TLIGHTUSERDATA: - params[key] = lua_touserdata(L,-1); - break; - default: - break; - } - lua_pop(L, 1); //pops value, leaves key for next iteration - } - obj->DispatchEvent(event, params); - return 0; + const char* event = luaL_checkstring(L, 1); + Dictionary params; + lua_pushnil(L); // becauase lua_next pops a key from the stack first, we don't want to pop the table + while (lua_next(L, 2) != 0) + { + //[-1] is value, [-2] is key + int type = lua_type(L, -1); + const char* key = luaL_checkstring(L, -2); // key HAS to be a string, or things will go bad + switch (type) + { + case LUA_TNUMBER: params[key] = (float)lua_tonumber(L, -1); break; + case LUA_TBOOLEAN: params[key] = RMLUI_CHECK_BOOL(L, -1); break; + case LUA_TSTRING: params[key] = luaL_checkstring(L, -1); break; + case LUA_TUSERDATA: + case LUA_TLIGHTUSERDATA: params[key] = lua_touserdata(L, -1); break; + default: break; + } + lua_pop(L, 1); // pops value, leaves key for next iteration + } + obj->DispatchEvent(event, params); + return 0; } int ElementFocus(lua_State* /*L*/, Element* obj) { - obj->Focus(); - return 0; + obj->Focus(); + return 0; } int ElementGetAttribute(lua_State* L, Element* obj) { - const char* name = luaL_checkstring(L,1); - Variant* var = obj->GetAttribute(name); - PushVariant(L,var); - return 1; + const char* name = luaL_checkstring(L, 1); + Variant* var = obj->GetAttribute(name); + PushVariant(L, var); + return 1; } int ElementGetElementById(lua_State* L, Element* obj) { - const char* id = luaL_checkstring(L,1); - Element* ele = obj->GetElementById(id); - LuaType::push(L,ele,false); - return 1; + const char* id = luaL_checkstring(L, 1); + Element* ele = obj->GetElementById(id); + LuaType::push(L, ele, false); + return 1; } int ElementGetElementsByTagName(lua_State* L, Element* obj) { - const char* tag = luaL_checkstring(L,1); - ElementList list; - obj->GetElementsByTagName(list,tag); - lua_newtable(L); - for(unsigned int i = 0; i < list.size(); i++) - { - PushIndex(L,i); - LuaType::push(L,list[i],false); - lua_settable(L,-3); //-3 is the table - } - return 1; + const char* tag = luaL_checkstring(L, 1); + ElementList list; + obj->GetElementsByTagName(list, tag); + lua_newtable(L); + for (unsigned int i = 0; i < list.size(); i++) + { + PushIndex(L, i); + LuaType::push(L, list[i], false); + lua_settable(L, -3); //-3 is the table + } + return 1; } int ElementQuerySelector(lua_State* L, Element* obj) { - const char* sel = luaL_checkstring(L,1); - Element* ele = obj->QuerySelector(sel); - LuaType::push(L,ele,false); - return 1; + const char* sel = luaL_checkstring(L, 1); + Element* ele = obj->QuerySelector(sel); + LuaType::push(L, ele, false); + return 1; } int ElementQuerySelectorAll(lua_State* L, Element* obj) { - const char* tag = luaL_checkstring(L,1); - ElementList list; - obj->QuerySelectorAll(list,tag); - lua_newtable(L); - for(unsigned int i = 0; i < list.size(); i++) - { - PushIndex(L,i); - LuaType::push(L,list[i],false); - lua_settable(L,-3); //-3 is the table - } - return 1; + const char* tag = luaL_checkstring(L, 1); + ElementList list; + obj->QuerySelectorAll(list, tag); + lua_newtable(L); + for (unsigned int i = 0; i < list.size(); i++) + { + PushIndex(L, i); + LuaType::push(L, list[i], false); + lua_settable(L, -3); //-3 is the table + } + return 1; } int ElementHasAttribute(lua_State* L, Element* obj) { - const char* name = luaL_checkstring(L,1); - lua_pushboolean(L,obj->HasAttribute(name)); - return 1; + const char* name = luaL_checkstring(L, 1); + lua_pushboolean(L, obj->HasAttribute(name)); + return 1; } int ElementHasChildNodes(lua_State* L, Element* obj) { - lua_pushboolean(L,obj->HasChildNodes()); - return 1; + lua_pushboolean(L, obj->HasChildNodes()); + return 1; } int ElementInsertBefore(lua_State* L, Element* obj) { - ElementPtr* element = LuaType::check(L,1); - Element* adjacent = LuaType::check(L,2); - if(*element) + ElementPtr* element = LuaType::check(L, 1); + Element* adjacent = LuaType::check(L, 2); + if (*element) obj->InsertBefore(std::move(*element), adjacent); else - Log::Message(Log::LT_WARNING, "Could not insert child to element '%s', as the child was null. Was it already moved from?", obj->GetAddress().c_str()); - return 0; + Log::Message(Log::LT_WARNING, "Could not insert child to element '%s', as the child was null. Was it already moved from?", + obj->GetAddress().c_str()); + return 0; } int ElementIsClassSet(lua_State* L, Element* obj) { - const char* name = luaL_checkstring(L,1); - lua_pushboolean(L,obj->IsClassSet(name)); - return 1; + const char* name = luaL_checkstring(L, 1); + lua_pushboolean(L, obj->IsClassSet(name)); + return 1; } int ElementRemoveAttribute(lua_State* L, Element* obj) { - const char* name = luaL_checkstring(L,1); - obj->RemoveAttribute(name); - return 0; + const char* name = luaL_checkstring(L, 1); + obj->RemoveAttribute(name); + return 0; } int ElementRemoveChild(lua_State* L, Element* obj) { - Element* element = LuaType::check(L,1); - lua_pushboolean(L,static_cast(obj->RemoveChild(element))); - return 1; + Element* element = LuaType::check(L, 1); + lua_pushboolean(L, static_cast(obj->RemoveChild(element))); + return 1; } int ElementReplaceChild(lua_State* L, Element* obj) { - ElementPtr* inserted = LuaType::check(L,1); - Element* replaced = LuaType::check(L,2); - if(*inserted) - lua_pushboolean(L, static_cast(obj->ReplaceChild(std::move(*inserted),replaced))); + ElementPtr* inserted = LuaType::check(L, 1); + Element* replaced = LuaType::check(L, 2); + if (*inserted) + lua_pushboolean(L, static_cast(obj->ReplaceChild(std::move(*inserted), replaced))); else - Log::Message(Log::LT_WARNING, "Could not replace child in element '%s', as the child was null. Was it already moved from?", obj->GetAddress().c_str()); - return 1; + Log::Message(Log::LT_WARNING, "Could not replace child in element '%s', as the child was null. Was it already moved from?", + obj->GetAddress().c_str()); + return 1; } int ElementScrollIntoView(lua_State* L, Element* obj) { - bool align = RMLUI_CHECK_BOOL(L,1); - obj->ScrollIntoView(align); - return 0; + bool align = RMLUI_CHECK_BOOL(L, 1); + obj->ScrollIntoView(align); + return 0; } int ElementSetAttribute(lua_State* L, Element* obj) { - const char* name = luaL_checkstring(L,1); - const char* value = luaL_checkstring(L,2); - obj->SetAttribute(name,String(value)); - return 0; + const char* name = luaL_checkstring(L, 1); + const char* value = luaL_checkstring(L, 2); + obj->SetAttribute(name, String(value)); + return 0; } int ElementSetClass(lua_State* L, Element* obj) { - const char* name = luaL_checkstring(L,1); - bool value = RMLUI_CHECK_BOOL(L,2); - obj->SetClass(name,value); - return 0; + const char* name = luaL_checkstring(L, 1); + bool value = RMLUI_CHECK_BOOL(L, 2); + obj->SetClass(name, value); + return 0; } -//getters +// getters int ElementGetAttrattributes(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - ElementAttributesProxy* proxy = new ElementAttributesProxy(); - proxy->owner = ele; - LuaType::push(L,proxy,true); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + ElementAttributesProxy* proxy = new ElementAttributesProxy(); + proxy->owner = ele; + LuaType::push(L, proxy, true); + return 1; } int ElementGetAttrchild_nodes(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - ElementChildNodesProxy* ecnp = new ElementChildNodesProxy(); - ecnp->owner = ele; - LuaType::push(L,ecnp,true); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + ElementChildNodesProxy* ecnp = new ElementChildNodesProxy(); + ecnp->owner = ele; + LuaType::push(L, ecnp, true); + return 1; } int ElementGetAttrclass_name(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - String classnames = ele->GetClassNames(); - lua_pushstring(L,classnames.c_str()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + String classnames = ele->GetClassNames(); + lua_pushstring(L, classnames.c_str()); + return 1; } int ElementGetAttrclient_left(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetClientLeft()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetClientLeft()); + return 1; } int ElementGetAttrclient_height(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetClientHeight()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetClientHeight()); + return 1; } int ElementGetAttrclient_top(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetClientTop()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetClientTop()); + return 1; } int ElementGetAttrclient_width(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetClientWidth()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetClientWidth()); + return 1; } int ElementGetAttrfirst_child(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Element* child = ele->GetFirstChild(); - if(child == nullptr) - lua_pushnil(L); - else - LuaType::push(L,child,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Element* child = ele->GetFirstChild(); + if (child == nullptr) + lua_pushnil(L); + else + LuaType::push(L, child, false); + return 1; } int ElementGetAttrid(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushstring(L,ele->GetId().c_str()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushstring(L, ele->GetId().c_str()); + return 1; } int ElementGetAttrinner_rml(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushstring(L,ele->GetInnerRML().c_str()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushstring(L, ele->GetInnerRML().c_str()); + return 1; } int ElementGetAttrlast_child(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Element* child = ele->GetLastChild(); - if(child == nullptr) - lua_pushnil(L); - else - LuaType::push(L,child,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Element* child = ele->GetLastChild(); + if (child == nullptr) + lua_pushnil(L); + else + LuaType::push(L, child, false); + return 1; } int ElementGetAttrnext_sibling(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Element* sibling = ele->GetNextSibling(); - if(sibling == nullptr) - lua_pushnil(L); - else - LuaType::push(L,sibling,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Element* sibling = ele->GetNextSibling(); + if (sibling == nullptr) + lua_pushnil(L); + else + LuaType::push(L, sibling, false); + return 1; } int ElementGetAttroffset_height(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetOffsetHeight()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetOffsetHeight()); + return 1; } int ElementGetAttroffset_left(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetOffsetLeft()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetOffsetLeft()); + return 1; } int ElementGetAttroffset_parent(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Element* parent = ele->GetOffsetParent(); - LuaType::push(L,parent,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Element* parent = ele->GetOffsetParent(); + LuaType::push(L, parent, false); + return 1; } int ElementGetAttroffset_top(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L, ele->GetOffsetTop()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetOffsetTop()); + return 1; } int ElementGetAttroffset_width(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetOffsetWidth()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetOffsetWidth()); + return 1; } int ElementGetAttrowner_document(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Document* doc = ele->GetOwnerDocument(); - LuaType::push(L,doc,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Document* doc = ele->GetOwnerDocument(); + LuaType::push(L, doc, false); + return 1; } int ElementGetAttrparent_node(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Element* parent = ele->GetParentNode(); - if(parent == nullptr) - lua_pushnil(L); - else - LuaType::push(L,parent,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Element* parent = ele->GetParentNode(); + if (parent == nullptr) + lua_pushnil(L); + else + LuaType::push(L, parent, false); + return 1; } int ElementGetAttrprevious_sibling(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - Element* sibling = ele->GetPreviousSibling(); - if(sibling == nullptr) - lua_pushnil(L); - else - LuaType::push(L,sibling,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + Element* sibling = ele->GetPreviousSibling(); + if (sibling == nullptr) + lua_pushnil(L); + else + LuaType::push(L, sibling, false); + return 1; } int ElementGetAttrscroll_height(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetScrollHeight()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetScrollHeight()); + return 1; } int ElementGetAttrscroll_left(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetScrollLeft()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetScrollLeft()); + return 1; } int ElementGetAttrscroll_top(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetScrollTop()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetScrollTop()); + return 1; } int ElementGetAttrscroll_width(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushnumber(L,ele->GetScrollWidth()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushnumber(L, ele->GetScrollWidth()); + return 1; } int ElementGetAttrstyle(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - ElementStyleProxy* prox = new ElementStyleProxy(); - prox->owner = ele; - LuaType::push(L,prox,true); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + ElementStyleProxy* prox = new ElementStyleProxy(); + prox->owner = ele; + LuaType::push(L, prox, true); + return 1; } int ElementGetAttrtag_name(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - lua_pushstring(L,ele->GetTagName().c_str()); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + lua_pushstring(L, ele->GetTagName().c_str()); + return 1; } - -//setters +// setters int ElementSetAttrclass_name(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - const char* name = luaL_checkstring(L,2); - ele->SetClassNames(name); - return 0; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + const char* name = luaL_checkstring(L, 2); + ele->SetClassNames(name); + return 0; } int ElementSetAttrid(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - const char* id = luaL_checkstring(L,2); - ele->SetId(id); - return 0; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + const char* id = luaL_checkstring(L, 2); + ele->SetId(id); + return 0; } int ElementSetAttrinner_rml(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - const char* rml = luaL_checkstring(L,2); - ele->SetInnerRML(rml); - return 0; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + const char* rml = luaL_checkstring(L, 2); + ele->SetInnerRML(rml); + return 0; } int ElementSetAttrscroll_left(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - float scroll = (float)luaL_checknumber(L,2); - ele->SetScrollLeft(scroll); - return 0; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + float scroll = (float)luaL_checknumber(L, 2); + ele->SetScrollLeft(scroll); + return 0; } int ElementSetAttrscroll_top(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - float scroll = (float)luaL_checknumber(L,2); - ele->SetScrollTop(scroll); - return 0; -} - - -RegType ElementMethods[] = -{ - RMLUI_LUAMETHOD(Element,AddEventListener) - RMLUI_LUAMETHOD(Element,AppendChild) - RMLUI_LUAMETHOD(Element,Blur) - RMLUI_LUAMETHOD(Element,Click) - RMLUI_LUAMETHOD(Element,DispatchEvent) - RMLUI_LUAMETHOD(Element,Focus) - RMLUI_LUAMETHOD(Element,GetAttribute) - RMLUI_LUAMETHOD(Element,GetElementById) - RMLUI_LUAMETHOD(Element,GetElementsByTagName) - RMLUI_LUAMETHOD(Element,QuerySelector) - RMLUI_LUAMETHOD(Element,QuerySelectorAll) - RMLUI_LUAMETHOD(Element,HasAttribute) - RMLUI_LUAMETHOD(Element,HasChildNodes) - RMLUI_LUAMETHOD(Element,InsertBefore) - RMLUI_LUAMETHOD(Element,IsClassSet) - RMLUI_LUAMETHOD(Element,RemoveAttribute) - RMLUI_LUAMETHOD(Element,RemoveChild) - RMLUI_LUAMETHOD(Element,ReplaceChild) - RMLUI_LUAMETHOD(Element,ScrollIntoView) - RMLUI_LUAMETHOD(Element,SetAttribute) - RMLUI_LUAMETHOD(Element,SetClass) - { nullptr, nullptr }, + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + float scroll = (float)luaL_checknumber(L, 2); + ele->SetScrollTop(scroll); + return 0; +} + +RegType ElementMethods[] = { + RMLUI_LUAMETHOD(Element, AddEventListener), + RMLUI_LUAMETHOD(Element, AppendChild), + RMLUI_LUAMETHOD(Element, Blur), + RMLUI_LUAMETHOD(Element, Click), + RMLUI_LUAMETHOD(Element, DispatchEvent), + RMLUI_LUAMETHOD(Element, Focus), + RMLUI_LUAMETHOD(Element, GetAttribute), + RMLUI_LUAMETHOD(Element, GetElementById), + RMLUI_LUAMETHOD(Element, GetElementsByTagName), + RMLUI_LUAMETHOD(Element, QuerySelector), + RMLUI_LUAMETHOD(Element, QuerySelectorAll), + RMLUI_LUAMETHOD(Element, HasAttribute), + RMLUI_LUAMETHOD(Element, HasChildNodes), + RMLUI_LUAMETHOD(Element, InsertBefore), + RMLUI_LUAMETHOD(Element, IsClassSet), + RMLUI_LUAMETHOD(Element, RemoveAttribute), + RMLUI_LUAMETHOD(Element, RemoveChild), + RMLUI_LUAMETHOD(Element, ReplaceChild), + RMLUI_LUAMETHOD(Element, ScrollIntoView), + RMLUI_LUAMETHOD(Element, SetAttribute), + RMLUI_LUAMETHOD(Element, SetClass), + {nullptr, nullptr}, }; -luaL_Reg ElementGetters[] = -{ - RMLUI_LUAGETTER(Element,attributes) - RMLUI_LUAGETTER(Element,child_nodes) - RMLUI_LUAGETTER(Element,class_name) - RMLUI_LUAGETTER(Element,client_left) - RMLUI_LUAGETTER(Element,client_height) - RMLUI_LUAGETTER(Element,client_top) - RMLUI_LUAGETTER(Element,client_width) - RMLUI_LUAGETTER(Element,first_child) - RMLUI_LUAGETTER(Element,id) - RMLUI_LUAGETTER(Element,inner_rml) - RMLUI_LUAGETTER(Element,last_child) - RMLUI_LUAGETTER(Element,next_sibling) - RMLUI_LUAGETTER(Element,offset_height) - RMLUI_LUAGETTER(Element,offset_left) - RMLUI_LUAGETTER(Element,offset_parent) - RMLUI_LUAGETTER(Element,offset_top) - RMLUI_LUAGETTER(Element,offset_width) - RMLUI_LUAGETTER(Element,owner_document) - RMLUI_LUAGETTER(Element,parent_node) - RMLUI_LUAGETTER(Element,previous_sibling) - RMLUI_LUAGETTER(Element,scroll_height) - RMLUI_LUAGETTER(Element,scroll_left) - RMLUI_LUAGETTER(Element,scroll_top) - RMLUI_LUAGETTER(Element,scroll_width) - RMLUI_LUAGETTER(Element,style) - RMLUI_LUAGETTER(Element,tag_name) - { nullptr, nullptr }, +luaL_Reg ElementGetters[] = { + RMLUI_LUAGETTER(Element, attributes), + RMLUI_LUAGETTER(Element, child_nodes), + RMLUI_LUAGETTER(Element, class_name), + RMLUI_LUAGETTER(Element, client_left), + RMLUI_LUAGETTER(Element, client_height), + RMLUI_LUAGETTER(Element, client_top), + RMLUI_LUAGETTER(Element, client_width), + RMLUI_LUAGETTER(Element, first_child), + RMLUI_LUAGETTER(Element, id), + RMLUI_LUAGETTER(Element, inner_rml), + RMLUI_LUAGETTER(Element, last_child), + RMLUI_LUAGETTER(Element, next_sibling), + RMLUI_LUAGETTER(Element, offset_height), + RMLUI_LUAGETTER(Element, offset_left), + RMLUI_LUAGETTER(Element, offset_parent), + RMLUI_LUAGETTER(Element, offset_top), + RMLUI_LUAGETTER(Element, offset_width), + RMLUI_LUAGETTER(Element, owner_document), + RMLUI_LUAGETTER(Element, parent_node), + RMLUI_LUAGETTER(Element, previous_sibling), + RMLUI_LUAGETTER(Element, scroll_height), + RMLUI_LUAGETTER(Element, scroll_left), + RMLUI_LUAGETTER(Element, scroll_top), + RMLUI_LUAGETTER(Element, scroll_width), + RMLUI_LUAGETTER(Element, style), + RMLUI_LUAGETTER(Element, tag_name), + {nullptr, nullptr}, }; -luaL_Reg ElementSetters[] = -{ - RMLUI_LUASETTER(Element,class_name) - RMLUI_LUASETTER(Element,id) - RMLUI_LUASETTER(Element,inner_rml) - RMLUI_LUASETTER(Element,scroll_left) - RMLUI_LUASETTER(Element,scroll_top) - { nullptr, nullptr }, +luaL_Reg ElementSetters[] = { + RMLUI_LUASETTER(Element, class_name), + RMLUI_LUASETTER(Element, id), + RMLUI_LUASETTER(Element, inner_rml), + RMLUI_LUASETTER(Element, scroll_left), + RMLUI_LUASETTER(Element, scroll_top), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Element) - -template<> void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) +template <> +void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) { return; } -RegType ElementPtrMethods[] = -{ - { nullptr, nullptr }, +RegType ElementPtrMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementPtrGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementPtrGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementPtrSetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementPtrSetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ElementPtr) - } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Element.h b/Source/Lua/Element.h index 5f47c4702..7c2746eaa 100644 --- a/Source/Lua/Element.h +++ b/Source/Lua/Element.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,21 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENT_H #define RMLUI_LUA_ELEMENT_H -#include -#include #include +#include +#include namespace Rml { namespace Lua { -template<> RMLUILUA_API void ExtraInit(lua_State* L, int metatable_index); +template <> +RMLUILUA_API void ExtraInit(lua_State* L, int metatable_index); int Elementnew(lua_State* L); -//methods +// methods int ElementAddEventListener(lua_State* L, Element* obj); int ElementAppendChild(lua_State* L, Element* obj); int ElementBlur(lua_State* L, Element* obj); @@ -61,7 +62,7 @@ int ElementScrollIntoView(lua_State* L, Element* obj); int ElementSetAttribute(lua_State* L, Element* obj); int ElementSetClass(lua_State* L, Element* obj); -//getters +// getters int ElementGetAttrattributes(lua_State* L); int ElementGetAttrchild_nodes(lua_State* L); int ElementGetAttrclass_name(lua_State* L); @@ -89,22 +90,21 @@ int ElementGetAttrscroll_width(lua_State* L); int ElementGetAttrstyle(lua_State* L); int ElementGetAttrtag_name(lua_State* L); -//setters +// setters int ElementSetAttrclass_name(lua_State* L); int ElementSetAttrid(lua_State* L); int ElementSetAttrinner_rml(lua_State* L); int ElementSetAttrscroll_left(lua_State* L); int ElementSetAttrscroll_top(lua_State* L); - extern RegType ElementMethods[]; extern luaL_Reg ElementGetters[]; extern luaL_Reg ElementSetters[]; RMLUI_LUATYPE_DECLARE(Element) - -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int LogMessage(lua_State* L); extern RegType ElementPtrMethods[]; diff --git a/Source/Lua/ElementAttributesProxy.cpp b/Source/Lua/ElementAttributesProxy.cpp index a771d36f6..4591a8609 100644 --- a/Source/Lua/ElementAttributesProxy.cpp +++ b/Source/Lua/ElementAttributesProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,58 +25,56 @@ * THE SOFTWARE. * */ - + #include "ElementAttributesProxy.h" -#include -#include #include "Pairs.h" +#include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,ElementAttributesProxy__index); - lua_setfield(L,metatable_index,"__index"); - lua_pushcfunction(L,ElementAttributesProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); + lua_pushcfunction(L, ElementAttributesProxy__index); + lua_setfield(L, metatable_index, "__index"); + lua_pushcfunction(L, ElementAttributesProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); } int ElementAttributesProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int keytype = lua_type(L,2); - if(keytype == LUA_TSTRING) //only valid key types - { - ElementAttributesProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - const char* key = lua_tostring(L,2); - Variant* attr = obj->owner->GetAttribute(key); - PushVariant(L,attr); //Utilities.h - return 1; - } - else - return LuaType::index(L); + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int keytype = lua_type(L, 2); + if (keytype == LUA_TSTRING) // only valid key types + { + ElementAttributesProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + const char* key = lua_tostring(L, 2); + Variant* attr = obj->owner->GetAttribute(key); + PushVariant(L, attr); // Utilities.h + return 1; + } + else + return LuaType::index(L); } int ElementAttributesProxy__pairs(lua_State* L) { - ElementAttributesProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - return MakePairs(L, obj->owner->GetAttributes()); + ElementAttributesProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + return MakePairs(L, obj->owner->GetAttributes()); } -RegType ElementAttributesProxyMethods[] = -{ - { nullptr, nullptr }, +RegType ElementAttributesProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementAttributesProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementAttributesProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementAttributesProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementAttributesProxySetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ElementAttributesProxy) diff --git a/Source/Lua/ElementAttributesProxy.h b/Source/Lua/ElementAttributesProxy.h index f1fbb171b..5cf322d94 100644 --- a/Source/Lua/ElementAttributesProxy.h +++ b/Source/Lua/ElementAttributesProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,23 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTATTRIBUTESPROXY_H #define RMLUI_LUA_ELEMENTATTRIBUTESPROXY_H +#include #include #include -#include namespace Rml { namespace Lua { -//where owner is the Element that we should look up information from -struct ElementAttributesProxy { Element* owner; }; +// where owner is the Element that we should look up information from +struct ElementAttributesProxy { + Element* owner; +}; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int ElementAttributesProxy__index(lua_State* L); int ElementAttributesProxy__pairs(lua_State* L); diff --git a/Source/Lua/ElementChildNodesProxy.cpp b/Source/Lua/ElementChildNodesProxy.cpp index 1dec084ae..3a94399cd 100644 --- a/Source/Lua/ElementChildNodesProxy.cpp +++ b/Source/Lua/ElementChildNodesProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #include "ElementChildNodesProxy.h" #include "Element.h" #include "Pairs.h" @@ -33,57 +33,56 @@ namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,ElementChildNodesProxy__index); - lua_setfield(L,metatable_index,"__index"); - lua_pushcfunction(L,ElementChildNodesProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); - lua_pushcfunction(L,ElementChildNodesProxy__len); - lua_setfield(L,metatable_index,"__len"); + lua_pushcfunction(L, ElementChildNodesProxy__index); + lua_setfield(L, metatable_index, "__index"); + lua_pushcfunction(L, ElementChildNodesProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); + lua_pushcfunction(L, ElementChildNodesProxy__len); + lua_setfield(L, metatable_index, "__len"); } int ElementChildNodesProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int keytype = lua_type(L,2); - if(keytype == LUA_TNUMBER) //only valid key types - { - ElementChildNodesProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int key = (int)luaL_checkinteger(L,2); - Element* child = obj->owner->GetChild(key-1); - LuaType::push(L,child,false); - return 1; - } - else - return LuaType::index(L); + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int keytype = lua_type(L, 2); + if (keytype == LUA_TNUMBER) // only valid key types + { + ElementChildNodesProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int key = (int)luaL_checkinteger(L, 2); + Element* child = obj->owner->GetChild(key - 1); + LuaType::push(L, child, false); + return 1; + } + else + return LuaType::index(L); } int ElementChildNodesProxy__pairs(lua_State* L) { - return MakeIntPairs(L); + return MakeIntPairs(L); } int ElementChildNodesProxy__len(lua_State* L) { - ElementChildNodesProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L, obj->owner->GetNumChildren());; - return 1; + ElementChildNodesProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->owner->GetNumChildren()); + ; + return 1; } -RegType ElementChildNodesProxyMethods[] = -{ - { nullptr, nullptr }, +RegType ElementChildNodesProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementChildNodesProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementChildNodesProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementChildNodesProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementChildNodesProxySetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ElementChildNodesProxy) diff --git a/Source/Lua/ElementChildNodesProxy.h b/Source/Lua/ElementChildNodesProxy.h index 6ac4a2b23..475d8f80a 100644 --- a/Source/Lua/ElementChildNodesProxy.h +++ b/Source/Lua/ElementChildNodesProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,21 +25,23 @@ * THE SOFTWARE. * */ - #ifndef RMLUI_LUA_ELEMENTCHILDNODESPROXY_H #define RMLUI_LUA_ELEMENTCHILDNODESPROXY_H +#include #include #include -#include namespace Rml { namespace Lua { -//where owner is the Element that we should look up information from -struct ElementChildNodesProxy { Element* owner; }; +// where owner is the Element that we should look up information from +struct ElementChildNodesProxy { + Element* owner; +}; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int ElementChildNodesProxy__index(lua_State* L); int ElementChildNodesProxy__pairs(lua_State* L); int ElementChildNodesProxy__len(lua_State* L); diff --git a/Source/Lua/ElementInstancer.cpp b/Source/Lua/ElementInstancer.cpp index 642395d9f..c2064e5aa 100644 --- a/Source/Lua/ElementInstancer.cpp +++ b/Source/Lua/ElementInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,58 +26,54 @@ * */ - #include "ElementInstancer.h" - namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,ElementInstancernew); - lua_setfield(L,metatable_index-1,"new"); + lua_pushcfunction(L, ElementInstancernew); + lua_setfield(L, metatable_index - 1, "new"); } -//method +// method int ElementInstancernew(lua_State* L) { - LuaElementInstancer* lei = new LuaElementInstancer(L); - LuaType::push(L,lei,true); - return 1; + LuaElementInstancer* lei = new LuaElementInstancer(L); + LuaType::push(L, lei, true); + return 1; } -//setter +// setter int ElementInstancerSetAttrInstanceElement(lua_State* L) { - LuaElementInstancer* lei = (LuaElementInstancer*)LuaType::check(L,1); - RMLUI_CHECK_OBJ(lei); - - if(lua_type(L,2) != LUA_TFUNCTION) - { - Log::Message(Log::LT_ERROR, "The argument to ElementInstancer.InstanceElement must be a function. You passed in a %s.", luaL_typename(L,2)); - return 0; - } - lei->PushFunctionsTable(L); //top of the stack is now ELEMENTINSTANCERFUNCTIONS table - lua_pushvalue(L,2); //copy of the function - lei->ref_InstanceElement = luaL_ref(L,-2); - lua_pop(L,1); //pop the ELEMENTINSTANCERFUNCTIONS table - return 0; + LuaElementInstancer* lei = (LuaElementInstancer*)LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lei); + + if (lua_type(L, 2) != LUA_TFUNCTION) + { + Log::Message(Log::LT_ERROR, "The argument to ElementInstancer.InstanceElement must be a function. You passed in a %s.", luaL_typename(L, 2)); + return 0; + } + lei->PushFunctionsTable(L); // top of the stack is now ELEMENTINSTANCERFUNCTIONS table + lua_pushvalue(L, 2); // copy of the function + lei->ref_InstanceElement = luaL_ref(L, -2); + lua_pop(L, 1); // pop the ELEMENTINSTANCERFUNCTIONS table + return 0; } -RegType ElementInstancerMethods[] = -{ - { nullptr, nullptr }, +RegType ElementInstancerMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementInstancerGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementInstancerGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementInstancerSetters[] = -{ - RMLUI_LUASETTER(ElementInstancer,InstanceElement) - { nullptr, nullptr }, +luaL_Reg ElementInstancerSetters[] = { + RMLUI_LUASETTER(ElementInstancer, InstanceElement), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ElementInstancer) diff --git a/Source/Lua/ElementInstancer.h b/Source/Lua/ElementInstancer.h index 11fe77eda..8882ba260 100644 --- a/Source/Lua/ElementInstancer.h +++ b/Source/Lua/ElementInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,16 +29,17 @@ #ifndef RMLUI_LUA_ELEMENTINSTANCER_H #define RMLUI_LUA_ELEMENTINSTANCER_H +#include "LuaElementInstancer.h" #include #include -#include "LuaElementInstancer.h" namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); -//method +template <> +void ExtraInit(lua_State* L, int metatable_index); +// method int ElementInstancernew(lua_State* L); -//setter +// setter int ElementInstancerSetAttrInstanceElement(lua_State* L); extern RegType ElementInstancerMethods[]; diff --git a/Source/Lua/ElementStyleProxy.cpp b/Source/Lua/ElementStyleProxy.cpp index 6812e782a..d1ceea04d 100644 --- a/Source/Lua/ElementStyleProxy.cpp +++ b/Source/Lua/ElementStyleProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,146 +25,139 @@ * THE SOFTWARE. * */ - + #include "ElementStyleProxy.h" -#include -#include #include +#include #include #include -#include +#include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,ElementStyleProxy__index); - lua_setfield(L,metatable_index,"__index"); + lua_pushcfunction(L, ElementStyleProxy__index); + lua_setfield(L, metatable_index, "__index"); - lua_pushcfunction(L,ElementStyleProxy__newindex); - lua_setfield(L,metatable_index,"__newindex"); + lua_pushcfunction(L, ElementStyleProxy__newindex); + lua_setfield(L, metatable_index, "__newindex"); - lua_pushcfunction(L,ElementStyleProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); + lua_pushcfunction(L, ElementStyleProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); } int ElementStyleProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int keytype = lua_type(L,2); - if(keytype == LUA_TSTRING) //if we are trying to access a string, then we will assume that it is a property - { - ElementStyleProxy* es = LuaType::check(L,1); - RMLUI_CHECK_OBJ(es); - const Property* prop = es->owner->GetProperty(lua_tostring(L,2)); - RMLUI_CHECK_OBJ(prop) - lua_pushstring(L,prop->ToString().c_str()); - return 1; - } - else //if it wasn't trying to get a string - { - lua_settop(L,2); - return LuaType::index(L); - } + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int keytype = lua_type(L, 2); + if (keytype == LUA_TSTRING) // if we are trying to access a string, then we will assume that it is a property + { + ElementStyleProxy* es = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(es); + const Property* prop = es->owner->GetProperty(lua_tostring(L, 2)); + RMLUI_CHECK_OBJ(prop) + lua_pushstring(L, prop->ToString().c_str()); + return 1; + } + else // if it wasn't trying to get a string + { + lua_settop(L, 2); + return LuaType::index(L); + } } int ElementStyleProxy__newindex(lua_State* L) { - //[1] = obj, [2] = key, [3] = value - ElementStyleProxy* es = LuaType::check(L,1); - RMLUI_CHECK_OBJ(es); - int keytype = lua_type(L,2); - int valuetype = lua_type(L,3); - if(keytype == LUA_TSTRING ) - { - const char* key = lua_tostring(L,2); - if(valuetype == LUA_TSTRING) - { - const char* value = lua_tostring(L,3); - lua_pushboolean(L,es->owner->SetProperty(key,value)); - return 1; - } - else if (valuetype == LUA_TNIL) - { - es->owner->RemoveProperty(key); - return 0; - } - } - //everything else returns when it needs to, so we are safe to pass it - //on if needed - - lua_settop(L,3); - return LuaType::newindex(L); + //[1] = obj, [2] = key, [3] = value + ElementStyleProxy* es = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(es); + int keytype = lua_type(L, 2); + int valuetype = lua_type(L, 3); + if (keytype == LUA_TSTRING) + { + const char* key = lua_tostring(L, 2); + if (valuetype == LUA_TSTRING) + { + const char* value = lua_tostring(L, 3); + lua_pushboolean(L, es->owner->SetProperty(key, value)); + return 1; + } + else if (valuetype == LUA_TNIL) + { + es->owner->RemoveProperty(key); + return 0; + } + } + // everything else returns when it needs to, so we are safe to pass it + // on if needed + lua_settop(L, 3); + return LuaType::newindex(L); } -struct ElementStyleProxyPairs -{ - static int next(lua_State* L) - { - ElementStyleProxyPairs* self = static_cast(lua_touserdata(L, lua_upvalueindex(1))); - if (self->m_view.AtEnd()) - { - return 0; - } +struct ElementStyleProxyPairs { + static int next(lua_State* L) + { + ElementStyleProxyPairs* self = static_cast(lua_touserdata(L, lua_upvalueindex(1))); + if (self->m_view.AtEnd()) + { + return 0; + } const String& key = self->m_view.GetName(); const Property& property = self->m_view.GetProperty(); String val; - property.definition->GetValue(val, property); - lua_pushlstring(L, key.c_str(), key.size()); - lua_pushlstring(L, val.c_str(), val.size()); - ++self->m_view; - return 2; - } - static int destroy(lua_State* L) - { - static_cast(lua_touserdata(L, 1))->~ElementStyleProxyPairs(); - return 0; - } - static int constructor(lua_State* L, ElementStyleProxy* obj) - { - void* storage = lua_newuserdata(L, sizeof(ElementStyleProxyPairs)); - if (luaL_newmetatable(L, "RmlUi::Lua::ElementStyleProxyPairs")) - { - static luaL_Reg mt[] = - { - {"__gc", destroy}, - {NULL, NULL}, - }; - luaL_setfuncs(L, mt, 0); - } - lua_setmetatable(L, -2); - lua_pushcclosure(L, next, 1); - new (storage) ElementStyleProxyPairs(obj); - return 1; - } - ElementStyleProxyPairs(ElementStyleProxy* obj) - : m_view(obj->owner->IterateLocalProperties()) - { } - PropertiesIteratorView m_view; + property.definition->GetValue(val, property); + lua_pushlstring(L, key.c_str(), key.size()); + lua_pushlstring(L, val.c_str(), val.size()); + ++self->m_view; + return 2; + } + static int destroy(lua_State* L) + { + static_cast(lua_touserdata(L, 1))->~ElementStyleProxyPairs(); + return 0; + } + static int constructor(lua_State* L, ElementStyleProxy* obj) + { + void* storage = lua_newuserdata(L, sizeof(ElementStyleProxyPairs)); + if (luaL_newmetatable(L, "RmlUi::Lua::ElementStyleProxyPairs")) + { + static luaL_Reg mt[] = { + {"__gc", destroy}, + {NULL, NULL}, + }; + luaL_setfuncs(L, mt, 0); + } + lua_setmetatable(L, -2); + lua_pushcclosure(L, next, 1); + new (storage) ElementStyleProxyPairs(obj); + return 1; + } + ElementStyleProxyPairs(ElementStyleProxy* obj) : m_view(obj->owner->IterateLocalProperties()) {} + PropertiesIteratorView m_view; }; int ElementStyleProxy__pairs(lua_State* L) { - ElementStyleProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - ElementStyleProxyPairs::constructor(L, obj); - return 1; + ElementStyleProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + ElementStyleProxyPairs::constructor(L, obj); + return 1; } -RegType ElementStyleProxyMethods[] = -{ - { nullptr, nullptr }, +RegType ElementStyleProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementStyleProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementStyleProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementStyleProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementStyleProxySetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ElementStyleProxy) diff --git a/Source/Lua/ElementStyleProxy.h b/Source/Lua/ElementStyleProxy.h index 30d30ab3b..5d03692a5 100644 --- a/Source/Lua/ElementStyleProxy.h +++ b/Source/Lua/ElementStyleProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,23 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTSTYLEPROXY_H #define RMLUI_LUA_ELEMENTSTYLEPROXY_H -#include #include +#include namespace Rml { class Element; namespace Lua { -struct ElementStyleProxy { Element* owner; }; +struct ElementStyleProxy { + Element* owner; +}; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int ElementStyleProxy__index(lua_State* L); int ElementStyleProxy__newindex(lua_State* L); int ElementStyleProxy__pairs(lua_State* L); diff --git a/Source/Lua/ElementText.cpp b/Source/Lua/ElementText.cpp index ba9a8b30c..57dd8774f 100644 --- a/Source/Lua/ElementText.cpp +++ b/Source/Lua/ElementText.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,53 +25,51 @@ * THE SOFTWARE. * */ - + #include "ElementText.h" #include "Element.h" #include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - //inherit from Element - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + // inherit from Element + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } int ElementTextGetAttrtext(lua_State* L) { - ElementText* obj = LuaType::check(L, 1); - RMLUI_CHECK_OBJ(obj); - lua_pushstring(L, obj->GetText().c_str()); - return 1; + ElementText* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushstring(L, obj->GetText().c_str()); + return 1; } int ElementTextSetAttrtext(lua_State* L) { - ElementText* obj = LuaType::check(L, 1); - RMLUI_CHECK_OBJ(obj); - const char* text = luaL_checkstring(L,2); - obj->SetText(text); - return 0; + ElementText* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + const char* text = luaL_checkstring(L, 2); + obj->SetText(text); + return 0; } -RegType ElementTextMethods[] = -{ - { nullptr, nullptr }, +RegType ElementTextMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementTextGetters[] = -{ - RMLUI_LUAGETTER(ElementText,text) - { nullptr, nullptr }, +luaL_Reg ElementTextGetters[] = { + RMLUI_LUAGETTER(ElementText, text), + {nullptr, nullptr}, }; -luaL_Reg ElementTextSetters[] = -{ - RMLUI_LUASETTER(ElementText,text) - { nullptr, nullptr }, +luaL_Reg ElementTextSetters[] = { + RMLUI_LUASETTER(ElementText, text), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(ElementText) diff --git a/Source/Lua/ElementText.h b/Source/Lua/ElementText.h index d3c656834..7629728f0 100644 --- a/Source/Lua/ElementText.h +++ b/Source/Lua/ElementText.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,18 +25,19 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTTEXT_H #define RMLUI_LUA_ELEMENTTEXT_H +#include #include #include -#include namespace Rml { namespace Lua { -//will inherit from Element -template<> void ExtraInit(lua_State* L, int metatable_index); +// will inherit from Element +template <> +void ExtraInit(lua_State* L, int metatable_index); int ElementTextGetAttrtext(lua_State* L); int ElementTextSetAttrtext(lua_State* L); diff --git a/Source/Lua/Elements/As.h b/Source/Lua/Elements/As.h index 22a9efc8f..31da755cb 100644 --- a/Source/Lua/Elements/As.h +++ b/Source/Lua/Elements/As.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,44 +25,44 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_AS_H #define RMLUI_LUA_ELEMENTS_AS_H /* These are helper functions to fill up the Element.As table with types that are able to be casted */ -#include -#include #include +#include +#include namespace Rml { namespace Lua { -//Helper function for the controls, so that the types don't have to define individual functions themselves -// to fill the Elements.As table -template +// Helper function for the controls, so that the types don't have to define individual functions themselves +// to fill the Elements.As table +template int CastFromElementTo(lua_State* L) { - Element* ele = LuaType::check(L,1); - RMLUI_CHECK_OBJ(ele); - LuaType::push(L,(ToType*)ele,false); - return 1; + Element* ele = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(ele); + LuaType::push(L, (ToType*)ele, false); + return 1; } -//Adds to the Element.As table the name of the type, and the function to use to cast -template +// Adds to the Element.As table the name of the type, and the function to use to cast +template void AddCastFunctionToElementAsTable(lua_State* L) { - int top = lua_gettop(L); - lua_getglobal(L,"Element"); - lua_getfield(L,-1,"As"); - if(!lua_isnoneornil(L,-1)) - { - lua_pushcfunction(L,CastFromElementTo); - lua_setfield(L,-2,GetTClassName()); - } - lua_settop(L,top); //pop "As" and "Element" + int top = lua_gettop(L); + lua_getglobal(L, "Element"); + lua_getfield(L, -1, "As"); + if (!lua_isnoneornil(L, -1)) + { + lua_pushcfunction(L, CastFromElementTo); + lua_setfield(L, -2, GetTClassName()); + } + lua_settop(L, top); // pop "As" and "Element" } } // namespace Lua diff --git a/Source/Lua/Elements/ElementForm.cpp b/Source/Lua/Elements/ElementForm.cpp index 7ce5da23d..121af01cb 100644 --- a/Source/Lua/Elements/ElementForm.cpp +++ b/Source/Lua/Elements/ElementForm.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #include "ElementForm.h" #include #include @@ -34,45 +34,42 @@ namespace Rml { namespace Lua { -//method +// method int ElementFormSubmit(lua_State* L, ElementForm* obj) { - int top = lua_gettop(L); - const char* name = ""; - const char* value = ""; - if(top > 0) - { - name = luaL_checkstring(L,1); - if(top > 1) - value = luaL_checkstring(L,2); - } - obj->Submit(name,value); - return 0; + int top = lua_gettop(L); + const char* name = ""; + const char* value = ""; + if (top > 0) + { + name = luaL_checkstring(L, 1); + if (top > 1) + value = luaL_checkstring(L, 2); + } + obj->Submit(name, value); + return 0; } -RegType ElementFormMethods[] = -{ - RMLUI_LUAMETHOD(ElementForm,Submit) - { nullptr, nullptr }, +RegType ElementFormMethods[] = { + RMLUI_LUAMETHOD(ElementForm, Submit), + {nullptr, nullptr}, }; -luaL_Reg ElementFormGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementFormGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementFormSetters[] = -{ - { nullptr, nullptr }, +luaL_Reg ElementFormSetters[] = { + {nullptr, nullptr}, }; - -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - //inherit from Element - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + // inherit from Element + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } RMLUI_LUATYPE_DEFINE(ElementForm) } // namespace Lua diff --git a/Source/Lua/Elements/ElementForm.h b/Source/Lua/Elements/ElementForm.h index d35480631..7b0d5818b 100644 --- a/Source/Lua/Elements/ElementForm.h +++ b/Source/Lua/Elements/ElementForm.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,27 +25,27 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_ELEMENTFORM_H #define RMLUI_LUA_ELEMENTS_ELEMENTFORM_H -#include -#include #include +#include +#include namespace Rml { namespace Lua { -//method +// method int ElementFormSubmit(lua_State* L, ElementForm* obj); extern RegType ElementFormMethods[]; extern luaL_Reg ElementFormGetters[]; extern luaL_Reg ElementFormSetters[]; - -//this will be used to "inherit" from Element -template<> void ExtraInit(lua_State* L, int metatable_index); +// this will be used to "inherit" from Element +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(ElementForm) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Elements/ElementFormControl.cpp b/Source/Lua/Elements/ElementFormControl.cpp index f0bae1375..a0372794b 100644 --- a/Source/Lua/Elements/ElementFormControl.cpp +++ b/Source/Lua/Elements/ElementFormControl.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,98 +25,92 @@ * THE SOFTWARE. * */ - -#include "../Element.h" + #include "ElementFormControl.h" -#include +#include "../Element.h" #include +#include #include - namespace Rml { namespace Lua { -//getters +// getters int ElementFormControlGetAttrdisabled(lua_State* L) { - ElementFormControl* efc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(efc); - lua_pushboolean(L,efc->IsDisabled()); - return 1; + ElementFormControl* efc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(efc); + lua_pushboolean(L, efc->IsDisabled()); + return 1; } int ElementFormControlGetAttrname(lua_State* L) { - ElementFormControl* efc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(efc); - lua_pushstring(L,efc->GetName().c_str()); - return 1; + ElementFormControl* efc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(efc); + lua_pushstring(L, efc->GetName().c_str()); + return 1; } int ElementFormControlGetAttrvalue(lua_State* L) { - ElementFormControl* efc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(efc); - lua_pushstring(L,efc->GetValue().c_str()); - return 1; + ElementFormControl* efc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(efc); + lua_pushstring(L, efc->GetValue().c_str()); + return 1; } - -//setters +// setters int ElementFormControlSetAttrdisabled(lua_State* L) { - ElementFormControl* efc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(efc); - efc->SetDisabled(RMLUI_CHECK_BOOL(L,2)); - return 0; + ElementFormControl* efc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(efc); + efc->SetDisabled(RMLUI_CHECK_BOOL(L, 2)); + return 0; } int ElementFormControlSetAttrname(lua_State* L) { - ElementFormControl* efc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(efc); - const char* name = luaL_checkstring(L,2); - efc->SetName(name); - return 0; + ElementFormControl* efc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(efc); + const char* name = luaL_checkstring(L, 2); + efc->SetName(name); + return 0; } int ElementFormControlSetAttrvalue(lua_State* L) { - ElementFormControl* efc = LuaType::check(L,1); - RMLUI_CHECK_OBJ(efc); - const char* value = luaL_checkstring(L,2); - efc->SetValue(value); - return 0; + ElementFormControl* efc = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(efc); + const char* value = luaL_checkstring(L, 2); + efc->SetValue(value); + return 0; } - -RegType ElementFormControlMethods[] = -{ - { nullptr, nullptr }, +RegType ElementFormControlMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlGetters[] = -{ - RMLUI_LUAGETTER(ElementFormControl,disabled) - RMLUI_LUAGETTER(ElementFormControl,name) - RMLUI_LUAGETTER(ElementFormControl,value) - { nullptr, nullptr }, +luaL_Reg ElementFormControlGetters[] = { + RMLUI_LUAGETTER(ElementFormControl, disabled), + RMLUI_LUAGETTER(ElementFormControl, name), + RMLUI_LUAGETTER(ElementFormControl, value), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlSetters[] = -{ - RMLUI_LUASETTER(ElementFormControl,disabled) - RMLUI_LUASETTER(ElementFormControl,name) - RMLUI_LUASETTER(ElementFormControl,value) - { nullptr, nullptr }, +luaL_Reg ElementFormControlSetters[] = { + RMLUI_LUASETTER(ElementFormControl, disabled), + RMLUI_LUASETTER(ElementFormControl, name), + RMLUI_LUASETTER(ElementFormControl, value), + {nullptr, nullptr}, }; - -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } RMLUI_LUATYPE_DEFINE(ElementFormControl) } // namespace Lua diff --git a/Source/Lua/Elements/ElementFormControl.h b/Source/Lua/Elements/ElementFormControl.h index 06d7a9b18..a37f34ff1 100644 --- a/Source/Lua/Elements/ElementFormControl.h +++ b/Source/Lua/Elements/ElementFormControl.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,23 +25,23 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROL_H #define RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROL_H +#include #include #include -#include namespace Rml { namespace Lua { -//getters +// getters int ElementFormControlGetAttrdisabled(lua_State* L); int ElementFormControlGetAttrname(lua_State* L); int ElementFormControlGetAttrvalue(lua_State* L); -//setters +// setters int ElementFormControlSetAttrdisabled(lua_State* L); int ElementFormControlSetAttrname(lua_State* L); int ElementFormControlSetAttrvalue(lua_State* L); @@ -50,8 +50,8 @@ extern RegType ElementFormControlMethods[]; extern luaL_Reg ElementFormControlGetters[]; extern luaL_Reg ElementFormControlSetters[]; - -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(ElementFormControl) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Elements/ElementFormControlInput.cpp b/Source/Lua/Elements/ElementFormControlInput.cpp index be81df342..3adadd7c2 100644 --- a/Source/Lua/Elements/ElementFormControlInput.cpp +++ b/Source/Lua/Elements/ElementFormControlInput.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,186 +25,181 @@ * THE SOFTWARE. * */ - + #include "ElementFormControlInput.h" -#include #include "ElementFormControl.h" +#include #include namespace Rml { namespace Lua { -//methods +// methods int ElementFormControlInputSelect(lua_State* /*L*/, ElementFormControlInput* obj) { - obj->Select(); - return 0; + obj->Select(); + return 0; } int ElementFormControlInputSetSelection(lua_State* L, ElementFormControlInput* obj) { - int start = (int)GetIndex(L, 1); - int end = (int)GetIndex(L, 2); - obj->SetSelectionRange(start, end); - return 0; + int start = (int)GetIndex(L, 1); + int end = (int)GetIndex(L, 2); + obj->SetSelectionRange(start, end); + return 0; } int ElementFormControlInputGetSelection(lua_State* L, ElementFormControlInput* obj) { - int selection_start = 0, selection_end = 0; - String selected_text; - obj->GetSelection(&selection_start, &selection_end, &selected_text); - PushIndex(L, selection_start); - PushIndex(L, selection_end); - lua_pushstring(L, selected_text.c_str()); - return 3; + int selection_start = 0, selection_end = 0; + String selected_text; + obj->GetSelection(&selection_start, &selection_end, &selected_text); + PushIndex(L, selection_start); + PushIndex(L, selection_end); + lua_pushstring(L, selected_text.c_str()); + return 3; } -//getters +// getters int ElementFormControlInputGetAttrchecked(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushboolean(L,obj->HasAttribute("checked")); - return 1; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushboolean(L, obj->HasAttribute("checked")); + return 1; } int ElementFormControlInputGetAttrmaxlength(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetAttribute("maxlength",-1)); - return 1; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetAttribute("maxlength", -1)); + return 1; } int ElementFormControlInputGetAttrsize(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetAttribute("size",20)); - return 1; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetAttribute("size", 20)); + return 1; } int ElementFormControlInputGetAttrmax(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetAttribute("max",100)); - return 1; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetAttribute("max", 100)); + return 1; } int ElementFormControlInputGetAttrmin(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetAttribute("min",0)); - return 1; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetAttribute("min", 0)); + return 1; } int ElementFormControlInputGetAttrstep(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetAttribute("step",1)); - return 1; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetAttribute("step", 1)); + return 1; } - -//setters +// setters int ElementFormControlInputSetAttrchecked(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - bool checked = RMLUI_CHECK_BOOL(L,2); - if(checked) - obj->SetAttribute("checked",true); - else - obj->RemoveAttribute("checked"); - return 0; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + bool checked = RMLUI_CHECK_BOOL(L, 2); + if (checked) + obj->SetAttribute("checked", true); + else + obj->RemoveAttribute("checked"); + return 0; } int ElementFormControlInputSetAttrmaxlength(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int maxlength = (int)luaL_checkinteger(L,2); - obj->SetAttribute("maxlength",maxlength); - return 0; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int maxlength = (int)luaL_checkinteger(L, 2); + obj->SetAttribute("maxlength", maxlength); + return 0; } int ElementFormControlInputSetAttrsize(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int size = (int)luaL_checkinteger(L,2); - obj->SetAttribute("size",size); - return 0; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int size = (int)luaL_checkinteger(L, 2); + obj->SetAttribute("size", size); + return 0; } int ElementFormControlInputSetAttrmax(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int max = (int)luaL_checkinteger(L,2); - obj->SetAttribute("max",max); - return 0; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int max = (int)luaL_checkinteger(L, 2); + obj->SetAttribute("max", max); + return 0; } int ElementFormControlInputSetAttrmin(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int min = (int)luaL_checkinteger(L,2); - obj->SetAttribute("min",min); - return 0; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int min = (int)luaL_checkinteger(L, 2); + obj->SetAttribute("min", min); + return 0; } int ElementFormControlInputSetAttrstep(lua_State* L) { - ElementFormControlInput* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int step = (int)luaL_checkinteger(L,2); - obj->SetAttribute("step",step); - return 0; + ElementFormControlInput* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int step = (int)luaL_checkinteger(L, 2); + obj->SetAttribute("step", step); + return 0; } - -RegType ElementFormControlInputMethods[] = -{ - RMLUI_LUAMETHOD(ElementFormControlInput,Select) - RMLUI_LUAMETHOD(ElementFormControlInput,SetSelection) - RMLUI_LUAMETHOD(ElementFormControlInput,GetSelection) - {nullptr,nullptr}, +RegType ElementFormControlInputMethods[] = { + RMLUI_LUAMETHOD(ElementFormControlInput, Select), + RMLUI_LUAMETHOD(ElementFormControlInput, SetSelection), + RMLUI_LUAMETHOD(ElementFormControlInput, GetSelection), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlInputGetters[] = -{ - RMLUI_LUAGETTER(ElementFormControlInput,checked) - RMLUI_LUAGETTER(ElementFormControlInput,maxlength) - RMLUI_LUAGETTER(ElementFormControlInput,size) - RMLUI_LUAGETTER(ElementFormControlInput,max) - RMLUI_LUAGETTER(ElementFormControlInput,min) - RMLUI_LUAGETTER(ElementFormControlInput,step) - {nullptr,nullptr}, +luaL_Reg ElementFormControlInputGetters[] = { + RMLUI_LUAGETTER(ElementFormControlInput, checked), + RMLUI_LUAGETTER(ElementFormControlInput, maxlength), + RMLUI_LUAGETTER(ElementFormControlInput, size), + RMLUI_LUAGETTER(ElementFormControlInput, max), + RMLUI_LUAGETTER(ElementFormControlInput, min), + RMLUI_LUAGETTER(ElementFormControlInput, step), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlInputSetters[] = -{ - RMLUI_LUASETTER(ElementFormControlInput,checked) - RMLUI_LUASETTER(ElementFormControlInput,maxlength) - RMLUI_LUASETTER(ElementFormControlInput,size) - RMLUI_LUASETTER(ElementFormControlInput,max) - RMLUI_LUASETTER(ElementFormControlInput,min) - RMLUI_LUASETTER(ElementFormControlInput,step) - {nullptr,nullptr}, +luaL_Reg ElementFormControlInputSetters[] = { + RMLUI_LUASETTER(ElementFormControlInput, checked), + RMLUI_LUASETTER(ElementFormControlInput, maxlength), + RMLUI_LUASETTER(ElementFormControlInput, size), + RMLUI_LUASETTER(ElementFormControlInput, max), + RMLUI_LUASETTER(ElementFormControlInput, min), + RMLUI_LUASETTER(ElementFormControlInput, step), + {nullptr, nullptr}, }; - -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } RMLUI_LUATYPE_DEFINE(ElementFormControlInput) } // namespace Lua diff --git a/Source/Lua/Elements/ElementFormControlInput.h b/Source/Lua/Elements/ElementFormControlInput.h index db49632c1..0a75ed16d 100644 --- a/Source/Lua/Elements/ElementFormControlInput.h +++ b/Source/Lua/Elements/ElementFormControlInput.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,23 +25,23 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROLINPUT_H #define RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROLINPUT_H +#include #include #include -#include namespace Rml { namespace Lua { -//methods +// methods int ElementFormControlInputSelect(lua_State* L, ElementFormControlInput* obj); int ElementFormControlInputSetSelection(lua_State* L, ElementFormControlInput* obj); int ElementFormControlInputGetSelection(lua_State* L, ElementFormControlInput* obj); -//getters +// getters int ElementFormControlInputGetAttrchecked(lua_State* L); int ElementFormControlInputGetAttrmaxlength(lua_State* L); int ElementFormControlInputGetAttrsize(lua_State* L); @@ -49,7 +49,7 @@ int ElementFormControlInputGetAttrmax(lua_State* L); int ElementFormControlInputGetAttrmin(lua_State* L); int ElementFormControlInputGetAttrstep(lua_State* L); -//setters +// setters int ElementFormControlInputSetAttrchecked(lua_State* L); int ElementFormControlInputSetAttrmaxlength(lua_State* L); int ElementFormControlInputSetAttrsize(lua_State* L); @@ -61,9 +61,9 @@ extern RegType ElementFormControlInputMethods[]; extern luaL_Reg ElementFormControlInputGetters[]; extern luaL_Reg ElementFormControlInputSetters[]; - -//inherits from ElementFormControl which inherits from Element -template<> void ExtraInit(lua_State* L, int metatable_index); +// inherits from ElementFormControl which inherits from Element +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(ElementFormControlInput) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Elements/ElementFormControlSelect.cpp b/Source/Lua/Elements/ElementFormControlSelect.cpp index 87dc3b1d6..ff3a7af74 100644 --- a/Source/Lua/Elements/ElementFormControlSelect.cpp +++ b/Source/Lua/Elements/ElementFormControlSelect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,108 +25,102 @@ * THE SOFTWARE. * */ - + #include "ElementFormControlSelect.h" +#include "ElementFormControl.h" #include "SelectOptionsProxy.h" -#include -#include #include -#include "ElementFormControl.h" +#include +#include #include - namespace Rml { namespace Lua { -//methods +// methods int ElementFormControlSelectAdd(lua_State* L, ElementFormControlSelect* obj) { - const char* rml = luaL_checkstring(L,1); - const char* value = luaL_checkstring(L,2); - int before = -1; //default - if(lua_gettop(L) >= 3) - before = GetIndex(L,3); - - int index = obj->Add(rml,value,before); - lua_pushinteger(L,index); - return 1; + const char* rml = luaL_checkstring(L, 1); + const char* value = luaL_checkstring(L, 2); + int before = -1; // default + if (lua_gettop(L) >= 3) + before = GetIndex(L, 3); + + int index = obj->Add(rml, value, before); + lua_pushinteger(L, index); + return 1; } int ElementFormControlSelectRemove(lua_State* L, ElementFormControlSelect* obj) { - int index = GetIndex(L,1); - obj->Remove(index); - return 0; + int index = GetIndex(L, 1); + obj->Remove(index); + return 0; } int ElementFormControlSelectRemoveAll(lua_State* /*L*/, ElementFormControlSelect* obj) { - obj->RemoveAll(); - return 0; + obj->RemoveAll(); + return 0; } -//getters +// getters int ElementFormControlSelectGetAttroptions(lua_State* L) { - ElementFormControlSelect* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - SelectOptionsProxy* proxy = new SelectOptionsProxy(); - proxy->owner = obj; - LuaType::push(L,proxy,true); - return 1; + ElementFormControlSelect* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + SelectOptionsProxy* proxy = new SelectOptionsProxy(); + proxy->owner = obj; + LuaType::push(L, proxy, true); + return 1; } int ElementFormControlSelectGetAttrselection(lua_State* L) { - ElementFormControlSelect* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int selection = obj->GetSelection(); - PushIndex(L,selection); - return 1; + ElementFormControlSelect* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int selection = obj->GetSelection(); + PushIndex(L, selection); + return 1; } - -//setter +// setter int ElementFormControlSelectSetAttrselection(lua_State* L) { - ElementFormControlSelect* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int selection = GetIndex(L,2); - obj->SetSelection(selection); - return 0; + ElementFormControlSelect* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int selection = GetIndex(L, 2); + obj->SetSelection(selection); + return 0; } - -RegType ElementFormControlSelectMethods[] = -{ - RMLUI_LUAMETHOD(ElementFormControlSelect,Add) - RMLUI_LUAMETHOD(ElementFormControlSelect,Remove) - RMLUI_LUAMETHOD(ElementFormControlSelect,RemoveAll) - { nullptr, nullptr }, +RegType ElementFormControlSelectMethods[] = { + RMLUI_LUAMETHOD(ElementFormControlSelect, Add), + RMLUI_LUAMETHOD(ElementFormControlSelect, Remove), + RMLUI_LUAMETHOD(ElementFormControlSelect, RemoveAll), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlSelectGetters[] = -{ - RMLUI_LUAGETTER(ElementFormControlSelect,options) - RMLUI_LUAGETTER(ElementFormControlSelect,selection) - { nullptr, nullptr }, +luaL_Reg ElementFormControlSelectGetters[] = { + RMLUI_LUAGETTER(ElementFormControlSelect, options), + RMLUI_LUAGETTER(ElementFormControlSelect, selection), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlSelectSetters[] = -{ - RMLUI_LUASETTER(ElementFormControlSelect,selection) - { nullptr, nullptr }, +luaL_Reg ElementFormControlSelectSetters[] = { + RMLUI_LUASETTER(ElementFormControlSelect, selection), + {nullptr, nullptr}, }; - -//inherits from ElementFormControl which inherits from Element -template<> void ExtraInit(lua_State* L, int metatable_index) +// inherits from ElementFormControl which inherits from Element +template <> +void ExtraInit(lua_State* L, int metatable_index) { - //init whatever elementformcontrol did extra, like inheritance - ExtraInit(L,metatable_index); - //then inherit from elementformcontrol - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + // init whatever elementformcontrol did extra, like inheritance + ExtraInit(L, metatable_index); + // then inherit from elementformcontrol + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } RMLUI_LUATYPE_DEFINE(ElementFormControlSelect) } // namespace Lua diff --git a/Source/Lua/Elements/ElementFormControlSelect.h b/Source/Lua/Elements/ElementFormControlSelect.h index d4e0c48ad..a06c567bb 100644 --- a/Source/Lua/Elements/ElementFormControlSelect.h +++ b/Source/Lua/Elements/ElementFormControlSelect.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,35 +25,35 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROLSELECT_H #define RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROLSELECT_H +#include #include #include -#include namespace Rml { namespace Lua { -//methods +// methods int ElementFormControlSelectAdd(lua_State* L, ElementFormControlSelect* obj); int ElementFormControlSelectRemove(lua_State* L, ElementFormControlSelect* obj); -//getters +// getters int ElementFormControlSelectGetAttroptions(lua_State* L); int ElementFormControlSelectGetAttrselection(lua_State* L); -//setter +// setter int ElementFormControlSelectSetAttrselection(lua_State* L); extern RegType ElementFormControlSelectMethods[]; extern luaL_Reg ElementFormControlSelectGetters[]; extern luaL_Reg ElementFormControlSelectSetters[]; - -//inherits from ElementFormControl which inherits from Element -template<> void ExtraInit(lua_State* L, int metatable_index); +// inherits from ElementFormControl which inherits from Element +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(ElementFormControlSelect) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Elements/ElementFormControlTextArea.cpp b/Source/Lua/Elements/ElementFormControlTextArea.cpp index 5a7fec469..1387e421d 100644 --- a/Source/Lua/Elements/ElementFormControlTextArea.cpp +++ b/Source/Lua/Elements/ElementFormControlTextArea.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,145 +25,140 @@ * THE SOFTWARE. * */ - + #include "ElementFormControlTextArea.h" -#include #include "ElementFormControl.h" +#include #include namespace Rml { namespace Lua { -//methods +// methods int ElementFormControlTextAreaSelect(lua_State* /*L*/, ElementFormControlTextArea* obj) { - obj->Select(); - return 0; + obj->Select(); + return 0; } int ElementFormControlTextAreaSetSelection(lua_State* L, ElementFormControlTextArea* obj) { - int start = (int)GetIndex(L, 1); - int end = (int)GetIndex(L, 2); - obj->SetSelectionRange(start, end); - return 0; + int start = (int)GetIndex(L, 1); + int end = (int)GetIndex(L, 2); + obj->SetSelectionRange(start, end); + return 0; } int ElementFormControlTextAreaGetSelection(lua_State* L, ElementFormControlTextArea* obj) { - int selection_start = 0, selection_end = 0; - String selected_text; - obj->GetSelection(&selection_start, &selection_end, &selected_text); - PushIndex(L, selection_start); - PushIndex(L, selection_end); - lua_pushstring(L, selected_text.c_str()); - return 3; + int selection_start = 0, selection_end = 0; + String selected_text; + obj->GetSelection(&selection_start, &selection_end, &selected_text); + PushIndex(L, selection_start); + PushIndex(L, selection_end); + lua_pushstring(L, selected_text.c_str()); + return 3; } -//getters +// getters int ElementFormControlTextAreaGetAttrcols(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetNumColumns()); - return 1; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetNumColumns()); + return 1; } int ElementFormControlTextAreaGetAttrmaxlength(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetMaxLength()); - return 1; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetMaxLength()); + return 1; } int ElementFormControlTextAreaGetAttrrows(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushinteger(L,obj->GetNumRows()); - return 1; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushinteger(L, obj->GetNumRows()); + return 1; } int ElementFormControlTextAreaGetAttrwordwrap(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - lua_pushboolean(L,obj->GetWordWrap()); - return 1; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + lua_pushboolean(L, obj->GetWordWrap()); + return 1; } - -//setters +// setters int ElementFormControlTextAreaSetAttrcols(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int cols = (int)luaL_checkinteger(L,2); - obj->SetNumColumns(cols); - return 0; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int cols = (int)luaL_checkinteger(L, 2); + obj->SetNumColumns(cols); + return 0; } int ElementFormControlTextAreaSetAttrmaxlength(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int ml = (int)luaL_checkinteger(L,2); - obj->SetMaxLength(ml); - return 0; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int ml = (int)luaL_checkinteger(L, 2); + obj->SetMaxLength(ml); + return 0; } int ElementFormControlTextAreaSetAttrrows(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int rows = (int)luaL_checkinteger(L,2); - obj->SetNumRows(rows); - return 0; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int rows = (int)luaL_checkinteger(L, 2); + obj->SetNumRows(rows); + return 0; } int ElementFormControlTextAreaSetAttrwordwrap(lua_State* L) { - ElementFormControlTextArea* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - bool ww = RMLUI_CHECK_BOOL(L,2); - obj->SetWordWrap(ww); - return 0; + ElementFormControlTextArea* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + bool ww = RMLUI_CHECK_BOOL(L, 2); + obj->SetWordWrap(ww); + return 0; } - -RegType ElementFormControlTextAreaMethods[] = -{ - RMLUI_LUAMETHOD(ElementFormControlTextArea,Select) - RMLUI_LUAMETHOD(ElementFormControlTextArea,SetSelection) - RMLUI_LUAMETHOD(ElementFormControlTextArea,GetSelection) - { nullptr, nullptr }, +RegType ElementFormControlTextAreaMethods[] = { + RMLUI_LUAMETHOD(ElementFormControlTextArea, Select), + RMLUI_LUAMETHOD(ElementFormControlTextArea, SetSelection), + RMLUI_LUAMETHOD(ElementFormControlTextArea, GetSelection), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlTextAreaGetters[] = -{ - RMLUI_LUAGETTER(ElementFormControlTextArea,cols) - RMLUI_LUAGETTER(ElementFormControlTextArea,maxlength) - RMLUI_LUAGETTER(ElementFormControlTextArea,rows) - RMLUI_LUAGETTER(ElementFormControlTextArea,wordwrap) - { nullptr, nullptr }, +luaL_Reg ElementFormControlTextAreaGetters[] = { + RMLUI_LUAGETTER(ElementFormControlTextArea, cols), + RMLUI_LUAGETTER(ElementFormControlTextArea, maxlength), + RMLUI_LUAGETTER(ElementFormControlTextArea, rows), + RMLUI_LUAGETTER(ElementFormControlTextArea, wordwrap), + {nullptr, nullptr}, }; -luaL_Reg ElementFormControlTextAreaSetters[] = -{ - RMLUI_LUASETTER(ElementFormControlTextArea,cols) - RMLUI_LUASETTER(ElementFormControlTextArea,maxlength) - RMLUI_LUASETTER(ElementFormControlTextArea,rows) - RMLUI_LUASETTER(ElementFormControlTextArea,wordwrap) - { nullptr, nullptr }, +luaL_Reg ElementFormControlTextAreaSetters[] = { + RMLUI_LUASETTER(ElementFormControlTextArea, cols), + RMLUI_LUASETTER(ElementFormControlTextArea, maxlength), + RMLUI_LUASETTER(ElementFormControlTextArea, rows), + RMLUI_LUASETTER(ElementFormControlTextArea, wordwrap), + {nullptr, nullptr}, }; - -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } RMLUI_LUATYPE_DEFINE(ElementFormControlTextArea) diff --git a/Source/Lua/Elements/ElementFormControlTextArea.h b/Source/Lua/Elements/ElementFormControlTextArea.h index c835778e6..dcb8e84e8 100644 --- a/Source/Lua/Elements/ElementFormControlTextArea.h +++ b/Source/Lua/Elements/ElementFormControlTextArea.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,29 +25,29 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROLTEXTAREA_H #define RMLUI_LUA_ELEMENTS_ELEMENTFORMCONTROLTEXTAREA_H +#include #include #include -#include namespace Rml { namespace Lua { -//methods +// methods int ElementFormControlTextAreaSelect(lua_State* L, ElementFormControlTextArea* obj); int ElementFormControlTextAreaSetSelection(lua_State* L, ElementFormControlTextArea* obj); int ElementFormControlTextAreaGetSelection(lua_State* L, ElementFormControlTextArea* obj); -//getters +// getters int ElementFormControlTextAreaGetAttrcols(lua_State* L); int ElementFormControlTextAreaGetAttrmaxlength(lua_State* L); int ElementFormControlTextAreaGetAttrrows(lua_State* L); int ElementFormControlTextAreaGetAttrwordwrap(lua_State* L); -//setters +// setters int ElementFormControlTextAreaSetAttrcols(lua_State* L); int ElementFormControlTextAreaSetAttrmaxlength(lua_State* L); int ElementFormControlTextAreaSetAttrrows(lua_State* L); @@ -57,9 +57,9 @@ extern RegType ElementFormControlTextAreaMethods[]; extern luaL_Reg ElementFormControlTextAreaGetters[]; extern luaL_Reg ElementFormControlTextAreaSetters[]; - -//inherits from ElementFormControl which inherits from Element -template<> void ExtraInit(lua_State* L, int metatable_index); +// inherits from ElementFormControl which inherits from Element +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(ElementFormControlTextArea) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Elements/ElementTabSet.cpp b/Source/Lua/Elements/ElementTabSet.cpp index 60b8f5aaa..965c6ce2b 100644 --- a/Source/Lua/Elements/ElementTabSet.cpp +++ b/Source/Lua/Elements/ElementTabSet.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,95 +25,88 @@ * THE SOFTWARE. * */ - + #include "ElementTabSet.h" #include #include - namespace Rml { namespace Lua { -//methods +// methods int ElementTabSetSetPanel(lua_State* L, ElementTabSet* obj) { - RMLUI_CHECK_OBJ(obj); - int index = GetIndex(L,1); - const char* rml = luaL_checkstring(L,2); + RMLUI_CHECK_OBJ(obj); + int index = GetIndex(L, 1); + const char* rml = luaL_checkstring(L, 2); - obj->SetPanel(index,rml); - return 0; + obj->SetPanel(index, rml); + return 0; } int ElementTabSetSetTab(lua_State* L, ElementTabSet* obj) { - RMLUI_CHECK_OBJ(obj); - int index = GetIndex(L,1); - const char* rml = luaL_checkstring(L,2); + RMLUI_CHECK_OBJ(obj); + int index = GetIndex(L, 1); + const char* rml = luaL_checkstring(L, 2); - obj->SetTab(index,rml); - return 0; + obj->SetTab(index, rml); + return 0; } - -//getters +// getters int ElementTabSetGetAttractive_tab(lua_State* L) { - ElementTabSet* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int tab = obj->GetActiveTab(); - PushIndex(L,tab); - return 1; + ElementTabSet* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int tab = obj->GetActiveTab(); + PushIndex(L, tab); + return 1; } int ElementTabSetGetAttrnum_tabs(lua_State* L) { - ElementTabSet* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int num = obj->GetNumTabs(); - lua_pushinteger(L,num); - return 1; + ElementTabSet* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int num = obj->GetNumTabs(); + lua_pushinteger(L, num); + return 1; } - -//setter +// setter int ElementTabSetSetAttractive_tab(lua_State* L) { - ElementTabSet* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - int tab = GetIndex(L,2); - obj->SetActiveTab(tab); - return 0; + ElementTabSet* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + int tab = GetIndex(L, 2); + obj->SetActiveTab(tab); + return 0; } - -RegType ElementTabSetMethods[] = -{ - RMLUI_LUAMETHOD(ElementTabSet,SetPanel) - RMLUI_LUAMETHOD(ElementTabSet,SetTab) - { nullptr, nullptr }, +RegType ElementTabSetMethods[] = { + RMLUI_LUAMETHOD(ElementTabSet, SetPanel), + RMLUI_LUAMETHOD(ElementTabSet, SetTab), + {nullptr, nullptr}, }; -luaL_Reg ElementTabSetGetters[] = -{ - RMLUI_LUAGETTER(ElementTabSet,active_tab) - RMLUI_LUAGETTER(ElementTabSet,num_tabs) - { nullptr, nullptr }, +luaL_Reg ElementTabSetGetters[] = { + RMLUI_LUAGETTER(ElementTabSet, active_tab), + RMLUI_LUAGETTER(ElementTabSet, num_tabs), + {nullptr, nullptr}, }; -luaL_Reg ElementTabSetSetters[] = -{ - RMLUI_LUASETTER(ElementTabSet,active_tab) - { nullptr, nullptr }, +luaL_Reg ElementTabSetSetters[] = { + RMLUI_LUASETTER(ElementTabSet, active_tab), + {nullptr, nullptr}, }; - -//this will be used to "inherit" from Element -template<> void ExtraInit(lua_State* L, int metatable_index) +// this will be used to "inherit" from Element +template <> +void ExtraInit(lua_State* L, int metatable_index) { - ExtraInit(L,metatable_index); - LuaType::_regfunctions(L,metatable_index,metatable_index-1); - AddTypeToElementAsTable(L); + ExtraInit(L, metatable_index); + LuaType::_regfunctions(L, metatable_index, metatable_index - 1); + AddTypeToElementAsTable(L); } RMLUI_LUATYPE_DEFINE(ElementTabSet) diff --git a/Source/Lua/Elements/ElementTabSet.h b/Source/Lua/Elements/ElementTabSet.h index 15119547e..8aa66d189 100644 --- a/Source/Lua/Elements/ElementTabSet.h +++ b/Source/Lua/Elements/ElementTabSet.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,35 +25,35 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_ELEMENTTABSET_H #define RMLUI_LUA_ELEMENTS_ELEMENTTABSET_H -#include -#include #include +#include +#include namespace Rml { namespace Lua { -//methods +// methods int ElementTabSetSetPanel(lua_State* L, ElementTabSet* obj); int ElementTabSetSetTab(lua_State* L, ElementTabSet* obj); -//getters +// getters int ElementTabSetGetAttractive_tab(lua_State* L); int ElementTabSetGetAttrnum_tabs(lua_State* L); -//setter +// setter int ElementTabSetSetAttractive_tab(lua_State* L); extern RegType ElementTabSetMethods[]; extern luaL_Reg ElementTabSetGetters[]; extern luaL_Reg ElementTabSetSetters[]; - -//this will be used to "inherit" from Element -template<> void ExtraInit(lua_State* L, int metatable_index); +// this will be used to "inherit" from Element +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(ElementTabSet) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Elements/SelectOptionsProxy.cpp b/Source/Lua/Elements/SelectOptionsProxy.cpp index 90aff0ebe..10600ce2d 100644 --- a/Source/Lua/Elements/SelectOptionsProxy.cpp +++ b/Source/Lua/Elements/SelectOptionsProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,66 +25,60 @@ * THE SOFTWARE. * */ - + #include "SelectOptionsProxy.h" -#include #include "../Pairs.h" - +#include namespace Rml { namespace Lua { - int SelectOptionsProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int keytype = lua_type(L,2); - if(keytype == LUA_TNUMBER) //only valid key types - { - SelectOptionsProxy* proxy = LuaType::check(L,1); - RMLUI_CHECK_OBJ(proxy); - int index = (int)luaL_checkinteger(L,2); - Element* opt = proxy->owner->GetOption(index-1); - RMLUI_CHECK_OBJ(opt); - lua_newtable(L); - LuaType::push(L,opt,false); - lua_setfield(L,-2,"element"); - lua_pushstring(L,opt->GetAttribute("value",String()).c_str()); - lua_setfield(L,-2,"value"); - return 1; - } - else - return LuaType::index(L); + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int keytype = lua_type(L, 2); + if (keytype == LUA_TNUMBER) // only valid key types + { + SelectOptionsProxy* proxy = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(proxy); + int index = (int)luaL_checkinteger(L, 2); + Element* opt = proxy->owner->GetOption(index - 1); + RMLUI_CHECK_OBJ(opt); + lua_newtable(L); + LuaType::push(L, opt, false); + lua_setfield(L, -2, "element"); + lua_pushstring(L, opt->GetAttribute("value", String()).c_str()); + lua_setfield(L, -2, "value"); + return 1; + } + else + return LuaType::index(L); } - int SelectOptionsProxy__pairs(lua_State* L) { - return MakeIntPairs(L); + return MakeIntPairs(L); } -RegType SelectOptionsProxyMethods[] = -{ - { nullptr, nullptr }, +RegType SelectOptionsProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg SelectOptionsProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg SelectOptionsProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg SelectOptionsProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg SelectOptionsProxySetters[] = { + {nullptr, nullptr}, }; - -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,SelectOptionsProxy__index); - lua_setfield(L,metatable_index,"__index"); - lua_pushcfunction(L,SelectOptionsProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); + lua_pushcfunction(L, SelectOptionsProxy__index); + lua_setfield(L, metatable_index, "__index"); + lua_pushcfunction(L, SelectOptionsProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); } RMLUI_LUATYPE_DEFINE(SelectOptionsProxy) diff --git a/Source/Lua/Elements/SelectOptionsProxy.h b/Source/Lua/Elements/SelectOptionsProxy.h index 2bdc32fd4..83e6b0e9d 100644 --- a/Source/Lua/Elements/SelectOptionsProxy.h +++ b/Source/Lua/Elements/SelectOptionsProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,18 +25,20 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_ELEMENTS_SELECTOPTIONSPROXY_H #define RMLUI_LUA_ELEMENTS_SELECTOPTIONSPROXY_H +#include #include #include -#include namespace Rml { namespace Lua { -//where owner is the ElementFormControlSelect that we should look up information from -struct SelectOptionsProxy { ElementFormControlSelect* owner; }; +// where owner is the ElementFormControlSelect that we should look up information from +struct SelectOptionsProxy { + ElementFormControlSelect* owner; +}; int SelectOptionsProxy__index(lua_State* L); int SelectOptionsProxy__pairs(lua_State* L); @@ -45,8 +47,8 @@ extern RegType SelectOptionsProxyMethods[]; extern luaL_Reg SelectOptionsProxyGetters[]; extern luaL_Reg SelectOptionsProxySetters[]; - -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); RMLUI_LUATYPE_DECLARE(SelectOptionsProxy) } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Event.cpp b/Source/Lua/Event.cpp index 762ea13e1..015b78ee8 100644 --- a/Source/Lua/Event.cpp +++ b/Source/Lua/Event.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,82 +25,82 @@ * THE SOFTWARE. * */ - -#include -#include -#include -#include -#include -#include "EventParametersProxy.h" +#include "EventParametersProxy.h" +#include +#include +#include +#include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) { return; } +template <> +void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) +{ + return; +} -//method +// method int EventStopPropagation(lua_State* /*L*/, Event* obj) { - obj->StopPropagation(); - return 0; + obj->StopPropagation(); + return 0; } -//getters +// getters int EventGetAttrcurrent_element(lua_State* L) { - Event* evt = LuaType::check(L,1); - RMLUI_CHECK_OBJ(evt); - Element* ele = evt->GetCurrentElement(); - LuaType::push(L,ele,false); - return 1; + Event* evt = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(evt); + Element* ele = evt->GetCurrentElement(); + LuaType::push(L, ele, false); + return 1; } int EventGetAttrtype(lua_State* L) { - Event* evt = LuaType::check(L,1); - RMLUI_CHECK_OBJ(evt); - String type = evt->GetType(); - lua_pushstring(L,type.c_str()); - return 1; + Event* evt = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(evt); + String type = evt->GetType(); + lua_pushstring(L, type.c_str()); + return 1; } int EventGetAttrtarget_element(lua_State* L) { - Event* evt = LuaType::check(L,1); - RMLUI_CHECK_OBJ(evt); - Element* target = evt->GetTargetElement(); - LuaType::push(L,target,false); - return 1; + Event* evt = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(evt); + Element* target = evt->GetTargetElement(); + LuaType::push(L, target, false); + return 1; } int EventGetAttrparameters(lua_State* L) { - Event* evt = LuaType::check(L,1); - RMLUI_CHECK_OBJ(evt); - EventParametersProxy* proxy = new EventParametersProxy(); - proxy->owner = evt; - LuaType::push(L,proxy,true); - return 1; + Event* evt = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(evt); + EventParametersProxy* proxy = new EventParametersProxy(); + proxy->owner = evt; + LuaType::push(L, proxy, true); + return 1; } -RegType EventMethods[] = -{ - RMLUI_LUAMETHOD(Event,StopPropagation) - { nullptr, nullptr }, +RegType EventMethods[] = { + RMLUI_LUAMETHOD(Event, StopPropagation), + {nullptr, nullptr}, }; -luaL_Reg EventGetters[] = -{ - RMLUI_LUAGETTER(Event,current_element) - RMLUI_LUAGETTER(Event,type) - RMLUI_LUAGETTER(Event,target_element) - RMLUI_LUAGETTER(Event,parameters) - { nullptr, nullptr }, +luaL_Reg EventGetters[] = { + RMLUI_LUAGETTER(Event, current_element), + RMLUI_LUAGETTER(Event, type), + RMLUI_LUAGETTER(Event, target_element), + RMLUI_LUAGETTER(Event, parameters), + {nullptr, nullptr}, }; -luaL_Reg EventSetters[] = -{ - { nullptr, nullptr }, +luaL_Reg EventSetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Event) diff --git a/Source/Lua/Event.h b/Source/Lua/Event.h index c61e79023..e3af4add3 100644 --- a/Source/Lua/Event.h +++ b/Source/Lua/Event.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,21 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_EVENT_H #define RMLUI_LUA_EVENT_H -#include #include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); -//method +template <> +void ExtraInit(lua_State* L, int metatable_index); +// method int EventStopPropagation(lua_State* L, Event* obj); -//getters +// getters int EventGetAttrcurrent_element(lua_State* L); int EventGetAttrtype(lua_State* L); int EventGetAttrtarget_element(lua_State* L); diff --git a/Source/Lua/EventParametersProxy.cpp b/Source/Lua/EventParametersProxy.cpp index 1c1daeaec..243f5e3b2 100644 --- a/Source/Lua/EventParametersProxy.cpp +++ b/Source/Lua/EventParametersProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,70 +25,64 @@ * THE SOFTWARE. * */ - + #include "EventParametersProxy.h" -#include -#include -#include #include "Pairs.h" +#include +#include +#include #include - namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,EventParametersProxy__index); - lua_setfield(L,metatable_index,"__index"); - lua_pushcfunction(L,EventParametersProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); + lua_pushcfunction(L, EventParametersProxy__index); + lua_setfield(L, metatable_index, "__index"); + lua_pushcfunction(L, EventParametersProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); } int EventParametersProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int keytype = lua_type(L,2); - if(keytype == LUA_TSTRING) //only valid key types - { - EventParametersProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - const char* key = lua_tostring(L,2); + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int keytype = lua_type(L, 2); + if (keytype == LUA_TSTRING) // only valid key types + { + EventParametersProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + const char* key = lua_tostring(L, 2); auto it = obj->owner->GetParameters().find(key); const Variant* param = (it == obj->owner->GetParameters().end() ? nullptr : &it->second); - if (obj->owner->GetId() == EventId::Tabchange && - std::strcmp(key, "tab_index") == 0 && - param && - param->GetType() == Variant::Type::INT) - { - PushIndex(L,param->Get()); - } - else - PushVariant(L,param); - return 1; - } - else - return LuaType::index(L); + if (obj->owner->GetId() == EventId::Tabchange && std::strcmp(key, "tab_index") == 0 && param && param->GetType() == Variant::Type::INT) + { + PushIndex(L, param->Get()); + } + else + PushVariant(L, param); + return 1; + } + else + return LuaType::index(L); } int EventParametersProxy__pairs(lua_State* L) { - EventParametersProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - return MakePairs(L, obj->owner->GetParameters()); + EventParametersProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + return MakePairs(L, obj->owner->GetParameters()); } -RegType EventParametersProxyMethods[] = -{ - { nullptr, nullptr }, +RegType EventParametersProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg EventParametersProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg EventParametersProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg EventParametersProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg EventParametersProxySetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(EventParametersProxy) diff --git a/Source/Lua/EventParametersProxy.h b/Source/Lua/EventParametersProxy.h index 89e8cd2f9..88255a952 100644 --- a/Source/Lua/EventParametersProxy.h +++ b/Source/Lua/EventParametersProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,23 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_EVENTPARAMETERSPROXY_H #define RMLUI_LUA_EVENTPARAMETERSPROXY_H +#include #include #include -#include namespace Rml { namespace Lua { -//where owner is the Element that we should look up information from -struct EventParametersProxy { Event* owner; }; +// where owner is the Element that we should look up information from +struct EventParametersProxy { + Event* owner; +}; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int EventParametersProxy__index(lua_State* L); int EventParametersProxy__pairs(lua_State* L); diff --git a/Source/Lua/GlobalLuaFunctions.cpp b/Source/Lua/GlobalLuaFunctions.cpp index 8bea2b821..9f07f7141 100644 --- a/Source/Lua/GlobalLuaFunctions.cpp +++ b/Source/Lua/GlobalLuaFunctions.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,13 +26,12 @@ * */ - #include "GlobalLuaFunctions.h" -#include +#include +#include #include +#include #include -#include -#include namespace Rml { namespace Lua { @@ -40,41 +39,41 @@ namespace Lua { Below here are global functions and their helper functions that help overwrite the Lua global functions */ -//Based off of the luaB_print function from Lua's lbaselib.c +// Based off of the luaB_print function from Lua's lbaselib.c int LuaPrint(lua_State* L) { - int n = lua_gettop(L); /* number of arguments */ - int i; - lua_getglobal(L, "tostring"); - StringList string_list = StringList(); - String output = ""; - for (i=1; i<=n; i++) - { - const char *s; - lua_pushvalue(L, -1); /* function to be called */ - lua_pushvalue(L, i); /* value to print */ - lua_call(L, 1, 1); - s = lua_tostring(L, -1); /* get result */ - if (s == nullptr) - return luaL_error(L, "'tostring' must return a string to 'print'"); - if (i>1) - output += "\t"; - output += String(s); - lua_pop(L, 1); /* pop result */ - } - output += "\n"; - Log::Message(Log::LT_INFO, "%s", output.c_str()); - return 0; + int n = lua_gettop(L); /* number of arguments */ + int i; + lua_getglobal(L, "tostring"); + StringList string_list = StringList(); + String output = ""; + for (i = 1; i <= n; i++) + { + const char* s; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tostring(L, -1); /* get result */ + if (s == nullptr) + return luaL_error(L, "'tostring' must return a string to 'print'"); + if (i > 1) + output += "\t"; + output += String(s); + lua_pop(L, 1); /* pop result */ + } + output += "\n"; + Log::Message(Log::LT_INFO, "%s", output.c_str()); + return 0; } void OverrideLuaGlobalFunctions(lua_State* L) { - lua_getglobal(L,"_G"); + lua_getglobal(L, "_G"); - lua_pushcfunction(L,LuaPrint); - lua_setfield(L,-2,"print"); + lua_pushcfunction(L, LuaPrint); + lua_setfield(L, -2, "print"); - lua_pop(L,1); //pop _G + lua_pop(L, 1); // pop _G } } // namespace Lua diff --git a/Source/Lua/GlobalLuaFunctions.h b/Source/Lua/GlobalLuaFunctions.h index b35e348b5..73f4eb99e 100644 --- a/Source/Lua/GlobalLuaFunctions.h +++ b/Source/Lua/GlobalLuaFunctions.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,8 +34,8 @@ typedef struct lua_State lua_State; namespace Rml { namespace Lua { void OverrideLuaGlobalFunctions(lua_State* L); -//overrides pairs and ipairs to respect __pairs and __ipairs metamethods -//overrdes print to print to the console +// overrides pairs and ipairs to respect __pairs and __ipairs metamethods +// overrdes print to print to the console } // namespace Lua } // namespace Rml #endif diff --git a/Source/Lua/Interpreter.cpp b/Source/Lua/Interpreter.cpp index 698b54210..177eb4754 100644 --- a/Source/Lua/Interpreter.cpp +++ b/Source/Lua/Interpreter.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,14 +25,14 @@ * THE SOFTWARE. * */ - -#include -#include "LuaPlugin.h" + #include "LuaDocumentElementInstancer.h" #include "LuaEventListenerInstancer.h" +#include "LuaPlugin.h" #include -#include #include +#include +#include #include namespace Rml { @@ -40,107 +40,109 @@ namespace Lua { static int ErrorHandler(lua_State* L) { - const char* msg = lua_tostring(L, 1); - if (msg == NULL) - { - if (luaL_callmeta(L, 1, "__tostring") && lua_type(L, -1) == LUA_TSTRING) - return 1; - else - msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1)); - } - luaL_traceback(L, L, msg, 1); - return 1; + const char* msg = lua_tostring(L, 1); + if (msg == NULL) + { + if (luaL_callmeta(L, 1, "__tostring") && lua_type(L, -1) == LUA_TSTRING) + return 1; + else + msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1)); + } + luaL_traceback(L, L, msg, 1); + return 1; } static bool LuaCall(lua_State* L, int nargs, int nresults) { - int errfunc = -2 - nargs; - lua_pushcfunction(L, ErrorHandler); - lua_insert(L, errfunc); - if (lua_pcall(L, nargs, nresults, errfunc) != LUA_OK) - { - Log::Message(Log::LT_WARNING, "%s", lua_tostring(L, -1)); - lua_pop(L, 2); - return false; - } - lua_remove(L, -1 - nresults); - return true; + int errfunc = -2 - nargs; + lua_pushcfunction(L, ErrorHandler); + lua_insert(L, errfunc); + if (lua_pcall(L, nargs, nresults, errfunc) != LUA_OK) + { + Log::Message(Log::LT_WARNING, "%s", lua_tostring(L, -1)); + lua_pop(L, 2); + return false; + } + lua_remove(L, -1 - nresults); + return true; } lua_State* Interpreter::GetLuaState() { - return LuaPlugin::GetLuaState(); + return LuaPlugin::GetLuaState(); } bool Interpreter::LoadFile(const String& file) { - lua_State* L = GetLuaState(); - - //use the file interface to get the contents of the script - FileInterface* file_interface = GetFileInterface(); - FileHandle handle = file_interface->Open(file); - if (handle == 0) { - Log::Message(Log::LT_WARNING, "LoadFile: Unable to open file: %s", file.c_str()); - return false; - } - - size_t size = file_interface->Length(handle); - if (size == 0) { - Log::Message(Log::LT_WARNING, "LoadFile: File is 0 bytes in size: %s", file.c_str()); - return false; - } - UniquePtr file_contents(new char[size]); - file_interface->Read(file_contents.get(), size, handle); - file_interface->Close(handle); - - if (luaL_loadbuffer(L, file_contents.get(), size, ("@" + file).c_str()) != 0) - { - Log::Message(Log::LT_WARNING, "%s", lua_tostring(L, -1)); - lua_pop(L, 1); - return false; - } - return LuaCall(L, 0, 0);; + lua_State* L = GetLuaState(); + + // use the file interface to get the contents of the script + FileInterface* file_interface = GetFileInterface(); + FileHandle handle = file_interface->Open(file); + if (handle == 0) + { + Log::Message(Log::LT_WARNING, "LoadFile: Unable to open file: %s", file.c_str()); + return false; + } + + size_t size = file_interface->Length(handle); + if (size == 0) + { + Log::Message(Log::LT_WARNING, "LoadFile: File is 0 bytes in size: %s", file.c_str()); + return false; + } + UniquePtr file_contents(new char[size]); + file_interface->Read(file_contents.get(), size, handle); + file_interface->Close(handle); + + if (luaL_loadbuffer(L, file_contents.get(), size, ("@" + file).c_str()) != 0) + { + Log::Message(Log::LT_WARNING, "%s", lua_tostring(L, -1)); + lua_pop(L, 1); + return false; + } + return LuaCall(L, 0, 0); + ; } bool Interpreter::DoString(const String& code, const String& name) { - lua_State* L = GetLuaState(); - return LoadString(code, name) && LuaCall(L, 0, 0); + lua_State* L = GetLuaState(); + return LoadString(code, name) && LuaCall(L, 0, 0); } bool Interpreter::LoadString(const String& code, const String& name) { - lua_State* L = GetLuaState(); - - if (luaL_loadbuffer(L, code.c_str(), code.length(), name.c_str()) != 0) - { - Log::Message(Log::LT_WARNING, "%s", lua_tostring(L, -1)); - lua_pop(L, 1); - return false; - } - return true; + lua_State* L = GetLuaState(); + + if (luaL_loadbuffer(L, code.c_str(), code.length(), name.c_str()) != 0) + { + Log::Message(Log::LT_WARNING, "%s", lua_tostring(L, -1)); + lua_pop(L, 1); + return false; + } + return true; } - void Interpreter::BeginCall(int funRef) { - lua_State* L = GetLuaState(); + lua_State* L = GetLuaState(); - lua_settop(L, 0); //empty stack - //lua_getref(g_L,funRef); - lua_rawgeti(L, LUA_REGISTRYINDEX, (int)funRef); + lua_settop(L, 0); // empty stack + // lua_getref(g_L,funRef); + lua_rawgeti(L, LUA_REGISTRYINDEX, (int)funRef); } bool Interpreter::ExecuteCall(int params, int res) { - lua_State* L = GetLuaState(); - return LuaCall(L, params, res); + lua_State* L = GetLuaState(); + return LuaCall(L, params, res); } void Interpreter::EndCall(int res) { - lua_State* L = GetLuaState(); - lua_pop(L, res); + lua_State* L = GetLuaState(); + lua_pop(L, res); } } // namespace Lua diff --git a/Source/Lua/Log.cpp b/Source/Lua/Log.cpp index dd347fddf..25835450f 100644 --- a/Source/Lua/Log.cpp +++ b/Source/Lua/Log.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,71 +25,68 @@ * THE SOFTWARE. * */ - + #include "Log.h" #include #include - namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - //due to they way that LuaType::Register is made, we know that the method table is at the index - //directly below the metatable - int method_index = metatable_index - 1; + // due to they way that LuaType::Register is made, we know that the method table is at the index + // directly below the metatable + int method_index = metatable_index - 1; - lua_pushcfunction(L,LogMessage); - lua_setfield(L,method_index, "Message"); + lua_pushcfunction(L, LogMessage); + lua_setfield(L, method_index, "Message"); - //construct the "logtype" table, so that we can use the Log::Type enum like Log.logtype.always in Lua for Log::LT_ALWAYS - lua_newtable(L); - int logtype = lua_gettop(L); - lua_pushvalue(L,-1); //copy of the new table, so that the logtype index will stay valid - lua_setfield(L,method_index,"logtype"); + // construct the "logtype" table, so that we can use the Log::Type enum like Log.logtype.always in Lua for Log::LT_ALWAYS + lua_newtable(L); + int logtype = lua_gettop(L); + lua_pushvalue(L, -1); // copy of the new table, so that the logtype index will stay valid + lua_setfield(L, method_index, "logtype"); - lua_pushinteger(L,(int)Log::LT_ALWAYS); - lua_setfield(L,logtype,"always"); + lua_pushinteger(L, (int)Log::LT_ALWAYS); + lua_setfield(L, logtype, "always"); - lua_pushinteger(L,(int)Log::LT_ERROR); - lua_setfield(L,logtype,"error"); + lua_pushinteger(L, (int)Log::LT_ERROR); + lua_setfield(L, logtype, "error"); - lua_pushinteger(L,(int)Log::LT_WARNING); - lua_setfield(L,logtype,"warning"); + lua_pushinteger(L, (int)Log::LT_WARNING); + lua_setfield(L, logtype, "warning"); - lua_pushinteger(L,(int)Log::LT_INFO); - lua_setfield(L,logtype,"info"); + lua_pushinteger(L, (int)Log::LT_INFO); + lua_setfield(L, logtype, "info"); - lua_pushinteger(L,(int)Log::LT_DEBUG); - lua_setfield(L,logtype,"debug"); + lua_pushinteger(L, (int)Log::LT_DEBUG); + lua_setfield(L, logtype, "debug"); - lua_pop(L,1); //pop the logtype table - return; + lua_pop(L, 1); // pop the logtype table + return; } int LogMessage(lua_State* L) { - Log::Type type = Log::Type((int)luaL_checkinteger(L,1)); - const char* str = luaL_checkstring(L,2); - - Log::Message(type, "%s", str); - return 0; + Log::Type type = Log::Type((int)luaL_checkinteger(L, 1)); + const char* str = luaL_checkstring(L, 2); + + Log::Message(type, "%s", str); + return 0; } -RegType LogMethods[] = -{ - { nullptr, nullptr }, +RegType LogMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg LogGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg LogGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg LogSetters[] = -{ - { nullptr, nullptr }, +luaL_Reg LogSetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Log) diff --git a/Source/Lua/Log.h b/Source/Lua/Log.h index 2bbc78bab..b859bc6e3 100644 --- a/Source/Lua/Log.h +++ b/Source/Lua/Log.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,16 +27,17 @@ */ #ifndef RMLUI_LUA_LOG_H -#define RMLUI_LUA_LOG_H +#define RMLUI_LUA_LOG_H -#include -#include #include +#include +#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int LogMessage(lua_State* L); extern RegType LogMethods[]; diff --git a/Source/Lua/Lua.cpp b/Source/Lua/Lua.cpp index b190aa33e..448ec5dc8 100644 --- a/Source/Lua/Lua.cpp +++ b/Source/Lua/Lua.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,10 +25,10 @@ * THE SOFTWARE. * */ - -#include -#include + #include "LuaPlugin.h" +#include +#include namespace Rml { namespace Lua { diff --git a/Source/Lua/LuaDataModel.cpp b/Source/Lua/LuaDataModel.cpp index 3bd569599..30379f75d 100644 --- a/Source/Lua/LuaDataModel.cpp +++ b/Source/Lua/LuaDataModel.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,12 +25,12 @@ * THE SOFTWARE. * */ - + #include "LuaDataModel.h" -#include -#include #include #include +#include +#include #define RMLDATAMODEL "RMLDATAMODEL" @@ -39,69 +39,81 @@ namespace Lua { namespace luabind { #if LUA_VERSION_NUM < 503 - static void lua_reverse(lua_State* L, int a, int b) { - for (; a < b; ++a, --b) { - lua_pushvalue(L, a); - lua_pushvalue(L, b); - lua_replace(L, a); - lua_replace(L, b); - } +static void lua_reverse(lua_State* L, int a, int b) +{ + for (; a < b; ++a, --b) + { + lua_pushvalue(L, a); + lua_pushvalue(L, b); + lua_replace(L, a); + lua_replace(L, b); } - void lua_rotate(lua_State* L, int idx, int n) { - int n_elems = 0; - idx = lua_absindex(L, idx); - n_elems = lua_gettop(L) - idx + 1; - if (n < 0) { - n += n_elems; - } - if (n > 0 && n < n_elems) { - luaL_checkstack(L, 2, "not enough stack slots available"); - n = n_elems - n; - lua_reverse(L, idx, idx + n - 1); - lua_reverse(L, idx + n, idx + n_elems - 1); - lua_reverse(L, idx, idx + n_elems - 1); - } +} +void lua_rotate(lua_State* L, int idx, int n) +{ + int n_elems = 0; + idx = lua_absindex(L, idx); + n_elems = lua_gettop(L) - idx + 1; + if (n < 0) + { + n += n_elems; } -#endif - using call_t = Rml::Function; - inline int errhandler(lua_State* L) { - const char* msg = lua_tostring(L, 1); - if (msg == NULL) { - if (luaL_callmeta(L, 1, "__tostring") && lua_type(L, -1) == LUA_TSTRING) - return 1; - else - msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1)); - } - luaL_traceback(L, L, msg, 1); - return 1; + if (n > 0 && n < n_elems) + { + luaL_checkstack(L, 2, "not enough stack slots available"); + n = n_elems - n; + lua_reverse(L, idx, idx + n - 1); + lua_reverse(L, idx + n, idx + n_elems - 1); + lua_reverse(L, idx, idx + n_elems - 1); } - inline void errfunc(const char* msg) { - Log::Message(Log::LT_WARNING, "%s", msg); +} +#endif +using call_t = Rml::Function; +inline int errhandler(lua_State* L) +{ + const char* msg = lua_tostring(L, 1); + if (msg == NULL) + { + if (luaL_callmeta(L, 1, "__tostring") && lua_type(L, -1) == LUA_TSTRING) + return 1; + else + msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1)); } - inline int function_call(lua_State* L) { - call_t& f = *(call_t*)lua_touserdata(L, 1); - f(); - return 0; + luaL_traceback(L, L, msg, 1); + return 1; +} +inline void errfunc(const char* msg) +{ + Log::Message(Log::LT_WARNING, "%s", msg); +} +inline int function_call(lua_State* L) +{ + call_t& f = *(call_t*)lua_touserdata(L, 1); + f(); + return 0; +} +inline bool invoke(lua_State* L, call_t f, int argn = 0) +{ + if (!lua_checkstack(L, 3)) + { + errfunc("stack overflow"); + lua_pop(L, argn); + return false; } - inline bool invoke(lua_State* L, call_t f, int argn = 0) { - if (!lua_checkstack(L, 3)) { - errfunc("stack overflow"); - lua_pop(L, argn); - return false; - } - lua_pushcfunction(L, errhandler); - lua_pushcfunction(L, function_call); - lua_pushlightuserdata(L, &f); - lua_rotate(L, -argn - 3, 3); - if (lua_pcall(L, 1 + argn, 0, lua_gettop(L) - argn - 2) != LUA_OK) { - errfunc(lua_tostring(L, -1)); - lua_pop(L, 2); - return false; - } - lua_pop(L, 1); - return true; + lua_pushcfunction(L, errhandler); + lua_pushcfunction(L, function_call); + lua_pushlightuserdata(L, &f); + lua_rotate(L, -argn - 3, 3); + if (lua_pcall(L, 1 + argn, 0, lua_gettop(L) - argn - 2) != LUA_OK) + { + errfunc(lua_tostring(L, -1)); + lua_pop(L, 2); + return false; } + lua_pop(L, 1); + return true; } +} // namespace luabind class LuaScalarDef; class LuaTableDef; @@ -109,9 +121,9 @@ class LuaTableDef; struct LuaDataModel { DataModelConstructor constructor; DataModelHandle handle; - lua_State *dataL; - LuaScalarDef *scalarDef; - LuaTableDef *tableDef; + lua_State* dataL; + LuaScalarDef* scalarDef; + LuaTableDef* tableDef; int top; }; @@ -122,6 +134,7 @@ class LuaTableDef : public VariableDefinition { bool Set(void* ptr, const Variant& variant) override; int Size(void* ptr) override; DataVariable Child(void* ptr, const DataAddressEntry& address) override; + protected: const struct LuaDataModel* model; }; @@ -132,13 +145,11 @@ class LuaScalarDef final : public LuaTableDef { DataVariable Child(void* ptr, const DataAddressEntry& address) override; }; -LuaTableDef::LuaTableDef(const struct LuaDataModel *model) - : VariableDefinition(DataVariableType::Scalar) - , model(model) -{} +LuaTableDef::LuaTableDef(const struct LuaDataModel* model) : VariableDefinition(DataVariableType::Scalar), model(model) {} -bool LuaTableDef::Get(void* ptr, Variant& variant) { - lua_State *L = model->dataL; +bool LuaTableDef::Get(void* ptr, Variant& variant) +{ + lua_State* L = model->dataL; if (!L) return false; int id = (int)(intptr_t)ptr; @@ -146,9 +157,10 @@ bool LuaTableDef::Get(void* ptr, Variant& variant) { return true; } -bool LuaTableDef::Set(void* ptr, const Variant& variant) { +bool LuaTableDef::Set(void* ptr, const Variant& variant) +{ int id = (int)(intptr_t)ptr; - lua_State *L = model->dataL; + lua_State* L = model->dataL; if (!L) return false; PushVariant(L, &variant); @@ -156,33 +168,36 @@ bool LuaTableDef::Set(void* ptr, const Variant& variant) { return true; } - -static int -lLuaTableDefSize(lua_State* L) { +static int lLuaTableDefSize(lua_State* L) +{ lua_pushinteger(L, luaL_len(L, 1)); return 1; } -static int -lLuaTableDefChild(lua_State* L) { +static int lLuaTableDefChild(lua_State* L) +{ lua_gettable(L, 1); return 1; } -int LuaTableDef::Size(void* ptr) { +int LuaTableDef::Size(void* ptr) +{ lua_State* L = model->dataL; if (!L) return 0; int id = (int)(intptr_t)ptr; - if (lua_type(L, id) != LUA_TTABLE) { + if (lua_type(L, id) != LUA_TTABLE) + { return 0; } - if (!lua_checkstack(L, 4)) { + if (!lua_checkstack(L, 4)) + { return 0; } lua_pushcfunction(L, lLuaTableDefSize); lua_pushvalue(L, id); - if (LUA_OK != lua_pcall(L, 1, 1, 0)) { + if (LUA_OK != lua_pcall(L, 1, 1, 0)) + { lua_pop(L, 1); return 0; } @@ -191,37 +206,42 @@ int LuaTableDef::Size(void* ptr) { return size; } -DataVariable LuaTableDef::Child(void* ptr, const DataAddressEntry& address) { +DataVariable LuaTableDef::Child(void* ptr, const DataAddressEntry& address) +{ lua_State* L = model->dataL; if (!L) return DataVariable{}; int id = (int)(intptr_t)ptr; - if (lua_type(L, id) != LUA_TTABLE) { + if (lua_type(L, id) != LUA_TTABLE) + { return DataVariable{}; } - if (!lua_checkstack(L, 4)) { + if (!lua_checkstack(L, 4)) + { return DataVariable{}; } lua_pushcfunction(L, lLuaTableDefChild); lua_pushvalue(L, id); - if (address.index == -1) { + if (address.index == -1) + { lua_pushlstring(L, address.name.data(), address.name.size()); } - else { + else + { lua_pushinteger(L, (lua_Integer)address.index + 1); } - if (LUA_OK != lua_pcall(L, 2, 1, 0)) { + if (LUA_OK != lua_pcall(L, 2, 1, 0)) + { lua_pop(L, 1); return DataVariable{}; } return DataVariable(model->tableDef, (void*)(intptr_t)lua_gettop(L)); } -LuaScalarDef::LuaScalarDef(const struct LuaDataModel* model) - : LuaTableDef(model) -{} +LuaScalarDef::LuaScalarDef(const struct LuaDataModel* model) : LuaTableDef(model) {} -DataVariable LuaScalarDef::Child(void* ptr, const DataAddressEntry& address) { +DataVariable LuaScalarDef::Child(void* ptr, const DataAddressEntry& address) +{ lua_State* L = model->dataL; if (!L) return DataVariable{}; @@ -229,48 +249,54 @@ DataVariable LuaScalarDef::Child(void* ptr, const DataAddressEntry& address) { return LuaTableDef::Child(ptr, address); } -static void -BindVariable(struct LuaDataModel* D, lua_State* L) { +static void BindVariable(struct LuaDataModel* D, lua_State* L) +{ lua_State* dataL = D->dataL; - if (!lua_checkstack(dataL, 4)) { + if (!lua_checkstack(dataL, 4)) + { luaL_error(L, "Memory Error"); } int id = lua_gettop(dataL) + 1; D->top = id; // L top : key value - lua_xmove(L, dataL, 1); // move value to dataL with index(id) - lua_pushvalue(L, -1); // dup key + lua_xmove(L, dataL, 1); // move value to dataL with index(id) + lua_pushvalue(L, -1); // dup key lua_xmove(L, dataL, 1); lua_pushinteger(dataL, id); lua_rawset(dataL, 1); const char* key = lua_tostring(L, -1); - if (lua_type(dataL, D->top) == LUA_TFUNCTION) { + if (lua_type(dataL, D->top) == LUA_TFUNCTION) + { D->constructor.BindEventCallback(key, [=](DataModelHandle, Event& event, const VariantList& varlist) { lua_pushvalue(dataL, id); lua_xmove(dataL, L, 1); - luabind::invoke(L, [&](){ - LuaType::push(L,&event,false); - for (auto const& variant : varlist) { - PushVariant(L, &variant); - } - lua_call(L, (int)varlist.size() + 1, 0); - }, 1); + luabind::invoke( + L, + [&]() { + LuaType::push(L, &event, false); + for (auto const& variant : varlist) + { + PushVariant(L, &variant); + } + lua_call(L, (int)varlist.size() + 1, 0); + }, + 1); }); } - else { - D->constructor.BindCustomDataVariable(key, - DataVariable(D->scalarDef, (void*)(intptr_t)id) - ); + else + { + D->constructor.BindCustomDataVariable(key, DataVariable(D->scalarDef, (void*)(intptr_t)id)); } } -static int -getId(lua_State *L, lua_State *dataL) { +static int getId(lua_State* L, lua_State* dataL) +{ lua_pushvalue(dataL, 1); lua_xmove(dataL, L, 1); lua_pushvalue(L, 2); lua_rawget(L, -2); - if (lua_type(L, -1) != LUA_TNUMBER) { + if (lua_type(L, -1) != LUA_TNUMBER) + { luaL_error(L, "DataModel has no key : %s", lua_tostring(L, 2)); } int id = (int)lua_tointeger(L, -1); @@ -278,10 +304,10 @@ getId(lua_State *L, lua_State *dataL) { return id; } -static int -lDataModelGet(lua_State *L) { - struct LuaDataModel *D = (struct LuaDataModel *)lua_touserdata(L, 1); - lua_State *dataL = D->dataL; +static int lDataModelGet(lua_State* L) +{ + struct LuaDataModel* D = (struct LuaDataModel*)lua_touserdata(L, 1); + lua_State* dataL = D->dataL; if (dataL == nullptr) luaL_error(L, "DataModel closed"); int id = getId(L, dataL); @@ -290,10 +316,10 @@ lDataModelGet(lua_State *L) { return 1; } -static int -lDataModelSet(lua_State *L) { - struct LuaDataModel *D = (struct LuaDataModel *)lua_touserdata(L, 1); - lua_State *dataL = D->dataL; +static int lDataModelSet(lua_State* L) +{ + struct LuaDataModel* D = (struct LuaDataModel*)lua_touserdata(L, 1); + lua_State* dataL = D->dataL; if (dataL == NULL) luaL_error(L, "DataModel released"); lua_settop(dataL, D->top); @@ -301,7 +327,8 @@ lDataModelSet(lua_State *L) { lua_pushvalue(L, 2); lua_xmove(L, dataL, 1); lua_rawget(dataL, 1); - if (lua_type(dataL, -1) == LUA_TNUMBER) { + if (lua_type(dataL, -1) == LUA_TNUMBER) + { int id = (int)lua_tointeger(dataL, -1); lua_pop(dataL, 1); lua_xmove(L, dataL, 1); @@ -314,20 +341,22 @@ lDataModelSet(lua_State *L) { return 0; } -bool -OpenLuaDataModel(lua_State *L, Context *context, int name_index, int table_index) { +bool OpenLuaDataModel(lua_State* L, Context* context, int name_index, int table_index) +{ String name = luaL_checkstring(L, name_index); luaL_checktype(L, table_index, LUA_TTABLE); DataModelConstructor constructor = context->CreateDataModel(name); - if (!constructor) { + if (!constructor) + { constructor = context->GetDataModel(name); - if (!constructor) { + if (!constructor) + { return false; } } - struct LuaDataModel *D = (struct LuaDataModel *)lua_newuserdata(L, sizeof(*D)); + struct LuaDataModel* D = (struct LuaDataModel*)lua_newuserdata(L, sizeof(*D)); D->dataL = nullptr; D->scalarDef = nullptr; D->tableDef = nullptr; @@ -340,16 +369,18 @@ OpenLuaDataModel(lua_State *L, Context *context, int name_index, int table_index D->top = 1; lua_newtable(D->dataL); lua_pushnil(L); - while (lua_next(L, table_index) != 0) { + while (lua_next(L, table_index) != 0) + { BindVariable(D, L); } lua_setuservalue(L, -2); - if (luaL_newmetatable(L, RMLDATAMODEL)) { + if (luaL_newmetatable(L, RMLDATAMODEL)) + { luaL_Reg l[] = { - { "__index", lDataModelGet }, - { "__newindex", lDataModelSet }, - { nullptr, nullptr }, + {"__index", lDataModelGet}, + {"__newindex", lDataModelSet}, + {nullptr, nullptr}, }; luaL_setfuncs(L, l, 0); } @@ -362,10 +393,10 @@ OpenLuaDataModel(lua_State *L, Context *context, int name_index, int table_index // and call CloseLuaDataModel for each after Context released. // We don't put it in __gc, becuase LuaDataModel can be free before DataModel if you are not careful. // scalarDef will free by CloseLuaDataModel, but DataModel need it. -void -CloseLuaDataModel(lua_State *L) { +void CloseLuaDataModel(lua_State* L) +{ luaL_checkudata(L, -1, RMLDATAMODEL); - struct LuaDataModel *D = (struct LuaDataModel *)lua_touserdata(L, -1); + struct LuaDataModel* D = (struct LuaDataModel*)lua_touserdata(L, -1); D->dataL = nullptr; D->top = 0; delete D->scalarDef; @@ -378,7 +409,3 @@ CloseLuaDataModel(lua_State *L) { } // namespace Lua } // namespace Rml - - - - diff --git a/Source/Lua/LuaDataModel.h b/Source/Lua/LuaDataModel.h index 4772dd5e1..ff7d13141 100644 --- a/Source/Lua/LuaDataModel.h +++ b/Source/Lua/LuaDataModel.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,12 +25,12 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_DATAMODEL_H #define RMLUI_LUA_DATAMODEL_H -#include #include +#include #include namespace Rml { @@ -39,9 +39,9 @@ namespace Lua { struct LuaDataModel; // Create or Get a DataModel in L, return false on fail -bool OpenLuaDataModel(lua_State *L, Rml::Context *context, int name_index, int table_index); +bool OpenLuaDataModel(lua_State* L, Rml::Context* context, int name_index, int table_index); // Should Close object (on L top) after DataModel released (Context::RemoveDataModel) -void CloseLuaDataModel(lua_State *L); +void CloseLuaDataModel(lua_State* L); } // namespace Lua } // namespace Rml diff --git a/Source/Lua/LuaDocument.cpp b/Source/Lua/LuaDocument.cpp index 57e3fbe04..66f500e46 100644 --- a/Source/Lua/LuaDocument.cpp +++ b/Source/Lua/LuaDocument.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,35 +25,32 @@ * THE SOFTWARE. * */ - + #include "LuaDocument.h" #include #include #include - namespace Rml { namespace Lua { -LuaDocument::LuaDocument(const String& tag) : ElementDocument(tag) -{ -} +LuaDocument::LuaDocument(const String& tag) : ElementDocument(tag) {} void LuaDocument::LoadInlineScript(const String& context, const String& source_path, int source_line) { - String buffer; - buffer += "--"; - buffer += source_path; - buffer += ":"; - buffer += Rml::ToString(source_line); - buffer += "\n"; - buffer += context; - Interpreter::DoString(buffer, buffer); + String buffer; + buffer += "--"; + buffer += source_path; + buffer += ":"; + buffer += Rml::ToString(source_line); + buffer += "\n"; + buffer += context; + Interpreter::DoString(buffer, buffer); } void LuaDocument::LoadExternalScript(const String& source_path) { - Interpreter::LoadFile(source_path); + Interpreter::LoadFile(source_path); } } // namespace Lua diff --git a/Source/Lua/LuaDocument.h b/Source/Lua/LuaDocument.h index 5c5700895..52cccc6ec 100644 --- a/Source/Lua/LuaDocument.h +++ b/Source/Lua/LuaDocument.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUADOCUMENT_H #define RMLUI_LUA_LUADOCUMENT_H /* @@ -36,12 +36,11 @@ namespace Rml { namespace Lua { -class LuaDocument : public ::Rml::ElementDocument -{ +class LuaDocument : public ::Rml::ElementDocument { public: - LuaDocument(const String& tag); - void LoadInlineScript(const String& content, const String& source_path, int source_line) override; - void LoadExternalScript(const String& source_path) override; + LuaDocument(const String& tag); + void LoadInlineScript(const String& content, const String& source_path, int source_line) override; + void LoadExternalScript(const String& source_path) override; }; } // namespace Lua diff --git a/Source/Lua/LuaDocumentElementInstancer.cpp b/Source/Lua/LuaDocumentElementInstancer.cpp index e8a5441d3..619aff2ea 100644 --- a/Source/Lua/LuaDocumentElementInstancer.cpp +++ b/Source/Lua/LuaDocumentElementInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #include "LuaDocumentElementInstancer.h" #include "LuaDocument.h" @@ -44,7 +44,7 @@ ElementPtr LuaDocumentElementInstancer::InstanceElement(Element* /*parent*/, con /// @param[in] element The element to release. void LuaDocumentElementInstancer::ReleaseElement(Element* element) { - delete element; + delete element; } } // namespace Lua diff --git a/Source/Lua/LuaDocumentElementInstancer.h b/Source/Lua/LuaDocumentElementInstancer.h index 586abfc9a..c3d8690e0 100644 --- a/Source/Lua/LuaDocumentElementInstancer.h +++ b/Source/Lua/LuaDocumentElementInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUADOCUMENTELEMENTINSTANCER_H #define RMLUI_LUA_LUADOCUMENTELEMENTINSTANCER_H @@ -34,9 +34,8 @@ namespace Rml { namespace Lua { -class LuaDocumentElementInstancer : public ::Rml::ElementInstancer -{ - /// Instances an element given the tag name and attributes. +class LuaDocumentElementInstancer : public ::Rml::ElementInstancer { + /// Instances an element given the tag name and attributes. /// @param[in] parent The element the new element is destined to be parented to. /// @param[in] tag The tag of the element to instance. /// @param[in] attributes Dictionary of attributes. diff --git a/Source/Lua/LuaElementInstancer.cpp b/Source/Lua/LuaElementInstancer.cpp index 8734447d3..108f7ba07 100644 --- a/Source/Lua/LuaElementInstancer.cpp +++ b/Source/Lua/LuaElementInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,67 +27,64 @@ */ #include "LuaElementInstancer.h" +#include #include -#include #include -#include +#include namespace Rml { namespace Lua { -//This will be called from ElementInstancernew +// This will be called from ElementInstancernew LuaElementInstancer::LuaElementInstancer(lua_State* L) : ElementInstancer(), ref_InstanceElement(LUA_NOREF) { - if(lua_type(L,1) != LUA_TFUNCTION && !lua_isnoneornil(L,1)) - { - Log::Message(Log::LT_ERROR, "The argument to ElementInstancer.new has to be a function or nil. You passed in a %s.", luaL_typename(L,1)); - return; - } - PushFunctionsTable(L); //top of the table is now ELEMENTINSTANCERFUNCTIONS table - lua_pushvalue(L,1); //copy of the function - ref_InstanceElement = luaL_ref(L,-2); - lua_pop(L,1); //pop the ELEMENTINSTANCERFUNCTIONS table + if (lua_type(L, 1) != LUA_TFUNCTION && !lua_isnoneornil(L, 1)) + { + Log::Message(Log::LT_ERROR, "The argument to ElementInstancer.new has to be a function or nil. You passed in a %s.", luaL_typename(L, 1)); + return; + } + PushFunctionsTable(L); // top of the table is now ELEMENTINSTANCERFUNCTIONS table + lua_pushvalue(L, 1); // copy of the function + ref_InstanceElement = luaL_ref(L, -2); + lua_pop(L, 1); // pop the ELEMENTINSTANCERFUNCTIONS table } -ElementPtr LuaElementInstancer::InstanceElement(Element* RMLUI_UNUSED_PARAMETER(parent), const String& tag, const XMLAttributes& RMLUI_UNUSED_PARAMETER(attributes)) +ElementPtr LuaElementInstancer::InstanceElement(Element* /*parent*/, const String& tag, const XMLAttributes& /*attributes*/) { - RMLUI_UNUSED(parent); - RMLUI_UNUSED(attributes); - - lua_State* L = Interpreter::GetLuaState(); - int top = lua_gettop(L); - ElementPtr ret = nullptr; - if(ref_InstanceElement != LUA_REFNIL && ref_InstanceElement != LUA_NOREF) - { - PushFunctionsTable(L); - lua_rawgeti(L,-1,ref_InstanceElement); //push the function - lua_pushstring(L,tag.c_str()); //push the tag - Interpreter::ExecuteCall(1,1); //we pass in a string, and we want to get an Element back - ret = std::move(*LuaType::check(L,-1)); - } - else - { - Log::Message(Log::LT_WARNING, "Attempt to call the function for ElementInstancer.InstanceElement, the function does not exist."); - } - lua_settop(L,top); - return ret; + lua_State* L = Interpreter::GetLuaState(); + int top = lua_gettop(L); + ElementPtr ret = nullptr; + if (ref_InstanceElement != LUA_REFNIL && ref_InstanceElement != LUA_NOREF) + { + PushFunctionsTable(L); + lua_rawgeti(L, -1, ref_InstanceElement); // push the function + lua_pushstring(L, tag.c_str()); // push the tag + Interpreter::ExecuteCall(1, 1); // we pass in a string, and we want to get an Element back + ret = std::move(*LuaType::check(L, -1)); + } + else + { + Log::Message(Log::LT_WARNING, "Attempt to call the function for ElementInstancer.InstanceElement, the function does not exist."); + } + lua_settop(L, top); + return ret; } void LuaElementInstancer::ReleaseElement(Element* element) { - delete element; + delete element; } void LuaElementInstancer::PushFunctionsTable(lua_State* L) { - //make sure there is an area to save the function - lua_getglobal(L,"ELEMENTINSTANCERFUNCTIONS"); - if(lua_isnoneornil(L,-1)) - { - lua_newtable(L); - lua_setglobal(L,"ELEMENTINSTANCERFUNCTIONS"); - lua_pop(L,1); //pop the unsucessful getglobal - lua_getglobal(L,"ELEMENTINSTANCERFUNCTIONS"); - } + // make sure there is an area to save the function + lua_getglobal(L, "ELEMENTINSTANCERFUNCTIONS"); + if (lua_isnoneornil(L, -1)) + { + lua_newtable(L); + lua_setglobal(L, "ELEMENTINSTANCERFUNCTIONS"); + lua_pop(L, 1); // pop the unsucessful getglobal + lua_getglobal(L, "ELEMENTINSTANCERFUNCTIONS"); + } } } // namespace Lua diff --git a/Source/Lua/LuaElementInstancer.h b/Source/Lua/LuaElementInstancer.h index 49185071a..df512b275 100644 --- a/Source/Lua/LuaElementInstancer.h +++ b/Source/Lua/LuaElementInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,11 +36,10 @@ namespace Rml { namespace Lua { -class LuaElementInstancer : public ::Rml::ElementInstancer -{ +class LuaElementInstancer : public ::Rml::ElementInstancer { public: - LuaElementInstancer(lua_State* L); - /// Instances an element given the tag name and attributes. + LuaElementInstancer(lua_State* L); + /// Instances an element given the tag name and attributes. /// @param[in] parent The element the new element is destined to be parented to. /// @param[in] tag The tag of the element to instance. /// @param[in] attributes Dictionary of attributes. @@ -49,10 +48,10 @@ class LuaElementInstancer : public ::Rml::ElementInstancer /// @param[in] element The element to release. void ReleaseElement(Element* element) override; - int ref_InstanceElement; + int ref_InstanceElement; - //Pushes on to the top of the stack the table named EVENTINSTNACERFUNCTIONS - void PushFunctionsTable(lua_State* L); + // Pushes on to the top of the stack the table named EVENTINSTNACERFUNCTIONS + void PushFunctionsTable(lua_State* L); }; } // namespace Lua diff --git a/Source/Lua/LuaEventListener.cpp b/Source/Lua/LuaEventListener.cpp index 6626723c0..96651ab21 100644 --- a/Source/Lua/LuaEventListener.cpp +++ b/Source/Lua/LuaEventListener.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,12 +25,12 @@ * THE SOFTWARE. * */ - + #include "LuaEventListener.h" +#include #include #include #include -#include namespace Rml { namespace Lua { @@ -38,64 +38,64 @@ typedef ElementDocument Document; LuaEventListener::LuaEventListener(const String& code, Element* element) : EventListener() { - //compose function - String function = "return function (event,element,document) "; - function.append(code); - function.append(" end"); - - //make sure there is an area to save the function - lua_State* L = Interpreter::GetLuaState(); - int top = lua_gettop(L); - lua_getglobal(L,"EVENTLISTENERFUNCTIONS"); - if(lua_isnoneornil(L,-1)) - { - lua_newtable(L); - lua_setglobal(L,"EVENTLISTENERFUNCTIONS"); - lua_pop(L,1); //pop the unsucessful getglobal - lua_getglobal(L,"EVENTLISTENERFUNCTIONS"); - } - int tbl = lua_gettop(L); - - //compile,execute,and save the function - if (!Interpreter::LoadString(function, code) || !Interpreter::ExecuteCall(0, 1)) - { - return; - } - - luaFuncRef = luaL_ref(L,tbl); //creates a reference to the item at the top of the stack in to the table we just created - lua_pop(L,1); //pop the EVENTLISTENERFUNCTIONS table - - attached = element; - if(element) + // compose function + String function = "return function (event,element,document) "; + function.append(code); + function.append(" end"); + + // make sure there is an area to save the function + lua_State* L = Interpreter::GetLuaState(); + int top = lua_gettop(L); + lua_getglobal(L, "EVENTLISTENERFUNCTIONS"); + if (lua_isnoneornil(L, -1)) + { + lua_newtable(L); + lua_setglobal(L, "EVENTLISTENERFUNCTIONS"); + lua_pop(L, 1); // pop the unsucessful getglobal + lua_getglobal(L, "EVENTLISTENERFUNCTIONS"); + } + int tbl = lua_gettop(L); + + // compile,execute,and save the function + if (!Interpreter::LoadString(function, code) || !Interpreter::ExecuteCall(0, 1)) + { + return; + } + + luaFuncRef = luaL_ref(L, tbl); // creates a reference to the item at the top of the stack in to the table we just created + lua_pop(L, 1); // pop the EVENTLISTENERFUNCTIONS table + + attached = element; + if (element) owner_document = element->GetOwnerDocument(); else owner_document = nullptr; - strFunc = function; - lua_settop(L,top); + strFunc = function; + lua_settop(L, top); } -//if it is passed in a Lua function +// if it is passed in a Lua function LuaEventListener::LuaEventListener(lua_State* L, int narg, Element* element) { - int top = lua_gettop(L); - lua_getglobal(L,"EVENTLISTENERFUNCTIONS"); - if(lua_isnoneornil(L,-1)) + int top = lua_gettop(L); + lua_getglobal(L, "EVENTLISTENERFUNCTIONS"); + if (lua_isnoneornil(L, -1)) { lua_newtable(L); - lua_setglobal(L,"EVENTLISTENERFUNCTIONS"); - lua_pop(L,1); //pop the unsucessful getglobal - lua_getglobal(L,"EVENTLISTENERFUNCTIONS"); + lua_setglobal(L, "EVENTLISTENERFUNCTIONS"); + lua_pop(L, 1); // pop the unsucessful getglobal + lua_getglobal(L, "EVENTLISTENERFUNCTIONS"); } - lua_pushvalue(L,narg); - luaFuncRef = luaL_ref(L,-2); //put the funtion as a ref in to that table - lua_pop(L,1); //pop the EVENTLISTENERFUNCTIONS table + lua_pushvalue(L, narg); + luaFuncRef = luaL_ref(L, -2); // put the funtion as a ref in to that table + lua_pop(L, 1); // pop the EVENTLISTENERFUNCTIONS table attached = element; - if(element) + if (element) owner_document = element->GetOwnerDocument(); else owner_document = nullptr; - lua_settop(L,top); + lua_settop(L, top); } LuaEventListener::~LuaEventListener() @@ -117,24 +117,24 @@ void LuaEventListener::OnDetach(Element* /*element*/) /// Process the incoming Event void LuaEventListener::ProcessEvent(Event& event) { - //not sure if this is the right place to do this, but if the element we are attached to isn't a document, then - //the 'owner_document' variable will be nullptr, because element->ower_document hasn't been set on the construction. We should - //correct that - if(!owner_document && attached) owner_document = attached->GetOwnerDocument(); - lua_State* L = Interpreter::GetLuaState(); - int top = lua_gettop(L); - - //push the arguments - lua_getglobal(L,"EVENTLISTENERFUNCTIONS"); - lua_rawgeti(L,-1,luaFuncRef); - LuaType::push(L,&event,false); - LuaType::push(L,attached,false); - LuaType::push(L,owner_document,false); - - Interpreter::ExecuteCall(3,0); //call the function at the top of the stack with 3 arguments - - lua_settop(L,top); //balanced stack makes Lua happy - + // not sure if this is the right place to do this, but if the element we are attached to isn't a document, then + // the 'owner_document' variable will be nullptr, because element->ower_document hasn't been set on the construction. We should + // correct that + if (!owner_document && attached) + owner_document = attached->GetOwnerDocument(); + lua_State* L = Interpreter::GetLuaState(); + int top = lua_gettop(L); + + // push the arguments + lua_getglobal(L, "EVENTLISTENERFUNCTIONS"); + lua_rawgeti(L, -1, luaFuncRef); + LuaType::push(L, &event, false); + LuaType::push(L, attached, false); + LuaType::push(L, owner_document, false); + + Interpreter::ExecuteCall(3, 0); // call the function at the top of the stack with 3 arguments + + lua_settop(L, top); // balanced stack makes Lua happy } } // namespace Lua diff --git a/Source/Lua/LuaEventListener.h b/Source/Lua/LuaEventListener.h index f75846cf0..5fa017e57 100644 --- a/Source/Lua/LuaEventListener.h +++ b/Source/Lua/LuaEventListener.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUAEVENTLISTENER_H #define RMLUI_LUA_LUAEVENTLISTENER_H @@ -38,20 +38,19 @@ class ElementDocument; namespace Lua { -class LuaEventListener : public ::Rml::EventListener -{ +class LuaEventListener : public ::Rml::EventListener { public: - //The plan is to wrap the code in an anonymous function so that we can have named parameters to use, - //rather than putting them in global variables - LuaEventListener(const String& code, Element* element); + // The plan is to wrap the code in an anonymous function so that we can have named parameters to use, + // rather than putting them in global variables + LuaEventListener(const String& code, Element* element); - //This is called from a Lua Element if in element:AddEventListener it passes a function in as the 2nd - //parameter rather than a string. We don't wrap the function in an anonymous function, so the user - //should take care to have the proper order. The order is event,element,document. - //narg is the position on the stack - LuaEventListener(lua_State* L, int narg, Element* element); + // This is called from a Lua Element if in element:AddEventListener it passes a function in as the 2nd + // parameter rather than a string. We don't wrap the function in an anonymous function, so the user + // should take care to have the proper order. The order is event,element,document. + // narg is the position on the stack + LuaEventListener(lua_State* L, int narg, Element* element); - virtual ~LuaEventListener(); + virtual ~LuaEventListener(); // Deletes itself, which also unreferences the Lua function. void OnDetach(Element* element) override; @@ -60,12 +59,12 @@ class LuaEventListener : public ::Rml::EventListener void ProcessEvent(Event& event) override; private: - //the lua-side function to call when ProcessEvent is called - int luaFuncRef = -1; + // the lua-side function to call when ProcessEvent is called + int luaFuncRef = -1; - Element* attached = nullptr; - ElementDocument* owner_document = nullptr; - String strFunc; //for debugging purposes + Element* attached = nullptr; + ElementDocument* owner_document = nullptr; + String strFunc; // for debugging purposes }; } // namespace Lua diff --git a/Source/Lua/LuaEventListenerInstancer.cpp b/Source/Lua/LuaEventListenerInstancer.cpp index 1adb933b8..2b64d8850 100644 --- a/Source/Lua/LuaEventListenerInstancer.cpp +++ b/Source/Lua/LuaEventListenerInstancer.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #include "LuaEventListenerInstancer.h" #include "LuaEventListener.h" @@ -37,7 +37,7 @@ namespace Lua { /// @param element Element that triggers the events. EventListener* LuaEventListenerInstancer::InstanceEventListener(const String& value, Element* element) { - return new LuaEventListener(value,element); + return new LuaEventListener(value, element); } } // namespace Lua diff --git a/Source/Lua/LuaEventListenerInstancer.h b/Source/Lua/LuaEventListenerInstancer.h index 0bfd86520..b4e0ba9b6 100644 --- a/Source/Lua/LuaEventListenerInstancer.h +++ b/Source/Lua/LuaEventListenerInstancer.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,7 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUAEVENTLISTENERINSTANCER_H #define RMLUI_LUA_LUAEVENTLISTENERINSTANCER_H #include @@ -33,10 +33,9 @@ namespace Rml { namespace Lua { -class LuaEventListenerInstancer : public ::Rml::EventListenerInstancer -{ +class LuaEventListenerInstancer : public ::Rml::EventListenerInstancer { public: - /// Instance an event listener object. + /// Instance an event listener object. /// @param value Value of the event. /// @param element Element that triggers the events. EventListener* InstanceEventListener(const String& value, Element* element) override; diff --git a/Source/Lua/LuaPlugin.cpp b/Source/Lua/LuaPlugin.cpp index 575c8a08f..30b9e4733 100644 --- a/Source/Lua/LuaPlugin.cpp +++ b/Source/Lua/LuaPlugin.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,56 +25,54 @@ * THE SOFTWARE. * */ - + #include "LuaPlugin.h" -#include -#include -#include -#include -#include #include "LuaDocumentElementInstancer.h" -#include #include "LuaEventListenerInstancer.h" #include "RmlUi.h" -//the types I made -#include "ContextDocumentsProxy.h" -#include "EventParametersProxy.h" -#include "ElementAttributesProxy.h" -#include "Log.h" -#include "Element.h" -#include "ElementStyleProxy.h" -#include "Document.h" +#include +#include +#include +#include +#include +#include +// the types I made #include "Colourb.h" #include "Colourf.h" -#include "Vector2f.h" -#include "Vector2i.h" #include "Context.h" -#include "Event.h" -#include "ElementInstancer.h" +#include "ContextDocumentsProxy.h" +#include "Document.h" +#include "Element.h" +#include "ElementAttributesProxy.h" #include "ElementChildNodesProxy.h" +#include "ElementInstancer.h" +#include "ElementStyleProxy.h" #include "ElementText.h" +#include "Event.h" +#include "EventParametersProxy.h" #include "GlobalLuaFunctions.h" +#include "Log.h" #include "RmlUiContextsProxy.h" +#include "Vector2f.h" +#include "Vector2i.h" // Control types -#include "Elements/SelectOptionsProxy.h" #include "Elements/ElementForm.h" #include "Elements/ElementFormControl.h" -#include "Elements/ElementFormControlSelect.h" #include "Elements/ElementFormControlInput.h" +#include "Elements/ElementFormControlSelect.h" #include "Elements/ElementFormControlTextArea.h" #include "Elements/ElementTabSet.h" +#include "Elements/SelectOptionsProxy.h" namespace Rml { namespace Lua { static lua_State* g_L = nullptr; - /** This will populate the global Lua table with all of the Lua core types by calling LuaType::Register @remark This is called automatically by LuaPlugin::OnInitialise(). */ static void RegisterTypes(); - LuaPlugin::LuaPlugin(lua_State* lua_state) { RMLUI_ASSERT(g_L == nullptr); @@ -83,7 +81,7 @@ LuaPlugin::LuaPlugin(lua_State* lua_state) int LuaPlugin::GetEventClasses() { - return EVT_BASIC; + return EVT_BASIC; } void LuaPlugin::OnInitialise() @@ -104,7 +102,7 @@ void LuaPlugin::OnInitialise() lua_document_element_instancer = new LuaDocumentElementInstancer(); lua_event_listener_instancer = new LuaEventListenerInstancer(); - Factory::RegisterElementInstancer("body", lua_document_element_instancer); + Factory::RegisterElementInstancer("body", lua_document_element_instancer); Factory::RegisterEventListenerInstancer(lua_event_listener_instancer); } @@ -117,59 +115,57 @@ void LuaPlugin::OnShutdown() if (owns_lua_state) lua_close(g_L); - + g_L = nullptr; delete this; } - static void RegisterTypes() { - RMLUI_ASSERT(g_L); - lua_State* L = g_L; - - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - //things that inherit from Element - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - //Proxy tables - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - OverrideLuaGlobalFunctions(L); - //push the global variable "rmlui" to use the "RmlUi" methods - LuaRmlUiPushrmluiGlobal(L); - - // Control types - LuaType::Register(L); - LuaType::Register(L); - //Inherits from ElementFormControl - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - LuaType::Register(L); - //proxy tables - LuaType::Register(L); + RMLUI_ASSERT(g_L); + lua_State* L = g_L; + + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + // things that inherit from Element + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + // Proxy tables + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + OverrideLuaGlobalFunctions(L); + // push the global variable "rmlui" to use the "RmlUi" methods + LuaRmlUiPushrmluiGlobal(L); + + // Control types + LuaType::Register(L); + LuaType::Register(L); + // Inherits from ElementFormControl + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + LuaType::Register(L); + // proxy tables + LuaType::Register(L); } - lua_State* LuaPlugin::GetLuaState() { - return g_L; + return g_L; } } // namespace Lua diff --git a/Source/Lua/LuaPlugin.h b/Source/Lua/LuaPlugin.h index 4b693a605..65c65efb7 100644 --- a/Source/Lua/LuaPlugin.h +++ b/Source/Lua/LuaPlugin.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,12 +25,12 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_LUAPLUGIN_H -#define RMLUI_LUA_LUAPLUGIN_H +#define RMLUI_LUA_LUAPLUGIN_H -#include #include +#include typedef struct lua_State lua_State; @@ -46,18 +46,17 @@ class LuaEventListenerInstancer; @author Nathan Starkey */ -class RMLUILUA_API LuaPlugin : public Plugin -{ +class RMLUILUA_API LuaPlugin : public Plugin { public: - LuaPlugin(lua_State* lua_state); + LuaPlugin(lua_State* lua_state); - static lua_State* GetLuaState(); + static lua_State* GetLuaState(); private: - int GetEventClasses() override; - + int GetEventClasses() override; + void OnInitialise() override; - + void OnShutdown() override; LuaDocumentElementInstancer* lua_document_element_instancer = nullptr; diff --git a/Source/Lua/LuaType.cpp b/Source/Lua/LuaType.cpp index e4595c899..0bd5b9bb2 100644 --- a/Source/Lua/LuaType.cpp +++ b/Source/Lua/LuaType.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,96 +25,94 @@ * THE SOFTWARE. * */ - + +#include #include #include -#include namespace Rml { namespace Lua { - int LuaTypeImpl::index(lua_State* L, const char* class_name) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - lua_getglobal(L, class_name); //stack pos [3] (fairly important, just refered to as [3]) - // string form of the key. - const char* key = luaL_checkstring(L, 2); - if (lua_istable(L, -1)) //[-1 = 3] - { - lua_pushvalue(L, 2); //[2] = key, [4] = copy of key - lua_rawget(L, -2); //[-2 = 3] -> pop top and push the return value to top [4] - //If the key were looking for is not in the table, retrieve its' metatables' index value. - if (lua_isnil(L, -1)) //[-1 = 4] is value from rawget above - { - //try __getters - lua_pop(L, 1); //remove top item (nil) from the stack - lua_pushstring(L, "__getters"); - lua_rawget(L, -2); //[-2 = 3], ._getters -> result to [4] - lua_pushvalue(L, 2); //[2 = key] -> copy to [5] - lua_rawget(L, -2); //[-2 = __getters] -> __getters[key], result to [5] - if (lua_type(L, -1) == LUA_TFUNCTION) //[-1 = 5] - { - lua_pushvalue(L, 1); //push the userdata to the stack [6] - lua_call(L, 1, 1); //remove one, result is at [6] - } - else - { - lua_settop(L, 4); //forget everything we did above - lua_getmetatable(L, -2); //[-2 = 3] -> metatable from to top [5] - if (lua_istable(L, -1)) //[-1 = 5] = the result of the above - { - lua_getfield(L, -1, "__index"); //[-1 = 5] = check the __index metamethod for the metatable-> push result to [6] - if (lua_isfunction(L, -1)) //[-1 = 6] = __index metamethod - { - lua_pushvalue(L, 1); //[1] = object -> [7] = object - lua_pushvalue(L, 2); //[2] = key -> [8] = key - lua_call(L, 2, 1); //call function at top of stack (__index) -> pop top 2 as args; [7] = return value - } - else if (lua_istable(L, -1)) - lua_getfield(L, -1, key); //shorthand version of above -> [7] = return value - else - lua_pushnil(L); //[7] = nil - } - else - lua_pushnil(L); //[6] = nil - } - } - else if (lua_istable(L, -1))//[-1 = 4] is value from rawget [3] - { - lua_pushvalue(L, 2); //[2] = key, [5] = key - lua_rawget(L, -2); //[-2 = 3] = table of -> pop top and push the return value to top [5] - } - } - else - lua_pushnil(L); //[4] = nil + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + lua_getglobal(L, class_name); // stack pos [3] (fairly important, just refered to as [3]) + // string form of the key. + const char* key = luaL_checkstring(L, 2); + if (lua_istable(L, -1)) //[-1 = 3] + { + lua_pushvalue(L, 2); //[2] = key, [4] = copy of key + lua_rawget(L, -2); //[-2 = 3] -> pop top and push the return value to top [4] + // If the key were looking for is not in the table, retrieve its' metatables' index value. + if (lua_isnil(L, -1)) //[-1 = 4] is value from rawget above + { + // try __getters + lua_pop(L, 1); // remove top item (nil) from the stack + lua_pushstring(L, "__getters"); + lua_rawget(L, -2); //[-2 = 3], ._getters -> result to [4] + lua_pushvalue(L, 2); //[2 = key] -> copy to [5] + lua_rawget(L, -2); //[-2 = __getters] -> __getters[key], result to [5] + if (lua_type(L, -1) == LUA_TFUNCTION) //[-1 = 5] + { + lua_pushvalue(L, 1); // push the userdata to the stack [6] + lua_call(L, 1, 1); // remove one, result is at [6] + } + else + { + lua_settop(L, 4); // forget everything we did above + lua_getmetatable(L, -2); //[-2 = 3] -> metatable from to top [5] + if (lua_istable(L, -1)) //[-1 = 5] = the result of the above + { + lua_getfield(L, -1, "__index"); //[-1 = 5] = check the __index metamethod for the metatable-> push result to [6] + if (lua_isfunction(L, -1)) //[-1 = 6] = __index metamethod + { + lua_pushvalue(L, 1); //[1] = object -> [7] = object + lua_pushvalue(L, 2); //[2] = key -> [8] = key + lua_call(L, 2, 1); // call function at top of stack (__index) -> pop top 2 as args; [7] = return value + } + else if (lua_istable(L, -1)) + lua_getfield(L, -1, key); // shorthand version of above -> [7] = return value + else + lua_pushnil(L); //[7] = nil + } + else + lua_pushnil(L); //[6] = nil + } + } + else if (lua_istable(L, -1)) //[-1 = 4] is value from rawget [3] + { + lua_pushvalue(L, 2); //[2] = key, [5] = key + lua_rawget(L, -2); //[-2 = 3] = table of -> pop top and push the return value to top [5] + } + } + else + lua_pushnil(L); //[4] = nil - lua_insert(L, 1); //top element to position 1 -> [1] = top element as calculated in the earlier rest of the function - lua_settop(L, 1); // -> [1 = -1], removes the other elements - return 1; + lua_insert(L, 1); // top element to position 1 -> [1] = top element as calculated in the earlier rest of the function + lua_settop(L, 1); // -> [1 = -1], removes the other elements + return 1; } int LuaTypeImpl::newindex(lua_State* L, const char* class_name) { - //[1] = obj, [2] = key, [3] = value - //look for it in __setters - lua_getglobal(L, class_name); //[4] = this table - lua_pushstring(L, "__setters"); //[5] - lua_rawget(L, -2); //[-2 = 4] -> .__setters to [5] - lua_pushvalue(L, 2); //[2 = key] -> [6] = copy of key - lua_rawget(L, -2); //[-2 = __setters] -> __setters[key] to [6] - if (lua_type(L, -1) == LUA_TFUNCTION) - { - lua_pushvalue(L, 1); //userdata at [7] - lua_pushvalue(L, 3); //[8] = copy of [3] - lua_call(L, 2, 0); //call function, pop 2 off push 0 on - } - else - lua_pop(L, 1); //not a setter function. - lua_pop(L, 2); //pop __setters and the table - return 0; + //[1] = obj, [2] = key, [3] = value + // look for it in __setters + lua_getglobal(L, class_name); //[4] = this table + lua_pushstring(L, "__setters"); //[5] + lua_rawget(L, -2); //[-2 = 4] -> .__setters to [5] + lua_pushvalue(L, 2); //[2 = key] -> [6] = copy of key + lua_rawget(L, -2); //[-2 = __setters] -> __setters[key] to [6] + if (lua_type(L, -1) == LUA_TFUNCTION) + { + lua_pushvalue(L, 1); // userdata at [7] + lua_pushvalue(L, 3); //[8] = copy of [3] + lua_call(L, 2, 0); // call function, pop 2 off push 0 on + } + else + lua_pop(L, 1); // not a setter function. + lua_pop(L, 2); // pop __setters and the table + return 0; } - } // namespace Lua } // namespace Rml diff --git a/Source/Lua/Pairs.h b/Source/Lua/Pairs.h index 1d2b2bf7f..b93646668 100644 --- a/Source/Lua/Pairs.h +++ b/Source/Lua/Pairs.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,9 +25,9 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_PAIRS_H -#define RMLUI_LUA_PAIRS_H +#define RMLUI_LUA_PAIRS_H #include #include @@ -35,95 +35,104 @@ namespace Rml { namespace Lua { - + template int PairsConvertTolua(lua_State* L, const T& v); template -int PairsConvertTolua(lua_State* L, const std::pair& v) { - int nresult = 0; - nresult += PairsConvertTolua(L, v.first); - nresult += PairsConvertTolua(L, v.second); - return nresult; +int PairsConvertTolua(lua_State* L, const std::pair& v) +{ + int nresult = 0; + nresult += PairsConvertTolua(L, v.first); + nresult += PairsConvertTolua(L, v.second); + return nresult; } template <> -inline int PairsConvertTolua(lua_State* L, const String& s) { - lua_pushlstring(L, s.c_str(), s.size()); - return 1; +inline int PairsConvertTolua(lua_State* L, const String& s) +{ + lua_pushlstring(L, s.c_str(), s.size()); + return 1; } template <> -inline int PairsConvertTolua(lua_State* L, const Variant& v) { - PushVariant(L, &v); - return 1; +inline int PairsConvertTolua(lua_State* L, const Variant& v) +{ + PushVariant(L, &v); + return 1; } template struct PairsHelper { - static int next(lua_State* L) { - PairsHelper* self = static_cast(lua_touserdata(L, lua_upvalueindex(1))); - if (self->m_first == self->m_last) { - return 0; - } - int nreslut = PairsConvertTolua(L, *self->m_first); - ++(self->m_first); - return nreslut; - } - static int destroy(lua_State* L) { - static_cast(lua_touserdata(L, 1))->~PairsHelper(); - return 0; - } - static int constructor(lua_State* L, const T& first, const T& last) { - void* storage = lua_newuserdata(L, sizeof(PairsHelper)); - if (luaL_newmetatable(L, "RmlUi::Lua::PairsHelper")) { - static luaL_Reg mt[] = { - {"__gc", destroy}, - {NULL, NULL}, - }; - luaL_setfuncs(L, mt, 0); - } - lua_setmetatable(L, -2); - lua_pushcclosure(L, next, 1); - new (storage) PairsHelper(first, last); - return 1; - } - PairsHelper(const T& first, const T& last) - : m_first(first) - , m_last(last) - { } - T m_first; - T m_last; + static int next(lua_State* L) + { + PairsHelper* self = static_cast(lua_touserdata(L, lua_upvalueindex(1))); + if (self->m_first == self->m_last) + { + return 0; + } + int nreslut = PairsConvertTolua(L, *self->m_first); + ++(self->m_first); + return nreslut; + } + static int destroy(lua_State* L) + { + static_cast(lua_touserdata(L, 1))->~PairsHelper(); + return 0; + } + static int constructor(lua_State* L, const T& first, const T& last) + { + void* storage = lua_newuserdata(L, sizeof(PairsHelper)); + if (luaL_newmetatable(L, "RmlUi::Lua::PairsHelper")) + { + static luaL_Reg mt[] = { + {"__gc", destroy}, + {NULL, NULL}, + }; + luaL_setfuncs(L, mt, 0); + } + lua_setmetatable(L, -2); + lua_pushcclosure(L, next, 1); + new (storage) PairsHelper(first, last); + return 1; + } + PairsHelper(const T& first, const T& last) : m_first(first), m_last(last) {} + T m_first; + T m_last; }; template -int MakePairs(lua_State* L, const Iterator& first, const Iterator& last) { - return PairsHelper::constructor(L, first, last); +int MakePairs(lua_State* L, const Iterator& first, const Iterator& last) +{ + return PairsHelper::constructor(L, first, last); } template -int MakePairs(lua_State* L, const Container& container) { - return MakePairs(L, std::begin(container), std::end(container)); +int MakePairs(lua_State* L, const Container& container) +{ + return MakePairs(L, std::begin(container), std::end(container)); } -inline int ipairsaux(lua_State* L) { - lua_Integer i = luaL_checkinteger(L, 2) + 1; - lua_pushinteger(L, i); +inline int ipairsaux(lua_State* L) +{ + lua_Integer i = luaL_checkinteger(L, 2) + 1; + lua_pushinteger(L, i); #if LUA_VERSION_NUM >= 503 - return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; + return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; #else - lua_pushinteger(L, i); - lua_gettable(L, 1); - return (lua_isnil(L, -1)) ? 1 : 2; + lua_pushinteger(L, i); + lua_gettable(L, 1); + return (lua_isnil(L, -1)) ? 1 : 2; #endif } -inline int MakeIntPairs(lua_State* L) { - luaL_checkany(L, 1); - lua_pushcfunction(L, ipairsaux); - lua_pushvalue(L, 1); - lua_pushinteger(L, 0); - return 3; +inline int MakeIntPairs(lua_State* L) +{ + luaL_checkany(L, 1); + lua_pushcfunction(L, ipairsaux); + lua_pushvalue(L, 1); + lua_pushinteger(L, 0); + return 3; } } // namespace Lua diff --git a/Source/Lua/RmlUi.cpp b/Source/Lua/RmlUi.cpp index 13306e446..4c37ac261 100644 --- a/Source/Lua/RmlUi.cpp +++ b/Source/Lua/RmlUi.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,303 +25,307 @@ * THE SOFTWARE. * */ - + #include "RmlUi.h" -#include -#include -#include #include "ElementInstancer.h" #include "LuaElementInstancer.h" #include "RmlUiContextsProxy.h" +#include +#include +#include namespace Rml { namespace Lua { -#define RMLUILUA_INPUTENUM(keyident,tbl) lua_pushinteger(L,Input::KI_##keyident); lua_setfield(L,(tbl),#keyident); -#define RMLUILUA_INPUTMODIFIERENUM(keymod,tbl) lua_pushinteger(L,Input::KM_##keymod); lua_setfield(L,(tbl),#keymod); +#define RMLUILUA_INPUTENUM(keyident, tbl) \ + lua_pushinteger(L, Input::KI_##keyident); \ + lua_setfield(L, (tbl), #keyident); +#define RMLUILUA_INPUTMODIFIERENUM(keymod, tbl) \ + lua_pushinteger(L, Input::KM_##keymod); \ + lua_setfield(L, (tbl), #keymod); -//c++ representation of the global variable in Lua so that the syntax is consistent +// c++ representation of the global variable in Lua so that the syntax is consistent LuaRmlUi lua_global_rmlui; void LuaRmlUiPushrmluiGlobal(lua_State* L) { - luaL_getmetatable(L,GetTClassName()); - LuaRmlUiEnumkey_identifier(L); - lua_global_rmlui.key_identifier_ref = luaL_ref(L,-2); - LuaRmlUiEnumkey_modifier(L); - lua_global_rmlui.key_modifier_ref = luaL_ref(L,-2); - LuaType::push(L,&lua_global_rmlui,false); - lua_setglobal(L,"rmlui"); + luaL_getmetatable(L, GetTClassName()); + LuaRmlUiEnumkey_identifier(L); + lua_global_rmlui.key_identifier_ref = luaL_ref(L, -2); + LuaRmlUiEnumkey_modifier(L); + lua_global_rmlui.key_modifier_ref = luaL_ref(L, -2); + LuaType::push(L, &lua_global_rmlui, false); + lua_setglobal(L, "rmlui"); } -template<> void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) { return; } +template <> +void ExtraInit(lua_State* /*L*/, int /*metatable_index*/) +{ + return; +} int LuaRmlUiCreateContext(lua_State* L, LuaRmlUi* /*obj*/) { - const char* name = luaL_checkstring(L,1); - Vector2i* dimensions = LuaType::check(L,2); - Context* new_context = CreateContext(name, *dimensions); - if(new_context == nullptr || dimensions == nullptr) - { - lua_pushnil(L); - } - else - { - LuaType::push(L, new_context); - } - return 1; + const char* name = luaL_checkstring(L, 1); + Vector2i* dimensions = LuaType::check(L, 2); + Context* new_context = CreateContext(name, *dimensions); + if (new_context == nullptr || dimensions == nullptr) + { + lua_pushnil(L); + } + else + { + LuaType::push(L, new_context); + } + return 1; } int LuaRmlUiLoadFontFace(lua_State* L, LuaRmlUi* /*obj*/) { - const char* file = luaL_checkstring(L,1); - lua_pushboolean(L,LoadFontFace(file)); - return 1; + const char* file = luaL_checkstring(L, 1); + lua_pushboolean(L, LoadFontFace(file)); + return 1; } int LuaRmlUiRegisterTag(lua_State* L, LuaRmlUi* /*obj*/) { - const char* tag = luaL_checkstring(L,1); - LuaElementInstancer* lei = (LuaElementInstancer*)LuaType::check(L,2); - RMLUI_CHECK_OBJ(lei); - Factory::RegisterElementInstancer(tag,lei); - return 0; + const char* tag = luaL_checkstring(L, 1); + LuaElementInstancer* lei = (LuaElementInstancer*)LuaType::check(L, 2); + RMLUI_CHECK_OBJ(lei); + Factory::RegisterElementInstancer(tag, lei); + return 0; } int LuaRmlUiGetAttrcontexts(lua_State* L) { - RmlUiContextsProxy* proxy = new RmlUiContextsProxy(); - LuaType::push(L,proxy,true); - return 1; + RmlUiContextsProxy* proxy = new RmlUiContextsProxy(); + LuaType::push(L, proxy, true); + return 1; } int LuaRmlUiGetAttrkey_identifier(lua_State* L) { - luaL_getmetatable(L,GetTClassName()); - lua_rawgeti(L,-1,lua_global_rmlui.key_identifier_ref); - return 1; + luaL_getmetatable(L, GetTClassName()); + lua_rawgeti(L, -1, lua_global_rmlui.key_identifier_ref); + return 1; } int LuaRmlUiGetAttrkey_modifier(lua_State* L) { - luaL_getmetatable(L,GetTClassName()); - lua_rawgeti(L,-1,lua_global_rmlui.key_modifier_ref); - return 1; + luaL_getmetatable(L, GetTClassName()); + lua_rawgeti(L, -1, lua_global_rmlui.key_modifier_ref); + return 1; } void LuaRmlUiEnumkey_identifier(lua_State* L) { - lua_newtable(L); - int tbl = lua_gettop(L); - RMLUILUA_INPUTENUM(UNKNOWN,tbl) - RMLUILUA_INPUTENUM(SPACE,tbl) - RMLUILUA_INPUTENUM(0,tbl) - RMLUILUA_INPUTENUM(1,tbl) - RMLUILUA_INPUTENUM(2,tbl) - RMLUILUA_INPUTENUM(3,tbl) - RMLUILUA_INPUTENUM(4,tbl) - RMLUILUA_INPUTENUM(5,tbl) - RMLUILUA_INPUTENUM(6,tbl) - RMLUILUA_INPUTENUM(7,tbl) - RMLUILUA_INPUTENUM(8,tbl) - RMLUILUA_INPUTENUM(9,tbl) - RMLUILUA_INPUTENUM(A,tbl) - RMLUILUA_INPUTENUM(B,tbl) - RMLUILUA_INPUTENUM(C,tbl) - RMLUILUA_INPUTENUM(D,tbl) - RMLUILUA_INPUTENUM(E,tbl) - RMLUILUA_INPUTENUM(F,tbl) - RMLUILUA_INPUTENUM(G,tbl) - RMLUILUA_INPUTENUM(H,tbl) - RMLUILUA_INPUTENUM(I,tbl) - RMLUILUA_INPUTENUM(J,tbl) - RMLUILUA_INPUTENUM(K,tbl) - RMLUILUA_INPUTENUM(L,tbl) - RMLUILUA_INPUTENUM(M,tbl) - RMLUILUA_INPUTENUM(N,tbl) - RMLUILUA_INPUTENUM(O,tbl) - RMLUILUA_INPUTENUM(P,tbl) - RMLUILUA_INPUTENUM(Q,tbl) - RMLUILUA_INPUTENUM(R,tbl) - RMLUILUA_INPUTENUM(S,tbl) - RMLUILUA_INPUTENUM(T,tbl) - RMLUILUA_INPUTENUM(U,tbl) - RMLUILUA_INPUTENUM(V,tbl) - RMLUILUA_INPUTENUM(W,tbl) - RMLUILUA_INPUTENUM(X,tbl) - RMLUILUA_INPUTENUM(Y,tbl) - RMLUILUA_INPUTENUM(Z,tbl) - RMLUILUA_INPUTENUM(OEM_1,tbl) - RMLUILUA_INPUTENUM(OEM_PLUS,tbl) - RMLUILUA_INPUTENUM(OEM_COMMA,tbl) - RMLUILUA_INPUTENUM(OEM_MINUS,tbl) - RMLUILUA_INPUTENUM(OEM_PERIOD,tbl) - RMLUILUA_INPUTENUM(OEM_2,tbl) - RMLUILUA_INPUTENUM(OEM_3,tbl) - RMLUILUA_INPUTENUM(OEM_4,tbl) - RMLUILUA_INPUTENUM(OEM_5,tbl) - RMLUILUA_INPUTENUM(OEM_6,tbl) - RMLUILUA_INPUTENUM(OEM_7,tbl) - RMLUILUA_INPUTENUM(OEM_8,tbl) - RMLUILUA_INPUTENUM(OEM_102,tbl) - RMLUILUA_INPUTENUM(NUMPAD0,tbl) - RMLUILUA_INPUTENUM(NUMPAD1,tbl) - RMLUILUA_INPUTENUM(NUMPAD2,tbl) - RMLUILUA_INPUTENUM(NUMPAD3,tbl) - RMLUILUA_INPUTENUM(NUMPAD4,tbl) - RMLUILUA_INPUTENUM(NUMPAD5,tbl) - RMLUILUA_INPUTENUM(NUMPAD6,tbl) - RMLUILUA_INPUTENUM(NUMPAD7,tbl) - RMLUILUA_INPUTENUM(NUMPAD8,tbl) - RMLUILUA_INPUTENUM(NUMPAD9,tbl) - RMLUILUA_INPUTENUM(NUMPADENTER,tbl) - RMLUILUA_INPUTENUM(MULTIPLY,tbl) - RMLUILUA_INPUTENUM(ADD,tbl) - RMLUILUA_INPUTENUM(SEPARATOR,tbl) - RMLUILUA_INPUTENUM(SUBTRACT,tbl) - RMLUILUA_INPUTENUM(DECIMAL,tbl) - RMLUILUA_INPUTENUM(DIVIDE,tbl) - RMLUILUA_INPUTENUM(OEM_NEC_EQUAL,tbl) - RMLUILUA_INPUTENUM(BACK,tbl) - RMLUILUA_INPUTENUM(TAB,tbl) - RMLUILUA_INPUTENUM(CLEAR,tbl) - RMLUILUA_INPUTENUM(RETURN,tbl) - RMLUILUA_INPUTENUM(PAUSE,tbl) - RMLUILUA_INPUTENUM(CAPITAL,tbl) - RMLUILUA_INPUTENUM(KANA,tbl) - RMLUILUA_INPUTENUM(HANGUL,tbl) - RMLUILUA_INPUTENUM(JUNJA,tbl) - RMLUILUA_INPUTENUM(FINAL,tbl) - RMLUILUA_INPUTENUM(HANJA,tbl) - RMLUILUA_INPUTENUM(KANJI,tbl) - RMLUILUA_INPUTENUM(ESCAPE,tbl) - RMLUILUA_INPUTENUM(CONVERT,tbl) - RMLUILUA_INPUTENUM(NONCONVERT,tbl) - RMLUILUA_INPUTENUM(ACCEPT,tbl) - RMLUILUA_INPUTENUM(MODECHANGE,tbl) - RMLUILUA_INPUTENUM(PRIOR,tbl) - RMLUILUA_INPUTENUM(NEXT,tbl) - RMLUILUA_INPUTENUM(END,tbl) - RMLUILUA_INPUTENUM(HOME,tbl) - RMLUILUA_INPUTENUM(LEFT,tbl) - RMLUILUA_INPUTENUM(UP,tbl) - RMLUILUA_INPUTENUM(RIGHT,tbl) - RMLUILUA_INPUTENUM(DOWN,tbl) - RMLUILUA_INPUTENUM(SELECT,tbl) - RMLUILUA_INPUTENUM(PRINT,tbl) - RMLUILUA_INPUTENUM(EXECUTE,tbl) - RMLUILUA_INPUTENUM(SNAPSHOT,tbl) - RMLUILUA_INPUTENUM(INSERT,tbl) - RMLUILUA_INPUTENUM(DELETE,tbl) - RMLUILUA_INPUTENUM(HELP,tbl) - RMLUILUA_INPUTENUM(LWIN,tbl) - RMLUILUA_INPUTENUM(RWIN,tbl) - RMLUILUA_INPUTENUM(APPS,tbl) - RMLUILUA_INPUTENUM(POWER,tbl) - RMLUILUA_INPUTENUM(SLEEP,tbl) - RMLUILUA_INPUTENUM(WAKE,tbl) - RMLUILUA_INPUTENUM(F1,tbl) - RMLUILUA_INPUTENUM(F2,tbl) - RMLUILUA_INPUTENUM(F3,tbl) - RMLUILUA_INPUTENUM(F4,tbl) - RMLUILUA_INPUTENUM(F5,tbl) - RMLUILUA_INPUTENUM(F6,tbl) - RMLUILUA_INPUTENUM(F7,tbl) - RMLUILUA_INPUTENUM(F8,tbl) - RMLUILUA_INPUTENUM(F9,tbl) - RMLUILUA_INPUTENUM(F10,tbl) - RMLUILUA_INPUTENUM(F11,tbl) - RMLUILUA_INPUTENUM(F12,tbl) - RMLUILUA_INPUTENUM(F13,tbl) - RMLUILUA_INPUTENUM(F14,tbl) - RMLUILUA_INPUTENUM(F15,tbl) - RMLUILUA_INPUTENUM(F16,tbl) - RMLUILUA_INPUTENUM(F17,tbl) - RMLUILUA_INPUTENUM(F18,tbl) - RMLUILUA_INPUTENUM(F19,tbl) - RMLUILUA_INPUTENUM(F20,tbl) - RMLUILUA_INPUTENUM(F21,tbl) - RMLUILUA_INPUTENUM(F22,tbl) - RMLUILUA_INPUTENUM(F23,tbl) - RMLUILUA_INPUTENUM(F24,tbl) - RMLUILUA_INPUTENUM(NUMLOCK,tbl) - RMLUILUA_INPUTENUM(SCROLL,tbl) - RMLUILUA_INPUTENUM(OEM_FJ_JISHO,tbl) - RMLUILUA_INPUTENUM(OEM_FJ_MASSHOU,tbl) - RMLUILUA_INPUTENUM(OEM_FJ_TOUROKU,tbl) - RMLUILUA_INPUTENUM(OEM_FJ_LOYA,tbl) - RMLUILUA_INPUTENUM(OEM_FJ_ROYA,tbl) - RMLUILUA_INPUTENUM(LSHIFT,tbl) - RMLUILUA_INPUTENUM(RSHIFT,tbl) - RMLUILUA_INPUTENUM(LCONTROL,tbl) - RMLUILUA_INPUTENUM(RCONTROL,tbl) - RMLUILUA_INPUTENUM(LMENU,tbl) - RMLUILUA_INPUTENUM(RMENU,tbl) - RMLUILUA_INPUTENUM(BROWSER_BACK,tbl) - RMLUILUA_INPUTENUM(BROWSER_FORWARD,tbl) - RMLUILUA_INPUTENUM(BROWSER_REFRESH,tbl) - RMLUILUA_INPUTENUM(BROWSER_STOP,tbl) - RMLUILUA_INPUTENUM(BROWSER_SEARCH,tbl) - RMLUILUA_INPUTENUM(BROWSER_FAVORITES,tbl) - RMLUILUA_INPUTENUM(BROWSER_HOME,tbl) - RMLUILUA_INPUTENUM(VOLUME_MUTE,tbl) - RMLUILUA_INPUTENUM(VOLUME_DOWN,tbl) - RMLUILUA_INPUTENUM(VOLUME_UP,tbl) - RMLUILUA_INPUTENUM(MEDIA_NEXT_TRACK,tbl) - RMLUILUA_INPUTENUM(MEDIA_PREV_TRACK,tbl) - RMLUILUA_INPUTENUM(MEDIA_STOP,tbl) - RMLUILUA_INPUTENUM(MEDIA_PLAY_PAUSE,tbl) - RMLUILUA_INPUTENUM(LAUNCH_MAIL,tbl) - RMLUILUA_INPUTENUM(LAUNCH_MEDIA_SELECT,tbl) - RMLUILUA_INPUTENUM(LAUNCH_APP1,tbl) - RMLUILUA_INPUTENUM(LAUNCH_APP2,tbl) - RMLUILUA_INPUTENUM(OEM_AX,tbl) - RMLUILUA_INPUTENUM(ICO_HELP,tbl) - RMLUILUA_INPUTENUM(ICO_00,tbl) - RMLUILUA_INPUTENUM(PROCESSKEY,tbl) - RMLUILUA_INPUTENUM(ICO_CLEAR,tbl) - RMLUILUA_INPUTENUM(ATTN,tbl) - RMLUILUA_INPUTENUM(CRSEL,tbl) - RMLUILUA_INPUTENUM(EXSEL,tbl) - RMLUILUA_INPUTENUM(EREOF,tbl) - RMLUILUA_INPUTENUM(PLAY,tbl) - RMLUILUA_INPUTENUM(ZOOM,tbl) - RMLUILUA_INPUTENUM(PA1,tbl) - RMLUILUA_INPUTENUM(OEM_CLEAR,tbl) + lua_newtable(L); + int tbl = lua_gettop(L); + RMLUILUA_INPUTENUM(UNKNOWN, tbl) + RMLUILUA_INPUTENUM(SPACE, tbl) + RMLUILUA_INPUTENUM(0, tbl) + RMLUILUA_INPUTENUM(1, tbl) + RMLUILUA_INPUTENUM(2, tbl) + RMLUILUA_INPUTENUM(3, tbl) + RMLUILUA_INPUTENUM(4, tbl) + RMLUILUA_INPUTENUM(5, tbl) + RMLUILUA_INPUTENUM(6, tbl) + RMLUILUA_INPUTENUM(7, tbl) + RMLUILUA_INPUTENUM(8, tbl) + RMLUILUA_INPUTENUM(9, tbl) + RMLUILUA_INPUTENUM(A, tbl) + RMLUILUA_INPUTENUM(B, tbl) + RMLUILUA_INPUTENUM(C, tbl) + RMLUILUA_INPUTENUM(D, tbl) + RMLUILUA_INPUTENUM(E, tbl) + RMLUILUA_INPUTENUM(F, tbl) + RMLUILUA_INPUTENUM(G, tbl) + RMLUILUA_INPUTENUM(H, tbl) + RMLUILUA_INPUTENUM(I, tbl) + RMLUILUA_INPUTENUM(J, tbl) + RMLUILUA_INPUTENUM(K, tbl) + RMLUILUA_INPUTENUM(L, tbl) + RMLUILUA_INPUTENUM(M, tbl) + RMLUILUA_INPUTENUM(N, tbl) + RMLUILUA_INPUTENUM(O, tbl) + RMLUILUA_INPUTENUM(P, tbl) + RMLUILUA_INPUTENUM(Q, tbl) + RMLUILUA_INPUTENUM(R, tbl) + RMLUILUA_INPUTENUM(S, tbl) + RMLUILUA_INPUTENUM(T, tbl) + RMLUILUA_INPUTENUM(U, tbl) + RMLUILUA_INPUTENUM(V, tbl) + RMLUILUA_INPUTENUM(W, tbl) + RMLUILUA_INPUTENUM(X, tbl) + RMLUILUA_INPUTENUM(Y, tbl) + RMLUILUA_INPUTENUM(Z, tbl) + RMLUILUA_INPUTENUM(OEM_1, tbl) + RMLUILUA_INPUTENUM(OEM_PLUS, tbl) + RMLUILUA_INPUTENUM(OEM_COMMA, tbl) + RMLUILUA_INPUTENUM(OEM_MINUS, tbl) + RMLUILUA_INPUTENUM(OEM_PERIOD, tbl) + RMLUILUA_INPUTENUM(OEM_2, tbl) + RMLUILUA_INPUTENUM(OEM_3, tbl) + RMLUILUA_INPUTENUM(OEM_4, tbl) + RMLUILUA_INPUTENUM(OEM_5, tbl) + RMLUILUA_INPUTENUM(OEM_6, tbl) + RMLUILUA_INPUTENUM(OEM_7, tbl) + RMLUILUA_INPUTENUM(OEM_8, tbl) + RMLUILUA_INPUTENUM(OEM_102, tbl) + RMLUILUA_INPUTENUM(NUMPAD0, tbl) + RMLUILUA_INPUTENUM(NUMPAD1, tbl) + RMLUILUA_INPUTENUM(NUMPAD2, tbl) + RMLUILUA_INPUTENUM(NUMPAD3, tbl) + RMLUILUA_INPUTENUM(NUMPAD4, tbl) + RMLUILUA_INPUTENUM(NUMPAD5, tbl) + RMLUILUA_INPUTENUM(NUMPAD6, tbl) + RMLUILUA_INPUTENUM(NUMPAD7, tbl) + RMLUILUA_INPUTENUM(NUMPAD8, tbl) + RMLUILUA_INPUTENUM(NUMPAD9, tbl) + RMLUILUA_INPUTENUM(NUMPADENTER, tbl) + RMLUILUA_INPUTENUM(MULTIPLY, tbl) + RMLUILUA_INPUTENUM(ADD, tbl) + RMLUILUA_INPUTENUM(SEPARATOR, tbl) + RMLUILUA_INPUTENUM(SUBTRACT, tbl) + RMLUILUA_INPUTENUM(DECIMAL, tbl) + RMLUILUA_INPUTENUM(DIVIDE, tbl) + RMLUILUA_INPUTENUM(OEM_NEC_EQUAL, tbl) + RMLUILUA_INPUTENUM(BACK, tbl) + RMLUILUA_INPUTENUM(TAB, tbl) + RMLUILUA_INPUTENUM(CLEAR, tbl) + RMLUILUA_INPUTENUM(RETURN, tbl) + RMLUILUA_INPUTENUM(PAUSE, tbl) + RMLUILUA_INPUTENUM(CAPITAL, tbl) + RMLUILUA_INPUTENUM(KANA, tbl) + RMLUILUA_INPUTENUM(HANGUL, tbl) + RMLUILUA_INPUTENUM(JUNJA, tbl) + RMLUILUA_INPUTENUM(FINAL, tbl) + RMLUILUA_INPUTENUM(HANJA, tbl) + RMLUILUA_INPUTENUM(KANJI, tbl) + RMLUILUA_INPUTENUM(ESCAPE, tbl) + RMLUILUA_INPUTENUM(CONVERT, tbl) + RMLUILUA_INPUTENUM(NONCONVERT, tbl) + RMLUILUA_INPUTENUM(ACCEPT, tbl) + RMLUILUA_INPUTENUM(MODECHANGE, tbl) + RMLUILUA_INPUTENUM(PRIOR, tbl) + RMLUILUA_INPUTENUM(NEXT, tbl) + RMLUILUA_INPUTENUM(END, tbl) + RMLUILUA_INPUTENUM(HOME, tbl) + RMLUILUA_INPUTENUM(LEFT, tbl) + RMLUILUA_INPUTENUM(UP, tbl) + RMLUILUA_INPUTENUM(RIGHT, tbl) + RMLUILUA_INPUTENUM(DOWN, tbl) + RMLUILUA_INPUTENUM(SELECT, tbl) + RMLUILUA_INPUTENUM(PRINT, tbl) + RMLUILUA_INPUTENUM(EXECUTE, tbl) + RMLUILUA_INPUTENUM(SNAPSHOT, tbl) + RMLUILUA_INPUTENUM(INSERT, tbl) + RMLUILUA_INPUTENUM(DELETE, tbl) + RMLUILUA_INPUTENUM(HELP, tbl) + RMLUILUA_INPUTENUM(LWIN, tbl) + RMLUILUA_INPUTENUM(RWIN, tbl) + RMLUILUA_INPUTENUM(APPS, tbl) + RMLUILUA_INPUTENUM(POWER, tbl) + RMLUILUA_INPUTENUM(SLEEP, tbl) + RMLUILUA_INPUTENUM(WAKE, tbl) + RMLUILUA_INPUTENUM(F1, tbl) + RMLUILUA_INPUTENUM(F2, tbl) + RMLUILUA_INPUTENUM(F3, tbl) + RMLUILUA_INPUTENUM(F4, tbl) + RMLUILUA_INPUTENUM(F5, tbl) + RMLUILUA_INPUTENUM(F6, tbl) + RMLUILUA_INPUTENUM(F7, tbl) + RMLUILUA_INPUTENUM(F8, tbl) + RMLUILUA_INPUTENUM(F9, tbl) + RMLUILUA_INPUTENUM(F10, tbl) + RMLUILUA_INPUTENUM(F11, tbl) + RMLUILUA_INPUTENUM(F12, tbl) + RMLUILUA_INPUTENUM(F13, tbl) + RMLUILUA_INPUTENUM(F14, tbl) + RMLUILUA_INPUTENUM(F15, tbl) + RMLUILUA_INPUTENUM(F16, tbl) + RMLUILUA_INPUTENUM(F17, tbl) + RMLUILUA_INPUTENUM(F18, tbl) + RMLUILUA_INPUTENUM(F19, tbl) + RMLUILUA_INPUTENUM(F20, tbl) + RMLUILUA_INPUTENUM(F21, tbl) + RMLUILUA_INPUTENUM(F22, tbl) + RMLUILUA_INPUTENUM(F23, tbl) + RMLUILUA_INPUTENUM(F24, tbl) + RMLUILUA_INPUTENUM(NUMLOCK, tbl) + RMLUILUA_INPUTENUM(SCROLL, tbl) + RMLUILUA_INPUTENUM(OEM_FJ_JISHO, tbl) + RMLUILUA_INPUTENUM(OEM_FJ_MASSHOU, tbl) + RMLUILUA_INPUTENUM(OEM_FJ_TOUROKU, tbl) + RMLUILUA_INPUTENUM(OEM_FJ_LOYA, tbl) + RMLUILUA_INPUTENUM(OEM_FJ_ROYA, tbl) + RMLUILUA_INPUTENUM(LSHIFT, tbl) + RMLUILUA_INPUTENUM(RSHIFT, tbl) + RMLUILUA_INPUTENUM(LCONTROL, tbl) + RMLUILUA_INPUTENUM(RCONTROL, tbl) + RMLUILUA_INPUTENUM(LMENU, tbl) + RMLUILUA_INPUTENUM(RMENU, tbl) + RMLUILUA_INPUTENUM(BROWSER_BACK, tbl) + RMLUILUA_INPUTENUM(BROWSER_FORWARD, tbl) + RMLUILUA_INPUTENUM(BROWSER_REFRESH, tbl) + RMLUILUA_INPUTENUM(BROWSER_STOP, tbl) + RMLUILUA_INPUTENUM(BROWSER_SEARCH, tbl) + RMLUILUA_INPUTENUM(BROWSER_FAVORITES, tbl) + RMLUILUA_INPUTENUM(BROWSER_HOME, tbl) + RMLUILUA_INPUTENUM(VOLUME_MUTE, tbl) + RMLUILUA_INPUTENUM(VOLUME_DOWN, tbl) + RMLUILUA_INPUTENUM(VOLUME_UP, tbl) + RMLUILUA_INPUTENUM(MEDIA_NEXT_TRACK, tbl) + RMLUILUA_INPUTENUM(MEDIA_PREV_TRACK, tbl) + RMLUILUA_INPUTENUM(MEDIA_STOP, tbl) + RMLUILUA_INPUTENUM(MEDIA_PLAY_PAUSE, tbl) + RMLUILUA_INPUTENUM(LAUNCH_MAIL, tbl) + RMLUILUA_INPUTENUM(LAUNCH_MEDIA_SELECT, tbl) + RMLUILUA_INPUTENUM(LAUNCH_APP1, tbl) + RMLUILUA_INPUTENUM(LAUNCH_APP2, tbl) + RMLUILUA_INPUTENUM(OEM_AX, tbl) + RMLUILUA_INPUTENUM(ICO_HELP, tbl) + RMLUILUA_INPUTENUM(ICO_00, tbl) + RMLUILUA_INPUTENUM(PROCESSKEY, tbl) + RMLUILUA_INPUTENUM(ICO_CLEAR, tbl) + RMLUILUA_INPUTENUM(ATTN, tbl) + RMLUILUA_INPUTENUM(CRSEL, tbl) + RMLUILUA_INPUTENUM(EXSEL, tbl) + RMLUILUA_INPUTENUM(EREOF, tbl) + RMLUILUA_INPUTENUM(PLAY, tbl) + RMLUILUA_INPUTENUM(ZOOM, tbl) + RMLUILUA_INPUTENUM(PA1, tbl) + RMLUILUA_INPUTENUM(OEM_CLEAR, tbl) } void LuaRmlUiEnumkey_modifier(lua_State* L) { - lua_newtable(L); - int tbl = lua_gettop(L); - RMLUILUA_INPUTMODIFIERENUM(CTRL,tbl) - RMLUILUA_INPUTMODIFIERENUM(SHIFT,tbl) - RMLUILUA_INPUTMODIFIERENUM(ALT,tbl) - RMLUILUA_INPUTMODIFIERENUM(META,tbl) - RMLUILUA_INPUTMODIFIERENUM(CAPSLOCK,tbl) - RMLUILUA_INPUTMODIFIERENUM(NUMLOCK,tbl) - RMLUILUA_INPUTMODIFIERENUM(SCROLLLOCK,tbl) + lua_newtable(L); + int tbl = lua_gettop(L); + RMLUILUA_INPUTMODIFIERENUM(CTRL, tbl) + RMLUILUA_INPUTMODIFIERENUM(SHIFT, tbl) + RMLUILUA_INPUTMODIFIERENUM(ALT, tbl) + RMLUILUA_INPUTMODIFIERENUM(META, tbl) + RMLUILUA_INPUTMODIFIERENUM(CAPSLOCK, tbl) + RMLUILUA_INPUTMODIFIERENUM(NUMLOCK, tbl) + RMLUILUA_INPUTMODIFIERENUM(SCROLLLOCK, tbl) } - -RegType LuaRmlUiMethods[] = -{ - RMLUI_LUAMETHOD(LuaRmlUi,CreateContext) - RMLUI_LUAMETHOD(LuaRmlUi,LoadFontFace) - RMLUI_LUAMETHOD(LuaRmlUi,RegisterTag) - { nullptr, nullptr }, +RegType LuaRmlUiMethods[] = { + RMLUI_LUAMETHOD(LuaRmlUi, CreateContext), + RMLUI_LUAMETHOD(LuaRmlUi, LoadFontFace), + RMLUI_LUAMETHOD(LuaRmlUi, RegisterTag), + {nullptr, nullptr}, }; -luaL_Reg LuaRmlUiGetters[] = -{ - RMLUI_LUAGETTER(LuaRmlUi,contexts) - RMLUI_LUAGETTER(LuaRmlUi,key_identifier) - RMLUI_LUAGETTER(LuaRmlUi,key_modifier) - { nullptr, nullptr }, +luaL_Reg LuaRmlUiGetters[] = { + RMLUI_LUAGETTER(LuaRmlUi, contexts), + RMLUI_LUAGETTER(LuaRmlUi, key_identifier), + RMLUI_LUAGETTER(LuaRmlUi, key_modifier), + {nullptr, nullptr}, }; -luaL_Reg LuaRmlUiSetters[] = -{ - { nullptr, nullptr }, +luaL_Reg LuaRmlUiSetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(LuaRmlUi) diff --git a/Source/Lua/RmlUi.h b/Source/Lua/RmlUi.h index 04fef5fcb..04e76abf0 100644 --- a/Source/Lua/RmlUi.h +++ b/Source/Lua/RmlUi.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,29 +25,28 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_RMLUI_H #define RMLUI_LUA_RMLUI_H -#include #include +#include namespace Rml { namespace Lua { - -class LuaRmlUi -{ +class LuaRmlUi { public: - //reference to the table defined in LuaRmlUiEnumkey_identifier - int key_identifier_ref; - //reference to the table defined in LuaRmlUiEnumkey_modifier - int key_modifier_ref; -}; + // reference to the table defined in LuaRmlUiEnumkey_identifier + int key_identifier_ref; + // reference to the table defined in LuaRmlUiEnumkey_modifier + int key_modifier_ref; +}; void LuaRmlUiPushrmluiGlobal(lua_State* L); -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int LuaRmlUiCreateContext(lua_State* L, LuaRmlUi* obj); int LuaRmlUiLoadFontFace(lua_State* L, LuaRmlUi* obj); int LuaRmlUiRegisterTag(lua_State* L, LuaRmlUi* obj); diff --git a/Source/Lua/RmlUiContextsProxy.cpp b/Source/Lua/RmlUiContextsProxy.cpp index 159a0cde2..f5a9114ba 100644 --- a/Source/Lua/RmlUiContextsProxy.cpp +++ b/Source/Lua/RmlUiContextsProxy.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,65 +25,61 @@ * THE SOFTWARE. * */ - + #include "RmlUiContextsProxy.h" +#include "Pairs.h" #include #include -#include "Pairs.h" namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,RmlUiContextsProxy__index); - lua_setfield(L,metatable_index,"__index"); - lua_pushcfunction(L,RmlUiContextsProxy__pairs); - lua_setfield(L,metatable_index,"__pairs"); + lua_pushcfunction(L, RmlUiContextsProxy__index); + lua_setfield(L, metatable_index, "__index"); + lua_pushcfunction(L, RmlUiContextsProxy__pairs); + lua_setfield(L, metatable_index, "__pairs"); } int RmlUiContextsProxy__index(lua_State* L) { - /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ - int keytype = lua_type(L,2); - if(keytype == LUA_TSTRING || keytype == LUA_TNUMBER) //only valid key types - { - RmlUiContextsProxy* obj = LuaType::check(L,1); - RMLUI_CHECK_OBJ(obj); - if(keytype == LUA_TSTRING) - { - const char* key = lua_tostring(L,2); - LuaType::push(L,GetContext(key)); - } - else - { - int key = (int)luaL_checkinteger(L,2); - LuaType::push(L,GetContext(key-1)); - } - return 1; - } - else - return LuaType::index(L); + /*the table obj and the missing key are currently on the stack(index 1 & 2) as defined by the Lua language*/ + int keytype = lua_type(L, 2); + if (keytype == LUA_TSTRING || keytype == LUA_TNUMBER) // only valid key types + { + RmlUiContextsProxy* obj = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(obj); + if (keytype == LUA_TSTRING) + { + const char* key = lua_tostring(L, 2); + LuaType::push(L, GetContext(key)); + } + else + { + int key = (int)luaL_checkinteger(L, 2); + LuaType::push(L, GetContext(key - 1)); + } + return 1; + } + else + return LuaType::index(L); } - int RmlUiContextsProxy__pairs(lua_State* L) { - return MakeIntPairs(L); + return MakeIntPairs(L); } - -RegType RmlUiContextsProxyMethods[] = -{ - { nullptr, nullptr }, +RegType RmlUiContextsProxyMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg RmlUiContextsProxyGetters[] = -{ - { nullptr, nullptr }, +luaL_Reg RmlUiContextsProxyGetters[] = { + {nullptr, nullptr}, }; -luaL_Reg RmlUiContextsProxySetters[] = -{ - { nullptr, nullptr }, +luaL_Reg RmlUiContextsProxySetters[] = { + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(RmlUiContextsProxy) diff --git a/Source/Lua/RmlUiContextsProxy.h b/Source/Lua/RmlUiContextsProxy.h index 7c0b09261..df456bc11 100644 --- a/Source/Lua/RmlUiContextsProxy.h +++ b/Source/Lua/RmlUiContextsProxy.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,20 +25,22 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_RMLUICONTEXTSPROXY_H #define RMLUI_LUA_RMLUICONTEXTSPROXY_H #include #include - namespace Rml { namespace Lua { -//where owner is the Element that we should look up information from -struct RmlUiContextsProxy { void* nothing; }; +// where owner is the Element that we should look up information from +struct RmlUiContextsProxy { + void* nothing; +}; -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int RmlUiContextsProxy__index(lua_State* L); int RmlUiContextsProxy__pairs(lua_State* L); diff --git a/Source/Lua/Utilities.cpp b/Source/Lua/Utilities.cpp index 1c56bce7b..14e997004 100644 --- a/Source/Lua/Utilities.cpp +++ b/Source/Lua/Utilities.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,43 +25,42 @@ * THE SOFTWARE. * */ - -#include + #include +#include namespace Rml { namespace Lua { #if LUA_VERSION_NUM < 502 -void lua_len (lua_State *L, int i) { - switch (lua_type(L, i)) { - case LUA_TSTRING: - lua_pushnumber(L, (lua_Number)lua_objlen(L, i)); - break; - case LUA_TTABLE: - if (!luaL_callmeta(L, i, "__len")) - lua_pushnumber(L, (lua_Number)lua_objlen(L, i)); - break; - case LUA_TUSERDATA: - if (luaL_callmeta(L, i, "__len")) - break; - /* FALLTHROUGH */ - default: - luaL_error(L, "attempt to get length of a %s value", - lua_typename(L, lua_type(L, i))); - } +void lua_len(lua_State* L, int i) +{ + switch (lua_type(L, i)) + { + case LUA_TSTRING: lua_pushnumber(L, (lua_Number)lua_objlen(L, i)); break; + case LUA_TTABLE: + if (!luaL_callmeta(L, i, "__len")) + lua_pushnumber(L, (lua_Number)lua_objlen(L, i)); + break; + case LUA_TUSERDATA: + if (luaL_callmeta(L, i, "__len")) + break; + /* FALLTHROUGH */ + default: luaL_error(L, "attempt to get length of a %s value", lua_typename(L, lua_type(L, i))); + } } -lua_Integer luaL_len(lua_State *L, int i) { - lua_Integer res = 0; - int isnum = 0; - luaL_checkstack(L, 1, "not enough stack slots"); - lua_len(L, i); - res = lua_tointegerx(L, -1, &isnum); - lua_pop(L, 1); - if (!isnum) - luaL_error(L, "object length is not an integer"); - return res; +lua_Integer luaL_len(lua_State* L, int i) +{ + lua_Integer res = 0; + int isnum = 0; + luaL_checkstack(L, 1, "not enough stack slots"); + lua_len(L, i); + res = lua_tointegerx(L, -1, &isnum); + lua_pop(L, 1); + if (!isnum) + luaL_error(L, "object length is not an integer"); + return res; } #endif @@ -75,33 +74,17 @@ void PushVariant(lua_State* L, const Variant* var) switch (var->GetType()) { - case Variant::BOOL: - lua_pushboolean(L, var->Get()); - break; + case Variant::BOOL: lua_pushboolean(L, var->Get()); break; case Variant::BYTE: case Variant::CHAR: - case Variant::INT: - lua_pushinteger(L, var->Get()); - break; - case Variant::INT64: - lua_pushinteger(L, var->Get()); - break; - case Variant::UINT: - lua_pushinteger(L, var->Get()); - break; - case Variant::UINT64: - lua_pushinteger(L, var->Get()); - break; + case Variant::INT: lua_pushinteger(L, var->Get()); break; + case Variant::INT64: lua_pushinteger(L, var->Get()); break; + case Variant::UINT: lua_pushinteger(L, var->Get()); break; + case Variant::UINT64: lua_pushinteger(L, var->Get()); break; case Variant::FLOAT: - case Variant::DOUBLE: - lua_pushnumber(L, var->Get()); - break; - case Variant::COLOURB: - LuaType::push(L, new Colourb(var->Get()), true); - break; - case Variant::COLOURF: - LuaType::push(L, new Colourf(var->Get()), true); - break; + case Variant::DOUBLE: lua_pushnumber(L, var->Get()); break; + case Variant::COLOURB: LuaType::push(L, new Colourb(var->Get()), true); break; + case Variant::COLOURF: LuaType::push(L, new Colourf(var->Get()), true); break; case Variant::STRING: { const String& s = var->GetReference(); @@ -109,15 +92,11 @@ void PushVariant(lua_State* L, const Variant* var) } break; case Variant::VECTOR2: - //according to Variant.inl, it is going to be a Vector2f + // according to Variant.inl, it is going to be a Vector2f LuaType::push(L, new Vector2f(var->Get()), true); break; - case Variant::VOIDPTR: - lua_pushlightuserdata(L, var->Get()); - break; - default: - lua_pushnil(L); - break; + case Variant::VOIDPTR: lua_pushlightuserdata(L, var->Get()); break; + default: lua_pushnil(L); break; } } @@ -128,20 +107,12 @@ void GetVariant(lua_State* L, int index, Variant* variant) switch (lua_type(L, index)) { - case LUA_TBOOLEAN: - *variant = (bool)lua_toboolean(L, index); - break; - case LUA_TNUMBER: - *variant = lua_tonumber(L, index); - break; - case LUA_TSTRING: - *variant = Rml::String(lua_tostring(L, index)); - break; - case LUA_TLIGHTUSERDATA: - *variant = lua_touserdata(L, index); - break; + case LUA_TBOOLEAN: *variant = (bool)lua_toboolean(L, index); break; + case LUA_TNUMBER: *variant = lua_tonumber(L, index); break; + case LUA_TSTRING: *variant = Rml::String(lua_tostring(L, index)); break; + case LUA_TLIGHTUSERDATA: *variant = lua_touserdata(L, index); break; case LUA_TNIL: - default: // todo: support other types + default: // todo: support other types *variant = Variant(); break; } diff --git a/Source/Lua/Vector2f.cpp b/Source/Lua/Vector2f.cpp index 1cba7a4ec..bd4d3a09d 100644 --- a/Source/Lua/Vector2f.cpp +++ b/Source/Lua/Vector2f.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,214 +25,210 @@ * THE SOFTWARE. * */ - + #include "Vector2f.h" #include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,Vector2fnew); - lua_setfield(L,metatable_index-1,"new"); + lua_pushcfunction(L, Vector2fnew); + lua_setfield(L, metatable_index - 1, "new"); - lua_pushcfunction(L,Vector2f__mul); - lua_setfield(L,metatable_index,"__mul"); + lua_pushcfunction(L, Vector2f__mul); + lua_setfield(L, metatable_index, "__mul"); - lua_pushcfunction(L,Vector2f__div); - lua_setfield(L,metatable_index,"__div"); + lua_pushcfunction(L, Vector2f__div); + lua_setfield(L, metatable_index, "__div"); - lua_pushcfunction(L,Vector2f__add); - lua_setfield(L,metatable_index,"__add"); + lua_pushcfunction(L, Vector2f__add); + lua_setfield(L, metatable_index, "__add"); - lua_pushcfunction(L,Vector2f__sub); - lua_setfield(L,metatable_index,"__sub"); + lua_pushcfunction(L, Vector2f__sub); + lua_setfield(L, metatable_index, "__sub"); - lua_pushcfunction(L,Vector2f__eq); - lua_setfield(L,metatable_index,"__eq"); + lua_pushcfunction(L, Vector2f__eq); + lua_setfield(L, metatable_index, "__eq"); - //stack is in the same state as it was before it entered this function - return; + // stack is in the same state as it was before it entered this function + return; } int Vector2fnew(lua_State* L) { - float x = (float)luaL_checknumber(L,1); - float y = (float)luaL_checknumber(L,2); + float x = (float)luaL_checknumber(L, 1); + float y = (float)luaL_checknumber(L, 2); - Vector2f* vect = new Vector2f(x,y); + Vector2f* vect = new Vector2f(x, y); - LuaType::push(L,vect,true); //true means it will be deleted when it is garbage collected - return 1; + LuaType::push(L, vect, true); // true means it will be deleted when it is garbage collected + return 1; } int Vector2f__mul(lua_State* L) { - Vector2f* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - float rhs = (float)luaL_checknumber(L,2); + Vector2f* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + float rhs = (float)luaL_checknumber(L, 2); - Vector2f* res = new Vector2f(0.f,0.f); - (*res) = (*lhs) * rhs; + Vector2f* res = new Vector2f(0.f, 0.f); + (*res) = (*lhs) * rhs; - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2f__div(lua_State* L) { - Vector2f* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - float rhs = (float)luaL_checknumber(L,2); + Vector2f* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + float rhs = (float)luaL_checknumber(L, 2); - Vector2f* res = new Vector2f(0.f,0.f); - (*res) = (*lhs) / rhs; + Vector2f* res = new Vector2f(0.f, 0.f); + (*res) = (*lhs) / rhs; - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2f__add(lua_State* L) { - Vector2f* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Vector2f* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Vector2f* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Vector2f* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - Vector2f* res = new Vector2f(0.f,0.f); - (*res) = (*lhs) + (*rhs); + Vector2f* res = new Vector2f(0.f, 0.f); + (*res) = (*lhs) + (*rhs); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2f__sub(lua_State* L) { - Vector2f* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Vector2f* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Vector2f* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Vector2f* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - Vector2f* res = new Vector2f(0.f,0.f); - (*res) = (*lhs) - (*rhs); + Vector2f* res = new Vector2f(0.f, 0.f); + (*res) = (*lhs) - (*rhs); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2f__eq(lua_State* L) { - Vector2f* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Vector2f* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Vector2f* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Vector2f* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); - return 1; + lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); + return 1; } - int Vector2fDotProduct(lua_State* L, Vector2f* obj) { - Vector2f* rhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(rhs); - - float res = obj->DotProduct(*rhs); + Vector2f* rhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(rhs); + + float res = obj->DotProduct(*rhs); - lua_pushnumber(L,res); - return 1; + lua_pushnumber(L, res); + return 1; } int Vector2fNormalise(lua_State* L, Vector2f* obj) { - Vector2f* res = new Vector2f(); - (*res) = obj->Normalise(); + Vector2f* res = new Vector2f(); + (*res) = obj->Normalise(); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2fRotate(lua_State* L, Vector2f* obj) { - float num = (float)luaL_checknumber(L,1); + float num = (float)luaL_checknumber(L, 1); - Vector2f* res = new Vector2f(); - (*res) = obj->Rotate(num); + Vector2f* res = new Vector2f(); + (*res) = obj->Rotate(num); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } -int Vector2fGetAttrx(lua_State*L) +int Vector2fGetAttrx(lua_State* L) { - Vector2f* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); + Vector2f* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); - lua_pushnumber(L,self->x); - return 1; + lua_pushnumber(L, self->x); + return 1; } -int Vector2fGetAttry(lua_State*L) +int Vector2fGetAttry(lua_State* L) { - Vector2f* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); + Vector2f* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); - lua_pushnumber(L,self->y); - return 1; + lua_pushnumber(L, self->y); + return 1; } -int Vector2fGetAttrmagnitude(lua_State*L) +int Vector2fGetAttrmagnitude(lua_State* L) { - Vector2f* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); + Vector2f* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); - lua_pushnumber(L,self->Magnitude()); - return 1; + lua_pushnumber(L, self->Magnitude()); + return 1; } -int Vector2fSetAttrx(lua_State*L) +int Vector2fSetAttrx(lua_State* L) { - Vector2f* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); - float value = (float)luaL_checknumber(L,2); + Vector2f* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); + float value = (float)luaL_checknumber(L, 2); - self->x = value; - return 0; + self->x = value; + return 0; } -int Vector2fSetAttry(lua_State*L) +int Vector2fSetAttry(lua_State* L) { - Vector2f* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); - float value = (float)luaL_checknumber(L,2); + Vector2f* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); + float value = (float)luaL_checknumber(L, 2); - self->y = value; - return 0; + self->y = value; + return 0; } - -RegType Vector2fMethods[] = -{ - RMLUI_LUAMETHOD(Vector2f,DotProduct) - RMLUI_LUAMETHOD(Vector2f,Normalise) - RMLUI_LUAMETHOD(Vector2f,Rotate) - { nullptr, nullptr }, +RegType Vector2fMethods[] = { + RMLUI_LUAMETHOD(Vector2f, DotProduct), + RMLUI_LUAMETHOD(Vector2f, Normalise), + RMLUI_LUAMETHOD(Vector2f, Rotate), + {nullptr, nullptr}, }; -luaL_Reg Vector2fGetters[]= -{ - RMLUI_LUAGETTER(Vector2f,x) - RMLUI_LUAGETTER(Vector2f,y) - RMLUI_LUAGETTER(Vector2f,magnitude) - { nullptr, nullptr }, +luaL_Reg Vector2fGetters[] = { + RMLUI_LUAGETTER(Vector2f, x), + RMLUI_LUAGETTER(Vector2f, y), + RMLUI_LUAGETTER(Vector2f, magnitude), + {nullptr, nullptr}, }; -luaL_Reg Vector2fSetters[]= -{ - RMLUI_LUASETTER(Vector2f,x) - RMLUI_LUASETTER(Vector2f,y) - { nullptr, nullptr }, +luaL_Reg Vector2fSetters[] = { + RMLUI_LUASETTER(Vector2f, x), + RMLUI_LUASETTER(Vector2f, y), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Vector2f) diff --git a/Source/Lua/Vector2f.h b/Source/Lua/Vector2f.h index bc6ca8a61..bf4dbfe16 100644 --- a/Source/Lua/Vector2f.h +++ b/Source/Lua/Vector2f.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,17 +25,18 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_VECTOR2F_H #define RMLUI_LUA_VECTOR2F_H +#include #include #include -#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int Vector2fnew(lua_State* L); int Vector2f__mul(lua_State* L); @@ -48,13 +49,12 @@ int Vector2fDotProduct(lua_State* L, Vector2f* obj); int Vector2fNormalise(lua_State* L, Vector2f* obj); int Vector2fRotate(lua_State* L, Vector2f* obj); -int Vector2fGetAttrx(lua_State*L); -int Vector2fGetAttry(lua_State*L); -int Vector2fGetAttrmagnitude(lua_State*L); - -int Vector2fSetAttrx(lua_State*L); -int Vector2fSetAttry(lua_State*L); +int Vector2fGetAttrx(lua_State* L); +int Vector2fGetAttry(lua_State* L); +int Vector2fGetAttrmagnitude(lua_State* L); +int Vector2fSetAttrx(lua_State* L); +int Vector2fSetAttry(lua_State* L); extern RegType Vector2fMethods[]; extern luaL_Reg Vector2fGetters[]; diff --git a/Source/Lua/Vector2i.cpp b/Source/Lua/Vector2i.cpp index ec96548f1..640f31e19 100644 --- a/Source/Lua/Vector2i.cpp +++ b/Source/Lua/Vector2i.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,178 +25,174 @@ * THE SOFTWARE. * */ - -#include "Vector2i.h" +#include "Vector2i.h" namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index) +template <> +void ExtraInit(lua_State* L, int metatable_index) { - lua_pushcfunction(L,Vector2inew); - lua_setfield(L,metatable_index-1,"new"); + lua_pushcfunction(L, Vector2inew); + lua_setfield(L, metatable_index - 1, "new"); - lua_pushcfunction(L,Vector2i__mul); - lua_setfield(L,metatable_index,"__mul"); + lua_pushcfunction(L, Vector2i__mul); + lua_setfield(L, metatable_index, "__mul"); - lua_pushcfunction(L,Vector2i__div); - lua_setfield(L,metatable_index,"__div"); + lua_pushcfunction(L, Vector2i__div); + lua_setfield(L, metatable_index, "__div"); - lua_pushcfunction(L,Vector2i__add); - lua_setfield(L,metatable_index,"__add"); + lua_pushcfunction(L, Vector2i__add); + lua_setfield(L, metatable_index, "__add"); - lua_pushcfunction(L,Vector2i__sub); - lua_setfield(L,metatable_index,"__sub"); + lua_pushcfunction(L, Vector2i__sub); + lua_setfield(L, metatable_index, "__sub"); - lua_pushcfunction(L,Vector2i__eq); - lua_setfield(L,metatable_index,"__eq"); + lua_pushcfunction(L, Vector2i__eq); + lua_setfield(L, metatable_index, "__eq"); - //stack is in the same state as it was before it entered this function - return; + // stack is in the same state as it was before it entered this function + return; } int Vector2inew(lua_State* L) { - int x = (int)luaL_checkinteger(L,1); - int y = (int)luaL_checkinteger(L,2); + int x = (int)luaL_checkinteger(L, 1); + int y = (int)luaL_checkinteger(L, 2); - Vector2i* vect = new Vector2i(x,y); + Vector2i* vect = new Vector2i(x, y); - LuaType::push(L,vect,true); //true means it will be deleted when it is garbage collected - return 1; + LuaType::push(L, vect, true); // true means it will be deleted when it is garbage collected + return 1; } int Vector2i__mul(lua_State* L) { - Vector2i* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - int rhs = (int)luaL_checkinteger(L,2); + Vector2i* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + int rhs = (int)luaL_checkinteger(L, 2); - Vector2i* res = new Vector2i(0,0); - (*res) = (*lhs) * rhs; + Vector2i* res = new Vector2i(0, 0); + (*res) = (*lhs) * rhs; - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2i__div(lua_State* L) { - Vector2i* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - int rhs = (int)luaL_checkinteger(L,2); + Vector2i* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + int rhs = (int)luaL_checkinteger(L, 2); - Vector2i* res = new Vector2i(0,0); - (*res) = (*lhs) / rhs; + Vector2i* res = new Vector2i(0, 0); + (*res) = (*lhs) / rhs; - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2i__add(lua_State* L) { - Vector2i* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Vector2i* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Vector2i* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Vector2i* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - Vector2i* res = new Vector2i(0,0); - (*res) = (*lhs) + (*rhs); + Vector2i* res = new Vector2i(0, 0); + (*res) = (*lhs) + (*rhs); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2i__sub(lua_State* L) { - Vector2i* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Vector2i* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Vector2i* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Vector2i* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - Vector2i* res = new Vector2i(0,0); - (*res) = (*lhs) - (*rhs); + Vector2i* res = new Vector2i(0, 0); + (*res) = (*lhs) - (*rhs); - LuaType::push(L,res,true); - return 1; + LuaType::push(L, res, true); + return 1; } int Vector2i__eq(lua_State* L) { - Vector2i* lhs = LuaType::check(L,1); - RMLUI_CHECK_OBJ(lhs); - Vector2i* rhs = LuaType::check(L,2); - RMLUI_CHECK_OBJ(rhs); + Vector2i* lhs = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(lhs); + Vector2i* rhs = LuaType::check(L, 2); + RMLUI_CHECK_OBJ(rhs); - lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); - return 1; + lua_pushboolean(L, (*lhs) == (*rhs) ? 1 : 0); + return 1; } -int Vector2iGetAttrx(lua_State*L) +int Vector2iGetAttrx(lua_State* L) { - Vector2i* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); + Vector2i* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); - lua_pushinteger(L,self->x); - return 1; + lua_pushinteger(L, self->x); + return 1; } -int Vector2iGetAttry(lua_State*L) +int Vector2iGetAttry(lua_State* L) { - Vector2i* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); + Vector2i* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); - lua_pushinteger(L,self->y); - return 1; + lua_pushinteger(L, self->y); + return 1; } -int Vector2iGetAttrmagnitude(lua_State*L) +int Vector2iGetAttrmagnitude(lua_State* L) { - Vector2i* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); + Vector2i* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); - lua_pushnumber(L,self->Magnitude()); - return 1; + lua_pushnumber(L, self->Magnitude()); + return 1; } -int Vector2iSetAttrx(lua_State*L) +int Vector2iSetAttrx(lua_State* L) { - Vector2i* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); - int value = (int)luaL_checkinteger(L,2); + Vector2i* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); + int value = (int)luaL_checkinteger(L, 2); - self->x = value; - return 0; + self->x = value; + return 0; } -int Vector2iSetAttry(lua_State*L) +int Vector2iSetAttry(lua_State* L) { - Vector2i* self = LuaType::check(L,1); - RMLUI_CHECK_OBJ(self); - int value = (int)luaL_checkinteger(L,2); + Vector2i* self = LuaType::check(L, 1); + RMLUI_CHECK_OBJ(self); + int value = (int)luaL_checkinteger(L, 2); - self->y = value; - return 0; + self->y = value; + return 0; } - -RegType Vector2iMethods[] = -{ - { nullptr, nullptr }, +RegType Vector2iMethods[] = { + {nullptr, nullptr}, }; -luaL_Reg Vector2iGetters[]= -{ - RMLUI_LUAGETTER(Vector2i,x) - RMLUI_LUAGETTER(Vector2i,y) - RMLUI_LUAGETTER(Vector2i,magnitude) - { nullptr, nullptr }, +luaL_Reg Vector2iGetters[] = { + RMLUI_LUAGETTER(Vector2i, x), + RMLUI_LUAGETTER(Vector2i, y), + RMLUI_LUAGETTER(Vector2i, magnitude), + {nullptr, nullptr}, }; -luaL_Reg Vector2iSetters[]= -{ - RMLUI_LUASETTER(Vector2i,x) - RMLUI_LUASETTER(Vector2i,y) - { nullptr, nullptr }, +luaL_Reg Vector2iSetters[] = { + RMLUI_LUASETTER(Vector2i, x), + RMLUI_LUASETTER(Vector2i, y), + {nullptr, nullptr}, }; RMLUI_LUATYPE_DEFINE(Vector2i) diff --git a/Source/Lua/Vector2i.h b/Source/Lua/Vector2i.h index acfdc65b7..4994c9be8 100644 --- a/Source/Lua/Vector2i.h +++ b/Source/Lua/Vector2i.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,17 +25,18 @@ * THE SOFTWARE. * */ - + #ifndef RMLUI_LUA_VECTOR2I_H #define RMLUI_LUA_VECTOR2I_H +#include #include #include -#include namespace Rml { namespace Lua { -template<> void ExtraInit(lua_State* L, int metatable_index); +template <> +void ExtraInit(lua_State* L, int metatable_index); int Vector2inew(lua_State* L); int Vector2i__mul(lua_State* L); int Vector2i__div(lua_State* L); @@ -43,15 +44,14 @@ int Vector2i__add(lua_State* L); int Vector2i__sub(lua_State* L); int Vector2i__eq(lua_State* L); -//getters -int Vector2iGetAttrx(lua_State*L); -int Vector2iGetAttry(lua_State*L); -int Vector2iGetAttrmagnitude(lua_State*L); - -//setters -int Vector2iSetAttrx(lua_State*L); -int Vector2iSetAttry(lua_State*L); +// getters +int Vector2iGetAttrx(lua_State* L); +int Vector2iGetAttry(lua_State* L); +int Vector2iGetAttrmagnitude(lua_State* L); +// setters +int Vector2iSetAttrx(lua_State* L); +int Vector2iSetAttry(lua_State* L); extern RegType Vector2iMethods[]; extern luaL_Reg Vector2iGetters[]; diff --git a/Source/SVG/ElementSVG.cpp b/Source/SVG/ElementSVG.cpp index 2ddd68f7e..0ea6b7d32 100644 --- a/Source/SVG/ElementSVG.cpp +++ b/Source/SVG/ElementSVG.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -42,14 +42,9 @@ namespace Rml { +ElementSVG::ElementSVG(const String& tag) : Element(tag), geometry(this) {} -ElementSVG::ElementSVG(const String& tag) : Element(tag), geometry(this) -{ -} - -ElementSVG::~ElementSVG() -{ -} +ElementSVG::~ElementSVG() {} bool ElementSVG::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio) { @@ -58,11 +53,13 @@ bool ElementSVG::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio) dimensions = intrinsic_dimensions; - if (HasAttribute("width")) { - dimensions.x = GetAttribute< float >("width", -1); + if (HasAttribute("width")) + { + dimensions.x = GetAttribute("width", -1); } - if (HasAttribute("height")) { - dimensions.y = GetAttribute< float >("height", -1); + if (HasAttribute("height")) + { + dimensions.y = GetAttribute("height", -1); } if (dimensions.y > 0) @@ -99,8 +96,7 @@ void ElementSVG::OnAttributeChange(const ElementAttributes& changed_attributes) DirtyLayout(); } - if (changed_attributes.find("width") != changed_attributes.end() || - changed_attributes.find("height") != changed_attributes.end()) + if (changed_attributes.find("width") != changed_attributes.end() || changed_attributes.find("height") != changed_attributes.end()) { DirtyLayout(); } @@ -110,8 +106,8 @@ void ElementSVG::OnPropertyChange(const PropertyIdSet& changed_properties) { Element::OnPropertyChange(changed_properties); - if (changed_properties.Contains(PropertyId::ImageColor) || - changed_properties.Contains(PropertyId::Opacity)) { + if (changed_properties.Contains(PropertyId::ImageColor) || changed_properties.Contains(PropertyId::Opacity)) + { geometry_dirty = true; } } @@ -120,15 +116,15 @@ void ElementSVG::GenerateGeometry() { geometry.Release(true); - Vector< Vertex >& vertices = geometry.GetVertices(); - Vector< int >& indices = geometry.GetIndices(); + Vector& vertices = geometry.GetVertices(); + Vector& indices = geometry.GetIndices(); vertices.resize(4); indices.resize(6); Vector2f texcoords[2] = { {0.0f, 0.0f}, - {1.0f, 1.0f} + {1.0f, 1.0f}, }; const ComputedValues& computed = GetComputedValues(); diff --git a/Source/SVG/SVGPlugin.cpp b/Source/SVG/SVGPlugin.cpp index 77a8e36d1..cb5a00144 100644 --- a/Source/SVG/SVGPlugin.cpp +++ b/Source/SVG/SVGPlugin.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,48 +26,39 @@ * */ - -#include "../../Include/RmlUi/SVG/ElementSVG.h" #include "../../Include/RmlUi/Core/Core.h" #include "../../Include/RmlUi/Core/ElementInstancer.h" #include "../../Include/RmlUi/Core/Factory.h" #include "../../Include/RmlUi/Core/Log.h" #include "../../Include/RmlUi/Core/Plugin.h" +#include "../../Include/RmlUi/SVG/ElementSVG.h" namespace Rml { namespace SVG { + class SVGPlugin : public Plugin { + public: + void OnInitialise() override + { + instancer = MakeUnique>(); -class SVGPlugin : public Plugin { -public: - void OnInitialise() override - { - instancer = MakeUnique >(); - - Factory::RegisterElementInstancer("svg", instancer.get()); - - Log::Message(Log::LT_INFO, "SVG plugin initialised."); - } + Factory::RegisterElementInstancer("svg", instancer.get()); - void OnShutdown() override - { - delete this; - } + Log::Message(Log::LT_INFO, "SVG plugin initialised."); + } - int GetEventClasses() override - { - return Plugin::EVT_BASIC; - } + void OnShutdown() override { delete this; } -private: - UniquePtr> instancer; -}; + int GetEventClasses() override { return Plugin::EVT_BASIC; } + private: + UniquePtr> instancer; + }; -void Initialise() -{ - RegisterPlugin(new SVGPlugin); -} + void Initialise() + { + RegisterPlugin(new SVGPlugin); + } } // namespace SVG } // namespace Rml diff --git a/Source/SVG/SVGPlugin.h b/Source/SVG/SVGPlugin.h index 31363e3a5..7f71777e2 100644 --- a/Source/SVG/SVGPlugin.h +++ b/Source/SVG/SVGPlugin.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,13 +29,12 @@ #ifndef RMLUI_SVG_SVG_PLUGIN_H #define RMLUI_SVG_SVG_PLUGIN_H - namespace Rml { namespace SVG { -void Initialise(); + void Initialise(); } -} +} // namespace Rml #endif diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 7643536d0..bc17d4aaa 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -104,7 +104,7 @@ endif() if(EMSCRIPTEN) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sLLD_REPORT_UNDEFINED --preload-file ${CMAKE_CURRENT_SOURCE_DIR}/Data/@/Tests/Data/") - + # Benchmarks additionally use the benchmark sample data. target_link_libraries(Benchmarks "--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../Samples/basic/benchmark/data/@/Samples/basic/benchmark/data/") endif() diff --git a/Tests/Data/UnitTests/Specificity_Basic.rcss b/Tests/Data/UnitTests/Specificity_Basic.rcss index 44b636bda..a9ce2b500 100644 --- a/Tests/Data/UnitTests/Specificity_Basic.rcss +++ b/Tests/Data/UnitTests/Specificity_Basic.rcss @@ -1,16 +1,16 @@ body { - display: block; - width: 10px; - height: 100px; + display: block; + width: 10px; + height: 100px; background: #ccc; } .a { - width: 80px; + width: 80px; } .b { - width: 90px; + width: 90px; } .c { - width: 100px; + width: 100px; } diff --git a/Tests/Data/UnitTests/Specificity_MediaQuery.rcss b/Tests/Data/UnitTests/Specificity_MediaQuery.rcss index 1c540be23..1396f231c 100644 --- a/Tests/Data/UnitTests/Specificity_MediaQuery.rcss +++ b/Tests/Data/UnitTests/Specificity_MediaQuery.rcss @@ -1,6 +1,6 @@ body { - display:block; - width: 100px; - height: 100px; + display:block; + width: 100px; + height: 100px; background: #ccc; } diff --git a/Tests/Data/VisualTests/LICENSE.txt b/Tests/Data/VisualTests/LICENSE.txt index 2d181f7cf..851310aae 100644 --- a/Tests/Data/VisualTests/LICENSE.txt +++ b/Tests/Data/VisualTests/LICENSE.txt @@ -39,4 +39,4 @@ COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQ OF THE SOFTWARE OR DOCUMENT. The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without -specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders. \ No newline at end of file +specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders. diff --git a/Tests/Data/VisualTests/acid1.rml b/Tests/Data/VisualTests/acid1.rml index 024a0826d..1703990f8 100644 --- a/Tests/Data/VisualTests/acid1.rml +++ b/Tests/Data/VisualTests/acid1.rml @@ -127,49 +127,49 @@ h1 {
- toggle + toggle
  • - the way + the way
  • - the world ends + the world ends

    - bang + bang

    - whimper + whimper

  • - i grow old + i grow old
  • - pluot? + pluot?
- bar maids, + bar maids,

- sing to me, erbarme dich + sing to me, erbarme dich

- This is a nonsensical document, but syntactically valid HTML 4.0. All 100%-conformant CSS1 agents should be able to render the document elements above this paragraph indistinguishably (to the pixel) from this + This is a nonsensical document, but syntactically valid HTML 4.0. All 100%-conformant CSS1 agents should be able to render the document elements above this paragraph indistinguishably (to the pixel) from this reference rendering, - (except font rasterization and form widgets). All discrepancies should be traceable to CSS1 implementation shortcomings. Once you have finished evaluating this test, you can return to the parent page. + (except font rasterization and form widgets). All discrepancies should be traceable to CSS1 implementation shortcomings. Once you have finished evaluating this test, you can return to the parent page.

diff --git a/Tests/Data/VisualTests/border_radius.rml b/Tests/Data/VisualTests/border_radius.rml index cec21f423..e1cd0408c 100644 --- a/Tests/Data/VisualTests/border_radius.rml +++ b/Tests/Data/VisualTests/border_radius.rml @@ -1,7 +1,7 @@ - Border-radius - + Border-radius + @@ -79,7 +79,7 @@

diff --git a/Tests/Data/VisualTests/flex_04.rml b/Tests/Data/VisualTests/flex_04.rml index c88b70e49..bdae30bea 100644 --- a/Tests/Data/VisualTests/flex_04.rml +++ b/Tests/Data/VisualTests/flex_04.rml @@ -1,7 +1,7 @@ - Flex 04 - Flex shorthand - + Flex 04 - Flex shorthand + diff --git a/Tests/Data/VisualTests/flex_05.rml b/Tests/Data/VisualTests/flex_05.rml index ac2f68e52..efdba20d6 100644 --- a/Tests/Data/VisualTests/flex_05.rml +++ b/Tests/Data/VisualTests/flex_05.rml @@ -1,8 +1,8 @@ - Flex 05 - Height constraints - - + Flex 05 - Height constraints + + + + CSS Test: flex flow direction + + + + + + -

flex-direction:row

-
-
1
-
2
-
3
-
+

flex-direction:row

+
+
1
+
2
+
3
+
+ +

flex-direction:row-reverse

+
+
1
+
2
+
3
+
-

flex-direction:row-reverse

-
-
1
-
2
-
3
-
+

flex-direction:column

+
+
1
+
2
+
3
+
-

flex-direction:column

-
-
1
-
2
-
3
-
+

flex-direction:column-reverse

+
+
1
+
2
+
3
+
-

flex-direction:column-reverse

-
-
1
-
2
-
3
-
- - +
diff --git a/Tests/Data/VisualTests/flex_nested.rml b/Tests/Data/VisualTests/flex_nested.rml index ae5bf6065..46b19a090 100644 --- a/Tests/Data/VisualTests/flex_nested.rml +++ b/Tests/Data/VisualTests/flex_nested.rml @@ -2,12 +2,12 @@ Flex - Nested flex boxes - + + + CSS Test: flex container multiline wrapping in column-reverse direction + + + + + + + + -
-

1-3

-

1-2

-

1-1

-

2-2

-

2-1

-

3-1

-
+
+

1-3

+

1-2

+

1-1

+

2-2

+

2-1

+

3-1

+
diff --git a/Tests/Data/VisualTests/float_basic.rml b/Tests/Data/VisualTests/float_basic.rml index a4aae5951..fb2f3c410 100644 --- a/Tests/Data/VisualTests/float_basic.rml +++ b/Tests/Data/VisualTests/float_basic.rml @@ -1,7 +1,7 @@ - Floats, block formatting contexts - + Floats, block formatting contexts + diff --git a/Tests/Data/VisualTests/inline_block.rml b/Tests/Data/VisualTests/inline_block.rml index 651ec1d52..d2bae83c2 100644 --- a/Tests/Data/VisualTests/inline_block.rml +++ b/Tests/Data/VisualTests/inline_block.rml @@ -1,7 +1,7 @@ - Inline-block - + Inline-block + @@ -38,7 +38,7 @@
Left filler text.
An inline-block.
Float right
Float left
Filler text.
Right filler text.

-
Nesting inline-blocks: +
Nesting inline-blocks:
A
B
C
D
E
F
diff --git a/Tests/Data/VisualTests/inline_formatting_01.rml b/Tests/Data/VisualTests/inline_formatting_01.rml index fd4bd1a33..38fa65dd4 100644 --- a/Tests/Data/VisualTests/inline_formatting_01.rml +++ b/Tests/Data/VisualTests/inline_formatting_01.rml @@ -1,7 +1,7 @@ - Inline formatting 01 - + Inline formatting 01 + + .flex-container.flex-direction-column-reverse .flex-item.first{ + margin-top:0px; + } + .flex-container.flex-direction-column-reverse .flex-item.last{ + margin-bottom:0px; + } + -

flex-direction:row

-
1
2
3
+

flex-direction:row

+
1
2
3
-

flex-direction:row-reverse

-
3
2
1
+

flex-direction:row-reverse

+
3
2
1
-

flex-direction:column

-
1
2
3
+

flex-direction:column

+
1
2
3
-

flex-direction:column-reverse

-
3
2
1
+

flex-direction:column-reverse

+
3
2
1
- +
diff --git a/Tests/Data/VisualTests/reference/flex_nested-ref.rml b/Tests/Data/VisualTests/reference/flex_nested-ref.rml index 9a7162aa5..d4d8f3b8e 100644 --- a/Tests/Data/VisualTests/reference/flex_nested-ref.rml +++ b/Tests/Data/VisualTests/reference/flex_nested-ref.rml @@ -1,7 +1,7 @@ - Flex nested ref - + Flex nested ref + + .clear { + clear: both; + } + -
-

1-1

-

1-2

-

1-3

-
-
-

2-1

-

2-2

-
-
-

3-1

-
-
+
+

1-1

+

1-2

+

1-3

+
+
+

2-1

+

2-2

+
+
+

3-1

+
+
diff --git a/Tests/Data/VisualTests/reference/overflow_hidden-ref.rml b/Tests/Data/VisualTests/reference/overflow_hidden-ref.rml index 3abf4a58d..31eb0144d 100644 --- a/Tests/Data/VisualTests/reference/overflow_hidden-ref.rml +++ b/Tests/Data/VisualTests/reference/overflow_hidden-ref.rml @@ -1,7 +1,7 @@ - Overflow: hidden - + Overflow: hidden + diff --git a/Tests/Data/VisualTests/replaced_elements.rml b/Tests/Data/VisualTests/replaced_elements.rml index fbec66f6e..93852b211 100644 --- a/Tests/Data/VisualTests/replaced_elements.rml +++ b/Tests/Data/VisualTests/replaced_elements.rml @@ -1,11 +1,11 @@ - Replaced elements - + Replaced elements + diff --git a/Tests/Data/VisualTests/table_03.rml b/Tests/Data/VisualTests/table_03.rml index 81ed45926..e7d08b3cb 100644 --- a/Tests/Data/VisualTests/table_03.rml +++ b/Tests/Data/VisualTests/table_03.rml @@ -1,7 +1,7 @@ - Table 03 - + Table 03 + diff --git a/Tests/Data/description.rml b/Tests/Data/description.rml index 350f06712..9be837ee7 100644 --- a/Tests/Data/description.rml +++ b/Tests/Data/description.rml @@ -25,7 +25,7 @@ } h1 { color: white; font-size: 1.3em; } h3 { color: white; font-size: 1.15em; } - + p.links a { margin: 0 0.7em; } #header { color: #ddb; @@ -54,7 +54,7 @@ color: #ffc; } #content { - overflow: hidden auto; + overflow: hidden auto; } #goto { margin: 0 20dp 10dp 20dp; diff --git a/Tests/Source/Benchmarks/BackgroundBorder.cpp b/Tests/Source/Benchmarks/BackgroundBorder.cpp index 0a9106068..1eef15a8d 100644 --- a/Tests/Source/Benchmarks/BackgroundBorder.cpp +++ b/Tests/Source/Benchmarks/BackgroundBorder.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -31,7 +31,6 @@ #include #include #include - #include #include @@ -78,7 +77,6 @@ static String document_rml = R"( )"; - TEST_CASE("backgrounds_and_borders") { Context* context = TestsShell::GetContext(); diff --git a/Tests/Source/Benchmarks/DataBinding.cpp b/Tests/Source/Benchmarks/DataBinding.cpp index dcfbbcf3a..ad435e44c 100644 --- a/Tests/Source/Benchmarks/DataBinding.cpp +++ b/Tests/Source/Benchmarks/DataBinding.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/Benchmarks/DataExpression.cpp b/Tests/Source/Benchmarks/DataExpression.cpp index f893ddb27..f61d1f229 100644 --- a/Tests/Source/Benchmarks/DataExpression.cpp +++ b/Tests/Source/Benchmarks/DataExpression.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,9 +26,7 @@ * */ - #include "../../../Source/Core/DataExpression.cpp" - #include #include #include @@ -40,7 +38,6 @@ static DataTypeRegister type_register; static DataModel model(&type_register); static DataExpressionInterface interface(&model, nullptr); - TEST_CASE("data_expressions") { float radius = 6.0f; @@ -50,9 +47,7 @@ TEST_CASE("data_expressions") DataModelConstructor constructor(&model); constructor.Bind("radius", &radius); constructor.Bind("color_name", &color_name); - constructor.BindFunc("color_value", [&](Variant& variant) { - variant = ToString(color_value); - }); + constructor.BindFunc("color_value", [&](Variant& variant) { variant = ToString(color_value); }); nanobench::Bench bench; bench.title("Data expression"); @@ -62,9 +57,7 @@ TEST_CASE("data_expressions") DataParser parser(expression, interface); bool result = true; - bench.run(parse_name, [&] { - result &= parser.Parse(false); - }); + bench.run(parse_name, [&] { result &= parser.Parse(false); }); REQUIRE(result); @@ -72,32 +65,20 @@ TEST_CASE("data_expressions") AddressList addresses = parser.ReleaseAddresses(); DataInterpreter interpreter(program, addresses, interface); - bench.run(execute_name, [&] { - result &= interpreter.Run(); - }); + bench.run(execute_name, [&] { result &= interpreter.Run(); }); REQUIRE(result); }; - bench_expression( - "2 * 2", - "Simple (parse)", - "Simple (execute)" - ); + bench_expression("2 * 2", "Simple (parse)", "Simple (execute)"); - bench_expression( - "true || false ? true && radius==1+2 ? 'Absolutely!' : color_value : 'no'", - "Complex (parse)", - "Complex (execute)" - ); + bench_expression("true || false ? true && radius==1+2 ? 'Absolutely!' : color_value : 'no'", "Complex (parse)", "Complex (execute)"); auto bench_assignment = [&](const String& expression, const char* parse_name, const char* execute_name) { - DataParser parser(expression, interface); - + DataParser parser(expression, interface); + bool result = true; - bench.run(parse_name, [&] { - result &= parser.Parse(true); - }); + bench.run(parse_name, [&] { result &= parser.Parse(true); }); REQUIRE(result); @@ -105,22 +86,12 @@ TEST_CASE("data_expressions") AddressList addresses = parser.ReleaseAddresses(); DataInterpreter interpreter(program, addresses, interface); - bench.run(execute_name, [&] { - result &= interpreter.Run(); - }); + bench.run(execute_name, [&] { result &= interpreter.Run(); }); REQUIRE(result); }; - bench_assignment( - "radius = 15", - "Simple assign (parse)", - "Simple assign (execute)" - ); - - bench_assignment( - "radius = radius*radius*3.14; color_name = 'image-color'", - "Complex assign (parse)", - "Complex assign (execute)" - ); + bench_assignment("radius = 15", "Simple assign (parse)", "Simple assign (execute)"); + + bench_assignment("radius = radius*radius*3.14; color_name = 'image-color'", "Complex assign (parse)", "Complex assign (execute)"); } diff --git a/Tests/Source/Benchmarks/Element.cpp b/Tests/Source/Benchmarks/Element.cpp index b2c925b26..ae8e29d9b 100644 --- a/Tests/Source/Benchmarks/Element.cpp +++ b/Tests/Source/Benchmarks/Element.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -112,10 +112,10 @@ static const char* LongTextRow = R"( static String GenerateRml(const int num_rows, const char* row) { static nanobench::Rng rng; - + Rml::String rml; rml.reserve(10000 * num_rows); - + for (int i = 0; i < num_rows; i++) { int index = rng() % 1000; @@ -125,7 +125,7 @@ static String GenerateRml(const int num_rows, const char* row) Rml::String rml_row = Rml::CreateString(10000, row, index, route, max, value); rml += rml_row; } - + return rml; } @@ -196,35 +196,35 @@ TEST_CASE("element.long_texts") { Context* context = TestsShell::GetContext(); REQUIRE(context); - + ElementDocument* document = context->LoadDocumentFromMemory(document_rml); REQUIRE(document); document->Show(); - + Element* el = document->GetElementById("performance"); REQUIRE(el); constexpr int num_rows = 50; const String rml = GenerateRml(num_rows, LongTextRow); - + el->SetInnerRML(rml); context->Update(); context->Render(); TestsShell::RenderLoop(); - + String msg = Rml::CreateString(128, "\nElement construction and destruction of %d total very long elements.\n", GetNumDescendentElements(el)); msg += TestsShell::GetRenderStats(); MESSAGE(msg); - + nanobench::Bench bench; bench.title("Element"); bench.timeUnit(std::chrono::microseconds(1), "us"); bench.relative(true); - + bench.run("Update (unmodified)", [&] { context->Update(); }); - + bool hover_toggle = true; auto child = el->GetChild(num_rows / 2); - + bench.run("Update (hover child)", [&] { static nanobench::Rng rng; child->SetPseudoClass(":hover", hover_toggle); @@ -236,22 +236,22 @@ TEST_CASE("element.long_texts") hover_toggle = !hover_toggle; context->Update(); }); - + bench.run("Render", [&] { context->Render(); }); - + bench.run("SetInnerRML", [&] { el->SetInnerRML(rml); }); - + bench.run("SetInnerRML + Update", [&] { el->SetInnerRML(rml); context->Update(); }); - + bench.run("SetInnerRML + Update + Render", [&] { el->SetInnerRML(rml); context->Update(); context->Render(); }); - + document->Close(); } diff --git a/Tests/Source/Benchmarks/ElementDocument.cpp b/Tests/Source/Benchmarks/ElementDocument.cpp index e5379036c..1c748facd 100644 --- a/Tests/Source/Benchmarks/ElementDocument.cpp +++ b/Tests/Source/Benchmarks/ElementDocument.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,14 +26,13 @@ * */ -#include "../Common/TestsShell.h" #include "../Common/TestsInterface.h" +#include "../Common/TestsShell.h" #include #include #include #include #include - #include #include @@ -82,8 +81,6 @@ static const String document_rml = R"( )"; - - TEST_CASE("elementdocument") { Context* context = TestsShell::GetContext(); @@ -140,7 +137,6 @@ TEST_CASE("elementdocument") }); } - { nanobench::Bench bench; bench.title("ElementDocument w/ClearStyleSheetCache"); diff --git a/Tests/Source/Benchmarks/Flexbox.cpp b/Tests/Source/Benchmarks/Flexbox.cpp index ee84cdf72..efd607e10 100644 --- a/Tests/Source/Benchmarks/Flexbox.cpp +++ b/Tests/Source/Benchmarks/Flexbox.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/Benchmarks/FontEffect.cpp b/Tests/Source/Benchmarks/FontEffect.cpp index 7db01dcdb..2ef7c2d82 100644 --- a/Tests/Source/Benchmarks/FontEffect.cpp +++ b/Tests/Source/Benchmarks/FontEffect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/Benchmarks/Selectors.cpp b/Tests/Source/Benchmarks/Selectors.cpp index 200cd2f04..2648c4bdd 100644 --- a/Tests/Source/Benchmarks/Selectors.cpp +++ b/Tests/Source/Benchmarks/Selectors.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -153,7 +153,6 @@ static String GenerateRCSS(SelectorFlags selectors, const String& complex_select // Set a property that does not require a layout change result += CreateString(64, " { scrollbar-margin: %dpx; }\n", int(c - 'a') + 1); - #if 1 // This conditions ensures that only a single version of the complex selector is included. This can be disabled to test how well the rules // are de-duplicated, since then a lot more selectors will be tested per update call. Rules that contain sub-selectors are currently not diff --git a/Tests/Source/Benchmarks/Table.cpp b/Tests/Source/Benchmarks/Table.cpp index 5d6433aa7..0f2842077 100644 --- a/Tests/Source/Benchmarks/Table.cpp +++ b/Tests/Source/Benchmarks/Table.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -31,7 +31,6 @@ #include #include #include - #include #include @@ -132,7 +131,6 @@ static const String rml_table_element = R"( )"; - static const String rml_inlineblock_document = R"( @@ -236,7 +234,6 @@ static const String rml_inline_block_element = R"( )"; - TEST_CASE("table_basic") { Context* context = TestsShell::GetContext(); @@ -258,17 +255,11 @@ TEST_CASE("table_basic") const String msg = TestsShell::GetRenderStats(); MESSAGE(msg); - bench.run("Update (unmodified)", [&] { - context->Update(); - }); + bench.run("Update (unmodified)", [&] { context->Update(); }); - bench.run("Render", [&] { - context->Render(); - }); + bench.run("Render", [&] { context->Render(); }); - bench.run("SetInnerRML", [&] { - document->SetInnerRML(rml_table_element); - }); + bench.run("SetInnerRML", [&] { document->SetInnerRML(rml_table_element); }); bench.run("SetInnerRML + Update", [&] { document->SetInnerRML(rml_table_element); @@ -284,7 +275,6 @@ TEST_CASE("table_basic") document->Close(); } - TEST_CASE("table_inline-block") { Context* context = TestsShell::GetContext(); @@ -306,17 +296,11 @@ TEST_CASE("table_inline-block") const String msg = TestsShell::GetRenderStats(); MESSAGE(msg); - bench.run("Update (unmodified)", [&] { - context->Update(); - }); + bench.run("Update (unmodified)", [&] { context->Update(); }); - bench.run("Render", [&] { - context->Render(); - }); + bench.run("Render", [&] { context->Render(); }); - bench.run("SetInnerRML", [&] { - document->SetInnerRML(rml_inline_block_element); - }); + bench.run("SetInnerRML", [&] { document->SetInnerRML(rml_inline_block_element); }); bench.run("SetInnerRML + Update", [&] { document->SetInnerRML(rml_inline_block_element); diff --git a/Tests/Source/Benchmarks/main.cpp b/Tests/Source/Benchmarks/main.cpp index 68f5f6d23..f1acd8d50 100644 --- a/Tests/Source/Benchmarks/main.cpp +++ b/Tests/Source/Benchmarks/main.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -34,22 +34,21 @@ #define DOCTEST_CONFIG_IMPLEMENT #include +int main(int argc, char** argv) +{ + // Initialize and run doctest + doctest::Context doctest_context; -int main(int argc, char** argv) { + doctest_context.applyCommandLine(argc, argv); - // Initialize and run doctest - doctest::Context doctest_context; + int doctest_result = doctest_context.run(); - doctest_context.applyCommandLine(argc, argv); + if (doctest_context.shouldExit()) + return doctest_result; - int doctest_result = doctest_context.run(); + // RmlUi is initialized during doctest run above as necessary. + // Clean everything up here. + TestsShell::ShutdownShell(); - if (doctest_context.shouldExit()) - return doctest_result; - - // RmlUi is initialized during doctest run above as necessary. - // Clean everything up here. - TestsShell::ShutdownShell(); - - return doctest_result; + return doctest_result; } diff --git a/Tests/Source/Common/Mocks.h b/Tests/Source/Common/Mocks.h index 61ad92eec..5459cf651 100644 --- a/Tests/Source/Common/Mocks.h +++ b/Tests/Source/Common/Mocks.h @@ -2,20 +2,17 @@ #include #include - #include #include -class MockEventListener : public trompeloeil::mock_interface -{ +class MockEventListener : public trompeloeil::mock_interface { public: IMPLEMENT_MOCK1(OnAttach); IMPLEMENT_MOCK1(OnDetach); IMPLEMENT_MOCK1(ProcessEvent); }; -class MockEventListenerInstancer : public trompeloeil::mock_interface -{ +class MockEventListenerInstancer : public trompeloeil::mock_interface { public: IMPLEMENT_MOCK2(InstanceEventListener); }; diff --git a/Tests/Source/Common/TestsInterface.cpp b/Tests/Source/Common/TestsInterface.cpp index 7668c16eb..189945d26 100644 --- a/Tests/Source/Common/TestsInterface.cpp +++ b/Tests/Source/Common/TestsInterface.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -38,7 +38,7 @@ double TestsSystemInterface::GetElapsedTime() bool TestsSystemInterface::LogMessage(Rml::Log::Type type, const Rml::String& message) { - static const char* message_type_str[Rml::Log::Type::LT_MAX] = { "Always", "Error", "Assert", "Warning", "Info", "Debug" }; + static const char* message_type_str[Rml::Log::Type::LT_MAX] = {"Always", "Error", "Assert", "Warning", "Info", "Debug"}; const bool result = Rml::SystemInterface::LogMessage(type, message); if (type <= Rml::Log::Type::LT_WARNING) @@ -83,7 +83,8 @@ void TestsSystemInterface::SetTime(double t) elapsed_time = t; } -void TestsRenderInterface::RenderGeometry(Rml::Vertex* /*vertices*/, int /*num_vertices*/, int* /*indices*/, int /*num_indices*/, const Rml::TextureHandle /*texture*/, const Rml::Vector2f& /*translation*/) +void TestsRenderInterface::RenderGeometry(Rml::Vertex* /*vertices*/, int /*num_vertices*/, int* /*indices*/, int /*num_indices*/, + const Rml::TextureHandle /*texture*/, const Rml::Vector2f& /*translation*/) { counters.render_calls += 1; } @@ -107,7 +108,8 @@ bool TestsRenderInterface::LoadTexture(Rml::TextureHandle& texture_handle, Rml:: return true; } -bool TestsRenderInterface::GenerateTexture(Rml::TextureHandle& texture_handle, const Rml::byte* /*source*/, const Rml::Vector2i& /*source_dimensions*/) +bool TestsRenderInterface::GenerateTexture(Rml::TextureHandle& texture_handle, const Rml::byte* /*source*/, + const Rml::Vector2i& /*source_dimensions*/) { counters.generate_texture += 1; texture_handle = 1; diff --git a/Tests/Source/Common/TestsInterface.h b/Tests/Source/Common/TestsInterface.h index 6ad8c4609..828bf434f 100644 --- a/Tests/Source/Common/TestsInterface.h +++ b/Tests/Source/Common/TestsInterface.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -15,7 +15,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Tests/Source/Common/TestsShell.cpp b/Tests/Source/Common/TestsShell.cpp index 8fa7f81bd..49b4b49a1 100644 --- a/Tests/Source/Common/TestsShell.cpp +++ b/Tests/Source/Common/TestsShell.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -38,81 +38,80 @@ #include // Uncomment the following to render to the shell window instead of the dummy renderer. Useful for viewing the result while building RML. -//#define RMLUI_TESTS_USE_SHELL +// #define RMLUI_TESTS_USE_SHELL namespace { - const Rml::Vector2i window_size(1500, 800); +const Rml::Vector2i window_size(1500, 800); - bool shell_initialized = false; - bool debugger_allowed = true; - int num_documents_begin = 0; - Rml::Context* shell_context = nullptr; +bool shell_initialized = false; +bool debugger_allowed = true; +int num_documents_begin = 0; +Rml::Context* shell_context = nullptr; - TestsSystemInterface tests_system_interface; +TestsSystemInterface tests_system_interface; #ifdef RMLUI_TESTS_USE_SHELL - class TestsShellEventListener : public Rml::EventListener { - public: - void ProcessEvent(Rml::Event& event) override +class TestsShellEventListener : public Rml::EventListener { +public: + void ProcessEvent(Rml::Event& event) override + { + if (event.GetId() == Rml::EventId::Keydown) { - if (event.GetId() == Rml::EventId::Keydown) - { - Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter< int >("key_identifier", 0); - - // Will escape the current render loop - if (key_identifier == Rml::Input::KI_ESCAPE || key_identifier == Rml::Input::KI_RETURN || key_identifier == Rml::Input::KI_NUMPADENTER) - Backend::RequestExit(); - } + Rml::Input::KeyIdentifier key_identifier = (Rml::Input::KeyIdentifier)event.GetParameter("key_identifier", 0); + + // Will escape the current render loop + if (key_identifier == Rml::Input::KI_ESCAPE || key_identifier == Rml::Input::KI_RETURN || key_identifier == Rml::Input::KI_NUMPADENTER) + Backend::RequestExit(); } - } shell_event_listener; + } +} shell_event_listener; #else - // The tests renderer only collects statistics, does not render anything. - TestsRenderInterface shell_render_interface; +// The tests renderer only collects statistics, does not render anything. +TestsRenderInterface shell_render_interface; #endif } // namespace - static void InitializeShell(bool allow_debugger) +static void InitializeShell(bool allow_debugger) +{ + // Initialize shell and create context. + if (!shell_initialized) { - // Initialize shell and create context. - if (!shell_initialized) - { - shell_initialized = true; - debugger_allowed = allow_debugger; - REQUIRE(Shell::Initialize()); + shell_initialized = true; + debugger_allowed = allow_debugger; + REQUIRE(Shell::Initialize()); #ifdef RMLUI_TESTS_USE_SHELL - // Initialize the backend and launch a window. - REQUIRE(Backend::Initialize("RmlUi Tests", window_size.x, window_size.y, true)); + // Initialize the backend and launch a window. + REQUIRE(Backend::Initialize("RmlUi Tests", window_size.x, window_size.y, true)); - // Use our custom tests system interface. - Rml::SetSystemInterface(&tests_system_interface); - // However, use the backend's render interface. - Rml::SetRenderInterface(Backend::GetRenderInterface()); + // Use our custom tests system interface. + Rml::SetSystemInterface(&tests_system_interface); + // However, use the backend's render interface. + Rml::SetRenderInterface(Backend::GetRenderInterface()); - REQUIRE(Rml::Initialise()); - shell_context = Rml::CreateContext("main", window_size); - Shell::LoadFonts(); + REQUIRE(Rml::Initialise()); + shell_context = Rml::CreateContext("main", window_size); + Shell::LoadFonts(); - if (allow_debugger) - { - Rml::Debugger::Initialise(shell_context); - num_documents_begin = shell_context->GetNumDocuments(); - } + if (allow_debugger) + { + Rml::Debugger::Initialise(shell_context); + num_documents_begin = shell_context->GetNumDocuments(); + } - shell_context->GetRootElement()->AddEventListener(Rml::EventId::Keydown, &shell_event_listener, true); + shell_context->GetRootElement()->AddEventListener(Rml::EventId::Keydown, &shell_event_listener, true); #else - // Set our custom system and render interfaces. - Rml::SetSystemInterface(&tests_system_interface); - Rml::SetRenderInterface(&shell_render_interface); + // Set our custom system and render interfaces. + Rml::SetSystemInterface(&tests_system_interface); + Rml::SetRenderInterface(&shell_render_interface); - REQUIRE(Rml::Initialise()); - shell_context = Rml::CreateContext("main", window_size); - Shell::LoadFonts(); + REQUIRE(Rml::Initialise()); + shell_context = Rml::CreateContext("main", window_size); + Shell::LoadFonts(); #endif - } } - +} Rml::Context* TestsShell::GetContext(bool allow_debugger) { @@ -171,7 +170,7 @@ void TestsShell::ShutdownShell() #ifdef RMLUI_TESTS_USE_SHELL Backend::Shutdown(); #endif - + Shell::Shutdown(); shell_context = nullptr; @@ -204,14 +203,8 @@ Rml::String TestsShell::GetRenderStats() " Texture generate: %zu\n" " Texture release: %zu\n" " Transform set: %zu", - counters.render_calls, - counters.enable_scissor, - counters.set_scissor, - counters.load_texture, - counters.generate_texture, - counters.release_texture, - counters.set_transform - ); + counters.render_calls, counters.enable_scissor, counters.set_scissor, counters.load_texture, counters.generate_texture, + counters.release_texture, counters.set_transform); #endif @@ -230,4 +223,4 @@ TestsRenderInterface* TestsShell::GetTestsRenderInterface() TestsSystemInterface* TestsShell::GetTestsSystemInterface() { return &tests_system_interface; -} \ No newline at end of file +} diff --git a/Tests/Source/Common/TestsShell.h b/Tests/Source/Common/TestsShell.h index c610ff003..8017951c6 100644 --- a/Tests/Source/Common/TestsShell.h +++ b/Tests/Source/Common/TestsShell.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -30,37 +30,40 @@ #define RMLUI_TESTS_COMMON_TESTSSHELL_H #include -namespace Rml { class RenderInterface; } +namespace Rml { +class RenderInterface; +} class TestsRenderInterface; class TestsSystemInterface; namespace TestsShell { - // Will initialize the shell and create a context on first use. - Rml::Context* GetContext(bool allow_debugger = true); +// Will initialize the shell and create a context on first use. +Rml::Context* GetContext(bool allow_debugger = true); - void BeginFrame(); - void PresentFrame(); +void BeginFrame(); +void PresentFrame(); - // Render the current state of the context. Press 'escape' or 'return' to break out of the loop. - // Useful for viewing documents while building the RML to benchmark. - // Applies only when compiled with the shell backend. - void RenderLoop(); +// Render the current state of the context. Press 'escape' or 'return' to break out of the loop. +// Useful for viewing documents while building the RML to benchmark. +// Applies only when compiled with the shell backend. +void RenderLoop(); - void ShutdownShell(); +void ShutdownShell(); - // Set the number of expected warnings and errors logged by RmlUi until the next call to this function - // or until 'ShutdownShell()'. - void SetNumExpectedWarnings(int num_warnings); +// Set the number of expected warnings and errors logged by RmlUi until the next call to this function +// or until 'ShutdownShell()'. +void SetNumExpectedWarnings(int num_warnings); - void SetTime(double t); +void SetTime(double t); - // Stats only available for the dummy renderer. - Rml::String GetRenderStats(); +// Stats only available for the dummy renderer. +Rml::String GetRenderStats(); - // Returns nullptr if the dummy renderer is not being used. - TestsRenderInterface* GetTestsRenderInterface(); - TestsSystemInterface* GetTestsSystemInterface(); -} +// Returns nullptr if the dummy renderer is not being used. +TestsRenderInterface* GetTestsRenderInterface(); +TestsSystemInterface* GetTestsSystemInterface(); + +} // namespace TestsShell #endif diff --git a/Tests/Source/Common/TypesToString.h b/Tests/Source/Common/TypesToString.h index 543e9717d..c54fe8693 100644 --- a/Tests/Source/Common/TypesToString.h +++ b/Tests/Source/Common/TypesToString.h @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/UnitTests/Animation.cpp b/Tests/Source/UnitTests/Animation.cpp index 37b77f6ef..50dbf5b89 100644 --- a/Tests/Source/UnitTests/Animation.cpp +++ b/Tests/Source/UnitTests/Animation.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -83,35 +83,39 @@ TEST_CASE("animation.decorator") Vector tests{ // Only standard declaration { - "", "", - + "", + "", + "gradient(horizontal transparent transparent)", "gradient(horizontal white white)", - + "gradient(horizontal rgba(127,127,127,63) rgba(127,127,127,63))", }, { - "", "", - + "", + "", + "none", "gradient(horizontal transparent transparent)", - + "gradient(horizontal rgba(220,220,220,191) rgba(220,220,220,191))", }, { - "", "", - + "", + "", + "none", "gradient(horizontal transparent transparent), gradient(vertical transparent transparent)", - + "gradient(horizontal rgba(220,220,220,191) rgba(220,220,220,191)), gradient(horizontal rgba(220,220,220,191) rgba(220,220,220,191))", }, { - "", "", - + "", + "", + "gradient(horizontal transparent transparent), gradient(vertical transparent transparent)", "none", - + "gradient(horizontal rgba(127,127,127,63) rgba(127,127,127,63)), gradient(vertical rgba(127,127,127,63) rgba(127,127,127,63))", }, @@ -119,28 +123,28 @@ TEST_CASE("animation.decorator") { "direction: horizontal; start-color: transparent; stop-color: transparent;", "direction: horizontal; start-color: white; stop-color: white;", - + "from_rule", "to_rule", - + "gradient(horizontal rgba(127,127,127,63) rgba(127,127,127,63))", }, { "", "direction: horizontal; start-color: transparent; stop-color: transparent;", - + "from_rule", "to_rule", - + "gradient(horizontal rgba(220,220,220,191) rgba(220,220,220,191))", }, { "direction: vertical; start-color: transparent; stop-color: transparent;", "", - + "from_rule", "to_rule", - + "gradient(vertical rgba(127,127,127,63) rgba(127,127,127,63))", }, @@ -173,7 +177,8 @@ TEST_CASE("animation.decorator") "gradient(vertical rgba(127,127,127,63) rgba(127,127,127,63))", }, { - "", "", + "", + "", "from_rule, to_rule", "gradient(horizontal transparent transparent), gradient(vertical transparent transparent)", @@ -181,7 +186,8 @@ TEST_CASE("animation.decorator") "gradient(horizontal rgba(220,220,220,191) rgba(220,220,220,191)), gradient(horizontal rgba(220,220,220,191) rgba(220,220,220,191))", }, { - "", "", + "", + "", "gradient(horizontal transparent transparent), gradient(vertical transparent transparent)", "from_rule, to_rule", @@ -218,4 +224,4 @@ TEST_CASE("animation.decorator") system_interface->SetTime(0.0); TestsShell::ShutdownShell(); -} \ No newline at end of file +} diff --git a/Tests/Source/UnitTests/Core.cpp b/Tests/Source/UnitTests/Core.cpp index f9033c92f..e3787c0ad 100644 --- a/Tests/Source/UnitTests/Core.cpp +++ b/Tests/Source/UnitTests/Core.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/UnitTests/DataBinding.cpp b/Tests/Source/UnitTests/DataBinding.cpp index 08fdb1744..9e7ac0648 100644 --- a/Tests/Source/UnitTests/DataBinding.cpp +++ b/Tests/Source/UnitTests/DataBinding.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -38,7 +38,6 @@ using namespace Rml; namespace { - static const String document_rml = R"( @@ -180,14 +179,12 @@ static const String aliasing_rml = R"( )"; -struct StringWrap -{ +struct StringWrap { StringWrap(String val = "wrap_default") : val(val) {} String val; }; -struct Globals -{ +struct Globals { int i0 = 0; int* i1 = new int(1); UniquePtr i2 = MakeUnique(2); @@ -208,117 +205,110 @@ struct Globals UniquePtr x4 = MakeUnique("x3"); // Invalid: const pointer } globals; -struct Basic -{ +struct Basic { int a = 1; int* b = new int(2); - int GetC() { + int GetC() + { static int v = 5; return v; } - int& GetD() { + int& GetD() + { static int v = 5; return v; } - int* GetE() { + int* GetE() + { static int v = 6; return &v; } - UniquePtr GetF() { - return MakeUnique(7); - } + UniquePtr GetF() { return MakeUnique(7); } // Invalid: const member const int x0 = 2; // Invalid: const pointer const int* x1 = new int(3); // Invalid: const qualified member function - int GetX2() const { - return 4; - } + int GetX2() const { return 4; } // Invalid: const reference return - const int& GetX3() { + const int& GetX3() + { static int g = 7; return g; } // Invalid: const pointer return - const int* GetX4() { + const int* GetX4() + { static int h = 8; return &h; } // Invalid: Illegal signature - int GetX5(int) { - return 9; - } + int GetX5(int) { return 9; } }; -struct Wrapped -{ - StringWrap a = { "a" }; +struct Wrapped { + StringWrap a = {"a"}; StringWrap* b = new StringWrap("b"); UniquePtr c = MakeUnique("c"); - StringWrap& GetD() { - static StringWrap v = { "e" }; + StringWrap& GetD() + { + static StringWrap v = {"e"}; return v; } - StringWrap* GetE() { - static StringWrap v = { "f" }; + StringWrap* GetE() + { + static StringWrap v = {"f"}; return &v; } - + // Invalid: const pointer const StringWrap* x0 = new StringWrap("x0"); // Invalid (run-time): Returning non-scalar variable by value. - StringWrap GetX1() { - return { "x1" }; - } + StringWrap GetX1() { return {"x1"}; } // Invalid (run-time): Returning non-scalar variable by value. - UniquePtr GetX2() { - return MakeUnique("x2"); - } + UniquePtr GetX2() { return MakeUnique("x2"); } }; using StringWrapPtr = UniquePtr; -struct Pointed -{ +struct Pointed { StringWrapPtr a = MakeUnique("a"); - StringWrapPtr& GetB() { + StringWrapPtr& GetB() + { static StringWrapPtr v = MakeUnique("b"); return v; } - StringWrapPtr* GetC() { + StringWrapPtr* GetC() + { static StringWrapPtr v = MakeUnique("c"); return &v; } - + // Invalid: We disallow recursive pointer types (pointer to pointer) StringWrapPtr* x0 = new StringWrapPtr(new StringWrap("x0")); // Invalid (run-time error): Only scalar data members can be returned by value - StringWrapPtr GetX1() { - return MakeUnique("x1"); - } - + StringWrapPtr GetX1() { return MakeUnique("x1"); } }; -struct Arrays -{ - Vector a = { 10, 11, 12 }; - Vector b = { new int(20), new int(21), new int(22) }; - Vector c = { StringWrap("c1"), StringWrap("c2"), StringWrap("c3") }; - Vector d = { new StringWrap("d1"), new StringWrap("d2"), new StringWrap("d3") }; +struct Arrays { + Vector a = {10, 11, 12}; + Vector b = {new int(20), new int(21), new int(22)}; + Vector c = {StringWrap("c1"), StringWrap("c2"), StringWrap("c3")}; + Vector d = {new StringWrap("d1"), new StringWrap("d2"), new StringWrap("d3")}; Vector e; - + // Invalid: const pointer - Vector x0 = { new int(30), new int(31), new int(32) }; + Vector x0 = {new int(30), new int(31), new int(32)}; // Invalid: const pointer Vector> x1; - - Arrays() { + + Arrays() + { e.emplace_back(MakeUnique("e1")); e.emplace_back(MakeUnique("e2")); e.emplace_back(MakeUnique("e3")); @@ -330,8 +320,6 @@ struct Arrays DataModelHandle model_handle; - - bool InitializeDataBindings(Context* context) { Rml::DataModelConstructor constructor = context->CreateDataModel("basics"); @@ -358,11 +346,11 @@ bool InitializeDataBindings(Context* context) constructor.Bind("s5", &globals.s5); // Invalid: Each of the following should give a compile-time failure. - //constructor.Bind("x0", &globals.x0); - //constructor.Bind("x1", &globals.x1); - //constructor.Bind("x2", &globals.x2); - //constructor.Bind("x3", &globals.x3); - //constructor.Bind("x4", &globals.x4); + // constructor.Bind("x0", &globals.x0); + // constructor.Bind("x1", &globals.x1); + // constructor.Bind("x2", &globals.x2); + // constructor.Bind("x3", &globals.x3); + // constructor.Bind("x4", &globals.x4); } if (auto handle = constructor.RegisterStruct()) @@ -374,15 +362,15 @@ bool InitializeDataBindings(Context* context) handle.RegisterMember("e", &Basic::GetE); handle.RegisterMember("f", &Basic::GetF); - //handle.RegisterMember("x0", &Basic::x0); - //handle.RegisterMember("x1", &Basic::x1); - //handle.RegisterMember("x2", &Basic::GetX2); - //handle.RegisterMember("x3", &Basic::GetX3); - //handle.RegisterMember("x4", &Basic::GetX4); - //handle.RegisterMember("x5", &Basic::GetX5); + // handle.RegisterMember("x0", &Basic::x0); + // handle.RegisterMember("x1", &Basic::x1); + // handle.RegisterMember("x2", &Basic::GetX2); + // handle.RegisterMember("x3", &Basic::GetX3); + // handle.RegisterMember("x4", &Basic::GetX4); + // handle.RegisterMember("x5", &Basic::GetX5); } constructor.Bind("basic", new Basic); - + if (auto handle = constructor.RegisterStruct()) { handle.RegisterMember("a", &Wrapped::a); @@ -391,20 +379,20 @@ bool InitializeDataBindings(Context* context) handle.RegisterMember("d", &Wrapped::GetD); handle.RegisterMember("e", &Wrapped::GetE); - //handle.RegisterMember("x0", &Wrapped::x0); - //handle.RegisterMember("x1", &Wrapped::GetX1); - //handle.RegisterMember("x2", &Wrapped::GetX2); + // handle.RegisterMember("x0", &Wrapped::x0); + // handle.RegisterMember("x1", &Wrapped::GetX1); + // handle.RegisterMember("x2", &Wrapped::GetX2); } constructor.Bind("wrapped", new Wrapped); - + if (auto handle = constructor.RegisterStruct()) { handle.RegisterMember("a", &Pointed::a); handle.RegisterMember("b", &Pointed::GetB); handle.RegisterMember("c", &Pointed::GetC); - //handle.RegisterMember("x0", &Pointed::x0); - //handle.RegisterMember("x1", &Pointed::GetX1); + // handle.RegisterMember("x0", &Pointed::x0); + // handle.RegisterMember("x1", &Pointed::GetX1); } constructor.Bind("pointed", new Pointed); @@ -414,8 +402,8 @@ bool InitializeDataBindings(Context* context) constructor.RegisterArray(); constructor.RegisterArray(); - //constructor.RegisterArray(); - //constructor.RegisterArray(); + // constructor.RegisterArray(); + // constructor.RegisterArray(); if (auto handle = constructor.RegisterStruct()) { @@ -425,11 +413,11 @@ bool InitializeDataBindings(Context* context) handle.RegisterMember("d", &Arrays::d); handle.RegisterMember("e", &Arrays::e); - //handle.RegisterMember("x0", &Arrays::x0); - //handle.RegisterMember("x1", &Arrays::x1); + // handle.RegisterMember("x0", &Arrays::x0); + // handle.RegisterMember("x1", &Arrays::x1); } constructor.Bind("arrays", new Arrays); - + model_handle = constructor.GetModelHandle(); return true; @@ -437,7 +425,6 @@ bool InitializeDataBindings(Context* context) } // Anonymous namespace - TEST_CASE("databinding") { Context* context = TestsShell::GetContext(); @@ -498,4 +485,4 @@ TEST_CASE("databinding.aliasing") document->Close(); TestsShell::ShutdownShell(); -} \ No newline at end of file +} diff --git a/Tests/Source/UnitTests/DataExpression.cpp b/Tests/Source/UnitTests/DataExpression.cpp index 855b63321..3d381fa8b 100644 --- a/Tests/Source/UnitTests/DataExpression.cpp +++ b/Tests/Source/UnitTests/DataExpression.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/UnitTests/DataModel.cpp b/Tests/Source/UnitTests/DataModel.cpp index 01c98f520..4236d1f4b 100644 --- a/Tests/Source/UnitTests/DataModel.cpp +++ b/Tests/Source/UnitTests/DataModel.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,8 +27,8 @@ */ #include "../../../Source/Core/DataModel.cpp" -#include #include +#include #include using namespace Rml; @@ -40,7 +40,7 @@ TEST_CASE("Data variables") struct FunData { int i = 99; String x = "hello"; - IntVector magic = { 3, 5, 7, 11, 13 }; + IntVector magic = {3, 5, 7, 11, 13}; }; using FunArray = Array; @@ -84,8 +84,9 @@ TEST_CASE("Data variables") // Test data addresses, setters, and assignments { - Vector test_addresses = { "data.more_fun[1].magic[3]", "data.more_fun[1].magic.size", "data.fun.x", "data.valid" }; - Vector expected_results = { ToString(data.more_fun[1].magic[3]), ToString(int(data.more_fun[1].magic.size())), ToString(data.fun.x), ToString(data.valid) }; + Vector test_addresses = {"data.more_fun[1].magic[3]", "data.more_fun[1].magic.size", "data.fun.x", "data.valid"}; + Vector expected_results = {ToString(data.more_fun[1].magic[3]), ToString(int(data.more_fun[1].magic.size())), ToString(data.fun.x), + ToString(data.valid)}; Vector results; @@ -103,7 +104,7 @@ TEST_CASE("Data variables") REQUIRE(model.GetVariable(ParseAddress("data.more_fun[1].magic[1]")).Set(Variant(String("199")))); CHECK(data.more_fun[1].magic[1] == 199); - data.fun.magic = { 99, 190, 55, 2000, 50, 60, 70, 80, 90 }; + data.fun.magic = {99, 190, 55, 2000, 50, 60, 70, 80, 90}; Variant get_result; diff --git a/Tests/Source/UnitTests/Debugger.cpp b/Tests/Source/UnitTests/Debugger.cpp index b25d94e34..690efa409 100644 --- a/Tests/Source/UnitTests/Debugger.cpp +++ b/Tests/Source/UnitTests/Debugger.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/Source/UnitTests/Element.cpp b/Tests/Source/UnitTests/Element.cpp index 509a17169..11967fb59 100644 --- a/Tests/Source/UnitTests/Element.cpp +++ b/Tests/Source/UnitTests/Element.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -180,20 +180,17 @@ TEST_CASE("Element") std::vector> expectations; UniquePtr mockEventListener; - const auto configureMockEventListener = [&]() - { + const auto configureMockEventListener = [&]() { mockEventListener.reset(new MockEventListener()); expectations.emplace_back(NAMED_ALLOW_CALL(*mockEventListener, OnAttach(button))); - expectations.emplace_back(NAMED_ALLOW_CALL(*mockEventListener, OnDetach(button)) - .LR_SIDE_EFFECT(mockEventListener.reset())); + expectations.emplace_back(NAMED_ALLOW_CALL(*mockEventListener, OnDetach(button)).LR_SIDE_EFFECT(mockEventListener.reset())); }; MockEventListenerInstancer mockEventListenerInstancer; - const auto configureMockEventListenerInstancer = [&](const auto value) - { + const auto configureMockEventListenerInstancer = [&](const auto value) { expectations.emplace_back(NAMED_REQUIRE_CALL(mockEventListenerInstancer, InstanceEventListener(value, button)) - .LR_SIDE_EFFECT(configureMockEventListener()) - .LR_RETURN(mockEventListener.get())); + .LR_SIDE_EFFECT(configureMockEventListener()) + .LR_RETURN(mockEventListener.get())); }; Factory::RegisterEventListenerInstancer(&mockEventListenerInstancer); diff --git a/Tests/Source/UnitTests/ElementDocument.cpp b/Tests/Source/UnitTests/ElementDocument.cpp index 9525abcbf..cadf25bf5 100644 --- a/Tests/Source/UnitTests/ElementDocument.cpp +++ b/Tests/Source/UnitTests/ElementDocument.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -32,8 +32,8 @@ #include #include #include -#include #include +#include using namespace Rml; @@ -120,7 +120,7 @@ TEST_CASE("Focus") document->Focus(); SUBCASE("Forward") { - for(const String& id : ids) + for (const String& id : ids) { context->ProcessKeyDown(Input::KI_TAB, 0); CHECK(context->GetFocusElement()->GetId() == id); diff --git a/Tests/Source/UnitTests/ElementFormControlSelect.cpp b/Tests/Source/UnitTests/ElementFormControlSelect.cpp index be9958e94..883ff9bc8 100644 --- a/Tests/Source/UnitTests/ElementFormControlSelect.cpp +++ b/Tests/Source/UnitTests/ElementFormControlSelect.cpp @@ -4,7 +4,7 @@ * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd - * Copyright (c) 2019 The RmlUi Team, and contributors + * Copyright (c) 2019-2023 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,9 +28,9 @@ #include "../Common/TestsShell.h" #include +#include #include #include -#include #include #include #include @@ -84,7 +84,6 @@ static String GetSelectValueRml(ElementFormControlSelect* select_element) return String(); } - TEST_CASE("form.select.value") { Context* context = TestsShell::GetContext(); @@ -105,8 +104,8 @@ TEST_CASE("form.select.value") - )", "", "A" - }, + )", + "", "A"}, { R"( @@ -116,8 +115,8 @@ TEST_CASE("form.select.value") - )", "a", "A" - }, + )", + "a", "A"}, { R"( @@ -127,8 +126,8 @@ TEST_CASE("form.select.value") - )", "", "A" - }, + )", + "", "A"}, { R"( @@ -138,8 +137,8 @@ TEST_CASE("form.select.value") - )", "c", "C" - }, + )", + "c", "C"}, { R"( @@ -149,8 +148,8 @@ TEST_CASE("form.select.value") - )", "d", "D" - }, + )", + "d", "D"}, { R"( @@ -160,8 +159,8 @@ TEST_CASE("form.select.value") - )", "a", "A" - }, + )", + "a", "A"}, { R"( @@ -171,8 +170,8 @@ TEST_CASE("form.select.value") - )", "d", "D" - }, + )", + "d", "D"}, { R"( @@ -182,8 +181,8 @@ TEST_CASE("form.select.value") - )", "c", "C" - }, + )", + "c", "C"}, }; ElementDocument* document = context->LoadDocumentFromMemory(basic_doc_rml); @@ -217,7 +216,6 @@ TEST_CASE("form.select.value") TestsShell::ShutdownShell(); } - TEST_CASE("form.select.databinding") { Context* context = TestsShell::GetContext(); @@ -231,7 +229,7 @@ TEST_CASE("form.select.databinding") int selected_index = 2; String selected_value = "b"; - Vector values = { "a", "b", "c", "d" }; + Vector values = {"a", "b", "c", "d"}; Test tests[] = { { @@ -242,8 +240,8 @@ TEST_CASE("form.select.databinding") - )", "2", "C" - }, + )", + "2", "C"}, { R"( @@ -253,8 +251,8 @@ TEST_CASE("form.select.databinding") - )", "b", "B" - }, + )", + "b", "B"}, { R"( @@ -264,40 +262,40 @@ TEST_CASE("form.select.databinding") - )", "b", "B" - }, + )", + "b", "B"}, { R"( - )", "b", "B" - }, + )", + "b", "B"}, { R"( - )", "2", "C" - }, + )", + "2", "C"}, { R"( - )", "b", "B" - }, + )", + "b", "B"}, { R"( - )", "2", "C" - }, + )", + "2", "C"}, }; DataModelConstructor constructor = context->CreateDataModel("select-test"); @@ -339,7 +337,6 @@ TEST_CASE("form.select.databinding") TestsShell::ShutdownShell(); } - TEST_CASE("form.select.data-for") { Context* context = TestsShell::GetContext(); @@ -352,7 +349,7 @@ TEST_CASE("form.select.data-for") }; String selected_value = "b"; - Vector values = { "a", "b", "c", "d" }; + Vector values = {"a", "b", "c", "d"}; DataModelConstructor constructor = context->CreateDataModel("select-test"); constructor.RegisterArray>(); @@ -363,7 +360,6 @@ TEST_CASE("form.select.data-for") DataModelHandle handle = constructor.GetModelHandle(); { - const String select_rml = R"(