Introduce ViewGuard: A weak ptr to View

This commit is contained in:
Waqar Ahmed
2022-04-05 17:05:17 +05:00
parent 84497f422d
commit b573d3f0f7
5 changed files with 124 additions and 0 deletions

View File

@@ -98,6 +98,8 @@ set(DOCKSLIBS_SRCS
controllers/TabBar.h
View.cpp
View.h
ViewGuard.cpp
ViewGuard.h
ViewWrapper.cpp
ViewWrapper.h
Controller.cpp

57
src/ViewGuard.cpp Normal file
View File

@@ -0,0 +1,57 @@
#include "ViewGuard.h"
#include "View.h"
using namespace KDDockWidgets;
ViewGuard::ViewGuard(View *view)
: v(view && view->inDtor() ? nullptr : view)
{
if (v) {
m_onDestroy = v->beingDestroyed.connect([this] {
v = nullptr;
});
}
}
ViewGuard::operator bool() const
{
return !isNull();
}
bool ViewGuard::isNull() const
{
return v == nullptr;
}
View *ViewGuard::operator->()
{
return v;
}
void ViewGuard::clear()
{
v = nullptr;
}
View *ViewGuard::view() const
{
return v;
}
ViewGuard& ViewGuard::operator=(View *view)
{
if (view == v) {
return *this;
}
// Remove the pervious connection
if (m_onDestroy.isActive())
m_onDestroy.disconnect();
v = view;
m_onDestroy = v->beingDestroyed.connect([this] {
v = nullptr;
});
return *this;
}

33
src/ViewGuard.h Normal file
View File

@@ -0,0 +1,33 @@
#ifndef KDDW_VIEW_GUARD_H
#define KDDW_VIEW_GUARD_H
#include "docks_export.h"
#include "kdbindings/signal.h"
namespace KDDockWidgets {
class View;
/// @brief This class provides a weak reference to a view
/// i.e., it becomes null automatically once a View is destroyed
class DOCKS_EXPORT ViewGuard
{
public:
ViewGuard(View *v);
operator bool() const;
View *operator->();
void clear();
bool isNull() const;
View *view() const;
ViewGuard& operator=(View *);
private:
View *v = nullptr;
KDBindings::ConnectionHandle m_onDestroy;
};
}
#endif

View File

@@ -49,3 +49,6 @@ endif()
# tests_launcher
add_executable(tests_launcher tests_launcher.cpp)
target_link_libraries(tests_launcher Qt${Qt_VERSION_MAJOR}::Core)
add_executable(tst_viewguard tst_viewguard.cpp)
target_link_libraries(tst_viewguard kddockwidgets)

29
tests/tst_viewguard.cpp Normal file
View File

@@ -0,0 +1,29 @@
#include <cstdio>
#include <ViewGuard.h>
#include <qtwidgets/views/ViewWrapper_qtwidgets.h>
using namespace KDDockWidgets;
void test(bool cond, const char *stmt, int line)
{
if (!cond) {
printf("[FAILED] %s line; %d\n", stmt, line);
exit(1);
}
}
#define TEST(cond) test(cond, #cond, __LINE__)
int main()
{
ViewGuard g(nullptr);
TEST(g.isNull());
{
Views::ViewWrapper_qtwidgets wv(static_cast<QWidget*>(nullptr));
g = &wv;
TEST(!g.isNull());
}
TEST(g.isNull());
}