diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f71ea16 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,84 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +jobs: + linux: + name: ${{ matrix.name }} + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - name: Release + build_type: Release + options: -DOGUI_BUILD_EXAMPLES=ON + flags: "" + - name: Static library + build_type: Release + options: -DOGUI_BUILD_SHARED=OFF -DOGUI_BUILD_EXAMPLES=OFF + flags: "" + - name: Bundled GLFW + build_type: Release + options: -DOGUI_SYSTEM_GLFW=OFF -DOGUI_BUILD_EXAMPLES=OFF + flags: "" + - name: AddressSanitizer + build_type: Debug + options: -DOGUI_BUILD_EXAMPLES=OFF + flags: -fsanitize=address,undefined -fno-omit-frame-pointer + - name: ThreadSanitizer + build_type: Debug + options: -DOGUI_BUILD_EXAMPLES=OFF + flags: -fsanitize=thread -fno-omit-frame-pointer + + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + cmake g++ libopencv-dev libglew-dev libglfw3-dev \ + libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev \ + xvfb xauth libgl1-mesa-dri + + # The default address randomization of the runners breaks ThreadSanitizer + - name: Allow ThreadSanitizer memory mappings + if: contains(matrix.flags, 'thread') + run: sudo sysctl vm.mmap_rnd_bits=28 + + - name: Configure + run: > + cmake -S . -B build + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}/install + -DOGUI_BUILD_TESTS=ON + ${{ matrix.options }} + "-DCMAKE_C_FLAGS=${{ matrix.flags }}" + "-DCMAKE_CXX_FLAGS=${{ matrix.flags }}" + "-DCMAKE_EXE_LINKER_FLAGS=${{ matrix.flags }}" + "-DCMAKE_SHARED_LINKER_FLAGS=${{ matrix.flags }}" + + - name: Build + run: cmake --build build -j $(nproc) + + - name: Test + env: + LIBGL_ALWAYS_SOFTWARE: 1 + UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1 + run: xvfb-run -a -s "-screen 0 1024x768x24" ctest --test-dir build --output-on-failure + + - name: Install and use the CMake package + if: matrix.flags == '' + env: + LIBGL_ALWAYS_SOFTWARE: 1 + run: | + cmake --install build + cmake -S tests/consumer -B build-consumer -DCMAKE_PREFIX_PATH=${{ github.workspace }}/install + cmake --build build-consumer + LD_LIBRARY_PATH=${{ github.workspace }}/install/lib xvfb-run -a build-consumer/consumer diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f33ed8..f21c2af 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.16) -project(OpenCVGUI VERSION 1.0.1 LANGUAGES C CXX) +project(OpenCVGUI VERSION 2.0.0 LANGUAGES C CXX) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bin") @@ -8,6 +8,7 @@ option(OGUI_BUILD_SHARED "Build OpenCVGUI as a shared library?" ON) option(OGUI_GL3 "Build OpenCVGUI with OpenGL 3 support?" ON) option(OGUI_BUILD_EXAMPLES "Build OpenCVGUI examples?" ON) option(OGUI_SYSTEM_GLFW "Use system GLFW if available instead of 3rdparty/glfw?" ON) +option(OGUI_BUILD_TESTS "Build OpenCVGUI tests? They need a display, use xvfb-run in CI" OFF) include(GNUInstallDirs) include(CMakePackageConfigHelpers) @@ -67,7 +68,7 @@ set_target_properties(opencvgui PROPERTIES EXPORT_NAME OpenCVGUI FOLDER "OpenCVGUI") -target_compile_features(opencvgui PUBLIC cxx_std_11) +target_compile_features(opencvgui PUBLIC cxx_std_14) if(OGUI_GL3) target_compile_definitions(opencvgui PRIVATE OGUI_GL3) @@ -112,6 +113,18 @@ endif() add_executable(font2c src/font2c.cpp) +# Tests +if(OGUI_BUILD_TESTS) + enable_testing() + foreach(test test_render test_dialogs) + add_executable(${test} tests/${test}.cpp) + target_link_libraries(${test} PRIVATE opencvgui glfw) + set_target_properties(${test} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tests") + add_test(NAME ${test} COMMAND ${test}) + set_tests_properties(${test} PROPERTIES TIMEOUT 60) + endforeach() +endif() + # INSTALLATION install(TARGETS opencvgui EXPORT OpenCVGUITargets diff --git a/README.md b/README.md index 1db097f..bc222f8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # OpenCVGUI +[![CI](https://github.com/damiles/OpenCVGUI/actions/workflows/ci.yml/badge.svg)](https://github.com/damiles/OpenCVGUI/actions/workflows/ci.yml) + Do you like OpenCV Highui but it's not enough and don't want waste your time in a new UI SDK? **This is your solution!** OpenCVGUI is a new graphical user inteface for OpenCV with different @@ -22,6 +24,16 @@ Why OpenCVGUI: more Powerful and exactly so simple than OpenCV Highui. 5. make 6. sudo make install +# Tests +Tests open a window, so they need a display. Use `xvfb-run` on machines +without one. + +```bash +cmake -S . -B build -DOGUI_BUILD_TESTS=ON +cmake --build build +ctest --test-dir build --output-on-failure +``` + ## Features @@ -58,7 +70,7 @@ Create a new window Show image in window ```C++ Mat image= imread("./lena.jpg"); - window->imshow("image title key like highui imshow", &image); + window->imshow("image title key like highui imshow", image); ``` Custom 3D plot shaders (optional, defaults are embedded in the library). @@ -88,11 +100,11 @@ OGUICVWindow *window; void cv_process() { while(app_is_running) { cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); Mat output; cvtColor( frame, gray, COLOR_RGB2GRAY ); threshold( gray, output, (int)thr, 255, CV_THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); } } @@ -118,7 +130,7 @@ int main( int argc, const char* argv[] ) if(cap.isOpened()){ cap >> frame; // show image - window->imshow("camera", &frame); + window->imshow("camera", frame); }else{ return 0; } @@ -127,7 +139,7 @@ int main( int argc, const char* argv[] ) cvtColor( frame, gray, COLOR_RGB2GRAY ); Mat output; threshold( gray, output, 125, 255, CV_THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); // Start the Comptuer vision process OpenCVGUI::app_run(cv_process); diff --git a/docs/docs/hello-world.md b/docs/docs/hello-world.md index 55c21bc..14ca219 100644 --- a/docs/docs/hello-world.md +++ b/docs/docs/hello-world.md @@ -28,11 +28,11 @@ OGUICVWindow *window; void cv_process() { while(app_is_running) { cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); Mat output; cvtColor( frame, gray, COLOR_RGB2GRAY ); threshold( gray, output, (int)thr, 255, CV_THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); } } @@ -58,7 +58,7 @@ int main( int argc, const char* argv[] ) if(cap.isOpened()){ cap >> frame; // show image - window->imshow("camera", &frame); + window->imshow("camera", frame); }else{ return 0; } @@ -67,7 +67,7 @@ int main( int argc, const char* argv[] ) cvtColor( frame, gray, COLOR_RGB2GRAY ); Mat output; threshold( gray, output, 125, 255, CV_THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); // Start the Comptuer vision process OpenCVGUI::app_run(cv_process); diff --git a/include/OpenCVGUI/OGUI3D.h b/include/OpenCVGUI/OGUI3D.h index 0dae21b..f7bf4e8 100644 --- a/include/OpenCVGUI/OGUI3D.h +++ b/include/OpenCVGUI/OGUI3D.h @@ -46,7 +46,7 @@ class OGUI3D : public OGUIArea { virtual void draw(int x, int y, int width, int height); virtual void draw3d(int x, int y, int width, int height); virtual void updateScrollStatus(double xoffset,double yoffset); - void replot(void *data); + void replot(const Mat& data); /** * Set a function to draw custom OpenGL content in the 3D area. @@ -56,7 +56,7 @@ class OGUI3D : public OGUIArea { */ void setExternalDraw3D(std::function func); - OGUI3D(OGUIWindow* window, std::string title, void* data); + OGUI3D(OGUIWindow* window, const std::string& title, const Mat& data); // 3d functions GLuint vao, vbo, ibo, shaderProgram, MatrixID, position_attribute; diff --git a/include/OpenCVGUI/OGUIArea.h b/include/OpenCVGUI/OGUIArea.h index dab3b2a..2cb365f 100644 --- a/include/OpenCVGUI/OGUIArea.h +++ b/include/OpenCVGUI/OGUIArea.h @@ -13,6 +13,7 @@ class OGUIArea { public: OGUIArea(OGUIWindow* window); + virtual ~OGUIArea() {} virtual void draw(int x, int y, int width, int height); virtual void draw3d(int x, int y, int width, int height); diff --git a/include/OpenCVGUI/OGUICVWindow.h b/include/OpenCVGUI/OGUICVWindow.h index 3eb171a..0d71a71 100644 --- a/include/OpenCVGUI/OGUICVWindow.h +++ b/include/OpenCVGUI/OGUICVWindow.h @@ -13,6 +13,7 @@ #include "OGUI3D.h" #include "OGUIPlotArea.h" #include +#include namespace OpenCVGUI { /** @@ -37,9 +38,11 @@ class OGUICVWindow : public OGUIWindow{ /** * Add new image to window with title * @param {string} area_title image are title - * @param {Mat} image opencv mat + * @param {Mat} image opencv mat, it is copied */ - void imshow(string area_title, void* img); + void imshow(const string& area_title, const Mat& img); + [[deprecated("use imshow(title, const cv::Mat&)")]] + void imshow(const string& area_title, const Mat* img); /** * Add callback for mouse interaction to specific image area @@ -57,9 +60,29 @@ class OGUICVWindow : public OGUIWindow{ OGUIArea* findAreaByTitle(string title); void addFormWidget(OGUIWidget* widget); - void plot3D(string area_title, void* data); - void plot2D(string area_title, void* data, std::vector labels, float xstep=1, int plot_type=0); + /** + * Add or update a 3D plot of a CV_32F Mat, values are the height + * @param {string} area_title plot area title + * @param {Mat} data opencv mat, it is copied + */ + void plot3D(const string& area_title, const Mat& data); + [[deprecated("use plot3D(title, const cv::Mat&)")]] + void plot3D(const string& area_title, const Mat* data); + + /** + * Add or update a 2D plot, each Mat row is a serie + * @param {string} area_title plot area title + * @param {Mat} data opencv mat, it is copied + * @param {vector} labels one label per serie + * @param {float} xstep x distance between values + * @param {int} plot_type one of PlotTypes + */ + void plot2D(const string& area_title, const Mat& data, const std::vector& labels, float xstep=1, int plot_type=0); + [[deprecated("use plot2D(title, const cv::Mat&, labels, ...)")]] + void plot2D(const string& area_title, const Mat* data, const std::vector& labels, float xstep=1, int plot_type=0); + + // Areas and layouts are owned by the window, these pointers are only for access std::vector areas_showing; std::vector layout; OGUIFormArea *formArea; @@ -67,6 +90,10 @@ class OGUICVWindow : public OGUIWindow{ private: + // Areas created by the window, released when the window is destroyed + std::vector> _owned_areas; + template T* own(T* area); + // Protects areas_showing, imshow and plots can be called from any thread std::mutex _areas_mutex; OGUIArea* findArea(string title); diff --git a/include/OpenCVGUI/OGUIFile.h b/include/OpenCVGUI/OGUIFile.h index 8db45a6..b290ca5 100644 --- a/include/OpenCVGUI/OGUIFile.h +++ b/include/OpenCVGUI/OGUIFile.h @@ -13,25 +13,29 @@ using namespace std; using namespace cv; +struct NVGcontext; + namespace OpenCVGUI { + class OGUIWindow; + class OGUIFile { public: - OGUIFile(void* window, const char* file_name, const char* path, int isdir, const char* ext, double size); + OGUIFile(OGUIWindow* window, const char* file_name, const char* path, int isdir, const char* ext, double size); string _file_name; string _path; string _ext; int _is_dir; //1 is dir 2 is drive double _size; - void* _window; + OGUIWindow* _window; - bool draw(void *vvg, int x, int y, int mouse_x, int mouse_y); + bool draw(NVGcontext* vg, int x, int y, int mouse_x, int mouse_y); bool isImage(); unsigned char* getPreview(); private: int _mouse_state; - unsigned char* _preview_data; + Mat _preview; // 150x150 RGBA preview }; } diff --git a/include/OpenCVGUI/OGUIFileBrowser.h b/include/OpenCVGUI/OGUIFileBrowser.h index 7151cc8..66d5430 100644 --- a/include/OpenCVGUI/OGUIFileBrowser.h +++ b/include/OpenCVGUI/OGUIFileBrowser.h @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -34,11 +35,11 @@ namespace OpenCVGUI { private: OGUIWindow* _window; bool _is_file_browser_visible = false; - OGUIFile* _file_browser_result; - std::vector _file_list; + OGUIFile* _file_browser_result; // Points to a file in _file_list or _system + std::vector> _file_list; string _actual_folder; std::vector _filter; - std::vector _system; + std::vector> _system; char resolved_path[4096]; diff --git a/include/OpenCVGUI/OGUIImageArea.h b/include/OpenCVGUI/OGUIImageArea.h index b80a4da..65c3c09 100644 --- a/include/OpenCVGUI/OGUIImageArea.h +++ b/include/OpenCVGUI/OGUIImageArea.h @@ -21,7 +21,10 @@ class OGUIImageArea : public OGUIArea { virtual void draw(int x, int y, int width, int height); virtual void updateScrollStatus(double xoffset,double yoffset); OGUIImageArea(OGUIWindow* window, string title=""); - void setImage(Mat *img); + // Set the image to show, it is copied + void setImage(const Mat& img); + [[deprecated("use setImage(const cv::Mat&)")]] + void setImage(const Mat* img); void setMouseClickCallBack(std::function func); void calcHistogram(); private: diff --git a/include/OpenCVGUI/OGUIPlotArea.h b/include/OpenCVGUI/OGUIPlotArea.h index d4fced5..7f778d7 100644 --- a/include/OpenCVGUI/OGUIPlotArea.h +++ b/include/OpenCVGUI/OGUIPlotArea.h @@ -22,8 +22,8 @@ class OGUIPlotArea : public OGUIArea { virtual void draw(int x, int y, int width, int height); - OGUIPlotArea(OGUIWindow* window, std::string title, void* data, std::vector labels, float xstep=1.f, int plot_type=0); - void replot(void *data, std::vector labels, float xstep=1.f); + OGUIPlotArea(OGUIWindow* window, const std::string& title, const Mat& data, const std::vector& labels, float xstep=1.f, int plot_type=0); + void replot(const Mat& data, const std::vector& labels, float xstep=1.f); std::vector color_scheme={ 0,160,192, 255,51,102, diff --git a/include/OpenCVGUI/OGUIUtils.h b/include/OpenCVGUI/OGUIUtils.h index bc6fac3..ac04045 100644 --- a/include/OpenCVGUI/OGUIUtils.h +++ b/include/OpenCVGUI/OGUIUtils.h @@ -9,8 +9,8 @@ using namespace OpenCVGUI; -void drawParagraph(void* vvg, const char* text, float x, float y, float width, float height, float mx, float my); -bool drawBasicButton(void *context, OGUIWindow* window, const char* title, int x, int y, int width, int height, int mouse_x, int mouse_y, const char* typography="sans", double font_size=20.0f ); -void drawHeader(void* vvg, string title, int x, int y, int w); -void drawLabel(void *context, const char* text, int x, int y, const char* typography="sans", double font_size=16.0f, int r=255, int g=255, int b=255, int a=255 ); +void drawParagraph(NVGcontext* vg, const char* text, float x, float y, float width, float height, float mx, float my); +bool drawBasicButton(NVGcontext* vg, OGUIWindow* window, const char* title, int x, int y, int width, int height, int mouse_x, int mouse_y, const char* typography="sans", double font_size=20.0f ); +void drawHeader(NVGcontext* vg, string title, int x, int y, int w); +void drawLabel(NVGcontext* vg, const char* text, int x, int y, const char* typography="sans", double font_size=16.0f, int r=255, int g=255, int b=255, int a=255 ); #endif //OPENCVGUI_OGUIUTILS_H diff --git a/include/OpenCVGUI/OGUIVideoTimeline.h b/include/OpenCVGUI/OGUIVideoTimeline.h index 945cd10..d1fbe8f 100644 --- a/include/OpenCVGUI/OGUIVideoTimeline.h +++ b/include/OpenCVGUI/OGUIVideoTimeline.h @@ -18,7 +18,7 @@ namespace OpenCVGUI { string title; NVGcolor color; TimeMarker(string title, int start, int end, NVGcolor color): title(title), start(start), end(end), color(color) {}; - void draw(void* vvg, int x, int y, int mouse_x, int mouse_y); + void draw(NVGcontext* vg, int x, int y, int mouse_x, int mouse_y); }; class Track { @@ -28,7 +28,7 @@ namespace OpenCVGUI { VideoCapture* videocap; double duration; string title; - void draw(void* vvg, int x, int y, int width, int height, int mouse_x, int mouse_y); + void draw(NVGcontext* vg, int x, int y, int width, int height, int mouse_x, int mouse_y); void add_marker(string title, int start, int end, NVGcolor color); private: vector markers; diff --git a/include/OpenCVGUI/OGUIWidget.h b/include/OpenCVGUI/OGUIWidget.h index dc182c7..4345726 100644 --- a/include/OpenCVGUI/OGUIWidget.h +++ b/include/OpenCVGUI/OGUIWidget.h @@ -11,6 +11,7 @@ class OGUIWidget { public: + virtual ~OGUIWidget() {} virtual void draw(int x, int y, int widht); virtual void characterCallback(unsigned int key); virtual void keyCallback(int key, int scancode, int action, int mods); diff --git a/include/OpenCVGUI/OGUIWindow.h b/include/OpenCVGUI/OGUIWindow.h index 1caa733..1425c92 100644 --- a/include/OpenCVGUI/OGUIWindow.h +++ b/include/OpenCVGUI/OGUIWindow.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include "perf.h" @@ -17,6 +18,11 @@ using namespace std; +// GLFW and NanoVG types, declared here to not include their headers +struct GLFWwindow; +struct GLFWcursor; +struct NVGcontext; + // Font images extern unsigned char font_roboto[]; extern int font_roboto_size; @@ -59,10 +65,10 @@ class OGUIWindow { void draw(); bool update(); // Return false if window is closed - void* glfw_window;//GLFWwindow + GLFWwindow* glfw_window; static bool isInitGlfw; int init(bool fullScreen); - void* vg;//NVGcontext + NVGcontext* vg; void addArea(OGUIArea* area); double mouse_x, mouse_y; int mouse_state; @@ -74,20 +80,20 @@ class OGUIWindow { int mouse_left_state; // save pointers to all loaded mouse cursors - std::vector mouse_cursors_;//GLFWcursor + std::vector mouse_cursors_; OGUILayout* getMainLayout(); - static void scroll_callback(void* window, double xoffset, double yoffset);//GLFWwindow + static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void setKeyFocus(OGUIWidget* widget); - static void charCallback(void* window, unsigned int key);//GLFWwindow - static void keyCallback(void* window, int key, int scancode, int action, int mods);//GLFWwindow + static void charCallback(GLFWwindow* window, unsigned int key); + static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); OGUIWidget* getKeyFocusWidget(); int getWindowHeight(); int getWindowWidth(); void updatePerfGraph(); void showPerfGraph(bool show); - void setExternal2DDraw(std::function func); + void setExternal2DDraw(std::function func); /// Popups, blocks until it is closed, can not be called from the UI thread int popup(string title, string text, int type=2); @@ -127,7 +133,7 @@ class OGUIWindow { /** * @element-type OGUIArea */ - OGUILayout* mainLayout; + std::unique_ptr mainLayout; int width, height; string title; OGUIWidget* key_focus_widget_; @@ -145,7 +151,7 @@ class OGUIWindow { float _progress = 0; string _progress_title; - std::function _external2dDraw; + std::function _external2dDraw; // Popups bool drawPopup(); // Return true if a popup is visible @@ -155,7 +161,7 @@ class OGUIWindow { int _popup_result=0; // File Browser - OGUIFileBrowser *_fileBrowser; + std::unique_ptr _fileBrowser; // Maxmized Area OGUIArea *_maximizedArea; diff --git a/include/OpenCVGUI/perf.h b/include/OpenCVGUI/perf.h index 16c6eb1..db791b9 100644 --- a/include/OpenCVGUI/perf.h +++ b/include/OpenCVGUI/perf.h @@ -22,7 +22,8 @@ typedef struct PerfGraph PerfGraph; void initGraph(PerfGraph* fps, int style, const char* name); void updateGraph(PerfGraph* fps, float frameTime); -void renderGraph(void* vg, float x, float y, PerfGraph* fps); +struct NVGcontext; +void renderGraph(struct NVGcontext* vg, float x, float y, PerfGraph* fps); float getGraphAverage(PerfGraph* fps); #define GPU_QUERY_COUNT 5 diff --git a/src/OpenCVGUI/OGUI3D.cpp b/src/OpenCVGUI/OGUI3D.cpp index 326ed4c..ad5b454 100644 --- a/src/OpenCVGUI/OGUI3D.cpp +++ b/src/OpenCVGUI/OGUI3D.cpp @@ -370,7 +370,7 @@ void OGUI3D::draw(int x, int y, int width, int height) this->y=y; this->width= width; this->height= height; - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; nvgScissor(vg, x, y, width, height); OGUIArea::draw(x,y,width,height); @@ -379,11 +379,11 @@ void OGUI3D::draw(int x, int y, int width, int height) nvgResetScissor(vg); } -OGUI3D::OGUI3D(OGUIWindow* window, std::string title, void* d): OGUIArea(window) +OGUI3D::OGUI3D(OGUIWindow* window, const std::string& title, const Mat& d): OGUIArea(window) { this->type= 1; // 3d type window this->title= title; - ((Mat*)d)->copyTo(data); + d.copyTo(data); shaderProgram= 0; vao= vbo= ibo= 0; @@ -396,11 +396,11 @@ void OGUI3D::setExternalDraw3D(std::functioncopyTo(new_data); + d.copyTo(new_data); std::lock_guard lock(_mutex); data= new_data; isBufferCreated= false; diff --git a/src/OpenCVGUI/OGUIArea.cpp b/src/OpenCVGUI/OGUIArea.cpp index 3432f36..d5a3677 100644 --- a/src/OpenCVGUI/OGUIArea.cpp +++ b/src/OpenCVGUI/OGUIArea.cpp @@ -19,7 +19,7 @@ void OGUIArea::draw(int x, int y, int width, int height) this->width=width; this->height=height; - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; // Window nvgBeginPath(vg); nvgRect(vg, x,y, width,height); @@ -44,7 +44,7 @@ void OGUIArea::draw(int x, int y, int width, int height) void OGUIArea::drawTitle(bool always_show) { - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; if((isMouseIn() && _show_title_bar) || always_show ) { nvgBeginPath(vg); nvgRect(vg, x, y, width, 22); diff --git a/src/OpenCVGUI/OGUIButton.cpp b/src/OpenCVGUI/OGUIButton.cpp index 2108bd0..78c99b9 100644 --- a/src/OpenCVGUI/OGUIButton.cpp +++ b/src/OpenCVGUI/OGUIButton.cpp @@ -16,7 +16,7 @@ namespace OpenCVGUI { { OGUIWidget::draw(x, y, width); OGUIArea* area= (OGUIArea*)(this->area); - NVGcontext* vg= (NVGcontext*)(area->window->vg); + NVGcontext* vg= area->window->vg; // Draw box square nvgBeginPath(vg); nvgRoundedRect(vg, x+1,y+1, width-2,height-2, 3); diff --git a/src/OpenCVGUI/OGUICVWindow.cpp b/src/OpenCVGUI/OGUICVWindow.cpp index 2fe5b42..3e21f2f 100644 --- a/src/OpenCVGUI/OGUICVWindow.cpp +++ b/src/OpenCVGUI/OGUICVWindow.cpp @@ -8,9 +8,9 @@ namespace OpenCVGUI { OGUICVWindow::OGUICVWindow(int width,int height,const char* title, int layoutOrientation): OGUIWindow(width, height, title, layoutOrientation) { - this->formArea= new OGUIFormArea(this); - this->layout.push_back(new OGUILayout(this, 1)); - this->layout.push_back(new OGUILayout(this, 1)); + this->formArea= own(new OGUIFormArea(this)); + this->layout.push_back(own(new OGUILayout(this, 1))); + this->layout.push_back(own(new OGUILayout(this, 1))); this->addArea(formArea); this->addArea(layout.at(0)); @@ -25,7 +25,11 @@ namespace OpenCVGUI { } /// Show image into layouts - void OGUICVWindow::imshow(string area_title, void *img) { + void OGUICVWindow::imshow(const string& area_title, const Mat* img) { + imshow(area_title, *img); + } + + void OGUICVWindow::imshow(const string& area_title, const Mat& img) { std::lock_guard lock(_areas_mutex); /// Look for area OGUIArea* area=findArea(area_title); @@ -33,12 +37,12 @@ namespace OpenCVGUI { /// create or redraw if(area==NULL){ // create new area and ad - OGUIImageArea *ia= new OGUIImageArea(this, area_title); - ia->setImage((Mat*)img); + OGUIImageArea *ia= own(new OGUIImageArea(this, area_title)); + ia->setImage(img); showArea(ia); }else{ OGUIImageArea *ia= (OGUIImageArea*)area; - ia->setImage((Mat*)img); + ia->setImage(img); } } @@ -46,14 +50,18 @@ namespace OpenCVGUI { formArea->addWidget(widget); } - void OGUICVWindow::plot3D(string area_title, void *data) { + void OGUICVWindow::plot3D(const string& area_title, const Mat* data) { + plot3D(area_title, *data); + } + + void OGUICVWindow::plot3D(const string& area_title, const Mat& data) { std::lock_guard lock(_areas_mutex); /// Look for area OGUIArea* area=findArea(area_title); /// create or redraw if(area==NULL){ // create new area and ad - OGUI3D *ia= new OGUI3D(this, area_title, data); + OGUI3D *ia= own(new OGUI3D(this, area_title, data)); showArea(ia); }else{ OGUI3D *ia= (OGUI3D*)area; @@ -62,14 +70,18 @@ namespace OpenCVGUI { } } - void OGUICVWindow::plot2D(string area_title, void *data, std::vector labels, float xstep, int plot_type) { + void OGUICVWindow::plot2D(const string& area_title, const Mat* data, const std::vector& labels, float xstep, int plot_type) { + plot2D(area_title, *data, labels, xstep, plot_type); + } + + void OGUICVWindow::plot2D(const string& area_title, const Mat& data, const std::vector& labels, float xstep, int plot_type) { std::lock_guard lock(_areas_mutex); /// Look for area OGUIArea* area=findArea(area_title); /// create or redraw if(area==NULL){ // create new area and ad - OGUIPlotArea *ia= new OGUIPlotArea(this, area_title, data, labels, xstep, plot_type); + OGUIPlotArea *ia= own(new OGUIPlotArea(this, area_title, data, labels, xstep, plot_type)); showArea(ia); }else{ OGUIPlotArea *ia= (OGUIPlotArea*)area; @@ -94,6 +106,12 @@ namespace OpenCVGUI { return area; } + /// Keep ownership of an area created by the window + template T* OGUICVWindow::own(T* area) { + _owned_areas.push_back(std::unique_ptr(area)); + return area; + } + /// Add new area to the stacked layouts, layouts are only modified in the UI thread void OGUICVWindow::showArea(OGUIArea *area) { OGUILayout* l= layout.at(areas_showing.size()%2); diff --git a/src/OpenCVGUI/OGUICheckBox.cpp b/src/OpenCVGUI/OGUICheckBox.cpp index 4a2843c..6162a91 100644 --- a/src/OpenCVGUI/OGUICheckBox.cpp +++ b/src/OpenCVGUI/OGUICheckBox.cpp @@ -19,7 +19,7 @@ void OGUICheckBox::draw(int x, int y, int width) { OGUIWidget::draw(x, y, width); OGUIArea* area= (OGUIArea*)(this->area); - NVGcontext* vg= (NVGcontext*)(area->window->vg); + NVGcontext* vg= area->window->vg; // Draw text nvgFontSize(vg, 18.0f*area->window->font_scale); diff --git a/src/OpenCVGUI/OGUIFile.cpp b/src/OpenCVGUI/OGUIFile.cpp index 96ae6e6..082fbb3 100644 --- a/src/OpenCVGUI/OGUIFile.cpp +++ b/src/OpenCVGUI/OGUIFile.cpp @@ -10,7 +10,7 @@ using namespace cv; namespace OpenCVGUI { - OGUIFile::OGUIFile(void* window,const char* file_name, const char* path, int isdir, const char* ext, double size) { + OGUIFile::OGUIFile(OGUIWindow* window,const char* file_name, const char* path, int isdir, const char* ext, double size) { _file_name= file_name; _path= path; _ext= ext; @@ -18,12 +18,10 @@ namespace OpenCVGUI { _is_dir= isdir; _window= window; _mouse_state=0; - _preview_data= NULL; } - bool OGUIFile::draw(void *vvg, int x, int y, int mouse_x, int mouse_y) { - NVGcontext *vg = (NVGcontext *) vvg; - OGUIWindow *window= (OGUIWindow *)_window; + bool OGUIFile::draw(NVGcontext* vg, int x, int y, int mouse_x, int mouse_y) { + OGUIWindow *window= _window; int width=200; if(_is_dir==2){ width=180; @@ -123,9 +121,11 @@ namespace OpenCVGUI { unsigned char* OGUIFile::getPreview() { // generate data - if(_preview_data==NULL){ + if(_preview.empty()){ Mat img= imread(_path); - Mat imgRGBA, _img; + if(img.empty()) + return NULL; + Mat _img; int image_width = img.cols; int image_height = img.rows; if(image_width < image_height) @@ -138,20 +138,18 @@ namespace OpenCVGUI { switch (img.channels()) { case 1: - cvtColor(_img, imgRGBA, COLOR_GRAY2RGBA); - _preview_data = imgRGBA.data; + cvtColor(_img, _preview, COLOR_GRAY2RGBA); break; case 3: - cvtColor(_img, imgRGBA, COLOR_BGR2RGBA); - _preview_data = imgRGBA.data; + cvtColor(_img, _preview, COLOR_BGR2RGBA); break; case 4: - _preview_data = _img.data; + _preview= _img.clone(); // ROI is not continuous break; } } - return _preview_data; + return _preview.empty() ? NULL : _preview.data; } diff --git a/src/OpenCVGUI/OGUIFileBrowser.cpp b/src/OpenCVGUI/OGUIFileBrowser.cpp index 4a25a39..8bfb925 100644 --- a/src/OpenCVGUI/OGUIFileBrowser.cpp +++ b/src/OpenCVGUI/OGUIFileBrowser.cpp @@ -27,6 +27,7 @@ namespace OpenCVGUI { _window= window; _file_browser_result= NULL; _actual_folder=""; + resolved_path[0]= '\0'; readSystem(); } @@ -36,8 +37,9 @@ namespace OpenCVGUI { // ToDo (damiles): Windows and osx support aFile = setmntent("/proc/mounts", "r"); if (aFile == NULL) { - perror("setmntent"); - exit(1); + // Without mount points the browser still works from the given path + perror("OpenCVGUI: setmntent"); + return; } while (NULL != (ent = getmntent(aFile))) { if(ent->mnt_fsname[0]=='/'){ @@ -47,35 +49,34 @@ namespace OpenCVGUI { filename= mnt_dir.substr(found+1) ; if(filename.compare("")==0) filename="/"; - OGUIFile* file= new OGUIFile(_window, filename.c_str(),ent->mnt_dir, 2, "",0); - _system.push_back(file); + _system.push_back(std::unique_ptr(new OGUIFile(_window, filename.c_str(),ent->mnt_dir, 2, "",0))); } } endmntent(aFile); } void OGUIFileBrowser::readFolder(string path) { - realpath(path.c_str(), resolved_path); _file_list.clear(); + if (realpath(path.c_str(), resolved_path) == NULL) { + cerr << "OpenCVGUI: can not resolve folder " << path << endl; + snprintf(resolved_path, sizeof(resolved_path), "%s", path.c_str()); + return; + } tinydir_dir dir; if (tinydir_open_sorted(&dir, resolved_path) == -1) { - cout << "Error opening file" << endl; + cerr << "OpenCVGUI: can not open folder " << resolved_path << endl; return; } for (int i = 0; i < dir.n_files; i++) { tinydir_file file; if (tinydir_readfile_n(&dir, &file, i) == -1) { - cout << "Error getting file" << endl; - return; + cerr << "OpenCVGUI: can not read file in " << resolved_path << endl; + break; } if(strcmp(file.name,".")==0 || (file.name[0]=='.' && file.name[1]!='.')) continue; - OGUIFile *oguifile= new OGUIFile(_window, file.name, file.path, file.is_dir, file.extension, 0); - _file_list.push_back(oguifile); - - printf("\n"); - + _file_list.push_back(std::unique_ptr(new OGUIFile(_window, file.name, file.path, file.is_dir, file.extension, 0))); } tinydir_close(&dir); @@ -126,7 +127,7 @@ namespace OpenCVGUI { void OGUIFileBrowser::draw() { // ToDo (damiles): Create scroll for more files in window if (_is_file_browser_visible) { - NVGcontext *vg = (NVGcontext *) _window->vg; + NVGcontext *vg = _window->vg; nvgBeginPath(vg); nvgRect(vg, 0, 0, _window->getWindowWidth(), _window->getWindowHeight()); nvgFillColor(vg, nvgRGBA(28, 30, 34, 255)); @@ -168,16 +169,13 @@ namespace OpenCVGUI { int x=10; int y=75; for(int i=0; i<_system.size(); i++){ - OGUIFile *file= _system.at(i); + OGUIFile *file= _system.at(i).get(); if( file->draw(vg, x, y, _window->mouse_x, _window->mouse_y) ){ // is clicked _file_browser_result= file; - if(_file_browser_result!=NULL) { - if (_file_browser_result->_is_dir - && _actual_folder.compare(_file_browser_result->_path) != 0) { - readFolder(_file_browser_result->_path); - _actual_folder= _file_browser_result->_path; - _file_browser_result = NULL; - } + if (file->_is_dir && _actual_folder.compare(file->_path) != 0) { + _file_browser_result = NULL; + _actual_folder= file->_path; + readFolder(_actual_folder); } } y+=22; @@ -191,16 +189,15 @@ namespace OpenCVGUI { y=50; int max_height= _window->getWindowHeight()-80; for(int i=0; i<_file_list.size(); i++){ - OGUIFile *file= _file_list.at(i); + OGUIFile *file= _file_list.at(i).get(); if( file->draw(vg, x, y, _window->mouse_x, _window->mouse_y) ){ // is clicked _file_browser_result= file; - if(_file_browser_result!=NULL) { - if (_file_browser_result->_is_dir - && _actual_folder.compare(_file_browser_result->_path) != 0) { - readFolder(_file_browser_result->_path); - _actual_folder= _file_browser_result->_path; - _file_browser_result = NULL; - } + if (file->_is_dir && _actual_folder.compare(file->_path) != 0) { + // readFolder releases the current list, file is not valid after it + _file_browser_result = NULL; + _actual_folder= file->_path; + readFolder(_actual_folder); + break; } } y+=22; @@ -263,18 +260,21 @@ namespace OpenCVGUI { nvgStrokeColor(vg, nvgRGBA(0,0,0,48)); nvgStroke(vg); - // Image preview - if(_preview_image==-1){ - _preview_image= nvgCreateImageRGBA(vg, 150, 150, 0, _file_browser_result->getPreview()); - }else{ - nvgUpdateImage(vg, _preview_image, _file_browser_result->getPreview()); + // Image preview, NULL if the image can not be read + unsigned char* preview= _file_browser_result->getPreview(); + if(preview!=NULL) { + if(_preview_image==-1){ + _preview_image= nvgCreateImageRGBA(vg, 150, 150, 0, preview); + }else{ + nvgUpdateImage(vg, _preview_image, preview); + } + + NVGpaint imgPaint = nvgImagePattern(vg, 25, y+25, 150, 150, 0, _preview_image, 1); + nvgBeginPath(vg); + nvgRect(vg, 25, y+25, 150,150); + nvgFillPaint(vg, imgPaint); + nvgFill(vg); } - - NVGpaint imgPaint = nvgImagePattern(vg, 25, y+25, 150, 150, 0, _preview_image, 1); - nvgBeginPath(vg); - nvgRect(vg, 25, y+25, 150,150); - nvgFillPaint(vg, imgPaint); - nvgFill(vg); } diff --git a/src/OpenCVGUI/OGUIImageArea.cpp b/src/OpenCVGUI/OGUIImageArea.cpp index 1894101..8e8cfb9 100644 --- a/src/OpenCVGUI/OGUIImageArea.cpp +++ b/src/OpenCVGUI/OGUIImageArea.cpp @@ -36,7 +36,7 @@ namespace OpenCVGUI { this->y=y; this->width= width; this->height= height; - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; // Mouse click callback is called at the end, without the lock bool clicked= false; @@ -302,7 +302,7 @@ namespace OpenCVGUI { void OGUIImageArea::updateImage(){ if(has_to_update){ - NVGcontext *ctx = (NVGcontext*)(window->vg); + NVGcontext *ctx = window->vg; if(image!=-1 && _size_changed){ nvgDeleteImage(ctx, image); image= -1; @@ -319,11 +319,21 @@ namespace OpenCVGUI { } } - void OGUIImageArea::setImage(Mat *img) { + void OGUIImageArea::setImage(const Mat* img) { + setImage(*img); + } + + void OGUIImageArea::setImage(const Mat& img) { + + // Textures are 8 bit RGBA, OpenCV images are gray, BGR or BGRA + if (img.depth() != CV_8U || img.channels() == 2 || img.channels() > 4) { + cerr << "OpenCVGUI: imshow needs an 8 bit gray, BGR or BGRA image" << endl; + return; + } // Copy and convert img to RGBA outside the lock Mat new_img, new_rgba; - img->copyTo(new_img); + img.copyTo(new_img); switch (new_img.channels()) { case 1: @@ -333,7 +343,7 @@ namespace OpenCVGUI { cvtColor(new_img, new_rgba, COLOR_BGR2RGBA); break; case 4: - new_rgba= new_img; + cvtColor(new_img, new_rgba, COLOR_BGRA2RGBA); break; } @@ -343,11 +353,11 @@ namespace OpenCVGUI { data= imgRGBA.data; // Reinit image if don't have same size - if(img->cols!= image_width || img->rows!= image_height) + if(img.cols!= image_width || img.rows!= image_height) _size_changed= true; - image_width = img->cols; - image_height = img->rows; + image_width = img.cols; + image_height = img.rows; has_to_update= true; } diff --git a/src/OpenCVGUI/OGUILayout.cpp b/src/OpenCVGUI/OGUILayout.cpp index 60b34ad..805b1e9 100644 --- a/src/OpenCVGUI/OGUILayout.cpp +++ b/src/OpenCVGUI/OGUILayout.cpp @@ -57,7 +57,7 @@ void OGUILayout::draw(int x, int y, int width, int height) if(areas.size()==0) return; - //NVGcontext* vg= (window->vg); + //NVGcontext* vg= window->vg; // Draw the areas float x0=0; diff --git a/src/OpenCVGUI/OGUIPlotArea.cpp b/src/OpenCVGUI/OGUIPlotArea.cpp index ec0abcc..a0e6153 100644 --- a/src/OpenCVGUI/OGUIPlotArea.cpp +++ b/src/OpenCVGUI/OGUIPlotArea.cpp @@ -14,7 +14,7 @@ namespace OpenCVGUI { this->y=y; this->width= width; this->height= height; - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; nvgScissor(vg, x, y, width, height); OGUIArea::draw(x,y,width,height); @@ -29,7 +29,7 @@ namespace OpenCVGUI { nvgResetScissor(vg); } - OGUIPlotArea::OGUIPlotArea(OGUIWindow* window, std::string title, void* d, std::vector labels, float xstep, int plot_type): OGUIArea(window) + OGUIPlotArea::OGUIPlotArea(OGUIWindow* window, const std::string& title, const Mat& d, const std::vector& labels, float xstep, int plot_type): OGUIArea(window) { _plot_type= plot_type; color_scheme={ @@ -45,17 +45,17 @@ namespace OpenCVGUI { 99,176,99 }; this->title= title; - ((Mat*)d)->copyTo(data); + d.copyTo(data); //data= data.reshape(0,1); _labels= labels; _x_step= xstep; _auto_scale= true; } - void OGUIPlotArea::replot(void *d, std::vector labels, float xstep) { + void OGUIPlotArea::replot(const Mat& d, const std::vector& labels, float xstep) { // Copy outside the lock, the lock only swaps the data Mat new_data; - ((Mat*)d)->copyTo(new_data); + d.copyTo(new_data); //data= data.reshape(0,1); std::lock_guard lock(_mutex); data= new_data; @@ -73,7 +73,7 @@ namespace OpenCVGUI { } void OGUIPlotArea::drawLegends(){ - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; ///Plot labels box nvgBeginPath(vg); nvgRect(vg, x + width - 100-20, y + 40, 120, 15 + data.rows*20); @@ -116,7 +116,7 @@ namespace OpenCVGUI { float dy= (height-margin); - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; // Plot each graph for(int p=0; pvg); + NVGcontext* vg= window->vg; // Plot each graph for(int p=0; pvg); + NVGcontext* vg= window->vg; // Plot each graph for(int p=0; pvg); + NVGcontext* vg= window->vg; // Plot each graph for(int p=0; parea); - NVGcontext* vg= (NVGcontext*)(area->window->vg); + NVGcontext* vg= area->window->vg; NVGpaint bg; diff --git a/src/OpenCVGUI/OGUISlider.cpp b/src/OpenCVGUI/OGUISlider.cpp index 9242267..e37a516 100644 --- a/src/OpenCVGUI/OGUISlider.cpp +++ b/src/OpenCVGUI/OGUISlider.cpp @@ -22,7 +22,7 @@ void OGUISlider::draw(int x, int y, int w) { OGUIWidget::draw(x, y, w); OGUIArea* area= (OGUIArea*)(this->area); - NVGcontext* vg= (NVGcontext*)(area->window->vg); + NVGcontext* vg= area->window->vg; NVGpaint bg, knob; diff --git a/src/OpenCVGUI/OGUITextInput.cpp b/src/OpenCVGUI/OGUITextInput.cpp index 838b027..116cded 100644 --- a/src/OpenCVGUI/OGUITextInput.cpp +++ b/src/OpenCVGUI/OGUITextInput.cpp @@ -19,7 +19,7 @@ void OGUITextInput::draw(int x, int y, int w) int h = this->height; OGUIWidget::draw(x, y, w); OGUIArea* area= (OGUIArea*)(this->area); - NVGcontext* vg= (NVGcontext*)(area->window->vg); + NVGcontext* vg= area->window->vg; NVGpaint bg; // Edit diff --git a/src/OpenCVGUI/OGUIUtils.cpp b/src/OpenCVGUI/OGUIUtils.cpp index 292fc67..38c9767 100644 --- a/src/OpenCVGUI/OGUIUtils.cpp +++ b/src/OpenCVGUI/OGUIUtils.cpp @@ -21,9 +21,8 @@ static float maxf(float a, float b) { return a > b ? a : b; } //static float absf(float a) { return a >= 0.0f ? a : -a; } static float clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } -void drawParagraph(void* vvg, const char* text, float x, float y, float width, float height, float mx, float my) +void drawParagraph(NVGcontext* vg, const char* text, float x, float y, float width, float height, float mx, float my) { - NVGcontext* vg= (NVGcontext*)vvg; NVGtextRow rows[3]; NVGglyphPosition glyphs[100]; const char* start; @@ -141,9 +140,8 @@ void drawParagraph(void* vvg, const char* text, float x, float y, float width, f -bool drawBasicButton(void *context, OGUIWindow* window, const char* title, int x, int y, int width, int height, int mouse_x, int mouse_y, const char* typography, double font_size ) +bool drawBasicButton(NVGcontext* tmp_vg, OGUIWindow* window, const char* title, int x, int y, int width, int height, int mouse_x, int mouse_y, const char* typography, double font_size ) { - NVGcontext* tmp_vg=(NVGcontext*) context; bool internal_state= false; nvgBeginPath(tmp_vg); nvgRoundedRect(tmp_vg, x,y, width,height, 3); @@ -183,10 +181,9 @@ bool drawBasicButton(void *context, OGUIWindow* window, const char* title, int x return internal_state; } -void drawHeader(void* vvg, string title, int x, int y, int w){ +void drawHeader(NVGcontext* vg, string title, int x, int y, int w){ NVGpaint headerPaint; float cornerRadius = 3.0f; - NVGcontext* vg=(NVGcontext*) vvg; // Header headerPaint = nvgLinearGradient(vg, x,y,x,y+15, nvgRGBA(255,255,255,8), nvgRGBA(0,0,0,16)); nvgBeginPath(vg); @@ -213,9 +210,8 @@ void drawHeader(void* vvg, string title, int x, int y, int w){ } -void drawLabel(void *context, const char* text, int x, int y, const char* typography, double font_size, int r, int g, int b, int a ) +void drawLabel(NVGcontext* tmp_vg, const char* text, int x, int y, const char* typography, double font_size, int r, int g, int b, int a ) { - NVGcontext* tmp_vg=(NVGcontext*) context; // Draw text nvgFontSize(tmp_vg, font_size); nvgFontFace(tmp_vg, typography); diff --git a/src/OpenCVGUI/OGUIVideoTimeline.cpp b/src/OpenCVGUI/OGUIVideoTimeline.cpp index 06d72aa..9c9aed9 100644 --- a/src/OpenCVGUI/OGUIVideoTimeline.cpp +++ b/src/OpenCVGUI/OGUIVideoTimeline.cpp @@ -41,7 +41,7 @@ namespace OpenCVGUI { this->y=y; this->width= width; this->height= height; - NVGcontext* vg= (NVGcontext*)(window->vg); + NVGcontext* vg= window->vg; nvgScissor(vg, x, y, width, height); OGUIArea::draw(x,y,width,height); @@ -167,9 +167,8 @@ namespace OpenCVGUI { nvg_thumbnail_id=-1; } - void Track::draw(void* vvg, int x, int y, int width, int height, int mouse_x, int mouse_y) + void Track::draw(NVGcontext* vg, int x, int y, int width, int height, int mouse_x, int mouse_y) { - NVGcontext* vg= (NVGcontext*)(vvg); const int offset_time=150; nvgBeginPath(vg); nvgRect(vg, x + offset_time, y, width-offset_time, 38); @@ -216,9 +215,8 @@ namespace OpenCVGUI { markers.push_back(TimeMarker(title, start, end, color)); } - void TimeMarker::draw(void* vvg, int x, int y, int mouse_x, int mouse_y) + void TimeMarker::draw(NVGcontext* vg, int x, int y, int mouse_x, int mouse_y) { - NVGcontext* vg= (NVGcontext*)(vvg); nvgBeginPath(vg); int w= (end-start)/100; int s = x + start/100; diff --git a/src/OpenCVGUI/OGUIWindow.cpp b/src/OpenCVGUI/OGUIWindow.cpp index 0075d0a..a4fcbae 100644 --- a/src/OpenCVGUI/OGUIWindow.cpp +++ b/src/OpenCVGUI/OGUIWindow.cpp @@ -66,25 +66,25 @@ OGUIWindow::OGUIWindow(int width, int height, init(fullScreen); - this->mainLayout= new OGUILayout(this, layoutOrientation); + this->mainLayout.reset(new OGUILayout(this, layoutOrientation)); this->mainLayout->title="Main Layout"; this->actual_cursor_type=0; this->key_focus_widget_= NULL; this->key_pressed= 0; this->_show_graph= false; - this->_fileBrowser= new OGUIFileBrowser(this); + this->_fileBrowser.reset(new OGUIFileBrowser(this)); this->_maximizedArea= NULL; } OGUIWindow::~OGUIWindow() { #ifdef OGUI_GL3 - nvgDeleteGL3((NVGcontext*)vg); + nvgDeleteGL3(vg); #else - nvgDeleteGL2((NVGcontext*)vg); + nvgDeleteGL2(vg); #endif - glfwDestroyWindow((GLFWwindow*)glfw_window); + glfwDestroyWindow(glfw_window); glfwTerminate(); } @@ -106,8 +106,8 @@ int OGUIWindow::init(bool fullScreen) initGraph(&fps, GRAPH_RENDER_FPS, "Frame Time"); - glfwSetWindowUserPointer((GLFWwindow*)glfw_window, this); - glfwMakeContextCurrent((GLFWwindow*)glfw_window); + glfwSetWindowUserPointer(glfw_window, this); + glfwMakeContextCurrent(glfw_window); glfwSwapInterval(1); // Enable vsync to avoid drawing more frames than the screen shows // Init GLew @@ -134,9 +134,10 @@ int OGUIWindow::init(bool fullScreen) return 0; } - nvgCreateFontMem((NVGcontext*)vg, "sans", font_roboto, font_roboto_size, 1); - nvgCreateFontMem((NVGcontext*)vg, "sans-bold", font_valera, font_valera_size, 1); - nvgCreateFontMem((NVGcontext*)vg, "icons", font_awesome, font_awesome_size, 1); + // Fonts are static embedded data, nanovg must not free them + nvgCreateFontMem(vg, "sans", font_roboto, font_roboto_size, 0); + nvgCreateFontMem(vg, "sans-bold", font_valera, font_valera_size, 0); + nvgCreateFontMem(vg, "icons", font_awesome, font_awesome_size, 0); // Load all cursors mouse_cursors_.push_back(glfwCreateStandardCursor(GLFW_ARROW_CURSOR)); @@ -146,11 +147,11 @@ int OGUIWindow::init(bool fullScreen) mouse_cursors_.push_back(glfwCreateStandardCursor(GLFW_IBEAM_CURSOR)); mouse_cursors_.push_back(glfwCreateStandardCursor(GLFW_CROSSHAIR_CURSOR)); - glfwSetInputMode((GLFWwindow*)glfw_window, GLFW_STICKY_MOUSE_BUTTONS, 1); + glfwSetInputMode(glfw_window, GLFW_STICKY_MOUSE_BUTTONS, 1); - glfwSetScrollCallback((GLFWwindow*)glfw_window, (void (*)(GLFWwindow*, double, double))OGUIWindow::scroll_callback); - glfwSetCharCallback((GLFWwindow*)glfw_window, (void (*)(GLFWwindow*, unsigned int))OGUIWindow::charCallback); - glfwSetKeyCallback((GLFWwindow*)glfw_window, (void (*)(GLFWwindow*, int, int, int, int))OGUIWindow::keyCallback); + glfwSetScrollCallback(glfw_window, OGUIWindow::scroll_callback); + glfwSetCharCallback(glfw_window, OGUIWindow::charCallback); + glfwSetKeyCallback(glfw_window, OGUIWindow::keyCallback); glfwSetTime(0); prevt = glfwGetTime(); @@ -158,23 +159,23 @@ int OGUIWindow::init(bool fullScreen) return 1; } -void OGUIWindow::scroll_callback(void* window, double xoffset, double yoffset){ - OGUIWindow* oguiwindow= (OGUIWindow*)glfwGetWindowUserPointer((GLFWwindow*)window); +void OGUIWindow::scroll_callback(GLFWwindow* window, double xoffset, double yoffset){ + OGUIWindow* oguiwindow= (OGUIWindow*)glfwGetWindowUserPointer(window); oguiwindow->mainLayout->updateScrollStatus(xoffset, yoffset); } -void OGUIWindow::charCallback(void* window, unsigned int key) +void OGUIWindow::charCallback(GLFWwindow* window, unsigned int key) { - OGUIWindow* oguiwindow= (OGUIWindow*)glfwGetWindowUserPointer((GLFWwindow*)window); + OGUIWindow* oguiwindow= (OGUIWindow*)glfwGetWindowUserPointer(window); OGUIWidget* widget= oguiwindow->getKeyFocusWidget(); if(widget!=NULL){ widget->characterCallback(key); } } -void OGUIWindow::keyCallback(void* window, int key, int scancode, int action, int mods) +void OGUIWindow::keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { - OGUIWindow* oguiwindow= (OGUIWindow*)glfwGetWindowUserPointer((GLFWwindow*)window); + OGUIWindow* oguiwindow= (OGUIWindow*)glfwGetWindowUserPointer(window); OGUIWidget* widget= oguiwindow->getKeyFocusWidget(); if(widget!=NULL){ widget->keyCallback(key, scancode, action, mods); @@ -208,14 +209,14 @@ void OGUIWindow::showPerfGraph(bool show) } bool OGUIWindow::update(){ - glfwMakeContextCurrent((GLFWwindow *)glfw_window); - if(!glfwWindowShouldClose((GLFWwindow *)glfw_window)) { + glfwMakeContextCurrent(glfw_window); + if(!glfwWindowShouldClose(glfw_window)) { runUITasks(); - glfwGetCursorPos((GLFWwindow *) glfw_window, &mouse_x, &mouse_y); - mouse_left_state = glfwGetMouseButton((GLFWwindow *) glfw_window, GLFW_MOUSE_BUTTON_LEFT); - mouse_state = glfwGetMouseButton((GLFWwindow *) glfw_window, GLFW_MOUSE_BUTTON_LEFT); + glfwGetCursorPos(glfw_window, &mouse_x, &mouse_y); + mouse_left_state = glfwGetMouseButton(glfw_window, GLFW_MOUSE_BUTTON_LEFT); + mouse_state = glfwGetMouseButton(glfw_window, GLFW_MOUSE_BUTTON_LEFT); actual_cursor_type = 0; draw(); @@ -243,18 +244,18 @@ void OGUIWindow::draw() float ratio; // Get size and clean buffer - glfwGetFramebufferSize((GLFWwindow*)glfw_window, &width, &height); + glfwGetFramebufferSize(glfw_window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); glClearColor(0.3f, 0.3f, 0.3f, 0.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); - nvgBeginFrame((NVGcontext*)vg, width, height, ratio); + nvgBeginFrame(vg, width, height, ratio); if(_maximizedArea!=NULL){ // Draw title - NVGcontext* tvg= (NVGcontext*)(vg); + NVGcontext* tvg= vg; nvgBeginPath(tvg); nvgRect(tvg, 0, 0, width, 22); nvgFillColor(tvg, nvgRGBA(0, 0, 0, 100)); @@ -290,7 +291,7 @@ void OGUIWindow::draw() std::unique_lock state_lock(_state_mutex); if (_show_progress){ - NVGcontext* tvg= (NVGcontext*)(vg); + NVGcontext* tvg= vg; nvgResetScissor(tvg); nvgBeginPath(tvg); @@ -306,7 +307,7 @@ void OGUIWindow::draw() } state_lock.unlock(); - nvgEndFrame((NVGcontext*)vg); + nvgEndFrame(vg); if(_maximizedArea!=NULL){ // 3D draw @@ -319,7 +320,7 @@ void OGUIWindow::draw() // Swap buffers - glfwSwapBuffers((GLFWwindow*)glfw_window); + glfwSwapBuffers(glfw_window); } void OGUIWindow::show_progress(string title, float percentage) { @@ -349,7 +350,7 @@ void OGUIWindow::hide_progress(){ _show_progress=false; } -void OGUIWindow::setExternal2DDraw(std::function func) { +void OGUIWindow::setExternal2DDraw(std::function func) { _external2dDraw= func; } @@ -361,11 +362,11 @@ void OGUIWindow::setCursor(int cursor_type) void OGUIWindow::drawCursor() { - glfwSetCursor((GLFWwindow*)glfw_window, (GLFWcursor*)mouse_cursors_.at(actual_cursor_type)); + glfwSetCursor(glfw_window, mouse_cursors_.at(actual_cursor_type)); } OGUILayout* OGUIWindow::getMainLayout(){ - return mainLayout; + return mainLayout.get(); } OGUIWidget* OGUIWindow::getKeyFocusWidget() @@ -388,7 +389,7 @@ int OGUIWindow::getWindowWidth() { void OGUIWindow::close(){ // ToDo improve returns an Error GLXBadDrawable - glfwDestroyWindow((GLFWwindow*)glfw_window); + glfwDestroyWindow(glfw_window); } bool OGUIWindow::isUIThread() { @@ -416,7 +417,7 @@ int OGUIWindow::popup(string title, string text, int type) { bool OGUIWindow::drawPopup(){ std::unique_lock lock(_state_mutex); if(_popup_type != NO_POPUP) { - NVGcontext *tmp_vg = (NVGcontext *) vg; + NVGcontext *tmp_vg = vg; nvgBeginPath(tmp_vg); nvgRect(tmp_vg, 0, 0, width, height); nvgFillColor(tmp_vg, nvgRGBA(28,30,34, 220)); diff --git a/src/OpenCVGUI/perf.c b/src/OpenCVGUI/perf.c index 476a431..0302311 100644 --- a/src/OpenCVGUI/perf.c +++ b/src/OpenCVGUI/perf.c @@ -96,7 +96,7 @@ float getGraphAverage(PerfGraph* fps) return avg / (float)GRAPH_HISTORY_COUNT; } -void renderGraph(void* vg, float x, float y, PerfGraph* fps) +void renderGraph(struct NVGcontext* vg, float x, float y, PerfGraph* fps) { int i; float avg, w, h; diff --git a/src/basic_sample.cpp b/src/basic_sample.cpp index 1158fd3..4913d53 100644 --- a/src/basic_sample.cpp +++ b/src/basic_sample.cpp @@ -19,11 +19,11 @@ int first_info=0; void cv_process() { while(app_is_running) { cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); Mat output; cvtColor( frame, gray, COLOR_RGB2GRAY ); threshold( gray, output, (int)thr, 255, THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); if(first_info==0) { string file_string= window->openFileBrowser(".", {"*"}); stringstream ss; @@ -65,7 +65,7 @@ int main( int argc, const char* argv[] ) if(cap.isOpened()){ cap >> frame; // show image - window->imshow("camera", &frame); + window->imshow("camera", frame); }else{ cerr << "Can not open video source: " << source << endl; cerr << "Usage: " << argv[0] << " [camera index | video file | /dev/videoN]" << endl; @@ -76,7 +76,7 @@ int main( int argc, const char* argv[] ) cvtColor( frame, gray, COLOR_RGB2GRAY ); Mat output; threshold( gray, output, 125, 255, THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); // Start the Comptuer vision process OpenCVGUI::app_run(cv_process); diff --git a/src/example.cpp b/src/example.cpp index 86d813b..e1c92e7 100644 --- a/src/example.cpp +++ b/src/example.cpp @@ -31,7 +31,7 @@ Mat frame; void on_change_slider_threshold(double value){ threshold( gray, output, (int)value, 255, THRESH_BINARY); - imageArea2->setImage(&output); + imageArea2->setImage(output); } void hello_btn_click(){ @@ -41,7 +41,7 @@ void hello_btn_click(){ void cv_process() { while(app_is_running) { cap >> frame; - imageArea3->setImage(&frame); + imageArea3->setImage(frame); } } @@ -83,10 +83,10 @@ int main( int argc, const char* argv[] ) layout1.addArea(imageArea2); layout2.addArea(imageArea3); - imageArea1->setImage(&src); + imageArea1->setImage(src); cvtColor( src, gray, COLOR_RGB2GRAY ); threshold( gray, output, 125, 255, THRESH_BINARY); - imageArea2->setImage(&output); + imageArea2->setImage(output); // Start video capture: camera index or video file/device path, 0 by default string source= argc > 1 ? argv[1] : "0"; @@ -96,7 +96,7 @@ int main( int argc, const char* argv[] ) cap.open(source); if(cap.isOpened()){ cap >> frame; - imageArea3->setImage(&frame); + imageArea3->setImage(frame); }else{ cerr << "Can not open video source: " << source << endl; cerr << "Usage: " << argv[0] << " [camera index | video file | /dev/videoN]" << endl; diff --git a/src/example1.cpp b/src/example1.cpp index dec7fa3..b4dbc29 100644 --- a/src/example1.cpp +++ b/src/example1.cpp @@ -29,7 +29,7 @@ Mat frame; bool sayHello=false; void on_change_slider_threshold(double value){ threshold( gray, output, (int)value, 255, THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); } void hello_btn_click(){ @@ -41,13 +41,13 @@ void cv_process() { while(app_is_running) { cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); Mat g_data, data; cvtColor(frame, g_data, COLOR_BGR2GRAY); g_data.convertTo(data, CV_32F, 1/255.0); resize(data, data, Size(50,10)); - window->plot2D("2D plot Series", &data, {"g1","g2","g3","g4","g5","g6","g7","g8","g9", "g10"}, 1, OpenCVGUI::PLOT_SERIES); + window->plot2D("2D plot Series", data, {"g1","g2","g3","g4","g5","g6","g7","g8","g9", "g10"}, 1, OpenCVGUI::PLOT_SERIES); if(sayHello) { window->popup("Hello World", "Hello to OpenCV GUI Sample", POPUP_ALERT); @@ -60,7 +60,7 @@ void input_mouse_click(int mouse_x, int mouse_y) { cout << mouse_x << ", " << mouse_y << endl; circle(src, Point(mouse_x, mouse_y), 3, Scalar(0,255,0)); - window->imshow("input", &src); + window->imshow("input", src); } int main( int argc, const char* argv[] ) @@ -80,24 +80,24 @@ int main( int argc, const char* argv[] ) button1.setCallBack(hello_btn_click); window->addFormWidget(&button1); - window->imshow("input", &src); + window->imshow("input", src); window->setImShowMouseClickCallBack("input", input_mouse_click); cvtColor( src, gray, COLOR_RGB2GRAY ); threshold( gray, output, 125, 255, THRESH_BINARY); - window->imshow("threshold", &output); + window->imshow("threshold", output); Mat data; Mat indata= imread("../resources/3d.png", IMREAD_GRAYSCALE); - // window->imshow("3dindata", &indata); + // window->imshow("3dindata", indata); // indata.convertTo(data, CV_32F, 1/255.0); gray.convertTo(data, CV_32F, 1/255.0); resize(data, data, Size(100,100)); - window->plot3D("3D plot", &data); + window->plot3D("3D plot", data); resize(data, data, Size(10,10)); //data= data.reshape(0,1); - window->plot2D("2D plot", &data, {"g1","g2","g3","g4","g5","g6","g7","g8","g9", "g10"}); + window->plot2D("2D plot", data, {"g1","g2","g3","g4","g5","g6","g7","g8","g9", "g10"}); // Start video capture: camera index or video file/device path, 0 by default string source= argc > 1 ? argv[1] : "0"; @@ -107,7 +107,7 @@ int main( int argc, const char* argv[] ) cap.open(source); if(cap.isOpened()){ cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); }else{ cerr << "Can not open video source: " << source << endl; cerr << "Usage: " << argv[0] << " [camera index | video file | /dev/videoN]" << endl; diff --git a/src/example3d.cpp b/src/example3d.cpp index ba0839e..84a3594 100644 --- a/src/example3d.cpp +++ b/src/example3d.cpp @@ -115,19 +115,19 @@ int main( int argc, const char* argv[] ) return 1; } blur(indata, indata, Size(3,3)); - window->imshow("3D input data", &indata); + window->imshow("3D input data", indata); // 3D plot of the image with custom axes on top Mat data; indata.convertTo(data, CV_32F, 1/255.0); resize(data, data, Size(100,100)); - window->plot3D("3D plot", &data); + window->plot3D("3D plot", data); OGUI3D* plot3d= (OGUI3D*)window->findAreaByTitle("3D plot"); plot3d->setExternalDraw3D(custom_3d); // 3D area without data, only custom drawing Mat empty_data; - window->plot3D("Custom 3D", &empty_data); + window->plot3D("Custom 3D", empty_data); OGUI3D* custom3d= (OGUI3D*)window->findAreaByTitle("Custom 3D"); custom3d->setExternalDraw3D(custom_3d); diff --git a/src/example_2dplot.cpp b/src/example_2dplot.cpp index c3e6a84..d75c21b 100644 --- a/src/example_2dplot.cpp +++ b/src/example_2dplot.cpp @@ -88,21 +88,21 @@ void cv_process() { while(app_is_running) { cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); Mat g_data, data; cvtColor(frame, g_data, COLOR_BGR2GRAY); g_data.convertTo(data, CV_32F, 1/255.0); resize(data, data, Size(50,10)); - window->plot2D("2D plot Series", &data, {"g1","g2","g3","g4","g5","g6","g7","g8","g9", "g10"}, 1, OpenCVGUI::PLOT_SERIES); + window->plot2D("2D plot Series", data, {"g1","g2","g3","g4","g5","g6","g7","g8","g9", "g10"}, 1, OpenCVGUI::PLOT_SERIES); // 20 data 4 series (each channel is x and y) - window->plot2D("2D plot Scatter", &scatter_data, {"g1","g2","g3","g4"}, 1, OpenCVGUI::PLOT_SCATTER); + window->plot2D("2D plot Scatter", scatter_data, {"g1","g2","g3","g4"}, 1, OpenCVGUI::PLOT_SCATTER); - window->plot2D("2D plot Lines", &lines_data, {"star","circle"}, 1, OpenCVGUI::PLOT_LINE); + window->plot2D("2D plot Lines", lines_data, {"star","circle"}, 1, OpenCVGUI::PLOT_LINE); resize(data, data, Size(20,3)); - window->plot2D("2D plot Bars", &data, {"g1","g2","g3"}, 1, OpenCVGUI::PLOT_BARS); + window->plot2D("2D plot Bars", data, {"g1","g2","g3"}, 1, OpenCVGUI::PLOT_BARS); if(sayHello) { window->popup("2D Plot Demo", "In this sample you can check different 2d plot types", POPUP_ALERT); @@ -115,7 +115,7 @@ void input_mouse_click(int mouse_x, int mouse_y) { cout << mouse_x << ", " << mouse_y << endl; circle(src, Point(mouse_x, mouse_y), 3, Scalar(0,255,0)); - window->imshow("input", &src); + window->imshow("input", src); } int main( int argc, const char* argv[] ) @@ -137,7 +137,7 @@ int main( int argc, const char* argv[] ) cap.open(source); if(cap.isOpened()){ cap >> frame; - window->imshow("camera", &frame); + window->imshow("camera", frame); }else{ cerr << "Can not open video source: " << source << endl; cerr << "Usage: " << argv[0] << " [camera index | video file | /dev/videoN]" << endl; diff --git a/src/example_videotimeline.cpp b/src/example_videotimeline.cpp index 2263f47..9a1a5cf 100644 --- a/src/example_videotimeline.cpp +++ b/src/example_videotimeline.cpp @@ -55,9 +55,9 @@ void cv_process() { cap[i]->read(frame); if(frame.empty()) { - imageAreas[i]->setImage(&black); + imageAreas[i]->setImage(black); }else{ - imageAreas[i]->setImage(&frame); + imageAreas[i]->setImage(frame); } } @@ -74,9 +74,9 @@ void cv_process() { cap[i]->read(frame); if(frame.empty()) { - imageAreas[i]->setImage(&black); + imageAreas[i]->setImage(black); }else{ - imageAreas[i]->setImage(&frame); + imageAreas[i]->setImage(frame); } } } @@ -138,7 +138,7 @@ int main( int argc, const char* argv[] ) timeline->addTrack(track); c->read(src); - imageAreas[i]->setImage(&src); + imageAreas[i]->setImage(src); } // Track* track = new Track("Track test", cap); @@ -149,9 +149,9 @@ int main( int argc, const char* argv[] ) *cap[0] >> src; black = Mat::zeros(src.rows, src.cols, CV_8UC3 ); - // imageArea1->setImage(&src); + // imageArea1->setImage(src); // cvtColor( src, gray, COLOR_RGB2GRAY ); - // imageArea2->setImage(&gray); + // imageArea2->setImage(gray); OpenCVGUI::windows.push_back(window); OpenCVGUI::app_run(cv_process); diff --git a/tests/consumer/CMakeLists.txt b/tests/consumer/CMakeLists.txt new file mode 100644 index 0000000..aad260c --- /dev/null +++ b/tests/consumer/CMakeLists.txt @@ -0,0 +1,8 @@ +# Application using the installed library, checks the exported CMake package +cmake_minimum_required(VERSION 3.16) +project(consumer CXX) + +find_package(OpenCVGUI 2.0 REQUIRED) + +add_executable(consumer main.cpp) +target_link_libraries(consumer PRIVATE OpenCVGUI::OpenCVGUI) diff --git a/tests/consumer/main.cpp b/tests/consumer/main.cpp new file mode 100644 index 0000000..d6bb027 --- /dev/null +++ b/tests/consumer/main.cpp @@ -0,0 +1,11 @@ +#include "OGUI.h" + +int main() { + if (!OpenCVGUI::init()) + return 1; + OpenCVGUI::OGUICVWindow* window = OpenCVGUI::namedWindow("consumer", 320, 240); + window->imshow("image", cv::Mat(120, 160, CV_8UC3, cv::Scalar(0, 0, 255))); + for (int i = 0; i < 3; i++) + window->update(); + return 0; +} diff --git a/tests/test_dialogs.cpp b/tests/test_dialogs.cpp new file mode 100644 index 0000000..fcac0d7 --- /dev/null +++ b/tests/test_dialogs.cpp @@ -0,0 +1,50 @@ +// Blocking dialogs: they must return right away in the UI thread and +// release the process thread when the window is closed. +#include "OGUI.h" +#include +#include +#include +#include +#include + +using namespace OpenCVGUI; + +static int failures = 0; + +static void check(bool condition, const std::string& message) { + std::cout << (condition ? "[ OK ] " : "[FAIL] ") << message << std::endl; + if (!condition) + failures++; +} + +int main() { + if (!OpenCVGUI::init()) { + std::cerr << "Can not initialize GLFW" << std::endl; + return 1; + } + OGUICVWindow* window = OpenCVGUI::namedWindow("test dialogs", 640, 480); + + // Waiting here would block the UI forever + check(window->popup("title", "text", POPUP_ALERT) == 0, "popup from the UI thread returns"); + check(window->openFileBrowser(".", {"*"}).empty(), "file browser from the UI thread returns"); + + std::atomic popup_result(-1); + std::atomic browser_returned(false); + std::string browser_result = "not set"; + + std::thread closer([window]() { + std::this_thread::sleep_for(std::chrono::seconds(1)); + glfwSetWindowShouldClose(window->glfw_window, 1); + }); + + OpenCVGUI::app_run([&]() { + popup_result = window->popup("title", "waiting popup", POPUP_CONFIRM); + browser_result = window->openFileBrowser(".", {"*"}); + browser_returned = true; + }); + closer.join(); + + check(popup_result == 0, "popup returns 0 when the window is closed"); + check(browser_returned && browser_result.empty(), "file browser returns an empty path when the window is closed"); + return failures == 0 ? 0 : 1; +} diff --git a/tests/test_render.cpp b/tests/test_render.cpp new file mode 100644 index 0000000..c8b10f6 --- /dev/null +++ b/tests/test_render.cpp @@ -0,0 +1,126 @@ +// Render images, plots and widgets from the process thread and check the +// framebuffer: the red image must be on screen and the 3D surface drawn. +#include "OGUI.h" +#include "OGUI3D.h" +#include "OGUIButton.h" +#include "OGUICheckBox.h" +#include "OGUISlider.h" +#include +#include +#include +#include +#include + +using namespace OpenCVGUI; + +static int failures = 0; + +static void check(bool condition, const std::string& message) { + std::cout << (condition ? "[ OK ] " : "[FAIL] ") << message << std::endl; + if (!condition) + failures++; +} + +int main() { + if (!OpenCVGUI::init()) { + std::cerr << "Can not initialize GLFW" << std::endl; + return 1; + } + OGUICVWindow* window = OpenCVGUI::namedWindow("test render", 800, 600); + + OGUISlider slider("Slider", 0, 255, 125); + OGUICheckBox checkbox("CheckBox", true); + OGUIButton button("Button"); + window->addFormWidget(&slider); + window->addFormWidget(&checkbox); + window->addFormWidget(&button); + + std::atomic ui_tasks(0); + std::atomic red_pixels(-1); + std::atomic blue_pixels(-1); + std::atomic surface_pixels(-1); + std::atomic pixels_read(false); + + OpenCVGUI::app_run([&]() { + // BGR red, a gray image, a BGRA blue image and every plot type + cv::Mat red(240, 320, CV_8UC3, cv::Scalar(0, 0, 255)); + cv::Mat gray(240, 320, CV_8UC1); + cv::randu(gray, 0, 255); + cv::Mat bgra(120, 160, CV_8UC4, cv::Scalar(255, 0, 0, 255)); + + cv::Mat series(2, 50, CV_32F); + cv::randu(series, 0.f, 1.f); + cv::Mat points(1, 50, CV_32FC2); + cv::randu(points, 0.f, 1.f); + cv::Mat surface(40, 40, CV_32F); + for (int r = 0; r < surface.rows; r++) + for (int c = 0; c < surface.cols; c++) + surface.at(r, c) = std::sin(r * 0.2f) * std::cos(c * 0.2f); + + for (int frame = 0; frame < 30 && app_is_running; frame++) { + window->imshow("red", red); + window->imshow("gray", gray); + window->imshow("bgra", bgra); + window->plot2D("series", series, {"a", "b"}); + window->plot2D("bars", series, {"a", "b"}, 1, PLOT_BARS); + window->plot2D("line", points, {"xy"}, 1, PLOT_LINE); + window->plot2D("scatter", points, {"xy"}, 1, PLOT_SCATTER); + window->plot3D("surface", surface); + window->show_progress("progress", frame / 30.f); + window->runOnUIThread([&]() { ui_tasks++; }); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + window->hide_progress(); + + // Read the framebuffer after the 2D pass and the 3D surface are drawn + window->runOnUIThread([&]() { + OGUI3D* area = dynamic_cast(window->findAreaByTitle("surface")); + if (area == NULL) + return; + area->setExternalDraw3D([&](int, int, int, int, const glm::mat4&) { + if (pixels_read) + return; + int w = window->getWindowWidth(), h = window->getWindowHeight(); + cv::Mat pixels(h, w, CV_8UC4); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data); + cv::flip(pixels, pixels, 0); + + // Pixels of an RGB color inside the area, areas use window coordinates + auto count_color = [&](const std::string& title, cv::Scalar rgb) { + OGUIArea* image_area = window->findAreaByTitle(title); + cv::Rect rect = cv::Rect(image_area->x, image_area->y, image_area->width, image_area->height) + & cv::Rect(0, 0, w, h); + cv::Mat mask; + cv::inRange(pixels(rect), rgb - cv::Scalar(40, 40, 40, 255), rgb + cv::Scalar(40, 40, 40, 255), mask); + return cv::countNonZero(mask); + }; + blue_pixels = count_color("bgra", cv::Scalar(0, 0, 255, 255)); + red_pixels = count_color("red", cv::Scalar(255, 0, 0, 255)); + + // Only the 3D pass writes depth, NanoVG does not + GLint viewport[4]; + glGetIntegerv(GL_VIEWPORT, viewport); + cv::Mat depth(viewport[3], viewport[2], CV_32F); + glReadPixels(viewport[0], viewport[1], viewport[2], viewport[3], + GL_DEPTH_COMPONENT, GL_FLOAT, depth.data); + surface_pixels = cv::countNonZero(depth < 1.f); + pixels_read = true; + }); + }); + + for (int i = 0; i < 500 && !pixels_read && app_is_running; i++) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + + glfwSetWindowShouldClose(window->glfw_window, 1); + }); + + std::cout << "red pixels " << red_pixels << ", blue pixels " << blue_pixels + << ", surface pixels " << surface_pixels << std::endl; + check(ui_tasks == 30, "runOnUIThread runs every task"); + check(window->areas_showing.size() == 8, "one area for each image and plot"); + check(red_pixels > 5000, "BGR image is drawn with its colors"); + check(blue_pixels > 2000, "BGRA image is drawn with its colors"); + check(surface_pixels > 1000, "3D surface is drawn"); + return failures == 0 ? 0 : 1; +}