Compare commits

..

4 commits

Author SHA1 Message Date
IlyaShurupov
c57041a48e Refactor of layout manager to add support for all menus (dirty unstable) 2024-11-05 19:30:45 +03:00
IlyaShurupov
23fe07d3d3 fix focus locking bug 2024-11-05 19:30:02 +03:00
IlyaShurupov
458e56fb4c Debug Tools and Scrollable widget 2024-10-20 12:06:55 +03:00
IlyaShurupov
f68f91f7d5 fix focus locking 2024-10-20 12:01:42 +03:00
44 changed files with 604 additions and 295 deletions

3
.gitmodules vendored
View file

@ -19,3 +19,6 @@
[submodule "Externals/asio"] [submodule "Externals/asio"]
path = Externals/asio path = Externals/asio
url = https://github.com/elushaX/asio.git url = https://github.com/elushaX/asio.git
[submodule "Externals/implot"]
path = Externals/implot
url = https://github.com/epezent/implot.git

View file

@ -57,7 +57,7 @@ void Editor::loadDefaults() {
} }
void Editor::setViewportSize(const Vec2F& size) { void Editor::setViewportSize(const Vec2F& size) {
if (size.x < 0 || size.y < 0) return; if (size.x <= 0 || size.y <= 0) return;
// TODO remove // TODO remove
// mScene.mCamera.rotate(0.01f, 0.0); // mScene.mCamera.rotate(0.01f, 0.0);

View file

@ -2,7 +2,7 @@
#include "DockWidget.hpp" #include "DockWidget.hpp"
#include "Editor.hpp" #include "Editor.hpp"
#include "FloatingWidget.hpp" #include "MenuWidgets.hpp"
namespace tp { namespace tp {
@ -17,7 +17,7 @@ namespace tp {
~ViewportWidget() override { mCanvas->deleteImageHandle(mImage); } ~ViewportWidget() override { mCanvas->deleteImageHandle(mImage); }
void process(const EventHandler& events) override { void process(const EventHandler& events) override {
mEditor->setViewportSize(getArea().size); mEditor->setViewportSize(getAreaT().size);
} }
void draw(Canvas& canvas) override { void draw(Canvas& canvas) override {
@ -40,11 +40,11 @@ namespace tp {
mViewport(canvas, editor) { mViewport(canvas, editor) {
mEditor = editor; mEditor = editor;
mPanel.setText("Controls"); // mPanel.setText("Controls");
mPanel.addToMenu(&mNavigationMenu); //mPanel.addToMenu(&mNavigationMenu);
mPanel.addToMenu(&mRenderMenu); //mPanel.addToMenu(&mRenderMenu);
dockWidget(&mPanel, DockLayout::RIGHT); dockWidget(&mNavigationMenu, DockLayout::RIGHT);
setCenterWidget(&mViewport); setCenterWidget(&mViewport);
// Render // Render
@ -120,10 +120,10 @@ namespace tp {
ViewportWidget mViewport; ViewportWidget mViewport;
FloatingMenu mPanel; FloatingScrollableMenu mPanel;
// Controls // Controls
FloatingMenu mRenderMenu; FloatingScrollableMenu mRenderMenu;
ButtonWidget mRenderPathTracer; ButtonWidget mRenderPathTracer;
ButtonWidget mRenderRaster; ButtonWidget mRenderRaster;
ButtonWidget mRenderDeNoise; ButtonWidget mRenderDeNoise;
@ -131,7 +131,7 @@ namespace tp {
// Navigation // Navigation
enum NavigationType { ORBIT, PAN, ZOOM } mNavigationType = ORBIT; enum NavigationType { ORBIT, PAN, ZOOM } mNavigationType = ORBIT;
FloatingMenu mNavigationMenu; FloatingScrollableMenu mNavigationMenu;
ButtonWidget mNavigationPan; ButtonWidget mNavigationPan;
ButtonWidget mNavigationOrbit; ButtonWidget mNavigationOrbit;
ButtonWidget mNavigationZoom; ButtonWidget mNavigationZoom;

View file

@ -49,11 +49,14 @@ set(${PROJECT_NAME}_SOURCES
imgui/backends/imgui_impl_glfw.cpp imgui/backends/imgui_impl_glfw.cpp
imgui/backends/imgui_impl_opengl3.cpp imgui/backends/imgui_impl_opengl3.cpp
implot/implot.cpp
implot/implot_items.cpp
) )
add_library(${PROJECT_NAME} STATIC ${${PROJECT_NAME}_SOURCES}) add_library(${PROJECT_NAME} STATIC ${${PROJECT_NAME}_SOURCES})
include_directories(${PROJECT_NAME} ./glfw/include) include_directories(${PROJECT_NAME} ./glfw/include)
target_include_directories(${PROJECT_NAME} PUBLIC ./imgui/ ./imgui/backends/) target_include_directories(${PROJECT_NAME} PUBLIC ./imgui/ ./imgui/backends/ ./implot/)
project(Nanovg) project(Nanovg)
set(${PROJECT_NAME}_SOURCES set(${PROJECT_NAME}_SOURCES

1
Externals/implot vendored Submodule

@ -0,0 +1 @@
Subproject commit f156599faefe316f7dd20fe6c783bf87c8bb6fd9

View file

@ -9,6 +9,8 @@
#include <imgui_impl_opengl3.h> #include <imgui_impl_opengl3.h>
#include <imgui_internal.h> #include <imgui_internal.h>
#include "implot.h"
namespace tp { namespace tp {
class DebugGUI::Context { class DebugGUI::Context {
public: public:
@ -41,6 +43,8 @@ DebugGUI::DebugGUI(Window* window) {
// appearance // appearance
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
ImPlot::CreateContext();
return; return;
auto& colors = ImGui::GetStyle().Colors; auto& colors = ImGui::GetStyle().Colors;
@ -75,10 +79,13 @@ DebugGUI::DebugGUI(Window* window) {
} }
DebugGUI::~DebugGUI() { DebugGUI::~DebugGUI() {
ImPlot::DestroyContext();
ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown(); ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext(); ImGui::DestroyContext();
delete mContext; delete mContext;
} }

View file

@ -29,6 +29,8 @@ Window::Window(Vec2F size, const char* title) {
// glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 1); // glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, 1);
// glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); // glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
mSize = size;
// Create a window and OpenGL context // Create a window and OpenGL context
mContext->window = glfwCreateWindow((int) size.x, (int) size.y, title, nullptr, nullptr); mContext->window = glfwCreateWindow((int) size.x, (int) size.y, title, nullptr, nullptr);
if (!mContext->window) { if (!mContext->window) {

View file

@ -87,6 +87,7 @@ namespace tp {
[[nodiscard]] halnf getPointerPressure() const; [[nodiscard]] halnf getPointerPressure() const;
void setEnableKeyEvents(bool); void setEnableKeyEvents(bool);
[[nodiscard]] bool isKeyEventsEnabled() const { return mEnableKeyEvents; }
private: private:
void processEventUnguarded(); void processEventUnguarded();

View file

@ -248,7 +248,7 @@ namespace tp {
void process(const EventHandler& events) override { void process(const EventHandler& events) override {
filter(); filter();
for (auto track : mSongList.getContent()) { for (auto track : mSongList.getContainer()->getChildren()) {
if (auto trackWidget = dynamic_cast<TrackWidget*>(track.data())) { if (auto trackWidget = dynamic_cast<TrackWidget*>(track.data())) {
if (trackWidget->mState == TrackWidget::SELECTED) { if (trackWidget->mState == TrackWidget::SELECTED) {
mCurrentTrackInfo.mTrack = trackWidget->mTrack; mCurrentTrackInfo.mTrack = trackWidget->mTrack;
@ -268,7 +268,7 @@ namespace tp {
void filter() { void filter() {
if (!mCurrentTrackInfo.isSongFilterChanged) return; if (!mCurrentTrackInfo.isSongFilterChanged) return;
mSongList.clearChildren(); mSongList.getContainer()->clear();
for (auto track : mTracks) { for (auto track : mTracks) {
if (!mCurrentTrackInfo.songFilter.PassFilter(track->mTrack->mName.c_str()) && if (!mCurrentTrackInfo.songFilter.PassFilter(track->mTrack->mName.c_str()) &&
@ -290,7 +290,7 @@ namespace tp {
break; break;
} }
mSongList.addToMenu(track.data()); mSongList.getContainer()->addChild(track.data());
} }
mCurrentTrackInfo.isSongFilterChanged = false; mCurrentTrackInfo.isSongFilterChanged = false;
@ -302,7 +302,7 @@ namespace tp {
Buffer<TrackWidget*> mTracks; Buffer<TrackWidget*> mTracks;
FloatingMenu mSongList; ScrollableWidget mSongList;
TrackInfoWidget mCurrentTrackInfo; TrackInfoWidget mCurrentTrackInfo;
TrackWidget mCurrentTrack; TrackWidget mCurrentTrack;
}; };

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <functional>
#include "Environment.hpp" #include "Environment.hpp"
namespace tp { namespace tp {
@ -56,4 +57,19 @@ namespace tp {
} }
} }
}; };
struct TimerWrapper {
explicit TimerWrapper(const std::function<void()>& arg) {
codeSnippet = arg;
}
time_ms exec() {
Timer timer;
codeSnippet();
return timer.timePassed();
}
private:
std::function<void()> codeSnippet;
};
} }

View file

@ -3,7 +3,7 @@
#include "Sketch3D.hpp" #include "Sketch3D.hpp"
#include "Widget.hpp" #include "Widget.hpp"
#include "DockWidget.hpp" #include "DockWidget.hpp"
#include "FloatingWidget.hpp" #include "MenuWidgets.hpp"
namespace tp { namespace tp {
@ -150,15 +150,15 @@ namespace tp {
private: private:
Sketch3DWidget mViewport; Sketch3DWidget mViewport;
FloatingMenu mPanel; FloatingScrollableMenu mPanel;
FloatingMenu mControls; FloatingScrollableMenu mControls;
ButtonWidget mDrawButton; ButtonWidget mDrawButton;
ButtonWidget mMoveButton; ButtonWidget mMoveButton;
ButtonWidget mRotateButton; ButtonWidget mRotateButton;
ButtonWidget mZoomButton; ButtonWidget mZoomButton;
FloatingMenu mColorPicker; FloatingScrollableMenu mColorPicker;
SliderWidget mRed; SliderWidget mRed;
SliderWidget mGreen; SliderWidget mGreen;
SliderWidget mBlue; SliderWidget mBlue;

11
TODO
View file

@ -1,13 +1,18 @@
Widgets: Widgets:
Replace Old Widgets!! Basic scrollable widget
Collapsing menus
Icons
Toolbar widget
Fix focus locking mechanism
Hover PopUps
Color Picker
Optimize: Optimize:
Make visual parameters static Make visual parameters static
Make get-areas fetch cache and not animation objects Make get-areas fetch cache and not animation objects
New Widgets: New Widgets:
Collapsing menu
Sliders
Check Boxes Check Boxes
Drop-Downs Drop-Downs
Toaster notifications Toaster notifications

View file

@ -10,8 +10,8 @@ target_link_libraries(${PROJECT_NAME} PUBLIC Math Graphics Imgui)
### -------------------------- Applications -------------------------- ### ### -------------------------- Applications -------------------------- ###
add_executable(Widgets2Example examples/Example.cpp) add_executable(WidgetsExample examples/Example.cpp)
target_link_libraries(Widgets2Example ${PROJECT_NAME} ${GLEW_LIB}) target_link_libraries(WidgetsExample ${PROJECT_NAME} ${GLEW_LIB})
target_include_directories(Widgets2Example PUBLIC ../Externals/glfw/include ${GLEW_INCLUDE_DIR}) target_include_directories(WidgetsExample PUBLIC ../Externals/glfw/include ${GLEW_INCLUDE_DIR})
file(COPY "examples/Font.ttf" DESTINATION "${CMAKE_BINARY_DIR}/${PROJECT_NAME}/") file(COPY "examples/Font.ttf" DESTINATION "${CMAKE_BINARY_DIR}/${PROJECT_NAME}/")

View file

@ -2,7 +2,7 @@
#include "WidgetApplication.hpp" #include "WidgetApplication.hpp"
#include "RootWidget.hpp" #include "RootWidget.hpp"
#include "FloatingWidget.hpp" #include "MenuWidgets.hpp"
#include "DockWidget.hpp" #include "DockWidget.hpp"
#include "ScrollableLayout.hpp" #include "ScrollableLayout.hpp"
@ -13,15 +13,15 @@ using namespace tp;
class Example : public WidgetApplication { class Example : public WidgetApplication {
public: public:
Example() { Example() {
exampleScrolling(); exampleNestedMenus();
} }
void exampleAll() { void exampleAll() {
static DockWidget dock; static DockWidget dock;
static LabelWidget centralWidget; static LabelWidget centralWidget;
static FloatingMenu menus[4]; static FloatingScrollableMenu menus[4];
static FloatingMenu nestedMenus[4]; static FloatingScrollableMenu nestedMenus[4];
static FloatingMenu buttons[10]; static FloatingScrollableMenu buttons[10];
dock.setCenterWidget(&centralWidget); dock.setCenterWidget(&centralWidget);
@ -36,6 +36,30 @@ public:
setRoot(&dock); setRoot(&dock);
} }
void exampleCollapsingMenus() {
static DockWidget dock;
static CollapsingMenuWidget mainMenu;
static CollapsingMenuWidget menus[3];
static ButtonWidget buttons[5];
for (auto& menu : menus) {
mainMenu.getContainer()->addChild(&menu);
}
menus[0].getContainer()->addChild(&buttons[0]);
menus[0].getContainer()->addChild(&buttons[1]);
menus[0].getContainer()->addChild(&buttons[2]);
menus[1].getContainer()->addChild(&buttons[3]);
menus[1].getContainer()->addChild(&buttons[4]);
// dock.addChild(&menus[0]);
setRoot(&menus[0]);
// RootWidget::setWidgetArea(mainMenu, { 333, 333, 522, 522 });
}
void exampleBasic() { void exampleBasic() {
static Widget widget; static Widget widget;
static LabelWidget label; static LabelWidget label;
@ -50,40 +74,44 @@ public:
} }
void exampleScrolling() { void exampleScrolling() {
static Widget widget; static ScrollableWidget widget;
static Widget content;
static ButtonWidget buttons[10]; static ButtonWidget buttons[10];
static ScrollableBarWidget scrollBar;
// widget.setDirection(false);
setRoot(&widget); setRoot(&widget);
widget.addChild(&scrollBar);
widget.addChild(&content);
for (auto& button : buttons) { for (auto& button : buttons) {
content.addChild(&button); widget.getContainer()->addChild(&button);
} }
widget.setLayout(new ScrollableLayout(&widget)); RootWidget::setWidgetArea(*widget.getContainer(), { 333, 333, 522, 522 });
RootWidget::setWidgetArea(content, { 333, 333, 522, 522 });
} }
void examplePopup() { void examplePopup() {
static Widget root; static Widget root;
static Widget popup;
static ButtonWidget closeButton; static ButtonWidget closeButton;
static ButtonWidget openButton; static ButtonWidget openButton;
static ButtonWidget buttons[3];
for (auto& button : buttons) {
popup.addChild(&button);
}
popup.addChild(&closeButton);
root.addChild(&openButton); root.addChild(&openButton);
((BasicLayout*)root.getLayout())->setLayoutPolicy(LayoutPolicy::Passive); ((BasicLayout*)root.getLayout())->setLayoutPolicy(LayoutPolicy::Passive);
openButton.setAction([&](){ openButton.setAction([&](){
closeButton.setArea({ 50, 50, 100, 100 }); popup.setArea({ 50, 50, 300, 300 });
openButton.openPopup(&closeButton); openButton.openPopup(&popup);
}); });
closeButton.setAction([&](){ closeButton.setAction([&](){
closeButton.closePopup(&closeButton); closeButton.closePopup(&popup);
}); });
openButton.setText("open"); openButton.setText("open");
@ -96,8 +124,8 @@ public:
void exampleNestedMenus() { void exampleNestedMenus() {
static DockWidget dock; static DockWidget dock;
static FloatingMenu menu1; static FloatingScrollableMenu menu1;
static FloatingMenu menu2; static FloatingScrollableMenu menu2;
static ButtonWidget buttons[15]; static ButtonWidget buttons[15];
setRoot(&dock); setRoot(&dock);
@ -169,8 +197,8 @@ public:
void exampleDock() { void exampleDock() {
static DockWidget dock; static DockWidget dock;
static FloatingMenu menu1; static FloatingScrollableMenu menu1;
static FloatingMenu menu2; static FloatingScrollableMenu menu2;
static ButtonWidget buttons[15]; static ButtonWidget buttons[15];
setRoot(&dock); setRoot(&dock);

View file

@ -29,7 +29,11 @@ const Vec2<SizePolicy>& WidgetLayout::getSizePolicy() const { return mSizePolicy
void WidgetLayout::setSizePolicy(SizePolicy x, SizePolicy y) { mSizePolicy = { x, y }; } void WidgetLayout::setSizePolicy(SizePolicy x, SizePolicy y) { mSizePolicy = { x, y }; }
WidgetLayout* WidgetLayout::lay(Widget* w) { return w->getLayout(); }
RangeF WidgetLayout::pickRange(const RangeF& current, const RangeF& children, const RangeF& parent, bool vertical) const { RangeF WidgetLayout::pickRange(const RangeF& current, const RangeF& children, const RangeF& parent, bool vertical) const {
return current;
RangeF out; RangeF out;
switch (mSizePolicy[vertical]) { switch (mSizePolicy[vertical]) {
@ -44,10 +48,16 @@ RangeF WidgetLayout::pickRange(const RangeF& current, const RangeF& children, co
void WidgetLayout::clampMinMaxSize() { void WidgetLayout::clampMinMaxSize() {
auto current = getArea(); auto current = getArea();
current.size.clamp(mMinSize, mMaxSize); auto minContent = minContentArea();
minContent.size.clamp(mMinSize, mMaxSize);
current.clamp(minContent);
setArea(current); setArea(current);
} }
void WidgetLayout::pickMinimalRect(bool dir) {
setArea(minContentArea());
}
RangeF WidgetLayout::clampRange(const RangeF& current, const RangeF& child, const RangeF& parent, bool vertical) const { RangeF WidgetLayout::clampRange(const RangeF& current, const RangeF& child, const RangeF& parent, bool vertical) const {
auto out = current; auto out = current;
@ -84,13 +94,17 @@ RectF WidgetLayout::getChildrenEnclosure() const {
return out; return out;
} }
RectF WidgetLayout::getAvailableChildArea() const { RectF WidgetLayout::availableChildArea() const {
return getArea().relative(); return getArea().relative();
} }
RectF WidgetLayout::minContentArea() const {
return getChildrenEnclosure();
}
RectF WidgetLayout::getParentEnclosure() const { RectF WidgetLayout::getParentEnclosure() const {
DEBUG_ASSERT(parent()) DEBUG_ASSERT(parent())
if (!parent()) return { { 0, 0 }, mMaxSize }; if (!parent()) return { { 0, 0 }, mMaxSize };
auto out = parent()->getLayout()->getAvailableChildArea(); auto out = parent()->getLayout()->availableChildArea();
return out; return out;
} }

View file

@ -8,6 +8,8 @@
using namespace tp; using namespace tp;
#define SAMPLE(label, scope) gDebugWidget.##label.addSample(TimerWrapper([&]() scope ).exec());
WidgetLayout* WidgetManagerInterface::defaultLayout(Widget* widget) { WidgetLayout* WidgetManagerInterface::defaultLayout(Widget* widget) {
return new BasicLayout(widget); return new BasicLayout(widget);
} }
@ -35,26 +37,30 @@ void RootWidget::setRootWidget(Widget* widget) {
void RootWidget::processFrame(EventHandler* events, const RectF& screenArea) { void RootWidget::processFrame(EventHandler* events, const RectF& screenArea) {
mRoot.setArea(screenArea); mRoot.setArea(screenArea);
if (!gDebugWidget.update(this, *events)) return; gDebugWidget.mUpdManager.addSample(TimerWrapper([&]() {
// construct hierarchy tree of widgets to process
mUpdateManager.updateTreeToProcess(&mRoot);
// construct hierarchy tree of widgets to process updateAnimations();
mUpdateManager.updateTreeToProcess(&mRoot); updateAreaCache(&mRoot, true);
updateAnimations(); // update all events and call all event processing callbacks
updateAreaCache(&mRoot, true); mUpdateManager.processWidgets(&mRoot, *events);
// update all events and call all event processing callbacks updateAreaCache(&mRoot, true);
mUpdateManager.processWidgets(&mRoot, *events); }).exec());
updateAreaCache(&mRoot, true); gDebugWidget.mLayManager.addSample(TimerWrapper([&]() {
// update widget sizes base on individual size policies
// update widget sizes base on individual size policies mLayoutManager.adjust(&mRoot);
mLayoutManager.adjust(&mRoot); }).exec());
updateAreaCache(&mRoot, false); updateAreaCache(&mRoot, false);
// trigger some widgets by moise pointer // trigger some widgets by moise pointer
mUpdateManager.handleFocusChanges(&mRoot, *events); auto prevFocus = mUpdateManager.getFocusWidget();
auto newFocus = mUpdateManager.findFocusWidget(&mRoot, *events);
mUpdateManager.handleFocusChanges(newFocus, prevFocus);
// check triggered widgets for removal // check triggered widgets for removal
mUpdateManager.clean(); mUpdateManager.clean();
@ -67,13 +73,9 @@ bool RootWidget::needsUpdate() const {
void RootWidget::drawFrame(Canvas& canvas) { void RootWidget::drawFrame(Canvas& canvas) {
canvas.rect(mRoot.getAreaT(), RGBA(0, 0, 0, 1)); canvas.rect(mRoot.getAreaT(), RGBA(0, 0, 0, 1));
drawRecursion(canvas, &mRoot, { 0, 0 }); drawRecursion(canvas, &mRoot, { 0, 0 });
gDebugWidget.drawDebug(this, canvas);
} }
void RootWidget::drawRecursion(Canvas& canvas, Widget* active, const Vec2F& pos) { void RootWidget::drawRecursion(Canvas& canvas, Widget* active, const Vec2F& pos) {
if (!active->mFlags.get(ENABLED)) return; if (!active->mFlags.get(ENABLED)) return;
@ -81,7 +83,9 @@ void RootWidget::drawRecursion(Canvas& canvas, Widget* active, const Vec2F& pos)
canvas.pushClamp({ pos, active->getArea().size }); canvas.pushClamp({ pos, active->getArea().size });
if (canvas.getClampedArea().size.length2() > EPSILON) { if (canvas.getClampedArea().size.length2() > EPSILON) {
active->draw(canvas); if (active->getArea().sizeVecW() > active->getArea().pos) {
active->draw(canvas);
}
for (auto child = active->mDepthOrder.lastNode(); child; child = child->prev) { for (auto child = active->mDepthOrder.lastNode(); child; child = child->prev) {
drawRecursion(canvas, child->data, pos + child->data->getArea().pos); drawRecursion(canvas, child->data, pos + child->data->getArea().pos);
@ -152,4 +156,3 @@ void RootWidget::closePopup(Widget* widget) {
void RootWidget::lockFocus(Widget* widget) { mUpdateManager.lockFocus(widget); } void RootWidget::lockFocus(Widget* widget) { mUpdateManager.lockFocus(widget); }
void RootWidget::freeFocus(Widget* widget) { mUpdateManager.freeFocus(widget); } void RootWidget::freeFocus(Widget* widget) { mUpdateManager.freeFocus(widget); }
bool RootWidget::isDebug() const { return gDebugWidget.isDebug(); }

View file

@ -5,7 +5,8 @@
using namespace tp; using namespace tp;
Widget::Widget() { Widget::Widget() {
mArea.setTargetRect({ 100, 100, 10, 10 }); mArea.setTargetRect({ 100, 100, 50, 50 });
setLayout(WidgetManagerInterface::defaultLayout(this)); setLayout(WidgetManagerInterface::defaultLayout(this));
mArea.endAnimation(); mArea.endAnimation();

View file

@ -5,6 +5,58 @@
using namespace tp; using namespace tp;
void WidgetApplication::debugUI() { void WidgetApplication::debugUI() {
ImGui::Text("Proc ms : %i", (int) mProcTime); // pass
ImGui::SameLine(); ImGui::Text("Draw ms : %i", (int) mDrawTime); }
void WidgetApplication::setRoot(Widget* widget) {
mRootWidget.setRootWidget(widget);
tp::RootWidget::setWidgetArea(*widget, {{}, mWindow->getSize()});
}
void WidgetApplication::processFrame(EventHandler* eventHandler, halnf deltaTime) {
const auto area = RectF({ 0, 0 }, mWindow->getSize());
gDebugWidget.update(&mRootWidget, *eventHandler);
if (gDebugWidget.isDebug()) {
mGuiArea = area.splitByFactorHL(mDebugSplitFactor);
mDebugArea = area.splitByFactorHR(mDebugSplitFactor);
} else {
mGuiArea = area;
}
if (gDebugWidget.isFrozen()) return;
Timer timer;
mRootWidget.processFrame(eventHandler, mGuiArea);
gDebugWidget.mProcTime.addSample(timer.timePassed());
}
void WidgetApplication::drawFrame(Canvas* canvas) {
Timer timer;
mRootWidget.drawFrame(*canvas);
gDebugWidget.mDrawTime.addSample(timer.timePassed());
if (gDebugWidget.isDebug()) {
ImGui::SetNextWindowPos(ImVec2(mDebugArea.x, mDebugArea.y));
ImGui::SetNextWindowSize(ImVec2(mDebugArea.z, mDebugArea.w));
if (ImGui::Begin(
"Existing Window Name",
nullptr,
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoDecoration
)) {
drawDebug();
debugUI();
gDebugWidget.drawDebug(&mRootWidget, *canvas);
}
ImGui::End();
}
}
bool WidgetApplication::forceNewFrame() {
return mRootWidget.needsUpdate();
} }

View file

@ -26,20 +26,7 @@ void BasicLayout::pickRect(bool vertical) {
setArea(newArea); setArea(newArea);
} }
void BasicLayout::clampRect() { void BasicLayout::arrangeChildren(bool vertical) {
DEBUG_ASSERT(0)
auto current = getArea();
auto children = getChildrenEnclosure();
auto parent = getParentEnclosure();
auto rangeX = clampRange(current.getRangeX(), children.getRangeX(), parent.getRangeX(), false);
auto rangeY = clampRange(current.getRangeY(), children.getRangeY(), parent.getRangeY(), true);
setArea(RectF(rangeX, rangeY));
}
void BasicLayout::updateLayout(bool vertical) {
if (children().empty()) return; if (children().empty()) return;
if (vertical) { if (vertical) {
@ -57,61 +44,64 @@ void BasicLayout::updateLayout(bool vertical) {
} }
} }
halnf BasicLayout::shrinkLayoutSize(WidgetLayout* widget, halnf diff, bool vertical) {
auto area = widget->getArea();
auto prevSize = area.size[vertical];
area.size[vertical] += diff;
widget->setArea(area);
//widget->clampMinMaxSize();
return widget->getArea().size[vertical] - prevSize;
}
halnf BasicLayout::changeChildSize(tp::Widget* widget, halnf diff, bool vertical) { bool BasicLayout::canChange(Widget* widget, bool vertical) {
auto prevSize = widget->getLayout()->getArea().size[vertical]; return widget->getLayout()->getSizePolicy()[vertical] == SizePolicy::Expanding;
{
auto area = widget->getLayout()->getArea();
area.size[vertical] += diff;
widget->setAreaCache(area);
widget->getLayout()->clampMinMaxSize();
}
auto newSize = widget->getLayout()->getArea().size[vertical];
return newSize - prevSize;
} }
void BasicLayout::adjustLayout(bool vertical) { void BasicLayout::adjustLayout(bool vertical) {
std::vector<std::pair<Widget*, bool>> contributors;
Vec2F contentSize = { 0, 0 };
Vec2F availableSize = getArea().size;
for (auto child : children()) { std::vector<std::pair<WidgetLayout*, bool>> contributors;
child->getLayout()->pickRect(vertical); halnf contentSize = 0;
if (child->getLayout()->getSizePolicy()[vertical] == SizePolicy::Expanding) { // find contributors
contributors.emplace_back( child, true ); for (Widget* child : children()) {
if (canChange(child, vertical)) {
auto area = child->getLayout()->getArea(); contributors.emplace_back( lay(child), true );
area.size[vertical] = 0;
child->setAreaCache(area);
child->getLayout()->clampMinMaxSize();
} }
contentSize += child->getLayout()->getArea().size;
} }
availableSize -= mLayoutGap * ((halnf) children().size() - 1) + mLayoutMargin * 2; // let each child to chose desired rect
for (Widget* child : children()) {
if (canChange(child, vertical)) {
lay(child)->pickMinimalRect(vertical);
} else {
lay(child)->pickRect(vertical);
}
}
auto diff = availableSize - contentSize; // calculate content size
for (Widget* child : children()) {
contentSize += lay(child)->getArea().size[vertical];
}
halnf availableSize = getArea().size[vertical] - (mLayoutGap * ((halnf) children().size() - 1) + mLayoutMargin * 2);
if (availableSize < 0) return;
halnf totalQuota = availableSize - contentSize;
// expand or contract as much as possible // expand or contract as much as possible
while (!contributors.empty() && (diff[vertical] != 0)) { while (!contributors.empty() && (totalQuota != 0)) {
auto quota = diff / (halnf) contributors.size(); halnf quotaPerContributor = totalQuota / (halnf) contributors.size();
for (auto& contributor : contributors) { for (auto& contributor : contributors) {
if (!contributor.second) continue; halnf contribution = shrinkLayoutSize(contributor.first, quotaPerContributor, vertical);
// contributor.first->endAnimations();
auto contribution = changeChildSize(contributor.first, quota[vertical], vertical);
if (contribution == 0) { if (contribution == 0) {
contributor.second = false; contributor.second = false;
} }
totalQuota -= contribution;
diff[vertical] -= contribution;
} }
// remove useless contributors
contributors.erase( contributors.erase(
std::remove_if(contributors.begin(), contributors.end(), [](auto node) { return !node.second; }), std::remove_if(contributors.begin(), contributors.end(), [](auto node) { return !node.second; }),
contributors.end() contributors.end()
@ -120,30 +110,31 @@ void BasicLayout::adjustLayout(bool vertical) {
// set opposite direction size // set opposite direction size
for (auto child : children()) { for (auto child : children()) {
// if (child->getLayout()->getSizePolicy()[!vertical] != SizePolicy::Minimal) { RectF area = lay(child)->getArea();
auto area = child->getLayout()->getArea(); area.size[!vertical] = getArea().size[!vertical] - mLayoutMargin * 2;
area.size[!vertical] = getArea().size[!vertical] - mLayoutMargin * 2; child->setAreaCache(area);
child->setAreaCache(area);
// }
} }
// set pos // set pos
halnf iterPos = mLayoutMargin; halnf iterPos = mLayoutMargin;
for (auto child : children()) { for (auto child : children()) {
auto area = child->getLayout()->getArea(); RectF area = lay(child)->getArea();
area.pos[vertical] = iterPos; area.pos[vertical] = iterPos;
area.pos[!vertical] = mLayoutMargin; area.pos[!vertical] = mLayoutMargin;
iterPos += area.size[vertical] + mLayoutGap; iterPos += area.size[vertical] + mLayoutGap;
child->setAreaCache(area); lay(child)->setArea(area);
// child->updateAnimations();
// child->triggerWidgetUpdate("layout changed");
} }
} }
RectF BasicLayout::getAvailableChildArea() const { RectF BasicLayout::availableChildArea() const {
auto out = WidgetLayout::getAvailableChildArea(); auto out = WidgetLayout::availableChildArea();
return out.shrinkFromCenter(mLayoutMargin, true); return out.shrinkFromCenter(mLayoutMargin, true);
} }
RectF BasicLayout::minContentArea() const {
auto out = WidgetLayout::getChildrenEnclosure();
out.shrinkFromCenter(-mLayoutMargin, true);
return out;
}

View file

@ -61,6 +61,8 @@ void DockLayout::toggleWidgetVisibility(Side side) {
void DockLayout::calculateSideAreas() { void DockLayout::calculateSideAreas() {
auto startArea = getArea().relative(); auto startArea = getArea().relative();
if (startArea.size.x <= 0 || startArea.size.y <= 0) return;
for (auto& sideWidget : mSideWidgets) { for (auto& sideWidget : mSideWidgets) {
const auto side = sideWidget.order; const auto side = sideWidget.order;
@ -99,11 +101,13 @@ void DockLayout::calculateResizeHandles() {
RectF area = getArea().relative(); RectF area = getArea().relative();
for (auto& sideWidget : mSideWidgets) { for (auto& sideWidget : mSideWidgets) {
if (!sideWidget.widget) continue;
auto& sideSize = sideWidget.absoluteSize; auto& sideSize = sideWidget.absoluteSize;
auto& resizeHandle = sideWidget.resizeHandle; auto& resizeHandle = sideWidget.resizeHandle;
if (resizeHandle.end < mSideSizePadding * 2) { if (resizeHandle.end < mSideSizePadding * 2) {
sideSize = resizeHandle.end / 2.f; // sideSize = resizeHandle.end / 2.f;
} else { } else {
sideSize = clamp(sideSize, resizeHandle.start + mSideSizePadding, resizeHandle.end - mSideSizePadding); sideSize = clamp(sideSize, resizeHandle.start + mSideSizePadding, resizeHandle.end - mSideSizePadding);
} }
@ -184,7 +188,7 @@ auto DockLayout::getSideFromWidget(Widget* widget) -> Side {
return DockLayout::NONE; return DockLayout::NONE;
} }
void DockLayout::updateLayout(bool vertical) { void DockLayout::arrangeChildren(bool vertical) {
for (auto child : children()) { for (auto child : children()) {
child->getLayout()->pickRect(vertical); child->getLayout()->pickRect(vertical);
} }

View file

@ -5,7 +5,7 @@
using namespace tp; using namespace tp;
void OverlayLayout::updateLayout(bool vertical) { void OverlayLayout::arrangeChildren(bool vertical) {
if (vertical) return; if (vertical) return;
if (children().empty()) return; if (children().empty()) return;

View file

@ -5,7 +5,7 @@
using namespace tp; using namespace tp;
void ScrollableLayout::updateLayout(bool vertical) { void ScrollableLayout::arrangeChildren(bool vertical) {
if (vertical) return; if (vertical) return;
// TODO : make better interface to get scroller and content widget // TODO : make better interface to get scroller and content widget
@ -30,9 +30,9 @@ void ScrollableLayout::updateWidgetRects(const RectF& area, Widget* content, Scr
auto sizeFactor = (area.size[dir] / content->getLayout()->getArea().size[dir]); auto sizeFactor = (area.size[dir] / content->getLayout()->getArea().size[dir]);
auto splitFactor = 1 - ((sizeFactor > 1.f) ? 0 : mScrollerSize / area.size[!dir]); auto splitFactor = 1 - ((sizeFactor > 1.f) ? 0 : mScrollerSize / area.size[!dir]);
auto holderArea = area.splitByFactorHL(splitFactor); auto holderArea = dir ? area.splitByFactorHL(splitFactor) : area.splitByFactorVT(splitFactor);
auto contentArea = content->getLayout()->getArea(); auto contentArea = content->getLayout()->getArea();
auto scrollerArea = area.splitByFactorHR(splitFactor); auto scrollerArea = dir ? area.splitByFactorHR(splitFactor) : area.splitByFactorVB(splitFactor);
scroller->updateSizeFactor(sizeFactor); scroller->updateSizeFactor(sizeFactor);
@ -44,7 +44,7 @@ void ScrollableLayout::updateWidgetRects(const RectF& area, Widget* content, Scr
content->getLayout()->setArea(contentArea); content->getLayout()->setArea(contentArea);
} }
RectF ScrollableLayout::getAvailableChildArea() const { RectF ScrollableLayout::availableChildArea() const {
auto out = getArea(); auto out = getArea();
// dont constrain on scroll axis // dont constrain on scroll axis
out.pos = -FLT_MAX / 4; out.pos = -FLT_MAX / 4;

View file

@ -3,28 +3,26 @@
#include "BasicLayout.hpp" #include "BasicLayout.hpp"
#include "imgui.h" #include "imgui.h"
#include "implot.h"
#include <sstream> #include <sstream>
using namespace tp; using namespace tp;
DebugManager tp::gDebugWidget; DebugManager tp::gDebugWidget;
#define LIST_SIZE { -FLT_MIN, 150 } #define LIST_SIZE \
{ -FLT_MIN, 150 }
bool DebugManager::update(RootWidget* rootWidget, EventHandler& events) { void DebugManager::update(RootWidget* rootWidget, EventHandler& events) {
mRootWidget = rootWidget; mRootWidget = rootWidget;
events.setEnableKeyEvents(true); events.setEnableKeyEvents(true);
if (events.isPressed(InputID::D)) mDebug = !mDebug; if (events.isPressed(InputID::D)) mDebug = !mDebug;
if (mDebug) { if (mDebug) {
auto area = rootWidget->mRoot.getAreaT();
area.size -= { 400, 0 };
rootWidget->mRoot.setArea(area);
events.setEnableKeyEvents(true); events.setEnableKeyEvents(true);
if (events.isPressed(InputID::K)) mDebugStopProcessing = !mDebugStopProcessing; if (events.isPressed(InputID::K)) mDebugStopProcessing = !mDebugStopProcessing;
if (mDebugStopProcessing) return false;
if (auto widget = rootWidget->mUpdateManager.mInFocusWidget) { if (auto widget = rootWidget->mUpdateManager.mInFocusWidget) {
if (auto lay = dynamic_cast<BasicLayout*>(widget->getLayout())) { if (auto lay = dynamic_cast<BasicLayout*>(widget->getLayout())) {
@ -49,8 +47,6 @@ bool DebugManager::update(RootWidget* rootWidget, EventHandler& events) {
if (events.isPressed(InputID::L)) mLayBreakpoints.insert(breakWidget); if (events.isPressed(InputID::L)) mLayBreakpoints.insert(breakWidget);
} }
} }
return true;
} }
void DebugManager::drawDebug(RootWidget* rootWidget, Canvas& canvas) { void DebugManager::drawDebug(RootWidget* rootWidget, Canvas& canvas) {
@ -60,20 +56,24 @@ void DebugManager::drawDebug(RootWidget* rootWidget, Canvas& canvas) {
return; return;
} }
drawPerformance();
// ImGui::Checkbox("Draw debug", &mDebug); // ImGui::Checkbox("Draw debug", &mDebug);
ImGui::SameLine(); ImGui::Text("To Toggle processing press k"); ImGui::SameLine();
ImGui::Text("To Toggle processing press k");
auto& upd = rootWidget->mUpdateManager; auto& upd = rootWidget->mUpdateManager;
recursiveDraw(canvas, &rootWidget->mRoot, { 0, 0 }, 0);
ImGui::Text("Triggered: %i", (int) upd.mTriggeredWidgets.size()); ImGui::Text("Triggered: %i", (int) upd.mTriggeredWidgets.size());
ImGui::SameLine(); ImGui::Text("Processing: %i", upd.mDebugWidgetsToProcess); ImGui::SameLine();
ImGui::Text("Processing: %i", upd.mDebugWidgetsToProcess);
ImGui::Checkbox("Stop processing", &mDebugStopProcessing); ImGui::Checkbox("Stop processing", &mDebugStopProcessing);
ImGui::SameLine(); ImGui::Checkbox("Force new frames", &mDebugRedrawAlways); ImGui::SameLine();
ImGui::SameLine(); ImGui::Checkbox("Slow-mo", &mSlowMotion); ImGui::Checkbox("Force new frames", &mDebugRedrawAlways);
ImGui::SameLine();
ImGui::Checkbox("Detailed", &mDetailed);
if (upd.mInFocusWidget) { if (upd.mInFocusWidget) {
ImGui::Text("Under cursor"); ImGui::Text("Under cursor");
@ -87,17 +87,21 @@ void DebugManager::drawDebug(RootWidget* rootWidget, Canvas& canvas) {
} }
} }
ImGui::Text("Triggered"); if (mDetailed) {
{ ImGui::Text("Triggered");
if (ImGui::BeginListBox("##triggered", LIST_SIZE)) { {
for (auto widget : upd.mTriggeredWidgets) { if (ImGui::BeginListBox("##triggered", LIST_SIZE)) {
widgetMenu(widget.first); for (auto widget : upd.mTriggeredWidgets) {
widgetMenu(widget.first);
}
ImGui::EndListBox();
} }
ImGui::EndListBox();
} }
}
drawLayoutOrder(); drawLayoutOrder();
recursiveDraw(canvas, &rootWidget->mRoot, { 0, 0 }, 0);
}
} }
void DebugManager::recursiveDraw(Canvas& canvas, Widget* active, const Vec2F& pos, int depthOrder) { void DebugManager::recursiveDraw(Canvas& canvas, Widget* active, const Vec2F& pos, int depthOrder) {
@ -109,14 +113,17 @@ void DebugManager::recursiveDraw(Canvas& canvas, Widget* active, const Vec2F& po
canvas.text((active->mDebug.id + ":" + std::to_string(depthOrder)).c_str(), area, 22, Canvas::Align::LC, 2, color); canvas.text((active->mDebug.id + ":" + std::to_string(depthOrder)).c_str(), area, 22, Canvas::Align::LC, 2, color);
} }
if (active == mRootWidget->mUpdateManager.mFocusLockWidget) {
canvas.frame(area, { 0, 1, 0, 1 });
}
if (active->mFlags.get(Widget::IN_FOCUS)) { if (active->mFlags.get(Widget::IN_FOCUS)) {
if (active->isUpdate()) { if (active->isUpdate()) {
canvas.circle(pos + active->mDebug.pLocal, 5, active->mDebug.col); canvas.circle(pos + active->mDebug.pLocal, 5, active->mDebug.col);
canvas.circle(active->mDebug.pGlobal, 15, active->mDebug.col); canvas.circle(active->mDebug.pGlobal, 15, active->mDebug.col);
} }
RGBA color = { 1, 0, 0, 0.3f }; canvas.debugCross(area, { 0, 1, 0, 1 });
canvas.debugCross(area, color);
} }
int orderIdx = 0; int orderIdx = 0;
@ -175,3 +182,13 @@ void DebugManager::drawLayoutOrder() {
ImGui::EndListBox(); ImGui::EndListBox();
} }
} }
void DebugManager::drawPerformance() {
if (ImPlot::BeginPlot("Per Frame Time")) {
ImPlot::PlotLine("Proc ms", mProcTime.get(), mProcTime.size());
ImPlot::PlotLine("Draw ms", mDrawTime.get(), mDrawTime.size());
ImPlot::PlotLine("UPD ms", mUpdManager.get(), mUpdManager.size());
ImPlot::PlotLine("LAY ms", mLayManager.get(), mLayManager.size());
ImPlot::EndPlot();
}
}

View file

@ -3,6 +3,7 @@
#include "DockLayout.hpp" #include "DockLayout.hpp"
#include "ScrollableLayout.hpp" #include "ScrollableLayout.hpp"
#include "BasicLayout.hpp"
#include <algorithm> #include <algorithm>
@ -33,7 +34,11 @@ void LayoutManager::findDependencies(Widget* root) {
Widget::dfs(root, [this](Widget* widget) { mDepGraph.insert({ widget, {} }); }); Widget::dfs(root, [this](Widget* widget) { mDepGraph.insert({ widget, {} }); });
for (auto& [widget, deps] : mDepGraph) { for (auto& [widget, deps] : mDepGraph) {
if (!widget->isUpdate()) continue;
for (auto child : widget->mChildren) { for (auto child : widget->mChildren) {
if (!child->isUpdate()) continue;
mDepGraph.insert({ child, {} }); mDepGraph.insert({ child, {} });
if (auto depOrder = getLayoutOrder(widget->getLayout(), child->getLayout())) { if (auto depOrder = getLayoutOrder(widget->getLayout(), child->getLayout())) {
@ -74,7 +79,7 @@ void LayoutManager::adjustLayouts() {
}); });
for (auto& [iter, _] : mLayOrder) { for (auto& [iter, _] : mLayOrder) {
iter->getLayout()->updateLayout(mVertical); iter->getLayout()->arrangeChildren(mVertical);
} }
} }
@ -88,10 +93,13 @@ static int sizePolicyDep[3][3] = {
int LayoutManager::getLayoutOrder(WidgetLayout* parent, WidgetLayout* child) const { int LayoutManager::getLayoutOrder(WidgetLayout* parent, WidgetLayout* child) const {
if (!parent || !child) return 0; if (!parent || !child) return 0;
return 1;
auto policyParent = parent->getSizePolicy()[mVertical]; auto policyParent = parent->getSizePolicy()[mVertical];
auto policyChild = parent->getSizePolicy()[mVertical]; auto policyChild = parent->getSizePolicy()[mVertical];
if (dynamic_cast<DockLayout*>(parent)) return -1; // if (dynamic_cast<DockLayout*>(parent)) return -1;
// if (dynamic_cast<BasicLayout*>(parent)) return -1;
// if (dynamic_cast<ScrollableLayout*>(parent)) return -1; // if (dynamic_cast<ScrollableLayout*>(parent)) return -1;
return sizePolicyDep[int(policyParent)][int(policyChild)]; return sizePolicyDep[int(policyParent)][int(policyChild)];

View file

@ -69,26 +69,36 @@ void UpdateManager::getWidgetPath(Widget* widget, std::vector<Widget*>& out) {
} }
} }
void UpdateManager::handleFocusChanges(Widget* root, EventHandler& events) { Widget* UpdateManager::findFocusWidget(Widget* root, EventHandler& events) {
auto prevFocus = mInFocusWidget;
events.setCursorOrigin({ 0, 0 }); events.setCursorOrigin({ 0, 0 });
mInFocusWidget = nullptr; mInFocusWidget = nullptr;
findMouseFocusWidget(root, &mInFocusWidget, events.getPointer());
if (!mFocusLockWidget) { if (mFocusLockWidget) {
findFocusWidget(root, &mInFocusWidget, events.getPointer()); bool hasLockedWidget = false;
} else { for (auto iter = mInFocusWidget; iter; iter = iter->mParent) {
mInFocusWidget = mFocusLockWidget; if (iter == mFocusLockWidget) {
hasLockedWidget = true;
break;
}
}
if (!hasLockedWidget) {
mInFocusWidget = mFocusLockWidget;
}
} }
// if (mInFocusWidget == prevFocus) return; return mInFocusWidget;
if (mInFocusWidget) scheduleUpdate(mInFocusWidget, "focus entered"); }
if (!mInFocusWidget && !prevFocus) return; void UpdateManager::handleFocusChanges(Widget* active, Widget* prevActive) {
// if (mInFocusWidget == prevFocus) return;
if (active) scheduleUpdate(active, "focus entered");
if (!active && !prevActive) return;
std::vector<Widget*> path2; std::vector<Widget*> path2;
getWidgetPath(mInFocusWidget, path2); getWidgetPath(active, path2);
size_t propLen2 = path2.size(); size_t propLen2 = path2.size();
for (auto i = 0; i < path2.size(); i++) { for (auto i = 0; i < path2.size(); i++) {
if (!path2[i]->propagateEventsToChildren()) { if (!path2[i]->propagateEventsToChildren()) {
@ -98,7 +108,7 @@ void UpdateManager::handleFocusChanges(Widget* root, EventHandler& events) {
} }
std::vector<Widget*> path1; std::vector<Widget*> path1;
getWidgetPath(prevFocus, path1); getWidgetPath(prevActive, path1);
size_t propLen1 = path1.size(); size_t propLen1 = path1.size();
for (auto i = 0; i < path1.size(); i++) { for (auto i = 0; i < path1.size(); i++) {
if (!path1[i]->propagateEventsToChildren()) { if (!path1[i]->propagateEventsToChildren()) {
@ -126,7 +136,7 @@ void UpdateManager::handleFocusChanges(Widget* root, EventHandler& events) {
} }
} }
void UpdateManager::findFocusWidget(Widget* iter, Widget** focus, const Vec2F& pointer) { void UpdateManager::findMouseFocusWidget(Widget* iter, Widget** focus, const Vec2F& pointer) {
if (!iter->mArea.getTargetRect().isInside(pointer) || !iter->mFlags.get(Widget::ENABLED)) return; if (!iter->mArea.getTargetRect().isInside(pointer) || !iter->mFlags.get(Widget::ENABLED)) return;
if (iter->processesEvents()) { if (iter->processesEvents()) {
@ -134,7 +144,7 @@ void UpdateManager::findFocusWidget(Widget* iter, Widget** focus, const Vec2F& p
} }
for (auto child = iter->mDepthOrder.lastNode(); child; child = child->prev) { for (auto child = iter->mDepthOrder.lastNode(); child; child = child->prev) {
findFocusWidget(child->data, focus, pointer - iter->mArea.getTargetRect().pos); findMouseFocusWidget(child->data, focus, pointer - iter->mArea.getTargetRect().pos);
} }
} }
@ -206,6 +216,6 @@ void UpdateManager::lockFocus(tp::Widget* widget) {
} }
void UpdateManager::freeFocus(tp::Widget* widget) { void UpdateManager::freeFocus(tp::Widget* widget) {
// DEBUG_ASSERT(mFocusLockWidget == widget) DEBUG_ASSERT(mFocusLockWidget == widget)
mFocusLockWidget = nullptr; mFocusLockWidget = nullptr;
} }

View file

@ -80,9 +80,11 @@ void DockWidget::process(const EventHandler& events) {
if (events.isPressed(InputID::MOUSE1)) { if (events.isPressed(InputID::MOUSE1)) {
if (layout()->startResize(events.getPointer())) { if (layout()->startResize(events.getPointer())) {
triggerWidgetUpdate("dock layout resizing"); triggerWidgetUpdate("dock layout resizing");
lockFocus();
} }
} else if (events.isReleased(InputID::MOUSE1)) { } else if (events.isReleased(InputID::MOUSE1)) {
layout()->endResize(); layout()->endResize();
freeFocus();
} }
if (layout()->isResizing()) { if (layout()->isResizing()) {

View file

@ -47,30 +47,3 @@ FloatingLayout* FloatingWidget::layout() { return dynamic_cast<FloatingLayout*>(
const FloatingLayout* FloatingWidget::layout() const { const FloatingLayout* FloatingWidget::layout() const {
return dynamic_cast<const FloatingLayout*>(Widget::getLayout()); return dynamic_cast<const FloatingLayout*>(Widget::getLayout());
} }
FloatingMenu::FloatingMenu() : FloatingWidget() {
setDebug("float menu", { 0.0, 0.9, 0.1, 0.7 });
// addChild(&mMenuLayout);
addChild(&mHeader);
addChild(&mBodyLayout);
mHeader.setText("Menu");
mHeader.setSizePolicy(SizePolicy::Expanding, SizePolicy::Minimal);
mBodyLayout.setSizePolicy(SizePolicy::Expanding, SizePolicy::Expanding);
mBodyLayout.setLayout(new ScrollableLayout(&mBodyLayout));
mBodyLayout.addChild(&mScrollBar);
mBodyLayout.addChild(&mContentWidget);
mContentWidget.setSizePolicy(SizePolicy::Minimal, SizePolicy::Minimal);
// getLayout()->setLayoutPolicy(LayoutPolicy::Vertical);
// mBodyLayout.getLayout()->setLayoutPolicy(LayoutPolicy::Vertical);
}
void FloatingMenu::setText(const std::string& text) {
mHeader.setText(text);
}

View file

@ -0,0 +1,58 @@
#include "MenuWidgets.hpp"
#include "ScrollableLayout.hpp"
using namespace tp;
CollapsingMenuWidget::CollapsingMenuWidget() {
setDebug("Collapsing Menu", {1});
setSizePolicy(SizePolicy::Expanding, SizePolicy::Minimal);
addChild(&mHeader);
addChild(&mContent);
}
void CollapsingMenuWidget::process(const EventHandler& events) {
mHover = mHeader.getArea().isInside(events.getPointer());
if (events.isPressed(InputID::MOUSE1) && mHover) setCollapsed(!mContent.getEnabled());
}
void CollapsingMenuWidget::setCollapsed(bool collapsed) {
mContent.setEnabled(collapsed);
}
void CollapsingMenuWidget::draw(Canvas& canvas) {
canvas.rect(getArea().relative(), colorBG, rounding);
if (mHover) {
canvas.rect(mHeader.getArea(), colorHover, rounding);
}
}
FloatingScrollableMenu::FloatingScrollableMenu() : FloatingWidget() {
setDebug("float menu", { 0.0, 0.9, 0.1, 0.7 });
// addChild(&mMenuLayout);
addChild(&mHeader);
addChild(&mBodyLayout);
mHeader.setText("Menu");
mHeader.setSizePolicy(SizePolicy::Expanding, SizePolicy::Minimal);
mBodyLayout.setSizePolicy(SizePolicy::Expanding, SizePolicy::Expanding);
mBodyLayout.setLayout(new ScrollableLayout(&mBodyLayout));
mBodyLayout.addChild(&mScrollBar);
mBodyLayout.addChild(&mContentWidget);
mContentWidget.setSizePolicy(SizePolicy::Minimal, SizePolicy::Minimal);
// getLayout()->setLayoutPolicy(LayoutPolicy::Vertical);
// mBodyLayout.getLayout()->setLayoutPolicy(LayoutPolicy::Vertical);
}
void FloatingScrollableMenu::setText(const std::string& text) {
mHeader.setText(text);
}

View file

@ -1,13 +1,16 @@
#include "ScrollableWidget.hpp" #include "ScrollableWidget.hpp"
#include "ScrollableLayout.hpp"
#include "BasicLayout.hpp"
using namespace tp; using namespace tp;
void ScrollableBarWidget::process(const EventHandler& events) { void ScrollableBarWidget::process(const EventHandler& events) {
// all content is visible no need to process anything // all content is visible no need to process anything
if (mSizeFactor >= 1) { if (mSizeFactor >= 1) {
if (mScrolling) freeFocus();
mScrolling = false; mScrolling = false;
mPosFactor = mSizeFactor / 2.f; mPosFactor = mSizeFactor / 2.f;
freeFocus();
return; return;
} }
@ -85,3 +88,20 @@ void ScrollableBarWidget::updateHandleRect() {
const RectF& ScrollableBarWidget::getHandleRect() const { const RectF& ScrollableBarWidget::getHandleRect() const {
return mHandleRect; return mHandleRect;
} }
ScrollableWidget::ScrollableWidget() {
addChild(&mScroller);
addChild(&mContent);
setLayout(new ScrollableLayout(this));
mContent.setSizePolicy(SizePolicy::Minimal, SizePolicy::Minimal);
}
void ScrollableWidget::setDirection(bool direction) {
if (auto lay = dynamic_cast<BasicLayout*>(mContent.getLayout())) {
lay->setLayoutPolicy(direction ? LayoutPolicy::Vertical : LayoutPolicy::Horizontal);
}
mScroller.setDirection(direction);
}

View file

@ -107,7 +107,7 @@ void SliderWidget::process(const EventHandler& events) {
} }
void SliderWidget::draw(Canvas& canvas) { void SliderWidget::draw(Canvas& canvas) {
canvas.rect(getArea().relative(), mColorBG, mRounding); canvas.rect(getRelativeArea(), mColorBG, mRounding);
switch (mState) { switch (mState) {
case IDLE: canvas.rect(getHandleArea(), mColorIdle, mRounding); break; case IDLE: canvas.rect(getHandleArea(), mColorIdle, mRounding); break;

View file

@ -26,11 +26,20 @@ namespace tp {
explicit WidgetLayout(Widget* widget) { mWidget = widget; } explicit WidgetLayout(Widget* widget) { mWidget = widget; }
virtual ~WidgetLayout() = default; virtual ~WidgetLayout() = default;
virtual void updateLayout(bool vertical) {} public:
// picks own position and size
// modifies only own area
virtual void pickRect(bool vertical) {} virtual void pickRect(bool vertical) {}
virtual void clampRect() {}
[[nodiscard]] virtual RectF getAvailableChildArea() const; // arranges all children layouts inside itself
// modifies children areas
virtual void arrangeChildren(bool vertical) {}
// area that any child can have
[[nodiscard]] virtual RectF availableChildArea() const;
// minimal size base on the content of the layout
[[nodiscard]] virtual RectF minContentArea() const;
public: public:
const Vec2F& getMinSize(); const Vec2F& getMinSize();
@ -39,6 +48,8 @@ namespace tp {
[[nodiscard]] const Vec2<SizePolicy>& getSizePolicy() const; [[nodiscard]] const Vec2<SizePolicy>& getSizePolicy() const;
void setSizePolicy(SizePolicy x, SizePolicy y); void setSizePolicy(SizePolicy x, SizePolicy y);
static WidgetLayout* lay(Widget* w);
public: public:
[[nodiscard]] const RectF& getArea() const; [[nodiscard]] const RectF& getArea() const;
[[nodiscard]] RectF getAnimatedArea() const; [[nodiscard]] RectF getAnimatedArea() const;
@ -49,6 +60,7 @@ namespace tp {
public: public:
void clampMinMaxSize(); void clampMinMaxSize();
void pickMinimalRect(bool dir);
[[nodiscard]] RangeF pickRange(const RangeF& current, const RangeF& child, const RangeF& parent, bool v) const; [[nodiscard]] RangeF pickRange(const RangeF& current, const RangeF& child, const RangeF& parent, bool v) const;
[[nodiscard]] RangeF clampRange(const RangeF& current, const RangeF& child, const RangeF& parent, bool v) const; [[nodiscard]] RangeF clampRange(const RangeF& current, const RangeF& child, const RangeF& parent, bool v) const;
@ -61,7 +73,7 @@ namespace tp {
protected: protected:
Vec2<SizePolicy> mSizePolicy = { SizePolicy::Fixed, SizePolicy::Fixed }; Vec2<SizePolicy> mSizePolicy = { SizePolicy::Fixed, SizePolicy::Fixed };
Vec2F mMinSize = { 50, 50 }; Vec2F mMinSize = { 30, 30 };
Vec2F mMaxSize = { FLT_MAX / 2, FLT_MAX / 2 }; Vec2F mMaxSize = { FLT_MAX / 2, FLT_MAX / 2 };
private: private:

View file

@ -18,8 +18,6 @@ namespace tp {
void setRootWidget(Widget* widget); void setRootWidget(Widget* widget);
static void setWidgetArea(Widget& widget, const RectF& rect); static void setWidgetArea(Widget& widget, const RectF& rect);
[[nodiscard]] bool isDebug() const;
// Graphic Application Interface // Graphic Application Interface
public: public:
void processFrame(EventHandler* events, const RectF& screenArea); void processFrame(EventHandler* events, const RectF& screenArea);

View file

@ -31,6 +31,8 @@ namespace tp {
using DFSAction = std::function<void(Widget*)>; using DFSAction = std::function<void(Widget*)>;
protected:
enum Flags : int1 { enum Flags : int1 {
ENABLED = 0, ENABLED = 0,
NEEDS_UPDATE, NEEDS_UPDATE,
@ -59,6 +61,7 @@ namespace tp {
void setSizePolicy(SizePolicy x, SizePolicy y); void setSizePolicy(SizePolicy x, SizePolicy y);
void setEnabled(bool val) { mFlags.set(ENABLED, val); } void setEnabled(bool val) { mFlags.set(ENABLED, val); }
[[nodiscard]] bool getEnabled() const { return mFlags.get(ENABLED); }
WidgetLayout* getLayout(); WidgetLayout* getLayout();
[[nodiscard]] const WidgetLayout* getLayout() const; [[nodiscard]] const WidgetLayout* getLayout() const;

View file

@ -9,41 +9,24 @@ namespace tp {
public: public:
WidgetApplication() = default; WidgetApplication() = default;
void setRoot(Widget* widget) { void setRoot(Widget* widget);
mRootWidget.setRootWidget(widget);
}
private: private:
void processFrame(EventHandler* eventHandler, halnf deltaTime) override { void processFrame(EventHandler* eventHandler, halnf deltaTime) override;
const auto rec = RectF({ 0, 0 }, mWindow->getSize());
Timer timer; void drawFrame(Canvas* canvas) override;
mRootWidget.processFrame(eventHandler, rec); bool forceNewFrame() override ;
mProcTime = timer.timePassed();
}
void drawFrame(Canvas* canvas) override {
Timer timer;
mRootWidget.drawFrame(*canvas);
mDrawTime = timer.timePassed();
if (mRootWidget.isDebug()) {
drawDebug();
debugUI();
}
}
bool forceNewFrame() override {
return mRootWidget.needsUpdate();
}
private: private:
void debugUI(); void debugUI();
private: private:
time_ms mProcTime = 0; halnf mDebugSplitFactor = 0.7;
time_ms mDrawTime = 0;
RootWidget mRootWidget; RootWidget mRootWidget;
private:
RectF mGuiArea;
RectF mDebugArea;
}; };
} }

View file

@ -10,17 +10,21 @@ namespace tp {
public: public:
explicit BasicLayout(Widget* widget) : WidgetLayout(widget) {} explicit BasicLayout(Widget* widget) : WidgetLayout(widget) {}
void updateLayout(bool vertical) override; void arrangeChildren(bool vertical) override;
void pickRect(bool vertical) override; void pickRect(bool vertical) override;
void clampRect() override;
[[nodiscard]] RectF getAvailableChildArea() const override; [[nodiscard]] RectF availableChildArea() const override;
[[nodiscard]] RectF minContentArea() const override;
void setLayoutPolicy(LayoutPolicy layout) { mLayoutPolicy = layout; } void setLayoutPolicy(LayoutPolicy layout) { mLayoutPolicy = layout; }
private:
static bool canChange(Widget*, bool);
private: private:
void adjustLayout(bool vertical); void adjustLayout(bool vertical);
static halnf changeChildSize(Widget*, halnf diff, bool vertical); static halnf shrinkLayoutSize(WidgetLayout* widget, halnf diff, bool vertical);
private: private:
LayoutPolicy mLayoutPolicy = LayoutPolicy::Vertical; LayoutPolicy mLayoutPolicy = LayoutPolicy::Vertical;

View file

@ -43,8 +43,7 @@ namespace tp {
public: public:
void pickRect(bool vertical) override {} void pickRect(bool vertical) override {}
void clampRect() override {}; void arrangeChildren(bool vertical) override;
void updateLayout(bool vertical) override;
void adjustChildrenRect(); void adjustChildrenRect();
public: public:
@ -96,7 +95,7 @@ namespace tp {
bool mResizing = false; bool mResizing = false;
Widget* mCenterWidget = nullptr; Widget* mCenterWidget = nullptr;
RectF mCenterArea {}; RectF mCenterArea { 0, 0, 10, 10 };
// Parameters // Parameters
const halnf mHandleSplitFactor = 0.3; const halnf mHandleSplitFactor = 0.3;

View file

@ -10,9 +10,8 @@ namespace tp {
public: public:
explicit OverlayLayout(Widget* widget) : WidgetLayout(widget) {} explicit OverlayLayout(Widget* widget) : WidgetLayout(widget) {}
void updateLayout(bool vertical) override; void arrangeChildren(bool vertical) override;
void pickRect(bool vertical) override {} void pickRect(bool vertical) override {}
void clampRect() override {}
}; };
} }

View file

@ -12,8 +12,8 @@ namespace tp {
setSizePolicy(SizePolicy::Expanding, SizePolicy::Expanding); setSizePolicy(SizePolicy::Expanding, SizePolicy::Expanding);
} }
void updateLayout(bool vertical) override; void arrangeChildren(bool vertical) override;
[[nodiscard]] RectF getAvailableChildArea() const override; [[nodiscard]] RectF availableChildArea() const override;
private: private:
void updateWidgetRects(const RectF& area, Widget* content, ScrollableBarWidget* scroller) const; void updateWidgetRects(const RectF& area, Widget* content, ScrollableBarWidget* scroller) const;

View file

@ -5,12 +5,56 @@
#include <set> #include <set>
namespace tp { namespace tp {
class DebugTimeline {
enum {
STEP = 10,
LEN = 200,
};
public:
DebugTimeline() = default;
void addSample(time_ms time) {
samples[end] = time;
start++;
end++;
shift();
}
[[nodiscard]] int size() const {
return LEN - STEP;
}
[[nodiscard]] const time_ms* get() const {
return samples + start;
}
private:
void shift() {
if (end >= LEN) {
for (ualni i = STEP; i < LEN; i++) {
samples[i - STEP] = samples[i];
}
start = 0;
end = LEN - STEP;
}
}
private:
ualni start = 0;
ualni end = LEN - STEP;
time_ms samples[LEN + 1] {};
};
class DebugManager { class DebugManager {
public: public:
DebugManager() = default; DebugManager() = default;
bool isRedrawAlways() const { return mDebugRedrawAlways; } [[nodiscard]] bool isFrozen() const { return mDebugStopProcessing; }
bool update(RootWidget* rootWidget, EventHandler& events); [[nodiscard]] bool isRedrawAlways() const { return mDebugRedrawAlways; }
void update(RootWidget* rootWidget, EventHandler& events);
void drawDebug(RootWidget* rootWidget, Canvas& canvas); void drawDebug(RootWidget* rootWidget, Canvas& canvas);
void checkProcBreakPoints(Widget* widget) { void checkProcBreakPoints(Widget* widget) {
@ -32,6 +76,7 @@ namespace tp {
private: private:
void recursiveDraw(Canvas& canvas, Widget* active, const Vec2F& pos, int depthOrder); void recursiveDraw(Canvas& canvas, Widget* active, const Vec2F& pos, int depthOrder);
void drawPerformance();
static void widgetMenu(Widget*); static void widgetMenu(Widget*);
void drawLayoutOrder(); void drawLayoutOrder();
@ -42,10 +87,17 @@ namespace tp {
bool mDebug = false; bool mDebug = false;
bool mDebugStopProcessing = false; bool mDebugStopProcessing = false;
bool mDebugRedrawAlways = false; bool mDebugRedrawAlways = false;
bool mSlowMotion = false; bool mDetailed = true;
std::set<Widget*> mProcBreakpoints; std::set<Widget*> mProcBreakpoints;
std::set<Widget*> mLayBreakpoints; std::set<Widget*> mLayBreakpoints;
public:
DebugTimeline mProcTime;
DebugTimeline mUpdManager;
DebugTimeline mLayManager;
DebugTimeline mDrawTime;
}; };
extern DebugManager gDebugWidget; extern DebugManager gDebugWidget;

View file

@ -25,13 +25,16 @@ namespace tp {
void clean(); void clean();
void updateTreeToProcess(Widget* root); void updateTreeToProcess(Widget* root);
void handleFocusChanges(Widget* root, EventHandler& events); void handleFocusChanges(Widget* active, Widget* prevActive);
Widget* findFocusWidget(Widget* root, EventHandler& events);
void findFocusWidget(Widget* iter, Widget** focus, const Vec2F& pointer); void findMouseFocusWidget(Widget* iter, Widget** focus, const Vec2F& pointer);
static void getWidgetPath(Widget* widget, std::vector<Widget*>& out); static void getWidgetPath(Widget* widget, std::vector<Widget*>& out);
void processActiveTree(Widget* iter, EventHandler& events, Vec2F pos); void processActiveTree(Widget* iter, EventHandler& events, Vec2F pos);
void processFocusItems(EventHandler& events); void processFocusItems(EventHandler& events);
Widget* getFocusWidget() { return mInFocusWidget; }
private: private:
static void procWidget(Widget* widget, EventHandler& events, bool withEvents = false); static void procWidget(Widget* widget, EventHandler& events, bool withEvents = false);

View file

@ -13,10 +13,8 @@ namespace tp {
} }
void process(const EventHandler& events) override; void process(const EventHandler& events) override;
void draw(Canvas& canvas) override; void draw(Canvas& canvas) override;
[[nodiscard]] bool needsNextFrame() const override; [[nodiscard]] bool needsNextFrame() const override;
[[nodiscard]] bool propagateEventsToChildren() const override; [[nodiscard]] bool propagateEventsToChildren() const override;
@ -28,35 +26,4 @@ namespace tp {
FloatingLayout* layout(); FloatingLayout* layout();
[[nodiscard]] const FloatingLayout* layout() const; [[nodiscard]] const FloatingLayout* layout() const;
}; };
class FloatingMenu : public FloatingWidget {
public:
FloatingMenu();
public:
void addToMenu(Widget* widget) {
widget->setSizePolicy(SizePolicy::Expanding, SizePolicy::Minimal);
mContentWidget.addChild(widget);
}
const List<Widget*>& getContent() {
return mContentWidget.getChildren();
}
void clearChildren() {
mContentWidget.clear();
}
void setText(const std::string& text);
private:
// VerticalLayout mMenuLayout;
Widget mBodyLayout;
Widget mContentWidget;
ScrollableBarWidget mScrollBar;
LabelWidget mHeader;
// ButtonWidget mTestButton;
};
} }

View file

@ -0,0 +1,60 @@
#pragma once
#include "FloatingWidget.hpp"
namespace tp {
class CollapsingMenuWidget : public Widget {
public:
CollapsingMenuWidget();
void process(const EventHandler& events) override;
void draw(Canvas& canvas) override;
[[nodiscard]] bool processesEvents() const override { return true; }
public:
void setCollapsed(bool val);
LabelWidget* getHeader() { return &mHeader; }
Widget* getContainer() { return &mContent; }
private:
bool mHover = false;
LabelWidget mHeader;
Widget mContent;
private:
halnf rounding = 5;
RGBA colorHover = RGBA(0.7);
RGBA colorBG = RGBA(0.3);
};
class FloatingScrollableMenu : public FloatingWidget {
public:
FloatingScrollableMenu();
public:
void addToMenu(Widget* widget) {
widget->setSizePolicy(SizePolicy::Expanding, SizePolicy::Minimal);
mContentWidget.addChild(widget);
}
const List<Widget*>& getContent() {
return mContentWidget.getChildren();
}
void clearChildren() {
mContentWidget.clear();
}
void setText(const std::string& text);
private:
// VerticalLayout mMenuLayout;
Widget mBodyLayout;
Widget mContentWidget;
ScrollableBarWidget mScrollBar;
LabelWidget mHeader;
// ButtonWidget mTestButton;
};
}

View file

@ -20,6 +20,8 @@ namespace tp {
[[nodiscard]] bool getDirection() const { return mVertical; } [[nodiscard]] bool getDirection() const { return mVertical; }
[[nodiscard]] halnf getPosFactor() const { return mPosFactor - mSizeFactor / 2; } [[nodiscard]] halnf getPosFactor() const { return mPosFactor - mSizeFactor / 2; }
void setDirection(bool direction) { mVertical = direction; }
private: private:
[[nodiscard]] const RectF& getHandleRect() const; [[nodiscard]] const RectF& getHandleRect() const;
void updateHandleRect(); void updateHandleRect();
@ -53,5 +55,13 @@ namespace tp {
class ScrollableWidget : public Widget { class ScrollableWidget : public Widget {
public: public:
ScrollableWidget(); ScrollableWidget();
void setDirection(bool direction);
Widget* getContainer() { return &mContent; }
private:
Widget mContent;
ScrollableBarWidget mScroller;
}; };
} }

View file

@ -71,7 +71,7 @@ namespace tp {
void draw(Canvas& canvas) override; void draw(Canvas& canvas) override;
[[nodiscard]] bool processesEvents() const override { return true; } [[nodiscard]] bool processesEvents() const override { return true; }
[[nodiscard]] bool needsNextFrame() const override { return mState != SLIDING; } [[nodiscard]] bool needsNextFrame() const override { return mState != IDLE; }
[[nodiscard]] halnf val() const { return mFactor; } [[nodiscard]] halnf val() const { return mFactor; }