diff options
author | rtk0c <[email protected]> | 2022-11-27 12:04:31 -0800 |
---|---|---|
committer | rtk0c <[email protected]> | 2022-11-27 12:04:31 -0800 |
commit | 182c8f8357739f905bbd721006480502435b6b43 (patch) | |
tree | 082613a474d863182e2ad8f2167f1643f26e67a3 /app | |
parent | b01ed99a1cd0c863c8709930658513c04dd70f61 (diff) |
Update brace style to match rest of my projectscplt-imgui
Diffstat (limited to 'app')
84 files changed, 857 insertions, 1718 deletions
diff --git a/app/source/Cplt/ImGuiBackend/Backend.hpp b/app/source/Cplt/ImGuiBackend/Backend.hpp index ca391e6..9ceccb1 100644 --- a/app/source/Cplt/ImGuiBackend/Backend.hpp +++ b/app/source/Cplt/ImGuiBackend/Backend.hpp @@ -2,8 +2,7 @@ #include <memory> -class RenderingBackend -{ +class RenderingBackend { public: // Implemented in Backend_OpenGL2.cpp static std::unique_ptr<RenderingBackend> CreateOpenGL2Backend(); diff --git a/app/source/Cplt/ImGuiBackend/Backend_DirectX11.cpp b/app/source/Cplt/ImGuiBackend/Backend_DirectX11.cpp index 4dc33f7..6dcf674 100644 --- a/app/source/Cplt/ImGuiBackend/Backend_DirectX11.cpp +++ b/app/source/Cplt/ImGuiBackend/Backend_DirectX11.cpp @@ -11,8 +11,7 @@ // Forward declare message handler from imgui_impl_win32.cpp extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -class DirectX11Backend : public RenderingBackend -{ +class DirectX11Backend : public RenderingBackend { private: HWND hWnd; WNDCLASSEX wc; @@ -23,8 +22,7 @@ private: ID3D11RenderTargetView* mMainRenderTargetView = nullptr; public: - DirectX11Backend() - { + DirectX11Backend() { ImGui_ImplWin32_EnableDpiAwareness(); wc.cbSize = sizeof(WNDCLASSEX); @@ -70,8 +68,7 @@ public: ImGui_ImplDX11_Init(mD3dDevice, mD3dDeviceContext); } - virtual ~DirectX11Backend() - { + virtual ~DirectX11Backend() { ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); @@ -81,8 +78,7 @@ public: ::UnregisterClass(wc.lpszClassName, wc.hInstance); } - virtual void RunUntilWindowClose(void (*windowContent)()) - { + virtual void RunUntilWindowClose(void (*windowContent)()) { while (true) { MSG msg; bool done = false; @@ -113,8 +109,7 @@ public: } private: - bool CreateDeviceD3D() - { + bool CreateDeviceD3D() { // Setup swap chain DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); @@ -133,7 +128,7 @@ private: sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; UINT createDeviceFlags = 0; - //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + // createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, @@ -147,8 +142,7 @@ private: return true; } - void CleanupDeviceD3D() - { + void CleanupDeviceD3D() { CleanupRenderTarget(); if (mSwapChain) { mSwapChain->Release(); @@ -164,24 +158,21 @@ private: } } - void CreateRenderTarget() - { + void CreateRenderTarget() { ID3D11Texture2D* pBackBuffer; mSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); mD3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &mMainRenderTargetView); pBackBuffer->Release(); } - void CleanupRenderTarget() - { + void CleanupRenderTarget() { if (mMainRenderTargetView) { mMainRenderTargetView->Release(); mMainRenderTargetView = nullptr; } } - static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) - { + static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { DirectX11Backend* self; if (uMsg == WM_NCCREATE) { auto lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam); @@ -199,8 +190,7 @@ private: } } - LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam) - { + LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) { return true; } @@ -231,8 +221,7 @@ private: } }; -std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx11Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx11Backend() { try { return std::make_unique<DirectX11Backend>(); } catch (std::exception& e) { @@ -242,8 +231,7 @@ std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx11Backend() #else // ^^ BUILD_CORE_WITH_DX11_BACKEND | BUILD_CORE_WITH_DX11_BACKEND vv -std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx11Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx11Backend() { return nullptr; } diff --git a/app/source/Cplt/ImGuiBackend/Backend_DirectX12.cpp b/app/source/Cplt/ImGuiBackend/Backend_DirectX12.cpp index fd4a531..c0492c2 100644 --- a/app/source/Cplt/ImGuiBackend/Backend_DirectX12.cpp +++ b/app/source/Cplt/ImGuiBackend/Backend_DirectX12.cpp @@ -15,11 +15,9 @@ constexpr int kNumBackBuffers = 3; // Forward declare message handler from imgui_impl_win32.cpp extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -class DirectX12Backend : public RenderingBackend -{ +class DirectX12Backend : public RenderingBackend { private: - struct FrameContext - { + struct FrameContext { ID3D12CommandAllocator* CommandAllocator; UINT64 FenceValue; }; @@ -44,8 +42,7 @@ private: D3D12_CPU_DESCRIPTOR_HANDLE mMainRenderTargetDescriptor[kNumBackBuffers] = {}; public: - DirectX12Backend() - { + DirectX12Backend() { ImGui_ImplWin32_EnableDpiAwareness(); wc.cbSize = sizeof(WNDCLASSEX); @@ -91,8 +88,7 @@ public: ImGui_ImplDX12_Init(mD3dDevice, kNumFramesInFlight, DXGI_FORMAT_R8G8B8A8_UNORM, mD3dSrvDescHeap, mD3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), mD3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart()); } - virtual ~DirectX12Backend() - { + virtual ~DirectX12Backend() { WaitForLastSubmittedFrame(); // Cleanup @@ -105,8 +101,7 @@ public: ::UnregisterClass(wc.lpszClassName, wc.hInstance); } - virtual void RunUntilWindowClose(void (*windowContent)()) - { + virtual void RunUntilWindowClose(void (*windowContent)()) { while (true) { MSG msg; bool done = false; @@ -166,8 +161,7 @@ public: } private: - bool CreateDeviceD3D() - { + bool CreateDeviceD3D() { // Setup swap chain DXGI_SWAP_CHAIN_DESC1 sd; { @@ -266,8 +260,7 @@ private: return true; } - void CleanupDeviceD3D() - { + void CleanupDeviceD3D() { CleanupRenderTarget(); if (mSwapChain) { mSwapChain->Release(); @@ -311,8 +304,7 @@ private: } } - void CreateRenderTarget() - { + void CreateRenderTarget() { for (UINT i = 0; i < kNumBackBuffers; i++) { ID3D12Resource* pBackBuffer = nullptr; @@ -322,8 +314,7 @@ private: } } - void CleanupRenderTarget() - { + void CleanupRenderTarget() { WaitForLastSubmittedFrame(); for (UINT i = 0; i < kNumBackBuffers; i++) @@ -333,8 +324,7 @@ private: } } - void WaitForLastSubmittedFrame() - { + void WaitForLastSubmittedFrame() { FrameContext* frameCtx = &mFrameContext[mFrameIndex % kNumFramesInFlight]; UINT64 fenceValue = frameCtx->FenceValue; @@ -349,8 +339,7 @@ private: WaitForSingleObject(mFenceEvent, INFINITE); } - FrameContext* WaitForNextFrameResources() - { + FrameContext* WaitForNextFrameResources() { UINT nextFrameIndex = mFrameIndex + 1; mFrameIndex = nextFrameIndex; @@ -372,8 +361,7 @@ private: return frameCtx; } - void ResizeSwapChain(int width, int height) - { + void ResizeSwapChain(int width, int height) { DXGI_SWAP_CHAIN_DESC1 sd; mSwapChain->GetDesc1(&sd); sd.Width = width; @@ -397,8 +385,7 @@ private: assert(mSwapChainWaitableObject != nullptr); } - static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) - { + static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { DirectX12Backend* self; if (uMsg == WM_NCCREATE) { auto lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam); @@ -416,8 +403,7 @@ private: } } - LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam) - { + LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) { return true; } @@ -451,8 +437,7 @@ private: } }; -std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx12Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx12Backend() { try { return std::make_unique<DirectX12Backend>(); } catch (std::exception& e) { @@ -462,8 +447,7 @@ std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx12Backend() #else // ^^ BUILD_CORE_WITH_DX12_BACKEND | BUILD_CORE_WITH_DX12_BACKEND vv -std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx12Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateDx12Backend() { return nullptr; } diff --git a/app/source/Cplt/ImGuiBackend/Backend_Metal.mm b/app/source/Cplt/ImGuiBackend/Backend_Metal.mm index 276bef2..a1f4993 100644 --- a/app/source/Cplt/ImGuiBackend/Backend_Metal.mm +++ b/app/source/Cplt/ImGuiBackend/Backend_Metal.mm @@ -2,27 +2,22 @@ #if BUILD_CORE_WITH_METAL_BACKEND -class MetalBackend : public RenderingBackend -{ +class MetalBackend : public RenderingBackend { public: - MetalBackend() - { + MetalBackend() { // TODO } - virtual ~MetalBackend() - { + virtual ~MetalBackend() { // TODO } - virtual void RunUntilWindowClose(void (*windowContent)()) - { + virtual void RunUntilWindowClose(void (*windowContent)()) { // TODO } }; -std::unique_ptr<RenderingBackend> RenderingBackend::CreateMetalBackend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateMetalBackend() { try { return std::make_unique<MetalBackend>(); } catch (std::exception& e) { @@ -32,8 +27,7 @@ std::unique_ptr<RenderingBackend> RenderingBackend::CreateMetalBackend() #else // ^^ BUILD_CORE_WITH_METAL_BACKEND | BUILD_CORE_WITH_METAL_BACKEND vv -std::unique_ptr<RenderingBackend> RenderingBackend::CreateMetalBackend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateMetalBackend() { return nullptr; } diff --git a/app/source/Cplt/ImGuiBackend/Backend_OpenGL2.cpp b/app/source/Cplt/ImGuiBackend/Backend_OpenGL2.cpp index 943a527..e9d05a5 100644 --- a/app/source/Cplt/ImGuiBackend/Backend_OpenGL2.cpp +++ b/app/source/Cplt/ImGuiBackend/Backend_OpenGL2.cpp @@ -13,14 +13,12 @@ # define IMGUI_IMPL_OPENGL_LOADER_CUSTOM # include <backend/imgui_impl_opengl2.cpp> -class OpenGL2Backend : public RenderingBackend -{ +class OpenGL2Backend : public RenderingBackend { private: GLFWwindow* mWindow; public: - OpenGL2Backend() - { + OpenGL2Backend() { glfwSetErrorCallback(&GlfwErrorCallback); if (!glfwInit()) { throw std::runtime_error("Failed to initialize GLFW."); @@ -44,8 +42,7 @@ public: ImGui_ImplOpenGL2_Init(); } - virtual ~OpenGL2Backend() - { + virtual ~OpenGL2Backend() { ImGui_ImplOpenGL2_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); @@ -54,8 +51,7 @@ public: glfwTerminate(); } - virtual void RunUntilWindowClose(void (*windowContent)()) - { + virtual void RunUntilWindowClose(void (*windowContent)()) { while (!glfwWindowShouldClose(mWindow)) { glfwPollEvents(); @@ -81,14 +77,12 @@ public: } } - static void GlfwErrorCallback(int errorCode, const char* message) - { + static void GlfwErrorCallback(int errorCode, const char* message) { std::cerr << "GLFW Error " << errorCode << ": " << message << "\n"; } }; -std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL2Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL2Backend() { try { return std::make_unique<OpenGL2Backend>(); } catch (std::exception& e) { @@ -98,8 +92,7 @@ std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL2Backend() #else // ^^ BUILD_CORE_WITH_OPENGL2_BACKEND | !BUILD_CORE_WITH_OPENGL2_BACKEND vv -std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL2Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL2Backend() { return nullptr; } diff --git a/app/source/Cplt/ImGuiBackend/Backend_OpenGL3.cpp b/app/source/Cplt/ImGuiBackend/Backend_OpenGL3.cpp index 9a7d67f..c2b6e20 100644 --- a/app/source/Cplt/ImGuiBackend/Backend_OpenGL3.cpp +++ b/app/source/Cplt/ImGuiBackend/Backend_OpenGL3.cpp @@ -13,14 +13,12 @@ # define IMGUI_IMPL_OPENGL_LOADER_CUSTOM # include <backend/imgui_impl_opengl3.cpp> -class OpenGL3Backend : public RenderingBackend -{ +class OpenGL3Backend : public RenderingBackend { private: GLFWwindow* mWindow; public: - OpenGL3Backend() - { + OpenGL3Backend() { glfwSetErrorCallback(&GlfwErrorCallback); if (!glfwInit()) { throw std::runtime_error("Failed to initialize GLFW."); @@ -60,8 +58,7 @@ public: ImGui_ImplOpenGL3_Init(glslVersion); } - virtual ~OpenGL3Backend() - { + virtual ~OpenGL3Backend() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); @@ -70,8 +67,7 @@ public: glfwTerminate(); } - virtual void RunUntilWindowClose(void (*windowContent)()) - { + virtual void RunUntilWindowClose(void (*windowContent)()) { while (!glfwWindowShouldClose(mWindow)) { glfwPollEvents(); @@ -96,14 +92,12 @@ public: } } - static void GlfwErrorCallback(int errorCode, const char* message) - { + static void GlfwErrorCallback(int errorCode, const char* message) { std::cerr << "GLFW Error " << errorCode << ": " << message << "\n"; } }; -std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL3Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL3Backend() { try { return std::make_unique<OpenGL3Backend>(); } catch (std::exception& e) { @@ -113,8 +107,7 @@ std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL3Backend() #else // ^^ BUILD_CORE_WITH_OPENGL3_BACKEND | !BUILD_CORE_WITH_OPENGL3_BACKEND vv -std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL3Backend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateOpenGL3Backend() { return nullptr; } diff --git a/app/source/Cplt/ImGuiBackend/Backend_Vulkan.cpp b/app/source/Cplt/ImGuiBackend/Backend_Vulkan.cpp index 3694f05..6532b37 100644 --- a/app/source/Cplt/ImGuiBackend/Backend_Vulkan.cpp +++ b/app/source/Cplt/ImGuiBackend/Backend_Vulkan.cpp @@ -12,8 +12,7 @@ # include <backend/imgui_impl_vulkan.h> # include <backend/imgui_impl_vulkan.cpp> -class VulkanBackend : public RenderingBackend -{ +class VulkanBackend : public RenderingBackend { private: GLFWwindow* mWindow; @@ -32,8 +31,7 @@ private: bool mSwapChainRebuild = false; public: - VulkanBackend() - { + VulkanBackend() { glfwSetErrorCallback(&GlfwErrorCallback); if (!glfwInit()) { throw std::runtime_error("Failed to initialize GLFW."); @@ -82,8 +80,7 @@ public: ImGui_ImplVulkan_Init(&init_info, mMainWindowData.RenderPass); } - virtual ~VulkanBackend() - { + virtual ~VulkanBackend() { auto err = vkDeviceWaitIdle(mDevice); CheckVkResults(err); ImGui_ImplVulkan_Shutdown(); @@ -97,8 +94,7 @@ public: glfwTerminate(); } - virtual void RunUntilWindowClose(void (*windowContent)()) override - { + virtual void RunUntilWindowClose(void (*windowContent)()) override { // Upload Fonts { // Use any command queue @@ -162,8 +158,7 @@ public: } private: - void SetupVulkan(const char** extensions, uint32_t extensions_count) - { + void SetupVulkan(const char** extensions, uint32_t extensions_count) { VkResult err; // Create Vulkan Instance @@ -272,8 +267,7 @@ private: } } - void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) - { + void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; // Check for WSI support @@ -297,8 +291,7 @@ private: ImGui_ImplVulkanH_CreateOrResizeWindow(mInstance, mPhysicalDevice, mDevice, wd, mQueueFamily, mAllocator, width, height, mMinImageCount); } - void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* drawData) - { + void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* drawData) { VkResult err; VkSemaphore imageAcquiredSemaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; @@ -363,8 +356,7 @@ private: } } - void FramePresent(ImGui_ImplVulkanH_Window* wd) - { + void FramePresent(ImGui_ImplVulkanH_Window* wd) { if (mSwapChainRebuild) { return; } @@ -386,21 +378,18 @@ private: wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } - void CleanupVulkan() - { + void CleanupVulkan() { vkDestroyDescriptorPool(mDevice, mDescriptorPool, mAllocator); vkDestroyDevice(mDevice, mAllocator); vkDestroyInstance(mInstance, mAllocator); } - void CleanupVulkanWindow() - { + void CleanupVulkanWindow() { ImGui_ImplVulkanH_DestroyWindow(mInstance, mDevice, &mMainWindowData, mAllocator); } - static void CheckVkResults(VkResult err) - { + static void CheckVkResults(VkResult err) { if (err == 0) return; std::string message; @@ -413,14 +402,12 @@ private: std::cerr << message << '\n'; } } - static void GlfwErrorCallback(int errorCode, const char* message) - { + static void GlfwErrorCallback(int errorCode, const char* message) { std::cerr << "GLFW Error " << errorCode << ": " << message << "\n"; } }; -std::unique_ptr<RenderingBackend> RenderingBackend::CreateVulkanBackend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateVulkanBackend() { try { return std::make_unique<VulkanBackend>(); } catch (std::exception& e) { @@ -430,8 +417,7 @@ std::unique_ptr<RenderingBackend> RenderingBackend::CreateVulkanBackend() #else // ^^ BUILD_CORE_WITH_VULKAN_BACKEND | ~BUILD_CORE_WITH_VULKAN_BACKEND vv -std::unique_ptr<RenderingBackend> RenderingBackend::CreateVulkanBackend() -{ +std::unique_ptr<RenderingBackend> RenderingBackend::CreateVulkanBackend() { return nullptr; } diff --git a/app/source/Cplt/Model/Assets.cpp b/app/source/Cplt/Model/Assets.cpp index 0dfe847..42eacf3 100644 --- a/app/source/Cplt/Model/Assets.cpp +++ b/app/source/Cplt/Model/Assets.cpp @@ -17,27 +17,23 @@ using namespace std::literals::string_view_literals; namespace fs = std::filesystem; template <class TSavedAsset, class TStream> -void OperateStreamForSavedAsset(TSavedAsset& cell, TStream& proxy) -{ +void OperateStreamForSavedAsset(TSavedAsset& cell, TStream& proxy) { proxy.template ObjectAdapted<DataStreamAdapters::String>(cell.Name); proxy.template ObjectAdapted<DataStreamAdapters::Uuid>(cell.Uuid); proxy.Value(cell.Payload); } -void SavedAsset::ReadFromDataStream(InputDataStream& stream) -{ +void SavedAsset::ReadFromDataStream(InputDataStream& stream) { ::OperateStreamForSavedAsset(*this, stream); } -void SavedAsset::WriteToDataStream(OutputDataStream& stream) const -{ +void SavedAsset::WriteToDataStream(OutputDataStream& stream) const { ::OperateStreamForSavedAsset(*this, stream); } Asset::Asset() = default; -class AssetList::Private -{ +class AssetList::Private { public: Project* ConnectedProject; tsl::array_map<char, SavedAsset> Assets; @@ -49,8 +45,7 @@ public: std::string NewName; NameSelectionError NewNameError = NameSelectionError::Empty; - void ShowErrors() const - { + void ShowErrors() const { switch (NewNameError) { case NameSelectionError::None: break; case NameSelectionError::Duplicated: @@ -62,13 +57,11 @@ public: } } - bool HasErrors() const - { + bool HasErrors() const { return NewNameError != NameSelectionError::None; } - void Validate(const AssetList& self) - { + void Validate(const AssetList& self) { if (NewName.empty()) { NewNameError = NameSelectionError::Empty; return; @@ -85,23 +78,19 @@ public: }; AssetList::AssetList(Project& project) - : mPrivate{ std::make_unique<Private>() } -{ + : mPrivate{ std::make_unique<Private>() } { mPrivate->ConnectedProject = &project; } // Write an empty destructor here so std::unique_ptr's destructor can see AssetList::Private's implementation -AssetList::~AssetList() -{ +AssetList::~AssetList() { } -Project& AssetList::GetConnectedProject() const -{ +Project& AssetList::GetConnectedProject() const { return *mPrivate->ConnectedProject; } -void AssetList::Reload() -{ +void AssetList::Reload() { // TODO fix asset dicovery loading mPrivate->Assets.clear(); mPrivate->Cache.clear(); @@ -110,18 +99,15 @@ void AssetList::Reload() }); } -int AssetList::GetCount() const -{ +int AssetList::GetCount() const { return mPrivate->Assets.size(); } -const tsl::array_map<char, SavedAsset>& AssetList::GetAssets() const -{ +const tsl::array_map<char, SavedAsset>& AssetList::GetAssets() const { return mPrivate->Assets; } -const SavedAsset* AssetList::FindByName(std::string_view name) const -{ +const SavedAsset* AssetList::FindByName(std::string_view name) const { auto iter = mPrivate->Assets.find(name); if (iter != mPrivate->Assets.end()) { return &iter.value(); @@ -130,8 +116,7 @@ const SavedAsset* AssetList::FindByName(std::string_view name) const } } -const SavedAsset& AssetList::Create(SavedAsset asset) -{ +const SavedAsset& AssetList::Create(SavedAsset asset) { auto [iter, DISCARD] = mPrivate->Assets.insert(asset.Name, SavedAsset{}); auto& savedAsset = iter.value(); @@ -145,15 +130,13 @@ const SavedAsset& AssetList::Create(SavedAsset asset) return savedAsset; } -std::unique_ptr<Asset> AssetList::CreateAndLoad(SavedAsset assetIn) -{ +std::unique_ptr<Asset> AssetList::CreateAndLoad(SavedAsset assetIn) { auto& savedAsset = Create(std::move(assetIn)); auto asset = std::unique_ptr<Asset>(CreateInstance(savedAsset)); return asset; } -std::unique_ptr<Asset> AssetList::Load(std::string_view name) const -{ +std::unique_ptr<Asset> AssetList::Load(std::string_view name) const { if (auto savedAsset = FindByName(name)) { auto asset = Load(*savedAsset); return asset; @@ -162,13 +145,11 @@ std::unique_ptr<Asset> AssetList::Load(std::string_view name) const } } -std::unique_ptr<Asset> AssetList::Load(const SavedAsset& asset) const -{ +std::unique_ptr<Asset> AssetList::Load(const SavedAsset& asset) const { return std::unique_ptr<Asset>(LoadInstance(asset)); } -const SavedAsset* AssetList::Rename(std::string_view oldName, std::string_view newName) -{ +const SavedAsset* AssetList::Rename(std::string_view oldName, std::string_view newName) { auto iter = mPrivate->Assets.find(oldName); if (iter == mPrivate->Assets.end()) return nullptr; @@ -183,8 +164,7 @@ const SavedAsset* AssetList::Rename(std::string_view oldName, std::string_view n return &newIter.value(); } -bool AssetList::Remove(std::string_view name) -{ +bool AssetList::Remove(std::string_view name) { auto iter = mPrivate->Assets.find(name); if (iter == mPrivate->Assets.end()) { return false; @@ -197,29 +177,24 @@ bool AssetList::Remove(std::string_view name) return true; } -int AssetList::GetCacheSizeLimit() const -{ +int AssetList::GetCacheSizeLimit() const { return mPrivate->CacheSizeLimit; } -void AssetList::SetCacheSizeLimit(int limit) -{ +void AssetList::SetCacheSizeLimit(int limit) { mPrivate->CacheSizeLimit = limit; } -void AssetList::DisplayIconsList(ListState& state) -{ +void AssetList::DisplayIconsList(ListState& state) { // TODO } -void AssetList::DisplayDetailsList(ListState& state) -{ +void AssetList::DisplayDetailsList(ListState& state) { // Note: stub function remained here in case any state processing needs to be done before issuing to implementers DisplayDetailsTable(state); } -void AssetList::DisplayControls(ListState& state) -{ +void AssetList::DisplayControls(ListState& state) { auto& ps = mPrivate->PopupPrivateState; bool openedDummy = true; @@ -280,8 +255,7 @@ void AssetList::DisplayControls(ListState& state) } } -void AssetList::DiscoverFilesByExtension(const std::function<void(SavedAsset)>& callback, const fs::path& containerDir, std::string_view extension) const -{ +void AssetList::DiscoverFilesByExtension(const std::function<void(SavedAsset)>& callback, const fs::path& containerDir, std::string_view extension) const { for (auto entry : fs::directory_iterator(containerDir)) { if (!entry.is_regular_file()) continue; @@ -300,7 +274,6 @@ void AssetList::DiscoverFilesByExtension(const std::function<void(SavedAsset)>& } } -void AssetList::DiscoverFilesByHeader(const std::function<void(SavedAsset)>& callback, const fs::path& containerDir, const std::function<bool(std::istream&)>& validater) const -{ +void AssetList::DiscoverFilesByHeader(const std::function<void(SavedAsset)>& callback, const fs::path& containerDir, const std::function<bool(std::istream&)>& validater) const { // TODO } diff --git a/app/source/Cplt/Model/Assets.hpp b/app/source/Cplt/Model/Assets.hpp index d2f8570..309d967 100644 --- a/app/source/Cplt/Model/Assets.hpp +++ b/app/source/Cplt/Model/Assets.hpp @@ -12,8 +12,7 @@ /// A structure representing a ready-to-be-loaded asset, locating on the disk. /// Each asset should be identified by a unique uuid within the asset category (i.e. a workflow and a template can share the same uuid), /// generated on insertion to an asset list if not given by the caller. -struct SavedAsset -{ +struct SavedAsset { std::string Name; /// UUID of this asset. This field is generated as a random UUID v4 upon insertion into an AssetList, if not already provided by the caller (indicated by !is_nil()). uuids::uuid Uuid; @@ -24,22 +23,19 @@ struct SavedAsset void WriteToDataStream(OutputDataStream& stream) const; }; -class Asset -{ +class Asset { public: Asset(); virtual ~Asset() = default; }; -enum class NameSelectionError -{ +enum class NameSelectionError { None, Duplicated, Empty, }; -class AssetList -{ +class AssetList { private: class Private; std::unique_ptr<Private> mPrivate; @@ -71,8 +67,7 @@ public: int GetCacheSizeLimit() const; void SetCacheSizeLimit(int limit); - struct ListState - { + struct ListState { const SavedAsset* SelectedAsset = nullptr; }; void DisplayIconsList(ListState& state); @@ -105,25 +100,21 @@ protected: }; template <class T> -class AssetListTyped : public AssetList -{ +class AssetListTyped : public AssetList { public: using AssetList::AssetList; #pragma clang diagnostic push #pragma ide diagnostic ignored "HidingNonVirtualFunction" - std::unique_ptr<T> CreateAndLoad(SavedAsset asset) - { + std::unique_ptr<T> CreateAndLoad(SavedAsset asset) { return std::unique_ptr<T>(static_cast<T*>(AssetList::CreateAndLoad(asset).release())); } - std::unique_ptr<T> Load(std::string_view name) const - { + std::unique_ptr<T> Load(std::string_view name) const { return std::unique_ptr<T>(static_cast<T*>(AssetList::Load(name).release())); } - std::unique_ptr<T> Load(const SavedAsset& asset) const - { + std::unique_ptr<T> Load(const SavedAsset& asset) const { return std::unique_ptr<T>(static_cast<T*>(AssetList::Load(asset).release())); } #pragma clang diagnostic pop diff --git a/app/source/Cplt/Model/Database.cpp b/app/source/Cplt/Model/Database.cpp index 07c6e36..7f78ff4 100644 --- a/app/source/Cplt/Model/Database.cpp +++ b/app/source/Cplt/Model/Database.cpp @@ -13,8 +13,7 @@ SalesTable::SalesTable(MainDatabase& db) // language=SQLite , GetRows(db.GetSQLite(), "SELECT * FROM Sales LIMIT ? OFFSET ?") // language=SQLite - , GetItems(db.GetSQLite(), "SELECT * FROM SalesItems WHERE SaleId == ?") -{ + , GetItems(db.GetSQLite(), "SELECT * FROM SalesItems WHERE SaleId == ?") { } PurchasesTable::PurchasesTable(MainDatabase& db) @@ -23,20 +22,17 @@ PurchasesTable::PurchasesTable(MainDatabase& db) // language=SQLite , GetRows(db.GetSQLite(), "SELECT * FROM Purchases LIMIT ? OFFSET ?") // language=SQLite - , GetItems(db.GetSQLite(), "SELECT * FROM PurchasesItems WHERE PurchaseId == ?") -{ + , GetItems(db.GetSQLite(), "SELECT * FROM PurchasesItems WHERE PurchaseId == ?") { } DeliveryTable::DeliveryTable(MainDatabase& db) // language=SQLite : FilterByTypeAndId(db.GetSQLite(), "SELECT * FROM Deliveries WHERE AssociatedOrder == ? AND Outgoing = ?") // language=SQLite - , GetItems(db.GetSQLite(), "SELECT * FROM DeliveriesItems WHERE DeliveryId == ?") -{ + , GetItems(db.GetSQLite(), "SELECT * FROM DeliveriesItems WHERE DeliveryId == ?") { } -static std::string GetDatabaseFilePath(const Project& project) -{ +static std::string GetDatabaseFilePath(const Project& project) { auto dbsDir = project.GetPath() / "databases"; fs::create_directories(dbsDir); @@ -46,8 +42,7 @@ static std::string GetDatabaseFilePath(const Project& project) /// Wrapper for SQLite::Database that creates the default tables MainDatabase::DatabaseWrapper::DatabaseWrapper(MainDatabase& self) - : mSqlite(GetDatabaseFilePath(*self.mProject), SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE) -{ + : mSqlite(GetDatabaseFilePath(*self.mProject), SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE) { // If this table doesn't exist, the database probably just got initialized if (mSqlite.tableExists("Sales")) { return; @@ -118,46 +113,37 @@ MainDatabase::MainDatabase(Project& project) , mDbWrapper(*this) , mSales(*this) , mPurchases(*this) - , mDeliveries(*this) -{ + , mDeliveries(*this) { } -const SQLite::Database& MainDatabase::GetSQLite() const -{ +const SQLite::Database& MainDatabase::GetSQLite() const { return mDbWrapper.mSqlite; } -SQLite::Database& MainDatabase::GetSQLite() -{ +SQLite::Database& MainDatabase::GetSQLite() { return mDbWrapper.mSqlite; } -const SalesTable& MainDatabase::GetSales() const -{ +const SalesTable& MainDatabase::GetSales() const { return mSales; } -SalesTable& MainDatabase::GetSales() -{ +SalesTable& MainDatabase::GetSales() { return mSales; } -const PurchasesTable& MainDatabase::GetPurchases() const -{ +const PurchasesTable& MainDatabase::GetPurchases() const { return mPurchases; } -PurchasesTable& MainDatabase::GetPurchases() -{ +PurchasesTable& MainDatabase::GetPurchases() { return mPurchases; } -const DeliveryTable& MainDatabase::GetDeliveries() const -{ +const DeliveryTable& MainDatabase::GetDeliveries() const { return mDeliveries; } -DeliveryTable& MainDatabase::GetDeliveries() -{ +DeliveryTable& MainDatabase::GetDeliveries() { return mDeliveries; } diff --git a/app/source/Cplt/Model/Database.hpp b/app/source/Cplt/Model/Database.hpp index 222e43d..7d6509b 100644 --- a/app/source/Cplt/Model/Database.hpp +++ b/app/source/Cplt/Model/Database.hpp @@ -6,8 +6,7 @@ #include <SQLiteCpp/Statement.h> #include <cstdint> -enum class TableKind -{ +enum class TableKind { Sales, SalesItems, Purchases, @@ -16,8 +15,7 @@ enum class TableKind DeliveriesItems, }; -class SalesTable -{ +class SalesTable { public: SQLite::Statement GetRowCount; SQLite::Statement GetRows; @@ -27,8 +25,7 @@ public: SalesTable(MainDatabase& db); }; -class PurchasesTable -{ +class PurchasesTable { public: SQLite::Statement GetRowCount; SQLite::Statement GetRows; @@ -38,8 +35,7 @@ public: PurchasesTable(MainDatabase& db); }; -class DeliveryTable -{ +class DeliveryTable { public: SQLite::Statement FilterByTypeAndId; SQLite::Statement GetItems; @@ -48,11 +44,9 @@ public: DeliveryTable(MainDatabase& db); }; -class MainDatabase -{ +class MainDatabase { private: - class DatabaseWrapper - { + class DatabaseWrapper { public: SQLite::Database mSqlite; DatabaseWrapper(MainDatabase& self); diff --git a/app/source/Cplt/Model/Filter.hpp b/app/source/Cplt/Model/Filter.hpp index 1b923e1..53995c1 100644 --- a/app/source/Cplt/Model/Filter.hpp +++ b/app/source/Cplt/Model/Filter.hpp @@ -1,6 +1,5 @@ #pragma once -class TableRowsFilter -{ +class TableRowsFilter { // TODO }; diff --git a/app/source/Cplt/Model/GlobalStates.cpp b/app/source/Cplt/Model/GlobalStates.cpp index 417514f..b21e299 100644 --- a/app/source/Cplt/Model/GlobalStates.cpp +++ b/app/source/Cplt/Model/GlobalStates.cpp @@ -16,13 +16,11 @@ namespace fs = std::filesystem; static std::unique_ptr<GlobalStates> globalStateInstance; static fs::path globalDataPath; -void GlobalStates::Init() -{ +void GlobalStates::Init() { Init(StandardDirectories::UserData() / "cplt"); } -void GlobalStates::Init(std::filesystem::path userDataDir) -{ +void GlobalStates::Init(std::filesystem::path userDataDir) { globalStateInstance = std::make_unique<GlobalStates>(); globalDataPath = userDataDir; fs::create_directories(globalDataPath); @@ -53,8 +51,7 @@ void GlobalStates::Init(std::filesystem::path userDataDir) } } -void GlobalStates::Shutdown() -{ +void GlobalStates::Shutdown() { if (!globalStateInstance) return; globalStateInstance->SetCurrentProject(nullptr); @@ -64,29 +61,24 @@ void GlobalStates::Shutdown() } } -GlobalStates& GlobalStates::GetInstance() -{ +GlobalStates& GlobalStates::GetInstance() { return *globalStateInstance; } -const std::filesystem::path& GlobalStates::GetUserDataPath() -{ +const std::filesystem::path& GlobalStates::GetUserDataPath() { return globalDataPath; } -const std::vector<GlobalStates::RecentProject>& GlobalStates::GetRecentProjects() const -{ +const std::vector<GlobalStates::RecentProject>& GlobalStates::GetRecentProjects() const { return mRecentProjects; } -void GlobalStates::ClearRecentProjects() -{ +void GlobalStates::ClearRecentProjects() { mRecentProjects.clear(); MarkDirty(); } -void GlobalStates::AddRecentProject(const Project& project) -{ +void GlobalStates::AddRecentProject(const Project& project) { mRecentProjects.push_back(RecentProject{ .Path = project.GetPath(), .CachedUtf8String = project.GetPath().string(), @@ -94,8 +86,7 @@ void GlobalStates::AddRecentProject(const Project& project) MarkDirty(); } -void GlobalStates::MoveProjectToTop(const Project& project) -{ +void GlobalStates::MoveProjectToTop(const Project& project) { for (auto it = mRecentProjects.begin(); it != mRecentProjects.end(); ++it) { if (it->Path == project.GetPath()) { std::rotate(it, it + 1, mRecentProjects.end()); @@ -106,26 +97,22 @@ void GlobalStates::MoveProjectToTop(const Project& project) AddRecentProject(project); } -void GlobalStates::RemoveRecentProject(int idx) -{ +void GlobalStates::RemoveRecentProject(int idx) { assert(idx >= 0 && idx < mRecentProjects.size()); mRecentProjects.erase(mRecentProjects.begin() + idx); MarkDirty(); } -bool GlobalStates::HasCurrentProject() const -{ +bool GlobalStates::HasCurrentProject() const { return mCurrentProject != nullptr; } -Project* GlobalStates::GetCurrentProject() const -{ +Project* GlobalStates::GetCurrentProject() const { return mCurrentProject.get(); } -void GlobalStates::SetCurrentProject(std::unique_ptr<Project> project) -{ +void GlobalStates::SetCurrentProject(std::unique_ptr<Project> project) { if (mCurrentProject) { mCurrentProject->WriteToDisk(); mCurrentProject = nullptr; @@ -136,8 +123,7 @@ void GlobalStates::SetCurrentProject(std::unique_ptr<Project> project) mCurrentProject = std::move(project); } -void GlobalStates::WriteToDisk() const -{ +void GlobalStates::WriteToDisk() const { Json::Value root; auto& recentProjects = root["RecentProjects"] = Json::Value(Json::arrayValue); @@ -151,13 +137,11 @@ void GlobalStates::WriteToDisk() const mDirty = false; } -bool GlobalStates::IsDirty() const -{ +bool GlobalStates::IsDirty() const { return mDirty; } -void GlobalStates::MarkDirty() -{ +void GlobalStates::MarkDirty() { mDirty = true; OnModified(); } diff --git a/app/source/Cplt/Model/GlobalStates.hpp b/app/source/Cplt/Model/GlobalStates.hpp index 1eb47fb..c0b475c 100644 --- a/app/source/Cplt/Model/GlobalStates.hpp +++ b/app/source/Cplt/Model/GlobalStates.hpp @@ -7,8 +7,7 @@ #include <string> #include <vector> -class GlobalStates -{ +class GlobalStates { public: static void Init(); static void Init(std::filesystem::path userDataDir); @@ -17,8 +16,7 @@ public: static GlobalStates& GetInstance(); static const std::filesystem::path& GetUserDataPath(); - struct RecentProject - { + struct RecentProject { std::filesystem::path Path; std::string CachedUtf8String; }; diff --git a/app/source/Cplt/Model/Items.cpp b/app/source/Cplt/Model/Items.cpp index 9d2abc6..02a4516 100644 --- a/app/source/Cplt/Model/Items.cpp +++ b/app/source/Cplt/Model/Items.cpp @@ -1,36 +1,29 @@ #include "Items.hpp" -const std::string& ProductItem::GetDescription() const -{ +const std::string& ProductItem::GetDescription() const { return mDescription; } -void ProductItem::SetDescription(std::string description) -{ +void ProductItem::SetDescription(std::string description) { mDescription = std::move(description); } -int ProductItem::GetPrice() const -{ +int ProductItem::GetPrice() const { return mPrice; } -void ProductItem::SetPrice(int price) -{ +void ProductItem::SetPrice(int price) { mPrice = price; } -int ProductItem::GetStock() const -{ +int ProductItem::GetStock() const { return mStock; } -void ProductItem::SetStock(int stock) -{ +void ProductItem::SetStock(int stock) { mStock = stock; } -Json::Value ProductItem::Serialize() const -{ +Json::Value ProductItem::Serialize() const { Json::Value elm; elm["Description"] = mDescription; elm["Price"] = mPrice; @@ -38,77 +31,64 @@ Json::Value ProductItem::Serialize() const return elm; } -void ProductItem::Deserialize(const Json::Value& elm) -{ +void ProductItem::Deserialize(const Json::Value& elm) { mDescription = elm["Description"].asString(); mPrice = elm["Price"].asInt(); mStock = elm["Stock"].asInt(); } -const std::string& FactoryItem::GetDescription() const -{ +const std::string& FactoryItem::GetDescription() const { return mDescription; } -void FactoryItem::SetDescription(std::string description) -{ +void FactoryItem::SetDescription(std::string description) { mDescription = std::move(description); } -const std::string& FactoryItem::GetEmail() const -{ +const std::string& FactoryItem::GetEmail() const { return mEmail; } -void FactoryItem::SetEmail(std::string email) -{ +void FactoryItem::SetEmail(std::string email) { mEmail = std::move(email); } -Json::Value FactoryItem::Serialize() const -{ +Json::Value FactoryItem::Serialize() const { Json::Value elm; elm["Description"] = mDescription; elm["Email"] = mEmail; return elm; } -void FactoryItem::Deserialize(const Json::Value& elm) -{ +void FactoryItem::Deserialize(const Json::Value& elm) { mDescription = elm["Description"].asString(); mEmail = elm["Email"].asString(); } -const std::string& CustomerItem::GetDescription() const -{ +const std::string& CustomerItem::GetDescription() const { return mDescription; } -void CustomerItem::SetDescription(std::string description) -{ +void CustomerItem::SetDescription(std::string description) { mDescription = std::move(description); } -const std::string& CustomerItem::GetEmail() const -{ +const std::string& CustomerItem::GetEmail() const { return mEmail; } -void CustomerItem::SetEmail(std::string email) -{ +void CustomerItem::SetEmail(std::string email) { mEmail = std::move(email); } -Json::Value CustomerItem::Serialize() const -{ +Json::Value CustomerItem::Serialize() const { Json::Value elm; elm["Description"] = mDescription; elm["Email"] = mEmail; return elm; } -void CustomerItem::Deserialize(const Json::Value& elm) -{ +void CustomerItem::Deserialize(const Json::Value& elm) { mDescription = elm["Description"].asString(); mEmail = elm["Email"].asString(); } diff --git a/app/source/Cplt/Model/Items.hpp b/app/source/Cplt/Model/Items.hpp index c00ee59..f3254e2 100644 --- a/app/source/Cplt/Model/Items.hpp +++ b/app/source/Cplt/Model/Items.hpp @@ -15,16 +15,14 @@ #include <vector> template <class T> -class ItemList -{ +class ItemList { private: std::vector<T> mStorage; tsl::array_map<char, size_t> mNameLookup; public: template <class... Args> - T& Insert(std::string name, Args... args) - { + T& Insert(std::string name, Args... args) { auto iter = mNameLookup.find(name); if (iter != mNameLookup.end()) { throw std::runtime_error("Duplicate key."); @@ -44,25 +42,21 @@ public: return mStorage[id]; } - void Remove(size_t index) - { + void Remove(size_t index) { auto& item = mStorage[index]; mNameLookup.erase(item.GetName()); mStorage[index] = T(*this); } - T* Find(size_t id) - { + T* Find(size_t id) { return &mStorage[id]; } - const T* Find(size_t id) const - { + const T* Find(size_t id) const { return &mStorage[id]; } - const T* Find(std::string_view name) const - { + const T* Find(std::string_view name) const { auto iter = mNameLookup.find(name); if (iter != mNameLookup.end()) { return &mStorage[iter.value()]; @@ -71,8 +65,7 @@ public: } } - Json::Value Serialize() const - { + Json::Value Serialize() const { Json::Value items(Json::arrayValue); for (auto& item : mStorage) { if (!item.IsInvalid()) { @@ -92,8 +85,7 @@ public: ItemList() = default; - ItemList(const Json::Value& root) - { + ItemList(const Json::Value& root) { constexpr const char* kMessage = "Failed to load item list from JSON."; auto& itemCount = root["MaxItemId"]; @@ -118,23 +110,19 @@ public: } } - typename decltype(mStorage)::iterator begin() - { + typename decltype(mStorage)::iterator begin() { return mStorage.begin(); } - typename decltype(mStorage)::iterator end() - { + typename decltype(mStorage)::iterator end() { return mStorage.end(); } - typename decltype(mStorage)::const_iterator begin() const - { + typename decltype(mStorage)::const_iterator begin() const { return mStorage.begin(); } - typename decltype(mStorage)::const_iterator end() const - { + typename decltype(mStorage)::const_iterator end() const { return mStorage.end(); } @@ -142,16 +130,14 @@ private: template <class TSelf> friend class ItemBase; - void UpdateItemName(const T& item, const std::string& newName) - { + void UpdateItemName(const T& item, const std::string& newName) { mNameLookup.erase(item.GetName()); mNameLookup.insert(newName, item.GetId()); } }; template <class TSelf> -class ItemBase -{ +class ItemBase { private: ItemList<TSelf>* mList; size_t mId; @@ -161,39 +147,32 @@ public: ItemBase(ItemList<TSelf>& list, size_t id = std::numeric_limits<size_t>::max(), std::string name = "") : mList{ &list } , mId{ id } - , mName{ std::move(name) } - { + , mName{ std::move(name) } { } - bool IsInvalid() const - { + bool IsInvalid() const { return mId == std::numeric_limits<size_t>::max(); } - ItemList<TSelf>& GetList() const - { + ItemList<TSelf>& GetList() const { return *mList; } - size_t GetId() const - { + size_t GetId() const { return mId; } - const std::string& GetName() const - { + const std::string& GetName() const { return mName; } - void SetName(std::string name) - { + void SetName(std::string name) { mList->UpdateItemName(static_cast<TSelf&>(*this), name); mName = std::move(name); } }; -class ProductItem : public ItemBase<ProductItem> -{ +class ProductItem : public ItemBase<ProductItem> { private: std::string mDescription; int mPrice = 0; @@ -216,8 +195,7 @@ public: void Deserialize(const Json::Value& elm); }; -class FactoryItem : public ItemBase<FactoryItem> -{ +class FactoryItem : public ItemBase<FactoryItem> { private: std::string mDescription; std::string mEmail; @@ -234,8 +212,7 @@ public: void Deserialize(const Json::Value& elm); }; -class CustomerItem : public ItemBase<CustomerItem> -{ +class CustomerItem : public ItemBase<CustomerItem> { private: std::string mDescription; std::string mEmail; diff --git a/app/source/Cplt/Model/Project.cpp b/app/source/Cplt/Model/Project.cpp index a1e9bab..524e508 100644 --- a/app/source/Cplt/Model/Project.cpp +++ b/app/source/Cplt/Model/Project.cpp @@ -14,8 +14,7 @@ namespace fs = std::filesystem; template <class T> -static void ReadItemList(ItemList<T>& list, const fs::path& filePath) -{ +static void ReadItemList(ItemList<T>& list, const fs::path& filePath) { std::ifstream ifs(filePath); if (ifs) { Json::Value root; @@ -25,8 +24,7 @@ static void ReadItemList(ItemList<T>& list, const fs::path& filePath) } } -static void CreateProjectSubfolders(const Project& project) -{ +static void CreateProjectSubfolders(const Project& project) { fs::create_directory(project.GetDatabasesDirectory()); fs::create_directory(project.GetItemsDirectory()); fs::create_directory(project.GetWorkflowsDirectory()); @@ -38,8 +36,7 @@ Project::Project(fs::path rootPath) , mRootPathString{ mRootPath.string() } , Workflows(*this) , Templates(*this) - , Database(*this) -{ + , Database(*this) { // TODO better diagnostic const char* kInvalidFormatErr = "Failed to load project: invalid format."; @@ -85,63 +82,51 @@ Project::Project(fs::path rootPath, std::string name) , mName{ std::move(name) } , Workflows(*this) , Templates(*this) - , Database(*this) -{ + , Database(*this) { CreateProjectSubfolders(*this); } -const fs::path& Project::GetPath() const -{ +const fs::path& Project::GetPath() const { return mRootPath; } -const std::string& Project::GetPathString() const -{ +const std::string& Project::GetPathString() const { return mRootPathString; } -fs::path Project::GetDatabasesDirectory() const -{ +fs::path Project::GetDatabasesDirectory() const { return mRootPath / "databases"; } -fs::path Project::GetItemsDirectory() const -{ +fs::path Project::GetItemsDirectory() const { return mRootPath / "items"; } -fs::path Project::GetWorkflowsDirectory() const -{ +fs::path Project::GetWorkflowsDirectory() const { return mRootPath / "workflows"; } -fs::path Project::GetWorkflowPath(std::string_view name) const -{ +fs::path Project::GetWorkflowPath(std::string_view name) const { return (mRootPath / "workflows" / name).concat(".cplt-workflow"); } -fs::path Project::GetTemplatesDirectory() const -{ +fs::path Project::GetTemplatesDirectory() const { return mRootPath / "templates"; } -fs::path Project::GetTemplatePath(std::string_view name) const -{ +fs::path Project::GetTemplatePath(std::string_view name) const { return (mRootPath / "templates" / name).concat(".cplt-template"); } -const std::string& Project::GetName() const -{ +const std::string& Project::GetName() const { return mName; } -void Project::SetName(std::string name) -{ +void Project::SetName(std::string name) { mName = std::move(name); } -Json::Value Project::Serialize() -{ +Json::Value Project::Serialize() { Json::Value root(Json::objectValue); root["Name"] = mName; @@ -150,14 +135,12 @@ Json::Value Project::Serialize() } template <class T> -static void WriteItemList(ItemList<T>& list, const fs::path& filePath) -{ +static void WriteItemList(ItemList<T>& list, const fs::path& filePath) { std::ofstream ofs(filePath); ofs << list.Serialize(); } -void Project::WriteToDisk() -{ +void Project::WriteToDisk() { std::ofstream ofs(mRootPath / "cplt_project.json"); ofs << this->Serialize(); diff --git a/app/source/Cplt/Model/Project.hpp b/app/source/Cplt/Model/Project.hpp index 8119a97..c5ca7db 100644 --- a/app/source/Cplt/Model/Project.hpp +++ b/app/source/Cplt/Model/Project.hpp @@ -12,8 +12,7 @@ #include <string> #include <string_view> -class Project -{ +class Project { private: std::filesystem::path mRootPath; std::string mRootPathString; diff --git a/app/source/Cplt/Model/Template/TableTemplate.cpp b/app/source/Cplt/Model/Template/TableTemplate.cpp index 5cd9ed8..c7faf24 100644 --- a/app/source/Cplt/Model/Template/TableTemplate.cpp +++ b/app/source/Cplt/Model/Template/TableTemplate.cpp @@ -12,24 +12,20 @@ #include <iostream> #include <map> -bool TableCell::IsDataHoldingCell() const -{ +bool TableCell::IsDataHoldingCell() const { return IsPrimaryCell() || !IsMergedCell(); } -bool TableCell::IsPrimaryCell() const -{ +bool TableCell::IsPrimaryCell() const { return PrimaryCellLocation == Location; } -bool TableCell::IsMergedCell() const -{ +bool TableCell::IsMergedCell() const { return PrimaryCellLocation.x == -1 || PrimaryCellLocation.y == -1; } template <class TTableCell, class TStream> -void OperateStreamForTableCell(TTableCell& cell, TStream& proxy) -{ +void OperateStreamForTableCell(TTableCell& cell, TStream& proxy) { proxy.template ObjectAdapted<DataStreamAdapters::String>(cell.Content); proxy.Object(cell.Location); proxy.Object(cell.PrimaryCellLocation); @@ -41,40 +37,33 @@ void OperateStreamForTableCell(TTableCell& cell, TStream& proxy) proxy.Value(cell.DataId); } -void TableCell::ReadFromDataStream(InputDataStream& stream) -{ +void TableCell::ReadFromDataStream(InputDataStream& stream) { ::OperateStreamForTableCell(*this, stream); } -void TableCell::WriteToDataStream(OutputDataStream& stream) const -{ +void TableCell::WriteToDataStream(OutputDataStream& stream) const { ::OperateStreamForTableCell(*this, stream); } -Vec2i TableArrayGroup::GetLeftCell() const -{ +Vec2i TableArrayGroup::GetLeftCell() const { return { Row, LeftCell }; } -Vec2i TableArrayGroup::GetRightCell() const -{ +Vec2i TableArrayGroup::GetRightCell() const { return { Row, RightCell }; } -int TableArrayGroup::GetCount() const -{ +int TableArrayGroup::GetCount() const { return RightCell - LeftCell + 1; } -Vec2i TableArrayGroup::FindCell(std::string_view name) -{ +Vec2i TableArrayGroup::FindCell(std::string_view name) { // TODO return Vec2i{}; } template <class TMap> -static bool UpdateElementName(TMap& map, std::string_view oldName, std::string_view newName) -{ +static bool UpdateElementName(TMap& map, std::string_view oldName, std::string_view newName) { auto iter = map.find(oldName); if (iter == map.end()) { return false; @@ -90,75 +79,62 @@ static bool UpdateElementName(TMap& map, std::string_view oldName, std::string_v return true; } -bool TableArrayGroup::UpdateCellName(std::string_view oldName, std::string_view newName) -{ +bool TableArrayGroup::UpdateCellName(std::string_view oldName, std::string_view newName) { return ::UpdateElementName(mName2Cell, oldName, newName); } template <class TTableArrayGroup, class TStream> -void OperateStreamForTableArrayGroup(TTableArrayGroup& group, TStream& stream) -{ +void OperateStreamForTableArrayGroup(TTableArrayGroup& group, TStream& stream) { stream.Value(group.Row); stream.Value(group.LeftCell); stream.Value(group.RightCell); } -void TableArrayGroup::ReadFromDataStream(InputDataStream& stream) -{ +void TableArrayGroup::ReadFromDataStream(InputDataStream& stream) { ::OperateStreamForTableArrayGroup(*this, stream); } -void TableArrayGroup::WriteToDataStream(OutputDataStream& stream) const -{ +void TableArrayGroup::WriteToDataStream(OutputDataStream& stream) const { ::OperateStreamForTableArrayGroup(*this, stream); } TableInstantiationParameters::TableInstantiationParameters(const TableTemplate& table) - : mTable{ &table } -{ + : mTable{ &table } { } -TableInstantiationParameters& TableInstantiationParameters::ResetTable(const TableTemplate& newTable) -{ +TableInstantiationParameters& TableInstantiationParameters::ResetTable(const TableTemplate& newTable) { mTable = &newTable; return *this; } -TableInstantiationParameters TableInstantiationParameters::RebindTable(const TableTemplate& newTable) const -{ +TableInstantiationParameters TableInstantiationParameters::RebindTable(const TableTemplate& newTable) const { TableInstantiationParameters result(newTable); result.SingularCells = this->SingularCells; result.ArrayGroups = this->ArrayGroups; return result; } -const TableTemplate& TableInstantiationParameters::GetTable() const -{ +const TableTemplate& TableInstantiationParameters::GetTable() const { return *mTable; } -bool TableTemplate::IsInstance(const Template* tmpl) -{ +bool TableTemplate::IsInstance(const Template* tmpl) { return tmpl->GetKind() == KD_Table; } TableTemplate::TableTemplate() - : Template(KD_Table) -{ + : Template(KD_Table) { } -int TableTemplate::GetTableWidth() const -{ +int TableTemplate::GetTableWidth() const { return mColumnWidths.size(); } -int TableTemplate::GetTableHeight() const -{ +int TableTemplate::GetTableHeight() const { return mRowHeights.size(); } -void TableTemplate::Resize(int newWidth, int newHeight) -{ +void TableTemplate::Resize(int newWidth, int newHeight) { // TODO this doesn't gracefully handle resizing to a smaller size which trims some merged cells std::vector<TableCell> cells; @@ -190,39 +166,32 @@ void TableTemplate::Resize(int newWidth, int newHeight) mRowHeights.resize(newHeight, 20); } -int TableTemplate::GetRowHeight(int row) const -{ +int TableTemplate::GetRowHeight(int row) const { return mRowHeights[row]; } -void TableTemplate::SetRowHeight(int row, int height) -{ +void TableTemplate::SetRowHeight(int row, int height) { mRowHeights[row] = height; } -int TableTemplate::GetColumnWidth(int column) const -{ +int TableTemplate::GetColumnWidth(int column) const { return mColumnWidths[column]; } -void TableTemplate::SetColumnWidth(int column, int width) -{ +void TableTemplate::SetColumnWidth(int column, int width) { mColumnWidths[column] = width; } -const TableCell& TableTemplate::GetCell(Vec2i pos) const -{ +const TableCell& TableTemplate::GetCell(Vec2i pos) const { int tableWidth = GetTableWidth(); return mCells[pos.y * tableWidth + pos.x]; } -TableCell& TableTemplate::GetCell(Vec2i pos) -{ +TableCell& TableTemplate::GetCell(Vec2i pos) { return const_cast<TableCell&>(const_cast<const TableTemplate*>(this)->GetCell(pos)); } -void TableTemplate::SetCellType(Vec2i pos, TableCell::CellType type) -{ +void TableTemplate::SetCellType(Vec2i pos, TableCell::CellType type) { auto& cell = GetCell(pos); if (cell.Type == type) { return; @@ -274,28 +243,23 @@ void TableTemplate::SetCellType(Vec2i pos, TableCell::CellType type) cell.Type = type; } -bool TableTemplate::UpdateParameterName(std::string_view oldName, std::string_view newName) -{ +bool TableTemplate::UpdateParameterName(std::string_view oldName, std::string_view newName) { return ::UpdateElementName(mName2Parameters, oldName, newName); } -int TableTemplate::GetArrayGroupCount() const -{ +int TableTemplate::GetArrayGroupCount() const { return mArrayGroups.size(); } -const TableArrayGroup& TableTemplate::GetArrayGroup(int id) const -{ +const TableArrayGroup& TableTemplate::GetArrayGroup(int id) const { return mArrayGroups[id]; } -TableArrayGroup& TableTemplate::GetArrayGroup(int id) -{ +TableArrayGroup& TableTemplate::GetArrayGroup(int id) { return mArrayGroups[id]; } -TableArrayGroup* TableTemplate::AddArrayGroup(int row, int left, int right) -{ +TableArrayGroup* TableTemplate::AddArrayGroup(int row, int left, int right) { // size_t max value: 18446744073709551615 // ^~~~~~~~~~~~~~~~~~~~ 20 chars char name[20]; @@ -305,8 +269,7 @@ TableArrayGroup* TableTemplate::AddArrayGroup(int row, int left, int right) return AddArrayGroup(nameStr, row, left, right); } -TableArrayGroup* TableTemplate::AddArrayGroup(std::string_view name, int row, int left, int right) -{ +TableArrayGroup* TableTemplate::AddArrayGroup(std::string_view name, int row, int left, int right) { assert(row >= 0 && row < GetTableHeight()); assert(left >= 0 && left < GetTableWidth()); assert(right >= 0 && right < GetTableWidth()); @@ -349,13 +312,11 @@ TableArrayGroup* TableTemplate::AddArrayGroup(std::string_view name, int row, in return &ag; } -bool TableTemplate::UpdateArrayGroupName(std::string_view oldName, std::string_view newName) -{ +bool TableTemplate::UpdateArrayGroupName(std::string_view oldName, std::string_view newName) { return ::UpdateElementName(mName2ArrayGroups, oldName, newName); } -bool TableTemplate::ExtendArrayGroupLeft(int id, int n) -{ +bool TableTemplate::ExtendArrayGroupLeft(int id, int n) { assert(n > 0); auto& ag = mArrayGroups[id]; @@ -364,8 +325,7 @@ bool TableTemplate::ExtendArrayGroupLeft(int id, int n) return false; } -bool TableTemplate::ExtendArrayGroupRight(int id, int n) -{ +bool TableTemplate::ExtendArrayGroupRight(int id, int n) { assert(n > 0); auto& ag = mArrayGroups[id]; @@ -374,8 +334,7 @@ bool TableTemplate::ExtendArrayGroupRight(int id, int n) return false; } -TableCell* TableTemplate::FindCell(std::string_view name) -{ +TableCell* TableTemplate::FindCell(std::string_view name) { auto iter = mName2Parameters.find(name); if (iter != mName2Parameters.end()) { return &mCells[iter.value()]; @@ -384,8 +343,7 @@ TableCell* TableTemplate::FindCell(std::string_view name) } } -TableArrayGroup* TableTemplate::FindArrayGroup(std::string_view name) -{ +TableArrayGroup* TableTemplate::FindArrayGroup(std::string_view name) { auto iter = mName2ArrayGroups.find(name); if (iter != mName2ArrayGroups.end()) { return &mArrayGroups[iter.value()]; @@ -394,8 +352,7 @@ TableArrayGroup* TableTemplate::FindArrayGroup(std::string_view name) } } -TableTemplate::MergeCellsResult TableTemplate::MergeCells(Vec2i topLeft, Vec2i bottomRight) -{ +TableTemplate::MergeCellsResult TableTemplate::MergeCells(Vec2i topLeft, Vec2i bottomRight) { auto SortTwo = [](int& a, int& b) { if (a > b) { std::swap(a, b); @@ -432,8 +389,7 @@ TableTemplate::MergeCellsResult TableTemplate::MergeCells(Vec2i topLeft, Vec2i b return MCR_Success; } -TableTemplate::BreakCellsResult TableTemplate::BreakCells(Vec2i topLeft) -{ +TableTemplate::BreakCellsResult TableTemplate::BreakCells(Vec2i topLeft) { auto& primaryCell = GetCell(topLeft); if (!primaryCell.IsMergedCell()) { return BCR_CellNotMerged; @@ -452,15 +408,13 @@ TableTemplate::BreakCellsResult TableTemplate::BreakCells(Vec2i topLeft) return BCR_Success; } -lxw_workbook* TableTemplate::InstantiateToExcelWorkbook(const TableInstantiationParameters& params) const -{ +lxw_workbook* TableTemplate::InstantiateToExcelWorkbook(const TableInstantiationParameters& params) const { auto workbook = workbook_new("Table.xlsx"); InstantiateToExcelWorksheet(workbook, params); return workbook; } -lxw_worksheet* TableTemplate::InstantiateToExcelWorksheet(lxw_workbook* workbook, const TableInstantiationParameters& params) const -{ +lxw_worksheet* TableTemplate::InstantiateToExcelWorksheet(lxw_workbook* workbook, const TableInstantiationParameters& params) const { auto worksheet = workbook_add_worksheet(workbook, "CpltExport.xlsx"); // Map: row number -> length of generated ranges @@ -565,12 +519,10 @@ lxw_worksheet* TableTemplate::InstantiateToExcelWorksheet(lxw_workbook* workbook return worksheet; } -class TableTemplate::Private -{ +class TableTemplate::Private { public: template <class TTableTemplate, class TProxy> - static void OperateStream(TTableTemplate& table, TProxy& proxy) - { + static void OperateStream(TTableTemplate& table, TProxy& proxy) { proxy.template ObjectAdapted<DataStreamAdapters::Vector<>>(table.mColumnWidths); proxy.template ObjectAdapted<DataStreamAdapters::Vector<>>(table.mRowHeights); proxy.template ObjectAdapted<DataStreamAdapters::Vector<>>(table.mCells); @@ -580,12 +532,10 @@ public: } }; -void TableTemplate::ReadFromDataStream(InputDataStream& stream) -{ +void TableTemplate::ReadFromDataStream(InputDataStream& stream) { Private::OperateStream(*this, stream); } -void TableTemplate::WriteToDataStream(OutputDataStream& stream) const -{ +void TableTemplate::WriteToDataStream(OutputDataStream& stream) const { Private::OperateStream(*this, stream); } diff --git a/app/source/Cplt/Model/Template/TableTemplate.hpp b/app/source/Cplt/Model/Template/TableTemplate.hpp index 3e931d4..e0dea09 100644 --- a/app/source/Cplt/Model/Template/TableTemplate.hpp +++ b/app/source/Cplt/Model/Template/TableTemplate.hpp @@ -11,11 +11,9 @@ #include <string_view> #include <vector> -class TableCell -{ +class TableCell { public: - enum TextAlignment - { + enum TextAlignment { /// For horizontal alignment, this means align left. For vertical alignment, this means align top. AlignAxisMin, /// Align middle of the text to the middle of the axis. @@ -24,8 +22,7 @@ public: AlignAxisMax, }; - enum CellType - { + enum CellType { ConstantCell, SingularParametricCell, ArrayParametricCell, @@ -89,8 +86,7 @@ public: /// \see TableCell /// \see TableInstantiationParameters /// \see TableTemplate -class TableArrayGroup -{ +class TableArrayGroup { public: /// Parameter name mapped to cell location (index from LeftCell). tsl::array_map<char, int> mName2Cell; @@ -119,8 +115,7 @@ struct lxw_worksheet; /// An object containing the necessary information to instantiate a table template. /// \see TableTemplate -class TableInstantiationParameters -{ +class TableInstantiationParameters { private: const TableTemplate* mTable; @@ -144,8 +139,7 @@ public: /// parametric rows/columns, and grids are also supported. /// /// This current supports exporting to xlsx files. -class TableTemplate : public Template -{ +class TableTemplate : public Template { friend class TableSingleParamsIter; friend class TableArrayGroupsIter; class Private; @@ -201,15 +195,13 @@ public: /// Find an array group by its name. TableArrayGroup* FindArrayGroup(std::string_view name); - enum MergeCellsResult - { + enum MergeCellsResult { MCR_CellAlreadyMerged, MCR_Success, }; MergeCellsResult MergeCells(Vec2i topLeft, Vec2i bottomRight); - enum BreakCellsResult - { + enum BreakCellsResult { BCR_CellNotMerged, BCR_Success, }; diff --git a/app/source/Cplt/Model/Template/TableTemplateIterator.cpp b/app/source/Cplt/Model/Template/TableTemplateIterator.cpp index 19e30b9..3a8e8c2 100644 --- a/app/source/Cplt/Model/Template/TableTemplateIterator.cpp +++ b/app/source/Cplt/Model/Template/TableTemplateIterator.cpp @@ -2,17 +2,14 @@ TableSingleParamsIter::TableSingleParamsIter(TableTemplate& tmpl) : mTemplate{ &tmpl } - , mIter{ tmpl.mName2Parameters.begin() } -{ + , mIter{ tmpl.mName2Parameters.begin() } { } -bool TableSingleParamsIter::HasNext() const -{ +bool TableSingleParamsIter::HasNext() const { return mIter != mTemplate->mName2Parameters.end(); } -TableCell& TableSingleParamsIter::Next() -{ +TableCell& TableSingleParamsIter::Next() { int id = mIter.value(); ++mIter; @@ -21,32 +18,26 @@ TableCell& TableSingleParamsIter::Next() TableArrayGroupsIter::TableArrayGroupsIter(TableTemplate& tmpl) : mTemplate{ &tmpl } - , mIter{ tmpl.mName2ArrayGroups.begin() } -{ + , mIter{ tmpl.mName2ArrayGroups.begin() } { } -bool TableArrayGroupsIter::HasNext() const -{ +bool TableArrayGroupsIter::HasNext() const { return mIter != mTemplate->mName2ArrayGroups.end(); } -TableArrayGroup& TableArrayGroupsIter::Peek() const -{ +TableArrayGroup& TableArrayGroupsIter::Peek() const { int id = mIter.value(); return mTemplate->mArrayGroups[id]; } -std::string_view TableArrayGroupsIter::PeekName() const -{ +std::string_view TableArrayGroupsIter::PeekName() const { return mIter.key_sv(); } -const char* TableArrayGroupsIter::PeekNameCStr() const -{ +const char* TableArrayGroupsIter::PeekNameCStr() const { return mIter.key(); } -void TableArrayGroupsIter::Next() -{ +void TableArrayGroupsIter::Next() { ++mIter; } diff --git a/app/source/Cplt/Model/Template/TableTemplateIterator.hpp b/app/source/Cplt/Model/Template/TableTemplateIterator.hpp index c4b5bf9..d9cb2ad 100644 --- a/app/source/Cplt/Model/Template/TableTemplateIterator.hpp +++ b/app/source/Cplt/Model/Template/TableTemplateIterator.hpp @@ -5,8 +5,7 @@ #include <string_view> -class TableSingleParamsIter -{ +class TableSingleParamsIter { private: TableTemplate* mTemplate; tsl::array_map<char, int>::iterator mIter; @@ -18,8 +17,7 @@ public: TableCell& Next(); }; -class TableArrayGroupsIter -{ +class TableArrayGroupsIter { private: TableTemplate* mTemplate; tsl::array_map<char, int>::iterator mIter; diff --git a/app/source/Cplt/Model/Template/Template.hpp b/app/source/Cplt/Model/Template/Template.hpp index cf926d0..9591eaa 100644 --- a/app/source/Cplt/Model/Template/Template.hpp +++ b/app/source/Cplt/Model/Template/Template.hpp @@ -8,11 +8,9 @@ #include <memory> #include <string> -class Template : public Asset -{ +class Template : public Asset { public: - enum Kind - { + enum Kind { KD_Table, InvalidKind, @@ -39,8 +37,7 @@ public: virtual void WriteToDataStream(OutputDataStream& stream) const = 0; }; -class TemplateAssetList final : public AssetListTyped<Template> -{ +class TemplateAssetList final : public AssetListTyped<Template> { private: // AC = Asset Creator std::string mACNewName; diff --git a/app/source/Cplt/Model/Template/Template_Main.cpp b/app/source/Cplt/Model/Template/Template_Main.cpp index d658231..57f3925 100644 --- a/app/source/Cplt/Model/Template/Template_Main.cpp +++ b/app/source/Cplt/Model/Template/Template_Main.cpp @@ -17,23 +17,19 @@ using namespace std::literals::string_view_literals; namespace fs = std::filesystem; Template::Template(Kind kind) - : mKind{ kind } -{ + : mKind{ kind } { } -Template::Kind Template::GetKind() const -{ +Template::Kind Template::GetKind() const { return mKind; } -void TemplateAssetList::DiscoverFiles(const std::function<void(SavedAsset)>& callback) const -{ +void TemplateAssetList::DiscoverFiles(const std::function<void(SavedAsset)>& callback) const { auto dir = GetConnectedProject().GetTemplatesDirectory(); DiscoverFilesByExtension(callback, dir, ".cplt-template"sv); } -std::string TemplateAssetList::RetrieveNameFromFile(const fs::path& file) const -{ +std::string TemplateAssetList::RetrieveNameFromFile(const fs::path& file) const { auto res = DataArchive::LoadFile(file); if (!res) return ""; auto& stream = res.value(); @@ -44,19 +40,16 @@ std::string TemplateAssetList::RetrieveNameFromFile(const fs::path& file) const return assetInfo.Name; } -uuids::uuid TemplateAssetList::RetrieveUuidFromFile(const fs::path& file) const -{ +uuids::uuid TemplateAssetList::RetrieveUuidFromFile(const fs::path& file) const { return uuids::uuid::from_string(file.stem().string()); } -fs::path TemplateAssetList::RetrievePathFromAsset(const SavedAsset& asset) const -{ +fs::path TemplateAssetList::RetrievePathFromAsset(const SavedAsset& asset) const { auto fileName = uuids::to_string(asset.Uuid); return GetConnectedProject().GetTemplatePath(fileName); } -bool TemplateAssetList::SaveInstance(const SavedAsset& assetInfo, const Asset* asset) const -{ +bool TemplateAssetList::SaveInstance(const SavedAsset& assetInfo, const Asset* asset) const { auto path = RetrievePathFromAsset(assetInfo); auto res = DataArchive::SaveFile(path); if (!res) return false; @@ -71,8 +64,7 @@ bool TemplateAssetList::SaveInstance(const SavedAsset& assetInfo, const Asset* a return true; } -static std::unique_ptr<Template> LoadTemplateFromFile(const fs::path& path) -{ +static std::unique_ptr<Template> LoadTemplateFromFile(const fs::path& path) { auto res = DataArchive::LoadFile(path); if (!res) return nullptr; auto& stream = res.value(); @@ -87,19 +79,16 @@ static std::unique_ptr<Template> LoadTemplateFromFile(const fs::path& path) return tmpl; } -Template* TemplateAssetList::LoadInstance(const SavedAsset& assetInfo) const -{ +Template* TemplateAssetList::LoadInstance(const SavedAsset& assetInfo) const { return ::LoadTemplateFromFile(RetrievePathFromAsset(assetInfo)).release(); } -Template* TemplateAssetList::CreateInstance(const SavedAsset& assetInfo) const -{ +Template* TemplateAssetList::CreateInstance(const SavedAsset& assetInfo) const { auto kind = static_cast<Template::Kind>(assetInfo.Payload); return Template::CreateByKind(kind).release(); } -bool TemplateAssetList::RenameInstanceOnDisk(const SavedAsset& assetInfo, std::string_view oldName) const -{ +bool TemplateAssetList::RenameInstanceOnDisk(const SavedAsset& assetInfo, std::string_view oldName) const { // Get asset path, which is only dependent on UUID auto path = RetrievePathFromAsset(assetInfo); @@ -112,8 +101,7 @@ bool TemplateAssetList::RenameInstanceOnDisk(const SavedAsset& assetInfo, std::s return true; } -void TemplateAssetList::DisplayAssetCreator(ListState& state) -{ +void TemplateAssetList::DisplayAssetCreator(ListState& state) { auto ValidateNewName = [&]() -> void { if (mACNewName.empty()) { mACNewNameError = NameSelectionError::Empty; @@ -189,8 +177,7 @@ void TemplateAssetList::DisplayAssetCreator(ListState& state) } } -void TemplateAssetList::DisplayDetailsTable(ListState& state) const -{ +void TemplateAssetList::DisplayDetailsTable(ListState& state) const { ImGui::BeginTable("AssetDetailsTable", 2, ImGuiTableFlags_Borders); ImGui::TableSetupColumn(I18N_TEXT("Name", L10N_NAME)); diff --git a/app/source/Cplt/Model/Template/Template_RTTI.cpp b/app/source/Cplt/Model/Template/Template_RTTI.cpp index a96680b..40403ab 100644 --- a/app/source/Cplt/Model/Template/Template_RTTI.cpp +++ b/app/source/Cplt/Model/Template/Template_RTTI.cpp @@ -3,8 +3,7 @@ #include <Cplt/Model/Template/TableTemplate.hpp> #include <Cplt/Utils/I18n.hpp> -const char* Template::FormatKind(Kind kind) -{ +const char* Template::FormatKind(Kind kind) { switch (kind) { case KD_Table: return I18N_TEXT("Table template", L10N_TEMPLATE_TABLE); @@ -13,8 +12,7 @@ const char* Template::FormatKind(Kind kind) return ""; } -std::unique_ptr<Template> Template::CreateByKind(Kind kind) -{ +std::unique_ptr<Template> Template::CreateByKind(Kind kind) { switch (kind) { case KD_Table: return std::make_unique<TableTemplate>(); @@ -23,7 +21,6 @@ std::unique_ptr<Template> Template::CreateByKind(Kind kind) return nullptr; } -bool Template::IsInstance(const Template* tmpl) -{ +bool Template::IsInstance(const Template* tmpl) { return true; } diff --git a/app/source/Cplt/Model/Workflow/Evaluation.cpp b/app/source/Cplt/Model/Workflow/Evaluation.cpp index 7035bf9..fc5f661 100644 --- a/app/source/Cplt/Model/Workflow/Evaluation.cpp +++ b/app/source/Cplt/Model/Workflow/Evaluation.cpp @@ -2,16 +2,14 @@ #include <queue> -const char* WorkflowEvaluationError::FormatMessageType(enum MessageType messageType) -{ +const char* WorkflowEvaluationError::FormatMessageType(enum MessageType messageType) { switch (messageType) { case Error: return "Error"; case Warning: return "Warning"; } } -const char* WorkflowEvaluationError::FormatPinType(enum PinType pinType) -{ +const char* WorkflowEvaluationError::FormatPinType(enum PinType pinType) { switch (pinType) { case NoPin: return nullptr; case InputPin: return "Input pin"; @@ -19,8 +17,7 @@ const char* WorkflowEvaluationError::FormatPinType(enum PinType pinType) } } -std::string WorkflowEvaluationError::Format() const -{ +std::string WorkflowEvaluationError::Format() const { // TODO convert to std::format std::string result; @@ -39,10 +36,8 @@ std::string WorkflowEvaluationError::Format() const return result; } -struct WorkflowEvaluationContext::RuntimeNode -{ - enum EvaluationStatus - { +struct WorkflowEvaluationContext::RuntimeNode { + enum EvaluationStatus { ST_Unevaluated, ST_Success, ST_Failed, @@ -51,25 +46,21 @@ struct WorkflowEvaluationContext::RuntimeNode EvaluationStatus Status = ST_Unevaluated; }; -struct WorkflowEvaluationContext::RuntimeConnection -{ +struct WorkflowEvaluationContext::RuntimeConnection { std::unique_ptr<BaseValue> Value; - bool IsAvailableValue() const - { + bool IsAvailableValue() const { return Value != nullptr; } }; WorkflowEvaluationContext::WorkflowEvaluationContext(Workflow& workflow) - : mWorkflow{ &workflow } -{ + : mWorkflow{ &workflow } { mRuntimeNodes.resize(workflow.mNodes.size()); mRuntimeConnections.resize(workflow.mConnections.size()); } -BaseValue* WorkflowEvaluationContext::GetConnectionValue(size_t id, bool constant) -{ +BaseValue* WorkflowEvaluationContext::GetConnectionValue(size_t id, bool constant) { if (constant) { return mWorkflow->GetConstantById(id); } else { @@ -77,8 +68,7 @@ BaseValue* WorkflowEvaluationContext::GetConnectionValue(size_t id, bool constan } } -BaseValue* WorkflowEvaluationContext::GetConnectionValue(const WorkflowNode::InputPin& inputPin) -{ +BaseValue* WorkflowEvaluationContext::GetConnectionValue(const WorkflowNode::InputPin& inputPin) { if (inputPin.IsConnected()) { return GetConnectionValue(inputPin.Connection, inputPin.IsConstantConnection()); } else { @@ -86,20 +76,17 @@ BaseValue* WorkflowEvaluationContext::GetConnectionValue(const WorkflowNode::Inp } } -void WorkflowEvaluationContext::SetConnectionValue(size_t id, std::unique_ptr<BaseValue> value) -{ +void WorkflowEvaluationContext::SetConnectionValue(size_t id, std::unique_ptr<BaseValue> value) { mRuntimeConnections[id].Value = std::move(value); } -void WorkflowEvaluationContext::SetConnectionValue(const WorkflowNode::OutputPin& outputPin, std::unique_ptr<BaseValue> value) -{ +void WorkflowEvaluationContext::SetConnectionValue(const WorkflowNode::OutputPin& outputPin, std::unique_ptr<BaseValue> value) { if (outputPin.IsConnected()) { SetConnectionValue(outputPin.Connection, std::move(value)); } } -void WorkflowEvaluationContext::Run() -{ +void WorkflowEvaluationContext::Run() { int evaluatedCount = 0; int erroredCount = 0; @@ -129,8 +116,7 @@ void WorkflowEvaluationContext::Run() } } -void WorkflowEvaluationContext::ReportError(std::string message, const WorkflowNode& node, int pinId, bool inputPin) -{ +void WorkflowEvaluationContext::ReportError(std::string message, const WorkflowNode& node, int pinId, bool inputPin) { mErrors.push_back(WorkflowEvaluationError{ .Message = std::move(message), .NodeId = node.GetId(), @@ -140,8 +126,7 @@ void WorkflowEvaluationContext::ReportError(std::string message, const WorkflowN }); } -void WorkflowEvaluationContext::ReportError(std::string message, const WorkflowNode& node) -{ +void WorkflowEvaluationContext::ReportError(std::string message, const WorkflowNode& node) { mErrors.push_back(WorkflowEvaluationError{ .Message = std::move(message), .NodeId = node.GetId(), @@ -151,8 +136,7 @@ void WorkflowEvaluationContext::ReportError(std::string message, const WorkflowN }); } -void WorkflowEvaluationContext::ReportWarning(std::string message, const WorkflowNode& node, int pinId, bool inputPin) -{ +void WorkflowEvaluationContext::ReportWarning(std::string message, const WorkflowNode& node, int pinId, bool inputPin) { mErrors.push_back(WorkflowEvaluationError{ .Message = std::move(message), .NodeId = node.GetId(), @@ -162,8 +146,7 @@ void WorkflowEvaluationContext::ReportWarning(std::string message, const Workflo }); } -void WorkflowEvaluationContext::ReportWarning(std::string message, const WorkflowNode& node) -{ +void WorkflowEvaluationContext::ReportWarning(std::string message, const WorkflowNode& node) { mErrors.push_back(WorkflowEvaluationError{ .Message = std::move(message), .NodeId = node.GetId(), diff --git a/app/source/Cplt/Model/Workflow/Evaluation.hpp b/app/source/Cplt/Model/Workflow/Evaluation.hpp index 5b8c6cc..2cd0e53 100644 --- a/app/source/Cplt/Model/Workflow/Evaluation.hpp +++ b/app/source/Cplt/Model/Workflow/Evaluation.hpp @@ -7,17 +7,14 @@ #include <string> #include <vector> -class WorkflowEvaluationError -{ +class WorkflowEvaluationError { public: - enum MessageType : int16_t - { + enum MessageType : int16_t { Error, Warning, }; - enum PinType : int16_t - { + enum PinType : int16_t { NoPin, InputPin, OutputPin, @@ -37,8 +34,7 @@ public: std::string Format() const; }; -class WorkflowEvaluationContext -{ +class WorkflowEvaluationContext { private: struct RuntimeNode; struct RuntimeConnection; diff --git a/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.cpp b/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.cpp index df4a8bb..202f8cf 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.cpp +++ b/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.cpp @@ -3,16 +3,13 @@ #include <Cplt/Model/Workflow/Evaluation.hpp> #include <Cplt/Model/Workflow/Values/Basic.hpp> -bool DocumentTemplateExpansionNode::IsInstance(const WorkflowNode* node) -{ +bool DocumentTemplateExpansionNode::IsInstance(const WorkflowNode* node) { return node->GetKind() == KD_DocumentTemplateExpansion; } DocumentTemplateExpansionNode::DocumentTemplateExpansionNode() - : WorkflowNode(KD_DocumentTemplateExpansion, false) -{ + : WorkflowNode(KD_DocumentTemplateExpansion, false) { } -void DocumentTemplateExpansionNode::Evaluate(WorkflowEvaluationContext& ctx) -{ +void DocumentTemplateExpansionNode::Evaluate(WorkflowEvaluationContext& ctx) { } diff --git a/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.hpp b/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.hpp index a266b2c..2a49a91 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.hpp +++ b/app/source/Cplt/Model/Workflow/Nodes/DocumentNodes.hpp @@ -2,8 +2,7 @@ #include <Cplt/Model/Workflow/Workflow.hpp> -class DocumentTemplateExpansionNode : public WorkflowNode -{ +class DocumentTemplateExpansionNode : public WorkflowNode { public: static bool IsInstance(const WorkflowNode* node); DocumentTemplateExpansionNode(); diff --git a/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.cpp b/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.cpp index f8b29bb..8a47423 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.cpp +++ b/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.cpp @@ -9,8 +9,7 @@ #include <cassert> #include <utility> -WorkflowNode::Kind NumericOperationNode::OperationTypeToNodeKind(OperationType type) -{ +WorkflowNode::Kind NumericOperationNode::OperationTypeToNodeKind(OperationType type) { switch (type) { case Addition: return KD_NumericAddition; case Subtraction: return KD_NumericSubtraction; @@ -20,8 +19,7 @@ WorkflowNode::Kind NumericOperationNode::OperationTypeToNodeKind(OperationType t } } -NumericOperationNode::OperationType NumericOperationNode::NodeKindToOperationType(Kind kind) -{ +NumericOperationNode::OperationType NumericOperationNode::NodeKindToOperationType(Kind kind) { switch (kind) { case KD_NumericAddition: return Addition; case KD_NumericSubtraction: return Subtraction; @@ -31,15 +29,13 @@ NumericOperationNode::OperationType NumericOperationNode::NodeKindToOperationTyp } } -bool NumericOperationNode::IsInstance(const WorkflowNode* node) -{ +bool NumericOperationNode::IsInstance(const WorkflowNode* node) { return node->GetKind() >= KD_NumericAddition && node->GetKind() <= KD_NumericDivision; } NumericOperationNode::NumericOperationNode(OperationType type) : WorkflowNode(OperationTypeToNodeKind(type), false) - , mType{ type } -{ + , mType{ type } { mInputs.resize(2); mInputs[0].MatchingType = BaseValue::KD_Numeric; mInputs[1].MatchingType = BaseValue::KD_Numeric; @@ -48,8 +44,7 @@ NumericOperationNode::NumericOperationNode(OperationType type) mOutputs[0].MatchingType = BaseValue::KD_Numeric; } -void NumericOperationNode::Evaluate(WorkflowEvaluationContext& ctx) -{ +void NumericOperationNode::Evaluate(WorkflowEvaluationContext& ctx) { auto lhsVal = dyn_cast<NumericValue>(ctx.GetConnectionValue(mInputs[0])); if (!lhsVal) return; double lhs = lhsVal->GetValue(); @@ -79,16 +74,13 @@ void NumericOperationNode::Evaluate(WorkflowEvaluationContext& ctx) ctx.SetConnectionValue(mOutputs[0], std::move(value)); } -bool NumericExpressionNode::IsInstance(const WorkflowNode* node) -{ +bool NumericExpressionNode::IsInstance(const WorkflowNode* node) { return node->GetKind() == KD_NumericExpression; } NumericExpressionNode::NumericExpressionNode() - : WorkflowNode(KD_NumericExpression, false) -{ + : WorkflowNode(KD_NumericExpression, false) { } -void NumericExpressionNode::Evaluate(WorkflowEvaluationContext& ctx) -{ +void NumericExpressionNode::Evaluate(WorkflowEvaluationContext& ctx) { } diff --git a/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.hpp b/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.hpp index 3c89708..0d3120b 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.hpp +++ b/app/source/Cplt/Model/Workflow/Nodes/NumericNodes.hpp @@ -7,11 +7,9 @@ #include <variant> #include <vector> -class NumericOperationNode : public WorkflowNode -{ +class NumericOperationNode : public WorkflowNode { public: - enum OperationType - { + enum OperationType { Addition, Subtraction, Multiplication, @@ -33,8 +31,7 @@ public: virtual void Evaluate(WorkflowEvaluationContext& ctx) override; }; -class NumericExpressionNode : public WorkflowNode -{ +class NumericExpressionNode : public WorkflowNode { public: static bool IsInstance(const WorkflowNode* node); NumericExpressionNode(); diff --git a/app/source/Cplt/Model/Workflow/Nodes/TextNodes.cpp b/app/source/Cplt/Model/Workflow/Nodes/TextNodes.cpp index 9b31f7a..4bca0c8 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/TextNodes.cpp +++ b/app/source/Cplt/Model/Workflow/Nodes/TextNodes.cpp @@ -11,12 +11,10 @@ #include <variant> #include <vector> -class TextFormatterNode::Impl -{ +class TextFormatterNode::Impl { public: template <class TFunction> - static void ForArguments(std::vector<Element>::iterator begin, std::vector<Element>::iterator end, const TFunction& func) - { + static void ForArguments(std::vector<Element>::iterator begin, std::vector<Element>::iterator end, const TFunction& func) { for (auto it = begin; it != end; ++it) { auto& elm = *it; if (auto arg = std::get_if<Argument>(&elm)) { @@ -26,8 +24,7 @@ public: } /// Find the pin index that the \c elmIdx -th element should have, based on the elements coming before it. - static int FindPinForElement(const std::vector<Element>& vec, int elmIdx) - { + static int FindPinForElement(const std::vector<Element>& vec, int elmIdx) { for (int i = elmIdx; i >= 0; --i) { auto& elm = vec[i]; if (auto arg = std::get_if<Argument>(&elm)) { @@ -38,8 +35,7 @@ public: } }; -BaseValue::Kind TextFormatterNode::ArgumentTypeToValueKind(TextFormatterNode::ArgumentType arg) -{ +BaseValue::Kind TextFormatterNode::ArgumentTypeToValueKind(TextFormatterNode::ArgumentType arg) { switch (arg) { case NumericArgument: return BaseValue::KD_Numeric; case TextArgument: return BaseValue::KD_Text; @@ -47,28 +43,23 @@ BaseValue::Kind TextFormatterNode::ArgumentTypeToValueKind(TextFormatterNode::Ar } } -bool TextFormatterNode::IsInstance(const WorkflowNode* node) -{ +bool TextFormatterNode::IsInstance(const WorkflowNode* node) { return node->GetKind() == KD_TextFormatting; } TextFormatterNode::TextFormatterNode() - : WorkflowNode(KD_TextFormatting, false) -{ + : WorkflowNode(KD_TextFormatting, false) { } -int TextFormatterNode::GetElementCount() const -{ +int TextFormatterNode::GetElementCount() const { return mElements.size(); } -const TextFormatterNode::Element& TextFormatterNode::GetElement(int idx) const -{ +const TextFormatterNode::Element& TextFormatterNode::GetElement(int idx) const { return mElements[idx]; } -void TextFormatterNode::SetElement(int idx, std::string text) -{ +void TextFormatterNode::SetElement(int idx, std::string text) { assert(idx >= 0 && idx < mElements.size()); std::visit( @@ -82,8 +73,7 @@ void TextFormatterNode::SetElement(int idx, std::string text) mElements[idx] = std::move(text); } -void TextFormatterNode::SetElement(int idx, ArgumentType argument) -{ +void TextFormatterNode::SetElement(int idx, ArgumentType argument) { assert(idx >= 0 && idx < mElements.size()); std::visit( @@ -115,8 +105,7 @@ void TextFormatterNode::SetElement(int idx, ArgumentType argument) mElements[idx]); } -void TextFormatterNode::InsertElement(int idx, std::string text) -{ +void TextFormatterNode::InsertElement(int idx, std::string text) { assert(idx >= 0); if (idx >= mElements.size()) AppendElement(std::move(text)); @@ -124,8 +113,7 @@ void TextFormatterNode::InsertElement(int idx, std::string text) mElements.insert(mElements.begin() + idx, std::move(text)); } -void TextFormatterNode::InsertElement(int idx, ArgumentType argument) -{ +void TextFormatterNode::InsertElement(int idx, ArgumentType argument) { assert(idx >= 0); if (idx >= mElements.size()) AppendElement(argument); @@ -144,14 +132,12 @@ void TextFormatterNode::InsertElement(int idx, ArgumentType argument) }); } -void TextFormatterNode::AppendElement(std::string text) -{ +void TextFormatterNode::AppendElement(std::string text) { mMinOutputChars += text.size(); mElements.push_back(std::move(text)); } -void TextFormatterNode::AppendElement(ArgumentType argument) -{ +void TextFormatterNode::AppendElement(ArgumentType argument) { int pinIdx = mInputs.size(); // Create pin mInputs.push_back(InputPin{}); @@ -163,8 +149,7 @@ void TextFormatterNode::AppendElement(ArgumentType argument) }); } -void TextFormatterNode::RemoveElement(int idx) -{ +void TextFormatterNode::RemoveElement(int idx) { assert(idx >= 0 && idx < mElements.size()); PreRemoveElement(idx); @@ -174,8 +159,7 @@ void TextFormatterNode::RemoveElement(int idx) mElements.erase(mElements.begin() + idx); } -void TextFormatterNode::Evaluate(WorkflowEvaluationContext& ctx) -{ +void TextFormatterNode::Evaluate(WorkflowEvaluationContext& ctx) { std::string result; result.reserve((size_t)(mMinOutputChars * 1.5f)); @@ -216,8 +200,7 @@ void TextFormatterNode::Evaluate(WorkflowEvaluationContext& ctx) } } -void TextFormatterNode::PreRemoveElement(int idx) -{ +void TextFormatterNode::PreRemoveElement(int idx) { auto& elm = mElements[idx]; if (auto arg = std::get_if<Argument>(&elm)) { RemoveInputPin(arg->PinIdx); diff --git a/app/source/Cplt/Model/Workflow/Nodes/TextNodes.hpp b/app/source/Cplt/Model/Workflow/Nodes/TextNodes.hpp index 4689931..56eb19b 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/TextNodes.hpp +++ b/app/source/Cplt/Model/Workflow/Nodes/TextNodes.hpp @@ -7,11 +7,9 @@ #include <variant> #include <vector> -class TextFormatterNode : public WorkflowNode -{ +class TextFormatterNode : public WorkflowNode { public: - enum ArgumentType - { + enum ArgumentType { NumericArgument, TextArgument, DateTimeArgument, @@ -20,8 +18,7 @@ public: private: class Impl; - struct Argument - { + struct Argument { ArgumentType Type; int PinIdx; }; diff --git a/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.cpp b/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.cpp index 93d458c..4b56052 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.cpp +++ b/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.cpp @@ -3,30 +3,24 @@ #include <Cplt/Model/Workflow/Evaluation.hpp> #include <Cplt/Model/Workflow/Values/Basic.hpp> -bool FormInputNode::IsInstance(const WorkflowNode* node) -{ +bool FormInputNode::IsInstance(const WorkflowNode* node) { return node->GetKind() == KD_FormInput; } FormInputNode::FormInputNode() - : WorkflowNode(KD_FormInput, false) -{ + : WorkflowNode(KD_FormInput, false) { } -void FormInputNode::Evaluate(WorkflowEvaluationContext& ctx) -{ +void FormInputNode::Evaluate(WorkflowEvaluationContext& ctx) { } -bool DatabaseRowsInputNode::IsInstance(const WorkflowNode* node) -{ +bool DatabaseRowsInputNode::IsInstance(const WorkflowNode* node) { return node->GetKind() == KD_DatabaseRowsInput; } DatabaseRowsInputNode::DatabaseRowsInputNode() - : WorkflowNode(KD_DatabaseRowsInput, false) -{ + : WorkflowNode(KD_DatabaseRowsInput, false) { } -void DatabaseRowsInputNode::Evaluate(WorkflowEvaluationContext& ctx) -{ +void DatabaseRowsInputNode::Evaluate(WorkflowEvaluationContext& ctx) { } diff --git a/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.hpp b/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.hpp index f0b923c..4ad4b02 100644 --- a/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.hpp +++ b/app/source/Cplt/Model/Workflow/Nodes/UserInputNodes.hpp @@ -2,8 +2,7 @@ #include <Cplt/Model/Workflow/Workflow.hpp> -class FormInputNode : public WorkflowNode -{ +class FormInputNode : public WorkflowNode { public: static bool IsInstance(const WorkflowNode* node); FormInputNode(); @@ -12,8 +11,7 @@ public: virtual void Evaluate(WorkflowEvaluationContext& ctx) override; }; -class DatabaseRowsInputNode : public WorkflowNode -{ +class DatabaseRowsInputNode : public WorkflowNode { public: static bool IsInstance(const WorkflowNode* node); DatabaseRowsInputNode(); diff --git a/app/source/Cplt/Model/Workflow/Value.hpp b/app/source/Cplt/Model/Workflow/Value.hpp index 70fcb57..8e39358 100644 --- a/app/source/Cplt/Model/Workflow/Value.hpp +++ b/app/source/Cplt/Model/Workflow/Value.hpp @@ -8,11 +8,9 @@ #include <string> #include <vector> -class BaseValue -{ +class BaseValue { public: - enum Kind - { + enum Kind { KD_Numeric, KD_Text, KD_DateTime, @@ -30,8 +28,7 @@ public: KindCount = InvalidKind, }; - struct KindInfo - { + struct KindInfo { ImGui::IconType PinIcon; RgbaColor PinColor; }; @@ -64,11 +61,9 @@ public: virtual void WriteTo(std::ostream& stream); }; -class BaseObjectDescription -{ +class BaseObjectDescription { public: - struct Property - { + struct Property { std::string Name; BaseValue::Kind Kind; bool Mutatable = true; @@ -78,8 +73,7 @@ public: std::vector<Property> Properties; }; -class BaseObjectValue : public BaseValue -{ +class BaseObjectValue : public BaseValue { public: /// \param kind A value kind enum, within the range of KD_BaseObject and KD_BaseObjectLast (both inclusive). static const BaseObjectDescription& QueryObjectInfo(Kind kind); diff --git a/app/source/Cplt/Model/Workflow/Value_Main.cpp b/app/source/Cplt/Model/Workflow/Value_Main.cpp index ca972c4..ab78b86 100644 --- a/app/source/Cplt/Model/Workflow/Value_Main.cpp +++ b/app/source/Cplt/Model/Workflow/Value_Main.cpp @@ -1,35 +1,28 @@ #include "Value.hpp" BaseValue::BaseValue(Kind kind) - : mKind{ kind } -{ + : mKind{ kind } { } -BaseValue::Kind BaseValue::GetKind() const -{ +BaseValue::Kind BaseValue::GetKind() const { return mKind; } -bool BaseValue::SupportsConstant() const -{ +bool BaseValue::SupportsConstant() const { return false; } -void BaseValue::ReadFrom(std::istream& stream) -{ +void BaseValue::ReadFrom(std::istream& stream) { } -void BaseValue::WriteTo(std::ostream& stream) -{ +void BaseValue::WriteTo(std::ostream& stream) { } BaseObjectValue::BaseObjectValue(Kind kind) - : BaseValue(kind) -{ + : BaseValue(kind) { assert(kind >= KD_BaseObject && kind <= KD_BaseObjectLast); } -const BaseObjectDescription& BaseObjectValue::GetObjectDescription() const -{ +const BaseObjectDescription& BaseObjectValue::GetObjectDescription() const { return QueryObjectInfo(this->GetKind()); } diff --git a/app/source/Cplt/Model/Workflow/Value_RTTI.cpp b/app/source/Cplt/Model/Workflow/Value_RTTI.cpp index a2a6960..b075b12 100644 --- a/app/source/Cplt/Model/Workflow/Value_RTTI.cpp +++ b/app/source/Cplt/Model/Workflow/Value_RTTI.cpp @@ -52,8 +52,7 @@ constexpr BaseValue::KindInfo kObjectInfo{ .PinColor = RgbaColor(161, 161, 161), }; -const BaseValue::KindInfo& BaseValue::QueryInfo(BaseValue::Kind kind) -{ +const BaseValue::KindInfo& BaseValue::QueryInfo(BaseValue::Kind kind) { switch (kind) { case KD_Numeric: return kNumericInfo; case KD_Text: return kTextInfo; @@ -72,8 +71,7 @@ const BaseValue::KindInfo& BaseValue::QueryInfo(BaseValue::Kind kind) return kEmptyInfo; } -const char* BaseValue::Format(Kind kind) -{ +const char* BaseValue::Format(Kind kind) { switch (kind) { case KD_Numeric: return I18N_TEXT("Numeric", L10N_VALUE_NUMERIC); case KD_Text: return I18N_TEXT("Text", L10N_VALUE_TEXT); @@ -91,8 +89,7 @@ const char* BaseValue::Format(Kind kind) return ""; } -std::unique_ptr<BaseValue> BaseValue::CreateByKind(BaseValue::Kind kind) -{ +std::unique_ptr<BaseValue> BaseValue::CreateByKind(BaseValue::Kind kind) { switch (kind) { case KD_Numeric: return std::make_unique<NumericValue>(); case KD_Text: return std::make_unique<TextValue>(); @@ -110,8 +107,7 @@ std::unique_ptr<BaseValue> BaseValue::CreateByKind(BaseValue::Kind kind) return nullptr; } -bool BaseValue::IsInstance(const BaseValue* value) -{ +bool BaseValue::IsInstance(const BaseValue* value) { return true; } @@ -155,8 +151,7 @@ const BaseObjectDescription kPurchaseDbRowObject{ }, }; -const BaseObjectDescription& BaseObjectValue::QueryObjectInfo(Kind kind) -{ +const BaseObjectDescription& BaseObjectValue::QueryObjectInfo(Kind kind) { switch (kind) { case KD_BaseObject: return kEmptyObjectInfo; case KD_SaleDatabaseRow: return kSaleDbRowObject; @@ -167,8 +162,7 @@ const BaseObjectDescription& BaseObjectValue::QueryObjectInfo(Kind kind) return kEmptyObjectInfo; } -bool BaseObjectValue::IsInstance(const BaseValue* value) -{ +bool BaseObjectValue::IsInstance(const BaseValue* value) { return value->GetKind() >= KD_BaseObject && value->GetKind() <= KD_BaseObjectLast; } diff --git a/app/source/Cplt/Model/Workflow/Values/Basic.cpp b/app/source/Cplt/Model/Workflow/Values/Basic.cpp index 198387c..a480e2f 100644 --- a/app/source/Cplt/Model/Workflow/Values/Basic.cpp +++ b/app/source/Cplt/Model/Workflow/Values/Basic.cpp @@ -4,19 +4,16 @@ #include <cmath> #include <limits> -bool NumericValue::IsInstance(const BaseValue* value) -{ +bool NumericValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_Numeric; } NumericValue::NumericValue() - : BaseValue(BaseValue::KD_Numeric) -{ + : BaseValue(BaseValue::KD_Numeric) { } template <class T, int kMaxSize> -static std::string NumberToString(T value) -{ +static std::string NumberToString(T value) { char buf[kMaxSize]; auto res = std::to_chars(buf, buf + kMaxSize, value); if (res.ec == std::errc()) { @@ -26,71 +23,58 @@ static std::string NumberToString(T value) } } -std::string NumericValue::GetTruncatedString() const -{ +std::string NumericValue::GetTruncatedString() const { constexpr auto kMaxSize = std::numeric_limits<int64_t>::digits10; return ::NumberToString<int64_t, kMaxSize>((int64_t)mValue); } -std::string NumericValue::GetRoundedString() const -{ +std::string NumericValue::GetRoundedString() const { constexpr auto kMaxSize = std::numeric_limits<int64_t>::digits10; return ::NumberToString<int64_t, kMaxSize>((int64_t)std::round(mValue)); } -std::string NumericValue::GetString() const -{ +std::string NumericValue::GetString() const { constexpr auto kMaxSize = std::numeric_limits<double>::max_digits10; return ::NumberToString<double, kMaxSize>(mValue); } -int64_t NumericValue::GetInt() const -{ +int64_t NumericValue::GetInt() const { return static_cast<int64_t>(mValue); } -double NumericValue::GetValue() const -{ +double NumericValue::GetValue() const { return mValue; } -void NumericValue::SetValue(double value) -{ +void NumericValue::SetValue(double value) { mValue = value; } -bool TextValue::IsInstance(const BaseValue* value) -{ +bool TextValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_Text; } TextValue::TextValue() - : BaseValue(BaseValue::KD_Text) -{ + : BaseValue(BaseValue::KD_Text) { } -const std::string& TextValue::GetValue() const -{ +const std::string& TextValue::GetValue() const { return mValue; } -void TextValue::SetValue(const std::string& value) -{ +void TextValue::SetValue(const std::string& value) { mValue = value; } -bool DateTimeValue::IsInstance(const BaseValue* value) -{ +bool DateTimeValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_DateTime; } DateTimeValue::DateTimeValue() - : BaseValue(BaseValue::KD_DateTime) -{ + : BaseValue(BaseValue::KD_DateTime) { } -std::string DateTimeValue::GetString() const -{ +std::string DateTimeValue::GetString() const { namespace chrono = std::chrono; auto t = chrono::system_clock::to_time_t(mValue); @@ -100,12 +84,10 @@ std::string DateTimeValue::GetString() const return std::string(data); } -const std::chrono::time_point<std::chrono::system_clock>& DateTimeValue::GetValue() const -{ +const std::chrono::time_point<std::chrono::system_clock>& DateTimeValue::GetValue() const { return mValue; } -void DateTimeValue::SetValue(const std::chrono::time_point<std::chrono::system_clock>& value) -{ +void DateTimeValue::SetValue(const std::chrono::time_point<std::chrono::system_clock>& value) { mValue = value; } diff --git a/app/source/Cplt/Model/Workflow/Values/Basic.hpp b/app/source/Cplt/Model/Workflow/Values/Basic.hpp index 820fb13..65d2100 100644 --- a/app/source/Cplt/Model/Workflow/Values/Basic.hpp +++ b/app/source/Cplt/Model/Workflow/Values/Basic.hpp @@ -6,8 +6,7 @@ #include <cstdint> #include <string> -class NumericValue : public BaseValue -{ +class NumericValue : public BaseValue { private: double mValue; @@ -29,8 +28,7 @@ public: void SetValue(double value); }; -class TextValue : public BaseValue -{ +class TextValue : public BaseValue { private: std::string mValue; @@ -47,8 +45,7 @@ public: void SetValue(const std::string& value); }; -class DateTimeValue : public BaseValue -{ +class DateTimeValue : public BaseValue { private: std::chrono::time_point<std::chrono::system_clock> mValue; diff --git a/app/source/Cplt/Model/Workflow/Values/Database.cpp b/app/source/Cplt/Model/Workflow/Values/Database.cpp index 25b77e9..25487f3 100644 --- a/app/source/Cplt/Model/Workflow/Values/Database.cpp +++ b/app/source/Cplt/Model/Workflow/Values/Database.cpp @@ -5,40 +5,33 @@ #include <limits> -TableKind DatabaseRowIdValue::GetTable() const -{ +TableKind DatabaseRowIdValue::GetTable() const { return mTable; } -int64_t DatabaseRowIdValue::GetRowId() const -{ +int64_t DatabaseRowIdValue::GetRowId() const { return mRowId; } -bool DatabaseRowIdValue::IsInstance(const BaseValue* value) -{ +bool DatabaseRowIdValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_DatabaseRowId; } DatabaseRowIdValue::DatabaseRowIdValue() : BaseValue(KD_DatabaseRowId) , mTable{ TableKind::Sales } - , mRowId{ std::numeric_limits<int64_t>::max() } -{ + , mRowId{ std::numeric_limits<int64_t>::max() } { } -bool SaleDatabaseRowValue::IsInstance(const BaseValue* value) -{ +bool SaleDatabaseRowValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_SaleDatabaseRow; } SaleDatabaseRowValue::SaleDatabaseRowValue() - : BaseObjectValue(KD_SaleDatabaseRow) -{ + : BaseObjectValue(KD_SaleDatabaseRow) { } -const BaseValue* SaleDatabaseRowValue::GetProperty(int idx) const -{ +const BaseValue* SaleDatabaseRowValue::GetProperty(int idx) const { switch (idx) { case 0: return &mCustomerName; case 1: return &mDeadline; @@ -47,8 +40,7 @@ const BaseValue* SaleDatabaseRowValue::GetProperty(int idx) const } } -bool SaleDatabaseRowValue::SetProperty(int idx, std::unique_ptr<BaseValue> value) -{ +bool SaleDatabaseRowValue::SetProperty(int idx, std::unique_ptr<BaseValue> value) { switch (idx) { case 0: return false; case 1: CHECK_VALUE_TYPE_AND_MOVE(DateTimeValue, mDeadline, value.get()); break; @@ -57,18 +49,15 @@ bool SaleDatabaseRowValue::SetProperty(int idx, std::unique_ptr<BaseValue> value return true; } -bool PurchaseDatabaseRowValue::IsInstance(const BaseValue* value) -{ +bool PurchaseDatabaseRowValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_PurchaseDatabaseRow; } PurchaseDatabaseRowValue::PurchaseDatabaseRowValue() - : BaseObjectValue(KD_PurchaseDatabaseRow) -{ + : BaseObjectValue(KD_PurchaseDatabaseRow) { } -const BaseValue* PurchaseDatabaseRowValue::GetProperty(int idx) const -{ +const BaseValue* PurchaseDatabaseRowValue::GetProperty(int idx) const { switch (idx) { case 0: return &mFactoryName; case 1: return &mOrderTime; @@ -77,8 +66,7 @@ const BaseValue* PurchaseDatabaseRowValue::GetProperty(int idx) const } } -bool PurchaseDatabaseRowValue::SetProperty(int idx, std::unique_ptr<BaseValue> value) -{ +bool PurchaseDatabaseRowValue::SetProperty(int idx, std::unique_ptr<BaseValue> value) { switch (idx) { case 0: return false; case 1: CHECK_VALUE_TYPE_AND_MOVE(DateTimeValue, mOrderTime, value.get()); break; diff --git a/app/source/Cplt/Model/Workflow/Values/Database.hpp b/app/source/Cplt/Model/Workflow/Values/Database.hpp index f1c1571..cacbb1a 100644 --- a/app/source/Cplt/Model/Workflow/Values/Database.hpp +++ b/app/source/Cplt/Model/Workflow/Values/Database.hpp @@ -4,8 +4,7 @@ #include <Cplt/Model/Workflow/Values/Basic.hpp> #include <Cplt/fwd.hpp> -class DatabaseRowIdValue : public BaseValue -{ +class DatabaseRowIdValue : public BaseValue { private: TableKind mTable; int64_t mRowId; @@ -18,8 +17,7 @@ public: int64_t GetRowId() const; }; -class SaleDatabaseRowValue : public BaseObjectValue -{ +class SaleDatabaseRowValue : public BaseObjectValue { private: int mCustomerId; TextValue mCustomerName; @@ -34,8 +32,7 @@ public: virtual bool SetProperty(int idx, std::unique_ptr<BaseValue> value); }; -class PurchaseDatabaseRowValue : public BaseObjectValue -{ +class PurchaseDatabaseRowValue : public BaseObjectValue { private: int mFactoryId; TextValue mFactoryName; diff --git a/app/source/Cplt/Model/Workflow/Values/Dictionary.cpp b/app/source/Cplt/Model/Workflow/Values/Dictionary.cpp index 97bf509..718a0c8 100644 --- a/app/source/Cplt/Model/Workflow/Values/Dictionary.cpp +++ b/app/source/Cplt/Model/Workflow/Values/Dictionary.cpp @@ -2,23 +2,19 @@ #include <Cplt/Utils/Macros.hpp> -bool DictionaryValue::IsInstance(const BaseValue* value) -{ +bool DictionaryValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_Dictionary; } DictionaryValue::DictionaryValue() - : BaseValue(KD_Dictionary) -{ + : BaseValue(KD_Dictionary) { } -int DictionaryValue::GetCount() const -{ +int DictionaryValue::GetCount() const { return mElements.size(); } -BaseValue* DictionaryValue::Find(std::string_view key) -{ +BaseValue* DictionaryValue::Find(std::string_view key) { auto iter = mElements.find(key); if (iter != mElements.end()) { return iter.value().get(); @@ -27,8 +23,7 @@ BaseValue* DictionaryValue::Find(std::string_view key) } } -BaseValue* DictionaryValue::Insert(std::string_view key, std::unique_ptr<BaseValue>& value) -{ +BaseValue* DictionaryValue::Insert(std::string_view key, std::unique_ptr<BaseValue>& value) { auto [iter, success] = mElements.insert(key, std::move(value)); if (success) { return iter.value().get(); @@ -37,13 +32,11 @@ BaseValue* DictionaryValue::Insert(std::string_view key, std::unique_ptr<BaseVal } } -BaseValue& DictionaryValue::InsertOrReplace(std::string_view key, std::unique_ptr<BaseValue> value) -{ +BaseValue& DictionaryValue::InsertOrReplace(std::string_view key, std::unique_ptr<BaseValue> value) { auto [iter, DISCARD] = mElements.emplace(key, std::move(value)); return *iter.value(); } -void DictionaryValue::Remove(std::string_view key) -{ +void DictionaryValue::Remove(std::string_view key) { mElements.erase(mElements.find(key)); } diff --git a/app/source/Cplt/Model/Workflow/Values/Dictionary.hpp b/app/source/Cplt/Model/Workflow/Values/Dictionary.hpp index 6eff308..f14e04f 100644 --- a/app/source/Cplt/Model/Workflow/Values/Dictionary.hpp +++ b/app/source/Cplt/Model/Workflow/Values/Dictionary.hpp @@ -7,8 +7,7 @@ #include <string> #include <string_view> -class DictionaryValue : public BaseValue -{ +class DictionaryValue : public BaseValue { private: tsl::array_map<char, std::unique_ptr<BaseValue>> mElements; diff --git a/app/source/Cplt/Model/Workflow/Values/List.cpp b/app/source/Cplt/Model/Workflow/Values/List.cpp index 9fd6bfd..e274344 100644 --- a/app/source/Cplt/Model/Workflow/Values/List.cpp +++ b/app/source/Cplt/Model/Workflow/Values/List.cpp @@ -2,99 +2,80 @@ #include <utility> -BaseValue* ListValue::Iterator::operator*() const -{ +BaseValue* ListValue::Iterator::operator*() const { return mIter->get(); } -BaseValue* ListValue::Iterator::operator->() const -{ +BaseValue* ListValue::Iterator::operator->() const { return mIter->get(); } -ListValue::Iterator& ListValue::Iterator::operator++() -{ +ListValue::Iterator& ListValue::Iterator::operator++() { ++mIter; return *this; } -ListValue::Iterator ListValue::Iterator::operator++(int) const -{ +ListValue::Iterator ListValue::Iterator::operator++(int) const { return Iterator(mIter + 1); } -ListValue::Iterator& ListValue::Iterator::operator--() -{ +ListValue::Iterator& ListValue::Iterator::operator--() { --mIter; return *this; } -ListValue::Iterator ListValue::Iterator::operator--(int) const -{ +ListValue::Iterator ListValue::Iterator::operator--(int) const { return Iterator(mIter - 1); } -bool operator==(const ListValue::Iterator& a, const ListValue::Iterator& b) -{ +bool operator==(const ListValue::Iterator& a, const ListValue::Iterator& b) { return a.mIter == b.mIter; } ListValue::Iterator::Iterator(decltype(mIter) iter) - : mIter{ iter } -{ + : mIter{ iter } { } -bool ListValue::IsInstance(const BaseValue* value) -{ +bool ListValue::IsInstance(const BaseValue* value) { return value->GetKind() == KD_List; } ListValue::ListValue() - : BaseValue(KD_List) -{ + : BaseValue(KD_List) { } -int ListValue::GetCount() const -{ +int ListValue::GetCount() const { return mElements.size(); } -BaseValue* ListValue::GetElement(int i) const -{ +BaseValue* ListValue::GetElement(int i) const { return mElements[i].get(); } -void ListValue::Append(std::unique_ptr<BaseValue> element) -{ +void ListValue::Append(std::unique_ptr<BaseValue> element) { mElements.push_back(std::move(element)); } -void ListValue::Insert(int i, std::unique_ptr<BaseValue> element) -{ +void ListValue::Insert(int i, std::unique_ptr<BaseValue> element) { mElements.insert(mElements.begin() + i, std::move(element)); } -void ListValue::Insert(Iterator iter, std::unique_ptr<BaseValue> element) -{ +void ListValue::Insert(Iterator iter, std::unique_ptr<BaseValue> element) { mElements.insert(iter.mIter, std::move(element)); } -void ListValue::Remove(int i) -{ +void ListValue::Remove(int i) { mElements.erase(mElements.begin() + i); } -void ListValue::Remove(Iterator iter) -{ +void ListValue::Remove(Iterator iter) { mElements.erase(iter.mIter); } -ListValue::Iterator ListValue::begin() -{ +ListValue::Iterator ListValue::begin() { return Iterator(mElements.begin()); } -ListValue::Iterator ListValue::end() -{ +ListValue::Iterator ListValue::end() { return Iterator(mElements.end()); } diff --git a/app/source/Cplt/Model/Workflow/Values/List.hpp b/app/source/Cplt/Model/Workflow/Values/List.hpp index cc8e061..36f71a1 100644 --- a/app/source/Cplt/Model/Workflow/Values/List.hpp +++ b/app/source/Cplt/Model/Workflow/Values/List.hpp @@ -5,11 +5,9 @@ #include <memory> #include <vector> -class ListValue : public BaseValue -{ +class ListValue : public BaseValue { public: - class Iterator - { + class Iterator { private: std::vector<std::unique_ptr<BaseValue>>::iterator mIter; diff --git a/app/source/Cplt/Model/Workflow/Workflow.hpp b/app/source/Cplt/Model/Workflow/Workflow.hpp index e075e3c..bc75121 100644 --- a/app/source/Cplt/Model/Workflow/Workflow.hpp +++ b/app/source/Cplt/Model/Workflow/Workflow.hpp @@ -20,8 +20,7 @@ namespace ImNodes = ax::NodeEditor; -class WorkflowConnection -{ +class WorkflowConnection { public: static constexpr auto kInvalidId = std::numeric_limits<uint32_t>::max(); @@ -44,21 +43,18 @@ public: void WriteTo(std::ostream& stream) const; }; -class WorkflowNode -{ +class WorkflowNode { public: static constexpr auto kInvalidId = std::numeric_limits<uint32_t>::max(); static constexpr auto kInvalidPinId = std::numeric_limits<uint32_t>::max(); - enum Type - { + enum Type { InputType, TransformType, OutputType, }; - enum Kind - { + enum Kind { KD_NumericAddition, KD_NumericSubtraction, KD_NumericMultiplication, @@ -73,8 +69,7 @@ public: KindCount = InvalidKind, }; - enum Category - { + enum Category { CG_Numeric, CG_Text, CG_Document, @@ -86,8 +81,7 @@ public: CategoryCount = InvalidCategory, }; - struct InputPin - { + struct InputPin { uint32_t Connection = WorkflowConnection::kInvalidId; BaseValue::Kind MatchingType = BaseValue::InvalidKind; bool ConnectionToConst = false; @@ -98,8 +92,7 @@ public: BaseValue::Kind GetMatchingType() const; }; - struct OutputPin - { + struct OutputPin { uint32_t Connection = WorkflowConnection::kInvalidId; BaseValue::Kind MatchingType = BaseValue::InvalidKind; @@ -191,8 +184,7 @@ protected: void OnDetach(); }; -class Workflow : public Asset -{ +class Workflow : public Asset { friend class WorkflowNode; friend class WorkflowEvaluationContext; class Private; @@ -227,8 +219,7 @@ public: WorkflowNode* GetNodeByNodeId(ImNodes::NodeId nodeId); BaseValue* GetConstantById(uint32_t id); - struct GlobalPinId - { + struct GlobalPinId { WorkflowNode* Node; uint32_t PinId; /// true => input pin @@ -256,8 +247,7 @@ public: /* Graph rebuild */ - enum GraphUpdateResult - { + enum GraphUpdateResult { /// Successfully rebuilt graph dependent data. /// Details: nothing is written. GUR_Success, @@ -288,8 +278,7 @@ private: std::pair<std::unique_ptr<WorkflowNode>&, uint32_t> AllocWorkflowStep(); }; -class WorkflowAssetList final : public AssetListTyped<Workflow> -{ +class WorkflowAssetList final : public AssetListTyped<Workflow> { private: // AC = Asset Creator std::string mACNewName; diff --git a/app/source/Cplt/Model/Workflow/Workflow_Main.cpp b/app/source/Cplt/Model/Workflow/Workflow_Main.cpp index 0f35b32..cd0e419 100644 --- a/app/source/Cplt/Model/Workflow/Workflow_Main.cpp +++ b/app/source/Cplt/Model/Workflow/Workflow_Main.cpp @@ -28,112 +28,92 @@ WorkflowConnection::WorkflowConnection() , SourceNode{ WorkflowNode::kInvalidId } , SourcePin{ WorkflowNode::kInvalidPinId } , DestinationNode{ WorkflowNode::kInvalidId } - , DestinationPin{ WorkflowNode::kInvalidPinId } -{ + , DestinationPin{ WorkflowNode::kInvalidPinId } { } -bool WorkflowConnection::IsValid() const -{ +bool WorkflowConnection::IsValid() const { return Id != 0; } -ImNodes::LinkId WorkflowConnection::GetLinkId() const -{ +ImNodes::LinkId WorkflowConnection::GetLinkId() const { // Our id is 0-based (represents an index directly) // but imgui-node-editor uses the value 0 to represent a null id, so we need to offset by 1 return Id + 1; } -void WorkflowConnection::DrawDebugInfo() const -{ +void WorkflowConnection::DrawDebugInfo() const { ImGui::Text("Source (node with output pin):"); ImGui::Text("{ Node = %u, Pin = %u }", SourceNode, SourcePin); ImGui::Text("Destination (node with input pin):"); ImGui::Text("{ Node = %u, Pin = %u }", DestinationNode, DestinationPin); } -void WorkflowConnection::ReadFrom(std::istream& stream) -{ +void WorkflowConnection::ReadFrom(std::istream& stream) { stream >> SourceNode >> SourcePin; stream >> DestinationNode >> DestinationPin; } -void WorkflowConnection::WriteTo(std::ostream& stream) const -{ +void WorkflowConnection::WriteTo(std::ostream& stream) const { stream << SourceNode << SourcePin; stream << DestinationNode << DestinationPin; } -bool WorkflowNode::InputPin::IsConstantConnection() const -{ +bool WorkflowNode::InputPin::IsConstantConnection() const { return ConnectionToConst && IsConnected(); } -bool WorkflowNode::InputPin::IsConnected() const -{ +bool WorkflowNode::InputPin::IsConnected() const { return Connection != WorkflowConnection::kInvalidId; } -BaseValue::Kind WorkflowNode::InputPin::GetMatchingType() const -{ +BaseValue::Kind WorkflowNode::InputPin::GetMatchingType() const { return MatchingType; } -bool WorkflowNode::OutputPin::IsConnected() const -{ +bool WorkflowNode::OutputPin::IsConnected() const { return Connection != WorkflowConnection::kInvalidId; } -BaseValue::Kind WorkflowNode::OutputPin::GetMatchingType() const -{ +BaseValue::Kind WorkflowNode::OutputPin::GetMatchingType() const { return MatchingType; } WorkflowNode::WorkflowNode(Kind kind, bool locked) : mKind{ kind } , mDepth{ -1 } - , mLocked(locked) -{ + , mLocked(locked) { } -Vec2i WorkflowNode::GetPosition() const -{ +Vec2i WorkflowNode::GetPosition() const { return mPosition; } -void WorkflowNode::SetPosition(const Vec2i& position) -{ +void WorkflowNode::SetPosition(const Vec2i& position) { mPosition = position; } -uint32_t WorkflowNode::GetId() const -{ +uint32_t WorkflowNode::GetId() const { return mId; } -ImNodes::NodeId WorkflowNode::GetNodeId() const -{ +ImNodes::NodeId WorkflowNode::GetNodeId() const { // See WorkflowConnection::GetLinkId for the rationale return mId + 1; } -WorkflowNode::Kind WorkflowNode::GetKind() const -{ +WorkflowNode::Kind WorkflowNode::GetKind() const { return mKind; } -int WorkflowNode::GetDepth() const -{ +int WorkflowNode::GetDepth() const { return mDepth; } -bool WorkflowNode::IsLocked() const -{ +bool WorkflowNode::IsLocked() const { return mLocked; } -WorkflowNode::Type WorkflowNode::GetType() const -{ +WorkflowNode::Type WorkflowNode::GetType() const { if (IsInputNode()) { return InputType; } else if (IsOutputNode()) { @@ -143,70 +123,57 @@ WorkflowNode::Type WorkflowNode::GetType() const } } -bool WorkflowNode::IsInputNode() const -{ +bool WorkflowNode::IsInputNode() const { return mInputs.size() == 0; } -bool WorkflowNode::IsOutputNode() const -{ +bool WorkflowNode::IsOutputNode() const { return mOutputs.size() == 0; } -void WorkflowNode::ConnectInput(uint32_t pinId, WorkflowNode& srcNode, uint32_t srcPinId) -{ +void WorkflowNode::ConnectInput(uint32_t pinId, WorkflowNode& srcNode, uint32_t srcPinId) { mWorkflow->Connect(*this, pinId, srcNode, srcPinId); } -void WorkflowNode::DisconnectInput(uint32_t pinId) -{ +void WorkflowNode::DisconnectInput(uint32_t pinId) { mWorkflow->DisconnectByDestination(*this, pinId); } -void WorkflowNode::DrawInputPinDebugInfo(uint32_t pinId) const -{ +void WorkflowNode::DrawInputPinDebugInfo(uint32_t pinId) const { ImGui::Text("Node ID: %d", mId); ImGui::Text("Pin ID: (input) %d", pinId); } -const WorkflowNode::InputPin& WorkflowNode::GetInputPin(uint32_t pinId) const -{ +const WorkflowNode::InputPin& WorkflowNode::GetInputPin(uint32_t pinId) const { return mInputs[pinId]; } -ImNodes::PinId WorkflowNode::GetInputPinUniqueId(uint32_t pinId) const -{ +ImNodes::PinId WorkflowNode::GetInputPinUniqueId(uint32_t pinId) const { return mWorkflow->FabricateGlobalPinId(*this, pinId, false); } -void WorkflowNode::ConnectOutput(uint32_t pinId, WorkflowNode& dstNode, uint32_t dstPinId) -{ +void WorkflowNode::ConnectOutput(uint32_t pinId, WorkflowNode& dstNode, uint32_t dstPinId) { mWorkflow->Connect(dstNode, dstPinId, *this, pinId); } -void WorkflowNode::DisconnectOutput(uint32_t pinId) -{ +void WorkflowNode::DisconnectOutput(uint32_t pinId) { mWorkflow->DisconnectBySource(*this, pinId); } -void WorkflowNode::DrawOutputPinDebugInfo(uint32_t pinId) const -{ +void WorkflowNode::DrawOutputPinDebugInfo(uint32_t pinId) const { ImGui::Text("Node ID: %d", mId); ImGui::Text("Pin ID: (output) %d", pinId); } -const WorkflowNode::OutputPin& WorkflowNode::GetOutputPin(uint32_t pinId) const -{ +const WorkflowNode::OutputPin& WorkflowNode::GetOutputPin(uint32_t pinId) const { return mOutputs[pinId]; } -ImNodes::PinId WorkflowNode::GetOutputPinUniqueId(uint32_t pinId) const -{ +ImNodes::PinId WorkflowNode::GetOutputPinUniqueId(uint32_t pinId) const { return mWorkflow->FabricateGlobalPinId(*this, pinId, true); } -void WorkflowNode::Draw() -{ +void WorkflowNode::Draw() { for (uint32_t i = 0; i < mInputs.size(); ++i) { auto& pin = mInputs[i]; auto& typeInfo = BaseValue::QueryInfo(pin.MatchingType); @@ -223,8 +190,7 @@ void WorkflowNode::Draw() } } -void WorkflowNode::DrawDebugInfo() const -{ +void WorkflowNode::DrawDebugInfo() const { ImGui::Text("Node kind: %s", FormatKind(mKind)); ImGui::Text("Node type: %s", FormatType(GetType())); ImGui::Text("Node ID: %u", mId); @@ -232,20 +198,17 @@ void WorkflowNode::DrawDebugInfo() const DrawExtraDebugInfo(); } -void WorkflowNode::ReadFrom(std::istream& stream) -{ +void WorkflowNode::ReadFrom(std::istream& stream) { stream >> mId; stream >> mPosition.x >> mPosition.y; } -void WorkflowNode::WriteTo(std::ostream& stream) -{ +void WorkflowNode::WriteTo(std::ostream& stream) { stream << mId; stream << mPosition.x << mPosition.y; } -WorkflowNode::InputPin& WorkflowNode::InsertInputPin(int atIdx) -{ +WorkflowNode::InputPin& WorkflowNode::InsertInputPin(int atIdx) { assert(atIdx >= 0 && atIdx < mInputs.size()); mInputs.push_back(InputPin{}); @@ -256,8 +219,7 @@ WorkflowNode::InputPin& WorkflowNode::InsertInputPin(int atIdx) return mInputs[atIdx]; } -void WorkflowNode::RemoveInputPin(int pin) -{ +void WorkflowNode::RemoveInputPin(int pin) { DisconnectInput(pin); for (int i = 0, end = (int)mInputs.size() - 1; i < end; ++i) { SwapInputPin(i, i + 1); @@ -265,8 +227,7 @@ void WorkflowNode::RemoveInputPin(int pin) mInputs.resize(mInputs.size() - 1); } -void WorkflowNode::SwapInputPin(int a, int b) -{ +void WorkflowNode::SwapInputPin(int a, int b) { auto& pinA = mInputs[a]; auto& pinB = mInputs[b]; @@ -284,8 +245,7 @@ void WorkflowNode::SwapInputPin(int a, int b) std::swap(pinA, pinB); } -WorkflowNode::OutputPin& WorkflowNode::InsertOutputPin(int atIdx) -{ +WorkflowNode::OutputPin& WorkflowNode::InsertOutputPin(int atIdx) { assert(atIdx >= 0 && atIdx < mOutputs.size()); mOutputs.push_back(OutputPin{}); @@ -296,8 +256,7 @@ WorkflowNode::OutputPin& WorkflowNode::InsertOutputPin(int atIdx) return mOutputs[atIdx]; } -void WorkflowNode::RemoveOutputPin(int pin) -{ +void WorkflowNode::RemoveOutputPin(int pin) { DisconnectOutput(pin); for (int i = 0, end = (int)mOutputs.size() - 1; i < end; ++i) { SwapInputPin(i, i + 1); @@ -305,8 +264,7 @@ void WorkflowNode::RemoveOutputPin(int pin) mOutputs.resize(mOutputs.size() - 1); } -void WorkflowNode::SwapOutputPin(int a, int b) -{ +void WorkflowNode::SwapOutputPin(int a, int b) { auto& pinA = mOutputs[a]; auto& pinB = mOutputs[b]; @@ -324,71 +282,57 @@ void WorkflowNode::SwapOutputPin(int a, int b) std::swap(pinA, pinB); } -void WorkflowNode::OnAttach(Workflow& workflow, uint32_t newId) -{ +void WorkflowNode::OnAttach(Workflow& workflow, uint32_t newId) { } -void WorkflowNode::OnDetach() -{ +void WorkflowNode::OnDetach() { } -const std::vector<WorkflowConnection>& Workflow::GetConnections() const -{ +const std::vector<WorkflowConnection>& Workflow::GetConnections() const { return mConnections; } -std::vector<WorkflowConnection>& Workflow::GetConnections() -{ +std::vector<WorkflowConnection>& Workflow::GetConnections() { return mConnections; } -const std::vector<std::unique_ptr<WorkflowNode>>& Workflow::GetNodes() const -{ +const std::vector<std::unique_ptr<WorkflowNode>>& Workflow::GetNodes() const { return mNodes; } -std::vector<std::unique_ptr<WorkflowNode>>& Workflow::GetNodes() -{ +std::vector<std::unique_ptr<WorkflowNode>>& Workflow::GetNodes() { return mNodes; } -const std::vector<std::unique_ptr<BaseValue>>& Workflow::GetConstants() const -{ +const std::vector<std::unique_ptr<BaseValue>>& Workflow::GetConstants() const { return mConstants; } -std::vector<std::unique_ptr<BaseValue>>& Workflow::GetConstants() -{ +std::vector<std::unique_ptr<BaseValue>>& Workflow::GetConstants() { return mConstants; } -WorkflowConnection* Workflow::GetConnectionById(uint32_t id) -{ +WorkflowConnection* Workflow::GetConnectionById(uint32_t id) { return &mConnections[id]; } -WorkflowConnection* Workflow::GetConnectionByLinkId(ImNodes::LinkId id) -{ +WorkflowConnection* Workflow::GetConnectionByLinkId(ImNodes::LinkId id) { return &mConnections[(uint32_t)(size_t)id - 1]; } -WorkflowNode* Workflow::GetNodeById(uint32_t id) -{ +WorkflowNode* Workflow::GetNodeById(uint32_t id) { return mNodes[id].get(); } -WorkflowNode* Workflow::GetNodeByNodeId(ImNodes::NodeId id) -{ +WorkflowNode* Workflow::GetNodeByNodeId(ImNodes::NodeId id) { return mNodes[(uint32_t)(size_t)id - 1].get(); } -BaseValue* Workflow::GetConstantById(uint32_t id) -{ +BaseValue* Workflow::GetConstantById(uint32_t id) { return mConstants[id].get(); } -Workflow::GlobalPinId Workflow::DisassembleGlobalPinId(ImNodes::PinId pinId) -{ +Workflow::GlobalPinId Workflow::DisassembleGlobalPinId(ImNodes::PinId pinId) { // imgui-node-editor requires all pins to have a global, unique id // but in our model the pin are typed (input vs output) and associated with a node: there is no built-in global id // Therefore we encode one ourselves @@ -411,8 +355,7 @@ Workflow::GlobalPinId Workflow::DisassembleGlobalPinId(ImNodes::PinId pinId) return result; } -ImNodes::PinId Workflow::FabricateGlobalPinId(const WorkflowNode& node, uint32_t pinId, bool isOutput) const -{ +ImNodes::PinId Workflow::FabricateGlobalPinId(const WorkflowNode& node, uint32_t pinId, bool isOutput) const { // See this->DisassembleGlobalPinId for format details and rationale uint64_t id = 0; @@ -423,18 +366,15 @@ ImNodes::PinId Workflow::FabricateGlobalPinId(const WorkflowNode& node, uint32_t return id; } -const std::vector<std::vector<uint32_t>>& Workflow::GetDepthGroups() const -{ +const std::vector<std::vector<uint32_t>>& Workflow::GetDepthGroups() const { return mDepthGroups; } -bool Workflow::DoesDepthNeedsUpdate() const -{ +bool Workflow::DoesDepthNeedsUpdate() const { return mDepthsDirty; } -void Workflow::AddNode(std::unique_ptr<WorkflowNode> step) -{ +void Workflow::AddNode(std::unique_ptr<WorkflowNode> step) { auto [storage, id] = AllocWorkflowStep(); storage = std::move(step); storage->OnAttach(*this, id); @@ -442,8 +382,7 @@ void Workflow::AddNode(std::unique_ptr<WorkflowNode> step) storage->mId = id; } -void Workflow::RemoveNode(uint32_t id) -{ +void Workflow::RemoveNode(uint32_t id) { auto& step = mNodes[id]; if (step == nullptr) return; @@ -452,8 +391,7 @@ void Workflow::RemoveNode(uint32_t id) step->mId = WorkflowNode::kInvalidId; } -void Workflow::RemoveConnection(uint32_t id) -{ +void Workflow::RemoveConnection(uint32_t id) { auto& conn = mConnections[id]; if (!conn.IsValid()) return; @@ -464,8 +402,7 @@ void Workflow::RemoveConnection(uint32_t id) mDepthsDirty = true; } -bool Workflow::Connect(WorkflowNode& sourceNode, uint32_t sourcePin, WorkflowNode& destinationNode, uint32_t destinationPin) -{ +bool Workflow::Connect(WorkflowNode& sourceNode, uint32_t sourcePin, WorkflowNode& destinationNode, uint32_t destinationPin) { auto& src = sourceNode.mOutputs[sourcePin]; auto& dst = destinationNode.mInputs[destinationPin]; @@ -491,8 +428,7 @@ bool Workflow::Connect(WorkflowNode& sourceNode, uint32_t sourcePin, WorkflowNod return true; } -bool Workflow::DisconnectBySource(WorkflowNode& sourceNode, uint32_t sourcePin) -{ +bool Workflow::DisconnectBySource(WorkflowNode& sourceNode, uint32_t sourcePin) { auto& sn = sourceNode.mOutputs[sourcePin]; if (!sn.IsConnected()) return false; @@ -507,8 +443,7 @@ bool Workflow::DisconnectBySource(WorkflowNode& sourceNode, uint32_t sourcePin) return true; } -bool Workflow::DisconnectByDestination(WorkflowNode& destinationNode, uint32_t destinationPin) -{ +bool Workflow::DisconnectByDestination(WorkflowNode& destinationNode, uint32_t destinationPin) { auto& dn = destinationNode.mOutputs[destinationPin]; if (!dn.IsConnected()) return false; @@ -523,8 +458,7 @@ bool Workflow::DisconnectByDestination(WorkflowNode& destinationNode, uint32_t d return true; } -Workflow::GraphUpdateResult Workflow::UpdateGraph(GraphUpdateDetails* details) -{ +Workflow::GraphUpdateResult Workflow::UpdateGraph(GraphUpdateDetails* details) { if (!mDepthsDirty) { return GUR_NoWorkToDo; } @@ -533,8 +467,7 @@ Workflow::GraphUpdateResult Workflow::UpdateGraph(GraphUpdateDetails* details) // - Dependency = nodes its input pins are connected to // - Dependents = nodes its output pins are connected to - struct WorkingNode - { + struct WorkingNode { // The max depth out of all dependency nodes, maintained during the traversal and committed as the actual depth // when all dependencies of this node has been resolved. Add 1 to get the depth that will be assigned to the node. int MaximumDepth = 0; @@ -635,28 +568,23 @@ Workflow::GraphUpdateResult Workflow::UpdateGraph(GraphUpdateDetails* details) return GUR_Success; } -class Workflow::Private -{ +class Workflow::Private { public: template <class TSelf, class TProxy> - static void OperateStream(TSelf& self, TProxy& proxy) - { + static void OperateStream(TSelf& self, TProxy& proxy) { // TODO } }; -void Workflow::ReadFromDataStream(InputDataStream& stream) -{ +void Workflow::ReadFromDataStream(InputDataStream& stream) { Private::OperateStream(*this, stream); } -void Workflow::WriteToDataStream(OutputDataStream& stream) const -{ +void Workflow::WriteToDataStream(OutputDataStream& stream) const { Private::OperateStream(*this, stream); } -std::pair<WorkflowConnection&, uint32_t> Workflow::AllocWorkflowConnection() -{ +std::pair<WorkflowConnection&, uint32_t> Workflow::AllocWorkflowConnection() { for (size_t idx = 0; idx < mConnections.size(); ++idx) { auto& elm = mConnections[idx]; if (!elm.IsValid()) { @@ -671,8 +599,7 @@ std::pair<WorkflowConnection&, uint32_t> Workflow::AllocWorkflowConnection() return { conn, id }; } -std::pair<std::unique_ptr<WorkflowNode>&, uint32_t> Workflow::AllocWorkflowStep() -{ +std::pair<std::unique_ptr<WorkflowNode>&, uint32_t> Workflow::AllocWorkflowStep() { for (size_t idx = 0; idx < mNodes.size(); ++idx) { auto& elm = mNodes[idx]; if (elm == nullptr) { @@ -686,14 +613,12 @@ std::pair<std::unique_ptr<WorkflowNode>&, uint32_t> Workflow::AllocWorkflowStep( return { node, id }; } -void WorkflowAssetList::DiscoverFiles(const std::function<void(SavedAsset)>& callback) const -{ +void WorkflowAssetList::DiscoverFiles(const std::function<void(SavedAsset)>& callback) const { auto dir = GetConnectedProject().GetWorkflowsDirectory(); DiscoverFilesByExtension(callback, dir, ".cplt-workflow"sv); } -std::string WorkflowAssetList::RetrieveNameFromFile(const fs::path& file) const -{ +std::string WorkflowAssetList::RetrieveNameFromFile(const fs::path& file) const { auto res = DataArchive::LoadFile(file); if (!res) return ""; auto& stream = res.value(); @@ -704,19 +629,16 @@ std::string WorkflowAssetList::RetrieveNameFromFile(const fs::path& file) const return assetInfo.Name; } -uuids::uuid WorkflowAssetList::RetrieveUuidFromFile(const fs::path& file) const -{ +uuids::uuid WorkflowAssetList::RetrieveUuidFromFile(const fs::path& file) const { return uuids::uuid::from_string(file.stem().string()); } -fs::path WorkflowAssetList::RetrievePathFromAsset(const SavedAsset& asset) const -{ +fs::path WorkflowAssetList::RetrievePathFromAsset(const SavedAsset& asset) const { auto fileName = uuids::to_string(asset.Uuid); return GetConnectedProject().GetWorkflowPath(fileName); } -bool WorkflowAssetList::SaveInstance(const SavedAsset& assetInfo, const Asset* asset) const -{ +bool WorkflowAssetList::SaveInstance(const SavedAsset& assetInfo, const Asset* asset) const { auto path = RetrievePathFromAsset(assetInfo); auto res = DataArchive::SaveFile(path); if (!res) return false; @@ -731,8 +653,7 @@ bool WorkflowAssetList::SaveInstance(const SavedAsset& assetInfo, const Asset* a return true; } -static std::unique_ptr<Workflow> LoadWorkflowFromFile(const fs::path& path) -{ +static std::unique_ptr<Workflow> LoadWorkflowFromFile(const fs::path& path) { auto res = DataArchive::LoadFile(path); if (!res) return nullptr; auto& stream = res.value(); @@ -747,18 +668,15 @@ static std::unique_ptr<Workflow> LoadWorkflowFromFile(const fs::path& path) return workflow; } -Workflow* WorkflowAssetList::LoadInstance(const SavedAsset& assetInfo) const -{ +Workflow* WorkflowAssetList::LoadInstance(const SavedAsset& assetInfo) const { return ::LoadWorkflowFromFile(RetrievePathFromAsset(assetInfo)).release(); } -Workflow* WorkflowAssetList::CreateInstance(const SavedAsset& assetInfo) const -{ +Workflow* WorkflowAssetList::CreateInstance(const SavedAsset& assetInfo) const { return new Workflow(); } -bool WorkflowAssetList::RenameInstanceOnDisk(const SavedAsset& assetInfo, std::string_view oldName) const -{ +bool WorkflowAssetList::RenameInstanceOnDisk(const SavedAsset& assetInfo, std::string_view oldName) const { auto path = RetrievePathFromAsset(assetInfo); auto workflow = ::LoadWorkflowFromFile(path); @@ -769,8 +687,7 @@ bool WorkflowAssetList::RenameInstanceOnDisk(const SavedAsset& assetInfo, std::s return true; } -void WorkflowAssetList::DisplayAssetCreator(ListState& state) -{ +void WorkflowAssetList::DisplayAssetCreator(ListState& state) { auto ValidateNewName = [&]() -> void { if (mACNewName.empty()) { mACNewNameError = NameSelectionError::Empty; @@ -826,8 +743,7 @@ void WorkflowAssetList::DisplayAssetCreator(ListState& state) } } -void WorkflowAssetList::DisplayDetailsTable(ListState& state) const -{ +void WorkflowAssetList::DisplayDetailsTable(ListState& state) const { ImGui::BeginTable("AssetDetailsTable", 1, ImGuiTableFlags_Borders); ImGui::TableSetupColumn(I18N_TEXT("Name", L10N_NAME)); diff --git a/app/source/Cplt/Model/Workflow/Workflow_RTTI.cpp b/app/source/Cplt/Model/Workflow/Workflow_RTTI.cpp index ee3da28..6b8f76e 100644 --- a/app/source/Cplt/Model/Workflow/Workflow_RTTI.cpp +++ b/app/source/Cplt/Model/Workflow/Workflow_RTTI.cpp @@ -9,8 +9,7 @@ #include <memory> -const char* WorkflowNode::FormatKind(Kind kind) -{ +const char* WorkflowNode::FormatKind(Kind kind) { switch (kind) { case KD_NumericAddition: return I18N_TEXT("Add", L10N_WORKFLOW_ADD); case KD_NumericSubtraction: return I18N_TEXT("Subtract", L10N_WORKFLOW_SUB); @@ -27,8 +26,7 @@ const char* WorkflowNode::FormatKind(Kind kind) return ""; } -const char* WorkflowNode::FormatCategory(WorkflowNode::Category category) -{ +const char* WorkflowNode::FormatCategory(WorkflowNode::Category category) { switch (category) { case CG_Numeric: return I18N_TEXT("Numeric", L10N_WORKFLOW_CATEGORY_NUMERIC); case CG_Text: return I18N_TEXT("Text", L10N_WORKFLOW_CATEGORY_TEXT); @@ -42,8 +40,7 @@ const char* WorkflowNode::FormatCategory(WorkflowNode::Category category) return ""; } -const char* WorkflowNode::FormatType(Type type) -{ +const char* WorkflowNode::FormatType(Type type) { switch (type) { case InputType: return I18N_TEXT("Input", L10N_WORKFLOW_KIND_INPUT); case TransformType: return I18N_TEXT("Transform", L10N_WORKFLOW_KIND_TRANSFORM); @@ -52,8 +49,7 @@ const char* WorkflowNode::FormatType(Type type) return ""; } -WorkflowNode::Category WorkflowNode::QueryCategory(Kind kind) -{ +WorkflowNode::Category WorkflowNode::QueryCategory(Kind kind) { switch (kind) { case KD_NumericAddition: case KD_NumericSubtraction: @@ -74,8 +70,7 @@ WorkflowNode::Category WorkflowNode::QueryCategory(Kind kind) return InvalidCategory; } -std::span<const WorkflowNode::Kind> WorkflowNode::QueryCategoryMembers(Category category) -{ +std::span<const WorkflowNode::Kind> WorkflowNode::QueryCategoryMembers(Category category) { constexpr WorkflowNode::Kind kNumeric[] = { KD_NumericAddition, KD_NumericSubtraction, @@ -119,8 +114,7 @@ std::span<const WorkflowNode::Kind> WorkflowNode::QueryCategoryMembers(Category return {}; } -std::unique_ptr<WorkflowNode> WorkflowNode::CreateByKind(WorkflowNode::Kind kind) -{ +std::unique_ptr<WorkflowNode> WorkflowNode::CreateByKind(WorkflowNode::Kind kind) { switch (kind) { case KD_NumericAddition: return std::make_unique<NumericOperationNode>(NumericOperationNode::Addition); case KD_NumericSubtraction: return std::make_unique<NumericOperationNode>(NumericOperationNode::Subtraction); @@ -137,7 +131,6 @@ std::unique_ptr<WorkflowNode> WorkflowNode::CreateByKind(WorkflowNode::Kind kind return nullptr; } -bool WorkflowNode::IsInstance(const WorkflowNode* node) -{ +bool WorkflowNode::IsInstance(const WorkflowNode* node) { return true; } diff --git a/app/source/Cplt/UI/UI.hpp b/app/source/Cplt/UI/UI.hpp index 0a80b4c..64f1f9e 100644 --- a/app/source/Cplt/UI/UI.hpp +++ b/app/source/Cplt/UI/UI.hpp @@ -18,8 +18,7 @@ void ErrorMessage(const char* fmt, ...); void WarningIcon(); void WarningMessage(const char* fmt, ...); -enum class IconType -{ +enum class IconType { Flow, Circle, Square, diff --git a/app/source/Cplt/UI/UI_DatabaseView.cpp b/app/source/Cplt/UI/UI_DatabaseView.cpp index 1e58eb0..091e80d 100644 --- a/app/source/Cplt/UI/UI_DatabaseView.cpp +++ b/app/source/Cplt/UI/UI_DatabaseView.cpp @@ -23,35 +23,30 @@ constexpr int kMaxEntriesPerPage = 32; constexpr int kSummaryItemCount = 3; constexpr int kSummaryMaxLength = 25; -std::pair<int, int> SplitEntryIndex(int entryIdx) -{ +std::pair<int, int> SplitEntryIndex(int entryIdx) { int page = entryIdx / kMaxEntriesPerPage; int row = entryIdx % kMaxEntriesPerPage; return { page, row }; } -enum class DeliveryDirection -{ +enum class DeliveryDirection { FactoryToWarehouse, WarehouseToCustomer, }; -struct Item -{ +struct Item { int ItemId; int Count; }; -struct DeliveryEntry -{ +struct DeliveryEntry { std::vector<Item> Items; std::string ItemsSummary; std::string ShipmentTime; std::string ArriveTime; DeliveryDirection Direction; - const char* StringifyDirection() const - { + const char* StringifyDirection() const { switch (Direction) { case DeliveryDirection::FactoryToWarehouse: return "Factory to warehouse"; case DeliveryDirection::WarehouseToCustomer: return "Warehouse to customer"; @@ -59,8 +54,7 @@ struct DeliveryEntry } }; -struct SaleEntry -{ +struct SaleEntry { static constexpr auto kType = DeliveryDirection::WarehouseToCustomer; std::vector<DeliveryEntry> AssociatedDeliveries; @@ -73,8 +67,7 @@ struct SaleEntry bool DeliveriesCached = false; }; -struct PurchaseEntry -{ +struct PurchaseEntry { static constexpr auto kType = DeliveryDirection::FactoryToWarehouse; std::vector<DeliveryEntry> AssociatedDeliveries; @@ -88,27 +81,22 @@ struct PurchaseEntry }; template <class T> -class GenericTableView -{ +class GenericTableView { public: - // clang-format off - static constexpr bool kHasItems = requires(T t) - { - t.Items; - t.ItemsSummary; - }; + static constexpr bool kHasItems = requires(T t) { + t.Items; + t.ItemsSummary; + }; static constexpr bool kHasCustomer = requires(T t) { t.Customer; }; static constexpr bool kHasDeadline = requires(T t) { t.Deadline; }; static constexpr bool kHasFactory = requires(T t) { t.Factory; }; static constexpr bool kHasOrderTime = requires(T t) { t.OrderTime; }; static constexpr bool kHasCompletionTime = requires(T t) { t.DeliveryTime; }; static constexpr int kColumnCount = kHasItems + kHasCustomer + kHasDeadline + kHasFactory + kHasOrderTime + kHasCompletionTime; - // clang-format on using Page = std::vector<T>; - struct QueryStatements - { + struct QueryStatements { SQLite::Statement* GetRowCount; SQLite::Statement* GetRows; SQLite::Statement* GetItems; @@ -143,18 +131,15 @@ protected: public: /// Calculate the first visible row's entry index. - int GetFirstVisibleRowIdx() const - { + int GetFirstVisibleRowIdx() const { return mCurrentPageNumber * kMaxEntriesPerPage; } - Project* GetProject() const - { + Project* GetProject() const { return mProject; } - void OnProjectChanged(Project* newProject) - { + void OnProjectChanged(Project* newProject) { mProject = newProject; auto& stmt = *Statements.GetRowCount; @@ -176,17 +161,13 @@ public: mSelectRow = -1; } - TableRowsFilter* GetFilter() const - { + TableRowsFilter* GetFilter() const { return mActiveFilter.get(); } - void OnFilterChanged() - { + void OnFilterChanged() { auto& stmt = *Statements.FilterRows; - // clang-format off DEFER { stmt.reset(); }; - // clang-format on // TODO lazy loading when too many results mActiveEntries.clear(); @@ -201,14 +182,12 @@ public: mSelectRow = -1; } - void OnFilterChanged(std::unique_ptr<TableRowsFilter> filter) - { + void OnFilterChanged(std::unique_ptr<TableRowsFilter> filter) { mActiveFilter = std::move(filter); OnFilterChanged(); } - void Display() - { + void Display() { bool dummy = true; if (ImGui::Button(ICON_FA_ARROW_LEFT, mCurrentPageNumber == 0)) { @@ -260,29 +239,25 @@ public: ImGui::Columns(1); } - void SetPage(int page) - { + void SetPage(int page) { mCurrentPageNumber = page; mCurrentPage = &LoadAndGetPage(page); mSelectRow = -1; } private: - static int CalcPageForRowId(int64_t entryIdx) - { + static int CalcPageForRowId(int64_t entryIdx) { return entryIdx / kMaxEntriesPerPage; } /// Calculate range [begin, end) of index for the list of entries that are currently visible that the path-th page would show. /// i.e. when there is a filter, look into \c mActiveEntryIndices; when there is no filter, use directly. - static std::pair<int64_t, int64_t> CalcRangeForPage(int page) - { + static std::pair<int64_t, int64_t> CalcRangeForPage(int page) { int begin = page * kMaxEntriesPerPage; return { begin, begin + kMaxEntriesPerPage }; } - void DisplayMainTable() - { + void DisplayMainTable() { if (ImGui::BeginTable("DataTable", kColumnCount, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX)) { if constexpr (kHasCustomer) ImGui::TableSetupColumn(I18N_TEXT("Customer", L10N_DATABASE_COLUMN_CUSTOMER)); @@ -315,16 +290,14 @@ private: } } - void DisplayEntry(int rowIdx) - { + void DisplayEntry(int rowIdx) { // TODO // auto [pageNumber, pageEntry] = SplitRowIndex(rowIdx); // auto& entry = LoadAndGetPage(pageNumber)[pageEntry]; // DisplayEntry(entry, rowIdx); } - void DisplayEntry(T& entry, int rowIdx, int entryIdx) - { + void DisplayEntry(T& entry, int rowIdx, int entryIdx) { ImGui::PushID(rowIdx); ImGui::TableNextRow(); @@ -372,13 +345,11 @@ private: ImGui::PopID(); } - void EditEntry(T& entry, int rowIdx, int entryIdx) - { + void EditEntry(T& entry, int rowIdx, int entryIdx) { // TODO } - void DisplayDeliveriesTable() - { + void DisplayDeliveriesTable() { if (ImGui::BeginTable("DeliveriesTable", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX)) { ImGui::TableSetupColumn(I18N_TEXT("Shipment time", L10N_DATABASE_COLUMN_SHIPMENT_TIME)); @@ -408,11 +379,8 @@ private: } } - std::vector<Item> LoadItems(SQLite::Statement& stmt, int64_t id) - { - // clang-format off + std::vector<Item> LoadItems(SQLite::Statement& stmt, int64_t id) { DEFER { stmt.reset(); }; - // clang-format on stmt.bind(1, id); @@ -429,8 +397,7 @@ private: return entries; } - std::string CreateItemsSummary(const std::vector<Item>& items) - { + std::string CreateItemsSummary(const std::vector<Item>& items) { if (items.empty()) { return "<empty>"; } @@ -455,8 +422,7 @@ private: return result; } - std::vector<DeliveryEntry> LoadDeliveriesEntries(int64_t orderId, DeliveryDirection type) - { + std::vector<DeliveryEntry> LoadDeliveriesEntries(int64_t orderId, DeliveryDirection type) { bool outgoingFlag; switch (type) { case DeliveryDirection::FactoryToWarehouse: outgoingFlag = false; break; @@ -464,9 +430,7 @@ private: } auto& stmt = mProject->Database.GetDeliveries().FilterByTypeAndId; - // clang-format off DEFER { stmt.reset(); }; - // clang-format on stmt.bind(1, orderId); stmt.bind(2, outgoingFlag); @@ -493,17 +457,14 @@ private: return entries; } - Page& LoadAndGetPage(int page) - { + Page& LoadAndGetPage(int page) { auto iter = mPages.find(page); if (iter != mPages.end()) { return iter.value(); } auto& stmt = *Statements.GetRows; - // clang-format off DEFER { stmt.reset(); }; - // clang-format on stmt.bind(1, kMaxEntriesPerPage); stmt.bind(2, page * kMaxEntriesPerPage); @@ -575,34 +536,29 @@ private: return res.value(); } - void DrawItems(const std::vector<Item>& items) - { + void DrawItems(const std::vector<Item>& items) { for (auto& item : items) { auto& name = mProject->Products.Find(item.ItemId)->GetName(); ImGui::Text("%s × %d", name.c_str(), item.Count); } } - void UpdateLastPage() - { + void UpdateLastPage() { mLastPage = mActiveEntries.empty() ? CalcPageForRowId(mRowCount) : CalcPageForRowId(mActiveEntries.back()); } }; -class SalesTableView : public GenericTableView<SaleEntry> -{ +class SalesTableView : public GenericTableView<SaleEntry> { public: - SalesTableView() - { + SalesTableView() { mEditDialogTitle = I18N_TEXT("Edit sales entry", L10N_DATABASE_SALES_VIEW_EDIT_DIALOG_TITLE); } #pragma clang diagnostic push #pragma ide diagnostic ignored "HidingNonVirtualFunction" - void OnProjectChanged(Project* newProject) - { + void OnProjectChanged(Project* newProject) { auto& table = newProject->Database.GetSales(); Statements.GetRowCount = &table.GetRowCount; Statements.GetRows = &table.GetRows; @@ -615,18 +571,15 @@ public: #pragma clang diagnostic pop }; -class PurchasesTableView : public GenericTableView<PurchaseEntry> -{ +class PurchasesTableView : public GenericTableView<PurchaseEntry> { public: - PurchasesTableView() - { + PurchasesTableView() { mEditDialogTitle = I18N_TEXT("Edit purchase entry", L10N_DATABASE_PURCHASES_VIEW_EDIT_DIALOG_TITLE); } #pragma clang diagnostic push #pragma ide diagnostic ignored "HidingNonVirtualFunction" - void OnProjectChanged(Project* newProject) - { + void OnProjectChanged(Project* newProject) { auto& table = newProject->Database.GetPurchases(); Statements.GetRowCount = &table.GetRowCount; Statements.GetRows = &table.GetRows; @@ -640,8 +593,7 @@ public: }; } // namespace CPLT_UNITY_ID -void UI::DatabaseViewTab() -{ +void UI::DatabaseViewTab() { auto& gs = GlobalStates::GetInstance(); static Project* currentProject = nullptr; diff --git a/app/source/Cplt/UI/UI_Items.cpp b/app/source/Cplt/UI/UI_Items.cpp index 0170e1a..07787d5 100644 --- a/app/source/Cplt/UI/UI_Items.cpp +++ b/app/source/Cplt/UI/UI_Items.cpp @@ -10,8 +10,7 @@ namespace CPLT_UNITY_ID { -enum class ActionResult -{ +enum class ActionResult { Confirmed, Canceled, Pending, @@ -20,14 +19,11 @@ enum class ActionResult /// \param list Item list that the item is in. /// \param item A non-null pointer to the currently being edited item. It should not change until this function returns a non-\c ActionResult::Pending value. template <class T> -ActionResult ItemEditor(ItemList<T>& list, T* item) -{ - constexpr bool kHasDescription = requires(T t) - { +ActionResult ItemEditor(ItemList<T>& list, T* item) { + constexpr bool kHasDescription = requires(T t) { t.GetDescription(); }; - constexpr bool kHasEmail = requires(T t) - { + constexpr bool kHasEmail = requires(T t) { t.GetEmail(); }; @@ -93,22 +89,17 @@ ActionResult ItemEditor(ItemList<T>& list, T* item) } template <class T> -void ItemListEntries(ItemList<T>& list, int& selectedIdx) -{ - constexpr bool kHasDescription = requires(T t) - { +void ItemListEntries(ItemList<T>& list, int& selectedIdx) { + constexpr bool kHasDescription = requires(T t) { t.GetDescription(); }; - constexpr bool kHasEmail = requires(T t) - { + constexpr bool kHasEmail = requires(T t) { t.GetEmail(); }; - constexpr bool kHasStock = requires(T t) - { + constexpr bool kHasStock = requires(T t) { t.GetPrice(); }; - constexpr bool kHasPrice = requires(T t) - { + constexpr bool kHasPrice = requires(T t) { t.GetPrice(); }; constexpr int kColumns = 1 /* Name column */ + kHasDescription + kHasEmail + kHasStock + kHasPrice; @@ -163,8 +154,7 @@ void ItemListEntries(ItemList<T>& list, int& selectedIdx) } template <class T> -void ItemListEditor(ItemList<T>& list) -{ +void ItemListEditor(ItemList<T>& list) { bool opened = true; static int selectedIdx = -1; static T* editingItem = nullptr; @@ -230,8 +220,7 @@ void ItemListEditor(ItemList<T>& list) } } // namespace CPLT_UNITY_ID -void UI::ItemsTab() -{ +void UI::ItemsTab() { auto& gs = GlobalStates::GetInstance(); if (ImGui::BeginTabBar("ItemViewTabs")) { diff --git a/app/source/Cplt/UI/UI_MainWindow.cpp b/app/source/Cplt/UI/UI_MainWindow.cpp index 4653f79..c1c9dfc 100644 --- a/app/source/Cplt/UI/UI_MainWindow.cpp +++ b/app/source/Cplt/UI/UI_MainWindow.cpp @@ -14,8 +14,7 @@ namespace fs = std::filesystem; namespace CPLT_UNITY_ID { -void ProjectTab_Normal() -{ +void ProjectTab_Normal() { auto& gs = GlobalStates::GetInstance(); if (ImGui::Button(ICON_FA_TIMES " " I18N_TEXT("Close", L10N_CLOSE))) { @@ -31,8 +30,7 @@ void ProjectTab_Normal() ImGui::Text("%s %s", I18N_TEXT("Project path", L10N_PROJECT_PATH), gs.GetCurrentProject()->GetPathString().c_str()); } -void ProjectTab_NoProject() -{ +void ProjectTab_NoProject() { auto& gs = GlobalStates::GetInstance(); bool openedDummy = true; @@ -183,8 +181,7 @@ void ProjectTab_NoProject() } } // namespace CPLT_UNITY_ID -void UI::MainWindow() -{ +void UI::MainWindow() { auto& gs = GlobalStates::GetInstance(); auto windowSize = ImGui::GetMainViewport()->Size; diff --git a/app/source/Cplt/UI/UI_Settings.cpp b/app/source/Cplt/UI/UI_Settings.cpp index 71a752a..40da81d 100644 --- a/app/source/Cplt/UI/UI_Settings.cpp +++ b/app/source/Cplt/UI/UI_Settings.cpp @@ -2,7 +2,6 @@ #include <imgui.h> -void UI::SettingsTab() -{ +void UI::SettingsTab() { // TODO } diff --git a/app/source/Cplt/UI/UI_Templates.cpp b/app/source/Cplt/UI/UI_Templates.cpp index e01a97d..ae6c13e 100644 --- a/app/source/Cplt/UI/UI_Templates.cpp +++ b/app/source/Cplt/UI/UI_Templates.cpp @@ -19,8 +19,7 @@ #include <variant> namespace CPLT_UNITY_ID { -class TemplateUI -{ +class TemplateUI { public: static std::unique_ptr<TemplateUI> CreateByKind(std::unique_ptr<Template> tmpl); static std::unique_ptr<TemplateUI> CreateByKind(Template::Kind kind); @@ -34,28 +33,24 @@ public: constexpr ImU32 kSingleParamOutline = IM_COL32(255, 255, 0, 255); constexpr ImU32 kArrayGroupOutline = IM_COL32(255, 0, 0, 255); -class TableTemplateUI : public TemplateUI -{ +class TableTemplateUI : public TemplateUI { private: std::unique_ptr<TableTemplate> mTable; - struct UICell - { + struct UICell { bool Hovered = false; bool Held = false; bool Selected = false; }; std::vector<UICell> mUICells; - struct UIArrayGroup - { + struct UIArrayGroup { ImVec2 Pos; ImVec2 Size; }; std::vector<UIArrayGroup> mUIArrayGroups; - struct Sizer - { + struct Sizer { bool Hovered = false; bool Held = false; }; @@ -69,13 +64,11 @@ private: /* Selection states */ /// "CStates" stands for "Constant cell selection States" - struct CStates - { + struct CStates { }; /// "SStates" stands for "Singular parameter selection States". - struct SStates - { + struct SStates { std::string EditBuffer; bool ErrorDuplicateVarName; bool HasLeftAG; @@ -83,19 +76,16 @@ private: }; /// "AStates" stands for "Array group parameter selection States". - struct AStates - { + struct AStates { std::string EditBuffer; bool ErrorDuplicateVarName; }; // "RStates" stands for "Range selection States". - struct RStates - { + struct RStates { }; - union - { + union { // Initialize to this element std::monostate mIdleState{}; CStates mCS; @@ -109,8 +99,7 @@ private: int mNewTableHeight; /* Table states */ - enum EditMode - { + enum EditMode { ModeEditing, ModeColumnResizing, ModeRowResizing, @@ -128,14 +117,12 @@ public: TableTemplateUI(std::unique_ptr<TableTemplate> table) : mTable{ std::move(table) } , mSelectionTL{ -1, -1 } - , mSelectionBR{ -1, -1 } - { + , mSelectionBR{ -1, -1 } { // TODO debug code Resize(6, 5); } - ~TableTemplateUI() override - { + ~TableTemplateUI() override { // We can't move this to be a destructor of the union // because that way it would run after the destruction of mTable if (!IsSelected()) { @@ -164,8 +151,7 @@ public: } } - void Display() override - { + void Display() override { ImGui::Columns(2); if (mFirstDraw) { mFirstDraw = false; @@ -183,13 +169,11 @@ public: ImGui::Columns(1); } - void Close() override - { + void Close() override { // TODO } - void Resize(int width, int height) - { + void Resize(int width, int height) { mTable->Resize(width, height); mUICells.resize(width * height); mUIArrayGroups.resize(mTable->GetArrayGroupCount()); @@ -216,8 +200,7 @@ public: } private: - void DisplayInspector() - { + void DisplayInspector() { bool openedDummy = true; // This is an id, no need to localize @@ -269,21 +252,18 @@ private: } } - static char NthUppercaseLetter(int n) - { + static char NthUppercaseLetter(int n) { return (char)((int)'A' + n); } - static void ExcelRow(int row, char* bufferBegin, char* bufferEnd) - { + static void ExcelRow(int row, char* bufferBegin, char* bufferEnd) { auto res = std::to_chars(bufferBegin, bufferEnd, row); if (res.ec != std::errc()) { return; } } - static char* ExcelColumn(int column, char* bufferBegin, char* bufferEnd) - { + static char* ExcelColumn(int column, char* bufferBegin, char* bufferEnd) { // https://stackoverflow.com/a/182924/11323702 int dividend = column; @@ -311,8 +291,7 @@ private: return writeHead + 1; } - void DisplayCellProperties(Vec2i pos) - { + void DisplayCellProperties(Vec2i pos) { auto& cell = mTable->GetCell(pos); auto& uiCell = mUICells[pos.y * mTable->GetTableWidth() + pos.x]; @@ -472,13 +451,11 @@ private: } } - void DisplayRangeProperties(Vec2i tl, Vec2i br) - { + void DisplayRangeProperties(Vec2i tl, Vec2i br) { // TODO } - void DisplayTableContents() - { + void DisplayTableContents() { if (ImGui::TreeNode(ICON_FA_BONG " " I18N_TEXT("Parameters", L10N_TABLE_SINGLE_PARAMS))) { TableSingleParamsIter iter(*mTable); while (iter.HasNext()) { @@ -511,8 +488,7 @@ private: } } - void DisplayTableProperties() - { + void DisplayTableProperties() { ImGui::InputInt(I18N_TEXT("Width", L10N_TABLE_WIDTH), &mNewTableWidth); ImGui::InputInt(I18N_TEXT("Height", L10N_TABLE_HEIGHT), &mNewTableHeight); @@ -528,16 +504,13 @@ private: // TODO } - void DisplayTable() - { - struct CellPalette - { + void DisplayTable() { + struct CellPalette { ImU32 Regular; ImU32 Hovered; ImU32 Active; - ImU32 GetColorFor(const UICell& cell) const - { + ImU32 GetColorFor(const UICell& cell) const { if (cell.Held) { return Active; } else if (cell.Hovered) { @@ -689,8 +662,7 @@ private: std::type_identity_t<float ImVec2::*> vecCompGetter, std::type_identity_t<int (TableTemplate::*)() const> lenGetter, std::type_identity_t<int (TableTemplate::*)(int) const> dimGetter, - std::type_identity_t<void (TableTemplate::*)(int, int)> dimSetter) - { + std::type_identity_t<void (TableTemplate::*)(int, int)> dimSetter) { auto window = ImGui::GetCurrentWindow(); auto spacing = ImGui::GetStyle().ItemSpacing.*vecCompGetter; @@ -736,8 +708,7 @@ private: } } - void DisplayTableResizers(ImVec2 topLeftPixelPos) - { + void DisplayTableResizers(ImVec2 topLeftPixelPos) { constexpr float kExtraSideLength = 5.0f; constexpr float kExtraAxialLength = 2.0f; @@ -776,8 +747,7 @@ private: } } - float CalcTablePixelWidth() const - { + float CalcTablePixelWidth() const { float horizontalSpacing = ImGui::GetStyle().ItemSpacing.x; float width = 0; for (int x = 0; x < mTable->GetTableWidth(); ++x) { @@ -787,8 +757,7 @@ private: return width - horizontalSpacing; } - float CalcTablePixelHeight() const - { + float CalcTablePixelHeight() const { float verticalSpacing = ImGui::GetStyle().ItemSpacing.y; float height = 0; for (int y = 0; y < mTable->GetTableHeight(); ++y) { @@ -799,8 +768,7 @@ private: } template <class TFunction> - void ForeachSelectedCell(const TFunction& func) - { + void ForeachSelectedCell(const TFunction& func) { for (int y = mSelectionTL.y; y <= mSelectionBR.y; ++y) { for (int x = mSelectionTL.x; x <= mSelectionBR.x; ++x) { int i = y * mTable->GetTableWidth() + x; @@ -809,13 +777,11 @@ private: } } - bool IsSelected() const - { + bool IsSelected() const { return mSelectionTL.x != -1; } - void ClearSelection() - { + void ClearSelection() { if (IsSelected()) { ForeachSelectedCell([this](int i, int, int) { auto& uiCell = mUICells[i]; @@ -829,13 +795,11 @@ private: ResetIdleState(); } - void ResetIdleState() - { + void ResetIdleState() { mIdleState = {}; } - void SelectRange(Vec2i p1, Vec2i p2) - { + void SelectRange(Vec2i p1, Vec2i p2) { ClearSelection(); if (p2.x < p1.x) { @@ -856,13 +820,11 @@ private: ResetRS(); } - void ResetRS() - { + void ResetRS() { mRS = {}; } - void SelectCell(Vec2i pos) - { + void SelectCell(Vec2i pos) { ClearSelection(); mSelectionTL = pos; @@ -878,13 +840,11 @@ private: } } - void ResetCS() - { + void ResetCS() { mCS = {}; } - void ResetSS(Vec2i pos) - { + void ResetSS(Vec2i pos) { new (&mSS) SStates{ .EditBuffer = mTable->GetCell(pos).Content, .ErrorDuplicateVarName = false, @@ -893,8 +853,7 @@ private: }; } - void ResetAS(Vec2i pos) - { + void ResetAS(Vec2i pos) { new (&mAS) AStates{ .EditBuffer = mTable->GetCell(pos).Content, .ErrorDuplicateVarName = false, @@ -903,13 +862,11 @@ private: }; template <class TTarget> -static auto CastTemplateAs(std::unique_ptr<Template>& input) requires std::is_base_of_v<Template, TTarget> -{ +static auto CastTemplateAs(std::unique_ptr<Template>& input) requires std::is_base_of_v<Template, TTarget> { return std::unique_ptr<TTarget>(static_cast<TTarget*>(input.release())); } -std::unique_ptr<TemplateUI> TemplateUI::CreateByKind(std::unique_ptr<Template> tmpl) -{ +std::unique_ptr<TemplateUI> TemplateUI::CreateByKind(std::unique_ptr<Template> tmpl) { switch (tmpl->GetKind()) { case Template::KD_Table: return std::make_unique<TableTemplateUI>(CastTemplateAs<TableTemplate>(tmpl)); case Template::InvalidKind: break; @@ -917,8 +874,7 @@ std::unique_ptr<TemplateUI> TemplateUI::CreateByKind(std::unique_ptr<Template> t return nullptr; } -std::unique_ptr<TemplateUI> TemplateUI::CreateByKind(Template::Kind kind) -{ +std::unique_ptr<TemplateUI> TemplateUI::CreateByKind(Template::Kind kind) { switch (kind) { case Template::KD_Table: return std::make_unique<TableTemplateUI>(std::make_unique<TableTemplate>()); case Template::InvalidKind: break; @@ -927,8 +883,7 @@ std::unique_ptr<TemplateUI> TemplateUI::CreateByKind(Template::Kind kind) } } // namespace CPLT_UNITY_ID -void UI::TemplatesTab() -{ +void UI::TemplatesTab() { auto& project = *GlobalStates::GetInstance().GetCurrentProject(); static std::unique_ptr<CPLT_UNITY_ID::TemplateUI> openTemplate; diff --git a/app/source/Cplt/UI/UI_Utils.cpp b/app/source/Cplt/UI/UI_Utils.cpp index a2bf692..9fd645d 100644 --- a/app/source/Cplt/UI/UI_Utils.cpp +++ b/app/source/Cplt/UI/UI_Utils.cpp @@ -6,37 +6,31 @@ #define IMGUI_DEFINE_MATH_OPERATORS #include <imgui_internal.h> -void ImGui::SetNextWindowSizeRelScreen(float xPercent, float yPercent, ImGuiCond cond) -{ +void ImGui::SetNextWindowSizeRelScreen(float xPercent, float yPercent, ImGuiCond cond) { auto vs = ImGui::GetMainViewport()->Size; ImGui::SetNextWindowSize({ vs.x * xPercent, vs.y * yPercent }, cond); } -void ImGui::SetNextWindowCentered(ImGuiCond cond) -{ +void ImGui::SetNextWindowCentered(ImGuiCond cond) { auto vs = ImGui::GetMainViewport()->Size; ImGui::SetNextWindowPos({ vs.x / 2, vs.y / 2 }, cond, { 0.5f, 0.5f }); } -void ImGui::PushDisabled() -{ +void ImGui::PushDisabled() { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.5f * ImGui::GetStyle().Alpha); } -void ImGui::PopDisabled() -{ +void ImGui::PopDisabled() { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } -bool ImGui::Button(const char* label, bool disabled) -{ +bool ImGui::Button(const char* label, bool disabled) { return Button(label, ImVec2{}, disabled); } -bool ImGui::Button(const char* label, const ImVec2& sizeArg, bool disabled) -{ +bool ImGui::Button(const char* label, const ImVec2& sizeArg, bool disabled) { if (disabled) PushDisabled(); bool res = ImGui::Button(label, sizeArg); if (disabled) PopDisabled(); @@ -47,15 +41,13 @@ bool ImGui::Button(const char* label, const ImVec2& sizeArg, bool disabled) return res; } -void ImGui::ErrorIcon() -{ +void ImGui::ErrorIcon() { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4{ 237 / 255.0f, 67 / 255.0f, 55 / 255.0f, 1.0f }); // #ED4337 ImGui::Text(ICON_FA_EXCLAMATION_CIRCLE); ImGui::PopStyleColor(); } -void ImGui::ErrorMessage(const char* fmt, ...) -{ +void ImGui::ErrorMessage(const char* fmt, ...) { ErrorIcon(); SameLine(); @@ -65,15 +57,13 @@ void ImGui::ErrorMessage(const char* fmt, ...) va_end(args); } -void ImGui::WarningIcon() -{ +void ImGui::WarningIcon() { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4{ 255 / 255.0f, 184 / 255.0f, 24 / 255.0f, 1.0f }); // #FFB818 ImGui::Text(ICON_FA_EXCLAMATION_TRIANGLE); ImGui::PopStyleColor(); } -void ImGui::WarningMessage(const char* fmt, ...) -{ +void ImGui::WarningMessage(const char* fmt, ...) { WarningIcon(); SameLine(); @@ -83,8 +73,7 @@ void ImGui::WarningMessage(const char* fmt, ...) va_end(args); } -void ImGui::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2& b, IconType type, bool filled, ImU32 color, ImU32 innerColor) -{ +void ImGui::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2& b, IconType type, bool filled, ImU32 color, ImU32 innerColor) { // Taken from https://github.com/thedmd/imgui-node-editor/blob/master/examples/blueprints-example/utilities/drawing.cpp // ax::NodeEditor::DrawIcon @@ -109,7 +98,7 @@ void ImGui::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2& b, Ico const auto margin = 2.0f * origin_scale; const auto rounding = 0.1f * origin_scale; const auto tip_round = 0.7f; // percentage of triangle edge (for tip) - //const auto edge_round = 0.7f; // percentage of triangle edge (for corner) + // const auto edge_round = 0.7f; // percentage of triangle edge (for corner) const auto canvas = ImRect( rect.Min.x + margin + offset_x, rect.Min.y + margin + offset_y, @@ -125,7 +114,7 @@ void ImGui::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2& b, Ico const auto top = canvas_y + canvas_h * 0.5f * 0.2f; const auto bottom = canvas_y + canvas_h - canvas_h * 0.5f * 0.2f; const auto center_y = (top + bottom) * 0.5f; - //const auto angle = AX_PI * 0.5f * 0.5f * 0.5f; + // const auto angle = AX_PI * 0.5f * 0.5f * 0.5f; const auto tip_top = ImVec2(canvas_x + canvas_w * 0.5f, top); const auto tip_right = ImVec2(right, center_y); @@ -285,8 +274,7 @@ void ImGui::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2& b, Ico } } -void ImGui::Icon(const ImVec2& size, IconType type, bool filled, const ImVec4& color, const ImVec4& innerColor) -{ +void ImGui::Icon(const ImVec2& size, IconType type, bool filled, const ImVec4& color, const ImVec4& innerColor) { // Taken from https://github.com/thedmd/imgui-node-editor/blob/master/examples/blueprints-example/utilities/widgets.cpp // ax::NodeEditor::Icon @@ -300,8 +288,7 @@ void ImGui::Icon(const ImVec2& size, IconType type, bool filled, const ImVec4& c ImGui::Dummy(size); } -bool ImGui::Splitter(bool splitVertically, float thickness, float* size1, float* size2, float minSize1, float minSize2, float splitterLongAxisSize) -{ +bool ImGui::Splitter(bool splitVertically, float thickness, float* size1, float* size2, float minSize1, float minSize2, float splitterLongAxisSize) { // Taken from https://github.com/thedmd/imgui-node-editor/blob/master/examples/blueprints-example/blueprints-example.cpp // ::Splitter diff --git a/app/source/Cplt/UI/UI_Workflows.cpp b/app/source/Cplt/UI/UI_Workflows.cpp index 5eea53a..5d28372 100644 --- a/app/source/Cplt/UI/UI_Workflows.cpp +++ b/app/source/Cplt/UI/UI_Workflows.cpp @@ -21,8 +21,7 @@ namespace ImNodes = ax::NodeEditor; namespace CPLT_UNITY_ID { -class WorkflowUI -{ +class WorkflowUI { private: std::unique_ptr<Workflow> mWorkflow; @@ -34,18 +33,15 @@ private: public: WorkflowUI(std::unique_ptr<Workflow> workflow) - : mWorkflow{ std::move(workflow) } - { + : mWorkflow{ std::move(workflow) } { mContext = ImNodes::CreateEditor(); } - ~WorkflowUI() - { + ~WorkflowUI() { ImNodes::DestroyEditor(mContext); } - void Display() - { + void Display() { ImNodes::SetCurrentEditor(mContext); ImNodes::Begin(""); @@ -236,15 +232,13 @@ public: ImNodes::End(); } - void Close() - { + void Close() { // TODO } }; } // namespace CPLT_UNITY_ID -void UI::WorkflowsTab() -{ +void UI::WorkflowsTab() { auto& project = *GlobalStates::GetInstance().GetCurrentProject(); static std::unique_ptr<CPLT_UNITY_ID::WorkflowUI> openWorkflow; diff --git a/app/source/Cplt/Utils/Color.hpp b/app/source/Cplt/Utils/Color.hpp index 15fe6a1..6d56951 100644 --- a/app/source/Cplt/Utils/Color.hpp +++ b/app/source/Cplt/Utils/Color.hpp @@ -9,8 +9,7 @@ #include <cstdint> #include <limits> -class RgbaColor -{ +class RgbaColor { public: uint8_t r; uint8_t g; @@ -22,36 +21,31 @@ public: : r{ 255 } , g{ 255 } , b{ 255 } - , a{ 255 } - { + , a{ 255 } { } constexpr RgbaColor(float r, float g, float b, float a = 1.0f) noexcept : r{ static_cast<uint8_t>(r * 255.0f) } , g{ static_cast<uint8_t>(g * 255.0f) } , b{ static_cast<uint8_t>(b * 255.0f) } - , a{ static_cast<uint8_t>(a * 255.0f) } - { + , a{ static_cast<uint8_t>(a * 255.0f) } { } constexpr RgbaColor(int r, int g, int b, int a = 255) noexcept : r{ static_cast<uint8_t>(r & 0xFF) } , g{ static_cast<uint8_t>(g & 0xFF) } , b{ static_cast<uint8_t>(b & 0xFF) } - , a{ static_cast<uint8_t>(a & 0xFF) } - { + , a{ static_cast<uint8_t>(a & 0xFF) } { } constexpr RgbaColor(uint32_t rgba) noexcept : r{ static_cast<uint8_t>((rgba >> 0) & 0xFF) } , g{ static_cast<uint8_t>((rgba >> 8) & 0xFF) } , b{ static_cast<uint8_t>((rgba >> 16) & 0xFF) } - , a{ static_cast<uint8_t>((rgba >> 24) & 0xFF) } - { + , a{ static_cast<uint8_t>((rgba >> 24) & 0xFF) } { } - constexpr uint32_t GetScalar() const noexcept - { + constexpr uint32_t GetScalar() const noexcept { uint32_t res = 0; res |= r << 24; res |= g << 16; @@ -60,41 +54,34 @@ public: return res; } - constexpr void SetScalar(uint32_t scalar) noexcept - { + constexpr void SetScalar(uint32_t scalar) noexcept { r = (scalar >> 0) & 0xFF; g = (scalar >> 8) & 0xFF; b = (scalar >> 16) & 0xFF; a = (scalar >> 24) & 0xFF; } - constexpr float GetNormalizedRed() const noexcept - { + constexpr float GetNormalizedRed() const noexcept { return r / 255.0f; } - constexpr float GetNormalizedGreen() const noexcept - { + constexpr float GetNormalizedGreen() const noexcept { return g / 255.0f; } - constexpr float GetNormalizedBlue() const noexcept - { + constexpr float GetNormalizedBlue() const noexcept { return b / 255.0f; } - constexpr float GetNormalizedAlpha() const noexcept - { + constexpr float GetNormalizedAlpha() const noexcept { return a / 255.0f; } - constexpr Vec4i AsVec4i() const noexcept - { + constexpr Vec4i AsVec4i() const noexcept { return Vec4i{ r, g, b, a }; } - constexpr Vec4f AsVec4f() const noexcept - { + constexpr Vec4f AsVec4f() const noexcept { return Vec4f{ GetNormalizedRed(), GetNormalizedGreen(), @@ -103,20 +90,17 @@ public: }; } - ImVec4 AsImVec() const - { + ImVec4 AsImVec() const { auto v = AsVec4f(); return ImVec4{ v.x, v.y, v.z, v.w }; } - ImColor AsImColor() const - { + ImColor AsImColor() const { auto v = AsVec4f(); return ImColor{ v.x, v.y, v.z, v.w }; } - ImU32 AsImU32() const - { + ImU32 AsImU32() const { ImU32 res; res |= r << IM_COL32_R_SHIFT; res |= g << IM_COL32_G_SHIFT; @@ -125,8 +109,7 @@ public: return res; } - constexpr void SetVec(const Vec4f& vec) noexcept - { + constexpr void SetVec(const Vec4f& vec) noexcept { r = (uint8_t)(vec.x * 255.0f); g = (uint8_t)(vec.y * 255.0f); b = (uint8_t)(vec.z * 255.0f); @@ -139,8 +122,7 @@ public: friend constexpr bool operator==(const RgbaColor&, const RgbaColor&) noexcept = default; }; -class HsvColor -{ +class HsvColor { public: float h; float s; @@ -152,24 +134,21 @@ public: : h{ 0.0f } , s{ 0.0f } , v{ 1.0f } - , a{ 1.0f } - { + , a{ 1.0f } { } constexpr HsvColor(float h, float s, float v, float a) noexcept : h{ h } , s{ s } , v{ v } - , a{ a } - { + , a{ a } { } // Forward declaring because cyclic reference between RgbaColor and HsvColor constexpr RgbaColor ToRgba() const noexcept; }; -constexpr HsvColor RgbaColor::ToHsv() const noexcept -{ +constexpr HsvColor RgbaColor::ToHsv() const noexcept { float fr = GetNormalizedRed(); float fg = GetNormalizedBlue(); float fb = GetNormalizedGreen(); @@ -185,8 +164,7 @@ constexpr HsvColor RgbaColor::ToHsv() const noexcept return HsvColor(hcv.x, s, hcv.z, fa); } -constexpr RgbaColor HsvColor::ToRgba() const noexcept -{ +constexpr RgbaColor HsvColor::ToRgba() const noexcept { float r = MathUtils::Abs(h * 6 - 3) - 1; float g = 2 - MathUtils::Abs(h * 6 - 2); float b = 2 - MathUtils::Abs(h * 6 - 4); diff --git a/app/source/Cplt/Utils/Hash.hpp b/app/source/Cplt/Utils/Hash.hpp index cf7713a..de8e63b 100644 --- a/app/source/Cplt/Utils/Hash.hpp +++ b/app/source/Cplt/Utils/Hash.hpp @@ -6,8 +6,7 @@ namespace HashUtils { template <class T> -void Combine(size_t& seed, const T& v) -{ +void Combine(size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } diff --git a/app/source/Cplt/Utils/IO/Archive.cpp b/app/source/Cplt/Utils/IO/Archive.cpp index f6e7b27..2be18bc 100644 --- a/app/source/Cplt/Utils/IO/Archive.cpp +++ b/app/source/Cplt/Utils/IO/Archive.cpp @@ -10,13 +10,11 @@ constexpr uint8_t kByteOrderMark = []() { } }(); -std::span<const uint8_t, 8> DataArchive::GetMagicNumbers() -{ +std::span<const uint8_t, 8> DataArchive::GetMagicNumbers() { return std::span<const uint8_t, 8>{ kMagicNumbers }; } -std::optional<InputDataStream> DataArchive::LoadFile(const std::filesystem::path& path) -{ +std::optional<InputDataStream> DataArchive::LoadFile(const std::filesystem::path& path) { InputFileStream fileStream(path); fileStream.SetReadInSize(1024); InputDataStream stream(std::move(fileStream)); @@ -42,8 +40,7 @@ std::optional<InputDataStream> DataArchive::LoadFile(const std::filesystem::path return stream; } -std::optional<OutputDataStream> DataArchive::SaveFile(const std::filesystem::path& path) -{ +std::optional<OutputDataStream> DataArchive::SaveFile(const std::filesystem::path& path) { OutputFileStream fileStream(path, OutputFileStream::TruncateFile); fileStream.SetMaxBufferSize(1024); OutputDataStream stream(std::move(fileStream)); diff --git a/app/source/Cplt/Utils/IO/Archive.hpp b/app/source/Cplt/Utils/IO/Archive.hpp index 7632f3b..179db25 100644 --- a/app/source/Cplt/Utils/IO/Archive.hpp +++ b/app/source/Cplt/Utils/IO/Archive.hpp @@ -7,8 +7,7 @@ #include <optional> #include <span> -class DataArchive -{ +class DataArchive { public: static std::span<const uint8_t, 8> GetMagicNumbers(); diff --git a/app/source/Cplt/Utils/IO/CstdioFile.cpp b/app/source/Cplt/Utils/IO/CstdioFile.cpp index c414dfb..0496fa1 100644 --- a/app/source/Cplt/Utils/IO/CstdioFile.cpp +++ b/app/source/Cplt/Utils/IO/CstdioFile.cpp @@ -12,8 +12,7 @@ #endif namespace CPLT_UNITY_ID { -auto GetModeString(FileUtils::IoMode mode) -{ +auto GetModeString(FileUtils::IoMode mode) { switch (mode) { case FileUtils::IM_Read: return MODE_STRING("rb"); case FileUtils::IM_WriteAppend: return MODE_STRING("ab"); @@ -25,8 +24,7 @@ auto GetModeString(FileUtils::IoMode mode) #pragma pop_macro("MODE_STRING") -FILE* FileUtils::OpenCstdioFile(const std::filesystem::path& path, IoMode mode) -{ +FILE* FileUtils::OpenCstdioFile(const std::filesystem::path& path, IoMode mode) { #ifdef _WIN32 // std::filesystem::path::c_str() returns `const wchar_t*` under Windows, because NT uses UTF-16 natively return _wfopen(path.c_str(), ::GetModeString(mode)); diff --git a/app/source/Cplt/Utils/IO/CstdioFile.hpp b/app/source/Cplt/Utils/IO/CstdioFile.hpp index e863dd5..32957a2 100644 --- a/app/source/Cplt/Utils/IO/CstdioFile.hpp +++ b/app/source/Cplt/Utils/IO/CstdioFile.hpp @@ -5,8 +5,7 @@ namespace FileUtils { -enum IoMode -{ +enum IoMode { IM_Read, IM_WriteAppend, IM_WriteTruncate, diff --git a/app/source/Cplt/Utils/IO/DataStream.cpp b/app/source/Cplt/Utils/IO/DataStream.cpp index c0797e3..14afa04 100644 --- a/app/source/Cplt/Utils/IO/DataStream.cpp +++ b/app/source/Cplt/Utils/IO/DataStream.cpp @@ -11,15 +11,13 @@ static_assert(std::endian::native == std::endian::little || std::endian::native // Reading/writing signed integer byte-by-byte is fine, since the representation got fixed to 2's complements in C++20 -static uint16_t ByteSwap(uint16_t n) -{ +static uint16_t ByteSwap(uint16_t n) { auto bytes = reinterpret_cast<std::byte*>(n); std::swap(bytes[0], bytes[1]); return n; } -static uint32_t ByteSwap(uint32_t n) -{ +static uint32_t ByteSwap(uint32_t n) { #ifdef _MSC_VER return _byteswap_ulong(n); #else @@ -27,8 +25,7 @@ static uint32_t ByteSwap(uint32_t n) #endif } -static uint64_t ByteSwap(uint64_t n) -{ +static uint64_t ByteSwap(uint64_t n) { #ifdef _MSC_VER return _byteswap_uint64(n); #else @@ -37,57 +34,47 @@ static uint64_t ByteSwap(uint64_t n) } template <class TSigned> -static TSigned ByteSwap(TSigned n) -{ +static TSigned ByteSwap(TSigned n) { using Unsigned = std::make_unsigned_t<TSigned>; auto swapped = ::ByteSwap(std::bit_cast<Unsigned>(n)); return std::bit_cast<TSigned>(swapped); } -std::endian BaseDataStream::GetEndianness() const -{ +std::endian BaseDataStream::GetEndianness() const { return mEndian; } -void BaseDataStream::SetEndianness(std::endian endianness) -{ +void BaseDataStream::SetEndianness(std::endian endianness) { mEndian = endianness; } InputDataStream::InputDataStream(InputFileStream stream) - : mBackend{ std::move(stream) } -{ + : mBackend{ std::move(stream) } { } -void InputDataStream::ReadBytes(size_t byteCount, std::byte* buffer) -{ +void InputDataStream::ReadBytes(size_t byteCount, std::byte* buffer) { mBackend.ReadBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<std::byte*>(buffer)); } -void InputDataStream::ReadBytes(size_t byteCount, char* buffer) -{ +void InputDataStream::ReadBytes(size_t byteCount, char* buffer) { mBackend.ReadBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<std::byte*>(buffer)); } -void InputDataStream::ReadBytes(size_t byteCount, signed char* buffer) -{ +void InputDataStream::ReadBytes(size_t byteCount, signed char* buffer) { mBackend.ReadBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<std::byte*>(buffer)); } -void InputDataStream::ReadBytes(size_t byteCount, unsigned char* buffer) -{ +void InputDataStream::ReadBytes(size_t byteCount, unsigned char* buffer) { mBackend.ReadBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<std::byte*>(buffer)); } -void InputDataStream::Read(int8_t& n) -{ +void InputDataStream::Read(int8_t& n) { // sizeof() of a reference type yields the size of the reference mBackend.ReadBytes(sizeof(n), reinterpret_cast<std::byte*>(&n)); } -void InputDataStream::Read(int16_t& n) -{ +void InputDataStream::Read(int16_t& n) { int16_t tmp; mBackend.ReadBytes(sizeof(tmp), reinterpret_cast<std::byte*>(&tmp)); if (GetEndianness() != std::endian::native) { @@ -97,8 +84,7 @@ void InputDataStream::Read(int16_t& n) } } -void InputDataStream::Read(int32_t& n) -{ +void InputDataStream::Read(int32_t& n) { int32_t tmp; mBackend.ReadBytes(sizeof(tmp), reinterpret_cast<std::byte*>(&tmp)); if (GetEndianness() != std::endian::native) { @@ -108,8 +94,7 @@ void InputDataStream::Read(int32_t& n) } } -void InputDataStream::Read(int64_t& n) -{ +void InputDataStream::Read(int64_t& n) { int64_t tmp; mBackend.ReadBytes(sizeof(tmp), reinterpret_cast<std::byte*>(&tmp)); if (GetEndianness() != std::endian::native) { @@ -119,13 +104,11 @@ void InputDataStream::Read(int64_t& n) } } -void InputDataStream::Read(uint8_t& n) -{ +void InputDataStream::Read(uint8_t& n) { mBackend.ReadBytes(sizeof(n), reinterpret_cast<std::byte*>(&n)); } -void InputDataStream::Read(uint16_t& n) -{ +void InputDataStream::Read(uint16_t& n) { uint16_t tmp; mBackend.ReadBytes(sizeof(tmp), reinterpret_cast<std::byte*>(&tmp)); if (GetEndianness() != std::endian::native) { @@ -135,8 +118,7 @@ void InputDataStream::Read(uint16_t& n) } } -void InputDataStream::Read(uint32_t& n) -{ +void InputDataStream::Read(uint32_t& n) { uint32_t tmp; mBackend.ReadBytes(sizeof(tmp), reinterpret_cast<std::byte*>(&tmp)); if (GetEndianness() != std::endian::native) { @@ -146,8 +128,7 @@ void InputDataStream::Read(uint32_t& n) } } -void InputDataStream::Read(uint64_t& n) -{ +void InputDataStream::Read(uint64_t& n) { uint64_t tmp; mBackend.ReadBytes(sizeof(tmp), reinterpret_cast<std::byte*>(&tmp)); if (GetEndianness() != std::endian::native) { @@ -157,8 +138,7 @@ void InputDataStream::Read(uint64_t& n) } } -void InputDataStream::Read(float& n) -{ +void InputDataStream::Read(float& n) { uint32_t buffer; Read(buffer); @@ -169,8 +149,7 @@ void InputDataStream::Read(float& n) n = std::bit_cast<float>(buffer); } -void InputDataStream::Read(double& n) -{ +void InputDataStream::Read(double& n) { uint64_t buffer; Read(buffer); @@ -182,90 +161,76 @@ void InputDataStream::Read(double& n) } OutputDataStream::OutputDataStream(OutputFileStream stream) - : mBackend{ std::move(stream) } -{ + : mBackend{ std::move(stream) } { } -void OutputDataStream::WriteBytes(size_t byteCount, const std::byte* buffer) -{ +void OutputDataStream::WriteBytes(size_t byteCount, const std::byte* buffer) { mBackend.WriteBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<const std::byte*>(buffer)); } -void OutputDataStream::WriteBytes(size_t byteCount, const char* buffer) -{ +void OutputDataStream::WriteBytes(size_t byteCount, const char* buffer) { mBackend.WriteBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<const std::byte*>(buffer)); } -void OutputDataStream::WriteBytes(size_t byteCount, const signed char* buffer) -{ +void OutputDataStream::WriteBytes(size_t byteCount, const signed char* buffer) { mBackend.WriteBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<const std::byte*>(buffer)); } -void OutputDataStream::WriteBytes(size_t byteCount, const unsigned char* buffer) -{ +void OutputDataStream::WriteBytes(size_t byteCount, const unsigned char* buffer) { mBackend.WriteBytes(static_cast<std::streamsize>(byteCount), reinterpret_cast<const std::byte*>(buffer)); } -void OutputDataStream::Write(int8_t n) -{ +void OutputDataStream::Write(int8_t n) { mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(int16_t n) -{ +void OutputDataStream::Write(int16_t n) { if (GetEndianness() != std::endian::native) { n = ::ByteSwap(n); } mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(int32_t n) -{ +void OutputDataStream::Write(int32_t n) { if (GetEndianness() != std::endian::native) { n = ::ByteSwap(n); } mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(int64_t n) -{ +void OutputDataStream::Write(int64_t n) { if (GetEndianness() != std::endian::native) { n = ::ByteSwap(n); } mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(uint8_t n) -{ +void OutputDataStream::Write(uint8_t n) { mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(uint16_t n) -{ +void OutputDataStream::Write(uint16_t n) { if (GetEndianness() != std::endian::native) { n = ::ByteSwap(n); } mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(uint32_t n) -{ +void OutputDataStream::Write(uint32_t n) { if (GetEndianness() != std::endian::native) { n = ::ByteSwap(n); } mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(uint64_t n) -{ +void OutputDataStream::Write(uint64_t n) { if (GetEndianness() != std::endian::native) { n = ::ByteSwap(n); } mBackend.WriteBytes(sizeof(n), reinterpret_cast<const std::byte*>(&n)); } -void OutputDataStream::Write(float n) -{ +void OutputDataStream::Write(float n) { auto buffer = std::bit_cast<uint32_t>(n); if (GetEndianness() != std::endian::native) { buffer = ::ByteSwap(buffer); @@ -273,8 +238,7 @@ void OutputDataStream::Write(float n) mBackend.WriteBytes(sizeof(buffer), reinterpret_cast<const std::byte*>(&buffer)); } -void OutputDataStream::Write(double n) -{ +void OutputDataStream::Write(double n) { auto buffer = std::bit_cast<uint64_t>(n); if (GetEndianness() != std::endian::native) { buffer = ::ByteSwap(buffer); diff --git a/app/source/Cplt/Utils/IO/DataStream.hpp b/app/source/Cplt/Utils/IO/DataStream.hpp index 133adc2..770cebc 100644 --- a/app/source/Cplt/Utils/IO/DataStream.hpp +++ b/app/source/Cplt/Utils/IO/DataStream.hpp @@ -8,8 +8,7 @@ #include <cstdint> #include <span> -class BaseDataStream -{ +class BaseDataStream { private: std::endian mEndian = std::endian::big; @@ -18,14 +17,12 @@ public: void SetEndianness(std::endian endianness); }; -class InputDataStream : public BaseDataStream -{ +class InputDataStream : public BaseDataStream { private: InputFileStream mBackend; public: - static constexpr bool IsSerializer() - { + static constexpr bool IsSerializer() { return false; } @@ -37,8 +34,7 @@ public: void ReadBytes(size_t byteCount, unsigned char* buffer); template <class TInserter> - void ReadBytes(size_t byteCount, TInserter&& inserter) - { + void ReadBytes(size_t byteCount, TInserter&& inserter) { for (size_t i = 0; i < byteCount; ++i) { uint8_t byte; Read(byte); @@ -62,22 +58,19 @@ public: template <class TEnum> requires std::is_enum_v<TEnum> - void ReadEnum(TEnum& e) - { + void ReadEnum(TEnum& e) { std::underlying_type_t<TEnum> n; Read(n); e = static_cast<TEnum>(e); } template <class TObject> - void ReadObject(TObject& obj) - { + void ReadObject(TObject& obj) { obj.ReadFromDataStream(*this); } template <class TAdapter, class TObject> - void ReadObjectAdapted(TObject& obj) - { + void ReadObjectAdapted(TObject& obj) { TAdapter::ReadFromDataStream(*this, obj); } @@ -85,44 +78,37 @@ public: // Proxy functions for writing templated IO functions template <class T> - void Bytes(size_t byteCount, T* buffer) - { + void Bytes(size_t byteCount, T* buffer) { ReadBytes(byteCount, buffer); } template <class T> - void Value(T& t) - { + void Value(T& t) { Read(t); } template <class T> - void Enum(T& t) - { + void Enum(T& t) { ReadEnum(t); } template <class T> - void Object(T& obj) - { + void Object(T& obj) { ReadObject(obj); } template <class TAdapter, class TObject> - void ObjectAdapted(TObject& obj) - { + void ObjectAdapted(TObject& obj) { ReadObjectAdapted<TAdapter>(obj); } }; -class OutputDataStream : public BaseDataStream -{ +class OutputDataStream : public BaseDataStream { private: OutputFileStream mBackend; public: - static constexpr bool IsSerializer() - { + static constexpr bool IsSerializer() { return true; } @@ -134,8 +120,7 @@ public: void WriteBytes(size_t byteCount, const unsigned char* buffer); template <class TIterator> - void WriteBytes(TIterator&& begin, TIterator&& end) - { + void WriteBytes(TIterator&& begin, TIterator&& end) { for (; begin != end; ++begin) { uint8_t byte = *begin; Write(byte); @@ -157,21 +142,18 @@ public: template <class TEnum> requires std::is_enum_v<TEnum> - void WriteEnum(TEnum e) - { + void WriteEnum(TEnum e) { auto n = static_cast<std::underlying_type_t<TEnum>>(e); Write(n); } template <class TObject> - void WriteObject(const TObject& obj) - { + void WriteObject(const TObject& obj) { obj.WriteToDataStream(*this); } template <class TAdapter, class TObject> - void WriteObjectAdapted(const TObject& obj) - { + void WriteObjectAdapted(const TObject& obj) { TAdapter::WriteToDataStream(*this, obj); } @@ -179,32 +161,27 @@ public: // Proxy functions for writing templated IO functions template <class T> - void Bytes(size_t byteCount, T* buffer) - { + void Bytes(size_t byteCount, T* buffer) { WriteBytes(byteCount, buffer); } template <class T> - void Value(T t) - { + void Value(T t) { Write(t); } template <class T> - void Enum(T t) - { + void Enum(T t) { WriteEnum(t); } template <class T> - void Object(T& obj) - { + void Object(T& obj) { WriteObject(obj); } template <class TAdapter, class TObject> - void ObjectAdapted(TObject& obj) - { + void ObjectAdapted(TObject& obj) { WriteObjectAdapted<TAdapter>(obj); } }; diff --git a/app/source/Cplt/Utils/IO/FileStream.hpp b/app/source/Cplt/Utils/IO/FileStream.hpp index 453ddbe..37b2a36 100644 --- a/app/source/Cplt/Utils/IO/FileStream.hpp +++ b/app/source/Cplt/Utils/IO/FileStream.hpp @@ -8,10 +8,8 @@ // TODO switch to custom when unit tests are ready and bugs are fixed #define CPLT_FILESTREAM_USE_CSTDIO -struct IoResult -{ - enum ErrorKind - { +struct IoResult { + enum ErrorKind { ERR_None, ERR_PermissionDenied, ERR_UnexpectedEof, @@ -25,8 +23,7 @@ struct IoResult size_t BytesMoved; }; -class InputFileStream -{ +class InputFileStream { private: #if defined(CPLT_FILESTREAM_USE_CSTDIO) FILE* mFile; @@ -60,11 +57,9 @@ public: IoResult ReadBytes(size_t bufferLength, std::byte* buffer); }; -class OutputFileStream -{ +class OutputFileStream { public: - enum WriteMode - { + enum WriteMode { AppendFile, TruncateFile, }; diff --git a/app/source/Cplt/Utils/IO/Helper.hpp b/app/source/Cplt/Utils/IO/Helper.hpp index 7a84103..b8f4e6f 100644 --- a/app/source/Cplt/Utils/IO/Helper.hpp +++ b/app/source/Cplt/Utils/IO/Helper.hpp @@ -7,8 +7,7 @@ namespace DataStreamAdapters { /// Helper to invoke either Read() or ReadObject(). /// This is intended for writing IO adapters, users that's writing IO logic shouldn't using this - it increases compile time while reducing readability. template <class TAdapter, class T> -void ReadHelper(InputDataStream& stream, T& t) -{ +void ReadHelper(InputDataStream& stream, T& t) { if constexpr (!std::is_same_v<TAdapter, void>) { stream.ReadObjectAdapted<TAdapter>(t); } else if constexpr (requires(T tt, InputDataStream ss) { ss.Read(tt); }) { @@ -25,8 +24,7 @@ void ReadHelper(InputDataStream& stream, T& t) /// Helper to invoke either Write() or WriteObject(). /// This is intended for writing IO adapters, users that's writing IO logic shouldn't using this - it increases compile time while reducing readability. template <class TAdapter, class T> -void WriteHelper(OutputDataStream& stream, T& t) -{ +void WriteHelper(OutputDataStream& stream, T& t) { if constexpr (!std::is_same_v<TAdapter, void>) { stream.WriteObjectAdapted<TAdapter>(t); } else if constexpr (requires(T tt, OutputDataStream ss) { ss.Write(tt); }) { diff --git a/app/source/Cplt/Utils/IO/StringIntegration.hpp b/app/source/Cplt/Utils/IO/StringIntegration.hpp index 66f42b0..3ff715a 100644 --- a/app/source/Cplt/Utils/IO/StringIntegration.hpp +++ b/app/source/Cplt/Utils/IO/StringIntegration.hpp @@ -7,10 +7,8 @@ #include <string_view> namespace DataStreamAdapters { -struct String -{ - static void ReadFromDataStream(InputDataStream& stream, std::string& str) - { +struct String { + static void ReadFromDataStream(InputDataStream& stream, std::string& str) { uint64_t size; stream.Read(size); @@ -19,17 +17,14 @@ struct String stream.ReadBytes(size, std::back_inserter(str)); } - static void WriteToDataStream(OutputDataStream& stream, const std::string& str) - { + static void WriteToDataStream(OutputDataStream& stream, const std::string& str) { stream.Write((uint64_t)str.size()); stream.WriteBytes(str.size(), str.data()); } }; -struct StringView -{ - static void WriteToDataStream(OutputDataStream& stream, const std::string_view& str) - { +struct StringView { + static void WriteToDataStream(OutputDataStream& stream, const std::string_view& str) { stream.Write((uint64_t)str.size()); stream.WriteBytes(str.size(), str.data()); } diff --git a/app/source/Cplt/Utils/IO/TslArrayIntegration.hpp b/app/source/Cplt/Utils/IO/TslArrayIntegration.hpp index b585bee..1215c3b 100644 --- a/app/source/Cplt/Utils/IO/TslArrayIntegration.hpp +++ b/app/source/Cplt/Utils/IO/TslArrayIntegration.hpp @@ -13,11 +13,9 @@ namespace DataStreamAdapters { template <class TAdapter = void> -struct TslArrayMap -{ +struct TslArrayMap { template <class TValue> - static void ReadFromDataStream(InputDataStream& stream, tsl::array_map<char, TValue>& map) - { + static void ReadFromDataStream(InputDataStream& stream, tsl::array_map<char, TValue>& map) { static_assert(std::is_default_constructible_v<TValue>); static_assert(std::is_move_constructible_v<TValue>); @@ -37,8 +35,7 @@ struct TslArrayMap } template <class TValue> - static void WriteToDataStream(OutputDataStream& stream, const tsl::array_map<char, TValue>& map) - { + static void WriteToDataStream(OutputDataStream& stream, const tsl::array_map<char, TValue>& map) { stream.Write((uint64_t)map.size()); for (auto it = map.begin(); it != map.end(); ++it) { diff --git a/app/source/Cplt/Utils/IO/TslRobinIntegration.hpp b/app/source/Cplt/Utils/IO/TslRobinIntegration.hpp index bdea505..a19a4f1 100644 --- a/app/source/Cplt/Utils/IO/TslRobinIntegration.hpp +++ b/app/source/Cplt/Utils/IO/TslRobinIntegration.hpp @@ -9,11 +9,9 @@ namespace DataStreamAdapters { template <class TKeyAdapter = void, class TValueAdapter = void> -struct TslRobinMap -{ +struct TslRobinMap { template <class TKey, class TValue> - static void ReadFromDataStream(InputDataStream& stream, tsl::robin_map<TKey, TValue>& map) - { + static void ReadFromDataStream(InputDataStream& stream, tsl::robin_map<TKey, TValue>& map) { static_assert(std::is_default_constructible_v<TValue>); static_assert(std::is_move_constructible_v<TValue>); @@ -33,8 +31,7 @@ struct TslRobinMap } template <class TKey, class TValue> - static void WriteToDataStream(OutputDataStream& stream, const tsl::robin_map<TKey, TValue>& map) - { + static void WriteToDataStream(OutputDataStream& stream, const tsl::robin_map<TKey, TValue>& map) { stream.Write((uint64_t)map.size()); for (auto it = map.begin(); it != map.end(); ++it) { @@ -45,11 +42,9 @@ struct TslRobinMap }; template <class TAdapter = void> -struct TslRobinSet -{ +struct TslRobinSet { template <class TElement> - static void ReadFromDataStream(InputDataStream& stream, tsl::robin_set<TElement>& set) - { + static void ReadFromDataStream(InputDataStream& stream, tsl::robin_set<TElement>& set) { static_assert(std::is_default_constructible_v<TElement>); static_assert(std::is_move_constructible_v<TElement>); @@ -66,8 +61,7 @@ struct TslRobinSet } template <class TElement> - static void WriteToDataStream(OutputDataStream& stream, const tsl::robin_set<TElement>& set) - { + static void WriteToDataStream(OutputDataStream& stream, const tsl::robin_set<TElement>& set) { stream.Write((uint64_t)set.size()); for (auto& element : set) { diff --git a/app/source/Cplt/Utils/IO/UuidIntegration.hpp b/app/source/Cplt/Utils/IO/UuidIntegration.hpp index 20c1e7e..49afd19 100644 --- a/app/source/Cplt/Utils/IO/UuidIntegration.hpp +++ b/app/source/Cplt/Utils/IO/UuidIntegration.hpp @@ -8,18 +8,15 @@ #include <iterator> namespace DataStreamAdapters { -struct Uuid -{ - static void ReadFromDataStream(InputDataStream& stream, uuids::uuid& uuid) - { +struct Uuid { + static void ReadFromDataStream(InputDataStream& stream, uuids::uuid& uuid) { uint8_t buffer[16]; stream.ReadBytes(16, buffer); uuid = uuids::uuid(gsl::span<uint8_t, 16>{ buffer }); } - static void WriteToDataStream(OutputDataStream& stream, const uuids::uuid& uuid) - { + static void WriteToDataStream(OutputDataStream& stream, const uuids::uuid& uuid) { auto gslSpan = uuid.as_bytes(); stream.WriteBytes(gslSpan.size(), gslSpan.data()); } diff --git a/app/source/Cplt/Utils/IO/VectorIntegration.hpp b/app/source/Cplt/Utils/IO/VectorIntegration.hpp index 93967f6..e1a6108 100644 --- a/app/source/Cplt/Utils/IO/VectorIntegration.hpp +++ b/app/source/Cplt/Utils/IO/VectorIntegration.hpp @@ -8,11 +8,9 @@ namespace DataStreamAdapters { template <class TAdapter = void> -struct Vector -{ +struct Vector { template <class TElement> - static void ReadFromDataStream(InputDataStream& stream, std::vector<TElement>& vec) - { + static void ReadFromDataStream(InputDataStream& stream, std::vector<TElement>& vec) { static_assert(std::is_default_constructible_v<TElement>); static_assert(std::is_move_constructible_v<TElement>); @@ -31,8 +29,7 @@ struct Vector } template <class TElement> - static void WriteToDataStream(OutputDataStream& stream, const std::vector<TElement>& vec) - { + static void WriteToDataStream(OutputDataStream& stream, const std::vector<TElement>& vec) { stream.Write((uint64_t)vec.size()); for (auto& element : vec) { WriteHelper<TAdapter>(stream, element); diff --git a/app/source/Cplt/Utils/Math.hpp b/app/source/Cplt/Utils/Math.hpp index da53da2..0e760c1 100644 --- a/app/source/Cplt/Utils/Math.hpp +++ b/app/source/Cplt/Utils/Math.hpp @@ -3,8 +3,7 @@ namespace MathUtils { template <class T> -constexpr T Abs(T t) -{ +constexpr T Abs(T t) { return t < 0 ? -t : t; } diff --git a/app/source/Cplt/Utils/RTTI.hpp b/app/source/Cplt/Utils/RTTI.hpp index 86b1e2c..bc0d289 100644 --- a/app/source/Cplt/Utils/RTTI.hpp +++ b/app/source/Cplt/Utils/RTTI.hpp @@ -3,15 +3,13 @@ #include <cassert> template <class T, class TBase> -bool is_a(TBase* t) -{ +bool is_a(TBase* t) { assert(t != nullptr); return T::IsInstance(t); } template <class T, class TBase> -bool is_a_nullable(TBase* t) -{ +bool is_a_nullable(TBase* t) { if (t) { return is_a<T, TBase>(t); } else { @@ -20,8 +18,7 @@ bool is_a_nullable(TBase* t) } template <class T, class TBase> -T* dyn_cast(TBase* t) -{ +T* dyn_cast(TBase* t) { assert(t != nullptr); if (T::IsInstance(t)) { return static_cast<T*>(t); @@ -31,8 +28,7 @@ T* dyn_cast(TBase* t) } template <class T, class TBase> -const T* dyn_cast(const TBase* t) -{ +const T* dyn_cast(const TBase* t) { assert(t != nullptr); if (T::IsInstance(t)) { return static_cast<const T*>(t); @@ -42,8 +38,7 @@ const T* dyn_cast(const TBase* t) } template <class T, class TBase> -T* dyn_cast_nullable(TBase* t) -{ +T* dyn_cast_nullable(TBase* t) { if (!t) return nullptr; return dyn_cast<T, TBase>(t); } diff --git a/app/source/Cplt/Utils/ScopeGuard.hpp b/app/source/Cplt/Utils/ScopeGuard.hpp index f2b7f46..e7db2a4 100644 --- a/app/source/Cplt/Utils/ScopeGuard.hpp +++ b/app/source/Cplt/Utils/ScopeGuard.hpp @@ -5,8 +5,7 @@ #include <utility> template <class TCleanupFunc> -class ScopeGuard -{ +class ScopeGuard { private: TCleanupFunc mFunc; bool mDismissed = false; @@ -19,19 +18,16 @@ public: /// would work. It is highly discourage and unlikely that one would want to use ScopeGuard as a function /// parameter, so the normal argument that implicit conversion are harmful doesn't really apply here. ScopeGuard(TCleanupFunc func) - : mFunc{ std::move(func) } - { + : mFunc{ std::move(func) } { } - ~ScopeGuard() - { + ~ScopeGuard() { if (!mDismissed) { mFunc(); } } - void Dismiss() noexcept - { + void Dismiss() noexcept { mDismissed = true; } }; diff --git a/app/source/Cplt/Utils/Sigslot.cpp b/app/source/Cplt/Utils/Sigslot.cpp index 1132dfb..14deece 100644 --- a/app/source/Cplt/Utils/Sigslot.cpp +++ b/app/source/Cplt/Utils/Sigslot.cpp @@ -2,28 +2,23 @@ #include <doctest/doctest.h> -bool SignalStub::Connection::IsOccupied() const -{ +bool SignalStub::Connection::IsOccupied() const { return id != InvalidId; } SignalStub::SignalStub(IWrapper& wrapper) - : mWrapper{ &wrapper } -{ + : mWrapper{ &wrapper } { } -SignalStub::~SignalStub() -{ +SignalStub::~SignalStub() { RemoveAllConnections(); } -std::span<const SignalStub::Connection> SignalStub::GetConnections() const -{ +std::span<const SignalStub::Connection> SignalStub::GetConnections() const { return mConnections; } -SignalStub::Connection& SignalStub::InsertConnection(SlotGuard* guard) -{ +SignalStub::Connection& SignalStub::InsertConnection(SlotGuard* guard) { Connection* result; int size = static_cast<int>(mConnections.size()); for (int i = 0; i < size; ++i) { @@ -47,8 +42,7 @@ setup: return *result; } -void SignalStub::RemoveConnection(int id) -{ +void SignalStub::RemoveConnection(int id) { if (id >= 0 && id < mConnections.size()) { auto& conn = mConnections[id]; if (conn.IsOccupied()) { @@ -64,29 +58,24 @@ void SignalStub::RemoveConnection(int id) } } -void SignalStub::RemoveConnectionFor(SlotGuard& guard) -{ +void SignalStub::RemoveConnectionFor(SlotGuard& guard) { guard.RemoveConnectionFor(*this); } -void SignalStub::RemoveAllConnections() -{ +void SignalStub::RemoveAllConnections() { for (size_t i = 0; i < mConnections.size(); ++i) { RemoveConnection(i); } } -SlotGuard::SlotGuard() -{ +SlotGuard::SlotGuard() { } -SlotGuard::~SlotGuard() -{ +SlotGuard::~SlotGuard() { DisconnectAll(); } -void SlotGuard::DisconnectAll() -{ +void SlotGuard::DisconnectAll() { for (auto& conn : mConnections) { if (conn.stub) { // Also calls SlotGuard::removeConnection, our copy of the data will be cleared in it @@ -95,8 +84,7 @@ void SlotGuard::DisconnectAll() } } -int SlotGuard::InsertConnection(SignalStub& stub, int stubId) -{ +int SlotGuard::InsertConnection(SignalStub& stub, int stubId) { int size = static_cast<int>(mConnections.size()); for (int i = 0; i < size; ++i) { auto& conn = mConnections[i]; @@ -114,8 +102,7 @@ int SlotGuard::InsertConnection(SignalStub& stub, int stubId) return size; } -void SlotGuard::RemoveConnectionFor(SignalStub& stub) -{ +void SlotGuard::RemoveConnectionFor(SignalStub& stub) { for (auto& conn : mConnections) { if (conn.stub == &stub) { conn.stub->RemoveConnection(conn.stubId); @@ -123,13 +110,11 @@ void SlotGuard::RemoveConnectionFor(SignalStub& stub) } } -void SlotGuard::RemoveConnection(int slotId) -{ +void SlotGuard::RemoveConnection(int slotId) { mConnections[slotId] = {}; } -TEST_CASE("Signal connect and disconnect") -{ +TEST_CASE("Signal connect and disconnect") { Signal<> sig; int counter = 0; @@ -146,8 +131,7 @@ TEST_CASE("Signal connect and disconnect") CHECK(counter == 2); } -TEST_CASE("Signal with parameters") -{ +TEST_CASE("Signal with parameters") { Signal<int> sig; int counter = 0; @@ -167,8 +151,7 @@ TEST_CASE("Signal with parameters") CHECK(counter == 5); } -TEST_CASE("Signal disconnectAll()") -{ +TEST_CASE("Signal disconnectAll()") { Signal<> sig; int counter1 = 0; @@ -190,8 +173,7 @@ TEST_CASE("Signal disconnectAll()") CHECK(counter2 == 2); } -TEST_CASE("SlotGuard auto-disconnection") -{ +TEST_CASE("SlotGuard auto-disconnection") { int counter1 = 0; int counter2 = 0; Signal<> sig; @@ -215,8 +197,7 @@ TEST_CASE("SlotGuard auto-disconnection") CHECK(counter2 == 2); } -TEST_CASE("Signal destruct before SlotGuard") -{ +TEST_CASE("Signal destruct before SlotGuard") { int counter = 0; SlotGuard guard; diff --git a/app/source/Cplt/Utils/Sigslot.hpp b/app/source/Cplt/Utils/Sigslot.hpp index a4ab94e..92c8bcc 100644 --- a/app/source/Cplt/Utils/Sigslot.hpp +++ b/app/source/Cplt/Utils/Sigslot.hpp @@ -8,25 +8,21 @@ #include <utility> #include <vector> -class SignalStub -{ +class SignalStub { public: /// Non-template interface for Signal<T...> to implement (a barrier to stop template /// arguments propagation). - class IWrapper - { + class IWrapper { public: virtual ~IWrapper() = default; virtual void RemoveFunction(int id) = 0; }; - enum - { + enum { InvalidId = -1, }; - struct Connection - { + struct Connection { SlotGuard* guard; int slotId; int id = InvalidId; // If `InvalidId`, then this "spot" is unused @@ -59,8 +55,7 @@ private: }; template <class... TArgs> -class Signal : public SignalStub::IWrapper -{ +class Signal : public SignalStub::IWrapper { private: // Must be in this order so that mFunctions is still intact when mStub's destructor runs std::vector<std::function<void(TArgs...)>> mFunctions; @@ -68,8 +63,7 @@ private: public: Signal() - : mStub(*this) - { + : mStub(*this) { } virtual ~Signal() = default; @@ -79,8 +73,7 @@ public: Signal(Signal&&) = default; Signal& operator=(Signal&&) = default; - void operator()(TArgs... args) - { + void operator()(TArgs... args) { for (auto& conn : mStub.GetConnections()) { if (conn.IsOccupied()) { mFunctions[conn.id](std::forward<TArgs>(args)...); @@ -89,8 +82,7 @@ public: } template <class TFunction> - int Connect(TFunction slot) - { + int Connect(TFunction slot) { auto& conn = mStub.InsertConnection(); mFunctions.resize(std::max(mFunctions.size(), (size_t)conn.id + 1)); mFunctions[conn.id] = std::move(slot); @@ -98,31 +90,26 @@ public: } template <class TFunction> - int Connect(SlotGuard& guard, TFunction slot) - { + int Connect(SlotGuard& guard, TFunction slot) { auto& conn = mStub.InsertConnection(&guard); mFunctions.resize(std::max(mFunctions.size(), (size_t)conn.id + 1)); mFunctions[conn.id] = std::move(slot); return conn.id; } - void Disconnect(int id) - { + void Disconnect(int id) { mStub.RemoveConnection(id); } - void DisconnectFor(SlotGuard& guard) - { + void DisconnectFor(SlotGuard& guard) { mStub.RemoveConnectionFor(guard); } - void DisconnectAll() - { + void DisconnectAll() { mStub.RemoveAllConnections(); } - virtual void RemoveFunction(int id) - { + virtual void RemoveFunction(int id) { mFunctions[id] = {}; } }; @@ -130,11 +117,9 @@ public: /// Automatic disconnection mechanism for Signal<>. /// Bind connection to this guard by using the Connect(SlotGuard&, TFunction) overload. /// Either DisconnectAll() or the destructor disconnects all connections bound to this guard. -class SlotGuard -{ +class SlotGuard { private: - struct Connection - { + struct Connection { SignalStub* stub = nullptr; int stubId = SignalStub::InvalidId; }; diff --git a/app/source/Cplt/Utils/Size.hpp b/app/source/Cplt/Utils/Size.hpp index ae38e8a..bcad488 100644 --- a/app/source/Cplt/Utils/Size.hpp +++ b/app/source/Cplt/Utils/Size.hpp @@ -18,25 +18,21 @@ public: } Size2(Vec2<T> vec) - : width{ vec.x }, height{ vec.y } - { + : width{ vec.x }, height{ vec.y } { } - operator Vec2<T>() const - { + operator Vec2<T>() const { return { width, height }; } - Vec2<T> AsVec() const - { + Vec2<T> AsVec() const { return { width, height }; } friend bool operator==(const Size2<T>&, const Size2<T>&) = default; template <class TTarget> - Size2<TTarget> Cast() const - { + Size2<TTarget> Cast() const { return { static_cast<TTarget>(width), static_cast<TTarget>(height), diff --git a/app/source/Cplt/Utils/StandardDirectories.cpp b/app/source/Cplt/Utils/StandardDirectories.cpp index 2202f51..ff2c911 100644 --- a/app/source/Cplt/Utils/StandardDirectories.cpp +++ b/app/source/Cplt/Utils/StandardDirectories.cpp @@ -12,8 +12,7 @@ namespace fs = std::filesystem; # pragma comment(lib, "shell32.lib") # pragma comment(lib, "ole32.lib") -static fs::path GetAppDataRoaming() -{ +static fs::path GetAppDataRoaming() { PWSTR path = nullptr; HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE, nullptr, &path); if (SUCCEEDED(hr)) { @@ -34,8 +33,7 @@ static fs::path GetAppDataRoaming() #elif defined(__linux__) # include <cstdlib> -static fs::path GetEnvVar(const char* name, const char* backup) -{ +static fs::path GetEnvVar(const char* name, const char* backup) { if (const char* path = std::getenv(name)) { fs::path dataDir(path); fs::create_directories(dataDir); @@ -49,8 +47,7 @@ static fs::path GetEnvVar(const char* name, const char* backup) #endif -const std::filesystem::path& StandardDirectories::UserData() -{ +const std::filesystem::path& StandardDirectories::UserData() { static auto userDataDir = []() -> fs::path { #if defined(_WIN32) return GetAppDataRoaming(); @@ -63,8 +60,7 @@ const std::filesystem::path& StandardDirectories::UserData() return userDataDir; } -const std::filesystem::path& StandardDirectories::UserConfig() -{ +const std::filesystem::path& StandardDirectories::UserConfig() { static auto userConfigDir = []() -> fs::path { #if defined(_WIN32) return GetAppDataRoaming(); diff --git a/app/source/Cplt/Utils/Time.cpp b/app/source/Cplt/Utils/Time.cpp index 4e79ffa..423f6bd 100644 --- a/app/source/Cplt/Utils/Time.cpp +++ b/app/source/Cplt/Utils/Time.cpp @@ -2,8 +2,7 @@ #include <ctime> -std::string TimeUtils::StringifyTimePoint(std::chrono::time_point<std::chrono::system_clock> tp) -{ +std::string TimeUtils::StringifyTimePoint(std::chrono::time_point<std::chrono::system_clock> tp) { auto t = std::chrono::system_clock::to_time_t(tp); char data[32]; @@ -15,8 +14,7 @@ std::string TimeUtils::StringifyTimePoint(std::chrono::time_point<std::chrono::s return std::string(data); } -std::string TimeUtils::StringifyTimeStamp(int64_t timeStamp) -{ +std::string TimeUtils::StringifyTimeStamp(int64_t timeStamp) { if (timeStamp == 0) { return ""; } diff --git a/app/source/Cplt/Utils/Variant.hpp b/app/source/Cplt/Utils/Variant.hpp index df2f882..b601811 100644 --- a/app/source/Cplt/Utils/Variant.hpp +++ b/app/source/Cplt/Utils/Variant.hpp @@ -4,21 +4,18 @@ #include <variant> template <class... Ts> -struct Overloaded : Ts... -{ +struct Overloaded : Ts... { using Ts::operator()...; }; template <class... Ts> Overloaded(Ts...) -> Overloaded<Ts...>; template <class... Args> -struct VariantCastProxy -{ +struct VariantCastProxy { std::variant<Args...> v; template <class... ToArgs> - operator std::variant<ToArgs...>() const - { + operator std::variant<ToArgs...>() const { return std::visit( [](auto&& arg) -> std::variant<ToArgs...> { return arg; }, v); @@ -27,7 +24,6 @@ struct VariantCastProxy /// Use snake_case naming to align with `static_cast`, `dynamic_cast`, etc.. template <class... Args> -auto variant_cast(std::variant<Args...> v) -> VariantCastProxy<Args...> -{ +auto variant_cast(std::variant<Args...> v) -> VariantCastProxy<Args...> { return { std::move(v) }; } diff --git a/app/source/Cplt/Utils/Vector.hpp b/app/source/Cplt/Utils/Vector.hpp index 79f4ea2..5fdfab2 100644 --- a/app/source/Cplt/Utils/Vector.hpp +++ b/app/source/Cplt/Utils/Vector.hpp @@ -3,28 +3,24 @@ #include <Cplt/Utils/IO/DataStream.hpp> template <class T> -struct Vec2 -{ +struct Vec2 { T x = 0; T y = 0; template <class TTarget> - Vec2<TTarget> Cast() const - { + Vec2<TTarget> Cast() const { return { static_cast<TTarget>(x), static_cast<TTarget>(y), }; } - void ReadFromDataStream(InputDataStream& stream) - { + void ReadFromDataStream(InputDataStream& stream) { stream.Value(x); stream.Value(y); } - void WriteToDataStream(OutputDataStream& stream) const - { + void WriteToDataStream(OutputDataStream& stream) const { stream.Value(x); stream.Value(y); } @@ -46,15 +42,13 @@ using Vec2i = Vec2<int>; using Vec2f = Vec2<float>; template <class T> -struct Vec3 -{ +struct Vec3 { T x = 0; T y = 0; T z = 0; template <class TTarget> - Vec3<TTarget> Cast() const - { + Vec3<TTarget> Cast() const { return { static_cast<TTarget>(x), static_cast<TTarget>(y), @@ -62,15 +56,13 @@ struct Vec3 }; } - void ReadFromDataStream(InputDataStream& stream) - { + void ReadFromDataStream(InputDataStream& stream) { stream.Value(x); stream.Value(y); stream.Value(z); } - void WriteToDataStream(OutputDataStream& stream) const - { + void WriteToDataStream(OutputDataStream& stream) const { stream.Value(x); stream.Value(y); stream.Value(z); @@ -93,16 +85,14 @@ using Vec3i = Vec3<int>; using Vec3f = Vec3<float>; template <class T> -struct Vec4 -{ +struct Vec4 { T x = 0; T y = 0; T z = 0; T w = 0; template <class TTarget> - Vec4<TTarget> Cast() const - { + Vec4<TTarget> Cast() const { return { static_cast<TTarget>(x), static_cast<TTarget>(y), @@ -111,16 +101,14 @@ struct Vec4 }; } - void ReadFromDataStream(InputDataStream& stream) - { + void ReadFromDataStream(InputDataStream& stream) { stream.Value(x); stream.Value(y); stream.Value(z); stream.Value(w); } - void WriteToDataStream(OutputDataStream& stream) const - { + void WriteToDataStream(OutputDataStream& stream) const { stream.Value(x); stream.Value(y); stream.Value(z); diff --git a/app/source/Cplt/Utils/VectorHash.hpp b/app/source/Cplt/Utils/VectorHash.hpp index f649367..80a92fb 100644 --- a/app/source/Cplt/Utils/VectorHash.hpp +++ b/app/source/Cplt/Utils/VectorHash.hpp @@ -7,10 +7,8 @@ #include <functional> template <class T> -struct std::hash<Vec2<T>> -{ - size_t operator()(const Vec2<T>& vec) const - { +struct std::hash<Vec2<T>> { + size_t operator()(const Vec2<T>& vec) const { size_t result; HashUtils::Combine(result, vec.x); HashUtils::Combine(result, vec.y); @@ -19,10 +17,8 @@ struct std::hash<Vec2<T>> }; template <class T> -struct std::hash<Vec3<T>> -{ - size_t operator()(const Vec3<T>& vec) const - { +struct std::hash<Vec3<T>> { + size_t operator()(const Vec3<T>& vec) const { size_t result; HashUtils::Combine(result, vec.x); HashUtils::Combine(result, vec.y); @@ -32,10 +28,8 @@ struct std::hash<Vec3<T>> }; template <class T> -struct std::hash<Vec4<T>> -{ - size_t operator()(const Vec4<T>& vec) const - { +struct std::hash<Vec4<T>> { + size_t operator()(const Vec4<T>& vec) const { size_t result; HashUtils::Combine(result, vec.x); HashUtils::Combine(result, vec.y); diff --git a/app/source/Cplt/main.cpp b/app/source/Cplt/main.cpp index 55c1019..2fef2bb 100644 --- a/app/source/Cplt/main.cpp +++ b/app/source/Cplt/main.cpp @@ -19,8 +19,7 @@ namespace fs = std::filesystem; using namespace std::literals::string_literals; using namespace std::literals::string_view_literals; -static std::unique_ptr<RenderingBackend> CreateDefaultBackend() -{ +static std::unique_ptr<RenderingBackend> CreateDefaultBackend() { #if defined(_WIN32) # if BUILD_CORE_WITH_DX12_BACKEND if (auto backend = RenderingBackend::CreateDx12Backend()) { @@ -71,8 +70,7 @@ static std::unique_ptr<RenderingBackend> CreateDefaultBackend() return nullptr; } -static std::unique_ptr<RenderingBackend> CreateBackend(std::string_view option) -{ +static std::unique_ptr<RenderingBackend> CreateBackend(std::string_view option) { if (option == "default") { return CreateDefaultBackend(); } else if (option == "opengl2") { @@ -97,8 +95,7 @@ static std::unique_ptr<RenderingBackend> CreateBackend(std::string_view option) } #ifdef DOCTEST_CONFIG_DISABLE -int main(int argc, char* argv[]) -{ +int main(int argc, char* argv[]) { argparse::ArgumentParser parser; parser.add_argument("--global-data-directory") .help("Directory in which global data (such as recently used projects) are saved to. Use 'default' to use the default directory on each platform.") @@ -147,8 +144,7 @@ int main(int argc, char* argv[]) fs::path path(dataDirOption); GlobalStates::Init(std::move(path)); } - DEFER - { + DEFER { GlobalStates::Shutdown(); }; |