id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
753,915
|
wg_color.h
|
ColinPitrat_caprice32/src/gui/includes/wg_color.h
|
// wg_color.h
//
// CRGBColor class interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_COLOR_H_
#define _WG_COLOR_H_
#include "SDL.h"
#include <cmath>
#include <string>
namespace wGui
{
//! The CRGBColor class is used for all wGui representations of color
class CRGBColor
{
public:
unsigned char red; //!< Red component of the color
unsigned char green; //!< Green component of the color
unsigned char blue; //!< Blue component of the color
unsigned char alpha; //!< Alpha component (or opacity) of the color
//! Default copy constructor.
CRGBColor(const CRGBColor& other) = default;
//! Construct a new color object
//! \param r Red component value
//! \param b Blue component value
//! \param g Green component value
//! \param a Alpha value, default value of 0xFF (fully opaque)
CRGBColor(const unsigned char r, const unsigned char g, const unsigned char b, const unsigned char a = 0xFF) :
red(r), green(g), blue(b), alpha(a) { }
//! Construct a CRGBColor object from an SDL Color
//! \param pColorValue A pointer to the SDL Color
//! \param pFormat A pointer to the SDL Pixel Format
CRGBColor(const Uint32* pColorValue, const SDL_PixelFormat* pFormat);
//! Construct a CRGBColor object from a text string
//! The string can be passed one of 2 ways.
//! 1.) A color name - "RED"
//! 2.) An RGB comma separated value - "255,0,0"
//! \param s The string to get the color code of
CRGBColor(std::string s);
//! Convert the color so an SDL Color
//! \param pFormat A pointer to the SDL Pixel Format
unsigned long int SDLColor(SDL_PixelFormat* pFormat) const
{ return SDL_MapRGBA(pFormat, red, green, blue, alpha); }
//! Comparison operator does not take into account alpha values
//! \return true if the Red, Green, and Blue color components are the same
bool operator==(const CRGBColor& c) const
{
return (red == c.red && green == c.green && blue == c.blue);
}
//! Inequality operator does not take into accoutn alpha values
//! \return true if any of the Red, Green, or Blue color components differ
bool operator!=(const CRGBColor& c) const
{
return (red != c.red || green != c.green || blue != c.blue);
}
//! Assignment operator
CRGBColor& operator=(const CRGBColor& c);
//! Does additive color mixing
CRGBColor operator+(const CRGBColor& c) const;
//! Multiplies the r, g and b components by f.
CRGBColor operator*(float f) const;
//! Does OR color mixing
CRGBColor operator|(const CRGBColor& c) const;
//! Does AND color mixing
CRGBColor operator&(const CRGBColor& c) const;
//! Does XOR color mixing
CRGBColor operator^(const CRGBColor& c) const;
//! Does Normal color mixing
//! \param c The color to be applied as the foreground color
CRGBColor MixNormal(const CRGBColor& c) const;
};
// Predefined colors
extern CRGBColor DEFAULT_BUTTON_COLOR;
extern CRGBColor DEFAULT_TEXT_COLOR;
extern CRGBColor ALTERNATE_TEXT_COLOR;
extern CRGBColor DEFAULT_TITLEBAR_COLOR;
extern CRGBColor DEFAULT_TITLEBAR_TEXT_COLOR;
extern CRGBColor DEFAULT_BACKGROUND_COLOR;
extern CRGBColor DEFAULT_FOREGROUND_COLOR;
extern CRGBColor DEFAULT_LINE_COLOR;
extern CRGBColor DEFAULT_DISABLED_LINE_COLOR;
extern CRGBColor DEFAULT_CHECKBOX_COLOR;
extern CRGBColor DEFAULT_CHECKBOX_BACK_COLOR;
extern CRGBColor DEFAULT_SELECTION_COLOR;
extern CRGBColor COLOR_TRANSPARENT;
extern CRGBColor COLOR_WHITE;
extern CRGBColor COLOR_LIGHTGRAY;
extern CRGBColor COLOR_GRAY;
extern CRGBColor COLOR_DARKGRAY;
extern CRGBColor COLOR_BLACK;
extern CRGBColor COLOR_BLUE;
extern CRGBColor COLOR_DARKBLUE;
extern CRGBColor COLOR_BLUE_1;
extern CRGBColor COLOR_RED;
extern CRGBColor COLOR_GREEN;
extern CRGBColor COLOR_DARKGREEN;
extern CRGBColor COLOR_YELLOW;
extern CRGBColor COLOR_CYAN;
extern CRGBColor COLOR_MAGENTA;
extern CRGBColor COLOR_DARKMAGENTA;
}
#endif // _WG_COLOR_H_
| 4,622
|
C++
|
.h
| 119
| 37.058824
| 111
| 0.76264
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,916
|
wg_timer.h
|
ColinPitrat_caprice32/src/gui/includes/wg_timer.h
|
// wg_timer.h
//
// CTimer class interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_TIMER_H_
#define _WG_TIMER_H_
#include "wg_message_client.h"
namespace wGui
{
//! For internal use only
//! \internal The callback used by the SDL Timer
Uint32 TimerCallback(Uint32 Interval, void* param);
//! A simple timer class
//! CTimer will post a CTRL_TIMER message every time the timer expires
class CTimer : public CMessageClient
{
public:
//! Standard constructor
//! \param pOwner A pointer to the timer 'owner'. This is what the timer will set as the destination for it's messages. Use 0 to broadcast the message.
explicit CTimer(CApplication& application, CMessageClient* pOwner = nullptr);
//! Standard destructor
~CTimer() override;
//! Start the timer. When the timer expires, it will post an CTRL_TIMER message
//! \param Interval The time interval in milliseconds before the timer will expire
//! \param bAutoRestart If this is true, the timer will restart again as soon as it expires
void StartTimer(unsigned long int Interval, bool bAutoRestart = false);
//! Stops the running timer
void StopTimer();
//! Indicates if the timer is currently running
//! \return true is the timer is currently running
bool IsRunning() const { return m_TimerID != 0; }
//! Gets the number of times the timer has triggered since it was last reset
//! \return The count of times the timer has fired
long int GetCount() const { return m_iCounter; }
//! Resets the internal counter to zero
void ResetCount() { m_iCounter = 0; }
//! Gets the owner of the timer
//! \return A pointer to the owner of the timer
CMessageClient* GetOwner() { return m_pOwner; }
//! For internal use only
//! \internal This is where the SDL timer calls back to, and should not be used elsewhere
Uint32 TimerHit(Uint32 Interval);
// CMessageClient overrides
//! Attempt to handle the given message
//! \return true if the object handled the message (the message will not be given to any other handlers)
bool HandleMessage(CMessage* pMessage) override;
protected:
//! The ID of the SDL timer used
SDL_TimerID m_TimerID;
//! If this is true, the timer will restart as soon as it expires
bool m_bAutoRestart;
//! A simple counter that increments each time the timer fires
long int m_iCounter;
//! A pointer the the timer's owner. this is where messages are destined.
CMessageClient* m_pOwner;
};
}
#endif // _WG_TIMER_H_
| 3,223
|
C++
|
.h
| 76
| 40.539474
| 154
| 0.755613
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,917
|
wg_error.h
|
ColinPitrat_caprice32/src/gui/includes/wg_error.h
|
// wg_error.h
//
// wGui error classes
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// This is for all the exception classes that are used in wGui
#ifndef _WG_ERROR_H_
#define _WG_ERROR_H_
#include <exception>
#include <string>
namespace wGui
{
//! All wGui exception classes are derived from here
class Wg_Ex_Base : public std::exception
{
public:
//! Standard constructor
//! \param sWhat A string for more information on what caused the exception
Wg_Ex_Base(std::string sWhat, std::string sWhere) : m_sWhat(std::move(sWhat)), m_sWhere(std::move(sWhere)) { }
//! Standard Destructor
~Wg_Ex_Base() noexcept override = default;
//! Gets a text description of the exception
//! \return A string describing what caused the exception
const char* what() const noexcept override { return m_sWhat.c_str(); }
//! Gets a text description of where the exception happened
//! \return A string describing where the exception was raised
virtual const char* where() const noexcept { return m_sWhere.c_str(); }
//! Gets a text description of the exception
//! \return A std::string reference describing what caused the exception
virtual const std::string& std_what() const noexcept { return m_sWhat; }
private:
std::string m_sWhat;
std::string m_sWhere;
};
//! Exceptions caused by SDL errors
class Wg_Ex_SDL : public Wg_Ex_Base
{
public:
//! Standard constructor
//! \param sWhat A string for more information on what caused the exception
Wg_Ex_SDL(const std::string& sWhat, const std::string& sWhere = "") : Wg_Ex_Base(sWhat, sWhere) { }
};
//! Exceptions caused by FreeType errors
class Wg_Ex_FreeType : public Wg_Ex_Base
{
public:
//! Standard constructor
//! \param sWhat A string for more information on what caused the exception
Wg_Ex_FreeType(const std::string& sWhat, const std::string& sWhere = "") : Wg_Ex_Base(sWhat, sWhere) { }
};
//! General wGui errors
class Wg_Ex_App : public Wg_Ex_Base
{
public:
//! Standard constructor
//! \param sWhat A string for more information on what caused the exception
Wg_Ex_App(const std::string& sWhat, const std::string& sWhere = "") : Wg_Ex_Base(sWhat, sWhere) { }
};
//! Exceptions caused by out-of-range type errors
class Wg_Ex_Range : public Wg_Ex_Base
{
public:
//! Standard constructor
//! \param sWhat A string for more information on what caused the exception
Wg_Ex_Range(const std::string& sWhat, const std::string& sWhere = "") : Wg_Ex_Base(sWhat, sWhere) { }
};
}
#endif // _WG_ERROR_H_
| 3,247
|
C++
|
.h
| 85
| 36.611765
| 111
| 0.740127
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,919
|
CapriceAbout.h
|
ColinPitrat_caprice32/src/gui/includes/CapriceAbout.h
|
// 'About' box for Caprice32
// Inherited from CMessageBox
#ifndef _WG_CAPRICE32ABOUT_H_
#define _WG_CAPRICE32ABOUT_H_
#include "wg_messagebox.h"
#include "wg_label.h"
#include "wg_textbox.h"
namespace wGui
{
class CapriceAbout : public CMessageBox {
public:
//! \param pParent A pointer to the parent view
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is set to 0 it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CapriceAbout(const CRect& WindowRect, CWindow* pParent, CFontEngine* pFontEngine);
private:
CapriceAbout(const CapriceAbout&) = delete;
CapriceAbout& operator=(const CapriceAbout&) = delete;
CTextBox* m_pTextBox;
};
}
#endif // _WG_CAPRICE32ABOUT_H_
| 868
|
C++
|
.h
| 22
| 34.681818
| 150
| 0.713945
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,920
|
wg_messagebox.h
|
ColinPitrat_caprice32/src/gui/includes/wg_messagebox.h
|
// wg_messagebox.h
//
// CMessageBox interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_MESSAGEBOX_H_
#define _WG_MESSAGEBOX_H_
#include "wg_frame.h"
#include "wg_label.h"
#include <map>
#include <string>
namespace wGui
{
//! The CMessageBox class is a simple class that brings up a modal dialog box with a message and waits for user input
class CMessageBox : public CFrame
{
public:
//! \param pParent A pointer to the parent view
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is set to 0 it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
//! \param sTitle The window title, which will appear in the title bar of the view
//! \param sMessage The message to display in the message box
//! \param iButtons A flag field to indicate which buttons to display in the message box, defaults to a single OK button
CMessageBox(const CRect& WindowRect, CWindow* pParent, CFontEngine* pFontEngine, const std::string& sTitle, const std::string& sMessage, int iButtons = BUTTON_OK);
//! The return values for a message box
enum EButton {
BUTTON_INVALID = 0,
BUTTON_CANCEL = 1,
BUTTON_OK = 2,
BUTTON_NO = 4,
BUTTON_YES = 8
};
// CMessageClient overrides
//! CScrollBars handle MOUSE_BUTTONDOWN and MOUSE_BUTTONUP messages
//! \param pMessage A pointer to the message
bool HandleMessage(CMessage* pMessage) override;
protected:
CLabel* m_pMessageLabel; //!< The label that is used for the message
CPicture* m_pPicture; // judb an optional picture
std::map<EButton, CButton*> m_ButtonMap; //!< A map for the buttons
int m_iButtons; //!< The ORed value of the buttons to display in the message box
private:
CMessageBox(const CMessageBox&) = delete;
CMessageBox& operator=(const CMessageBox&) = delete;
};
}
#endif // _WG_MESSAGEBOX_H_
| 2,667
|
C++
|
.h
| 64
| 39.953125
| 164
| 0.757728
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,921
|
wg_application.h
|
ColinPitrat_caprice32/src/gui/includes/wg_application.h
|
// wg_application.h
//
// CApplication interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_APPLICATION_H_
#define _WG_APPLICATION_H_
#include "SDL.h"
#include <list>
#include <string>
#include <map>
#include <memory>
#include "wg_window.h"
#include "wg_message_server.h"
#include "wg_message_client.h"
#include "wg_fontengine.h"
#include "wg_resources.h"
#include "std_ex.h"
namespace wGui
{
const int DEFAULT_BPP = 32;
//! A class for encapsulating an application
//! CApplication is a singleton (only one instance of it should ever exist)
//! This handles all global level stuff like initializing SDL and creating a MessageServer
//! CApplication also takes care of turning SDL events into wGui messages
class CApplication : public CMessageClient
{
public:
//! Standard constructor
//! \param pWindow The SDL window this application runs in.
//! \param sFontFileName The font to use for controls, defaults to Arial
explicit CApplication(SDL_Window* pWindow, std::string sFontFileName = "resource/vera_sans.ttf");
//! Standard destructor
~CApplication() override;
//! Register the view for this application
//! \param The view to register
virtual void RegisterView(CView* pView);
//! Gets the default font file name
//! \return The default font
virtual const std::string& GetDefaultFontFileName() const { return m_sFontFileName; }
//! Gets the current exit code of the application
//! \return The exit code of the app
virtual int ExitCode() const { return m_iExitCode; }
//! Indicates if the application is currently "running" or not
//! \return true while the application is in it's message loop
virtual bool IsRunning() const { return m_bRunning; }
//! Indicates if the CApplication object has been properly initialized
//! \return true if Init() has been called
virtual bool IsInitialized() const { return m_bInited; }
//! This is for setting/getting the window that has the current keyboard focus
//! Any KEYBOARD messages will have this window as their destination
//! \param pWindow A pointer to the window that should get focus
virtual void SetKeyFocus(CWindow* pWindow);
//! Gets the current keyboard focus for the application
//! \return A pointer to the window with keyboard focus
virtual CWindow* GetKeyFocus() const { return m_pKeyFocusWindow; }
//! This is for setting/getting the window that has the current mouse focus
//! Any subsequent MOUSE messages will have this window as their destination
//! \param pWindow A pointer to the window that should get focus ( grab )
virtual void SetMouseFocus(CWindow* pWindow);
//! Gets the current mouse focus for the application
//! \return A pointer to the window with mouse focus ( grab )
virtual CWindow* GetMouseFocus() const { return m_pMouseFocusWindow; }
//! Init() must be called before Exec() or ProcessEvent()
//! Takes care of initializing SDL and other important stuff
virtual void Init();
//! A single step of the primary message loop. Useful to continue to update things outside of the application.
virtual void Update();
//! Processing one event. Useful when events can also affect things outside of the application.
virtual bool ProcessEvent(SDL_Event& e);
//! The primary message loop
virtual void Exec();
//! This is called just before the application exits
//! \param iExitCode The exit code to return, defaults to EXIT_SUCCESS
virtual void ApplicationExit(int iExitCode = EXIT_SUCCESS);
//! Creates a font engine
//! A seperate font engine is created for each font file and font size
//! \param sFontFileName The font to use
//! \param iFontSize The size (in points) of the font, defaults to 12
//! \return A pointer to the font engine, 0 if the font engine can't be loaded
virtual CFontEngine* GetFontEngine(std::string sFontFileName, unsigned char iFontSize = 8);
//! Sets the default font engine
//! If a default font engine is not set, a valid font engine must be passed to any controls that display text
virtual void SetDefaultFontEngine(CFontEngine* pFontEngine) { m_pDefaultFontEngine = pFontEngine; }
//! Gets the default font engine
//! \return A pointer to the default font engine
virtual CFontEngine* GetDefaultFontEngine() const { return m_pDefaultFontEngine; }
//! Gets the color depth (in bits per pixel) of the app
//! \return The color depth of the view
virtual int GetBitsPerPixel() const { return DEFAULT_BPP; }
//! Gets the default background color
//! \return Default background color
virtual CRGBColor GetDefaultBackgroundColor() const { return m_DefaultBackgroundColor; }
//! Gets the default foreground color
//! \return Default foreground color
virtual CRGBColor GetDefaultForegroundColor() const { return m_DefaultForegroundColor; }
//! Gets the default selection color
//! \return Default selection color
virtual CRGBColor GetDefaultSelectionColor() const { return m_DefaultSelectionColor; }
//! Adds a resource handle to the resource pool if the pool is enabled
//! Once a resource is added, it cannot be removed.
//! \param ResourceHandle The resource handle to copy into the pool
//! \return false if the resource pool is disabled
virtual bool AddToResourcePool(CResourceHandle& ResourceHandle);
//! Changes the mouse cursor
//! \param pCursorResourceHandle A pointer to the cursor resource handle, if no cursor is specified, the cursor will revert to the system default
virtual void SetMouseCursor(CCursorResourceHandle* pCursorResourceHandle = nullptr);
CMessageServer* MessageServer() const { return m_pMessageServer.get(); }
// CMessageClient overrides
//! CApplication will handle the APP_EXIT message, and will close the application on it's receipt
//! \param pMessage A pointer the the message to handle
bool HandleMessage(CMessage* pMessage) override;
protected:
//! For internal use only
//! \internal converts SDL events into wGui messages
//! \param event An SDL Event structure
virtual bool HandleSDLEvent(SDL_Event event);
SDL_Window* m_pSDLWindow;
bool m_bInMainView = true; //!< Whether the GUI is displayed through Caprice main view (i.e going through video_plugin)
int m_iScale = 1; //!< The scaling of the UI (necessary on high-DPI screens)
CView* m_pMainView;
bool m_Focused = true;
mutable std::unique_ptr<CMessageServer> m_pMessageServer;
std::string m_sFontFileName; //!< The font to use for all controls
int m_iExitCode; //!< The exit code to be returned when the app exits
bool m_bRunning; //!< Indicates if the app is currently spinning in the message loop
bool m_bInited; //!< true if Init() has been called
CWindow* m_pKeyFocusWindow; //!< A pointer to the window with keyboard focus
CWindow* m_pMouseFocusWindow; //!< A pointer to the window with mouse focus
using t_FontEngineMapKey = std::pair<std::string, unsigned char>; //!< A typedef of font name and size pairs
using t_FontEngineMap = std::map<t_FontEngineMapKey, CFontEngine*>; //!< A typedef of a map of font engine pointers
t_FontEngineMap m_FontEngines; //!< A map of font engine pointers
CFontEngine* m_pDefaultFontEngine; //!< A pointer to the default font engine
CRGBColor m_DefaultBackgroundColor; //!< Default background color
CRGBColor m_DefaultForegroundColor; //!< Default foreground color
CRGBColor m_DefaultSelectionColor; //!< Default selection color
std::list<CResourceHandle> m_ResourceHandlePool; //!< The resource handle pool which keeps commonly used resources alive
std::unique_ptr<CCursorResourceHandle> m_pCurrentCursorResourceHandle; //!< An autopointer to the handle for the current mouse cursor
SDL_Cursor* m_pSystemDefaultCursor; //!< A pointer to the default system cursor
};
}
#endif // _WG_APPLICATION_H_
| 8,483
|
C++
|
.h
| 159
| 51.327044
| 146
| 0.768357
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,922
|
cap_register.h
|
ColinPitrat_caprice32/src/gui/includes/cap_register.h
|
// cap_register.h
//
// A widget combining a label and 3 fields for hexadecimal, decimal and char
// content of a register or memory location.
#ifndef _CAP_REGISTER_H_
#define _CAP_REGISTER_H_
#include <string>
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_label.h"
#include "wg_editbox.h"
namespace wGui
{
//! A composite widget for register/memory location display, combining name, hexadecimal, decimal and char values.
class CRegister : public CWindow
{
public:
//! Construct a new Register control
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param name The name of the register (will constitute the label).
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is left out (or set to 0) it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CRegister(const CRect& WindowRect, CWindow* pParent, const std::string& name, CFontEngine* pFontEngine = nullptr);
//! Standard destructor
~CRegister() override;
//! Set the value of the register
//! \param c The value to assign to the control
void SetValue(const unsigned int c);
protected:
CFontEngine* m_pFontEngine; //!< A pointer to the font engine to use to render the text
unsigned int m_Value; //!< The value of the register/memory location
CLabel* m_pLabel;
CEditBox* m_pHexValue;
CEditBox* m_pDecValue;
CEditBox* m_pCharValue;
private:
CRegister(const CRegister&) = delete;
CRegister& operator=(const CRegister&) = delete;
};
}
#endif // _CAP_EDITBOX_H_
| 1,658
|
C++
|
.h
| 42
| 37.595238
| 157
| 0.758276
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,923
|
wg_scrollbar.h
|
ColinPitrat_caprice32/src/gui/includes/wg_scrollbar.h
|
// wg_scrollbar.h
//
// CScrollBar interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_SCROLLBAR_H_
#define _WG_SCROLLBAR_H_
#include "wg_range_control.h"
#include "wg_painter.h"
#include "wg_button.h"
namespace wGui
{
//! A scroll bar
class CScrollBar : public CRangeControl<int>
{
public:
//! The types of scrollbars possible
enum EScrollBarType
{
VERTICAL, //!< A standard vertical scrollbar
HORIZONTAL //!< A standard horizontal scrollbar
};
//! Constructs a scroll bar, initilizes the limits to 0, and 100 with the position at 0
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param ScrollBarType Indicates if this is to be a vertical or horizontal scrollbar
CScrollBar(const CRect& WindowRect, CWindow* pParent, EScrollBarType ScrollBarType);
//! Standard destructor
~CScrollBar() override;
//! Set the amount to jump by when the area below or above the thumb is clicked (this is 5 by default)
//! \param iJumpAmount The amount to step by
virtual void SetJumpAmount(int iJumpAmount) { m_iJumpAmount = iJumpAmount; }
//! Get the amount that the scrollbar will jump by when the arrow buttons are clicked
//! \return The amount the scrollbar jumps by when clicked above or below the thumb
virtual int GetJumpAmount() const { return m_iJumpAmount; }
// CRangeControl overrides
//! Set the current value.
//! \param iValue The new value for the control
//! \param bRedraw indicates if the control should be redrawn (defaults to true)
void SetValue(int iValue, bool bRedraw = true, bool bNotify = true) override;
//! Set the lower limit for the control.
//! \param minLimit The lower limit of the control
void SetMinLimit(int minLimit) override;
//! Set the upper limit for the control.
//! \param maxLimit The upper limit of the control
void SetMaxLimit(int maxLimit) override;
// CWindow overrides
//! Draws the scroll bar
void Draw() const override;
//! Giving a control a new WindowRect will move and resize the control
//! \param WindowRect A CRect that defines the outer limits of the control
void SetWindowRect(const CRect& WindowRect) override;
//! Move the window and any child windows
//! \param MoveDistance The relative distance to move the window
void MoveWindow(const CPoint& MoveDistance) override;
//! Verifies if the button is a wheel event and scroll accordingly.
//! Logic extracted from OnMouseButtonDown to allow calling it from an associated widget.
//! \param Button A bitfield indicating which button was clicked
//! \return True if the event had an effect.
bool HandleMouseScroll(unsigned int Button);
//! This is called whenever the scrollbar is clicked on by the mouse
//! Only the topmost window that bounds the point will be called by the system
//! \param Point The point where the mouse clicked
//! \param Button A bitfield indicating which button the window was clicked with
//! \return True if it's in the bounds of the scrollbar
bool OnMouseButtonDown(CPoint Point, unsigned int Button) override;
void SetIsFocusable(bool bFocusable) override;
// CMessageClient overrides
//! CScrollBars handle MOUSE_BUTTONDOWN and MOUSE_BUTTONUP messages
//! \param pMessage A pointer to the message
bool HandleMessage(CMessage* pMessage) override;
protected:
//! Repositions the thumb according to the value
virtual void RepositionThumb();
EScrollBarType m_ScrollBarType; //!< The type of scroll bar
int m_iJumpAmount; //!< The amount to jump when the area below or above the thumb is clicked
CPictureButton* m_pBtnUpLeft; //!< A pointer to the Up or Left button
CPictureButton* m_pBtnDownRight; //!< A pointer to the Down or Right button
CRect m_ThumbRect; //!< The thumb rect
bool m_bDragging; //!< Indicates if the thumb is currently being dragged
private:
CScrollBar(const CScrollBar&) = delete;
CScrollBar& operator=(const CScrollBar&) = delete;
};
}
#endif // _WG_SCROLLBAR_H_
| 4,772
|
C++
|
.h
| 103
| 44.368932
| 103
| 0.767306
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,924
|
CapriceOptions.h
|
ColinPitrat_caprice32/src/gui/includes/CapriceOptions.h
|
// 'Options' window for Caprice32
// Inherited from CFrame
#ifndef _WG_CAPRICE32OPTIONS_H_
#define _WG_CAPRICE32OPTIONS_H_
#include "wg_checkbox.h"
#include "wg_dropdown.h"
#include "wg_frame.h"
#include "wg_groupbox.h"
#include "wg_label.h"
#include "wg_navigationbar.h"
#include "wg_radiobutton.h"
#include "wg_scrollbar.h"
#include "CapriceRomSlots.h"
#include "cap32.h"
#include "video.h"
#include <map>
#include <string>
namespace wGui
{
class CapriceOptions : public CFrame {
public:
//! \param pParent A pointer to the parent view
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is set to 0 it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CapriceOptions(const CRect& WindowRect, CWindow* pParent, CFontEngine* pFontEngine);
~CapriceOptions() override;
bool HandleMessage(CMessage* pMessage) override;
// activate the specified tab (make its controls visible)
void EnableTab(std::string sTabName);
protected:
CButton* m_pButtonSave;
CButton* m_pButtonCancel;
CButton* m_pButtonOk;
// subdialogs that can be opened from the options dialog, e.g. ROM selection:
CapriceRomSlots* pRomSlotsDialog;
// New navigation bar control (to select the different pages or tabs on the options dialog)
CNavigationBar* m_pNavigationBar;
// groupbox to group the controls on each 'tab':
CGroupBox* m_pGroupBoxTabGeneral;
CGroupBox* m_pGroupBoxTabExpansion;
CGroupBox* m_pGroupBoxTabVideo;
CGroupBox* m_pGroupBoxTabAudio;
CGroupBox* m_pGroupBoxTabDisk;
CGroupBox* m_pGroupBoxTabInput;
// General options
CLabel* m_pLabelCPCModel;
CDropDown* m_pDropDownCPCModel; // CPC model (464,664,6128...)
CLabel* m_pLabelRamSize; // amount of RAM memory (64k up to 576k)
CScrollBar* m_pScrollBarRamSize;
CLabel* m_pLabelRamSizeValue;
CCheckBox* m_pCheckBoxLimitSpeed; // 'Limit emulation speed' (to original CPC speed)
CLabel* m_pLabelLimitSpeed; // text label for above checkbox
CLabel* m_pLabelCPCSpeed; // CPC emulation speed
CScrollBar* m_pScrollBarCPCSpeed;
CLabel* m_pLabelCPCSpeedValue;
CLabel* m_pLabelPrinterToFile; // Capture printer output to file
CCheckBox* m_pCheckBoxPrinterToFile;
// Expansion ROMs
std::vector<CButton *> m_pButtonRoms; // contains pointer to 16 'ROM buttons'
// Video options
CLabel* m_pLabelShowFps; // text label for above checkbox
CCheckBox* m_pCheckBoxShowFps; // Show emulation speed
CLabel* m_pLabelFullScreen;
CCheckBox* m_pCheckBoxFullScreen; // Full screen toggle
CLabel* m_pLabelAspectRatio;
CCheckBox* m_pCheckBoxAspectRatio; // Preserve aspect ratio toggle
CGroupBox* m_pGroupBoxMonitor;
CRadioButton* m_pRadioButtonColour; // Colour or monochrome monitor
CLabel* m_pLabelColour;
CRadioButton* m_pRadioButtonMonochrome;
CLabel* m_pLabelMonochrome;
CScrollBar* m_pScrollBarIntensity; // Monitor intensity (default 1.0)
CLabel* m_pLabelIntensity;
CLabel* m_pLabelIntensityValue;
CDropDown* m_pDropDownVideoPlugin; // Select video plugin
CLabel* m_pLabelVideoPlugin;
CDropDown* m_pDropDownVideoScale; // Select video scale factor
CLabel* m_pLabelVideoScale;
// Audio options
CCheckBox* m_pCheckBoxEnableSound; // Show emulation speed
CLabel* m_pLabelEnableSound;
CDropDown* m_pDropDownSamplingRate; // Select audio sampling rate
CLabel* m_pLabelSamplingRate;
CGroupBox* m_pGroupBoxChannels;
CGroupBox* m_pGroupBoxSampleSize;
CLabel* m_pLabelSoundVolume;
CScrollBar* m_pScrollBarVolume;
CLabel* m_pLabelSoundVolumeValue;
CRadioButton* m_pRadioButtonMono;
CLabel* m_pLabelMono;
CRadioButton* m_pRadioButtonStereo;
CLabel* m_pLabelStereo;
CRadioButton* m_pRadioButton8bit;
CLabel* m_pLabel8bit;
CRadioButton* m_pRadioButton16bit;
CLabel* m_pLabel16bit;
// Disk options
CGroupBox* m_pGroupBoxDriveA;
CGroupBox* m_pGroupBoxDriveB;
CDropDown* m_pDropDownDriveAFormat;
CLabel* m_pLabelDriveAFormat;
CDropDown* m_pDropDownDriveBFormat;
CLabel* m_pLabelDriveBFormat;
// Input options
CLabel* m_pLabelCPCLanguage;
CDropDown* m_pDropDownCPCLanguage;
CLabel* m_pLabelPCLanguage;
CDropDown* m_pDropDownPCLanguage;
CLabel* m_pLabelJoystickEmulation;
CCheckBox* m_pCheckBoxJoystickEmulation;
CLabel* m_pLabelJoysticks;
CCheckBox* m_pCheckBoxJoysticks;
t_CPC m_oldCPCsettings; // we will store the current CPC settings in this variable, and
// when clicking OK in the options screen, check what options have changed
// and take a required action (e.g. emulator reset, sound system reset...)
bool ProcessOptionChanges(t_CPC& CPC, bool saveChanges); // see m_oldCPCsettings
private:
std::map<std::string, CGroupBox*> TabMap; // mapping: <tab name> -> <groupbox that contains the 'tab'>.
CapriceOptions(const CapriceOptions&) = delete;
CapriceOptions& operator=(const CapriceOptions&) = delete;
};
}
#endif // _WG_CAPRICE32OPTIONS_H_
| 5,539
|
C++
|
.h
| 123
| 38.081301
| 150
| 0.7
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,925
|
wg_listbox.h
|
ColinPitrat_caprice32/src/gui/includes/wg_listbox.h
|
// wg_listbox.h
//
// CListBox interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_LISTBOX_H_
#define _WG_LISTBOX_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_renderedstring.h"
#include "wg_scrollbar.h"
#include <string>
#include <vector>
namespace wGui
{
//! A listbox item
struct SListItem
{
public:
//! Standard constructor
SListItem(std::string sItemTextIn, void* pItemDataIn = nullptr, CRGBColor ItemColorIn = DEFAULT_TEXT_COLOR) :
sItemText(std::move(sItemTextIn)), pItemData(pItemDataIn), ItemColor(ItemColorIn) { }
std::string sItemText; //!< The displayed text for the item
void* pItemData; //!< A pointer to void that can be used as a data pointer
CRGBColor ItemColor; //!< The color to display the item in
};
//! A simple listbox class
//! The button will generate CTRL_VALUECHANGE messages when a different listbox item is selected
//! The iNewValue of the message is the index of the item that was selected
class CListBox : public CWindow
{
public:
//! Constructs a new listbox
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param bSingleSelection If true, only one item can be selected at a time, defaults to false
//! \param iItemHeight The height of the items in the list, defaults to 15
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is left out (or set to 0) it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CListBox(const CRect& WindowRect, CWindow* pParent, bool bSingleSelection = false, unsigned int iItemHeight = 15, CFontEngine* pFontEngine = nullptr);
//! Standard destructor
~CListBox() override;
//! Gets the height of the items
//! \return The height of the items in the listbox
unsigned int GetItemHeight() const { return m_iItemHeight; }
//! Sets the heigh of the items in the listbox
//! \param iItemHeight The height of the items in the listbox
void SetItemHeight(unsigned int iItemHeight);
//! Adds a new item to the list
//! \param ListItem A SListItem structure with the data for the item
//! \return The index of the added item
unsigned int AddItem(SListItem ListItem);
//! Adds multiple items at once to the list
//! \param ListItems The items to add
//! \return The index of the last added item
unsigned int AddItems(std::vector<SListItem> ListItem);
//! Returns the desired item
//! \param iItemIndex The index of the item to check (will throw an exception if the index is out of range)
//! \return A reference to the SListItem struct
SListItem& GetItem(unsigned int iItemIndex) { return m_Items.at(iItemIndex); }
//! Returns the list of all items
//! \return A reference on the vector of SListItem struct
const std::vector<SListItem>& GetAllItems() const { return m_Items; }
//! Remove an item from the list
//! \param iItemIndex The index of the item to remove
void RemoveItem(unsigned int iItemIndex);
//! Remove all items from the list
void ClearItems();
//! Gets the number of items in the listbox
//! \return The number of items in the list
unsigned int Size() { return m_Items.size(); }
//! \param iItemIndex The index of the item to check (will return false if the index is out of range)
//! \return true if the item is selected
bool IsSelected(unsigned int iItemIndex)
{ return (iItemIndex < m_SelectedItems.size() && m_SelectedItems.at(iItemIndex)); }
// Returns the index of the first selected item; returns -1 if there is no selection.
int getFirstSelectedIndex();
enum EPosition {
UP,
CENTER,
DOWN
};
//! Move to the position where a given item would be at the given spot.
//! \param iItemIndex The index of the item to position
//! \param ePosition Where the item should be in the box
void SetPosition(int iItemIndex, EPosition ePosition);
//! Set an item as selected
//! \param iItemIndex The index of the item to change
//! \param bSelected Will select the item if true, or unselect if false
void SetSelection(unsigned int iItemIndex, bool bSelected, bool bNotify = true);
//! Selects or deselects all items
void SetAllSelections(bool bSelected);
//! Sets the focus rectangle on the specified item:
void SetFocus(unsigned int iItemIndex);
//! Set the dropdown window this is a part of
//! \param pDropDown A pointer to the dropdown window
void SetDropDown(CWindow* pDropDown);
// CWindow overrides
//! Draws the button and renders the button label
void Draw() const override;
//! Giving a control a new WindowRect will move and resize the control
//! \param WindowRect A CRect that defines the outer limits of the control
void SetWindowRect(const CRect& WindowRect) override;
//! Blit the window to the given surface, using m_WindowRect as the offset into the surface
//! \param ScreenSurface A reference to the surface that the window will be copied to
//! \param FloatingSurface A reference to the floating surface which is overlayed at the very end (used for tooltips, menus and such)
//! \param Offset This is the current offset into the Surface that should be used as reference
void PaintToSurface(SDL_Surface& ScreenSurface, SDL_Surface& FloatingSurface, const CPoint& Offset) const override;
//! This is called whenever the listbox is clicked on by the mouse
//! Only the topmost window that bounds the point will be called by the system
//! \param Point The point where the mouse clicked
//! \param Button A bitfield indicating which button the window was clicked with
//! \return True if it's in the bounds of the listbox
bool OnMouseButtonDown(CPoint Point, unsigned int Button) override;
//! This is called whenever the a mouse button is released in the listbox
//! Only the topmost window that bounds the point will be called by the system
//! \param Point The point where the mouse clicked
//! \param Button A bitfield indicating which button the window was clicked with
//! \return True if it's in the bounds of the listbox
bool OnMouseButtonUp(CPoint Point, unsigned int Button) override;
// CMessageClient overrides
//! CListBoxes handle MOUSE_BUTTONDOWN, MOUSE_BUTTONUP and CTRL_VALUECHANGE messages
//! \param pMessage A pointer to the message
bool HandleMessage(CMessage* pMessage) override;
protected:
void UpdateMaxLimit();
CFontEngine* m_pFontEngine; //!< A pointer to the font engine to use to render the text
CScrollBar* m_pVScrollbar; //!< A pointer to the vertical scrollbar
unsigned int m_iItemHeight; //!< The height of the items in the list
unsigned int m_iFocusedItem; //!< The currently focused item (rectangle)
std::vector<SListItem> m_Items; //!< The list of items
std::vector<bool> m_SelectedItems; //!< A vector of booleans indicating which items are selected
std::vector<CRenderedString> m_RenderedStrings; //!< A vector of the rendered strings
const bool m_bSingleSelection; //!< If true, only one item can be selected at a time
CWindow* m_pDropDown; //!< A pointer to the dropdown control if this a part of one
private:
CListBox(const CListBox&) = delete;
CListBox& operator=(const CListBox&) = delete;
};
}
#endif // _WG_LISTBOX_H_
| 8,012
|
C++
|
.h
| 158
| 48.607595
| 157
| 0.759959
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,926
|
wg_resource_handle.h
|
ColinPitrat_caprice32/src/gui/includes/wg_resource_handle.h
|
// wg_resource_handle.h
//
// Resource handles interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_RESOURCE_HANDLE_H_
#define _WG_RESOURCE_HANDLE_H_
#include "SDL.h"
#include <map>
#include <string>
namespace wGui
{
//! The resource ID type
using TResourceId = long int;
const TResourceId AUTO_CREATE_RESOURCE_ID = -2; //!< This is an internally used value for the Resource ID, that specifies that the next open resource ID should be used
const TResourceId INVALID_RESOURCE_ID = -1; //!< This is an internally used value for the resource ID that indicates an invalid resource
const TResourceId NULL_RESOURCE_ID = 0; //!< This is a resource ID for no resource
//! CResourceHandles are a basic smart handle for a resource pool
//! It will handle reference counting, allocation, and freeing of the resource
//! Classes derived from CResourceHandle should not have any personal data members, any data should be held in a static map
class CResourceHandle
{
public:
//! CResourceHandles must be instantiated with a valid resource ID
//! \param resId The ID of the resource which the handle will represent
CResourceHandle(TResourceId resId);
//! A copying constructor
//! \param resHandle An existing resource handle that will be cloned
CResourceHandle(const CResourceHandle& resHandle);
//! Standard destructor will decrement the refcount for the resource and will deallocate it if the refcount hits zero
virtual ~CResourceHandle();
//! Gets the resource ID of the handle
//! \return The resource ID of the handle
TResourceId GetResourceId() const { return m_ResourceId; }
//! Gets the handle's internal reference count
//! \return The reference count of the handle
unsigned int GetRefCount() const { return m_RefCountMap[m_ResourceId]; }
protected:
//! The resource ID for the handle
TResourceId m_ResourceId;
private:
//! Resource handles are not assignable
CResourceHandle& operator=(const CResourceHandle&) = delete;
//! The refcount for all the resources
static std::map<TResourceId, unsigned int> m_RefCountMap;
//! An internally used variable for keeping track of the next unused resource ID
static TResourceId m_NextUnusedResourceId;
};
//! CBitmapResourceHandle is a resource handle for bitmaps
//! It will allocate the bitmaps as needed and can be cast as a bitmap
class CBitmapResourceHandle : public CResourceHandle
{
public:
//! CBitmapResourceHandles must be instantiated with a valid resource ID
//! \param resId The ID of the resource which the handle will represent
CBitmapResourceHandle(TResourceId resId) : CResourceHandle(resId) { }
//! A copying constructor
//! \param resHandle An existing resource handle that will be cloned
CBitmapResourceHandle(const CBitmapResourceHandle& resHandle) = default;
//! Standard destructor, which frees the bitmap if the refcount is zero
~CBitmapResourceHandle() override;
//! Gets the handle's bitmap
//! \return An SDL_Surface pointer (the bitmap)
SDL_Surface* Bitmap() const;
protected:
//! The map of bitmaps held by the handles
static std::map<TResourceId, SDL_Surface*> m_BitmapMap;
private:
//! Resource handles are not assignable
CBitmapResourceHandle& operator=(const CBitmapResourceHandle&) = delete;
};
//! A resource handle for bitmap files
//! This will create a unique resource ID which can be used elsewhere
class CBitmapFileResourceHandle : public CBitmapResourceHandle
{
public:
//! CBitmapFileResourceHandle must be instantiated with a valid bitmap file
//! \param sFilename The bitmap file that will be loaded as a resource
CBitmapFileResourceHandle(std::string sFilename);
protected:
std::string m_sFilename; //!< The filename of the resource
private:
//! Resource handles are not assignable
CBitmapFileResourceHandle& operator=(const CBitmapFileResourceHandle&) = delete;
};
//! CStringResourceHandle is a resource handle for strings
class CStringResourceHandle : public CResourceHandle
{
public:
//! CStringResourceHandles must be instantiated with a valid resource ID
//! \param resId The ID of the resource which the handle will represent
CStringResourceHandle(TResourceId resId) : CResourceHandle(resId) { }
//! A copying constructor
//! \param resHandle An existing resource handle that will be cloned
CStringResourceHandle(const CStringResourceHandle& resHandle) = default;
//! Standard destructor, which frees the string if the refcount is zero
~CStringResourceHandle() override;
//! Returns the string
//! \return A string
std::string String() const;
protected:
//! A map of strings that are used by the handles
static std::map<TResourceId, std::string> m_StringMap;
private:
//! Resource handles are not assignable
CStringResourceHandle& operator=(const CStringResourceHandle&) = delete;
};
//! CCursorResourceHandle is a resource handle for mouse cursors
class CCursorResourceHandle : public CResourceHandle
{
public:
//! CCursorResourceHandles must be instantiated with a valid resource ID
//! \param resId The ID of the resource which the handle will represent
CCursorResourceHandle(TResourceId resId) : CResourceHandle(resId) { }
//! A copying constructor
//! \param resHandle An existing resource handle that will be cloned
CCursorResourceHandle(const CCursorResourceHandle& resHandle) = default;
//! Standard destructor, which frees the cursor if the refcount is zero
~CCursorResourceHandle() override;
//! Returns the SDL Cursor pointer
//! \return A pointer to an SDL cursor object
SDL_Cursor* Cursor() const;
protected:
//! A map of cursors used by the handles
static std::map<TResourceId, SDL_Cursor*> m_SDLCursorMap;
private:
//! Resource handles are not assignable
CCursorResourceHandle& operator=(const CCursorResourceHandle&) = delete;
};
}
#endif // _WG_RESOURCE_HANDLE_H
| 6,566
|
C++
|
.h
| 148
| 42.581081
| 168
| 0.787294
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,927
|
std_ex.h
|
ColinPitrat_caprice32/src/gui/includes/std_ex.h
|
// std_ex.h
//
// Extensions to the std library
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _STD_EX_H_
#define _STD_EX_H_
#include <string>
#include <list>
#include <limits>
#include <stdexcept>
namespace stdex
{
//! Converts an integer to it's string representation
//! \param iValue The integer to convert to a string
//! \return A std::string representing the value
std::string itoa(const int iValue);
//! Converts a long integer to it's string representation
//! \param lValue The integer to convert to a string
//! \return A std::string representing the value
std::string ltoa(const long lValue);
//! Converts a double to it's string representation
//! \param fValue The double to convert to a string
//! \return A std::string representing the value
std::string ftoa(const float fValue);
//! Converts a double to it's string representation
//! \param dValue The double to convert to a string
//! \return A std::string representing the value
std::string dtoa(const double dValue);
//! Converts a string to it's int representation
//! \param sValue the string to convert
//! \return integer
int atoi(const std::string& sValue);
//! Converts a string to it's long integer representation
//! \param sValue the string to convert
//! \return long integer
long int atol(const std::string& sValue);
//! Converts a string to it's float representation
//! \param sValue the string to convert
//! \return float
float atof(const std::string& sValue);
//! Converts a string to it's double representation
//! \param sValue the string to convert
//! \return double
double atod(const std::string& sValue);
//! Trim the whitespace (spaces and tabs) from the beginning and end of a string
//! \param sString The string to be trimmed
//! \return the trimmed string
std::string TrimString(const std::string& sString);
int MaxInt(int x, int y) ;
int MinInt(int x, int y) ;
//! Detokenize a string given a list of delimiters
//! \param sString The string to be tokenized
//! \param sDelimiters A string of delimiter characters
//! \return A list of string tokens
std::list<std::string> DetokenizeString(const std::string& sString, const std::string& sDelimiters);
//! Do a static cast with limits checking
//! This will throw a std::out_of_range exception if the value is outside the bounds of the type it's being casted to
#ifdef WIN32
#pragma warning (push)
#pragma warning (disable : 4018) // temporarily disable signed/unsigned comparison warning
#endif // WIN32
template<typename TDest, typename TSrc>
TDest safe_static_cast(const TSrc& Value)
{
return static_cast<TDest>(Value);
}
#ifdef WIN32
#pragma warning (default : 4018) // reenable signed/unsigned comparison warning
#pragma warning (pop)
#endif // WIN32
}
#endif // _STD_EX_H_
| 3,523
|
C++
|
.h
| 90
| 37.911111
| 117
| 0.759449
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,928
|
wg_message_server.h
|
ColinPitrat_caprice32/src/gui/includes/wg_message_server.h
|
// wg_message_server.h
//
// CMessageServer interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_MESSAGE_SERVER_H_
#define _WG_MESSAGE_SERVER_H_
#include "wg_message.h"
#include <deque>
#include <map>
#include "SDL.h"
#include "SDL_thread.h"
namespace wGui
{
class CMessageClient;
//! A struct that associates message client pointers with a flag that indicates if the client has recieved a particular message
struct s_MessageClientActive
{
//! struct constructor
//! \param pC a pointer to the message client
//! \param bW a boolean indicating if the client has gotten the current message
s_MessageClientActive(CMessageClient* pC, bool bW) :
pClient(pC), bWaitingForMessage(bW)
{ }
CMessageClient* pClient; //!< a pointer to the message client
bool bWaitingForMessage; //!< indicates if the client has recieved the current message
};
//! Multimap of message clients ordered by priority
using t_MessageClientPriorityMap = std::multimap<unsigned char, s_MessageClientActive, std::greater<> >;
//! Map of different message types
using t_MessageClientMap = std::map<wGui::CMessage::EMessageType, t_MessageClientPriorityMap>;
//! A server which queues and dispatches messages
//! CMessageServer is a singeton (only one instance of it is allowed to exist at any time)
//! Clients must register to get messages sent to them
//! \sa CMessage CMessageClient
class CMessageServer
{
public:
//! The CMessageServer class shouldn't be directly instantiated, but accessed through the CApplication
CMessageServer();
//! Standard constructor
virtual ~CMessageServer();
//! Used for marking the priority of registered message clients, where the higher priority clients will get messages first
enum EClientPriority
{
PRIORITY_LAST = 0, //!< The absolute lowest priority available
PRIORITY_LOW = 50, //!< Low priority
PRIORITY_NORMAL = 100, //!< Standard priority
PRIORITY_HIGH = 150, //!< High priority
PRIORITY_FIRST = 255 //!< The absolute highest priority available
};
//! Register a client to recieve messages
//! \param pClient A pointer to the client which should recieve the messages
//! \param eMessageType The message type the client wishes to recieve
//! \param Priority The priority of the client for recieving the message
void RegisterMessageClient(CMessageClient* pClient, CMessage::EMessageType eMessageType, unsigned char Priority = PRIORITY_NORMAL);
//! Deregister a client for a certain message type
//! \param pClient A pointer to the message client to be deregistered
//! \param eMessageType The message type for which the client no longer should recieve messages
void DeregisterMessageClient(CMessageClient* pClient, CMessage::EMessageType eMessageType);
//! Deregister a client for all message types
//! \param pClient A pointer to the message client to be deregistered
void DeregisterMessageClient(CMessageClient* pClient);
//! Takes the next message in the queue and dispatches it to any registered clients in priority order
void DeliverMessage();
//! Adds a message to the message queue
//! \param pMessage A pointer to the message to be queued
void QueueMessage(CMessage* pMessage);
//! Indicates if there are any messages available
//! \return true if there's a message available in the queue
bool MessageAvailable() { return !m_MessageQueue.empty(); }
//! Sets the server to ignore any new incoming messages (messages already in the queue are unaffected)
//! \param bIgnore if true, the message queue will ignore any new messages
void IgnoreAllNewMessages(bool bIgnore) { m_bIgnoreAllNewMessages = bIgnore; }
//! Discard all pending messages
void PurgeQueuedMessages();
protected:
std::deque<CMessage*> m_MessageQueue; //!< The message queue
t_MessageClientMap m_MessageClients; //!< A map of all the registered clients
SDL_sem* m_pSemaphore; //!< A semaphore indicating how many messages are in the queue
bool m_bIgnoreAllNewMessages; //!< Locks the queue so that no new messages are added, this is used during initialization, defaults to true
};
}
#endif // _WG_MESSAGE_SERVER_H_
| 4,869
|
C++
|
.h
| 101
| 46.326733
| 140
| 0.775807
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,929
|
CapriceGui.h
|
ColinPitrat_caprice32/src/gui/includes/CapriceGui.h
|
#ifndef CAPRICEGUI_H
#define CAPRICEGUI_H
#include "wg_application.h"
#include "wg_view.h"
#include "SDL.h"
class CapriceGui : public wGui::CApplication
{
public:
CapriceGui(SDL_Window* pWindow, bool bInMainView, int scale=1) : wGui::CApplication(pWindow) {
m_bInMainView = bInMainView;
m_iScale = scale;
};
void Init() override;
};
#endif
| 369
|
C++
|
.h
| 15
| 21.666667
| 98
| 0.717949
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,930
|
wg_progress.h
|
ColinPitrat_caprice32/src/gui/includes/wg_progress.h
|
// wg_progress.h
//
// CProgress interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_PROGRESS_H_
#define _WG_PROGRESS_H_
#include "wg_range_control.h"
#include "wg_painter.h"
namespace wGui
{
//! A progress bar display
class CProgress : public CRangeControl<int>
{
public:
//! Constructs a progress bar, initilizes the limits to 0, and 100 with the progress at 0
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param BarColor The color of the progress bar, defaults to Blue
CProgress(const CRect& WindowRect, CWindow* pParent, CRGBColor BarColor = COLOR_BLUE);
//! Standard destructor
~CProgress() override;
//! Gets the color of the bar
//! \return The bar color
CRGBColor GetBarColor() { return m_BarColor; }
//! Set the bar color
//! \param BarColor The new bar color
void SetBarColor(CRGBColor BarColor) { m_BarColor = BarColor; }
// CWindow overrides
//! Draws the progress bar
void Draw() const override;
protected:
CRGBColor m_BarColor; //!< The color of the progress bar
private:
CProgress(const CProgress&) = delete;
CProgress& operator=(const CProgress&) = delete;
};
}
#endif // _WG_PROGRESS_H_
| 2,010
|
C++
|
.h
| 56
| 34.160714
| 90
| 0.752327
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,931
|
wg_resources.h
|
ColinPitrat_caprice32/src/gui/includes/wg_resources.h
|
// wg_resources.h
//
// wgui resources
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_RESOURCES_H_
#define _WG_RESOURCES_H_
#include "SDL.h"
#include "wg_resource_handle.h"
#include "wg_color.h"
#include "wg_application.h"
namespace wGui
{
//! The list of wGui resources
enum EwgResourceId {
// Bitmaps
WGRES_UP_ARROW_BITMAP = 1,
WGRES_DOWN_ARROW_BITMAP,
WGRES_LEFT_ARROW_BITMAP,
WGRES_RIGHT_ARROW_BITMAP,
WGRES_X_BITMAP,
WGRES_RADIOBUTTON_BITMAP,
WGRES_CHECK_BITMAP,
WGRES_MAXIMIZE_UNMAXED_BITMAP,
WGRES_MAXIMIZE_MAXED_BITMAP,
WGRES_MINIMIZE_BITMAP,
// Cursors
WGRES_POINTER_CURSOR,
WGRES_IBEAM_CURSOR,
WGRES_WAIT_CURSOR,
WGRES_MOVE_CURSOR,
WGRES_ZOOM_CURSOR
};
//! Resource handle class for the internal wGui bitmap resources
class CwgBitmapResourceHandle : public CBitmapResourceHandle
{
public:
//! CwgBitmapResourceHandles must be instantiated with a valid resource ID
//! \param application The application using the resource and that will own the handle
//! \param resId The ID of the resource which the handle will represent
CwgBitmapResourceHandle(CApplication& application, EwgResourceId resId);
private:
SDL_Surface* DrawBitmap(CRGBColor Data[], int iDataLength, int iWidth, int iHeight) const;
};
//! Resource handle class for the internal wGui string resources
class CwgStringResourceHandle : public CStringResourceHandle
{
public:
//! CwgStringResourceHandles must be instantiated with a valid resource ID
//! \param application The application using the resource and that will own the handle
//! \param resId The ID of the resource which the handle will represent
CwgStringResourceHandle(CApplication& application, EwgResourceId resId);
};
//! Resource handle class for the internal wGui cursor resources
class CwgCursorResourceHandle : public CCursorResourceHandle
{
public:
//! CwgCursorResourceHandle must be instantiated with a valid resource ID
//! \param application The application using the resource and that will own the handle
//! \param resId The ID of the resource which the handle will represent
CwgCursorResourceHandle(CApplication& application, EwgResourceId resId);
private:
enum ECursorDataMask {
O, // empty
M, // masked
D, // data
X // data and mask
};
SDL_Cursor* CreateCursor(const char DataIn[], int iDataLength, int iWidth, int iHeight, int iXHotSpot, int iYHotSpot) const;
};
}
#endif // _WG_RESOURCES_H_
| 3,180
|
C++
|
.h
| 89
| 34.044944
| 125
| 0.787227
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,932
|
CapriceVKeyboardView.h
|
ColinPitrat_caprice32/src/gui/includes/CapriceVKeyboardView.h
|
#ifndef _WG_CAPRICEVKEYBOARDVIEW_H_
#define _WG_CAPRICEVKEYBOARDVIEW_H_
#include "wg_view.h"
#include "CapriceVKeyboard.h"
using namespace wGui;
class CapriceVKeyboardView : public CView
{
protected:
CapriceVKeyboard* m_kbdFrame;
public:
CapriceVKeyboardView(CApplication& application, SDL_Surface* surface, SDL_Surface* backSurface, const CRect& WindowRect);
std::list<SDL_Event> GetEvents();
void PaintToSurface(SDL_Surface& ScreenSurface, SDL_Surface& FloatingSurface, const CPoint& Offset) const override;
};
#endif
| 547
|
C++
|
.h
| 15
| 33.666667
| 125
| 0.792381
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,933
|
wg_renderedstring.h
|
ColinPitrat_caprice32/src/gui/includes/wg_renderedstring.h
|
// wg_renderedstring.h
//
// CRenderedString interface
// CRenderedString uses the FreeType 2 library
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_RENDEREDSTRING_H_
#define _WG_RENDEREDSTRING_H_
#include "wg_fontengine.h"
#include <vector>
#include "wg_rect.h"
#include "wg_color.h"
#include "SDL.h"
#include "std_ex.h"
#include <string>
namespace wGui
{
#ifdef WIN32
#pragma warning(push)
#pragma warning(disable: 4512)
#endif // WIN32
//! For drawing a string to the screen
//! Optimized for strings that don't often change
class CRenderedString
{
public:
//! The vertical alignment of the text
enum EVAlign
{
VALIGN_NORMAL, //!< Align the text so that the baseline is the bottom
VALIGN_CENTER, //!< Align the text in the center of the drawing area
VALIGN_TOP, //!< Align the top of the tallest character with the top of the drawing area
VALIGN_BOTTOM //!< Align the bottom of the lowest character with the bottom of the drawing area
};
//! The horizontal alignment of the text
enum EHAlign
{
HALIGN_LEFT, //!< Align the text to the left of the drawing area
HALIGN_CENTER, //!< Align the text with the center of the drawing area
HALIGN_RIGHT //!< Align the text with the right of the drawing area
};
//! Construct a new CRenderedString object
//! \param pFontEngine A pointer to a CFontEngine object which is used to render the string
//! \param sString The string to render
//! \param eVertAlign The vertical alignment
//! \param eHorzAlign The horizontal alignment
CRenderedString(CFontEngine* pFontEngine, std::string sString, EVAlign eVertAlign = VALIGN_NORMAL, EHAlign eHorzAlign = HALIGN_LEFT);
//! Render the string onto the given surface
//! \param pSurface A pointer to the surface that will be drawn to
//! \param BoundingRect The CRect to clip the rendered string to
//! \param OriginPoint The origin of the string
//! \param FontColor The color to draw the string in
void Draw(SDL_Surface* pSurface, const CRect& BoundingRect, const CPoint& OriginPoint, const CRGBColor& FontColor = DEFAULT_LINE_COLOR) const;
//! Get some metrics for the rendered string
//! \param pBoundedDimensions A pointer to a CPoint object that will receive the width and height of the rendered string
//! \param pOriginOffset A pointer to a CPoint object that will receive the offset of the top left corner of the rendered string from the origin of the string
//! \param pCharacterRects A pointer to a CRect vector that will receive CRects that contain each character. The corrdinates are in reference to the top left corner of the string as a whole
void GetMetrics(CPoint* pBoundedDimensions, CPoint* pOriginOffset, std::vector<CRect>* pCharacterRects = nullptr) const;
//! Get the length of the rendered string in characters
//! \return The length of the string
unsigned int GetLength() const { return stdex::safe_static_cast<unsigned int>(m_sString.size()); }
//! Get the maximum height of the font, ASCII characters 0-255
//! \return The max height of the font
unsigned int GetMaxFontHeight();
// judb
unsigned int GetMaxFontWidth();
// judb return the width of the given string when rendered in the engine's font
unsigned int GetWidth(std::string sText);
//! Set the mask character
//! \param MaskChar Character to use as the mask
void SetMaskChar(char MaskChar) { m_MaskChar = MaskChar; }
protected:
CFontEngine* m_pFontEngine; //!< A pointer to the font engine
std::string m_sString; //!< The string to be rendered
char m_MaskChar; //!< Character tp use as the mask, used for passwords and such
private:
EVAlign m_eVertAlign; //!< The vertical alignment
EHAlign m_eHorzAlign; //!< The horizontal alignment
mutable CPoint m_CachedBoundedDimensions; //!< The cached value of the rendered string's dimensions
mutable CPoint m_OriginOffset; //!< The cached value of the string's offset from the origin
mutable std::vector<CRect> m_CachedCharacterRects; //!< The cached value of the CRects for the various characters
mutable bool m_bCachedMetricsValid; //!< A boolean indicating if the cached values are valid
int m_MaxFontHeight; //!< Maximum height of any character with ASCII value 0-255 for the current font
int m_MaxFontWidth; //!< Maximum widht of any character with ASCII value 0-255 for the current font
};
#ifdef WIN32
#pragma warning(pop)
#endif // WIN32
}
#endif // _WG_RENDEREDSTRING_H_
| 5,173
|
C++
|
.h
| 107
| 46.514019
| 191
| 0.763633
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,934
|
wg_tooltip.h
|
ColinPitrat_caprice32/src/gui/includes/wg_tooltip.h
|
// wg_tooltip.h
//
// CToolTip interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_TOOLTIP_H_
#define _WG_TOOLTIP_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_renderedstring.h"
#include "wg_application.h"
#include "wg_timer.h"
#include <string>
#include <memory>
namespace wGui
{
//! A tooltip that can pop up over windows
//! They are attached to an existing CWindow object, and watch for the mouse cursor to stop over the object. When the cursor stops, the tooltip makes itself visible.
class CToolTip : public CWindow
{
public:
//! Construct a new label
//! \param pToolWindow A pointer to the CWindow based object the tooltip is for
//! \param sText The label text
//! \param FontColor The color of the tooltip text
//! \param BackgroundColor The color of the tooltip's background
//! \param pFontEngine A pointer to the font engine to use when drawing the tooltip
//! If this is left out (or set to 0) it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CToolTip(CWindow* pToolWindow, std::string sText,
CRGBColor& FontColor = DEFAULT_LINE_COLOR, CRGBColor& BackgroundColor = COLOR_WHITE, CFontEngine* pFontEngine = nullptr);
//! Standard destructor
~CToolTip() override;
//! Displays the tooltip
//! \param DrawPoint Where to poisition the top left corner of the tooltip, in view coordinates
void ShowTip(const CPoint& DrawPoint);
//! Hides the tooltip
void HideTip();
// CWindow overrides
//! Renders the Window Text, and clips to the Window Rect
void Draw() const override;
//! Move the window and any child windows
//! \param MoveDistance The relative distance to move the window
void MoveWindow(const CPoint& MoveDistance) override;
//! Blit the window to the given surface, using m_WindowRect as the offset into the surface
//! \param ScreenSurface A reference to the surface that the window will be copied to
//! \param FloatingSurface A reference to the floating surface which is overlayed at the very end (used for tooltips, menus and such)
//! \param Offset This is the current offset into the Surface that should be used as reference
void PaintToSurface(SDL_Surface& ScreenSurface, SDL_Surface& FloatingSurface, const CPoint& Offset) const override;
// CMessageClient overrides
//! CTooltips handle MOUSE_MOVE and CTRL_TIMER messages
//! \param pMessage A pointer to the message
bool HandleMessage(CMessage* pMessage) override;
protected:
CFontEngine* m_pFontEngine; //!< A pointer to the font engine to use to render the text
std::unique_ptr<CRenderedString> m_pRenderedString; //!< An autopointer to the rendered version of the string
CRGBColor m_FontColor; //!< The font color
CWindow* m_pToolWindow; //!< A pointer to the CWindow based object the tooltip is for
CTimer* m_pTimer; //!< A pointer to a timer so that tooltips only appear after the mouse has been motionless for a bit
CPoint m_LastMousePosition; //!< The last mouse position
CRect m_BoundingRect; //!< A CRect that bounds the text
private:
CToolTip(const CToolTip&) = delete;
CToolTip& operator=(const CToolTip&) = delete;
};
}
#endif // _WG_TOOLTIP_H_
| 3,973
|
C++
|
.h
| 83
| 46.084337
| 166
| 0.766227
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,935
|
wg_radiobutton.h
|
ColinPitrat_caprice32/src/gui/includes/wg_radiobutton.h
|
// wg_radiobutton.h
//
// CRadioButton interface
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_RADIOBUTTON_H_
#define _WG_RADIOBUTTON_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_resources.h"
namespace wGui
{
//! A radiobutton control
//! Radiobuttons should share a common parent (preferably a CGroupBox :-)) so they work as expected (only one can be
//! checked at a time)
//! The radiobutton will generate CTRL_xCLICK messages when clicked with the mouse (where x is the button L,M,R)
//! It will also generate a CTRL_VALUECHANGE message whenever the radiobutton is toggled (todo adopt for radiobutton)
//! Radiobuttons do not display their own labels
class CRadioButton : public CWindow
{
public:
//! Constructs a new radiobutton
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
CRadioButton(const CPoint& p, int size, CWindow* pParent);
//! Standard destructor
~CRadioButton() override;
//! The radiobutton state(s)
enum EState {
UNCHECKED, //!< The radiobutton is unchecked
CHECKED, //!< The radiobutton is checked
DISABLED //!< The radiobutton is disabled
};
//! Gets the current state of the radiobutton
//! \return The current radiobutton state
EState GetState() const { return m_eRadioButtonState; }
//! Set the radiobutton state
//! \param eState The radiobutton state
void SetState(EState eState);
//! Check this radiobutton and uncheck all its siblings
void Select();
// CWindow overrides
//! Draws the radiobutton
void Draw() const override;
//! This is called whenever the radiobutton is clicked on by the mouse
//! Only the topmost window that bounds the point will be called by the system
//! \param Point The point where the mouse clicked
//! \param Button A bitfield indicating which button the window was clicked with
//! \return True if it's in the bounds of the radiobutton
bool OnMouseButtonDown(CPoint Point, unsigned int Button) override;
//! This is called whenever the a mouse button is released in the radiobutton
//! Only the topmost window that bounds the point will be called by the system
//! \param Point The point where the mouse clicked
//! \param Button A bitfield indicating which button the window was clicked with
//! \return True if it's in the bounds of the radiobutton
bool OnMouseButtonUp(CPoint Point, unsigned int Button) override;
// CMessageClient overrides
//! CRadioButtons handle MOUSE_BUTTONDOWN, MOUSE_BUTTONUP, and it's own CTRL_SINGLELCLICK messages
//! \param pMessage A pointer to the message
bool HandleMessage(CMessage* pMessage) override;
protected:
EState m_eRadioButtonState; //!< The radiobutton's state
unsigned int m_MouseButton; //!< The last mouse button to be pushed over the control, it's used internally
CBitmapResourceHandle m_hBitmapRadioButton; // radiobutton (black dot if selected) defined as a bitmap resource.
private:
CRadioButton(const CRadioButton&) = delete;
CRadioButton& operator=(const CRadioButton&) = delete;
};
}
#endif // _WG_RADIOBUTTON_H_
| 3,810
|
C++
|
.h
| 83
| 43.975904
| 117
| 0.768151
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,936
|
CapriceLeavingWithoutSavingView.h
|
ColinPitrat_caprice32/src/gui/includes/CapriceLeavingWithoutSavingView.h
|
#ifndef _WG_CAPRICELEAVINGWITHOUTSAVINGVIEW_H_
#define _WG_CAPRICELEAVINGWITHOUTSAVINGVIEW_H_
#include "wg_view.h"
#include "wg_messagebox.h"
using namespace wGui;
class CapriceLeavingWithoutSavingView : public CView
{
protected:
wGui::CMessageBox *m_pMessageBox;
bool confirmed = false;
public:
CapriceLeavingWithoutSavingView(CApplication& application, SDL_Surface* surface, SDL_Surface* backSurface, const CRect& WindowRect);
bool Confirmed() const;
void PaintToSurface(SDL_Surface& ScreenSurface, SDL_Surface& FloatingSurface, const CPoint& Offset) const override;
bool HandleMessage(CMessage* pMessage) override;
};
#endif
| 664
|
C++
|
.h
| 17
| 35.941176
| 136
| 0.799687
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,937
|
wg_painter.h
|
ColinPitrat_caprice32/src/gui/includes/wg_painter.h
|
// wg_painter.h
//
// CPainter class which provides useful graphics routines
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_GRAPHICS_H_
#define _WG_GRAPHICS_H_
#include "wg_rect.h"
#include "wg_color.h"
#include "wg_point.h"
#include "wg_window.h"
#include "SDL.h"
namespace wGui
{
//! Painter objects take care of all the actual drawing functions needed to draw to an SDL surface
class CPainter
{
public:
//! A mode for painting the surface can be specified
//! currently this does not work for the DrawHLine, DrawVLine, or DrawRect methods
enum EPaintMode {
PAINT_IGNORE = 0, //!< Don't actually draw anything
PAINT_REPLACE, //!< Replace the pixel with the new pixel
PAINT_NORMAL, //!< Do normal color mixing (uses the alpha channel)
PAINT_OR, //!< OR the new color in
PAINT_AND, //!< AND the new color in
PAINT_XOR, //!< XOR the new color in
PAINT_ADDITIVE //!< Use Additive color mixing
};
//! Construct a new Painter object
//! \param pSurface A pointer to the SDL surface to draw to
//! \param ePaintMode The painting mode to use, defaults to PAINT_NORMAL
CPainter(SDL_Surface* pSurface, EPaintMode ePaintMode = PAINT_NORMAL);
//! Construct a new Painter object
//! \param pWindow A pointer to the CWindow to draw to, this will only allow drawing to the window's client area
//! \param ePaintMode The painting mode to use, defaults to PAINT_NORMAL
CPainter(CWindow* pWindow, EPaintMode ePaintMode = PAINT_NORMAL);
//! Standard destructor
virtual ~CPainter() = default;
//! Draw a horizontal line
//! \param xStart The start position of the line
//! \param xEnd The end position of the line
//! \param y The vertical location of the line
//! \param LineColor The color of the line
void DrawHLine(int xStart, int xEnd, int y, const CRGBColor& LineColor = DEFAULT_LINE_COLOR);
//! Draw a vertical line
//! \param yStart The start position of the line
//! \param yEnd The end position of the line
//! \param x The horizontal location of the line
//! \param LineColor The color of the line
void DrawVLine(int yStart, int yEnd, int x, const CRGBColor& LineColor = DEFAULT_LINE_COLOR);
//! Draw a rectangle (this has been optimized to work much faster for filled rects in PAINT_REPLACE mode)
//! \param Rect A CRect that describes the rectangle
//! \param bFilled If true, rectangle will be filled with the FillColor, otherwise only the border is drawn
//! \param BorderColor The color for the border
//! \param FillColor The color to fill the rectangle with
void DrawRect(const CRect& Rect, bool bFilled, const CRGBColor& BorderColor = DEFAULT_LINE_COLOR,
const CRGBColor& FillColor = DEFAULT_FOREGROUND_COLOR);
// judb draw a 'raised button' border based on the given color
void Draw3DRaisedRect(const CRect& Rect, const CRGBColor& Color);
// judb draw a 'lowered button' border based on the given color
void Draw3DLoweredRect(const CRect& Rect, const CRGBColor& Color);
//! Draw a line between two points
//! \param StartPoint The beginning point of the line
//! \param EndPoint The end point of the line
//! \param LineColor The color to use for drawing the line
void DrawLine(const CPoint& Point1, const CPoint& Point2, const CRGBColor& LineColor = DEFAULT_LINE_COLOR);
// judb draw a box (filled)
void DrawBox(CPoint UpperLeftPoint, int width, int height, const CRGBColor& LineColor);
//! Draw a pixel
//! \param Point The location of the pixel to set
//! \param PointColor The color to set the pixel to
void DrawPoint(const CPoint& Point, const CRGBColor& PointColor = DEFAULT_LINE_COLOR);
//! Get the color of the pixel at the given point
//! \param Point The location of the pixel to read
//! \return A CRGBColor object representing the color of the pixel
CRGBColor ReadPoint(const CPoint& Point);
//! Replace all pixels of a certain color with a new color
//! \param NewColor The color value to replace the pixels with
//! \param OldColor The color of the pixels to be replaced
void ReplaceColor(const CRGBColor& NewColor, const CRGBColor& OldColor);
//! Sets the transparent pixel
//! \param TransparentColor The pixel color to be treated as transparent
void TransparentColor(const CRGBColor& TransparentColor);
protected:
//! Locks the SDL surface
void LockSurface();
//! Unlocks the SDL surface
void UnlockSurface();
//! Mixes thje two colors based on the painting mode
//! \param ColorBase The color to use as the base
//! \param ColorAdd The color to add to the base
//! \return A CRGBColor object representing the mixed colors
CRGBColor MixColor(const CRGBColor& ColorBase, const CRGBColor& ColorAdd);
SDL_Surface* m_pSurface; //!< A pointer to the SDL Surface to draw on
CWindow* m_pWindow; //!< A pointer to the CWindow to draw to
EPaintMode m_PaintMode; //!< The painting mode to use
};
}
#endif // _WG_GRAPHICS_H_
| 5,647
|
C++
|
.h
| 117
| 46.153846
| 113
| 0.751818
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,938
|
wg_range_control.h
|
ColinPitrat_caprice32/src/gui/includes/wg_range_control.h
|
// wg_range_control.h
//
// CRangeControl interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_RANGE_CONTROL_H_
#define _WG_RANGE_CONTROL_H_
#include "wg_window.h"
#include "wg_application.h"
namespace wGui
{
//! A template class that handles all the basics of a control that uses a value that is constrained to a certain range
//! Sends a CTRL_VALUECHANGE message whenever the value changes
template<typename T>
class CRangeControl : public CWindow
{
public:
//! Constructs a range control
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param minLimit The minimum limit for the control
//! \param maxLimit The maximum limit for the control
//! \param stepSize The amount to increase/decrease the value by for Increment and Decrement
//! \param defaultValue The amount to initialize the value to
CRangeControl(const CRect& WindowRect, CWindow* pParent, T minLimit, T maxLimit, T stepSize, T defaultValue) :
CWindow(WindowRect, pParent), m_MinLimit(minLimit), m_MaxLimit(maxLimit), m_StepSize(stepSize), m_Value(defaultValue) { }
//! Set the lower limit for the control
//! \param minLimit The lower limit of the control
virtual void SetMinLimit(T minLimit) { m_MinLimit = minLimit; }
//! Gets the lower limit of the control
//! \return The minimum limit of the control
virtual T GetMinLimit() const { return m_MinLimit; }
//! Set the upper limit for the control
//! \param maxLimit The upper limit of the control
virtual void SetMaxLimit(T maxLimit) { m_MaxLimit = maxLimit; }
//! Gets teh upper limit of the control
//! \return The maximum limit of the control
virtual T GetMaxLimit() const { return m_MaxLimit; }
//! Set the current step size.
//! \param stepSize The amount to increment the value by for Increment() and Decrement() calls
virtual void SetStepSize(T stepSize) { m_StepSize = stepSize; }
//! Gets the current step size of the control
//! \return The current step size
virtual T GetStepSize() const { return m_StepSize; }
//! Set the current value.
//! \param value The new value for the control
//! \param bRedraw indicates if the control should be redrawn (defaults to true)
virtual void SetValue(T value, bool bRedraw = true, bool bNotify = true)
{
m_Value = ConstrainValue(value);
if (bNotify)
{
Application().MessageServer()->QueueMessage(new CValueMessage<T>(CMessage::CTRL_VALUECHANGE, m_pParentWindow, this, m_Value));
}
if (bRedraw)
{
Draw();
}
}
//! Gets the current value of the control
//! \return The current value
virtual T GetValue() const { return m_Value; }
//! Increase the value by one step size
//! \param bRedraw indicates if the control should be redrawn (defaults to true)
virtual void Increment(bool bRedraw = true) { SetValue(m_Value + m_StepSize, bRedraw); }
//! Decrease the value by one step size
//! \param bRedraw indicates if the control should be redrawn (defaults to true)
virtual void Decrement(bool bRedraw = true) { SetValue(m_Value - m_StepSize, bRedraw); }
//! takes the value and makes sure it's in it's limits
//! \param value The value to be checked
//! \return The closest value that's within the limits
virtual T ConstrainValue(T value) const
{
if (value < m_MinLimit)
{
value = m_MinLimit;
}
if (value > m_MaxLimit)
{
value = m_MaxLimit;
}
return value;
}
protected:
T m_MinLimit; //!< The minimum value of the control
T m_MaxLimit; //!< The maximum value of the control
T m_StepSize; //!< The step size of the control
T m_Value; //!< The current value of the control
private:
CRangeControl(const CRangeControl&) = delete;
CRangeControl& operator=(const CRangeControl&) = delete;
};
}
#endif // _WG_RANGE_CONTROL_H_
| 4,567
|
C++
|
.h
| 111
| 39.018018
| 129
| 0.742154
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,939
|
wg_groupbox.h
|
ColinPitrat_caprice32/src/gui/includes/wg_groupbox.h
|
// wg_groupbox.h
//
// CGroupBox interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_GROUPBOX_H_
#define _WG_GROUPBOX_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_renderedstring.h"
#include "wg_application.h"
#include <string>
#include <memory>
namespace wGui
{
//! A GroupBox is really just a fancier label that includes a box
class CGroupBox : public CWindow
{
public:
//! Construct a new group box
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param sText The label text
//! \param FontColor The color of the label text
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is left out (or set to 0) it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CGroupBox(const CRect& WindowRect, CWindow* pParent, std::string sText,
CRGBColor& FontColor = ALTERNATE_TEXT_COLOR, CFontEngine* pFontEngine = nullptr);
//! Standard destructor
~CGroupBox() override;
//! Sets the color of the font used to render the label
//! \param FontColor The color of the label text
void SetFontColor(CRGBColor& FontColor) { m_FontColor = FontColor; }
//! Gets the font color for the label od the group box
//! \return The color of the text in the label
CRGBColor GetFontColor() { return m_FontColor; }
// CWindow overrides
//! Renders the Window Text, and clips to the Window Rect
void Draw() const override;
//! Set the WindowText of the label
//! \param sWindowText The text to assign to the window
void SetWindowText(const std::string& sWindowText) override;
//! Giving a control a new WindowRect will move and resize the control
//! \param WindowRect A CRect that defines the outer limits of the control
void SetWindowRect(const CRect& WindowRect) override;
// CMessageClient overrides
//! CGroupBox will forward keyboard events to its parent
//! \param pMessage A pointer to the message that needs to be handled
bool HandleMessage(CMessage* pMessage) override;
protected:
CFontEngine* m_pFontEngine; //!< A pointer to the font engine to use to render the text
std::unique_ptr<CRenderedString> m_pRenderedString; //!< An autopointer to the rendered version of the string
CRGBColor m_FontColor; //!< The font color
private:
CGroupBox(const CGroupBox&) = delete;
CGroupBox& operator=(const CGroupBox&) = delete;
};
}
#endif // _WG_GROUPBOX_H_
| 3,275
|
C++
|
.h
| 76
| 41.328947
| 157
| 0.76195
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,940
|
wg_label.h
|
ColinPitrat_caprice32/src/gui/includes/wg_label.h
|
// wg_label.h
//
// CLabel interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_LABEL_H_
#define _WG_LABEL_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_renderedstring.h"
#include "wg_application.h"
#include <string>
#include <memory>
namespace wGui
{
//! A static label that renders it's WindowText to the screen
class CLabel : public CWindow
{
public:
//! Construct a new label
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param sText The label text, defaults to an empty string
//! \param FontColor The color of the label text, defaults to the DEFAULT_LINE_COLOR
//! \param pFontEngine A pointer to the font engine to use when drawing the control, defaults to 0
//! If this is left out (or set to 0) it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CLabel(const CRect& WindowRect, CWindow* pParent, std::string sText = "",
CRGBColor& FontColor = DEFAULT_TEXT_COLOR, CFontEngine* pFontEngine = nullptr);
// judb constructor using a reference point (upper-left corner)
CLabel(const CPoint& point, CWindow* pParent, std::string sText = "",
CRGBColor& FontColor = DEFAULT_TEXT_COLOR, CFontEngine* pFontEngine = nullptr);
//! Standard destructor
~CLabel() override;
//! Sets the color of the font used to render the label
//! \param FontColor The color of the label text
void SetFontColor(CRGBColor& FontColor) { m_FontColor = FontColor; }
//! Gets the font color for the label
//! \return The color of the text in the label
CRGBColor GetFontColor() { return m_FontColor; }
// CWindow overrides
//! Renders the Window Text, and clips to the Window Rect
void Draw() const override;
//! Set the WindowText of the label
//! \param sWindowText The text to assign to the window
void SetWindowText(const std::string& sWindowText) override;
protected:
CFontEngine* m_pFontEngine; //!< A pointer to the font engine to use to render the text
std::unique_ptr<CRenderedString> m_pRenderedString; //!< An autopointer to the rendered version of the string
CRGBColor m_FontColor; //!< The font color
private:
CLabel(const CLabel&) = delete;
CLabel& operator=(const CLabel&) = delete;
};
}
#endif // _WG_LABEL_H_
| 3,111
|
C++
|
.h
| 72
| 41.347222
| 157
| 0.753316
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,941
|
wg_message.h
|
ColinPitrat_caprice32/src/gui/includes/wg_message.h
|
// wg_message.h
//
// CMessage interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_MESSAGE_H_
#define _WG_MESSAGE_H_
#include "wg_point.h"
#include "wg_rect.h"
#include "SDL.h"
#include <string>
namespace wGui
{
// Forward declarations
class CMessageClient;
//! The base message class
//! wGui uses Message object to inform other objects of events.
//! \sa CMessageServer CMessageClient
class CMessage
{
public:
//! The various message types
enum EMessageType
{
UNKNOWN = 0, //!< An unknown message, this is not a valid type
APP_DESTROY_FRAME, //!< CMessage used to delete frame objects, where Source() is the frame that is to be deleted, Destination() should be 0
APP_EXIT, //!< CMessage used to tell controls or windows that the application is closing
APP_PAINT, //!< CMessage used to tell controls or windows to redraw themselves
CTRL_DOUBLELCLICK, //!< TIntMessage generated when a control is double clicked with the left mouse button
CTRL_DOUBLEMCLICK, //!< TIntMessage generated when a control is double clicked with the middle mouse button
CTRL_DOUBLERCLICK, //!< TIntMessage generated when a control is double clicked with the right mouse button
CTRL_GAININGKEYFOCUS, //!< CMessage used to tell a control that it's getting the keyboard focus
CTRL_GAININGMOUSEFOCUS, //!< CMessage used to tell a control that it's getting the mouse focus
CTRL_LOSINGKEYFOCUS, //!< CMessage used to tell a control that it's losing the keyboard focus
CTRL_LOSINGMOUSEFOCUS, //!< CMessage used to tell a control that it's losing the mouse focus
CTRL_MESSAGEBOXRETURN, //!< CValueMessage sent when a CMessageBox closes
CTRL_RESIZE, //!< TPointMessage used to tell the app that the view has been resized
CTRL_SINGLELCLICK, //!< TIntMessage generated when a control is clicked on with the left mouse button
CTRL_SINGLEMCLICK, //!< TIntMessage generated when a control is clicked on with the middle mouse button
CTRL_SINGLERCLICK, //!< TIntMessage generated when a control is clicked on with the right mouse button
CTRL_TIMER, //!< TIntMessage used to tell when a timer has expired, where Value() is the count of times fired
CTRL_VALUECHANGE, //!< CValueMessage generated when a control's text or value is changed via user input
CTRL_VALUECHANGING, //!< CValueMessage generated when a control's text or value is in the process of changing via user input
KEYBOARD_KEYDOWN, //!< CKeyboardMessage generated when a keyboard key is pressed
KEYBOARD_KEYUP, //!< CKeyboardMessage generated when a keyboard key is released
TEXTINPUT, //!< CTextInput generated when text is typed in a field that supports it
MOUSE_BUTTONDOWN, //!< CMouseMessage generated when a mouse button is pressed
MOUSE_BUTTONUP, //!< CMouseMessage generated when a mouse button is released
MOUSE_MOVE, //!< CMouseMessage generated when a mouse is moved
SDL, //!< An unhandled SDL event
USER //!< Any user defined messages of type CUserMessage
};
//! Construct a new message
//! \param MessageType The type of message being created
//! \param pDestination A pointer to the window that the message is destined for (0 for no specific destination, or to broadcast to all)
//! \param pSource A pointer to the source of the message
CMessage(const EMessageType MessageType, const CMessageClient* pDestination, const CMessageClient* pSource);
//! Standard destructor
virtual ~CMessage() = default;
//! Gets the message type
//! \return The message type of the message
EMessageType MessageType() { return m_MessageType; }
//! Return the string representation of a message type.
//! \return The string corresponding to the enum name.
static std::string ToString(EMessageType message_type);
//! Gets the intended destination for the message
//! \return A pointer to the destination of the message (0 for no specific destination, or to broadcast to all)
const CMessageClient* Destination() { return m_pDestination; }
//! Gets the source of the message
//! \return A pointer to the source of the message
const CMessageClient* Source() { return m_pSource; }
protected:
//! The message type
const EMessageType m_MessageType;
//! A pointer to the message destination (0 for no specific destination, or to broadcast to all)
const CMessageClient* m_pDestination;
//! A pointer to the control that generated the message
const CMessageClient* m_pSource;
private:
CMessage(const CMessage&) = delete;
CMessage& operator=(const CMessage&) = delete;
};
//! Any otherwise unhandled SDL messages
class CSDLMessage : public CMessage
{
public:
//! Construct a new SDL message
//! \param MessageType The type of message being created
//! \param pDestination A pointer to the window that the message is destined for (0 for no specific destination, or to broadcast to all)
//! \param pSource A pointer to the window that created the message
//! \param SDLEvent The untranslated SDL event
CSDLMessage(const EMessageType MessageType, const CMessageClient* pDestination, const CMessageClient* pSource, SDL_Event SDLEvent);
SDL_Event SDLEvent; //!< The untranslated SDL event
};
//! Any messages generated from keyboard input
class CKeyboardMessage : public CMessage
{
public:
//! Construct a new Keyboard message
//! \param MessageType The type of message being created
//! \param pDestination A pointer to the window that the message is destined for (0 for no specific destination, or to broadcast to all)
//! \param pSource A pointer to the window that created the message
//! \param ScanCode The scan code of the key pressed
//! \param Modifiers Any modifier keys that are being pressed (alt, ctrl, shift, etc)
//! \param Key The SDL_Keysym that defines the key pressed
CKeyboardMessage(const EMessageType MessageType, const CMessageClient* pDestination, const CMessageClient* pSource,
unsigned char ScanCode, SDL_Keymod Modifiers, SDL_Keycode Key);
unsigned char ScanCode; //!< The scan code of the key pressed
SDL_Keymod Modifiers; //!< Any modifier keys that are being pressed (alt, ctrl, shift, etc)
SDL_Keycode Key; //!< The SDL_Keysym that defines the key pressed
};
//! Any messages generated by text input
class CTextInputMessage : public CMessage
{
public:
//! Construct a new TextInput message
//! \param MessageType The type of message being created
//! \param pDestination A pointer to the window that the message is destined for (0 for no specific destination, or to broadcast to all)
//! \param pSource A pointer to the window that created the message
//! \param Text The text being typed.
CTextInputMessage(const EMessageType MessageType, const CMessageClient* pDestination, const CMessageClient* pSource,
std::string Text);
std::string Text; //!< The Text that has been typed
};
//! Any messages generated from mouse input
class CMouseMessage : public CMessage
{
public:
//! Constants for all the mouse buttons, these values can be ORed together for more than one button
enum EMouseButton
{
NONE = 0, //!< No mouse button
LEFT = 1, //!< The left mouse button
RIGHT = 2, //!< The right mouse button
MIDDLE = 4, //!< The middle mouse button
WHEELUP = 8, //!< The mouse wheel moved up
WHEELDOWN = 16 //!< The mouse wheel moved down
};
//! Construct a new mouse message
//! \param MessageType The type of message being created
//! \param pDestination A pointer to the window that the message is destined for (0 for no specific destination, or to broadcast to all)
//! \param pSource A pointer to the window that created the message
//! \param Point The location of the mouse cursor
//! \param Relative The relative movement of the cursor (only valid for MOUSE_MOVE messages)
//! \param Button An OR of all the EMouseButton values indicating which mouse buttons are pressed
CMouseMessage(const EMessageType MessageType, const CMessageClient* pDestination, const CMessageClient* pSource,
CPoint Point, CPoint Relative, unsigned int Button);
//! Converst an SDLButton value into an EMouseButton value
static unsigned int TranslateSDLButton(Uint8 SDLButton);
//! Converts an SDLButtonState value into an ORing of EMouseButton values
static unsigned int TranslateSDLButtonState(Uint8 SDLButtonState);
CPoint Point; //!< The point where the mouse cursor was at the time of the message
CPoint Relative; //!< The relative movement of the cursor (only valid for MOUSE_MOVE messages)
unsigned int Button; //!< Any mouse buttons pressed
};
//! A template for messages that contain values
//! Type T must have a valid copy constructor and assignment operator
template<typename T>
class CValueMessage : public CMessage
{
public:
//! Construct a new template based Value message
//! \param MessageType The type of message being created
//! \param pDestination A pointer to the window that the message is destined for (0 for no specific destination, or to broadcast to all)
//! \param pSource A pointer to the control that triggered the message
//! \param Value A template type data the user has
CValueMessage(const EMessageType MessageType, const CMessageClient* pDestination, const CMessageClient* pSource, T Value ) :
CMessage(MessageType, pDestination, pSource),
m_Value(std::move(Value))
{ }
//! Returns the value of the message
//! \return A constant reference to the internal value
const T& Value() { return m_Value; }
//! Sets the value of the message
//! \param Value The value
void SetValue(const T& Value) { m_Value = Value; }
protected:
//! The internal value
T m_Value;
};
//! Some predefined value messages
using TIntMessage = CValueMessage<int>;
using TFloatMessage = CValueMessage<float>;
using TDoubleMessage = CValueMessage<double>;
using TStringMessage = CValueMessage<std::string>;
using TPointMessage = CValueMessage<CPoint>;
using TRectMessage = CValueMessage<CRect>;
}
#endif // _WG_MESSAGE_H_
| 10,665
|
C++
|
.h
| 206
| 49.694175
| 141
| 0.767945
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,942
|
wg_editbox.h
|
ColinPitrat_caprice32/src/gui/includes/wg_editbox.h
|
// wg_editbox.h
//
// CEditBox interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_EDITBOX_H_
#define _WG_EDITBOX_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_renderedstring.h"
#include "wg_timer.h"
#include "wg_resources.h"
#include <memory>
#include <string>
namespace wGui
{
//! A simple edit box control
//! The CEditBox will generate CTRL_VALUECHANGE messages every time the text changes
class CEditBox : public CWindow
{
public:
//! Construct a new Edit control
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param pFontEngine A pointer to the font engine to use when drawing the control
//! If this is left out (or set to 0) it will use the default font engine specified by the CApplication (which must be set before instantiating this object)
CEditBox(const CRect& WindowRect, CWindow* pParent, CFontEngine* pFontEngine = nullptr);
//! Standard destructor
~CEditBox() override;
//! The content allowed
enum EContentType {
ANY, //!< Any char allowed
NUMBER, //!< Only numbers
HEXNUMBER, //!< Numbers and char [A-F]
ALPHA, //!< Only letters
ALPHANUM //!< Letters and digits
};
//! Set the Password mask state of the control
//! \param bUseMask If set to true, the control will act as a password mask box
void SetUsePasswordMask(bool bUseMask) { m_bUseMask = bUseMask; }
//! Indicates if the edit box is using a password mask
//! \return true if the control is a password box
bool UsingPasswordMask() const { return m_bUseMask; }
//! Set the Read-only state of the control
//! \param bReadOnly If set to true, the control will not take any keyboard input
void SetReadOnly(bool bReadOnly);
//! Indicates if the edit box is operating in read-only mode
//! \return true if the control is read-only
bool IsReadOnly() const { return m_bReadOnly; }
//! Gets the currently selected text
//! \return The currently selected text in the edit box, if the edit box is in Password Mask mode, this will always return an empty string
std::string GetSelText() const;
//! Set the selection
//! \param iSelStart The index of the start of the selection
//! \param iSelLength The number of characters selected
void SetSelection(std::string::size_type iSelStart, int iSelLength);
//! Gets the starting index of the selection
//! \return The index of the start of the selection
virtual std::string::size_type GetSelectionStart() const { return m_SelStart; }
//! Gets the length of the selection
//! \return The length of the selection
virtual int GetSelectionLength() const { return m_SelLength; }
//! Gets a character index from a point
//! \param Point The point (in window coordinates)
//! \return The index (in characters) of the point in the string
virtual std::string::size_type GetIndexFromPoint(const CPoint& Point) const;
// CWindow overrides
//! Renders the text contents of a control, and the cursor
void Draw() const override;
//! Set the WindowText of the control
//! \param sText The text to assign to the window
void SetWindowText(const std::string& sText) override;
//! This is called whenever the editbox is clicked on by the mouse
//! Only the topmost window that bounds the point will be called by the system
//! \param Point The point where the mouse clicked
//! \param Button A bitfield indicating which button the window was clicked with
//! \return True if it's in the bounds of the editbox
bool OnMouseButtonDown(CPoint Point, unsigned int Button) override;
// CMessageClient overrides
//! CEditBox will handle MOUSE_BUTTONDOWN and KEYBOARD_KEYDOWN messages
//! \param pMessage A pointer to the message that needs to be handled
bool HandleMessage(CMessage* pMessage) override;
void SetContentType(EContentType ctype) { m_contentType = ctype; };
protected:
//! Deletes the selected portion of the string
//! \internal
//! \param psString A pointer to the buffer
void SelDelete(std::string* psString);
CFontEngine* m_pFontEngine; //!< A pointer to the font engine to use to render the text
std::unique_ptr<CRenderedString> m_pRenderedString; //!< An autopointer to the rendered version of the string
std::string::size_type m_SelStart; //!< Selection start point, in characters
int m_SelLength; //!< Selection length, in characters
std::string::size_type m_DragStart; //!< The position where the draw started
mutable int m_ScrollOffset; //!< The offset of the left side of the string, used for scrolling in the edit box
bool m_bReadOnly; //!< If true, the text of the control cannot be changed
bool m_bMouseDown; //!< Set to true when the mouse button goes down
bool m_bUseMask; //!< Set to true if you want the edit box to act as a password box and have a mask of asterikses
bool m_bLastMouseMoveInside; //!< True if the cursor was inside the control on the last MOUSE_MOVE message
EContentType m_contentType;
private:
CEditBox(const CEditBox&) = delete;
CEditBox& operator=(const CEditBox&) = delete;
bool m_bDrawCursor;
CTimer* m_pDblClickTimer; //!< Timer to decide if we've double clicked or not.
CTimer* m_pCursorTimer; //!< Timer to blink the cursor
};
}
#endif // _WG_EDITBOX_H_
| 6,017
|
C++
|
.h
| 125
| 46.032
| 157
| 0.75273
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,943
|
wg_picture.h
|
ColinPitrat_caprice32/src/gui/includes/wg_picture.h
|
// wg_picture.h
//
// CPicture interface
//
//
// Copyright (c) 2002-2004 Rob Wiskow
// [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef _WG_PICTURE_H_
#define _WG_PICTURE_H_
#include "wg_window.h"
#include "wg_painter.h"
#include "wg_resource_handle.h"
#include <string>
namespace wGui
{
//! A picture control
//! Will take a picture file and display it
//! The CPicture control does not do any sort of resizing, but it will clip the picture to the client rect
class CPicture : public CWindow
{
public:
//! Constructs a new picture control
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param sPictureFile The picture resource, must be a bitmap (.bmp)
//! \param bDrawBorder If true, it will draw a border around the picture, defaults to false
//! \param BorderColor The color to use when drawing the border
CPicture(const CRect& WindowRect, CWindow* pParent, const std::string& sPictureFile,
bool bDrawBorder = false, const CRGBColor& BorderColor = DEFAULT_LINE_COLOR);
//! Constructs a new picture control
//! \param WindowRect A CRect that defines the outer limits of the control
//! \param pParent A pointer to the parent window
//! \param hBitmap A handle for the bitmap resource
//! \param bDrawBorder If true, it will draw a border around the picture, defaults to false
//! \param BorderColor The color to use when drawing the border
CPicture(const CRect& WindowRect, CWindow* pParent, const CBitmapResourceHandle& hBitmap,
bool bDrawBorder = false, const CRGBColor& BorderColor = DEFAULT_LINE_COLOR);
//! Standard destructor
~CPicture() override;
// CWindow overrides
//! Draws the button and renders the button label
void Draw() const override;
//! Giving a control a new WindowRect will move and resize the control
//! \param WindowRect A CRect that defines the outer limits of the control
void SetWindowRect(const CRect& WindowRect) override;
protected:
bool m_bDrawBorder; //!< The color to use when drawing the border
CRGBColor m_BorderColor; //!< The color to use when drawing the border
CBitmapResourceHandle m_hBitmap; //!< A handle for the bitmap resource
private:
CPicture(const CPicture&) = delete;
CPicture& operator=(const CPicture&) = delete;
};
}
#endif // _WG_PICTURE_H_
| 3,059
|
C++
|
.h
| 70
| 41.9
| 106
| 0.762546
|
ColinPitrat/caprice32
| 146
| 32
| 52
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
753,944
|
modele.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/modele.cc
|
#include "modele.hpp"
#include "mxml.hpp"
#include "cutil.hpp"
#include "templates/modele-private.hpp"
#include <iostream>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <sstream>
#include <locale>
#include <assert.h>
using namespace std;
using namespace utils;
#ifdef LINUX
#ifdef putc
#undef putc
#endif
#endif
namespace utils
{
namespace model
{
journal::Logable NodeSchema::log("model");
static journal::Logable log("model");
journal::Logable NodePatron::log("model");
journal::Logable AttributeSchema::log("model");
journal::Logable Attribute::log("model");
bool NodeSchema::is_empty() const
{
if(attributes.size() > 0)
return false;
if(children.size() > 0)
return false;
return true;
}
NodeSchema::~NodeSchema()
{
}
void NodeSchema::add_attribute(refptr<AttributeSchema> schema)
{
attributes.push_back(schema);
att_mapper[schema->name.get_id()] = attributes.size() - 1;
}
void NodeSchema::ajoute_enfant(NodeSchema *enfant, unsigned int min, unsigned int max)
{
SubSchema ss;
ss.child_str = enfant->name.get_id();
ss.default_count = min;
ss.min = min;
ss.max = max;
ss.name = enfant->name;
ss.ptr = enfant;
add_sub_node(ss);
}
void NodeSchema::add_sub_node(const SubSchema &schema)
{
children.push_back(schema);
string subname = schema.child_str;
if(schema.name.get_id().size() > 0)
subname = schema.name.get_id();
mapper[subname] = children.size() - 1;
}
bool NodeSchema::has_editable_props()
{
for(unsigned int i = 0; i < attributes.size(); i++)
{
AttributeSchema &as = *attributes[i];
if(!as.is_hidden)
return true;
}
if(this->children.size() > 0)
{
for(unsigned int i = 0; i < children.size(); i++)
{
if(children[i].ptr->has_editable_props())
return true;
}
}
if(this->references.size() > 0)
return true;
return false;
}
void NodeSchema::update_size_info()
{
attributes_fixed_size = true;
for(unsigned int i = 0; i < this->attributes.size(); i++)
{
AttributeSchema &as = *attributes[i];
attributes_fixed_size = attributes_fixed_size && as.fixed_size();
}
children_fixed_size = true;
for(unsigned int i = 0; i < this->children.size(); i++)
{
SubSchema ss = children[i];
//ss.ptr->update_size_info();
if((ss.min == -1)
|| (ss.max == -1)
|| (ss.min != ss.max)
|| (!ss.ptr->fixed_size))
children_fixed_size = false;
}
fixed_size = attributes_fixed_size && children_fixed_size;
}
bool fixed_size;
bool attributes_fixed_size;
bool children_fixed_size;
CommandSchema::CommandSchema(const MXml &mx)
{
name = Localized(mx);
if(mx.has_child("input"))
input = refptr<NodeSchema>(new NodeSchema(mx.get_child("input")));
if(mx.has_child("output"))
output = refptr<NodeSchema>(new NodeSchema(mx.get_child("output")));
}
CommandSchema::CommandSchema(const Node &model)
{
name = model.get_localized();
if(model.get_children_count("input") > 0)
input = refptr<NodeSchema>(new NodeSchema(model.get_child_at("input", 0)));
if(model.get_children_count("output") > 0)
output = refptr<NodeSchema>(new NodeSchema(model.get_child_at("output", 0)));
}
CommandSchema::CommandSchema(const CommandSchema &cs)
{
*this = cs;
}
void CommandSchema::operator =(const CommandSchema &cs)
{
name = cs.name;
input = cs.input;
output = cs.output;
}
Localized Node::get_localized() const
{
Localized res;
if(__builtin_expect(data == nullptr, 0))
{
res.set_value(Localized::LANG_ID, "");
return res;
}
if(has_attribute("name"))
res.set_value(Localized::LANG_ID, name());
else if(has_attribute("type"))
res.set_value(Localized::LANG_ID, get_attribute_as_string("type"));
else
{
avertissement("Localization of an node without identifier.");
}
auto lst = Localized::language_list();
for(auto l: lst)
{
auto s = Localized::language_id(l);
if(has_attribute(s))
{
auto v = get_attribute_as_string(s);
if(v.size() > 0)
res.set_value(l, v);
}
}
# if 0
if(has_attribute("fr"))
{
std::string fr = get_attribute_as_string("fr");
if(fr.size() > 0)
res.set_value(Localized::LANG_FR, fr);
}
if(has_attribute("en"))
{
std::string en = get_attribute_as_string("en");
if(en.size() > 0)
res.set_value(Localized::LANG_EN, en);
}
if(has_attribute("de"))
{
std::string de = get_attribute_as_string("de");
if(de.size() > 0)
res.set_value(Localized::LANG_DE, de);
}
# endif
if(this->has_child("description"))
{
for(const Node desc: children("description"))
{
res.set_description(
Localized::parse_language(desc.get_attribute_as_string("lang")),
desc.get_attribute_as_string("content"));
}
}
return res;
}
NodeSchema::NodeSchema(const Node &e, FileSchema *root, const string &name_)
{
unsigned int i;
inheritance = nullptr;
if(e.is_nullptr())
{
avertissement("constructor: from nullptr node.");
return;
}
string schema_name;
if(name_ != "")
name.set_value(Localized::LANG_ID, name_);
if(e.schema()->name.get_id().compare("input") == 0)
{
name.set_value(Localized::LANG_ID, "input");
}
else if(e.schema()->name.get_id().compare("output") == 0)
{
name.set_value(Localized::LANG_ID, "output");
}
else if(e.schema()->name.get_id().compare("partial") == 0)
{
name.set_value(Localized::LANG_ID, "partial");
}
else
name = e.get_localized();
fixed_size = true;
for(const Node &ch: e.children("attribute"))
{
string attname = ch.get_attribute_as_string("name");
auto ref = refptr<AttributeSchema>(new AttributeSchema(ch));
add_attribute(ref);
}
if(e.has_attribute("inherits"))
inheritance_name = e.get_attribute_as_string("inherits");
if(e.has_attribute("icon"))
icon_path = e.get_attribute_as_string("icon");
for(const Node cmde: e.children("command"))
{
CommandSchema cs(cmde);
commands.push_back(cs);
}
for(const Node sb: e.children("sub"))
{
SubSchema ss;
ss.min = sb.get_attribute_as_int("min");
ss.max = sb.get_attribute_as_int("max");
ss.child_str = sb.get_attribute_as_string("type");
ss.name = sb.get_localized();
ss.display_tab = false;
ss.display_tree = false;
if(sb.has_attribute("key"))
ss.default_key = sb.get_attribute_as_string("key");
if(sb.has_attribute("sub-readonly"))
ss.readonly = sb.get_attribute_as_boolean("sub-readonly");
if(sb.has_attribute("hidden"))
ss.is_hidden = sb.get_attribute_as_boolean("hidden");
if(sb.has_attribute("display-tree"))
{
ss.display_tree = sb.get_attribute_as_boolean("display-tree");
}
if(sb.has_attribute("default"))
ss.default_count = sb.get_attribute_as_int("default");
if(sb.has_attribute("display-tab"))
{
ss.display_tab = sb.get_attribute_as_boolean("display-tab");
std::string list = sb.get_attribute_as_string("display-resume");
std::vector<std::string> lst;
utils::str::parse_string_list(list, lst, ',');
ss.resume = lst;
}
ss.display_unfold = true;
if(sb.has_attribute("display-unfold"))
ss.display_unfold = sb.get_attribute_as_boolean("display-unfold");
if(ss.name.get_id().size() == 0)
ss.name.set_value(Localized::LANG_ID, ss.child_str);
//ss.ptr = nullptr;
if(root != nullptr)
ss.ptr = root->get_schema(ss.child_str);
add_sub_node(ss);
}
for(const Node sb: e.children("sub-node"))
{
SubSchema ss;
ss.min = sb.get_attribute_as_int("min");
ss.max = sb.get_attribute_as_int("max");
ss.child_str = sb.get_attribute_as_string(/*"type"*/"name");
ss.name = sb.get_localized();
ss.display_tab = false;
ss.display_tree = false;
if(sb.has_attribute("key"))
ss.default_key = sb.get_attribute_as_string("key");
if(sb.has_attribute("sub-readonly"))
ss.readonly = sb.get_attribute_as_boolean("sub-readonly");
if(sb.has_attribute("hidden"))
ss.is_hidden = sb.get_attribute_as_boolean("hidden");
if(sb.has_attribute("display-tree"))
{
ss.display_tree = sb.get_attribute_as_boolean("display-tree");
}
if(sb.has_attribute("default"))
ss.default_count = sb.get_attribute_as_int("default");
if(sb.has_attribute("display-tab"))
{
ss.display_tab = sb.get_attribute_as_boolean("display-tab");
std::string list = sb.get_attribute_as_string("display-resume");
std::vector<std::string> lst;
utils::str::parse_string_list(list, lst, ',');
ss.resume = lst;
}
ss.display_unfold = true;
if(sb.has_attribute("display-unfold"))
ss.display_unfold = sb.get_attribute_as_boolean("display-unfold");
if(ss.name.get_id().size() == 0)
ss.name.set_value(Localized::LANG_ID, ss.child_str);
//ss.ptr = nullptr;
if(root != nullptr)
ss.ptr = root->get_schema(ss.child_str);
add_sub_node(ss);
}
for(i = 0; i < e.get_children_count("ref"); i++)
{
const Node &sb = e.get_child_at("ref", i);
RefSchema ss;
ss.child_str = sb.get_attribute_as_string("type");
ss.name = sb.get_localized();
ss.path = sb.get_attribute_as_string("path");
references.push_back(ss);
}
}
void NodeSchema::from_xml(const MXml &mx)
{
std::vector<const MXml *> lst;
unsigned int i;
mx.get_children("attribute", lst);
for(const MXml *att: lst)
{
refptr<AttributeSchema> ref = refptr<AttributeSchema>(new AttributeSchema(*att));
add_attribute(ref);
}
lst.clear();
mx.get_children("command", lst);
for(i = 0; i < lst.size(); i++)
{
CommandSchema cs(*lst[i]);
commands.push_back(cs);
}
lst.clear();
mx.get_children("sub", lst);
for(i = 0; i < lst.size(); i++)
{
SubSchema ss;
ss.min = -1;
ss.max = -1;
if(lst[i]->has_attribute("key"))
ss.default_key = lst[i]->get_attribute("key").to_string();
if(lst[i]->has_attribute("sub-readonly"))
ss.readonly = lst[i]->get_attribute("sub-readonly").to_bool();
if(lst[i]->has_attribute("default"))
ss.default_count = lst[i]->get_attribute("default").to_int();
if(lst[i]->has_attribute("hidden"))
ss.is_hidden = lst[i]->get_attribute("hidden").to_bool();
if(lst[i]->has_attribute("min"))
ss.min = lst[i]->get_attribute("min").to_int();
if(lst[i]->has_attribute("max"))
ss.max= lst[i]->get_attribute("max").to_int();
ss.show_header = true;
if(lst[i]->has_attribute("show-header"))
ss.show_header= lst[i]->get_attribute("show-header").to_bool();
ss.child_str = lst[i]->get_attribute("type").to_string();
ss.name = Localized(*lst[i]);
ss.display_tree = false;
if(lst[i]->has_attribute("display-tree"))
{
ss.display_tree = lst[i]->get_attribute("display-tree").to_bool();
}
ss.display_tab = false;
if(lst[i]->has_attribute("display-tab"))
{
ss.display_tab = lst[i]->get_attribute("display-tab").to_bool();
std::string list;
if(lst[i]->has_attribute("display-resume"))
list = lst[i]->get_attribute("display-resume").to_string();
std::vector<std::string> lst;
utils::str::parse_string_list(list, lst, ',');
ss.resume = lst;
}
ss.display_unfold = true;
if(lst[i]->has_attribute("display-unfold"))
ss.display_unfold = lst[i]->get_attribute("display-unfold").to_bool();
//children.push_back(ss);
//mapper[ss.child_str] = children.size() - 1;
add_sub_node(ss);
}
lst.clear();
mx.get_children("sub-node", lst);
for(i = 0; i < lst.size(); i++)
{
SubSchema ss;
ss.min = -1;
ss.max = -1;
if(lst[i]->has_attribute("sub-readonly"))
ss.readonly = lst[i]->get_attribute("sub-readonly").to_bool();
if(lst[i]->has_attribute("key"))
ss.default_key = lst[i]->get_attribute("key").to_string();
if(lst[i]->has_attribute("default"))
ss.default_count = lst[i]->get_attribute("default").to_int();
if(lst[i]->has_attribute("hidden"))
ss.is_hidden = lst[i]->get_attribute("hidden").to_bool();
if(lst[i]->has_attribute("min"))
ss.min = lst[i]->get_attribute("min").to_int();
if(lst[i]->has_attribute("max"))
ss.max= lst[i]->get_attribute("max").to_int();
ss.show_header = true;
if(lst[i]->has_attribute("show-header"))
ss.show_header= lst[i]->get_attribute("show-header").to_bool();
ss.child_str = lst[i]->get_attribute("name").to_string();
ss.name = Localized(*lst[i]);
ss.display_tree = false;
if(lst[i]->has_attribute("display-tree"))
{
ss.display_tree = lst[i]->get_attribute("display-tree").to_bool();
}
ss.display_tab = false;
if(lst[i]->has_attribute("display-tab"))
{
ss.display_tab = lst[i]->get_attribute("display-tab").to_bool();
std::string list;
if(lst[i]->has_attribute("display-resume"))
list = lst[i]->get_attribute("display-resume").to_string();
std::vector<std::string> lst;
utils::str::parse_string_list(list, lst, ',');
ss.resume = lst;
}
ss.display_unfold = true;
if(lst[i]->has_attribute("display-unfold"))
ss.display_unfold = lst[i]->get_attribute("display-unfold").to_bool();
add_sub_node(ss);
}
lst.clear();
mx.get_children("ref", lst);
for(unsigned int i = 0; i < lst.size(); i++)
{
RefSchema ss;
ss.child_str = lst[i]->get_attribute("type").to_string();
ss.name = Localized(*lst[i]);
ss.path = "";
if(lst[i]->has_attribute("path"))
ss.path = lst[i]->get_attribute("path").to_string();
references.push_back(ss);
}
}
NodeSchema::NodeSchema(const MXml &mx)
{
fixed_size = true;
inheritance = nullptr;
if(mx.name.compare("input") == 0)
{
if(!mx.has_attribute("name"))
{
name.set_value(Localized::LANG_ID, "input");
}
else
name = Localized(mx);
}
else
{
if(!mx.has_attribute("name"))
{
erreur("XML has no 'name' attribute.");
return;
}
name = Localized(mx);
}
if(mx.has_attribute("inherits"))
inheritance_name = mx.get_attribute("inherits").to_string();
if(mx.has_attribute("icon"))
icon_path = mx.get_attribute("icon").to_string();
from_xml(mx);
}
NodeSchema::NodeSchema(const NodeSchema &c)
{
inheritance = nullptr;
*this = c;
}
bool NodeSchema::has_reference(std::string name) const
{
for(unsigned int i = 0; i < references.size(); i++)
{
if(references[i].name.get_id() == name)
return true;
}
return false;
}
SubSchema *NodeSchema::get_child(std::string name)
{
for(unsigned int i = 0; i < children.size(); i++)
{
if(children[i].name.get_id() == name)
return &(children[i]);
}
return nullptr;
}
bool NodeSchema::has_child(std::string name) const
{
for(unsigned int i = 0; i < children.size(); i++)
{
if(children[i].name.get_id().compare(name) == 0)
return true;
}
return false;
}
NodeSchema *NodeSchema::get_sub(std::string name)
{
for(uint32_t i = 0; i < children.size(); i++)
{
if(children[i].name.get_id().compare(name) == 0)
{
return children[i].ptr;
}
}
erreur("Sub not found: %s.", name.c_str());
return nullptr;
}
std::string NodeSchema::get_localized() const
{
std::string res = name.get_localized();
if(langue.has_item(res))
res = langue.get_item(res);
return res;
}
void Node::get_children_recursive(const string &type,
deque<Node> &res)
{
unsigned int n = schema()->children.size();
for(unsigned int i = 0; i < n; i++)
{
string sub_type = schema()->children[i].ptr->name.get_id();
for(Node child: children(sub_type))
{
if(type.compare(sub_type) == 0)
res.push_back(child);
child.get_children_recursive(type, res);
}
}
}
RefSchema *NodeSchema::get_reference(std::string name)
{
for(unsigned int i = 0; i < references.size(); i++)
{
if(references[i].name.get_id().compare(name) == 0)
return &(references[i]);
}
return nullptr;
}
bool NodeSchema::has_attribute(std::string name) const
{
for(const refptr<AttributeSchema> &as: attributes)
{
if(as->name.get_id().compare(name) == 0)
return true;
}
return false;
}
refptr<AttributeSchema> NodeSchema::get_attribute(std::string name)
{
for(const refptr<AttributeSchema> &as: attributes)
{
if(as->name.get_id().compare(name) == 0)
return as;
}
erreur("att not found: %s.", name.c_str());
return refptr<AttributeSchema>();
}
void NodeSchema::do_inherits()
{
if(inheritance == nullptr)
return;
for(unsigned int i = 0; i < inheritance->children.size(); i++)
{
bool present = false;
for(unsigned int j = 0; j < children.size(); j++)
{
if(children[j].ptr == inheritance->children[i].ptr)
{
present = true;
break;
}
}
if(!present)
{
//children.push_front(inheritance->children[i]);
add_sub_node(inheritance->children[i]);
}
}
for(unsigned int i = 0; i < inheritance->references.size(); i++)
references.push_front(inheritance->references[i]);
for(unsigned int i = 0; i < inheritance->attributes.size(); i++)
{
bool present = false;
for(unsigned int j = 0; j < attributes.size(); j++)
{
if(attributes[j]->name.get_id().compare(inheritance->attributes[i]->name.get_id()) == 0)
{
present = true;
break;
}
}
if(!present)
{
auto &att = inheritance->attributes[i];
attributes.push_back(att);
att_mapper[att->name.get_id()] = attributes.size() - 1;
}
}
//inheritance = nullptr;
}
void NodeSchema::serialize(ByteArray &ba)
{
ba.puts(name.get_id());
ba.putw(attributes.size());
for(const refptr<AttributeSchema> &as: attributes)
as->serialize(ba);
ba.putw(children.size());
for(const SubSchema &ss: children)
{
ba.puts(ss.name.get_id());
ba.puts(ss.child_str);
uint16_t flags = 0;
if(ss.has_min())
flags |= 1;
if(ss.has_max())
flags |= 2;
ba.putw(flags);
if(ss.has_min())
ba.putl(ss.min);
if(ss.has_max())
ba.putl(ss.max);
}
}
int NodeSchema::unserialize(ByteArray &ba)
{
uint32_t i, n;
name.set_value(Localized::LANG_ID, ba.pops());
n = ba.popw();
for(i = 0; i < n; i++)
{
AttributeSchema *as = new AttributeSchema();
as->unserialize(ba);
attributes.push_back(refptr<AttributeSchema>(as));
}
n = ba.popw();
for(i = 0; i < n; i++)
{
SubSchema ss;
ss.child_str = ba.pops();
uint16_t flags = ba.popw();
ss.min = -1;
ss.max = -1;
if(flags & 1)
ss.min = ba.popl();
if(flags & 2)
ss.max = ba.popl();
//children.push_back(ss);
add_sub_node(ss);
}
return 0;
}
void NodeSchema::operator =(const NodeSchema &c)
{
name = c.name;
icon_path = c.icon_path;
inheritance = c.inheritance;
inheritance_name = c.inheritance_name;
fixed_size = c.fixed_size;
mapper = c.mapper;
att_mapper = c.att_mapper;
children = c.children;
commands = c.commands;
references = c.references;
attributes = c.attributes;
}
CommandSchema *NodeSchema::get_command(std::string name)
{
for(unsigned int i = 0; i < commands.size(); i++)
{
if(commands[i].name.get_id().compare(name) == 0)
return &commands[i];
}
erreur("get_command(%s): not found.", name.c_str());
return nullptr;
}
void Node::dispatch_event(const ChangeEvent &ce)
{
if(data != nullptr)
{
data->dispatch(ce);
}
}
int FileSchema::check_complete()
{
build_references();
return 0;
}
FileSchema::~FileSchema()
{
//infos("Destruction file schema...");
}
void FileSchema::add_schema(const Node &e, const string &name)
{
if((e.type().compare("node") == 0) || (name.size() > 0))
{
refptr<NodeSchema> es(new NodeSchema(e, nullptr, name));
from_element2(e);
schemas.push_back(es);
}
else
{
if(e.type().compare("schema") != 0)
{
erreur("This file is not an application file (root tag is " + e.type() + ").");
return;
}
for(unsigned int i = 0; i < e.get_children_count("node"); i++)
{
NodeSchema *es_ = new NodeSchema(e.get_child_at("node", i));
refptr<NodeSchema> es(es_);
schemas.push_back(es);
//infos("Added schema: %s.", es.name.c_str());
}
# if 0
for(unsigned int i = 0; i < e.get_children_count("command"); i++)
{
Node cmd = e.get_child_at("command", i);
if(cmd.has_child("input"))
{
add_schema(cmd.get_child("input"));
}
NodeSchema *es_ = new NodeSchema(e.get_child_at("node", i));
refptr<NodeSchema> es(es_);
schemas.push_back(es);
//infos("Added schema: %s.", es.name.c_str());
}
# endif
}
//build_references();
}
void FileSchema::from_element2(const Node &e)
{
for(unsigned int i = 0; i < e.get_children_count("sub-node"); i++)
{
Node se = e.get_child_at("sub-node", i);
NodeSchema *es_ = new NodeSchema(se);
refptr<NodeSchema> es(es_);
schemas.push_back(es);
from_element2(se);
}
}
void FileSchema::from_element(const Node &e)
{
if(e.type().compare("schema") != 0)
{
if(e.type().compare("node") == 0)
{
NodeSchema *es_ = new NodeSchema(e);
refptr<NodeSchema> es(es_);
from_element2(e);
schemas.push_back(es);
build_references();
std::string rootname = e.get_attribute_as_string("name");
root = get_schema(rootname);
root->update_size_info();
return;
}
erreur("This file is not an application file (root tag is " + e.type() + ").");
return;
}
std::string rootname = e.get_attribute_as_string("root");
for(Node child: e.children("node"))
{
NodeSchema *es_ = new NodeSchema(child);
refptr<NodeSchema> es(es_);
from_element2(child);
schemas.push_back(es);
}
build_references();
root = get_schema(rootname);
root->update_size_info();
}
void FileSchema::from_xml2(const MXml &node)
{
std::vector<const MXml *> lst;
node.get_children("sub-node", lst);
for(unsigned int i = 0; i < lst.size(); i++)
{
const MXml &se = *(lst[i]);
refptr<NodeSchema> es(new NodeSchema(se));
schemas.push_back(es);
from_xml2(se);
}
lst.clear();
node.get_children("node", lst);
for(unsigned int i = 0; i < lst.size(); i++)
{
const MXml &se = *(lst[i]);
refptr<NodeSchema> es(new NodeSchema(se));
schemas.push_back(es);
// infos("added schema %s.", es.name.get_id().c_str());
from_xml2(se);
}
}
int FileSchema::from_xml(const MXml &xm)
{
unsigned int i, j;
if(xm.name.compare("schema") != 0)
{
erreur("This file is not an application file (root tag is " + xm.name + ").");
return -1;
}
/*std::string rootname;
if(xm.has_attribute("root"))
rootname = xm.get_attribute("root").to_string();*/
std::vector<const MXml *> lst;
xm.get_children("node", lst);
for(i = 0; i < lst.size(); i++)
{
from_xml2(*lst[i]);
refptr<NodeSchema> es(new NodeSchema(*lst[i]));
schemas.push_back(es);
}
lst.clear();
xm.get_children("include-schema", lst);
for(i = 0; i < lst.size(); i++)
{
if(!lst[i]->has_attribute("path"))
{
avertissement("Tag include-schema without path.");
continue;
}
std::string path = lst[i]->get_attribute("path").to_string();
MXml xm;
if(xm.from_file(utils::get_fixed_data_path() + PATH_SEP + path))
{
erreur("Echec chargement du schema @[%s].", path.c_str());
continue;
}
else
{
infos("Chargement schema a partir de [%s]..", path.c_str());
//infos("VALLLL = \n%s\n", xm.dump().c_str());
from_xml2(xm);
}
}
lst.clear();
xm.get_children("extension", lst);
for(i = 0; i < lst.size(); i++)
{
std::string type = lst[i]->get_attribute("type").to_string();
for(j = 0; j < schemas.size(); j++)
{
if(schemas[j]->name.get_id().compare(type) == 0)
{
schemas[j]->from_xml(*lst[i]);
break;
}
}
if(j == schemas.size())
{
avertissement("Extension: schema not found: %s.", type.c_str());
}
else
{
from_xml2(*lst[i]);
}
}
build_references();
// root = get_schema(rootname);
// if(root != nullptr)
// root->update_size_info();
return 0;
}
int FileSchema::from_string(const string &s)
{
MXml xm;
if(xm.from_file(s))
return -1;
return from_xml(xm);
}
int FileSchema::from_file(std::string filename)
{
MXml xm;
if(xm.from_file(filename))
return -1;
return from_xml(xm);
}
FileSchema::FileSchema(std::string filename)
{
infos("fileschema(%s)...", filename.c_str());
from_file(filename);
}
void FileSchema::build_references()
{
for(unsigned int i = 0; i < schemas.size(); i++)
{
restart:
for(unsigned int j = 0; j < schemas[i]->children.size(); j++)
{
schemas[i]->children[j].ptr = get_schema(schemas[i]->children[j].child_str);
if(schemas[i]->children[j].ptr == nullptr)
{
avertissement("build references: schema not found: %s.", schemas[i]->children[j].child_str.c_str());
// Remove schema from the children
std::deque<SubSchema>::iterator it = schemas[i]->children.begin() + j;
schemas[i]->children.erase(it);
goto restart;
}
}
for(unsigned int j = 0; j < schemas[i]->attributes.size(); j++)
{
refptr<AttributeSchema> &as = schemas[i]->attributes[j];
for(unsigned int k = 0; k < as->enumerations.size(); k++)
{
unsigned int l;
if(as->enumerations[k].schema_str.size() > 0)
{
as->enumerations[k].schema = get_schema(as->enumerations[k].schema_str);
for(l = 0; l < schemas[i]->children.size(); l++)
{
SubSchema &ss = schemas[i]->children[l];
if(ss.ptr == as->enumerations[k].schema)
{
ss.is_exclusive = true;
break;
}
}
}
}
}
for(unsigned int j = 0; j < schemas[i]->references.size(); j++)
{
schemas[i]->references[j].ptr = get_schema(schemas[i]->references[j].child_str);
if(schemas[i]->references[j].ptr == nullptr)
{
erreur("Schema not found for ref: %s.", schemas[i]->references[j].child_str.c_str());
return;
}
}
if(schemas[i]->inheritance_name.size() > 0)
{
schemas[i]->inheritance = get_schema(schemas[i]->inheritance_name);
}
}
// Ceci est fait plusieurs fois, afin de bien gérer le cas des héritages
// de schéma qui eux-mêmes héritent d'autres schémas...
for(unsigned int i = 0; i < schemas.size(); i++)
schemas[i]->do_inherits();
for(unsigned int i = 0; i < schemas.size(); i++)
schemas[i]->do_inherits();
for(unsigned int i = 0; i < schemas.size(); i++)
schemas[i]->do_inherits();
}
NodeSchema *FileSchema::get_schema(std::string name)
{
for(refptr<NodeSchema> &s: schemas)
{
if(s->name.get_id().compare(name) == 0)
return s.get_reference();
}
avertissement("Schema not found: " + name);
return nullptr;
}
std::string NodeSchema::to_string()
{
std::string res = "";
NodeSchema *s = this;
res += "<node " + utils::str::xmlAtt("name", s->name.get_id());
res += ">\n";
for(unsigned int j = 0; j < s->attributes.size(); j++)
res += s->attributes[j]->to_string();
for(const SubSchema &ss: children)
{
res += "<sub " + utils::str::xmlAtt("type", ss.ptr->name.get_id());
if(ss.ptr->name.get_id().compare(ss.name.get_id()) != 0)
res += utils::str::xmlAtt("name", ss.name.get_id());
if(ss.min != -1)
res += utils::str::xmlAtt("min", ss.min);
if(ss.max != -1)
res += utils::str::xmlAtt("max", ss.max);
res += "/>\n";
}
for(unsigned int j = 0; j < s->references.size(); j++)
{
res += "<ref " + utils::str::xmlAtt("type", s->references[j].ptr->name.get_id());
if(s->references[j].ptr->name.get_id().compare(s->references[j].name.get_id()) != 0)
res += utils::str::xmlAtt("name", s->references[j].name.get_id());
res += utils::str::xmlAtt("path", s->references[j].path);
res += "/>\n";
}
res += "</node>\n";
return res;
}
std::string FileSchema::to_string()
{
std::string res = "";
res += "<schema " + utils::str::xmlAtt("root", root->name.get_id()) + ">\n";
for(const refptr<NodeSchema> &s: schemas)
{
res += "<node " + utils::str::xmlAtt("name", s->name.get_id());
if(s->inheritance != nullptr)
res += utils::str::xmlAtt("inherits", s->inheritance->name.get_id());
res += ">\n";
for(unsigned int j = 0; j < s->attributes.size(); j++)
res += s->attributes[j]->to_string();
for(const SubSchema &ss: s->children)
{
res += "<sub " + utils::str::xmlAtt("type", ss.ptr->name.get_id());
if(ss.ptr->name.get_id().compare(ss.name.get_id()) != 0)
res += utils::str::xmlAtt("name", ss.name.get_id());
if(ss.min != -1)
res += utils::str::xmlAtt("min", ss.min);
if(ss.max != -1)
res += utils::str::xmlAtt("max", ss.max);
res += "/>\n";
}
for(unsigned int j = 0; j < s->references.size(); j++)
{
res += "<ref " + utils::str::xmlAtt("type", s->references[j].ptr->name.get_id());
if(s->references[j].ptr->name.get_id().compare(s->references[j].name.get_id()) != 0)
res += utils::str::xmlAtt("name", s->references[j].name.get_id());
res += utils::str::xmlAtt("path", s->references[j].path);
res += "/>\n";
}
res += "</node>\n";
}
res += "</schema>\n";
return res;
}
FileSchema::FileSchema()
{
}
FileSchema::FileSchema(const FileSchema &c)
{
*this = c;
}
void FileSchema::operator =(const FileSchema &c)
{
/*schemas.clear();
for(unsigned i = 0; i < c.schemas.size(); i++)
schemas.push_back(c.schemas[i]);*/
schemas = c.schemas;
build_references();
root = get_schema(c.root->name.get_id());
}
AttributeSchema::~AttributeSchema()
{
//infos("delete.");
}
long int AttributeSchema::get_min()
{
if(has_min)
return min;
if(!is_signed)
return 0;
if(size == 1)
return -127;
if(size == 2)
return -32767;
return -2147483647;
}
bool AttributeSchema::has_constraints() const
{
return (constraints.size() > 0);
}
long int AttributeSchema::get_max()
{
if(has_max)
{
if(max == -1)
{
erreur("max == -1");
return 4294967295UL;
}
return max;
}
if(is_signed)
{
if(size == 1)
return 128;
if(size == 2)
return 32768;
return 2147483647;
}
if(size == 1)
return 255;
if(size == 2)
return 65535;
return 2147483647;
}
AttributeSchema::AttributeSchema()
{
log.setup("model");
//fprintf(stderr, "att_schema: cons..\n"); fflush(stderr);
/*setup("model", "attribute-schema");*/
id= 0xffff;
size = 1;
//name = "";
type = TYPE_STRING;
is_signed = false;
min = -1;
is_ip = false;
max = -1;
unit = "";
extension = "";
//default_value;
is_hexa = false;
is_bytes = false;
is_hidden = false;
is_volatile = false;
is_read_only = false;
is_instrument = false;
formatted_text = false;
is_error = false;
}
void AttributeSchema::serialize(ByteArray &ba) const
{
uint16_t flags = 0;
if(is_signed)
flags |= (1 << 0);
if(is_bytes)
flags |= (1 << 1);
if(is_hexa)
flags |= (1 << 2);
if(is_hidden)
flags |= (1 << 3);
if(is_volatile)
flags |= (1 << 4);
if(is_read_only)
flags |= (1 << 5);
if(has_min)
flags |= (1 << 6);
if(has_max)
flags |= (1 << 7);
ba.putc((uint8_t) type);
ba.putw(flags);
ba.putc(size);
ba.puts(name.get_id());
ba.puts(unit);
# if 0
std::string unit, extension, requirement;
long int min;
long int max;
long int get_min();
long int get_max();
bool has_constraints() const;
std::vector<std::string> constraints;
std::vector<Enumeration> enumerations;
std::string default_value;
/** TODO: generalize */
std::string description, description_fr;
/** ? */
bool is_unique;
/** TODO: generalize */
std::string fr, en;
# endif
}
int AttributeSchema::unserialize(ByteArray &ba)
{
type = (attribute_type_t) ba.popc();
uint16_t flags = ba.popw();
is_signed = ((flags & 1) != 0);
is_bytes = ((flags & (1 << 1)) != 0);
is_hexa = ((flags & (1 << 2)) != 0);
is_hidden = ((flags & (1 << 3)) != 0);
is_volatile = ((flags & (1 << 4)) != 1);
is_read_only = ((flags & (1 << 5)) != 0);
has_min = ((flags & (1 << 6)) != 0);
has_max = ((flags & (1 << 7)) != 0);
size = ba.popc();
name.set_value(Localized::LANG_ID, ba.pops());
return 0;
}
bool AttributeSchema::fixed_size() const
{
if((type == TYPE_STRING) || (type == TYPE_FOLDER) || (type == TYPE_FILE)|| (type == TYPE_SERIAL))
return false;
return true;
}
std::string AttributeSchema::get_ihm_value(std::string val) const
{
for(const Enumeration &e: enumerations)
{
if((e.value.compare(val) == 0) || (e.name.get_id().compare(val) == 0))
return e.name.get_localized();
}
if(type == TYPE_BOOLEAN)
{
if(Localized::current_language == Localized::LANG_FR)
{
if((val.compare("0") == 0) || (val.compare("false") == 0))
return "non";
else
return "oui";
}
}
return val;
}
std::string AttributeSchema::get_default_value() const
{
if(default_value.size() > 0)
return get_string(default_value);
switch(type)
{
case TYPE_STRING: return "";
case TYPE_BOOLEAN: return "false";
case TYPE_FLOAT: return "0.0";
case TYPE_INT:
{
if(enumerations.size() > 0)
return enumerations[0].value;//name.get_id();
if(has_min)
return utils::str::int2str(min);
if(is_hexa)
return "0x00000000";
return "0";
}
case TYPE_COLOR: return "0.0.0";
case TYPE_BLOB: return "";
case TYPE_FOLDER: return ".";
case TYPE_FILE: return "";
case TYPE_SERIAL: return "";
case TYPE_DATE: return "1.1.2000";
}
return "";
}
std::string AttributeSchema::to_string() const
{
std::string res = "";
res = "<attribute ";
res += utils::str::xmlAtt("name", name.get_id());
res += utils::str::xmlAtt("type", type2string());
if((type == TYPE_INT) || (type == TYPE_FLOAT))
res += utils::str::xmlAtt("size", utils::str::int2str(size));
if(has_min)
res += utils::str::xmlAtt("min", utils::str::int2str(min));
if(has_max)
res += utils::str::xmlAtt("max", utils::str::int2str(max));
if(id != 0xffff)
res += utils::str::xmlAtt("id", utils::str::int2str(id));
if(this->is_signed)
res += utils::str::xmlAtt("signed", "true");
if(this->is_hexa)
res += utils::str::xmlAtt("is_hexa", "true");
if(unit.size() > 0)
res += utils::str::xmlAtt("unit", unit);
if(extension.size() > 0)
res += utils::str::xmlAtt("extension", extension);
if(default_value.size() > 0)
res += utils::str::xmlAtt("default", get_string(default_value));
if(constraints.size() > 0)
{
res += " constraints = \"";
for(unsigned int i = 0; i < constraints.size(); i++)
{
res += constraints[i];
if(i < constraints.size() - 1)
res += std::string("|");
}
res += "\"";
}
if(enumerations.size() == 0)
return res + "/>\n";
res += ">\n";
for(unsigned int i = 0; i < enumerations.size(); i++)
{
res += "<match "
+ utils::str::xmlAtt("name", enumerations[i].name.get_id())
+ utils::str::xmlAtt("value", enumerations[i].value)
+ "/>\n";
}
res += "</attribute>\n";
return res;
}
SubSchema::SubSchema()
{
display_unfold = true;
is_hidden = false;
is_exclusive = false;
default_count = 0;
readonly = false;
display_tree = false;
display_tab = false;
min = -1;
max = -1;
}
void SubSchema::operator =(const SubSchema &ss)
{
show_header = ss.show_header;
default_count = ss.default_count;
is_hidden = ss.is_hidden;
display_unfold = ss.display_unfold;
min = ss.min;
max = ss.max;
ptr = ss.ptr;
name = ss.name;
child_str = ss.child_str;
display_tab = ss.display_tab;
display_tree = ss.display_tree;
is_exclusive = ss.is_exclusive;
readonly = ss.readonly;
resume = ss.resume;
}
std::string SubSchema::to_string() const
{
std::string res = "sub-schema: ";
res += name.get_id() + ", cstr=";
res += child_str + ", ";
res += std::string("min = ") + utils::str::int2str(min) + ", ";
res += std::string("max = ") + utils::str::int2str(max) + ", ";
if(is_hidden)
res += "hidden ";
if(display_tab)
res += "display-tab ";
if(display_tree)
res += "display-tree ";
if(display_unfold)
res += "display-unfold ";
return res;
}
AttributeSchema::AttributeSchema(const Node &e)
{
std::string typestr = e.get_attribute_as_string("type");
name = e.get_localized();
min = -1;
is_ip = false;
max = -1;
size = 1;
id = 0xffff;
is_read_only = false;
if(e.has_attribute("require"))
requirement = e.get_attribute_as_string("require");
if(e.has_attribute("readonly"))
is_read_only = e.get_attribute_as_boolean("readonly");
is_instrument = false;
if(e.has_attribute("instrument"))
is_instrument = e.get_attribute_as_boolean("instrument");
is_error = e.get_attribute_as_boolean("error");
digits = e.get_attribute_as_int("digits");
is_volatile = e.has_attribute("volatile") ? e.get_attribute_as_boolean("volatile") : false;
is_hidden = e.has_attribute("hidden") ? e.get_attribute_as_boolean("hidden") : false;
is_hexa = e.get_attribute_as_boolean("hexa");
is_bytes = e.has_attribute("bytes") ? e.get_attribute_as_boolean("bytes") : false;
unit = e.get_attribute_as_string("unit");
extension = e.has_attribute("extension") ? e.get_attribute_as_string("extension") : "";
regular_exp = e.has_attribute("regular") ? e.get_attribute_as_string("regular") : "";
if(e.has_attribute("id"))
id = e.get_attribute_as_int("id");
formatted_text = false;
if(e.has_attribute("formatted-text"))
formatted_text = e.get_attribute_as_boolean("formatted-text");
for(const Node &sb: e.children("match"))
{
Enumeration en;
en.name = sb.get_localized();
en.value = sb.get_attribute_as_string("value");
if(en.value.size() == 0)
en.value = en.name.get_id();
if(sb.has_attribute("schema"))
en.schema_str = sb.get_attribute_as_string("schema");
enumerations.push_back(en);
}
if(typestr.compare("string") == 0)
{
type = TYPE_STRING;
}
else if(typestr.compare("ip") == 0)
{
type = TYPE_STRING;
is_ip = true;
}
else if(typestr.compare("folder") == 0)
{
type = TYPE_FOLDER;
size = 3;
}
else if(typestr.compare("file") == 0)
{
type = TYPE_FILE;
size = 3;
}
else if(typestr.compare("float") == 0)
{
type = TYPE_FLOAT;
size = 4;
is_signed = true;
}
else if(typestr.compare("double") == 0)
{
type = TYPE_FLOAT;
size = 8;
is_signed = true;
}
else if(typestr.compare("boolean") == 0)
{
type = TYPE_BOOLEAN;
size = 1;
}
else if(typestr.compare("blob") == 0)
{
type = TYPE_BLOB;
size = 3;
}
else
{
type = TYPE_INT;
size = e.get_attribute_as_int("size");
is_signed = e.get_attribute_as_boolean("signed");
}
has_max = (e.get_attribute_as_string("max").size() > 0) && (e.get_attribute_as_string("max")[0] != 'n') && (e.get_attribute_as_string("max") != "-1");
if(has_max)
{
string s = e.get_attribute_as_string("max");
ByteArray ba;
if(serialize(ba, s) == 0)
{
max = get_int(ba);
}
}
has_min = (e.get_attribute_as_string("min").size() > 0) && (e.get_attribute_as_string("min")[0] != 'n') && (e.get_attribute_as_int("min") != -1);
if(has_min)
{
string s = e.get_attribute_as_string("min");
ByteArray ba;
if(serialize(ba, s) == 0)
{
min = get_int(ba);
}
}
//min = e.get_attribute_as_int("min");
string s = e.get_attribute_as_string("default");
if(s.size() > 0)
{
default_value.clear();
serialize(default_value, e.get_attribute_as_string("default"));
}
else
{
make_default_default_value(default_value);
}
assert(is_valid(default_value));
std::string tot = e.get_attribute_as_string("constraints");
if(tot.size() > 0)
{
// Parse list of match ('|' separed)
const char *s = tot.c_str();
char current[200];
int current_index = 0;
for(unsigned int i = 0; i < strlen(s); i++)
{
if(s[i] != '|')
{
current[current_index++] = s[i];
}
else
{
current[current_index] = 0;
constraints.push_back(std::string(current));
current_index = 0;
}
}
if(current_index > 0)
{
current[current_index] = 0;
constraints.push_back(std::string(current));
}
}
}
AttributeSchema::AttributeSchema(const MXml &mx)
{
std::string typestr = "int";
log.setup(string("att-schema/") + mx.get_name());
if(mx.has_attribute("type"))
{
//anomaly("The XML attribute has no type: %s", mx.dump().c_str());
//return;
typestr = mx.get_attribute("type").to_string();
}
if(!mx.has_attribute("name"))
{
erreur("The XML attribute has no name: %s", mx.dump().c_str());
return;
}
is_error = false;
if(mx.has_attribute("error"))
is_error = mx.get_attribute("error").to_bool();
is_ip = false;
name = Localized(mx);
//log.setup("model", std::string("attribute-schema/") + name.get_id());
log.setup("model");
min = -1;
max = -1;
has_min = false;
has_max = false;
is_hexa = false;
is_bytes = false;
unit = "";
extension = "";
size = 1;
//default_value = "";
is_hidden = false;
is_volatile = false;
is_signed = false;
id = 0xffff;
is_read_only = false;
digits = 0;
if(mx.has_attribute("digits"))
digits = mx.get_attribute("digits").to_int();
formatted_text = false;
if(mx.has_attribute("formatted-text"))
formatted_text = mx.get_attribute("formatted-text").to_bool();
is_instrument = false;
if(mx.has_attribute("instrument"))
is_instrument = mx.get_attribute("instrument").to_bool();
//count = 1;
if(mx.has_attribute("require"))
requirement = mx.get_attribute("require").to_string();
regular_exp = "";
if(mx.has_attribute("regular"))
regular_exp = mx.get_attribute("regular").to_string();
//if(mx.has_attribute("count"))
// count = mx.get_attribute("count").to_int();
if(mx.has_attribute("readonly"))
is_read_only = mx.get_attribute("readonly").to_bool();
//infos("%s: readonly = %s.", name.c_str(), is_read_only ? "true" : "false");
/*if(mx.has_attribute("en"))
en = mx.get_attribute("en").to_string();
if(mx.has_attribute("fr"))
fr = mx.get_attribute("fr").to_string();*/
if(mx.has_attribute("id"))
id = mx.get_attribute("id").to_int();
if(mx.has_attribute("size"))
size = mx.get_attribute("size").to_int();
if(mx.has_attribute("signed"))
is_signed = mx.get_attribute("signed").to_bool();
if(mx.has_attribute("hidden"))
is_hidden = mx.get_attribute("hidden").to_bool();
if(mx.has_attribute("volatile"))
is_volatile = mx.get_attribute("volatile").to_bool();
if(mx.has_attribute("hexa"))
is_hexa = mx.get_attribute("hexa").to_bool();
if(mx.has_attribute("bytes"))
is_bytes = mx.get_attribute("bytes").to_bool();
if(mx.has_attribute("unit"))
unit = mx.get_attribute("unit").to_string();
if(mx.has_attribute("extension"))
extension = mx.get_attribute("extension").to_string();
if(mx.has_attribute("max"))
{
has_max = true;
max = mx.get_attribute("max").to_int();
}
if(mx.has_attribute("min"))
{
has_min = true;
min = mx.get_attribute("min").to_int();
}
std::vector<MXml> lst = mx.get_children("match");
for(unsigned int i = 0; i < lst.size(); i++)
{
Enumeration e;
e.name = Localized(lst[i]);//.get_attribute("name").to_string();
if(lst[i].has_attribute("value"))
e.value = lst[i].get_attribute("value").to_string();
else
e.value = e.name.get_id();
/*e.en = e.name;
e.fr = e.name;
if(lst[i].has_attribute("en"))
e.en = lst[i].get_attribute("en").to_string();
if(lst[i].has_attribute("fr"))
e.fr = lst[i].get_attribute("fr").to_string();*/
if(lst[i].has_attribute("schema"))
e.schema_str = lst[i].get_attribute("schema").to_string();
/*if(lst[i].hasChild("description"))
{
e.description = lst[i].get_child("description").dumpContent();
}*/
enumerations.push_back(e);
}
if(typestr.compare("string") == 0)
{
type = TYPE_STRING;
}
else if(typestr.compare("ip") == 0)
{
type = TYPE_STRING;
is_ip = true;
}
else if(typestr.compare("float") == 0)
{
type = TYPE_FLOAT;
size = 4;
is_signed = true;
}
else if(typestr.compare("double") == 0)
{
type = TYPE_FLOAT;
size = 8;
is_signed = true;
}
else if(typestr.compare("boolean") == 0)
{
type = TYPE_BOOLEAN;
size = 1;
}
else if(typestr.compare("color") == 0)
{
type = TYPE_COLOR;
size = 3;
}
else if(typestr.compare("date") == 0)
{
type = TYPE_DATE;
size = 3;
}
else if(typestr.compare("folder") == 0)
{
type = TYPE_FOLDER;
size = 3;
}
else if(typestr.compare("file") == 0)
{
type = TYPE_FILE;
size = 3;
}
else if(typestr.compare("serial") == 0)
{
type = TYPE_SERIAL;
size = 3;
}
else if(typestr.compare("blob") == 0)
{
type = TYPE_BLOB;
size = 3;
}
else
{
type = TYPE_INT;
}
default_value.clear();
if(mx.has_attribute("default"))
{
serialize(default_value, mx.get_attribute("default").to_string());
//default_value = mx.get_attribute("default").to_string();
}
else
{
make_default_default_value(default_value);
}
assert(is_valid(default_value));
if(mx.has_attribute("constraints"))
{
std::string tot = mx.get_attribute("constraints").to_string();
// Parse list of match ('|' separed)
const char *s = tot.c_str();
char current[200];
int current_index = 0;
for(unsigned int i = 0; i < strlen(s); i++)
{
if(s[i] != '|')
{
current[current_index++] = s[i];
}
else
{
current[current_index] = 0;
constraints.push_back(std::string(current));
current_index = 0;
}
}
if(current_index > 0)
{
current[current_index] = 0;
constraints.push_back(std::string(current));
}
}
}
void AttributeSchema::make_default_default_value(ByteArray &res) const
{
res.clear();
if(type == TYPE_INT)
{
for(int i = 0; i < size; i++)
res.putc(0);
}
else if(type == TYPE_FLOAT)
{
res.putf(0.0);
}
else if(type == TYPE_BOOLEAN)
{
res.putc(0);
}
else if(type == TYPE_BLOB)
{
/* (empty) */
}
else
{
res.puts("");
}
}
AttributeSchema::AttributeSchema(const AttributeSchema &c)
{
*this = c;
log.setup("model");
//log.setup("model", std::string("attribute-schema/") + c.name.get_id());
}
void AttributeSchema::operator =(const AttributeSchema &c)
{
enumerations.clear();
constraints.clear();
regular_exp = c.regular_exp;
is_ip = c.is_ip;
id = c.id;
name = c.name;
type = c.type;
size = c.size;
is_signed = c.is_signed;
is_hexa = c.is_hexa;
is_bytes = c.is_bytes;
is_volatile = c.is_volatile;
unit = c.unit;
extension = c.extension;
min = c.min;
max = c.max;
has_min = c.has_min;
has_max = c.has_max;
enumerations = c.enumerations;
is_unique = c.is_unique;
is_hidden = c.is_hidden;
constraints = c.constraints;
is_read_only = c.is_read_only;
requirement = c.requirement;
is_instrument = c.is_instrument;
formatted_text = c.formatted_text;
default_value.clear();
default_value = c.default_value;
is_error = c.is_error;
digits = c.digits;
assert(c.is_valid(c.default_value));
assert(is_valid(default_value));
//log.setup("model", string("att-schema<") + name.get_id() + ">");
}
std::string AttributeSchema::type2string() const
{
switch(type)
{
case TYPE_STRING: return "string";
case TYPE_BOOLEAN: return "boolean";
case TYPE_FLOAT: if(size == 4) return "float"; else return "double";
case TYPE_INT:
return "int";
case TYPE_COLOR: return "color";
case TYPE_BLOB: return "blob";
case TYPE_FOLDER: return "folder";
case TYPE_FILE: return "file";
case TYPE_SERIAL: return "serial";
case TYPE_DATE: return "date";
}
erreur("type2string");
return "error";
}
Attribute::Attribute()
{
inhibit_event_dispatch = false;
node = nullptr;
parent = nullptr;
}
Attribute::Attribute(refptr<AttributeSchema> schema)
{
node = nullptr;
parent = nullptr;
this->schema = schema;
inhibit_event_dispatch = true;
set_value(schema->default_value);
inhibit_event_dispatch = false;
}
int AttributeSchema::get_int (const ByteArray &ba) const
{
if(type == TYPE_FLOAT)
{
return (int) get_float(ba);
}
else if(type == TYPE_BOOLEAN)
{
return ba[0];
}
else if(type == TYPE_INT)
{
ByteArray tmp(ba);
if((unsigned int) size != ba.size())
{
erreur("get_int(): size in schema = %d, in data = %d.", size, ba.size());
return 0;
}
if(size == 8)
{
uint32_t rs = tmp.popL();
if(is_signed)
return (int32_t) rs;
else
return rs;
}
else if(size == 4)
{
uint32_t rs = tmp.popl();
if(is_signed)
return (int32_t) rs;
else
return rs;
}
else if(size == 2)
{
uint16_t c = tmp.popw();
if(is_signed)
{
return (int) ((int16_t) c);
}
return c;
}
else if(size == 1)
{
uint8_t c = tmp.popc();
if(is_signed)
{
return (int) ((int8_t) c);
}
return c;
}
erreur("get int: unmanaged size = %d.", size);
return 0;
}
else
{
if((type == TYPE_STRING) && (enumerations.size() > 0))
{
string s = get_string(ba);
for(unsigned int i = 0; i < enumerations.size(); i++)
{
if(s.compare(enumerations[i].name.get_id()) == 0)
return atoi(enumerations[i].value.c_str());
}
return 0;
}
}
return 0;
}
bool AttributeSchema::get_boolean(const ByteArray &ba) const
{
ByteArray tmp(ba);
return tmp.popc() != 0;
}
float AttributeSchema::get_float (const ByteArray &ba) const
{
if(type == TYPE_FLOAT)
{
ByteArray tmp(ba);
return tmp.popf();
}
else if(type == TYPE_INT)
{
return get_int(ba);
}
else if(type == TYPE_BOOLEAN)
{
return get_int(ba);
}
else
{
erreur("AttributeSchema::get_float(): invalid type.");
return 0.0;
}
}
string AttributeSchema::get_string (const ByteArray &ba) const
{
string s;
switch(type)
{
case TYPE_INT:
{
int i = get_int(ba);
if(is_hexa)
s = string("0x") + utils::str::int2strhexa(i);
else
s = utils::str::int2str(i);
return s;
}
case TYPE_BOOLEAN:
{
return get_boolean(ba) ? "true" : "false";
}
case TYPE_FLOAT:
{
float f = get_float(ba);
char buf[500];
if(digits >= 0)
{
char buf1[50];
sprintf(buf1, "%%.%df", digits);
sprintf(buf, buf1, f);
}
else
sprintf(buf, "%f", f);
return string(buf);
}
default:
case TYPE_FOLDER:
case TYPE_STRING:
{
ByteArray tmp(ba);
return tmp.pops();
}
}
string id = name.get_id();
erreur("%s: type unspecified, att name = %s.", __func__, id.c_str());
return "?";
}
bool AttributeSchema::is_valid(const ByteArray &ba) const
{
if(type == TYPE_INT)
{
if((unsigned int) size != ba.size())
{
return false;
}
}
else if(type == TYPE_FLOAT)
{
if(ba.size() != 4)
return false;
}
else if(type == TYPE_BOOLEAN)
{
if(ba.size() != 1)
return false;
}
return true;
}
int AttributeSchema::serialize(ByteArray &ba, int value) const
{
if(type == TYPE_FLOAT)
{
ba.putf((float) value);
return 0;
}
else if(type == TYPE_BOOLEAN)
{
ba.putc((value == 0) ? 0 : 1);
return 0;
}
if(type != TYPE_INT)
{
avertissement("serialize(int): not an int!");
}
if(size == 8)
ba.putL(value);
else if(size == 4)
ba.putl(value);
else if(size == 2)
ba.putw(value);
else if(size == 1)
ba.putc(value);
return 0;
}
int AttributeSchema::serialize(ByteArray &ba, bool value) const
{
ba.putc(value ? 0x01 : 0x00);
return 0;
}
int AttributeSchema::serialize(ByteArray &ba, float value) const
{
if(type == TYPE_INT)
return serialize(ba, (int) value);
ba.putf(value);
return 0;
}
int AttributeSchema::serialize(ByteArray &ba, const std::string &value_) const
{
std::string value = value_;
const AttributeSchema &as = *this;
switch(as.type)
{
/*case TYPE_BLOB:
{
ba.putl(blob.size());
ba.put(blob);
break;
}*/
case TYPE_INT:
{
int val = 0;
if(enumerations.size() > 0)
{
for(const auto &e: enumerations)
{
if((value == e.name.get_id()) || (value == e.name.get_localized()))
{
value = e.value;
break;
}
}
}
if(is_hexa)
{
std::string s = value;
const char *c = s.c_str();
if(((c[0] == '0') && (c[1] == 'x'))
|| ((c[0] == '0') && (c[1] == 'X')))
{
sscanf(c+2, "%x", &val);
}
else
val = atoi(s.c_str());
}
else
{
val = atoi(value.c_str());
}
if(as.size == 1)
{
uint8_t v = (uint8_t) val;
ba.putc(v);
}
else if(as.size == 2)
{
uint16_t v = (uint16_t) val;
ba.putw(v);
}
else if(as.size == 4)
{
uint32_t v = (uint32_t) val;
ba.putl(v);
}
else if(as.size == 8)
{
uint64_t v = (uint64_t) val;
ba.putL(v);
}
break;
}
case TYPE_BOOLEAN:
{
if(value.compare("true") == 0)
ba.putc(1);
else
ba.putc(0);
break;
}
case TYPE_FLOAT:
{
std::string s = value;
float result;
for(unsigned int i = 0; i < s.size(); i++)
{
if(s[i] == ',')
s[i] = '.';
}
std::istringstream istr(s);
istr.imbue(std::locale("C"));
istr >> result;
ba.putf(result);
//infos("Conversion string >> float : %s >> %f", s.c_str(), result);
//result = atof(s.c_str());
//printf("get_float: %s -> %f\n", s.c_str(), result);
//printf("get_float: %s -> %f\n", s.c_str(), result);
//return result;
break;
}
default:
case TYPE_STRING:
{
ba.puts(value);
break;
}
}
return 0;
}
void Attribute::serialize(ByteArray &ba) const
{
ba.put(value);
}
void Attribute::unserialize(ByteArray &ba)
{
ByteArray new_value;
//value.clear();
//infos("unserialize()...");
switch(schema->type)
{
case TYPE_INT:
{
ba.pop(new_value, schema->size);
//infos("int unserialization: size = %d, new size = %d.", schema->size, new_value.size());
break;
}
case TYPE_FLOAT:
{
ba.pop(new_value, 4);
break;
}
case TYPE_BLOB:
{
uint32_t len = ba.popl();
ba.pop(new_value, len);
break;
}
case TYPE_BOOLEAN:
{
ba.pop(new_value, 1);
break;
}
case TYPE_STRING:
default:
{
string s = ba.pops();
new_value.puts(s);
break;
}
}
if(value != new_value)
{
value = new_value;
//infos("unserialization: size = %d.", value.size());
if(!inhibit_event_dispatch)
{
value_changed();
ChangeEvent ce = ChangeEvent::create_att_changed(this);
//ce.source = this;
ce.path = XPath(XPathItem(schema->name.get_id()));
//ce.source_node = nullptr;//new Node(parent);
dispatch(ce);
//delete ce.source_node;
}
}
}
float Attribute::get_float() const
{
return schema->get_float(value);
}
bool Attribute::get_boolean() const
{
if(__builtin_expect(schema.is_nullptr(), 0))
{
erreur("get_bool : schema = null.");
return false;
}
return schema->get_boolean(value);
}
int Attribute::get_int() const
{
return schema->get_int(value);
}
void Node::add_listener(CListener<ChangeEvent> *lst)
{
if(__builtin_expect(data != nullptr, 1))
data->CProvider<ChangeEvent>::add_listener(lst);
}
void Node::remove_listener(CListener<ChangeEvent> *lst)
{
if(__builtin_expect(data != nullptr, 1))
data->CProvider<ChangeEvent>::remove_listener(lst);
}
int NodeSchema::get_sub_index(const string &name) const
{
map<string, int>::const_iterator it = mapper.find(name);
if(__builtin_expect(it == mapper.end(), 0))
return -1;
return it->second;
}
void RamNode::remove_child(Node child)
{
int index = schema->get_sub_index(child.schema()->name.get_id());
if(index == -1)
{
erreur("%s: no such child.", __func__);
return;
}
std::deque<Node>::iterator it;
for (it = children[index].nodes.begin(); it != children[index].nodes.end(); it++)
{
if(child == *it)
{
children[index].nodes.erase(it);
return;
}
}
erreur("Can't erase children.");
}
void RamNode::add_children(const std::string &type, const std::vector<const MXml *> &lst)
{
unsigned int n = lst.size();
int index = schema->get_sub_index(type);
if(__builtin_expect(index == -1, 0))
{
erreur("Type invalide : %s", type.c_str());
return;
}
SubSchema &ss = schema->children[index];
NodeSchema *schema = ss.ptr;
NodeCol &col = children[index];
unsigned int id = col.nodes.size();
for(auto i = 0u; i < n; i++)
{
Node nv(new RamNode(schema));
RamNode *nvram = (RamNode *) nv.data;
nvram->CProvider<ChangeEvent>::add_listener(this);
nvram->instance = id;
nvram->parent = this;
nvram->sub_type = type;
nvram->type = type;
col.nodes.push_back(nv);
id++;
nv.fromXml(*(lst[i]));
}
}
Node RamNode::add_child(const string sub_name)
{
int index = schema->get_sub_index(sub_name);
if(index == -1)
{
auto s = schema->to_string();
infos("Schema = \n%s\n", s.c_str());
infos("Mapper:");
std::map<string,int>::iterator it;
for(it = schema->mapper.begin(); it != schema->mapper.end(); it++)
{
infos("map(%s) = %d.", (*it).first.c_str(), (*it).second);
}
erreur("%s: no such child: %s.", __func__, sub_name.c_str());
return Node();
}
SubSchema &ss = schema->children[index];
Node nv(new RamNode(ss.ptr));
RamNode *nvram = (RamNode *) nv.data;
children[index].nodes.push_back(nv);
nvram->parent = this;
nvram->instance = children[index].nodes.size() - 1;
nvram->sub_type = sub_name;
nvram->type = sub_name;
return nv;
}
void RamNode::on_event(const ChangeEvent &ce)
{
event_detected = true;
if(inhibit_event_raise)
return;
//infos(ce.to_string());
if((ce.type == ChangeEvent::GROUP_CHANGE) && (inhibit_event_raise))
return;
// must not dispatch a group change to its parent
// but to external yes !
// Dispatch all normal events to parent
if((ce.type != ChangeEvent::GROUP_CHANGE))// && (!inhibit_event_raise))
{
ChangeEvent nce = ce;
XPathItem xpi(schema->name.get_id(), instance);
nce.path = ce.path.add_parent(xpi);
//infos("ram_node::on_event -> dispatch... %s", nce.to_string().c_str());
CProvider<ChangeEvent>::dispatch(nce);
}
// For each normal event, create a group change
if((ce.type != ChangeEvent::GROUP_CHANGE) && (!inhibit_event_raise))
{
ChangeEvent nce;
nce.type = ChangeEvent::GROUP_CHANGE;
XPathItem xpi(schema->name.get_id(), instance);
nce.path = XPath(xpi);
CProvider<ChangeEvent>::dispatch(nce);
}
}
bool Node::get_attribute_as_boolean(const string &name) const
{
if(data == nullptr)
{
erreur("%s: data est nul.", __func__);
return false;
}
const Attribute *att = get_attribute(name);
if(att == nullptr)
{
erreur("%s: echec get_att.", __func__);
return false;
}
return att->get_boolean();
}
std::string Node::get_attribute_as_string(const string &name) const
{
const Attribute *att = get_attribute(name);
if(att != nullptr)
return att->get_string();
return "";
}
ByteArray Node::get_attribute_as_raw(const string &name) const
{
const Attribute *att = get_attribute(name);
if(att != nullptr)
return att->value;
return ByteArray();
}
float Node::get_attribute_as_float(const string &name) const
{
const Attribute *att = get_attribute(name);
if(att != nullptr)
return att->get_float();
return 0.0;
}
int Node::get_attribute_as_int(const string &name) const
{
const Attribute *att = get_attribute(name);
if(att != nullptr)
return att->get_int();
return 0;
}
XPath::XPath(const char *s)
{
from_string(string(s));
}
XPath::XPath(const XPathItem &xpi)
{
items.push_back(xpi);
valid = true;
}
void Node::serialize(ByteArray &res) const
{
uint32_t i, n, m;
/* Serialize contents */
n = schema()->attributes.size();
for(i = 0; i < n; i++)
{
Attribute *att = data->get_attribute_at(i);
att->serialize(res);
}
n = schema()->children.size();
for(i = 0; i < n; i++)
{
std::string cname = schema()->children[i].name.get_id();
m = get_children_count(cname);
res.putl(m);
for(const Node &child: children(cname))
{
child.serialize(res);
}
}
}
void Node::unserialize(ByteArray &source)
{
uint32_t i, j, k, n, m;
if(data == nullptr)
{
erreur("%s: data == nullptr.", __func__);
return;
}
data->inhibit_event_raise = true;
data->event_detected = false;
/* Serialize contents */
n = schema()->attributes.size();
for(i = 0; i < n; i++)
{
data->get_attribute_at(i)->unserialize(source);
}
//get_attribute(schema()->attributes[i]->name.get_id())->unserialize(source);
n = schema()->children.size();
for(i = 0; i < n; i++)
{
std::string cname = schema()->children[i].name.get_id();
// m is the new number of children
if(source.size() < 4)
{
erreur("unserialization: incomplete source.");
return;
}
m = source.popl();
// k is the old number of children
k = get_children_count(cname);
//infos("unserialize type %s: local count = %d, new count = %d.",
// cname.c_str(), k, m);
// Update existing nodes
for(j = 0; (j < k) && (j < m); j++)
get_child_at(cname, j).unserialize(source);
// Add new nodes
if(m > k)
{
for(j = 0; j + k < m; j++)
{
Node e = add_child(schema()->children[i].ptr);
e.unserialize(source);
}
}
// Remove old nodes
if(m < k)
{
for(j = 0; j + m < k; j++)
remove_child(get_child_at(cname, k - 1 - j));
}
}
data->inhibit_event_raise = false;
if(data->event_detected)
{
ChangeEvent ce;
XPathItem xpi(schema()->name.get_id(), data->instance);
ce.path = XPath(xpi);
ce.type = ChangeEvent::GROUP_CHANGE;
data->dispatch(ce);
}
}
int Node::get_path_to(const Node &child, XPath &res)
{
unsigned int j;
if(schema() == nullptr)
{
erreur("get_path_to: no schema.");
return -1;
}
if(child == *this)
{
res = XPath();
return 0;
}
for(SubSchema &ss: schema()->children)
{
std::string sub_name = ss.name.get_id();//ss.ptr->name.get_id();
//infos("check sub %s: %d elems.", sub_name.c_str(), get_children_count(sub_name));
j = 0;
for(Node cld: children(sub_name))
{
XPath intpath;
if(cld.get_path_to(child, intpath) == 0)
{
XPathItem xpi;
if((ss.default_key.size() > 0) && (cld.has_attribute(ss.default_key)))
{
xpi.att_name = ss.default_key;
xpi.att_value = cld.get_attribute_as_string(ss.default_key);
}
else
{
xpi.instance = j;
}
xpi.name = sub_name;
res = intpath.add_parent(xpi);
return 0;
}
j++;
}
}
return -1;
}
XPathItem::XPathItem()
{
name = "";
instance = 0;
}
XPathItem::XPathItem(const string &name, int instance)
{
this->name = name;
this->instance = instance;
}
XPathItem::XPathItem(const string &name, const string &att_name, const string &att_value)
{
instance = -1;
this->att_name = att_name;
this->att_value = att_value;
}
XPathItem::~XPathItem()
{
}
XPath::XPath(const XPath &root, const string &leaf, int instance)
{
*this = root;
XPathItem xpi(leaf, instance);
items.push_back(xpi);
}
Node Node::get_child(const XPath &path)
{
Node res;
if(!path.is_valid())
{
erreur("get_child_from_path(): invalid path.");
return res;
}
if(path.length() == 0)
return *this;
XPathItem root = path.root();
//if(root.name.compare("") == 0)
//return root_model.get_child(path.child());
if(root.name.compare("..") == 0)
{
if(parent().is_nullptr())
{
erreur("get_child_from_path(%s): no parent.",
path.c_str());
return res;
}
return parent().get_child(path.child());
}
if(root.name.compare(".") == 0)
{
return get_child(path.child());
}
if(!this->has_child(root.name))
{
avertissement("model = %s\n", to_xml(0,true).c_str());
erreur("get_child_from_path(%s): no such child: %s, len = %d.",
path.c_str(),
root.name.c_str(),
path.length());
return res;
}
int instance = root.instance;
if(instance < 0)
instance = 0;
if(root.att_name.size() > 0)
{
bool found = false;
Node child;
for(Node ch: children(root.name))
{
if(ch.get_attribute_as_string(root.att_name).compare(root.att_value) == 0)
{
found = true;
child = ch;
}
}
if(!found)
{
erreur("get_child_from_path(%s: %s = %s): no such child.",
path.c_str(), root.att_name.c_str(), root.att_value.c_str());
return res;
}
return child.get_child(path.child());
}
if(instance >= (int) get_children_count(root.name))
{
erreur("get_child_from_path(%s): no such child instance: %s[%d].",
path.c_str(), root.name.c_str(), instance);
infos("model = %s\n", to_xml(0,true).c_str());
return res;
}
return get_child_at(root.name, instance).get_child(path.child());
}
const Node Node::get_child(const XPath &path) const
{
Node res;
if(!path.is_valid())
{
erreur("get_child_from_path(): invalid path.");
return res;
}
if(path.length() == 0)
return *this;
XPathItem root = path.root();
//if(root.name.compare("") == 0)
//return root_model.get_child(path.child());
if(root.name.compare("..") == 0)
{
if(parent().is_nullptr())
{
erreur("get_child_from_path(%s): no parent.",
path.c_str());
return res;
}
return parent().get_child(path.child());
}
if(root.name.compare(".") == 0)
{
return get_child(path.child());
}
if(!this->has_child(root.name))
{
avertissement("model = %s\n", to_xml(0,true).c_str());
erreur("get_child_from_path(%s): no such child: %s, len = %d.",
path.c_str(),
root.name.c_str(),
path.length());
return res;
}
int instance = root.instance;
if(instance < 0)
instance = 0;
if(root.att_name.size() > 0)
{
bool found = false;
Node child;
for(Node ch: children(root.name))
{
if(ch.get_attribute_as_string(root.att_name).compare(root.att_value) == 0)
{
found = true;
child = ch;
}
}
if(!found)
{
erreur("get_child_from_path(%s: %s=%s): no such child.",
path.c_str(), root.att_name.c_str(), root.att_value.c_str());
return res;
}
return child.get_child(path.child());
}
if(instance >= (int) get_children_count(root.name))
{
erreur("get_child_from_path(%s): no such child instance: %s[%d].",
path.c_str(), root.name.c_str(), instance);
infos("model = %s\n", to_xml(0,true).c_str());
return res;
}
return get_child_at(root.name, instance).get_child(path.child());
}
std::string Node::description() const
{
if(has_child("description"))
{
std::string res = get_child_at("description", 0).get_attribute_as_string("content");
for(unsigned int i = 0; i < get_children_count("description"); i++)
{
const Node &desc = get_child_at("description", i);
if(desc.get_attribute_as_string("lang") == Localized::language_id(Localized::current_language))
{
return desc.get_attribute_as_string("content");
}
}
return res;
}
else
{
return "";
}
}
bool Node::has_attribute(const XPath &path) const
{
if(data == nullptr)
return false;
if(path.length() == 1)
return (schema()->att_mapper.count(path[0].name) > 0);
Node owner = get_child(path.remove_last());
if(owner.is_nullptr())
return false;
return owner.has_attribute(path.get_last());
}
string Node::get_fullpath() const
{
string res = schema()->name.get_id();
if(!parent().is_nullptr())
res = parent().get_fullpath() + "/" + res;
return res;
}
Attribute *Node::get_attribute(const XPath &path)
{
if(path.length() == 1)
{
if(schema()->att_mapper.count(path[0].name) == 0)
{
string fpath = get_fullpath() + "/" + path[0].name;
erreur("Attribute not found: %s. Current path = %s.", path.c_str(), fpath.c_str());
return nullptr;
}
int index = schema()->att_mapper[path[0].name];
return data->get_attribute_at(index);
}
Node owner = get_child(path.remove_last());
if(owner.is_nullptr())
{
string fpath = get_fullpath();
erreur("Attribute not found: %s. Current path = %s.", path.c_str(), fpath.c_str());
return nullptr;
}
return owner.get_attribute(path.get_last());
}
const Attribute *Node::get_attribute(const XPath &path) const
{
if(path.length() == 1)
{
if(schema() == nullptr)
{
auto s = path.to_string();
erreur("Schema null / get_att(%s)", s.c_str());
return nullptr;
}
if(schema()->att_mapper.count(path[0].name) == 0)
{
auto s = schema()->name.get_id();
erreur("Attribute not found: %s (in %s). Aborting...", path.c_str(), s.c_str());
return nullptr;
}
int index = schema()->att_mapper[path[0].name];
return data->get_attribute_at(index);
}
const Node owner = get_child(path.remove_last());
if(owner.is_nullptr())
{
erreur("Attribute not found: %s. Aborting...", path.c_str());
return nullptr;
}
return owner.get_attribute(path.get_last());
}
int Node::set_attribute(const XPath &path, const ByteArray &value)
{
Attribute *att = get_attribute(path);
if(att == nullptr)
return -1;
att->set_value(value);
return 0;
}
int Node::set_attribute(const XPath &path, const string &value)
{
Attribute *att = get_attribute(path);
if(att == nullptr)
return -1;
att->set_value(value);
return 0;
}
int Node::set_attribute(const XPath &path, bool value)
{
if(value)
return set_attribute(path, std::string("true"));
return set_attribute(path, std::string("false"));
}
int Node::set_attribute(const XPath &path, int value)
{
Attribute *att = get_attribute(path);
if(att == nullptr)
return -1;
att->set_value(value);
return 0;
}
int Node::set_attribute(const XPath &path, float value)
{
Attribute *att = get_attribute(path);
if(att == nullptr)
return -1;
att->set_value(value);
return 0;
}
int Node::set_attribute(const XPath &name, const char *value)
{
return set_attribute(name, string(value));
}
unsigned long RamNode::get_attribute_count() const
{
return attributes.size();
}
const Attribute *RamNode::get_attribute_at(unsigned int i) const
{
if(i >= attributes.size())
{
erreur("%s: invalid att index:%d/%d", i, attributes.size());
return nullptr;
}
return &attributes[i];
}
Attribute *RamNode::get_attribute_at(unsigned int i)
{
if(i >= attributes.size())
{
erreur("%s: invalid att index:%d/%d", __func__, i, attributes.size());
return nullptr;
}
return &attributes[i];
}
std::string Node::get_identifier(bool disp_type, bool bold) const
{
// TODOOOOOOOOOOOOOOOOOOOOOOOOOO
std::string str_type = schema()->name.get_localized();
if(str_type.compare("?") == 0)
{
erreur("%s: schema name is not defined.", __func__);
}
if(langue.has_item(str_type))
str_type = langue.get_item(str_type);
/** If has a parent, preferably take the name of sub */
Node prt = parent();
if(!prt.is_nullptr())
{
NodeSchema *es = prt.schema();
for(unsigned int i = 0; i < es->children.size(); i++)
{
SubSchema &ss = es->children[i];
if((ss.child_str.compare(schema()->name.get_id()) == 0)
&& (ss.name.get_id().compare(ss.child_str)))
{
str_type = ss.name.get_localized();
}
}
}
if(!this->has_attribute("name"))
return str_type;
if(!disp_type)
{
auto lgs = Localized::language_list();
for(auto lg: lgs)
{
auto id = Localized::language_id(lg);
if((lg == Localized::current_language)
&& has_attribute(id) && (get_attribute_as_string(id).size() > 0))
return get_attribute_as_string(id);
}
// Default to english if available and no other translation available
if(has_attribute("en") && (get_attribute_as_string("en").size() > 0))
return get_attribute_as_string("en");
return get_attribute_as_string("name");
}
if(Localized::current_language == Localized::LANG_FR)
{
std::string nm;
if(has_attribute("fr"))
nm = get_attribute_as_string("fr");
if(nm.size() == 0)
nm = name();
if(bold)
return str_type + " <b>" + nm + "</b>";
else
return str_type + " " + nm;
}
else
{
if(bold)
return std::string("<b>") + name() + "</b> " + str_type ;
else
return name() + " " + str_type;
}
}
unsigned long RamNode::get_children_count(const string &type) const
{
int index = schema->get_sub_index(type);
if(index == -1)
return 0;
if(index >= (int) children.size())
{
erreur("get_children_count(%s): unitialized container.", type.c_str());
return 0;
}
return children[index].nodes.size();
}
unsigned long RamNode::get_children_count(int type) const
{
if(type >= (int) children.size())
{
erreur("get_children_count(%d): unitialized container.", type);
return 0;
}
return children[type].nodes.size();
}
std::string Node::type() const
{
if(data == nullptr)
return "";
return data->type;
}
NodeSchema *Node::schema() const
{
if(__builtin_expect(data == nullptr, 0))
{
erreur("Node::schema(): no schema.");
return nullptr;
}
return data->schema;
}
const Node RamNode::get_child_at(const string &type, unsigned int instance) const
{
int index = schema->get_sub_index(type);
if(index < 0)
{
erreur("get_children_at(%s,%d): invalid type.", type.c_str(), instance);
return Node();
}
if(index >= (int) children[index].nodes.size())
{
erreur("get_children_at(%s,%d): invalid index.", type.c_str(), instance);
return Node();
}
return children[index].nodes[instance];
}
const Node RamNode::get_child_at(int type, unsigned int instance) const
{
if(type >= (int) children.size())
{
erreur("%s: invalid type.", __func__);
return Node();
}
if(instance >= children[type].nodes.size())
{
erreur("get_children_at(%d,%d): invalid index.", type, instance);
return Node();
}
return children[type].nodes[instance];
}
Node RamNode::get_child_at(int type, unsigned int instance)
{
if(type >= (int) children.size())
{
erreur("%s: invalid type.", __func__);
return Node();
}
if(instance >= children[type].nodes.size())
{
erreur("get_children_at(%d,%d): invalid index.", type, instance);
return Node();
}
return children[type].nodes[instance];
}
Node RamNode::get_child_at(const string &type, unsigned int instance)
{
int index = schema->get_sub_index(type);
if(index < 0)
{
erreur("get_child_at(%s,%d): invalid type.", type.c_str(), instance);
return Node();
}
if(index >= (int) children.size())
{
erreur("get_child_at(%s,%d): Child container not ready.",
type.c_str(), instance);
return Node();
}
if(instance >= children[index].nodes.size())
{
erreur("get_child_at(%s,%d): invalid index (max = %d).",
type.c_str(), instance, ((int) children[index].nodes.size()) - 1);
return Node();
}
return children[index].nodes[instance];
}
bool Node::has_child(const XPath &path) const
{
if(path.length() == 0)
{
erreur("has_child("")!");
return true;
}
else if(path.length() == 1)
{
/* Must check an attribute value */
if(path[0].att_name.size() > 0)
{
for(const Node child: children(path[0].name))
{
if(child.get_attribute_as_string(path[0].att_name).compare(path[0].att_value) == 0)
return true;
}
return false;
}
else
return (get_children_count(path.to_string()) > 0);
}
else
{
XPath first = path.get_first();
return get_child(first).has_child(path.child());
}
}
Node Node::clone() const
{
Node res = Node::create_ram_node(schema());
res.copy_from(*this);
return res;
}
void Node::copy_from(const Node e)
{
unsigned int i, n;
// Must group different change events
// into a single one.
if(data == nullptr)
return;
data->inhibit_event_raise = true;
data->event_detected = false;
n = e.get_reference_count();
for(i = 0; i < n; i++)
{
std::string name;
Node ref = e.get_reference_at(i, name);
//infos("copy ref.");
set_reference(name, ref);
}
n = e.data->get_attribute_count();
for(unsigned int i = 0; i < n; i++)
{
Attribute *att = e.data->get_attribute_at(i);
set_attribute(att->schema->name.get_id(), att->value);
}
for(SubSchema &ss: schema()->children)
{
uint32_t dim0 = get_children_count(ss.name.get_id());
uint32_t dim1 = e.get_children_count(ss.name.get_id());
if(dim0 == dim1)
{
for(unsigned int j = 0; j < dim0; j++)
{
get_child_at(ss.name.get_id(), j).copy_from(e.get_child_at(ss.name.get_id(), j));
}
}
else if(dim0 < dim1)
{
//trace_major("%d<%d (ADD) on %s.", dim0, dim1, ss.name.c_str());
for(unsigned int j = 0; j < dim0; j++)
get_child_at(ss.name.get_id(), j).copy_from(e.get_child_at(ss.name.get_id(), j));
for(unsigned int j = 0; j < (dim1 - dim0); j++)
add_child(e.get_child_at(ss.name.get_id(), dim0 + j));
}
else if(dim0 > dim1)
{
//trace_major("%d>%d (DEL) on %s.", dim0, dim1, ss.name.c_str());
for(unsigned int j = 0; j < dim1; j++)
get_child_at(ss.name.get_id(), j).copy_from(e.get_child_at(ss.name.get_id(), j));
for(unsigned int j = 0; j < (dim0 - dim1); j++)
remove_child(get_child_at(ss.name.get_id(), dim1));
}
}
data->inhibit_event_raise = false;
if(data->event_detected)
{
auto s = schema()->name.get_id();
infos("Dispatch ensemble des evt precedents [%s]...", s.c_str());
ChangeEvent ce;
XPathItem xpi(schema()->name.get_id(), data->instance);
ce.path = XPath(xpi);
ce.type = ChangeEvent::GROUP_CHANGE;
data->dispatch(ce);
}
}
std::string Node::get_localized_name() const
{
if(this->data == nullptr)
return "null";
auto l = get_localized();
return l.get_localized();
# if 0
std::string res = this->type();
if(Localized::current_language == Localized::LANG_FR)
{
if(has_attribute("fr") && (get_attribute_as_string("fr").size() > 0))
return get_attribute_as_string("fr");
}
if(has_attribute("en") && (get_attribute_as_string("en").size() > 0))
return get_attribute_as_string("en");
if(has_attribute("name") && (name().size() > 0))
return name();
return res;
# endif
}
int Node::load(const string &schema_file, const string &data_file)
{
FileSchema fs;
if(fs.from_file(schema_file))
return -1;
Node n = Node::create_ram_node(fs.root, data_file);
*this = n;
return 0;
}
/// ??????
void Node::load(const string &filename)
{
Node n = Node::create_ram_node(schema(), filename);
copy_from(n);
}
int Node::save(const string &filename,
bool store_default_values)
{
infos("Enregistrement noeud vers [%s]...", filename.c_str());
string path, file;
files::split_path_and_filename(filename, path, file);
infos(" conversion vers chaine de caracteres...");
auto s = to_xml(0, store_default_values, true, false, path);
infos(" enregistrement...");
int res = files::save_txt_file(filename,
std::string("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + s);
infos("Ok.");
return res;
}
Node::Node(NodeSchema *schema, const std::string &fichier_source)
{
data = nullptr;
if(fichier_source.size() > 0)
*this = create_ram_node(schema, fichier_source);
else
*this = create_ram_node(schema);
}
Node::Node(const Node &e)
{
data = e.data;
if(data != nullptr)
data->reference();
}
Node::Node(Node &e)
{
data = e.data;
if(data != nullptr)
data->reference();
}
RamNode::~RamNode()
{
uint32_t i, j;
if(nb_references > 0)
{
erreur("delete, but nref = %d.", nb_references);
}
for(i = 0; i < attributes.size(); i++)
attributes[i].CProvider<ChangeEvent>::remove_listener(this);
for(i = 0; i < children.size(); i++)
{
for(j = 0; j < children[i].nodes.size(); j++)
children[i].nodes[j].data->remove_listener(this);
}
}
void Node::setup_default_subs()
{
if(__builtin_expect(schema() == nullptr, 0))
{
erreur("setup_default_subs: no schema.");
return;
}
for(SubSchema &ss: schema()->children)
{
NodeSchema *es = ss.ptr;
string subtype = es->name.get_id();
while(get_children_count(es->name.get_id()) < (unsigned int) ss.default_count)
add_child(es);
for(Node child: children(subtype))
child.setup_default_subs();
}
}
void Node::check_min()
{
if(__builtin_expect((data == nullptr) || (schema() == nullptr), 0))
return;
for(SubSchema &ss: schema()->children)
{
NodeSchema *es = ss.ptr;
if(__builtin_expect(es == nullptr, 0))
{
erreur("Schema ptr is nullptr: %s.", ss.child_str.c_str());
}
else if(ss.has_min())
{
while(get_children_count(es->name.get_id()) < (unsigned int) ss.min)
add_child(es);
}
}
}
void Node::setup_refs()
{
uint32_t i, j;
// Search for references
for(i = 0; i < schema()->references.size(); i++)
{
RefSchema rs = schema()->references[i];
//infos("Search reference for %s...", rs.name.get_id().c_str());
XPath path = get_reference_path(rs.name.get_id());
//infos("Path = %s", path.to_string().c_str());
//infos("Root path = %s", rs.path.c_str());
XPath full_path(rs.path + "/" + path.to_string());
//infos("Full path = %s", full_path.to_string().c_str());
Node target = get_child(full_path);
if(target.is_nullptr())
{
erreur("Referring node not found.");
}
else
{
set_reference(rs.name.get_id(), target);
}
}
for(i = 0; i < schema()->children.size(); i++)
{
string type = schema()->children[i].name.get_id();
unsigned int n = get_children_count(type);
for(j = 0; j < n; j++)
get_child_at(type, j).setup_refs();
}
}
XPath Node::get_reference_path(const string &name)
{
if(data == nullptr)
{
erreur("get_reference_path on nullptr node.");
return XPath();
}
return data->get_reference_path(name);
}
XPath RamNode::get_reference_path(const string &name)
{
for(unsigned int i = 0; i < references.size(); i++)
{
if(references[i].name.compare(name) == 0)
{
XPath res = references[i].path;
if(res.to_string().size() == 0)
{
if(!references[i].ptr.is_nullptr())
{
//warning("get_reference_path(): must build path from ptr.");
}
continue;
/*erreur("get_ref_path: nullptr path returned.");
for(unsigned int j = 0; j < references.size(); j++)
{
infos("ref[%d] = %s", j, references[i].name.c_str());
}*/
}
return res;
}
}
avertissement("get_reference_path(%s): not found.", name.c_str());
return XPath();
}
std::string Node::class_name() const
{
if(data == nullptr)
return "nullptr-node";
std::string res = "node";
//printf("class_name: type()...\n"); fflush(0);
if(type().size() > 0)
res += std::string("/") + type();
return res;
}
void Node::setup_schema()
{
unsigned int i;
if(__builtin_expect(schema() == nullptr, 0))
return;
auto &rlist = data->schema->references;
auto nrefs = rlist.size();
for(i = 0; i < nrefs; i++)
if(!has_reference(rlist[i].name.get_id()))
set_reference(rlist[i].name.get_id(), Node());
}
RamNode::RamNode(NodeSchema *schema)
{
inhibit_event_raise = false;
instance = 0;
parent = nullptr;
if(__builtin_expect(schema == nullptr, 0))
{
erreur("constructeur sans schema.");
}
/* To manage dereferencing of elt. */
{
nb_references = 1;
this->schema = schema;
for(const SubSchema &ss: schema->children)
{
NodeCol nc;
nc.type = ss.name.get_id();
children.push_back(nc);
}
for(const refptr<AttributeSchema> &as: schema->attributes)
{
Attribute att(as);
attributes.push_back(att);
attributes[attributes.size() - 1].parent = this;
attributes[attributes.size() - 1].CProvider<ChangeEvent>::add_listener(this);
}
{
Node elt(this);
type = schema->name.get_id();
elt.setup_schema();
elt.check_min();
elt.setup_default_subs();
}
}
nb_references = 0;
}
RamNode::RamNode()
{
inhibit_event_raise = false;
instance = 0;
parent = nullptr;
{
nb_references = 1;
Node elt(this);
}
nb_references = 0;
}
void Node::fromXml(const MXml &e, const string &root_path)
{
data->type = e.name;
auto schem = schema();
/* Special management of description which can
* contain embedded HTML/XML content not to be analyzed here. */
if(e.name == "description")
set_attribute("content", e.dump_content());
unsigned int n = e.attributes.size();
for(unsigned int i = 0; i < n; i++)
{
const XmlAttribute &xa = e.attributes[i];
// check references
if(__builtin_expect(schem->has_reference(xa.name), 0))
{
set_reference(xa.name, XPath(xa.to_string()));
continue;
}
if(schem->att_mapper.count(xa.name) == 0)
{
avertissement("No such attribute: %s.", xa.name.c_str());
continue;
}
int index = schema()->att_mapper[xa.name];
Attribute *att = data->get_attribute_at(index);
std::string s = xa.string_value;
std::string value = s;
auto &as = att->schema;//schem->get_attribute(xa.name);
if((as->type == TYPE_STRING)
|| (as->type == TYPE_FILE)
|| (as->type == TYPE_FOLDER))
{
char *tmp = (char *) malloc(s.size() + 1);
unsigned int ko = 0;
for(unsigned int k = 0; k < s.size(); k++)
{
if(s[k] != '\\')
{
tmp[ko++] = s[k];
}
else if((k + 1 < s.size()) && (s[k+1] == 'G'))
{
k++;
tmp[ko++] = '"';
}
else if((k + 1 < s.size()) && (s[k+1] == '\\'))
{
k++;
tmp[ko++] = '\\';
}
else
{
tmp[ko++] = s[k];
}
}
tmp[ko] = 0;
value = std::string(tmp);
free(tmp);
if((as->type == TYPE_FILE) && (root_path.size() > 0))
{
// Convert relative path to absolute path.
string abs;
if(files::rel2abs(root_path, value, abs))
{
avertissement("Relative path to absolute path conversion failed.");
}
else
{
/*infos("Converted rel path to abs: ref = [%s], rel = [%s], abs = [%s].",
root_path.c_str(), value.c_str(), abs.c_str());*/
value = abs;
}
}
}
//XPathItem xpi(xa.name);
//XPath xp(xpi);
//set_attribute(xp, value);
att->set_value(value);
}
for(const SubSchema &ss: schem->children)
{
std::string sname = ss.name.get_id();
unsigned int n0 = get_children_count(sname);
std::vector<const MXml *> lst;
e.get_children(sname, lst);
unsigned int n1 = lst.size();
if((n1 > 0) && (n0 == 0))
{
data->add_children(sname, lst);
}
else
{
for(unsigned int k = 0; (k < n0) && (k < n1); k++)
get_child_at(sname, k).fromXml(*lst[k], root_path);
if(n1 > n0)
{
for(unsigned int k = 0; k < n1 - n0; k++)
{
Node nv = add_child(sname);
nv.fromXml(*lst[k + n0], root_path);
}
}
else if(n0 > n1)
{
}
}
}
}
const Node Node::get_reference(const string &name) const
{
unsigned int n = get_reference_count();
for(unsigned int i = 0; i < n; i++)
{
std::string ref_name;
Node elt;
elt = get_reference_at(i, ref_name);
if(ref_name.compare(name) == 0)
return elt;
}
erreur(std::string("reference not found: ") + name);
infos("%d ref available:", n);
for(unsigned int i = 0; i < n; i++)
{
std::string ref_name;
Node elt;
elt = get_reference_at(i, ref_name);
infos("ref #%d = %s.", i, ref_name.c_str());
}
return Node();
}
unsigned int RamNode::get_reference_count() const
{
return references.size();
}
bool Node::has_reference(const string &name) const
{
unsigned int i, n = get_reference_count();
for(i = 0; i < n; i++)
{
std::string ref_name;
Node elt;
elt = get_reference_at(i, ref_name);
if(ref_name.compare(name) == 0)
return true;
}
return false;
}
void RamNode::set_reference(const string &name, const XPath &xp)
{
RefSchema *rs = schema->get_reference(name);
if(rs == nullptr)
{
Node n(this);
erreur("set_ref: '%s' not found.", name.c_str());
return;
}
unsigned int i, n = references.size();
for(i = 0; i < n; i++)
{
if(references[i].name.compare(name) == 0)
{
references[i].path = xp;
return;
}
}
Reference rf;
rf.name = name;
rf.path = xp;
references.push_back(rf);
{
Node tmp(this);
infos("set_ref(%s = %s).", name.c_str(), xp.to_string().c_str());
}
}
void RamNode::set_reference(const string &name, Node e)
{
for(unsigned int i = 0; i < references.size(); i++)
{
if(references[i].name.compare(name) == 0)
{
references[i].ptr = e;
return;
}
}
if((!e.is_nullptr()) && (e.schema() != nullptr))
{
Reference rf;
rf.name = e.schema()->name.get_id();
rf.ptr = e;
references.push_back(rf);
Node elt(this);
infos("Set ref ok (%s -> ...)", rf.name.c_str());
}
else
{
Reference rf;
rf.name = name;
rf.ptr = e;
references.push_back(rf);
}
}
const Node RamNode::get_reference_at(unsigned int i, std::string &name) const
{
name = references[i].name;
return references[i].ptr;
}
std::string Node::to_xml_atts(unsigned int indent,
bool display_default_values,
bool charset_latin,
string root_path) const
{
std::string res = "";
std::vector<std::string > attnames, attvalues;
unsigned int n = data->get_attribute_count();
for(unsigned int i = 0; i < n; i++)
{
const Attribute *a = data->get_attribute_at(i);
//if(a.name.compare("description") == 0)
if((a->schema->name.get_id().compare("content") == 0) && (schema()->name.get_id().compare("description") == 0))
continue;
if(display_default_values
|| (a->value != a->schema->default_value)
|| (a->schema->type == TYPE_BLOB))
{
if(!a->schema->is_volatile)
{
attnames.push_back(a->schema->name.get_id());
string val = a->schema->get_string(a->value);
// If necessary, convert absolute path to relative path.
if((a->schema->type == TYPE_FILE) && (root_path.size() > 0))
{
// Must get the relative path to the file from the root path.
if((val.size() >= 2) && (val[1] != ':'))
{
string rel;
if(files::abs2rel(root_path, val, rel))
avertissement("Abs to rel path conversion failed.");
infos("Abs to relative: root = [%s], abs = [%s], rel = [%s].",
root_path.c_str(), val.c_str(), rel.c_str());
val = rel;
}
}
// TODO: must protect against following characters: <, >, "
std::string s2;
for(auto i = 0u; i < val.size(); i++)
{
if(val[i] == '"')
s2 += "\\\"";
else if(val[i] == '<')
s2 += "\\<";
if(val[i] == '>')
s2 += "\\>";
else
{
char tmp[2];
tmp[0] = val[i];
tmp[1] = 0;
s2 += std::string(tmp);
}
}
val = s2;
if(charset_latin)
val = utils::str::utf8_to_latin(val);
attvalues.push_back(val);
}
}
}
n = get_reference_count();
for(unsigned int i = 0; i < n; i++)
{
std::string ref_name;
Node rs = get_reference_at(i, ref_name);
if(rs.is_nullptr())
avertissement("Cannot save nullptr reference.");
else
{
XPath rel_path;
std::string ref_path;
RefSchema *rschema = schema()->get_reference(ref_name);
std::string root_path = rschema->path;
Node root = get_child(root_path);
if(root.is_nullptr())
{
erreur("unable to retrieve root path for ref. %s.", ref_name.c_str());
continue;
}
if(root.get_path_to(rs, rel_path))
{
erreur("to_xml(): unable to retrieve relative path for %s.", ref_name.c_str());
continue;
}
ref_path = rel_path.to_string();
infos("Save ref %s = %s.", ref_name.c_str(), ref_path.c_str());
attnames.push_back(ref_name);
attvalues.push_back(ref_path);//rs.name());
}
}
unsigned int max_att_len = 0;
for(unsigned int i = 0; i < attnames.size(); i++)
{
if(attnames[i].size() > max_att_len)
max_att_len = attnames[i].size();
}
for(unsigned int i = 0; i < attnames.size(); i++)
{
res += attnames[i];
for(unsigned int j = 0; j < max_att_len - attnames[i].size(); j++)
res += " ";
std::string s = attvalues[i];
char *tmp = (char *) malloc(s.size() * 3 + 10);
unsigned int ko = 0;
for(unsigned int k = 0; k < s.size(); k++)
{
if(s[k] == '"')
{
tmp[ko++] = '\\';
tmp[ko++] = 'G';
}
else if(s[k] == '\\')
{
tmp[ko++] = '\\';
tmp[ko++] = '\\';
}
else
{
tmp[ko++] = s[k];
}
}
tmp[ko] = 0;
res += std::string(" = \"") + /*attvalues[i]*/std::string(tmp) + "\"";
free(tmp);
if(i < attnames.size() - 1)
{
res += "\n";
for(unsigned int j = 0; j < indent + 2 + type().size(); j++)
res += " ";
}
}
return res;
}
std::string Node::text_resume(int indent) const
{
if(schema() == nullptr)
{
erreur("text_resume(): schema is nullptr.");
return "";
}
std::string s = "";
NodeSchema *sch = schema();
for(uint32_t k = 0; k < (uint32_t) indent; k++)
s += std::string(" ");
char buf[500];
sprintf(buf, "[%s]: ", sch->name.get_id().c_str());
s += std::string(buf);
for(uint32_t i = 0; i < sch->attributes.size(); i++)
{
sprintf(buf, "%s = %s%s", sch->attributes[i]->name.get_id().c_str(),
this->get_attribute_as_string(sch->attributes[i]->name.get_id().c_str()).c_str(),
(i + 1 < sch->attributes.size()) ? ", ": "");
s += std::string(buf);
}
s += std::string("\n");
for(uint32_t i = 0; i < sch->children.size(); i++)
{
NodeSchema *csch = sch->children[i].ptr;
unsigned int n = this->get_children_count(csch->name.get_id());
for(uint32_t k = 0; k < (uint32_t) indent; k++)
s += std::string(" ");
char buf[500];
sprintf(buf, "%s: %d childs.\n", csch->name.get_id().c_str(), n);
s += std::string(buf);
if(n < 10)
{
for(uint32_t j = 0; j < n; j++)
{
s += this->get_child_at(csch->name.get_id(), j).text_resume(indent + 2);
}
}
}
return s;
}
std::string Node::to_xml(unsigned int indent,
bool display_default_values,
bool display_spaces,
bool charset_latin,
string root_path) const
{
bool is_description = false;
if(is_nullptr())
return "";
if((schema()->name.get_id().compare("description") == 0))
is_description = true;
if(this->is_nullptr())
{
return "(nullptr node)";
}
if(schema() == nullptr)
{
if(type().size() == 0)
{
erreur("Cannot save node without schema nor type.");
return "";
}
}
std::string res = "";
if(display_spaces && !is_description)
{
for(unsigned int i = 0; i < indent; i++)
res += " ";
}
res += std::string("<") + type() + " ";
res += to_xml_atts(indent, display_default_values, charset_latin, root_path);
bool has_child = (get_children_count() > 0);
if((schema()->name.get_id().compare("description") == 0)
&& (get_attribute_as_string("content").size() > 0))
has_child = true;
if(!has_child)
{
return res + "/>\n";
}
res += ">";
if(!is_description)
res += "\n";
if(schema()->name.get_id().compare("description") == 0)
{
std::string content = get_attribute_as_string("content");
if(content.size() > 0)
{
if(charset_latin)
content = utils::str::utf8_to_latin(content);
res += content;
}
}
unsigned int n = schema()->children.size();
for(unsigned int i = 0; i < n; i++)
{
const SubSchema &ss = schema()->children[i];
string sname = ss.name.get_id();
unsigned int m = get_children_count(sname);//child_str);
for(unsigned int j = 0; j < m; j++)
res += get_child_at(sname, j).to_xml(indent+2, display_default_values, display_spaces, charset_latin, root_path);
}
if(display_spaces && !is_description)
{
for(unsigned int i = 0; i < indent; i++)
res += " ";
}
res = res + "</" + type() + ">";
//if(!is_description)
res += "\n";
return res;
}
void Reference::set_reference(Node elt)
{
ptr = elt;
}
Node Reference::get_reference()
{
return ptr;
}
std::string Reference::get_name()
{
return name;
}
static void accept_interval(std::vector<std::string> &cars, char c1, char c2)
{
for(char c = c1; c <= c2; c++)
{
char b[2];
b[0] = c;
b[1] = 0;
cars.push_back(std::string(b));
}
}
static void accept_utf8(std::vector<std::string> &cars, char c1, char c2)
{
char b[3];
b[0] = c1;
b[1] = c2;
b[2] = 0;
cars.push_back(std::string(b));
}
static void accept_all(std::vector<std::string> &cars)
{
unsigned int i;
accept_interval(cars, 'a', 'z');
accept_interval(cars, 'A', 'Z');
accept_interval(cars, '0', '9');
accept_interval(cars, '.', '.');
accept_interval(cars, '&', '&');
accept_interval(cars, '-', '-');
accept_interval(cars, '_', '_');
accept_interval(cars, '(', '(');
accept_interval(cars, ')', ')');
for(i = 0x80; i <= 0xbf; i++)
accept_utf8(cars, 0xc2, i);
for(i = 0xc0; i <= 0xfe; i++)
accept_utf8(cars, 0xc3, i);
accept_interval(cars, '"', '"');
accept_interval(cars, '\'', '\'');
accept_interval(cars, '=', '=');
accept_interval(cars, ' ', ' ');
}
void AttributeSchema::get_valid_chars(std::vector<std::string> &cars)
{
unsigned int i;
infos("get_valid_chars()..");
cars.clear();
if(constraints.size() > 0)
{
// combo or choice
}
else if((enumerations.size() > 0) && (has_max) && (max < 100))
{
// combo
}
else if((type == TYPE_STRING) && (is_ip))
{
cars.push_back(".");
for(i = 0; i < 10; i++)
cars.push_back(utils::str::int2str(i));
}
# if 0
else if((type == TYPE_STRING) && (regular_exp.size() > 0))
{
RegExp re;
if(re.from_string(regular_exp))
{
erreur("Failed to parse regexp: %s.", regular_exp.c_str());
return;
}
re.get_valid_chars(cars);
}
# endif
else if(type == TYPE_STRING)
{
/* Accept all characters */
accept_all(cars);
}
else if((type == TYPE_INT) && (is_hexa))
{
/* Accept int and 'x' symbol */
accept_interval(cars, '0', '9');
accept_interval(cars, 'x', 'x');
}
else if(type == TYPE_INT)
{
/* Accept int symbols */
accept_interval(cars, '0', '9');
}
else
{
avertissement("get_vchars: unmanaged type %d.", type);
}
infos("done.");
}
bool AttributeSchema::is_valid(std::string s)
{
const char *ss = s.c_str();
uint32_t i, n = s.size();
if((type == TYPE_STRING) && (is_ip))
{
//infos("check ip(%s)", ss);
if((s.compare("test") == 0) || (s.compare("localhost") == 0))
{
}
else
{
std::vector<int> ilist;
if(utils::str::parse_int_list(s, ilist))
{
avertissement("set_value(\"%s\"): invalid ip.", ss);
return false;
}
else
{
if(ilist.size() != 4)
{
avertissement("set_value(\"%s\"): invalid ip.", ss);
return false;
}
else
{
for(uint32_t i = 0; i < 4; i++)
{
if((ilist[i] < 0) || (ilist[i] > 255))
{
avertissement("set_value(\"%s\"): invalid ip.", ss);
return false;
}
}
}
}
}
}
else if(type == TYPE_BLOB)
{
return true;
}
else if(type == TYPE_COLOR)
{
ByteArray ba(s);
if(ba.size() != 3)
{
avertissement("Invalid color spec: %s.", s.c_str());
return false;
}
return true;
}
else if(type == TYPE_INT)
{
if(s.size() == 0)
{
avertissement("set_value(\"\"): invalid value for int.");
return false;
}
for(i = 0; i < enumerations.size(); i++)
{
if(s.compare(enumerations[i].name.get_id()) == 0)
return true;
if(s.compare(enumerations[i].name.get_localized()) == 0)
return true;
}
if(!is_bytes)
{
if(is_hexa)
{
if(s.compare("0") == 0)
return true;
if(ss[0] != '0')
return false;
if(ss[1] != 'x')
return false;
// Check int
for(i = 2; i < n; i++)
{
if(!utils::str::is_hexa(ss[i]))
{
avertissement("set_value(\"%s\"): invalid character for hexa int.", ss);
return false;
}
}
}
else
{
// Check int
for(i = 0; i < n; i++)
{
if(!utils::str::is_deci(ss[i]) && (ss[i] != '-'))
{
avertissement("set_value(\"%s\"): invalid value for int.", ss);
return false;
}
}
if(has_min && (atoi(ss) < min))
{
avertissement("set_value(\"%s\"): < min = %ld.", ss, min);
return false;
}
if(has_max && (atoi(ss) > max))
{
avertissement("set_value(\"%s\"): > max = %ld.", ss, max);
return false;
}
}
}
}
return true;
}
void Attribute::forward_change_event()
{
/*ChangeEvent ce = ChangeEvent::create_att_changed(this);
ce.source = this;
ce.path = XPath(schema->name.get_id());
dispatch(ce);*/
}
int Attribute::set_value(const ByteArray &ba)
{
if(ba != value)
{
if(!schema->is_valid(ba))
{
string s = ba.to_string();
avertissement("%s(%s): Invalid value.", __func__, s.c_str());
return -1;
}
value = ba;
if(!inhibit_event_dispatch)
{
ChangeEvent ce = ChangeEvent::create_att_changed(this);
ce.path = XPath(XPathItem(schema->name.get_id()));
dispatch(ce);
}
return 0;
}
return 0;
}
int Attribute::set_value(const string &s)
{
if(!schema->is_valid(s))
{
avertissement("set_value(%s): invalid value.", s.c_str());
if(!inhibit_event_dispatch)
{
ChangeEvent ce = ChangeEvent::create_att_changed(this);
ce.path = XPath(XPathItem(schema->name.get_id()));
dispatch(ce);
}
return -1;
}
ByteArray ba;
if(__builtin_expect(schema->serialize(ba, s), 0))
return -1;
return set_value(ba);
}
string Attribute::get_string() const
{
return schema->get_string(value);
}
void Attribute::set_value(int i)
{
ByteArray ba;
schema->serialize(ba, i);
set_value(ba);
}
void Attribute::set_value(float f)
{
ByteArray ba;
schema->serialize(ba, f);
set_value(ba);
}
void Attribute::set_value(bool b)
{
ByteArray ba;
schema->serialize(ba, b);
set_value(ba);
}
// GET CHILDREN, TYPE NON PRECISE
unsigned long Node::get_children_count() const
{
uint32_t i, res = 0;
if(data == nullptr)
return 0;
for(i = 0; i < schema()->children.size(); i++)
{
res += data->get_children_count(i);
}
return res;
}
Node Node::get_child_at(unsigned int index)
{
uint32_t i, cpt = 0;
if(data == nullptr)
return Node();
for(i = 0; i < schema()->children.size(); i++)
{
unsigned int k = data->get_children_count(i);
if((index >= cpt) && (index < cpt + k))
{
return data->get_child_at(i, index - cpt);
}
cpt += k;
}
return Node();
}
const Node Node::get_child_at(unsigned int index) const
{
uint32_t i, cpt = 0;
if(data == nullptr)
return Node();
for(i = 0; i < schema()->children.size(); i++)
{
unsigned int k = data->get_children_count(i);
if((index >= cpt) && (index < cpt + k))
{
return data->get_child_at(i, index - cpt);
}
cpt += k;
}
return Node();
}
// GET CHILDREN, TYPE PRECISE
unsigned long Node::get_children_count(const string &type) const
{
if(data == nullptr)
return 0;
return data->get_children_count(type);
}
Node Node::get_child_at(const string &type, unsigned int i)
{
//infos("get child %s %d", type.c_str(), i);
if(data == nullptr)
return Node();
return data->get_child_at(type, i);
}
const Node Node::get_child_at(const string &type, unsigned int i) const
{
if(data == nullptr)
return Node();
//infos("get child %s %d", type.c_str(), i);
return data->get_child_at(type, i);
}
Node Node::add_child(Node nv)
{
if(__builtin_expect(data == nullptr, 0))
return Node();
Node res = data->add_child(nv.schema()->name.get_id());
res.copy_from(nv);
if(res.data != nullptr)
{
res.data->CProvider<ChangeEvent>::add_listener(data);
ChangeEvent ce = ChangeEvent::create_child_added(nv.schema()->name.get_id(),
get_children_count(nv.schema()->name.get_id()) - 1);
RamNode *rnode = (RamNode *) data;
ce.path = ce.path.add_parent(XPathItem(schema()->name.get_id(), rnode->instance));
//verbose("dispatch...");
data->CProvider<ChangeEvent>::dispatch(ce);
//verbose("dispatch done.");
}
return res;
}
Node Node::add_child(NodeSchema *schema)
{
return add_child(schema->name.get_id());
}
Node Node::add_child(const string &sub_name)
{
if(__builtin_expect(data == nullptr, 0))
return Node();
//verbose("add_child(%s)...", sub_name.c_str());
Node res = data->add_child(sub_name);
if(res.data != nullptr)
{
res.data->CProvider<ChangeEvent>::add_listener(data);
ChangeEvent ce = ChangeEvent::create_child_added(sub_name, get_children_count(sub_name) - 1);
RamNode *rnode = (RamNode *) data;
ce.path = ce.path.add_parent(XPathItem(this->schema()->name.get_id(), rnode->instance));
data->CProvider<ChangeEvent>::dispatch(ce);
}
//verbose("done.");
return res;
}
void Node::remove_child(Node child)
{
if(data == nullptr)
return;
if(child.data == nullptr)
return;
std::string sub_name = child.schema()->name.get_id();
unsigned int instance = 0, n = get_children_count(sub_name);
for(unsigned i = 0; i < n; i++)
{
if(child == get_child_at(sub_name, i))
{
instance = i;
break;
}
}
child.data->CProvider<ChangeEvent>::remove_listener(data);
data->remove_child(child);
ChangeEvent ce = ChangeEvent::create_child_removed(sub_name, instance);
RamNode *rnode = (RamNode *) data;
ce.path = ce.path.add_parent(XPathItem(this->schema()->name.get_id(), rnode->instance));
data->CProvider<ChangeEvent>::dispatch(ce);
}
bool Node::is_attribute_valid(const string &name)
{
if(!this->has_attribute(name))
{
avertissement("is_att_valid: att %s not found.", name.c_str());
return false;
}
Attribute *att = this->get_attribute(name);
std::string rq = att->schema->requirement;
/* No requirement? */
if(rq.size() == 0)
return true;
/* parse requirement:
* must be in the form
* "att-name=value1|value2|..." */
size_t pos = rq.find("=");
if(pos == std::string::npos)
{
avertissement("Invalid requirement: '%s'.", rq.c_str());
return false;
}
std::string attname = rq.substr(0, pos);
std::string tot = rq.substr(pos + 1, rq.size() - pos - 1);
std::vector<std::string> constraints;
if(tot.size() > 0)
{
// Parse list of match ('|' separed)
const char *s = tot.c_str();
char current[200];
int current_index = 0;
for(unsigned int i = 0; i < strlen(s); i++)
{
if(s[i] != '|')
{
current[current_index++] = s[i];
}
else
{
current[current_index] = 0;
constraints.push_back(std::string(current));
current_index = 0;
}
}
if(current_index > 0)
{
current[current_index] = 0;
constraints.push_back(std::string(current));
}
}
std::string s = std::string("Requirement: ") + attname + " = ";
for(uint32_t i = 0; i < constraints.size(); i++)
{
s += constraints[i];
if(i + 1 < constraints.size())
s += " | ";
}
//infos(s);
if(!has_attribute(attname))
{
avertissement("%s attribute not found (in requirement).", attname.c_str());
return false;
}
std::string value = get_attribute_as_string(attname);
for(uint32_t i = 0; i < constraints.size(); i++)
{
if(value.compare(constraints[i]) == 0)
{
//infos("att %s is available.", name.c_str());
return true;
}
}
//infos("att %s is not available.", name.c_str());
return false;
}
// REFERENCES
unsigned int Node::get_reference_count() const
{
if(__builtin_expect(data != nullptr, 1))
return data->get_reference_count();
else
return 0;
}
void Node::set_reference(const string &name, Node e)
{
if(data != nullptr)
data->set_reference(name, e);
}
void Node::set_reference(const string &name, const XPath &xp)
{
if(data != nullptr)
data->set_reference(name, xp);
}
const Node Node::get_reference_at(unsigned int i, std::string &name) const
{
if(data != nullptr)
return data->get_reference_at(i, name);
else
return Node();
}
Node::Node(NodePatron *data)
{
this->data = data;
if(__builtin_expect(data != nullptr, 1))
data->reference();
}
static utils::hal::Mutex mutex_refs;
void NodePatron::reference()
{
mutex_refs.lock();
nb_references++;
mutex_refs.unlock();
}
void NodePatron::dereference()
{
mutex_refs.lock();
nb_references--;
mutex_refs.unlock();
}
std::string NodePatron::class_name() const
{
return "node-patron";
}
NodePatron::NodePatron()
{
//this->ignore = false;
}
void NodePatron::lock()
{
locked = true;
}
void NodePatron::unlock()
{
locked = false;
}
Node::Node()
{
data = nullptr;
}
bool Node::contains(const Node &elt)
{
if(*this == elt)
return true;
unsigned int n = schema()->children.size();
for(unsigned int i = 0; i < n; i++)
{
SubSchema &ss = schema()->children[i];
unsigned int m = get_children_count(ss.child_str);
for(unsigned int j = 0; j < m; j++)
if(get_child_at(ss.child_str, j).contains(elt))
return true;
}
return false;
}
void Node::lock()
{
if(data != nullptr)
data->lock();
//for(uint32_t i = 0; i < get_children_count(); i++)
//get_child_at(i).lock();
}
void Node::unlock()
{
if(data != nullptr)
data->unlock();
//for(uint32_t i = 0; i < get_children_count(); i++)
//get_child_at(i).unlock();
}
Node Node::create_ram_node(NodeSchema *schema)
{
if(__builtin_expect(schema == nullptr, 0))
return Node();
Node res(new RamNode(schema));
return res;
}
Node Node::create_ram_node()
{
Node res(new RamNode());
return res;
}
Node Node::create_ram_node_from_string(NodeSchema *schema, const std::string &content)
{
if(__builtin_expect(schema == nullptr, 0))
return Node();
Node res(new RamNode(schema));
MXml mx;
if(mx.from_string(content))
{
erreur("Parse error while parsing:\n%s", content.c_str());
return res;
}
res.fromXml(mx);
return res;
}
Node Node::create_ram_node(NodeSchema *schema, std::string filename)
{
if(__builtin_expect(schema == nullptr, 0))
return Node();
utils::files::remplacement_motif(filename);
//schema->verbose("create empty rnode..");
RamNode *rn = new RamNode(schema);
Node res(rn);
if(files::file_exists(filename))
{
MXml mx;
infos("Chargement arbre de donnees a partir du fichier [%s]...", filename.c_str());
infos(" decodage xml..");
if(mx.from_file(filename))
{
erreur("erreur de parsing dans [%s].", filename.c_str());
return res;
}
string path, file;
files::split_path_and_filename(filename, path, file);
infos(" conversion XML -> noeud...");
res.fromXml(mx, path);
infos(" setup refs...");
res.setup_refs();
infos("ok.");
}
else
{
avertissement("Fichier non trouve (%s) : utilisation des parametres par defaut.", filename.c_str());
}
return res;
}
bool Node::est_egal(const Node &e) const
{
ByteArray ba[2];
serialize(ba[0]);
e.serialize(ba[1]);
return ba[0] == ba[1];
}
bool Node::operator ==(const Node &e) const
{
return (e.data == data);
}
bool Node::operator !=(const Node &e) const
{
return (e.data != data);
}
void Node::operator =(const Node &e)
{
NodePatron *old_data = data;
data = e.data;
if(data != nullptr)
data->reference();
if(old_data != nullptr)
{
old_data->dereference();
if(old_data->nb_references <= 0)
{
old_data->discard();
//infos("VRAI DELETE (op=).");
delete old_data; // ?
}
}
}
Node::~Node()
{
if(data == nullptr)
return;
//infos("destruction.");
data->dereference();
if(data->nb_references <= 0)
{
data->discard();
data->CProvider<ChangeEvent>::remove_all_listeners();
//infos("VRAI DELETE (des).");
delete data;
}
data = nullptr;
}
bool Node::is_nullptr() const
{
return (data == nullptr);
}
Node Node::parent() const
{
if(data == nullptr)
return Node();
return data->get_parent();
}
Node RamNode::get_parent()
{
Node elt(parent);
return elt;
}
Node Node::down(Node child)
{
Node res;
std::string cname = child.schema()->name.get_id();
unsigned int i, n = get_children_count(cname);
unsigned int index = n;
std::vector<Node> children;
for(i = 0; i < n; i++)
{
Node c = get_child_at(cname, i);
if(child == c)
index = i;
children.push_back(c);
}
if(index == n)
{
erreur("down(): child not found.");
return child;
}
else if(index == n - 1)
{
erreur("down(): index = n - 1.");
return child;
}
for(i = 0; i < n; i++)
remove_child(children[i]);
for(i = 0; i < n; i++)
{
if(i == index)
{
add_child(children[index + 1]);
}
else if(i == index + 1)
{
res = add_child(children[index]);
}
else
add_child(children[i]);
}
return res;
}
Node Node::up(Node child)
{
Node res;
std::string cname = child.schema()->name.get_id();
unsigned int i, n = get_children_count(cname);
unsigned int index = n;
std::vector<Node> children;
for(i = 0; i < n; i++)
{
Node c = get_child_at(cname, i);
if(child == c)
index = i;
children.push_back(c);
}
if(index == n)
{
erreur("up(): child not found.");
return child;
}
else if(index == 0)
{
erreur("up(): index = 0.");
return child;
}
for(i = 0; i < n; i++)
remove_child(children[i]);
for(i = 0; i < n; i++)
{
if((i + 1) == index)
{
res = add_child(children[index]);
}
else if(i == index)
{
add_child(children[i - 1]);
}
else
add_child(children[i]);
}
return res;
}
void NodePatron::get_vector(std::string name, uint32_t index, void *data, uint32_t n)
{
erreur("TODO: generic get_vector.");
}
void NodePatron::add_vector(std::string name, void *data, uint32_t n)
{
erreur("TODO: add_vector.");
# if 0
Node elt(this);
/* Default implementation */
for(uint32_t i = 0; i < n; i++)
{
Node nv = elt.add_child(name);
nv.schema()
nv.set_attribute()
}
# endif
}
XPath::XPath()
{
valid = true;
//setup("model", "xpath");
}
XPath::XPath(const string &s)
{
//setup("model", "xpath");
this->valid = false;
from_string(s);
}
int XPath::from_string(const string &s_)
{
string s = s_;
size_t pos;
valid = false;
items.clear();
while(s.size() > 0)
{
/* get one item */
uint32_t i = 0;
while((s[i] != '/') && (s[i] != '[') && (i < s.size()))
{
i++;
}
XPathItem item;
item.name = s.substr(0, i);
item.instance = -1;
if(i == s.size())
{
items.push_back(item);
break;
}
s = s.substr(i, s.size() - i);
if(s[0] == '[')
{
s = s.substr(1, s.size() - 1);
pos = s.find(']', 0);
if(pos == std::string::npos)
{
//erreur("xpath(\"%s\"): parse error.", s.c_str());
return -1;
}
std::string spec = s.substr(0, pos);
size_t pos_equal = spec.find('=', 0);
if(pos_equal == std::string::npos)
{
item.instance = atoi(spec.c_str());
}
else
{
item.instance = -1;
item.att_name = spec.substr(0, pos_equal);
item.att_value = spec.substr(pos_equal + 1, spec.size() - (pos_equal + 1));
}
s = s.substr(pos + 1, s.size() - (pos + 1));
}
if(s.size() == 0)
{
items.push_back(item);
break;
}
if(s[0] != '/')
{
//erreur("xpath(\"%s\"): parse error.", s.c_str());
return -1;
}
items.push_back(item);
s = s.substr(1, s.size() - 1);
}
valid = true;
return 0;
}
XPath::XPath(const XPath &xp)
{
(*this) = xp;
}
void XPath::operator =(const XPath &xp)
{
valid = xp.valid;
items = xp.items;
}
const char *XPath::c_str() const
{
XPath *th = (XPath *) this;
th->full_string = to_string();
return th->full_string.c_str();
}
std::string XPath::to_string() const
{
std::string s = "";
if(!is_valid())
return "(invalid path)";
if(items.size() == 0)
return "";
for(uint32_t i = 0; i < items.size(); i++)
{
s += items[i].name;
if(items[i].att_name.size() > 0)
s += std::string("[") + items[i].att_name + "=" + items[i].att_value + "]";
else if(items[i].instance > 0)
s += std::string("[") + utils::str::int2str(items[i].instance) + "]";
if(i + 1 < items.size())
s += "/";
}
return s;
}
bool XPath::is_valid() const
{
return valid;
}
XPath::~XPath()
{
}
XPathItem &XPath::operator[](const unsigned int i)
{
if(i >= (unsigned int) length())
{
//anomaly("operator[%d]: overflow (%d nodes).", i, length());
XPathItem *bidon = new XPathItem();
return *bidon;
}
return items[i];
}
const XPathItem &XPath::operator[](const unsigned int i) const
{
if(i >= (unsigned int) length())
{
//anomaly("operator[%d]: overflow (%d nodes).", i, length());
XPathItem *bidon = new XPathItem();
return *bidon;
}
return items[i];
}
XPathItem XPath::root() const
{
if(!valid)
{
//anomaly("root() on invalid xpath.");
XPathItem res;
return res;
}
if(items.size() == 0)
{
//anomaly("root() on empty xpath.");
XPathItem res;
return res;
}
return items[0];
}
bool XPath::has_child() const
{
if(!valid)
return false;
return items.size() > 1;
}
XPath XPath::child() const
{
XPath res;
if(!valid)
return res;
res.valid = true;
for(uint32_t i = 1; i < items.size(); i++)
res.items.push_back(items[i]);
return res;
}
XPath XPath::add_parent(XPathItem item) const
{
XPath res;
if(!valid)
return res;
res.valid = true;
res.items.push_back(item);
for(uint32_t i = 0; i < items.size(); i++)
res.items.push_back(items[i]);
return res;
}
bool XPath::operator ==(const XPath &xp) const
{
if(items.size() != xp.items.size())
return false;
for(unsigned int i = 0; i < items.size(); i++)
{
if(items[i].name.compare(xp.items[i].name) != 0)
return false;
int i1 = items[i].instance, i2 = xp.items[i].instance;
if(i1 == -1)
i1 = 0;
if(i2 == -1)
i2 = 0;
if(i1 != i2)
return false;
if(items[i].att_name.compare(xp.items[i].att_name))
return false;
if(items[i].att_value.compare(xp.items[i].att_value))
return false;
}
return true;
}
int XPath::length() const
{
return items.size();
}
void XPath::clear()
{
items.clear();
}
XPath XPath::remove_last() const
{
XPath res;
for(uint32_t i = 0; i + 1 < items.size(); i++)
{
res.items.push_back(items[i]);
}
return res;
}
XPath XPath::operator+(const XPath &xp) const
{
unsigned int i = 0;
XPath res(*this);
for(i = 0; i < (unsigned int) xp.length(); i++)
{
res.add(xp[i]);
}
return res;
}
void XPath::add(const XPathItem &xpi)
{
if((xpi.name.compare("") == 0)
|| (xpi.name.compare(".") == 0))
return;
if(xpi.name.compare("..") == 0)
this->remove_last();
else
{
items.push_back(xpi);
}
}
XPath XPath::get_first() const
{
XPath res;
if(items.size() > 0)
res.items.push_back(items[0]);
return res;
}
std::string XPath::get_last() const
{
if(items.size() == 0)
return "";
return items[items.size() - 1].name;
}
std::string ChangeEvent::to_string() const
{
std::string s = "";
switch(type)
{
case ATTRIBUTE_CHANGED: s += "ATTRIBUTE_CHANGED"; break;
case CHILD_ADDED: s += "CHILD_ADDED"; break;
case CHILD_REMOVED: s += "CHILD_REMOVED"; break;
case COMMAND_EXECUTED: s += "COMMAND_EXECUTED"; break;
case GROUP_CHANGE: s += "NODE_CHANGED"; break;
}
s += ", path = " + path.to_string();
return s;
}
ChangeEvent::ChangeEvent()
{
//source = nullptr;
//source_node = nullptr;
}
ChangeEvent ChangeEvent::create_att_changed(Attribute *source)
{
ChangeEvent res;
res.type = ATTRIBUTE_CHANGED;
res.path = XPath(source->schema->name.get_id());
return res;
}
ChangeEvent ChangeEvent::create_child_removed(std::string type, uint32_t instance)
{
ChangeEvent res;
res.type = CHILD_REMOVED;
res.path = XPath(type + "[" + utils::str::int2str(instance) + "]");
return res;
}
ChangeEvent ChangeEvent::create_child_added(std::string type, uint32_t instance)
{
ChangeEvent res;
res.type = CHILD_ADDED;
res.path = XPath(type + "[" + utils::str::int2str(instance) + "]");
return res;
}
ChangeEvent ChangeEvent::create_command_exec(Node *source, std::string name)
{
ChangeEvent res;
res.type = ChangeEvent::COMMAND_EXECUTED;
int instance = ((RamNode *) source->data)->instance;
res.path = XPath(source->schema()->name.get_id() + "[" + utils::str::int2str(instance) + "]/" + name);
return res;
}
Enumeration::Enumeration()
{
schema_str = "";
schema = nullptr;
}
Enumeration::Enumeration(const Enumeration &e)
{
*this = e;
}
void Enumeration::operator =(const Enumeration &e)
{
name = e.name;
value = e.value;
schema = e.schema;
schema_str = e.schema_str;
}
Enumeration::~Enumeration()
{
schema_str = "";
}
DotTools::DotTools()
{
log.setup("model");//, "dot-tools");
}
static std::string fcols[6] = {"FF8080", "80FF80", "FFFF30", "D0D0D0", "D0D0D0", "D0D0D0"};
string DotTools::get_name(const Node &e)
{
std::string res = "";
if(e.has_attribute("fr") && (e.get_attribute_as_string("fr").size() > 0))
res = e.get_attribute_as_string("fr");
else if(e.has_attribute("en") && (e.get_attribute_as_string("en").size() > 0))
res = e.get_attribute_as_string("en");
else
res = e.name();
if((res[0] >= 'a') && (res[0] <= 'z'))
res[0] += 'A' - 'a';
return res;
}
int DotTools::export_html_att_table(string &res, const Node &schema)
{
std::string s = "";
if(schema.get_children_count("attribute") > 0)
{
s += std::string("<table border=\"1\" width=700 style='table-layout:fixed'>")
+ "<col width=150>"
"<col width=100>"
"<col width=125>"
"<col width=95>"
"<col width=300>"
+ "<tr>"
+ "<th><font size=\"-1\">" + utils::str::latin_to_utf8("Paramètre") + "</font></th>"
+ "<th><font size=\"-1\">Identifiant</font></th>"
+ "<th><font size=\"-1\">Type</font></th>"
+ "<th><font size=\"-1\">Dimension</font></th>"
+ "<th><font size=\"-1\">Description</font></th>"
+ "</tr>";
for(uint32_t i = 0; i < schema.get_children_count("attribute"); i++)
{
const Node &att = schema.get_child_at("attribute", i);
s += std::string("<tr><td>")
+ "<font size=\"-1\">"
+ get_name(att)
+ "</font>"
+ "</td>";
s += "<th>";
s += "<font size=\"-1\">";
s += /*path + "/" +*/ att.name();
s += "</font>";
s += "</th>";
s += "<td><font size=\"-1\">" + get_attribute_type_description(att) + "</font></td>";
s += "<td><font size=\"-1\">";
if(att.get_attribute_as_string("type").compare("float") == 0)
{
s += "32 bits";
}
else
{
if(att.get_attribute_as_int("size") == 1)
s += "1 octet";
else
s += att.get_attribute_as_string("size") + " octets";
}
s += "</font></td>";
s += "<td><font size=\"-1\">" + get_attribute_long_description(att) + "</font></td>"
+ "</tr>";
}
s += std::string("</table>");
}
res = s;
return 0;
}
string LatexWrapper::get_attribute_long_description(const Node &e)
{
string res = "";
//res += std::string("<p>") + e.description() + "</p>";
if(e.has_child("match"))
{
res += "Valeurs possibles :";
res += "\\begin{description}\n";
for(uint32_t i = 0; i < e.get_children_count("match"); i++)
{
const Node &ch = e.get_child_at("match", i);
res += "\\item[" + ch.get_attribute_as_string("value") + "] " + get_name(ch);
if(ch.description().size() > 0)
res += "\n" + ch.description();
res += "\n";
}
res += "\\end{description}\n";
}
if(e.has_attribute("unit") && (e.get_attribute_as_string("unit").size() > 0))
{
res += "S'exprime en {\\bf " + e.get_attribute_as_string("unit") + "}.\n\n";
}
std::string def = e.get_attribute_as_string("default");
AttributeSchema as(e);
std::string def2 = as.get_ihm_value(as.get_default_value());
if(as.type == TYPE_STRING)
def2 = "\"" + def2 + "\"";
//Valeur par défaut
res += langue.get_item("default-val") + " : " + def2;
if(e.has_attribute("unit") && (e.get_attribute_as_string("unit").size() > 0))
res += " " + e.get_attribute_as_string("unit");
res += "\n\n";
if(!e.has_child("match"))
{
if(e.get_attribute_as_string("min").size() > 0)
{
res += "Valeur minimale : "
+ e.get_attribute_as_string("min")
+ " " + e.get_attribute_as_string("unit") + "\n\n";
}
if(e.get_attribute_as_string("max").size() > 0)
{
res += "Valeur maximale : "
+ e.get_attribute_as_string("max")
+ " " + e.get_attribute_as_string("unit")
+ "\n\n";
}
}
res += e.description();
return res;
}
string DotTools::get_attribute_type_description(const Node &e)
{
std::string res = "";
std::string tp = e.get_attribute_as_string("type");
if(tp.compare("int") == 0)
{
res += "Entier";
if(e.get_attribute_as_boolean("signed"))
res += " " + langue.get_item("signed");
else
res += " non " + langue.get_item("signed");
}
else if(tp.compare("boolean") == 0)
res += langue.get_item("boolean");
else if(tp.compare("string") == 0)
res += langue.get_item("string");
else if(tp.compare("float") == 0)
res += "Flottant";
else
{
res += "Type inconnu: " + tp;
}
/*if(e.get_attribute_as_int("count") > 1)
{
res += " (tableau de " + e.get_attribute_as_string("count") + " �l�ments)";
}*/
if(e.get_attribute_as_boolean("readonly"))
res += "<br/><b>lecture seule</b>";
/*if(e.get_attribute_as_string("type").compare("int") == 0)
{
res += std::string(" (") + e.get_attribute_as_string("size") + ")";
}*/
return res;
}
void DotTools::build_graphic(Node &schema, const std::string &output_filename)
{
std::string fn =
utils::get_current_user_path() + PATH_SEP +
std::string("tmp-") + schema.name()
+ ".dot";
infos("Building graphics from model =\n%s\n", schema.to_xml(0).c_str());
FILE *tmp = fopen(fn.c_str(), "wt");
if(tmp == nullptr)
{
erreur("Failed to create [%s].", fn.c_str());
return;
}
fprintf(tmp, "digraph G {\nratio=compress;\noverlap=false;\n");
fprintf(tmp, "root=%s;\n", str::str_to_var(schema.name()).c_str());
fprintf(tmp, "%s", complete_dot_graph(schema, 0).c_str());
fprintf(tmp, "fontsize=5;\n");
fprintf(tmp, "}");
fclose(tmp);
std::string img_fmt = "png";
infos("calling twopi..");
std::string dotpath = "dot";
#ifdef WIN
dotpath = "\"C:\\Program Files\\graphviz 2.28\\bin\\dot.exe\"";
trace_majeure("Win32 dot: %s.", dotpath.c_str());
#endif
utils::proceed_syscmde("%s -T" + img_fmt
+ " \"" + fn + "\" -o \"%s\"",
dotpath.c_str(),
output_filename.c_str());
}
std::string DotTools::complete_dot_graph(Node section, int level)
{
std::string res = "";
std::string fillcolor = fcols[level];
//section.infos("complete_dot_graph(level %d)..", level);
// margin=0 : marge horizontale
//res += "node [shape=box, fontsize=9, fillcolor=\"#" + fillcolor + "\", style=filled];\n";
//res += "node [shape=none, fontsize=9];\n";
/*res += utils::str::str_to_var(section.get_attribute_as_string("name"))
+ " [label=\""
+ section.get_attribute_as_string("name")
+ "\"];\n";*/
/** Construction de la classe */
std::string name = section.name();
res += str::str_to_var(name)
+ " [fontsize=9, shape=none, margin=0, label=<";
res += "<TABLE BORDER=\"1\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"3\"";
res += " BGCOLOR=\"#" + fillcolor + "\"";
res += ">\n";
res += "<TR><TD BORDER=\"1\">";
res += section.get_localized_name();
res += "</TD></TR>";
for(unsigned int i = 0; i < section.get_children_count("attribute"); i++)
{
Node att = section.get_child_at("attribute", i);
res += "<TR><TD>";
res += att.get_localized_name();
res += "</TD></TR>";
}
res += "</TABLE>\n";
res += ">";
std::string url = "";
if(level == 1)
{
url = "#" + section.name();
}
if(url.size() > 0)
res += ", URL=\"" + url + "\"";
res += "];\n";
fillcolor = fcols[level + 1];
res += "node [shape=box, fontsize=9, fillcolor=\"#" + fillcolor + "\", "
"style=filled";
//if(level == 0)
//res += ", root=true"
res += "];\n";
for(unsigned int i = 0; i < section.get_children_count("sub-node"); i++)
{
Node sub = section.get_child_at("sub-node", i);
// EDGE attributes
int weight = 10 * (level + 1);
//res += "edge [dir=\"back\", len=0.2, weight="
res += "edge [dir=\"back\", weight="
+ utils::str::int2str(weight) + ", arrowtail=\"diamond\", fontsize=7";
int min = sub.get_attribute_as_int("min");
int max = sub.get_attribute_as_int("max");
if(min == -1)
min = 0;
if((min != 1) || (max != 1))
{
std::string smin = utils::str::int2str(min);
std::string smax = utils::str::int2str(max);
if(max == -1)
smax = "n";
if(max == min)
res += ", label=\"" + smin + "\"";
else
res += ", label=\"" + smin + ".." + smax + "\"";
}
res += "];\n";
res += str::str_to_var(section.name())
+ " -> "
+ str::str_to_var(sub.name())
+ ";\n";
}
for(unsigned int i = 0; i < section.get_children_count("sub-node"); i++)
{
Node sub = section.get_child_at("sub-node", i);
res += complete_dot_graph(sub, level + 1);
}
//section.infos("complete_dot_graph(level %d): done.", level);
return res;
}
RefSchema::RefSchema()
{
is_hidden = false;
}
const Node NodeIterator::operator*() const
{
return parent->get_child_at(type, index);
//Node n(parent);
//return n.get_child_at(type, index);
}
Node NodeIterator::operator++()
{
index++;
return parent->get_child_at(type, index - 1);
//Node n(parent);
//return n.get_child_at(type, index - 1);
}
const Node ConstNodeIterator::operator*() const
{
//const Node n((NodePatron *) parent);
//printf("op*(%d)\n", index);
//return n.get_child_at(type, index);
return parent->get_child_at(type, index);
}
const Node ConstNodeIterator::operator++()
{
//printf("op++(%d->%d)\n", index, index+1);
//index++;
//Node n((NodePatron *) parent);
//return n.get_child_at(type, index - 1);
index++;
return parent->get_child_at(type, index - 1);
}
NodeIterator NodeList::end() const
{
return NodeIterator(parent, type, parent->get_children_count(type));
}
ConstNodeIterator ConstNodeList::end() const
{
return ConstNodeIterator(parent, type, parent->get_children_count(type));
}
std::string Node::format_c_comment(int indent)
{
Node e = (*this);
std::string s = "", desc = utils::str::utf8_to_latin(e.description());
uint32_t i, j, k;
for(i = 0; i < (uint32_t) indent; i++)
s += " ";
s += "/** @brief ";
//s += prefix;
s += utils::str::utf8_to_latin(e.get_localized_name());
/* Clean description. */
std::string d2;
bool only_spaces = true;
uint32_t scnt = 0;
for(i = 0; i < desc.size(); i++)
{
if((desc[i] == ' ') || (desc[i] == 0x0d) || (desc[i] == 0x0a) || (desc[i] == '\t'))
{
if(scnt == 0)
d2 += " ";
scnt++;
}
else
{
char c[2];
c[0] = desc[i];
c[1] = 0;
d2 += (&c[0]);
scnt = 0;
only_spaces = false;
}
}
if(only_spaces)
d2 = "";
if(only_spaces && (e.get_localized_name().size() == 0))
return "";
if(d2.size() > 0)
{
/* Text justification */
uint32_t colcnt = 0;
for(j = 0; j < d2.size(); j++)
{
if((j == 0) || (colcnt >= 70))
{
if((j > 0) && (d2[j-1] != ' '))
s += "-";
/* new line */
s += "\n";
for(k = 0; k < (uint32_t) indent; k++)
s += " ";
s += " * ";
if((j > 0) && (d2[j-1] != ' '))
s += "-";
colcnt = 0;
}
s += utils::str::utf8_to_latin(d2.substr(j, 1));
colcnt++;
}
}
uint32_t nmatch = e.get_children_count("match");
if(nmatch > 0)
{
TextMatrix mmatrix(2);
s += "\n";
for(j = 0; j < nmatch; j++)
{
Node match = e.get_child_at("match", j);
std::string idt = "";
for(i = 0; i < (uint32_t) indent + 4 + 7; i++)
idt += " ";
mmatrix.add(idt + match.get_attribute_as_string("value") + ": ");
std::string dsc = utils::str::utf8_to_latin(match.get_localized_name());
mmatrix.add(dsc);
mmatrix.next_line();
}
s += mmatrix.get_result();
s = s.substr(0, s.size() - 1);
}
s += " */\n";
return s;
}
NodeList Node::children(const string &type)
{
return NodeList(data, schema()->mapper[type]);
}
ConstNodeList Node::children(const string &type) const
{
return ConstNodeList(data, schema()->mapper[type]);
}
string Node::to_html(unsigned int level) const
{
unsigned int i, j, n;
ostringstream res;
NodeSchema *scheme = this->schema();
//res << "<h" << level << ">" << scheme->name.get_localized() << "</h" << level << ">\n";
res << "<div align=\"left\"><table>";
for(i = 0; i < scheme->attributes.size(); i++)
{
refptr<AttributeSchema> as = scheme->attributes[i];
Localized attname = scheme->attributes[i]->name;
string val = as->get_ihm_value(get_attribute_as_string(attname.get_id()));
string loc = attname.get_localized();
res << "<tr><td>" << loc << "</td>";
res << "<td>" << val;
if(as->has_unit())
res << " " << as->unit;
res << "</td></tr>";
}
res << "</table></div>";
for(i = 0; i < scheme->children.size(); i++)
{
string name = scheme->children[i].name.get_id();
n = this->get_children_count(scheme->children[i].name.get_id());
for(j = 0; j < n; j++)
{
res << "<h" << level << ">" << scheme->children[i].ptr->name.get_localized() << "</h" << level << ">\n";
res << get_child_at(name, j).to_html(level + 1);
}
}
return res.str();
}
int LatexWrapper::export_att_table(string &res, const Node &schema)
{
std::string s = "";
if(schema.get_children_count("attribute") > 0)
{
s += std::string("\\begin{longtable}{|c|c|c|c|p{7cm}|}\n")
+ "\\hline\n"
+ "{\\bf " + utils::str::latin_to_utf8("Paramètre") + "} & "
+ "{\\bf Identifiant} &"
+ "{\\bf Type} &"
+ "{\\bf Dimension} &"
+ "{\\bf Description}\\\\\n\\hline\n";
for(uint32_t i = 0; i < schema.get_children_count("attribute"); i++)
{
const Node &att = schema.get_child_at("attribute", i);
s += get_name(att) + " & ";
s += att.name() + " & ";
s += get_attribute_type_description(att) + " & ";
if(att.get_attribute_as_string("type").compare("float") == 0)
{
s += "32 bits";
}
else
{
if(att.get_attribute_as_int("size") == 1)
s += "1 octet";
else
s += att.get_attribute_as_string("size") + " octets";
}
s += " & ";
s += "\\begin{minipage}[c]{7cm}\n";
s += get_attribute_long_description(att);
s += "\\end{minipage}\\\\\n";
s += "\\hline\n";
}
s += std::string("\\end{longtable}\n");
}
res = s;
return 0;
}
string LatexWrapper::get_name(const Node &e)
{
std::string res = "";
if(e.has_attribute("fr") && (e.get_attribute_as_string("fr").size() > 0))
res = e.get_attribute_as_string("fr");
else if(e.has_attribute("en") && (e.get_attribute_as_string("en").size() > 0))
res = e.get_attribute_as_string("en");
else
res = e.name();
if((res[0] >= 'a') && (res[0] <= 'z'))
res[0] += 'A' - 'a';
return res;
}
string LatexWrapper::get_attribute_type_description(const Node &e)
{
std::string res = "";
std::string tp = e.get_attribute_as_string("type");
if(tp.compare("int") == 0)
{
res += "Entier";
if(e.get_attribute_as_boolean("signed"))
res += " " + langue.get_item("signed");
else
res += " non " + langue.get_item("signed");
}
else if(tp.compare("boolean") == 0)
res += langue.get_item("boolean");
else if(tp.compare("string") == 0)
res += langue.get_item("string");
else if(tp.compare("float") == 0)
res += "Flottant";
else
{
res += "Type inconnu: " + tp;
}
/*if(e.get_attribute_as_int("count") > 1)
{
res += " (tableau de " + e.get_attribute_as_string("count") + " �l�ments)";
}*/
if(e.get_attribute_as_boolean("readonly"))
res += " {\\bf lecture seule}";
/*if(e.get_attribute_as_string("type").compare("int") == 0)
{
res += std::string(" (") + e.get_attribute_as_string("size") + ")";
}*/
return res;
}
string DotTools::get_attribute_long_description(const Node &e)
{
string res = "";
//res += std::string("<p>") + e.description() + "</p>";
if(e.has_child("match"))
{
res += "<p>Valeurs possibles :<ul>";
for(uint32_t i = 0; i < e.get_children_count("match"); i++)
{
const Node &ch = e.get_child_at("match", i);
res += "<li><b>" + ch.get_attribute_as_string("value") + " : " + get_name(ch) + "</b>";
if(ch.description().size() > 0)
res += "<br/>" + ch.description();
res += "</li>";
}
res += "</ul></p>";
}
if(e.has_attribute("unit") && (e.get_attribute_as_string("unit").size() > 0))
{
res += "S'exprime en <b>" + e.get_attribute_as_string("unit") + "</b>.";
}
std::string def = e.get_attribute_as_string("default");
AttributeSchema as(e);
std::string def2 = as.get_ihm_value(as.get_default_value());
if(as.type == TYPE_STRING)
def2 = "\"" + def2 + "\"";
//Valeur par défaut
res += "<p> " + langue.get_item("default-val") + " : " + def2;
if(e.has_attribute("unit") && (e.get_attribute_as_string("unit").size() > 0))
res += " " + e.get_attribute_as_string("unit");
res += "</p>";
if(!e.has_child("match"))
{
if(e.get_attribute_as_string("min").size() > 0)
{
res += "<p>Valeur minimale : "
+ e.get_attribute_as_string("min")
+ " " + e.get_attribute_as_string("unit")
+ "</p>";
}
if(e.get_attribute_as_string("max").size() > 0)
{
res += "<p>Valeur maximale : "
+ e.get_attribute_as_string("max")
+ " " + e.get_attribute_as_string("unit")
+ "</p>";
}
}
res += "<p>" + e.description() + "</p>";
return res;
}
}
}
| 142,825
|
C++
|
.cc
| 5,415
| 21.9012
| 152
| 0.583526
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,945
|
modele-wrapper.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/modele-wrapper.cc
|
#include "modele.hpp"
#include <string>
using namespace std;
namespace utils
{
namespace model
{
string NodeCppWrapper::format_comment(int indent, const Localized &l)
{
string s = "", desc = utils::str::utf8_to_latin(l.get_description());
uint32_t i, j, k;
for(i = 0; i < (uint32_t) indent; i++)
s += " ";
s += "/** @brief ";
s += utils::str::utf8_to_latin(l.get_localized());
/* Clean description. */
string d2;
bool only_spaces = true;
uint32_t scnt = 0;
for(i = 0; i < desc.size(); i++)
{
if((desc[i] == ' ') || (desc[i] == 0x0d) || (desc[i] == 0x0a) || (desc[i] == '\t'))
{
if(scnt == 0)
d2 += " ";
scnt++;
}
else
{
char c[2];
c[0] = desc[i];
c[1] = 0;
d2 += (&c[0]);
scnt = 0;
only_spaces = false;
}
}
if(only_spaces)
d2 = "";
if(only_spaces && (l.get_localized().size() == 0))
return "";
if(d2.size() > 0)
{
/* Text justification */
uint32_t colcnt = 0;
for(j = 0; j < d2.size(); j++)
{
if((j == 0) || (colcnt >= 70))
{
if((j > 0) && (d2[j-1] != ' '))
s += "-";
/* new line */
s += "\n";
for(k = 0; k < (uint32_t) indent; k++)
s += " ";
s += " * ";
if((j > 0) && (d2[j-1] != ' '))
s += "-";
colcnt = 0;
}
s += utils::str::utf8_to_latin(d2.substr(j, 1));
colcnt++;
}
}
return s;
}
NodeCppWrapper::NodeCppWrapper()
{
}
int NodeCppWrapper::gen_ccp_wrapper(NodeSchema *schema, const string &path_c, const string &path_h)
{
if(files::check_and_build_directory(path_c))
{
erreur("unable to create output source folder.");
return -1;
}
if(files::check_and_build_directory(path_h))
{
erreur("unable to create output include folder.");
return -1;
}
string s;
string fileid = str::str_to_file(schema->name.get_id());
s += "/** @file " + fileid + ".hpp\n";
s += " * Specific interface to the node " + schema->name.get_id() + " (" + schema->name.get_localized() + ").\n\n";
s += " * File generated on @todo */\n\n\n";
s += "#include <string>\n";
s += "#include <deque>\n";
s += "#include \"modele.hpp\"\n";
s += "\n";
s += "using namespace std;\n";
s += "using namespace utils;\n";
s += "using namespace utils::model;\n\n";
string header_path = path_h + files::get_path_separator() + fileid + ".hpp";
string source_path = path_c + files::get_path_separator() + fileid + ".cc";
// (1) Make the include file
// @todo dependancies
s += gen_class(schema);
files::save_txt_file(header_path, s);
// (2) Make the source file
s = "";
s += "#include \"" + fileid + ".hpp\"\n";
s += "#include <sstream>\n";
s += "#include <stdexcept>\n";
s += "#include <cstdlib>\n";
s += "#include <iostream>\n\n";
s += gen_class_impl(schema);
files::save_txt_file(source_path, s);
return 0;
}
string NodeCppWrapper::gen_class_impl(NodeSchema *schema)
{
unsigned int i, n;
string s;
size_t indent = 0, indent_step = 2;
/* export child classes */
n = schema->children.size();
for(i = 0; i < n; i++)
s += gen_class_impl(schema->children[i].ptr);
string cls = str::str_to_class(schema->name.get_id());
///// (1) Read from model implementation
{
s += "int " + cls + "::read_from_model(const Node model, bool partial_model)\n{\n";
n = schema->attributes.size();
for(i = 0; i < n; i++)
{
const AttributeSchema &as = *(schema->attributes[i]);
// Manage partial model
s += " if (!partial_model || model.has_attribute(\"" + as.name.get_id() + "\"))\n";
s += " " + str::str_to_var(as.name.get_id()) + " = " + gen_get_attribute_as(as) + ";\n";
}
n = schema->children.size();
for(i = 0; i < n; i++)
{
SubSchema &ss = schema->children[i];
NodeSchema *child = ss.ptr;
std::string mname = str::str_to_var(child->name.get_id());
if(ss.max == 1)
{
// Manage partial model
s += " if (!partial_model || model.has_child(\"" + child->name.get_id() + "\"))\n";
s += " " + mname + ".read_from_model(model.get_child(\"" + child->name.get_id() + "\"));\n";
}
else
{
s += " // Adapt the size of the container\n";
s += " " + mname + "s.resize(model.get_children_count(\"" + child->name.get_id() + "\"));\n";
s += " for(unsigned int i = 0; i < " + mname + "s.size(); i++)\n";
s += " " + mname + "s[i].read_from_model(model.get_child_at(\"" + child->name.get_id() + "\", i));\n";
}
}
s += "\n return 0;\n";
s += "}\n\n";
}
///// (2) Write to model implementation
{
s += "int " + cls + "::write_to_model(Node model)\n{\n";
/* Initialize the fields values */
TextMatrix tm(2);
n = schema->attributes.size();
for(i = 0; i < n; i++)
{
const AttributeSchema &as = *(schema->attributes[i]);
tm.add(" model.set_attribute(\"" + as.name.get_id() + "\", ");
tm.add(" " + str::str_to_var(as.name.get_id()) + ");");
tm.next_line();
}
s += tm.get_result();
n = schema->children.size();
for(i = 0; i < n; i++)
{
SubSchema &ss = schema->children[i];
NodeSchema *child = ss.ptr;
std::string mname = str::str_to_var(child->name.get_id());
if(ss.max == 1)
s += " " + mname + ".write_to_model(model.get_child(\"" + child->name.get_id() + "\"));\n";
else
{
s += " {\n";
s += " // Adapt number of children in the model according to the deque size\n";
s += " unsigned int n1 = " + mname + "s.size();\n";
s += " unsigned int n2 = model.get_children_count(\"" + child->name.get_id() + "\");\n\n";
s += " for(unsigned int i = n1; i < n2; i++)\n";
s += " model.remove_child(model.get_child_at(\"" + child->name.get_id() + "\", n1));\n\n";
s += " for(unsigned int i = n2; i < n1; i++)\n";
s += " model.add_child(\"" + child->name.get_id() + "\");\n\n";
//s += " " + mname + "s.clear();";
//s += " " + mname + "s.resize(model.get_children_count(\"" + child->name.get_id() + "\");\n";
s += " for(unsigned int i = 0; i < " + mname + "s.size(); i++)\n";
s += " " + mname + "s[i].write_to_model(model.get_child_at(\""
+ child->name.get_id() + "\", i));\n";
s += " }\n";
}
}
s += "\n return 0;\n";
s += "}\n\n";
}
///// (3) Update model implementation
{
s += "void " + cls + "::update_model(Node model) const\n{\n";
indent += indent_step;
// Process attributes
n = schema->attributes.size();
for(i = 0; i < n; i++)
{
const AttributeSchema &as = *(schema->attributes[i]);
s += gen_indent(indent) + "if (model.has_attribute(\"" + as.name.get_id() + "\")) {\n";
indent += indent_step;
s += gen_indent(indent) + gen_attribute_type(as) + " _" + str::str_to_var(as.name.get_id()) + " = " + gen_get_attribute_as(as) + ";\n";
s += gen_indent(indent) + "if (_" + str::str_to_var(as.name.get_id()) + " != " + str::str_to_var(as.name.get_id()) + ") {\n";
indent += indent_step;
// s += gen_indent(indent) + "std::cout << \"--- Attribute '" + as.name.get_id() + "' value has changed : \" << _" + str::str_to_var(as.name.get_id()) + " << \" -> \" << " + str::str_to_var(as.name.get_id()) + " << std::endl;\n";
s += gen_indent(indent) + "model.set_attribute(\"" + as.name.get_id() + "\", " + str::str_to_var(as.name.get_id()) + ");\n";
indent -= indent_step;
s += gen_indent(indent) + "}\n";
indent -= indent_step;
s += gen_indent(indent) + "} else {\n";
indent += indent_step;
s += gen_indent(indent) + "throw std::invalid_argument(\"No attribute of name '" + as.name.get_id() + "' was found in model to update\");\n";
indent -= indent_step;
s += gen_indent(indent) + "}\n";
}
s += gen_indent(indent) + "\n";
// Process children
n = schema->children.size();
for(i = 0; i < n; i++)
{
SubSchema &ss = schema->children[i];
NodeSchema *child = ss.ptr;
std::string mname = str::str_to_var(child->name.get_id());
s += gen_indent(indent) + "if (model.has_child(\"" + child->name.get_id() + "\")) {\n";
indent += indent_step;
if (ss.max == 1) {
s += gen_indent(indent) + mname + ".update_model(model.get_child(\"" + child->name.get_id() + "\"));\n";
} else {
s += gen_indent(indent) + "if (model.get_children_count(\"" + child->name.get_id() + "\") == " + mname + "s.size()) {\n";
indent += indent_step;
s += gen_indent(indent) + "for (size_t i = 0 ; i < " + mname + "s.size() ; i++) {\n";
indent += indent_step;
s += gen_indent(indent) + mname + "s[i].update_model(model.get_child_at(\"" + child->name.get_id() + "\", i));\n";
indent -= indent_step;
s += gen_indent(indent) + "}\n";
indent -= indent_step;
s += gen_indent(indent) + "} else {\n";
indent += indent_step;
s += gen_indent(indent) + "stringstream ss;\n";
s += gen_indent(indent) + "ss << \"Number of children of name '" + child->name.get_id() + "' in model to update is not equal to expected size\";\n";
s += gen_indent(indent) + "ss << \" (\" << model.get_children_count(\"" + child->name.get_id() + "\") << \" != \" << " + mname + "s.size() << \")\";\n";
s += gen_indent(indent) + "throw std::invalid_argument(ss.str());\n";
indent -= indent_step;
s += gen_indent(indent) + "}\n";
}
indent -= indent_step;
s += gen_indent(indent) + "} else {\n";
indent += indent_step;
// s += gen_indent(indent) + "std::cout << \"--- ERROR: No child of name '" + child->name.get_id() + "' was found in model to update\" << std::endl;\n";
s += gen_indent(indent) + "throw std::invalid_argument(\"No child of name '" + child->name.get_id() + "' was found in model to update\");\n";
indent -= indent_step;
s += gen_indent(indent) + "}\n";
}
s += "}\n\n";
}
///// (4) Read a single attribute from path and value
{
s += "void " + cls + "::read(const string &_path_, const string &_value_)\n{\n";
s += " // Look if attribute is in a child\n";
s += " size_t pos = _path_.find(\"/\");\n";
s += " if (pos == std::string::npos) {\n";
s += " // Search and modify concerned attribute\n";
s += " ";
n = schema->attributes.size();
for(i = 0; i < n; i++)
{
const AttributeSchema &as = *(schema->attributes[i]);
s += "if (_path_ == \"" + as.name.get_id() + "\") {\n";
s += " " + str::str_to_var(as.name.get_id());
switch(as.type)
{
case TYPE_STRING:
s += " = _value_;\n";
break;
case TYPE_FLOAT:
// s += " = std::stof(_value_);\n";
s += " = strtof(_value_.c_str(), nullptr);\n";
break;
case TYPE_BOOLEAN:
// s += " = (bool)std::stoi(_value_);\n";
s += " = (bool)strtol(_value_.c_str(), nullptr, 10);\n";
break;
case TYPE_INT:
if(as.enumerations.size() > 0) {
// s += " = (" + str::str_to_var(as.name.get_id()) + "_t) std::stoi(_value_);\n";
s += " = (" + str::str_to_var(as.name.get_id()) + "_t) strtol(_value_.c_str(), nullptr, 10);\n";
} else {
// s += " = std::stoi(_value_);\n";
s += " = strtol(_value_.c_str(), nullptr, 10);\n";
}
break;
default:
erreur("unmanaged att type!");
break;
}
s += " } else ";
}
s += "{\n";
s += " throw std::invalid_argument(\"No attribute of name '\" + _path_ + \"' was found\");\n";
s += " }\n";
s += " } else {\n";
s += " // Search and enter in concerned child\n";
s += "\n // Extract child information\n";
s += " std::string child_name = _path_.substr(0, pos);\n";
s += " std::string next_path = _path_.substr(pos + 1);\n";
bool use_index = false;
n = schema->children.size();
for(i = 0; i < n; i++) {
SubSchema &ss = schema->children[i];
if (ss.max != 1) {
use_index = true;
break;
}
}
if (use_index) {
s += " std::size_t child_index = 0;\n";
s += " std::size_t pos_ind = child_name.find(\"[\");\n";
s += " if (pos_ind != std::string::npos) {\n";
s += " std::string str_ind = child_name.substr(pos_ind + 1, child_name.length() - pos_ind - 2);\n";
// s += " child_index = std::stoi(str_ind);\n";
s += " child_index = strtol(str_ind.c_str(), nullptr, 10);\n";
s += " child_name = child_name.substr(0, pos_ind);\n";
s += " }\n";
}
s += "\n // Find concerned child\n";
s += " ";
n = schema->children.size();
for(i = 0; i < n; i++)
{
SubSchema &ss = schema->children[i];
NodeSchema *child = ss.ptr;
std::string mname = str::str_to_var(child->name.get_id());
s += "if (child_name == \"" + child->name.get_id() + "\") {\n";
if (ss.max == 1) {
s += " " + mname + ".read(next_path, _value_);\n";
} else {
s += " // Verify size of the container\n";
s += " if (child_index < " + mname + "s.size()) {\n";
s += " " + mname + "s[child_index].read(next_path, _value_);\n";
s += " } else {\n";
s += " std::stringstream oss;\n";
s += " oss << \"Index \" << child_index << \" of child named '\" << child_name << \"' is out of range (size = \" << " + mname + "s.size() << \")\";\n";
s += " std::string ossstr = oss.str();\n";
s += " throw std::out_of_range(ossstr.c_str());\n";
s += " }\n";
}
s += " } else ";
}
s += "{\n";
s += " throw std::invalid_argument(\"No child of name '\" + child_name + \"' was found\");\n";
s += " }\n";
s += " }\n";
s += "}\n\n";
}
return s;
}
string NodeCppWrapper::gen_class(NodeSchema *schema, int indent)
{
string s;
unsigned int i, j, k, n;
string cls_name = str::str_to_class(schema->name.get_id());
/* export child classes */
n = schema->children.size();
for(i = 0; i < n; i++)
s += gen_class(schema->children[i].ptr, indent);
s += format_comment(indent, schema->name) + "*/\n";
for(i = 0; i < (unsigned int) indent; i++)
s += " ";
s += "class ";
s += cls_name;
s += "\n{\n";
s += "public:\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "/** @brief Initialize the content of this specific class from a generic tree model.\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += " * By default partial_model is false, the model is considered complete, so that expected but unavailable sub-nodes generate an error.\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += " * If partial_model is true, the model is partially completed and only available sub-nodes are read. */\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "int read_from_model(const Node model, bool partial_model = false);\n\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "/** @brief Write all the values (recursively) contained in this specific class to a generic tree model. */\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "int write_to_model(Node model);\n\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "/** @brief Update all the values (recursively) contained in this specific class to a generic tree model. */\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "void update_model(Node model) const;\n\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "/** @brief Modify an attribute value of this specific class given a path and a value.\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += " * If given path or given value is invalid, an std::invalid_argument or std::out_of_range is thrown. */\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "void read(const string &path, const string &value);\n\n";
n = schema->attributes.size();
for(j = 0; j < n; j++)
{
AttributeSchema &as = *(schema->attributes[j]);
s += gen_attribute_comment(as, indent + 2);
for(i = 0; i < (unsigned int) (indent + 2); i++)
s += " ";
unsigned int nb_enums = as.enumerations.size();
if((nb_enums > 0) && (as.type == TYPE_INT))
{
s += "enum "
+ str::str_to_var(as.name.get_id()) + "_t" +
"\n {\n";
TextMatrix tm(3);
for(k = 0; k < nb_enums; k++)
{
Enumeration &match = as.enumerations[k];
if(match.name.has_description())
tm.add_unformatted_line(format_comment(indent + 4, match.name) + "*/\n");
tm.add(" ");
tm.add(str::str_to_cst(as.name.get_id() + "_" + match.name.get_id()));
string str = string(" = ") + match.value;
if(k != nb_enums - 1)
str += ",";
tm.add(str);
tm.next_line();
}
s += tm.get_result();
s += " }";
}
else
{
s += gen_attribute_type(as);
}
s += " ";
s += str::str_to_var(as.name.get_id());
s += ";\n\n";
}
for(k = 0; k < schema->children.size(); k++)
{
const SubSchema &ss = schema->children[k];
NodeSchema *child = schema->children[k].ptr;
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
s += "/** @brief " + child->name.get_localized() + " */\n";
for(i = 0; i < (unsigned int) indent + 2; i++)
s += " ";
string cls_name = str::str_to_class(child->name.get_id());
string var_name = str::str_to_var(child->name.get_id());
/** Only one instance */
if((ss.min == 1) && (ss.max == 1))
{
s += cls_name + " " + var_name + ";\n\n";
}
/** Multiple instances */
else
{
s += "deque<" + cls_name + "> " + var_name + "s" + ";\n\n";
}
}
s += "};\n\n\n\n";
return s;
}
std::string NodeCppWrapper::gen_attribute_comment(const AttributeSchema &as, int indent)
{
unsigned int i, j;
string s = format_comment(indent, as.name);
uint32_t nmatch = as.enumerations.size();
if(nmatch > 0)
{
TextMatrix mmatrix(2);
s += "\n";
for(j = 0; j < nmatch; j++)
{
const Enumeration &match = as.enumerations[j];
string idt = "";
for(i = 0; i < (uint32_t) indent + 4; i++)
idt += " ";
mmatrix.add(idt + match.value + ": ");
string dsc = utils::str::utf8_to_latin(match.name.get_localized());
mmatrix.add(dsc);
mmatrix.next_line();
}
s += mmatrix.get_result();
s = s.substr(0, s.size() - 1);
}
s += " */\n";
return s;
}
std::string NodeCppWrapper::gen_attribute_type(const AttributeSchema &as) {
switch(as.type)
{
case utils::model::TYPE_STRING:
return "string";
break;
case utils::model::TYPE_INT:
return "int";
break;
case utils::model::TYPE_BOOLEAN:
return "bool";
break;
case utils::model::TYPE_FLOAT:
return "float";
break;
default:
avertissement("type unknown.");
return "int";
break;
}
}
std::string NodeCppWrapper::gen_indent(size_t indent) {
string res;
for(size_t i = 0; i < indent; i++)
res += " ";
return res;
}
std::string NodeCppWrapper::gen_get_attribute_as(const AttributeSchema &as) {
std::string res;
switch(as.type)
{
case TYPE_STRING:
res = "model.get_attribute_as_string(\"" + as.name.get_id() + "\")";
break;
case TYPE_FLOAT:
res = "model.get_attribute_as_float(\"" + as.name.get_id() + "\")";
break;
case TYPE_BOOLEAN:
res = "model.get_attribute_as_boolean(\"" + as.name.get_id() + "\")";
break;
case TYPE_INT:
if(as.enumerations.size() > 0) {
res = "(" + str::str_to_var(as.name.get_id()) + "_t) model.get_attribute_as_int(\"" + as.name.get_id() + "\")";
} else {
res = "model.get_attribute_as_int(\"" + as.name.get_id() + "\")";
}
break;
default:
erreur("unmanaged att type!");
break;
}
return res;
}
}
}
| 20,018
|
C++
|
.cc
| 556
| 31.151079
| 232
| 0.522398
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,946
|
erreurs.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/erreurs.cc
|
#include "erreurs.hpp"
#include "cutil.hpp"
#include "mmi/gtkutil.hpp"
namespace utils {
struct EvErreur
{
unsigned int id;
std::string titre, description;
};
static std::vector<Erreur> erreurs;
Erreur indef;
static int erreurs_charge(const std::string &chemin);
std::vector<EvErreur> pile_erreur;
void signale_erreur(unsigned int id, ...)
{
va_list ap;
va_start(ap, id);
EvErreur ev;
ev.id = id;
auto e = erreur_get(id);
char tampon[1000];
vsnprintf(tampon, 1000, e.locale.get_description(utils::model::Localized::LANG_CURRENT).c_str(), ap);
ev.description = std::string(tampon);
ev.titre = e.locale.get_localized();
pile_erreur.push_back(ev);
auto s = "Erreur detectee : " + ev.titre + "\n" + ev.description;
gen_trace(utils::journal::TraceLevel::AL_ANOMALY, "", s);
va_end(ap);
}
void affiche_pile_erreurs()
{
if(pile_erreur.size() == 0)
return;
//auto e = erreur_get(id);
//auto s = e.locale.get_localized();
int dernier = pile_erreur.size() - 1;
Gtk::MessageDialog dial(pile_erreur[dernier].titre,
true,
Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_OK,
true);
dial.set_title("Erreur");//pile_erreur[dernier].titre);//"Erreur");
std::string s = "", s2 = "";
s += std::string("<b>") + pile_erreur[dernier].titre + "</b>\n";
s += pile_erreur[dernier].description;
//if(pile_erreur.size() > 1)
//s += "\"
for(auto i = 1u; i < pile_erreur.size(); i++)
{
auto &e = pile_erreur[dernier-i];
//if(i > 0)
s2 += std::string("<b>") + e.titre + "</b>\n";
s2 += e.description;
if(i + 1 < pile_erreur.size())
s2 += "\n";
}
dial.set_message(s, true);
if(s2.size() > 0)
dial.set_secondary_text(s2, true);
dial.set_position(Gtk::WIN_POS_CENTER);
utils::mmi::DialogManager::setup_window(&dial);
dial.run();
pile_erreur.clear();
}
static int erreurs_charge(const utils::model::MXml &mx)
{
indef.id = 0xffffffff;
indef.locale.set_value(utils::model::Localized::LANG_FR, "Code d'erreur non trouvé.");
auto lst = mx.get_children("charge");
for(auto &c: lst)
erreurs_charge(utils::get_fixed_data_path() + "/" + c.get_attribute("fichier").to_string());
lst = mx.get_children("erreur");
for(auto &e: lst)
{
Erreur err;
err.locale = utils::model::Localized(e);
err.id = e.get_attribute("id").to_int();
erreurs.push_back(err);
}
return 0;
}
static int erreurs_charge(const std::string &chemin)
{
if(!utils::files::file_exists(chemin))
{
erreur("Fichier d'erreur non trouve.");
return -1;
}
utils::model::MXml mx;
if(mx.from_file(chemin))
{
erreur("Erreur lors du chargement du fichier d'erreur.");
return -1;
}
return erreurs_charge(mx);
}
int erreurs_charge()
{
if(erreurs_charge(utils::get_fixed_data_path() + "/" + "erreurs.xml"))
return -1;
infos("Charge %d messages d'erreurs.", erreurs.size());
return 0;
}
int erreur_affiche(unsigned int id)
{
auto e = erreur_get(id);
auto s = e.locale.get_localized();
avertissement("Erreur detectee : [%s]", s.c_str());
//utils::mmi::dialogs::affiche_erreur():
Gtk::MessageDialog dial(s,
false,
Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE,
true);
dial.set_title("Erreur");
dial.set_secondary_text(e.locale.get_description());
dial.set_position(Gtk::WIN_POS_CENTER);
utils::mmi::DialogManager::setup_window(&dial);
dial.run();
return 0;
}
Erreur &erreur_get(unsigned int id)
{
for(auto i = 0u; i < erreurs.size(); i++)
if(erreurs[i].id == id)
return erreurs[i];
return indef;
}
}
| 3,761
|
C++
|
.cc
| 129
| 24.449612
| 103
| 0.620536
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
753,947
|
journal.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/journal.cc
|
#include "cutil.hpp"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <malloc.h>
#include "../include/journal.hpp"
#ifdef LINUX
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <linux/unistd.h>
#endif
#include <iostream>
#include <csignal>
//#define DISPLAY_TIME
#ifdef DISPLAY_TIME
#include <boost/date_time/posix_time/posix_time.hpp>
#endif
#include <stdexcept>
using namespace std;
namespace utils
{
namespace journal
{
Logable journal_principal;
/** @brief Trace to a log file */
class FileTracer: public Tracer
{
public:
FileTracer();
~FileTracer();
int set_log_file(const std::string &filename);
void gen_trace(int trace_level, const std::string &module, const std::string &message);
void flush();
private:
FILE *of;
std::string filename;
};
/** @brief Trace to standard output */
class StdTracer: public Tracer
{
public:
StdTracer();
~StdTracer();
void gen_trace(int trace_level, const std::string &module, const std::string &message);
void flush();
private:
};
struct TraceData
{
TraceData();
friend class Tracer;
friend class Logable;
bool global_enable;
TraceLevel global_min_levels[2];
Tracer *tracers[2];
FileTracer file_tracer;
StdTracer std_tracer;
uint32_t anomaly_count, warning_count;
char *tmp_buffer;
bool abort_on_anomaly, throw_on_anomaly;
#ifndef DISPLAY_TIME
bool date_base_ok;
uint64_t date_base;
#endif
};
static TraceData instance;
/*
#ifdef LINUX
hal::Mutex tm_mutex_;
#define tm_mutex (&tm_mutex_)
#else
hal::Mutex *tm_mutex;
#endif
*/
hal::Mutex tm_mutex_;
#define tm_mutex (&tm_mutex_)
#define TRACE_BSIZE (10*1024)
TraceData::TraceData()
{
abort_on_anomaly = throw_on_anomaly = false;
# ifndef DISPLAY_TIME
date_base_ok = false;
date_base = 0;
# endif
warning_count = 0;
anomaly_count = 0;
global_enable = true;
global_min_levels[0] = AL_VERBOSE;
global_min_levels[1] = AL_NONE;
tracers[0] = &std_tracer;
tracers[1] = &file_tracer;
tmp_buffer = (char *) malloc(TRACE_BSIZE);
}
uint32_t get_anomaly_count()
{
return instance.anomaly_count;
}
uint32_t get_warning_count()
{
return instance.warning_count;
}
void set_abort_on_anomaly(bool abort)
{
instance.abort_on_anomaly = abort;
}
void enable_all(bool enable)
{
instance.global_enable = enable;
}
void set_log_file(std::string filename)
{
instance.file_tracer.set_log_file(filename);
}
TraceLevel get_global_min_level(TraceTarget target)
{
uint32_t tr = (uint32_t) target;
if(tr < 2)
return instance.global_min_levels[tr];
return AL_NONE;
}
void Logable::set_min_level(TraceTarget target, TraceLevel min_level)
{
uint32_t tr = (uint32_t) target;
if(tr < 2)
{
min_levels[tr] = min_level;
}
}
void set_global_min_level(TraceTarget target, TraceLevel min_level)
{
uint32_t tr = (uint32_t) target;
if(tr < 2)
{
instance.global_min_levels[tr] = min_level;
}
}
int FileTracer::set_log_file(const std::string &filename)
{
if(utils::files::file_exists(filename))
utils::files::copy_file(filename + ".old", filename);
this->filename = filename;
if(of != nullptr)
fclose(of);
of = fopen(filename.c_str(), "wt");
return (of == nullptr) ? -1 : 0;
}
FileTracer::FileTracer()
{
of = nullptr;
//set_log_file("./infos.log");
}
FileTracer::~FileTracer()
{
if(of != nullptr)
fclose(of);
}
void FileTracer::flush()
{
fflush(of);
}
void FileTracer::gen_trace(int trace_level, const std::string &module, const std::string &message)
{
if(of != nullptr)
{
#ifndef DISPLAY_TIME
if(!instance.date_base_ok)
{
instance.date_base_ok = true;
instance.date_base = hal::get_tick_count_us();
}
#endif
{
#ifndef DISPLAY_TIME
uint64_t ticks = hal::get_tick_count_us() - instance.date_base;
uint32_t seconds = ticks / (1000 * 1000);
ticks -= seconds * 1000 * 1000;
uint32_t ms = ticks / 1000;
ticks -= ms * 1000;
uint32_t us = (uint32_t) ticks;
#endif
if(trace_level == AL_WARNING)
fprintf(of, "-- AVERTISSEMENT : ");
else if(trace_level == AL_ANOMALY)
fprintf(of, "-- ANOMALIE : ");
#ifdef DISPLAY_TIME
// boost::posix_time::ptime time_now = boost::posix_time::microsec_clock::universal_time();
boost::posix_time::ptime time_now = boost::posix_time::microsec_clock::local_time();
std::string time_str = boost::posix_time::to_iso_extended_string(time_now);
fprintf(of, "%s: ", time_str.c_str());
#else
fprintf(of, "%4u,%03d,%03d: ", seconds, ms, us);
#endif
fprintf(of, "[%s] %s\n", module.c_str(), message.c_str());
//if(trace_level >= AL_NORMAL)
{
fflush(of);
}
if(ferror(of))
{
cerr << "Error while writing in the log file: closing & restart." << endl;
clearerr(of);
fclose(of);
of = fopen(filename.c_str(), "wt");
}
}
}
}
StdTracer::StdTracer()
{
}
StdTracer::~StdTracer()
{
}
void StdTracer::gen_trace(int trace_level, const std::string &module, const std::string &message)
{
FILE *fout = (trace_level < AL_WARNING) ? stdout : stderr;
ostream *out = &(std::cout);
//FILE *output = stdout;
char color[30];
if(trace_level >= AL_WARNING)
out = &(std::cerr); //output = stderr;
switch(trace_level)
{
case AL_VERBOSE:
{
sprintf(color, "34");
break;
}
case AL_NORMAL:
{
sprintf(color, "30");
break;
}
case AL_MAJOR:
{
sprintf(color, "1");
break;
}
case AL_WARNING:
{
sprintf(color, "31");
break;
}
case AL_ANOMALY:
{
//sprintf(color, "31");
sprintf(color, "1;37;41");
break;
}
}
#ifndef DISPLAY_TIME
if(!instance.date_base_ok)
{
instance.date_base_ok = true;
instance.date_base = hal::get_tick_count_us();
}
#endif
{
#ifdef DISPLAY_TIME
boost::posix_time::ptime time_now = boost::posix_time::microsec_clock::local_time();
std::string time_str = boost::posix_time::to_iso_extended_string(time_now);
fprintf(output, "%s: ", time_str.c_str());
#else
uint64_t new_ticks = hal::get_tick_count_us();
uint64_t ticks = new_ticks - instance.date_base;
uint32_t seconds = ticks / (1000 * 1000);
ticks -= seconds * 1000 * 1000;
uint32_t ms = ticks / 1000;
ticks -= ms * 1000;
uint32_t us = (uint32_t) ticks;
fprintf(fout, "%4u,%03u,%03u ", seconds, ms, us);
//*out << seconds << "," << ms << "," << us;
#endif
/*#ifdef LINUX
fprintf(output, " %x ", (unsigned int) pthread_self());///gettid());
#endif*/
*out << " \033[" << color << "m";
if(module.size() > 0)
*out << "[" << module << "] ";
*out << message << "\033[0m" << std::endl;
//fprintf(output, "\033[%sm[%s] %s\033[0m\n", color, module.c_str(), message.c_str());
//if(trace_level >= TraceManager::TRACE_LEVEL_WARNING)
// fflush(output);
/*if(seconds > 1000000)
{
fprintf(output, "Counter overflow: new ticks = %llu, base = %llu, diff = %llu, secs = %u.\n",
(long long unsigned int) new_ticks,
(long long unsigned int) date_base,
(long long unsigned int) ticks, seconds);
}*/
}
}
void StdTracer::flush()
{
std::cerr.flush();
std::cout.flush();
}
void gen_trace(TraceLevel niveau,
const std::string &fonction,
const Logable &log,
const std::string &s,
va_list ap)
{
bool somewhere_to_trace = false;
instance.anomaly_count += (niveau == AL_ANOMALY) ? 1 : 0;
instance.warning_count += (niveau == AL_WARNING) ? 1 : 0;
if(!instance.global_enable)
return;
for(uint32_t i = 0; i < 2; i++)
{
if((niveau >= instance.global_min_levels[i]) && (niveau >= log.min_levels[i]))
{
somewhere_to_trace = true;
break;
}
}
if(!somewhere_to_trace)
return;
if(instance.tmp_buffer != nullptr)
{
tm_mutex->lock();
if(vsnprintf(instance.tmp_buffer, TRACE_BSIZE, s.c_str(), ap) > 0)
{
for(uint32_t i = 0; i < 2; i++)
{
if((niveau >= instance.global_min_levels[i]) && (niveau >= log.min_levels[i]))
{
Tracer *tracer = instance.tracers[i];
tracer->gen_trace(niveau, fonction, instance.tmp_buffer);
/*
# ifdef DEBUG_MODE
tracer->flush();
# else
if(i == 1)
tracer->flush(); // always flush file infos.
# endif
*/
}
}
}
tm_mutex->unlock();
}
if(niveau == TraceLevel::AL_ANOMALY)
{
/*if(instance.abort_on_anomaly || instance.throw_on_anomaly)
{
for(uint32_t i = 0; i < 2; i++)
if(niveau >= instance.global_min_levels[i])
instance.tracers[i]->flush();
}*/
# ifdef DEBUG_MODE
if(instance.abort_on_anomaly)
*((char *) 0) = 5;
//if (ptrace(PTRACE_TRACEME, 0, NULL, 0) == -1)
//{
//raise(SIGABRT);
//}
# endif
# ifdef RELEASE_MODE
if(instance.abort_on_anomaly)
{
raise(SIGABRT);
}
# endif
if(instance.throw_on_anomaly)
throw std::runtime_error("Runtime anomaly detected. See log file for more informations.");
}
}
void gen_trace(TraceLevel level, const std::string &fonction, const Logable &log, const std::string &s, ...)
{
va_list ap;
va_start(ap, s);
gen_trace(level, fonction, log, s, ap);
va_end(ap);
}
void gen_trace(TraceLevel level, const std::string &fonction, const std::string &s, ...)
{
va_list ap;
va_start(ap, s);
gen_trace(level, fonction, journal_principal, s, ap);
va_end(ap);
}
Logable::Logable(const std::string &module)
{
module_id = module;
min_levels[0] = min_levels[1] = AL_VERBOSE;
}
void Logable::setup(const std::string &module)
{
module_id = module;
}
#if 0
void Logable::trace_normale(std::string s, ...) const
{
va_list ap;
va_start(ap, s);
journal::gen_trace(AL_NORMAL, *this, module_id, s, ap);
va_end(ap);
}
void Logable::trace_major(std::string s, ...) const
{
va_list ap;
va_start(ap, s);
journal::gen_trace(AL_MAJOR, *this, module_id, s, ap);
va_end(ap);
}
void Logable::anomaly(std::string s, ...) const
{
va_list ap;
va_start(ap, s);
journal::gen_trace(AL_ANOMALY, *this, module_id, s, ap);
va_end(ap);
}
void Logable::warning(std::string s, ...) const
{
va_list ap;
va_start(ap, s);
journal::gen_trace(AL_WARNING, *this, module_id, s, ap);
va_end(ap);
instance.warning_count++;
}
void Logable::verbose_internal(std::string s, va_list ap) const
{
if(actif)
journal::gen_trace(journal::AL_VERBOSE, journal_principal, module_id, s, ap);
}
#endif
}
#if 0
void verbose(const char *s, ...)
{
va_list ap;
va_start(ap, s);
journal::gen_trace(journal::AL_VERBOSE, "", s, ap);
va_end(ap);
}
void infos(const char *s, ...)
{
va_list ap;
va_start(ap, s);
journal::gen_trace(journal::AL_NORMAL, "", s, ap);
va_end(ap);
}
void trace_majeure(const char *s, ...)
{
va_list ap;
va_start(ap, s);
journal::gen_trace(journal::AL_MAJOR, "", s, ap);
va_end(ap);
}
void erreur(const char *s, ...)
{
va_list ap;
va_start(ap, s);
journal::gen_trace(journal::AL_ANOMALY, "", s, ap);
va_end(ap);
}
void avertissement(const char *s, ...)
{
va_list ap;
va_start(ap, s);
journal::gen_trace(journal::AL_WARNING, "", s, ap);
va_end(ap);
}
#endif
}
| 11,447
|
C++
|
.cc
| 467
| 20.860814
| 108
| 0.629184
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,948
|
cutil.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/cutil.cc
|
#include <sys/stat.h>
#include "cutil.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <ctime>
#include <sstream>
#include <unistd.h> // for unlink
#include <cmath>
#include <dirent.h>
#ifdef WIN
# include <windows.h>
# include <winbase.h>
# include <stdio.h>
# include <Shlobj.h>
#else
# include <sys/stat.h>
# include <limits.h>
#endif
#include <string.h>
#include <malloc.h>
#include "modele.hpp"
using namespace std;
namespace utils
{
using namespace model;
#if 0
void VoidEventProvider::remove_all_listeners()
{
functors.clear();
}
void VoidEventProvider::dispatch()
{
std::vector<void *> copy;
std::vector<VoidEventFunctor *> copy2;
for(unsigned int i = 0; i < functors.size(); i++)
copy2.push_back(functors[i]);
for(unsigned int i = 0; i < copy2.size(); i++)
{
VoidEventFunctor *ef = copy2[i];
ef->call();
}
}
#endif
////////////////////////////////////////////////
//// CONSTANT DATA
////////////////////////////////////////////////
#define NLANG 5
static std::string lglist[NLANG] =
{"fr", "en", "de", "ru", "es"};
////////////////////////////////////////////////
//// LOCAL FUNCTIONS
////////////////////////////////////////////////
static std::string get_self_path(const char *argv0);
////////////////////////////////////////////////
//// LOCAL DATA
////////////////////////////////////////////////
class AppData
{
public:
std::string nom_appli;
std::string nom_projet;
std::string dossier_executable;
std::string chemin_donnees_fixes;
std::string chemin_images;
};
static AppData appdata;
Localized::Language Localized::current_language = Localized::LANG_FR;
Section langue;
#ifdef WIN
static int vasprintf(char **sptr, const char *fmt, va_list argv )
{
int wanted = vsnprintf( *sptr = nullptr, 0, fmt, argv );
if( (wanted > 0) && ((*sptr = (char *) malloc( 1 + wanted )) != nullptr) )
return vsprintf( *sptr, fmt, argv );
return wanted;
}
#endif
#ifdef WIN
extern "C"
{
char *strdup(const char *s)
{
char *res = (char *) malloc(strlen(s) + 1);
strcpy(res, s);
return res;
}
}
#endif
static std::string get_self_path(const char *argv0)
{
# ifdef WIN
char actualpath[300];
HMODULE hmod = GetModuleHandle(NULL);//GetCurrentModule();
if(hmod == NULL)
{
cerr << "get_self_path: Failed to retrieve module handle!" << endl;
}
GetModuleFileName(hmod,/*nullptr,*/ /*(LPWSTR)*/ actualpath, 300);
# else
char actualpath[PATH_MAX + 1];
if(realpath(argv0, actualpath) == nullptr)
{
perror("realpath.");
return "";
}
# endif
return std::string(actualpath);
}
int files::copy_file(std::string target, std::string source)
{
# ifndef LINUX
infos("Copie fichier [%s] <- [%s]...", target.c_str(), source.c_str());
if(!(::CopyFile(source.c_str(), target.c_str(), false)))
{
int err = ::GetLastError();
avertissement("Echec copyfile, code d'erreur = %d (0x%x).", err, err);
return -1;
}
return 0;
# else
return utils::proceed_syscmde("cp \"%s\" \"%s\"", source.c_str(), target.c_str());
# endif
}
int proceed_syscmde_bg(std::string cmde, ...)
{
char *full_cmde;
va_list ap;
int result;
va_start(ap, cmde);
result = vasprintf(&full_cmde, cmde.c_str(), ap);
va_end(ap);
if(result == -1)
{
fprintf(stderr, "vasprintf failure: %d.\n", result);
return result;
}
/*TraceManager::infos(TraceManager::TRACE_LEVEL_NORMAL,
"util",
"System command: '%s'..", full_cmde);*/
# ifdef LINUX
std::string s = std::string(full_cmde) + " &";
result = system(s.c_str());
# else
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
//SECURITY_ATTRIBUTES sa;
if(!::CreateProcess(nullptr,
/*(LPWSTR)*/ full_cmde,
nullptr, /* security attributes for process */
nullptr, /* security attributes for thread */
0, /* inherits handles ? */
CREATE_NO_WINDOW, /* creation flags */
nullptr, /* environment */
nullptr, /* initial path */
&si, /* startup infos */
&pi /* process infos */
))
{
result = 1;
}
else
{
result = 0;
/*
// Wait until child process exits.
::WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);*/
}
# endif
if(result != 0)
{
fprintf(stderr, "System command failure (%d): '%s'.\n", result, full_cmde);
erreur("System command failure(%d): '%s'..\n", result, full_cmde);
}
free(full_cmde);
return result;
}
int proceed_syscmde(std::string cmde, ...)
{
char *full_cmde;
va_list ap;
int result;
va_start(ap, cmde);
result = vasprintf(&full_cmde, cmde.c_str(), ap);
va_end(ap);
if(result == -1)
{
fprintf(stderr, "vasprintf failure: %d.\n", result);
return result;
}
if(full_cmde != nullptr)
infos("System command: '%s'..", full_cmde);
# ifdef LINUX
result = system(full_cmde);
# else
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
//SECURITY_ATTRIBUTES sa;
if(!::CreateProcess(nullptr,
/*(LPWSTR)*/ full_cmde,
nullptr, /* security attributes for process */
nullptr, /* security attributes for thread */
1, /* inherits handles ? */
/*CREATE_NO_WINDOW*/0, /* creation flags */
nullptr, /* environment */
nullptr, /* initial path */
&si, /* startup infos */
&pi /* process infos */
))
{
result = 1;
}
else
{
result = 0;
// Wait until child process exits.
::WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
}
# endif
if(result != 0)
{
fprintf(stderr, "System command failure (%d): '%s'.\n", result, full_cmde);
erreur("System command failure(%d): '%s'..\n", result, full_cmde);
}
free(full_cmde);
return result;
}
std::string get_execution_path()
{
return appdata.dossier_executable;
}
void init(int argc, const char **argv, const std::string &projet, const std::string &app,
unsigned int vmaj,
unsigned int vmin,
unsigned int vpatch)
{
CmdeLine cl(argc, argv);
init(cl, projet, app, vmaj, vmin, vpatch);
}
void init(CmdeLine &cmdeline,
const std::string &projet,
const std::string &app,
unsigned int vmaj,
unsigned int vmin,
unsigned int vpatch)
{
std::string fullpath, unused;
appdata.nom_appli = app;
appdata.nom_projet = projet;
if(app.size() == 0)
{
std::string dummy, fn;
utils::files::split_path_and_filename(cmdeline.argv0, dummy, fn);
appdata.nom_appli = utils::files::remove_extension(fn);
}
if(appdata.nom_appli.size() == 0)
appdata.nom_appli = projet;
//if(cmdeline.argv != nullptr)
fullpath = get_self_path(cmdeline.argv0.c_str());
files::split_path_and_filename(fullpath, appdata.dossier_executable, unused);
Localized::current_language = Localized::LANG_FR;
//std::cout << "fullpath = " << fullpath << std::endl;
//std::cout << "Exec dir = " << appdata.exec_dir << std::endl;
if(cmdeline.has_option("-l"))
Localized::current_language = Localized::parse_language(cmdeline.get_option("-l", "fr"));
if(appdata.dossier_executable.size() == 0)
appdata.dossier_executable = ".";
appdata.chemin_donnees_fixes = appdata.dossier_executable + PATH_SEP + "data";
//std::cout << "Fixed data path = " << appdata.fixed_data_path << std::endl;
if(!files::dir_exists(appdata.chemin_donnees_fixes))// + PATH_SEP + "std-lang.xml"))
{
# ifdef WIN
// SHOULD EXIST ALL TIME!
fprintf(stderr, "Fixed data path not found: [%s].\n", appdata.chemin_donnees_fixes.c_str());
# else
appdata.chemin_donnees_fixes = "/usr/share/" + projet + "/data";
# endif
}
appdata.chemin_images = appdata.chemin_donnees_fixes + PATH_SEP + "img";
std::string cup = utils::get_current_user_path();
// Check if writable data path exists
if(!files::dir_exists(cup))
{
files::creation_dossier(cup);
//fprintf(stdout, "created directory %s.\n", cup.c_str());
}
std::string cudp = utils::get_current_user_doc_path();
if(!files::dir_exists(cudp))
files::creation_dossier(cudp);
std::string log_file = cup + PATH_SEP + appdata.nom_appli + "-log.txt";
journal::TraceLevel tl = journal::AL_NONE;
journal::TraceLevel tlf = journal::AL_NONE;
if(cmdeline.has_option("-v"))
tl = journal::AL_NORMAL;
if(cmdeline.has_option("-vv"))
tl = journal::AL_VERBOSE;
if(cmdeline.has_option("--ftrace-level"))
{
int level = cmdeline.get_int_option("--ftrace-level", 7);
if(level < 6)
tlf = (journal::TraceLevel) level;
}
if(cmdeline.has_option("--infos-file-name"))
{
log_file = cmdeline.get_option("--infos-file-name");
}
if(cmdeline.has_option("--infos-level"))
{
int level = cmdeline.get_int_option("--infos-level", 7);
if(level < 6)
tl = (journal::TraceLevel) level;
}
//printf("tl = %d\n", (int) tl);
/* Setup STDOUT traces level */
journal::set_global_min_level(journal::TRACE_TARGET_STD, tl);
/* Setup FILE traces level */
journal::set_global_min_level(journal::TRACE_TARGET_FILE, tlf);
journal::set_log_file(log_file);
{
string fs = utils::get_fixed_data_path() + PATH_SEP + "std-lang.xml";
if(files::file_exists(fs))
langue.load(fs);
}
{
string fs = utils::get_fixed_data_path() + PATH_SEP + "lang.xml";
if(files::file_exists(fs))
langue.load(fs);
}
# ifdef DEBUG_MODE
journal::set_abort_on_anomaly(true);
# else
if(cmdeline.has_option("--abrt"))
journal::set_abort_on_anomaly(true);
# endif
////////////////////////////////////////////////
/// Vérification / création du dossier utilisateur/MGC
////////////////////////////////////////////////
{
std::string chem = utils::get_current_user_doc_path();
if(!utils::files::dir_exists(chem))
{
infos("Creation du dossier utilisateur (%s).", chem.c_str());
utils::files::creation_dossier(chem);
}
if(!utils::files::dir_exists(chem))
erreur("Impossible de créer le dossier utilisateur [%s].", chem.c_str());
}
std::string dts = utils::get_current_date_time();
infos("Fichier journal pour l'application %s, version %d.%d.%d\nDate / heure lancement application : %s\n**************************************\n**************************************\n**************************************",
appdata.nom_appli.c_str(), vmaj, vmin, vpatch, dts.c_str());
infos("Initialisation libcutil faite.");
}
std::string get_fixed_data_path()
{
/*# ifdef WIN
return exec_dir;
# else
return exec_dir;
# endif*/
/*if(fixed_data_path.size() == 0)
{
if(exec_dir.size() == 0)
return ".";
return exec_dir;
}
return fixed_data_path;*/
//printf("get_fixed_data_path: %s\n", appdata.fixed_data_path.c_str());fflush(0);
return appdata.chemin_donnees_fixes;
}
std::string get_img_path()
{
/*if(img_path.size() == 0)
img_path = exec_dir + PATH_SEP + "img";
return img_path;*/
//return get_fixed_data_path() + PATH_SEP + "img";
return appdata.chemin_images;
}
/*void Util::set_fixed_data_path(std::string s)
{
fixed_data_path = s;
}*/
std::string str::unix_path_to_win_path(std::string s_)
{
//s_ = replace_template(s_);
const char *s = s_.c_str();
char buffer[1000];
unsigned int j = 0;
for(unsigned int i = 0; i < strlen(s); i++)
{
if(s[i] == '/')
buffer[j++] = '\\';
else
buffer[j++] = s[i];
}
buffer[j] = 0;
return std::string(buffer);
}
void str::encode_str(std::string str, std::vector<unsigned char> vec)
{
const char *s = str.c_str();
for(unsigned int i = 0; i < strlen(s); i++)
{
unsigned char c = (unsigned char) s[i];
vec.push_back(c);
}
vec.push_back(0x00);
}
void str::encode_byte_array_deci(std::string str, std::vector<unsigned char> vec)
{
const char *s = str.c_str();
unsigned char current = 0;
if(!is_deci(s[0]))
{
erreur("Encoding decimal byte array : this string cannot be encoded: %s", str.c_str());
return;
}
while(strlen(s) > 0)
{
if(is_deci(s[0]))
{
current = current * 10 + (s[0] - '0');
}
else
{
if(strlen(s) > 1)
{
vec.push_back(current);
current = 0;
}
}
s++;
}
vec.push_back(current);
}
bool str::is_deci(char c)
{
return ((c >= '0') && (c <= '9'));
}
bool str::is_hexa(char c)
{
return (((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')));
}
int str::parse_hexa_list(const std::string str, std::vector<unsigned char> &res)
{
const char *s = str.c_str();
res.clear();
int current = 0;
if(!str::is_hexa(s[0]))
return -1;
while(strlen(s) > 0)
{
if(str::is_deci(s[0]))
{
current = (current << 4) + (s[0] - '0');
}
else if((s[0] >= 'a') && (s[0] <= 'f'))
{
current = (current << 4) + (s[0] - 'a' + 10);
}
else if((s[0] >= 'A') && (s[0] <= 'F'))
{
current = (current << 4) + (s[0] - 'a' + 10);
}
else
{
if(strlen(s) > 1)
{
res.push_back((unsigned char) current);
current = 0;
}
}
s++;
}
res.push_back((unsigned char) current);
return 0;
}
int str::parse_string_list(const std::string str, std::vector<std::string> &res, char separator)
{
const char *s = str.c_str();
res.clear();
std::string current = "";
while(strlen(s) > 0)
{
if(s[0] != separator)
{
char tmp[2];
tmp[0] = s[0];
tmp[1] = 0;
current = current + std::string(tmp);
}
else
{
if(strlen(s) > 1)
{
res.push_back(current);
current = "";
}
}
s++;
}
res.push_back(current);
return 0;
}
int str::parse_int_list(const std::string str, std::vector<int> &res)
{
const char *s = str.c_str();
res.clear();
int current = 0;
if(!str::is_deci(s[0]))
return -1;
while(strlen(s) > 0)
{
if(str::is_deci(s[0]))
{
current = current * 10 + (s[0] - '0');
}
else
{
if(((s[0] == '.') || ((s[0] == ','))) && (strlen(s) > 1))
{
res.push_back(current);
current = 0;
}
else
{
return -1;
}
}
s++;
}
res.push_back(current);
return 0;
}
void str::encode_byte_array_hexa(std::string str, std::vector<unsigned char> vec)
{
const char *s = str.c_str();
unsigned char current = 0;
if(!is_hexa(s[0]))
{
return;
}
while(strlen(s) > 0)
{
if(is_deci(s[0]))
{
current = (current << 4) + (s[0] - '0');
}
else if((s[0] >= 'a') && (s[0] <= 'f'))
{
current = (current << 4) + (s[0] - 'a' + 10);
}
else if((s[0] >= 'A') && (s[0] <= 'F'))
{
current = (current << 4) + (s[0] - 'a' + 10);
}
else
{
if(strlen(s) > 1)
{
vec.push_back(current);
current = 0;
}
}
s++;
}
vec.push_back(current);
}
std::string str::xmlAtt(std::string name, std::string val)
{
const char *s = val.c_str();
char buf[1000];
unsigned int n = strlen(s);
unsigned int j = 0;
for(unsigned int i = 0; i < n; i++)
{
if(s[i] == '"')
{
buf[j++] = '\\';
buf[j++] = 'G';
}
else
{
buf[j++] = s[i];
}
}
buf[j] = 0;
return std::string(" ") + name + "=\"" + std::string(buf) + "\"";
}
std::string str::xmlAtt(std::string name, int val)
{
return std::string(" ") + name + "=\"" + str::int2str(val) + "\"";
}
std::string str::xmlAtt(std::string name, bool val)
{
return std::string(" ") + name + "=\"" + (val ? "true" : "false") + "\"";
}
std::string str::int2strasm(int i)
{
return std::string("d'") + int2str(i) + "'";
}
std::string str::uint2strhexa(int i)
{
char buf[100];
if(i < 0x10)
sprintf(buf, "0x0%x", i);
else
sprintf(buf, "0x%x", i);
return std::string(buf);
}
std::string str::int2strhexa(int i, int nbits)
{
unsigned int v = (unsigned int) i;
char buf[100];
if(nbits == 32)
sprintf(buf, "%.8x", v);
else if(nbits == 8)
sprintf(buf, "%.2x", v);
else
sprintf(buf, "%.4x", v);
return std::string(buf);
}
std::string str::int2strhexa(int i)
{
char buf[100];
sprintf(buf, "%x", i);
return std::string(buf);
}
std::string str::int2str_capacity(uint64_t val, bool truncate)
{
if(val < 1024)
{
return str::int2str(val) + " bytes";
}
else if(val < 1024*1024)
{
if(((val & 1023) == 0) || truncate)
return str::int2str(val >> 10) + " kbi";
else
return str::int2str(val) + " bytes";
}
if(((val & (1024*1024-1)) == 0) || truncate)
{
return str::int2str(val >> 20) + " mbi";
}
else if(((val & 1023) == 0) || truncate)
{
return str::int2str(val >> 10) + " kbi";
}
else
{
return str::int2str(val) + " bytes";
}
}
std::string str::int2str(int i, int nb_digits)
{
char buf[100];
char format[100];
sprintf(format, "%%%dd", nb_digits);
sprintf(buf, format, i);
return std::string(buf);
}
std::string str::int2str(int i)
{
char buf[100];
sprintf(buf, "%d", i);
return std::string(buf);
}
int files::save_txt_file(std::string filename, std::string content)
{
FILE *f = fopen(filename.c_str(), "wt");
if(f == nullptr)
{
# ifndef WIN
perror("fopen error.\n");
# endif
printf("Fatal error: Cannot open %s for writing.\n", filename.c_str());
fflush(0);
return -1;
}
fprintf(f, "%s", content.c_str());
fclose(f);
return 0;
}
std::string get_current_date_time()
{
time_t tim;
time(&tim);
std::string res = std::string(ctime(&tim));
if(res[res.size() - 1] == '\n')
res = res.substr(0, res.size() - 1);
return res;
}
string str::to_latex(const string s)
{
string res = "";
for(uint32_t i = 0; i < s.size(); i++)
{
if(s[i] == '%')
{
res += "\\%";
}
else
{
char c[2];
c[0] = s[i];
c[1] = 0;
res += string(&c[0]);
}
}
return res;
}
std::string str::str_to_file(std::string name)
{
std::string tmp = str::lowercase(name);
const char *s = tmp.c_str();
char *buf = (char *) malloc(strlen(s)*2+2);
unsigned int i, j = 0;
for(i = 0; i < strlen(s); i++)
{
char c = s[i];
if((c == ' ') || (c == '-') || (c == '_'))
{
c = '-';
}
buf[j++] = c;
}
buf[j] = 0;
tmp = std::string(buf);
free(buf);
return tmp;
}
std::string str::str_to_class(std::string name)
{
std::string tmp = str::lowercase(name);
const char *s = tmp.c_str();
char *buf = (char *) malloc(strlen(s)*2+2);
unsigned int i, j = 0;
bool next_maj = true;
for(i = 0; i < strlen(s); i++)
{
char c = s[i];
if((c == ' ') || (c == '-') || (c == '_'))
{
next_maj = true;
continue;
}
if(next_maj)
{
next_maj = false;
if((c >= 'a') && (c <= 'z'))
c = c + ('A' - 'a');
}
buf[j++] = c;
}
buf[j] = 0;
tmp = std::string(buf);
free(buf);
return tmp;
}
std::string str::str_to_var(std::string name)
{
if((name.size() > 0) && (name[0] >= '0') && (name[0] <= '9'))
name = "_" + name;
std::string tmp = str::lowercase(name);
const char *s = tmp.c_str();
char buf[500];
unsigned int i;
for(i = 0; i < strlen(s); i++)
{
char c = s[i];
if(c == ' ')
c = '_';
if(c == '-')
c = '_';
buf[i] = c;
}
buf[i] = 0;
return std::string(buf);
}
std::string str::str_to_cst(std::string s)
{
std::string buf = s;
unsigned int i;
for(i = 0; i < s.size(); i++)
{
char c = s[i];
if((c >= 'a') && (c <= 'z'))
c = c - 'a' + 'A';
if(c == '+')
c = 'P';
if(c == '/')
c = 'N';
/* Forbid every special character except '_' */
if(((c < 'A') || (c > 'Z')) && (!str::is_deci(c)))
c = '_';
buf[i] = c;
}
return buf;
}
bool files::dir_exists(string name)
{
//char *myDir = dirname(myPath);
struct stat my_stat;
if ((stat(name.c_str(), &my_stat) == 0) && (((my_stat.st_mode) & S_IFMT) == S_IFDIR))
{
return true;
}
return false;
//return file_exists(name);
}
bool files::file_exists(std::string name)
{
FILE *f = fopen(name.c_str(), "r");
if(f == nullptr)
return false;
fclose(f);
return true;
}
std::string get_current_user_doc_path()
{
# ifdef WIN
TCHAR tmp[MAX_PATH]={0};
if(S_OK == ::SHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, 0, tmp))
{
std::ostringstream tmp2;
tmp2 << tmp;
return tmp2.str() + PATH_SEP + appdata.nom_projet;
}
return "";
# else
std::string s = "";
{
char *temp = getenv("HOME");
if(temp == nullptr)
{
perror("getenv");
return s;
}
return std::string(temp) + "/" + appdata.nom_projet;
}
# endif
}
std::string get_current_user_path()
{
# ifdef WIN
TCHAR tmp[MAX_PATH]={0};
if(S_OK == ::SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, tmp))
{
std::ostringstream tmp2;
tmp2 << tmp;
return tmp2.str() + PATH_SEP + appdata.nom_projet;
}
return "";
# else
std::string s = "";
{
char *temp = getenv("HOME");
if(temp == nullptr)
{
perror("getenv");
return s;
}
return std::string(temp) + "/." + appdata.nom_projet;
}
# endif
}
std::string get_all_user_path()
{
# ifdef WIN
TCHAR tmp[MAX_PATH]={0};
if(S_OK == ::SHGetFolderPath(nullptr, CSIDL_COMMON_APPDATA, nullptr, 0, tmp))
{
std::ostringstream tmp2;
tmp2 << tmp;
return tmp2.str() + PATH_SEP + appdata.nom_appli;
}
return "";
# else
// TODO
return "";
# endif
}
std::string get_env_variable(const std::string &name,
const std::string &default_value)
{
# ifdef WIN
char bf[500];
#ifdef VSTUDIO
WCHAR bf2[500];
GetEnvironmentVariable((LPCWSTR) name.c_str(), bf2, 500);
wcstombs(bf, bf2, 250);
#else
GetEnvironmentVariable(name.c_str(), bf, 500);
#endif
return std::string(bf);
# else
char *res = getenv(name.c_str());
if((res == nullptr) || (strlen(res) == 0))
return default_value;
return std::string(res);
# endif
}
int files::check_and_build_directory(std::string path)
{
if(!files::file_exists(path))
{
avertissement("%s: output path [%s] does not exist.", __func__, path.c_str());
if(files::creation_dossier(path))
{
erreur("Failed to create output path.");
return -1;
}
}
return 0;
}
int files::explore_dossier(std::string chemin, std::vector<std::string> &fichiers)
{
# ifdef WIN
DIR *dir;
struct dirent *ent;
if((dir = opendir(chemin.c_str())) == NULL)
{
fprintf(stderr, "Chemin non trouve : [%s].\n", chemin.c_str());
return -1;
}
while ((ent = readdir (dir)) != NULL)
{
std::string f = std::string(ent->d_name);
if(f.size() > 4)
fichiers.push_back(chemin + '/' + f);
}
closedir (dir);
return 0;
# else
return -1;
# endif
}
int files::creation_dossier(std::string path)
{
# ifdef WIN
# ifdef VSTUDIO
CreateDirectory((LPCWSTR) path.c_str(), nullptr);
return 0;
#else
CreateDirectory(path.c_str(), nullptr);
return 0;
#endif
# else
int res = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
return res;
# endif
}
string str::get_filename_resume(const string &filename, unsigned int max_chars)
{
if(filename.size() < max_chars)
return filename;
int i;
unsigned int count = 0;
for(i = filename.size() - 1; i > 0; i--)
{
if((filename[i] == '/') || (filename[i] == '\\'))
{
count++;
if(count == 3)
break;
}
}
if(i > 3)
return filename.substr(0, 3) + "..." + filename.substr(i, filename.size() - i);
return filename;
}
string files::get_extension(const string &filepath)
{
unsigned int i, n = filepath.size();
for(i = 0; i < n; i++)
{
if(filepath[n-i-1] == '.')
break;
}
/* no extension? */
if((i == n) || (i == 0))
return "";
return filepath.substr(n - i, i);
}
string files::remove_extension(const string &filepath)
{
unsigned int i, n = filepath.size();
for(i = 0; i < n; i++)
{
if(filepath[n-i-1] == '.')
break;
}
/* no extension? */
if(i == 0)
return filepath;
return filepath.substr(0, n - i - 1);
}
int files::parse_filepath(const std::string &path,
std::vector<std::string> &items)
{
//string sep = files::get_path_separator();
items.clear();
string accu = "";
for(unsigned int i = 0; i < path.size(); i++)
{
if((path[i] == '/') || (path[i] == '\\'))
{
items.push_back(accu);
accu = "";
}
else
{
string s = " ";
s[0] = path[i];
accu += s;
}
}
if(accu.size() > 0)
items.push_back(accu);
return 0;
}
int files::abs2rel(const std::string &ref,
const std::string &abs,
std::string &result)
{
unsigned int i, ncommon;
vector<string> vref, vabs;
parse_filepath(abs, vabs);
parse_filepath(ref, vref);
printf("vabs = ");
for(i = 0; i < vabs.size(); i++)
printf("[%s] ", vabs[i].c_str());
printf("\nvref = ");
for(i = 0; i < vref.size(); i++)
printf("[%s] ", vref[i].c_str());
printf("\n");
for(i = 0; (i < vabs.size()) && (i < vref.size()); i++)
{
# ifdef WIN
if(str::lowercase(vref[i]).compare(str::lowercase(vabs[i])) != 0)
# else
if(vref[i].compare(vabs[i]) != 0)
# endif
break;
}
ncommon = i;
// ncommon = index of the first different item.
result = "";
for(i = ncommon; i < vref.size(); i++)
{
if(i > ncommon)
result += PATH_SEP;
result += "..";
}
// Target path is inside the reference path
if(ncommon == vref.size())
result += ".";
for(i = ncommon; i < vabs.size(); i++)
result += PATH_SEP + vabs[i];
return 0;
}
void files::remplacement_motif(std::string &chemin)
{
if(chemin.substr(0, 5) == "$DATA")
{
chemin = utils::get_fixed_data_path() + chemin.substr(5, chemin.size() - 5);
}
}
int files::rel2abs(const std::string &ref,
const std::string &rel,
std::string &result)
{
/* Not a relative path ? */
if(rel[0] != '.')
result = rel;
else
{
char psep = get_path_separator()[0];
string r = rel;
if((rel.size() == 1) && (rel[0] == '.'))
r = "";
// Supprime le "./" de "./*"
if((r.size() >= 2) && (r[0] == '.') && (r[1] == psep))
r = r.substr(2, r.size() - 2);
result = ref + PATH_SEP + r;
}
//result = build_absolute_path(ref, rel);
return 0;
}
std::string files::build_absolute_path(const std::string absolute_origin,
const std::string relative_path)
{
std::string res, abs_path, abs_fn, rel;
char psep = get_path_separator()[0];
if(relative_path[0] != '.')
{
return relative_path;
}
//printf("Building absolute path from '%s' and '%s'...\n",
// absolute_origin.c_str(),
// relative_path.c_str());
split_path_and_filename(absolute_origin, abs_path, abs_fn);
abs_path = files::correct_path_separators(abs_path);
rel = files::correct_path_separators(relative_path);
//printf("Absolute root path = '%s'.\n", abs_path.c_str());
// Supprime le "." de "."
if((rel.size() == 1) && (rel[0] == '.'))
rel = "";
// Supprime le "./" de "./*"
if((rel.size() >= 2) && (rel[0] == '.') && (rel[1] == psep))
rel = rel.substr(2, rel.size() - 2);
res = abs_path + get_path_separator() + rel;
//printf("Result = %s.\n", res.c_str());
return res;
}
std::string files::get_path_separator()
{
# ifdef WIN
return "\\";
# else
return "/";
# endif
}
std::string files::correct_path_separators(std::string s_)
{
//s_ = replace_template(s_);
const char *s = s_.c_str();
char buffer[1000];
unsigned int j = 0;
for(unsigned int i = 0; i < strlen(s); i++)
{
if((s[i] == '/') || (s[i] == '\\'))
buffer[j++] = get_path_separator()[0];
else
buffer[j++] = s[i];
}
buffer[j] = 0;
return std::string(buffer);
}
void files::split_path_and_filename(const std::string complete_filename,
std::string &path,
std::string &filename)
{
const char *s = complete_filename.c_str();
unsigned int n = strlen(s);
unsigned int i, j;
j = 0;
for(i = 0; i < n; i++)
{
if((s[i] == '/') || (s[i] == '\\'))
j = i+1;
}
char buf[500];
for(i = 0; i < j; i++)
buf[i] = s[i];
buf[j] = 0;
// Remove last '/' or '\'
if(j > 0)
buf[j-1] = 0;
path = std::string(buf);
char buf2[500];
for(i = j; i < n; i++)
buf2[i-j] = s[i];
buf2[n-j] = 0;
filename = std::string(buf2);
}
void files::delete_file(std::string name)
{
# ifdef WIN
::DeleteFile((LPTSTR) name.c_str());
# else
if(unlink(name.c_str()) != 0)
perror("unlink");
# endif
/*_chmod(nf, _S_IWRITE);
if (DeleteFile((LPTSTR)nf) == 0)
{
}*/
}
std::string str::lowercase(std::string s)
{
char buf[1000];
unsigned int i;
if(s.size() == 0)
return "";
sprintf(buf, "%s", s.c_str());
for(i = 0; i < s.size(); i++)
{
if((buf[i] >= 'A') && (buf[i] <= 'Z'))
buf[i] = 'a' + (buf[i] - 'A');
}
buf[i] = 0;
//TraceManager::infos(TraceManager::TRACE_LEVEL_MAJOR, "util", "lowercase: in = %s -> %s", s.c_str(), buf);
return std::string(buf);
}
TextMatrix::TextMatrix(uint32_t ncols)
{
this->ncols = ncols;
}
void TextMatrix::add(std::string s)
{
current_row.push_back(s);
}
void TextMatrix::add_unformatted_line(std::string s)
{
next_line();
current_row.push_back(s);
lst.push_back(current_row);
unformatted.push_back(true);
current_row.clear();
}
void TextMatrix::next_line()
{
if(current_row.size() > 0)
{
lst.push_back(current_row);
unformatted.push_back(false);
current_row.clear();
}
}
static unsigned int str_screen_len(const string &s)
{
unsigned int i, res = 0, n = s.size();
for(i = 0; i < n; i++)
{
if(((unsigned char) s[i]) == 0x1b)
{
i++;
while((i < n) && (s[i] != 'm'))
i++;
}
else
res++;
}
return res;
}
std::string TextMatrix::get_result()
{
unsigned int i, j, k, n = lst.size();
std::vector<uint32_t> max_size;
std::string res = "";
next_line();
max_size.clear();
for(i = 0; i < ncols; i++)
max_size.push_back(0);
for(i = 0; i < n; i++)
{
if(unformatted[i])
continue;
if(lst[i].size() > max_size.size())
{
uint32_t diff = lst[i].size() - max_size.size();
for(j = 0; j < diff; j++)
max_size.push_back(0);
}
if(lst[i].size() > 1)
{
for(j = 0; j < lst[i].size(); j++)
{
uint32_t len = str_screen_len(lst[i][j]);
if(len > max_size[j])
max_size[j] = len;
}
}
}
for(i = 0; i < n; i++)
{
if(unformatted[i])
{
res += lst[i][0];
continue;
}
for(j = 0; j < lst[i].size(); j++)
{
std::string cell = lst[i][j];
res += cell;
if(j + 1 < lst[i].size())
{
for(k = 0; k < (max_size[j] - str_screen_len(cell)) + 1; k++)
res += " ";
}
}
res += "\n";
}
current_row.clear();
lst.clear();
unformatted.clear();
return res;
}
void TextMatrix::reset(uint32_t ncols)
{
this->ncols = ncols;
current_row.clear();
lst.clear();
}
TextAlign::TextAlign()
{
}
void TextAlign::add(std::string s1, std::string s2)
{
alst1.push_back(s1);
alst2.push_back(s2);
}
void TextAlign::add(std::string s1, std::string s2, std::string s3)
{
alst1.push_back(s1);
alst2.push_back(s2);
alst3.push_back(s3);
}
void TextAlign::add(std::string comment)
{
comments.push_back(comment);
comments_pos.push_back(alst1.size());
}
std::string TextAlign::get_result()
{
int ncols = 2;
if(alst3.size() == alst1.size())
ncols = 3;
unsigned int i, j, n = alst1.size();
unsigned int max_size = 0, max_size2 = 0;
for(i = 0; i < n; i++)
{
unsigned int len1 = alst1[i].size();
if(len1 > max_size)
max_size = len1;
unsigned int len2 = alst2[i].size();
if(len2 > max_size2)
max_size2 = len2;
}
std::string res = "";
unsigned int k = 0;
for(i = 0; i < n; i++)
{
if((k < comments.size()) && (i == comments_pos[k]))
res += comments[k++];
res += alst1[i];
for(j = 0; j < (max_size - alst1[i].size()) + 2; j++)
res += " ";
res += alst2[i];
if(ncols == 3)
{
for(j = 0; j < (max_size2 - alst2[i].size()) + 2; j++)
res += " ";
res += alst3[i];
}
res += "\n";
}
if((k < comments.size()) && (i == comments_pos[k]))
res += comments[k++];
comments.clear();
comments_pos.clear();
alst1.clear();
alst2.clear();
alst3.clear();
return res;
}
void Section::load(std::string nom_fichier)
{
MXml mx;
if(mx.from_file(nom_fichier))
{
erreur("Impossible de charger le fichier de loc (%s).", nom_fichier.c_str());
return;
}
load(mx);
}
void Section::load()
{
load("lang.xml");
}
Section::Section()
{
}
void Section::operator =(const Section &c)
{
nom = c.nom;
elmts = c.elmts;
subs = c.subs;
//data = c.data;
//this->current_language = c.current_language;
}
Section::Section(const Section &c)
{
*this = c;
}
static unsigned char utf8_to_latin_char(unsigned char a, unsigned char b)
{
if(a == 0xc3)
{
return b + 0x40;
}
else if(a == 0xc2)
{
return b;
}
return ' ';
}
std::string str::utf8_to_latin(std::string s_)
{
unsigned char *buf = (unsigned char *) malloc(s_.size() + 1);//[2000];
const unsigned char *s = (const unsigned char *) s_.c_str();
int j = 0;
unsigned int n = strlen((const char *)s);
for(unsigned int i = 0; i < n; i++)
{
if((s[i] == 0xc3) || (s[i] == 0xc2))
{
buf[j++] = utf8_to_latin_char(s[i], s[i+1]);
i++;
}
else
{
buf[j++] = s[i];
}
}
buf[j] = 0;
std::string res = std::string((char *) buf);
free(buf);
return res;
}
std::string str::latin_to_utf8(std::string s)
{
// Unsigned char cast, otherwise faile to compare with hexadecimal values.
const unsigned char *s2 = (const unsigned char *) s.c_str();
unsigned char *buf = (unsigned char *) malloc(s.size() * 2 + 1);
unsigned int j = 0, n = s.size();
for(unsigned int i = 0; i < n; i++)
{
/** Already UTF8? Skip. */
if((s2[i] == 0xc2) || (s2[i] == 0xc3))
{
buf[j++] = s2[i++];
buf[j++] = s2[i];
}
else if((s2[i] >= 0x80) && (s2[i] <= 0xbf))
{
buf[j++] = 0xc2;
buf[j++] = s2[i];
}
else if(s2[i] >= 0xc0)
{
buf[j++] = 0xc3;
buf[j++] = s2[i] - 0x40;
}
else
buf[j++] = s2[i];
}
buf[j] = 0;
std::string res = std::string((char *) buf);
free(buf);
return res;
}
bool Section::has_item(const std::string &name) const
{
//return data.has_child("item", "name", name);
for(const auto &e: elmts)
if(e.get_id() == name)
return true;
return false;
}
const utils::model::Localized &Section::get_localized(const std::string &name) const
{
for(const auto &e: elmts)
if(e.get_id() == name)
return e;
erreur("Item de localisation non trouve: %s", name.c_str());
return elmts[0];
}
std::string Section::get_item(const std::string &name) const
{
for(const auto &e: elmts)
if(e.get_id() == name)
return e.get_localized();
erreur("Item de localisation non trouvé : %s (dans section [%s]).",
name.c_str(), this->nom.c_str());
return name + "=?";
}
/*const char *Section::get_text(std::string name)
{*/
/*if((data == nullptr) || (data == 0))
return name.c_str();*/
/* if(!data.has_child("item", "name", name))
{
printf("Item not found: %s\n", name.c_str());
return name.c_str();
}
MXml elt = data.get_child("item", "name", name);
return elt.get_attribute(this->current_language).string_value.c_str();
}*/
const Section &Section::get_section(const std::string &name) const
{
for(const auto &s: subs)
if(s->nom == name)
return *s;
erreur("Sous section non trouvee : %s", name.c_str());
return *this;
}
Section &Section::get_section(const std::string &name)
{
for(auto &s: subs)
if(s->nom == name)
return *s;
erreur("Sous section non trouvee : %s", name.c_str());
return *this;
}
Section::~Section()
{
//printf("delete section.\n");
}
void Section::load(const utils::model::MXml &mx)
{
this->nom = mx.get_attribute("name").to_string();
for(auto &ch: mx.children)
{
if(ch.name == "include")
{
load(utils::get_fixed_data_path() + PATH_SEP + ch.get_attribute("file").to_string());
}
else if(ch.name == "item")
{
elmts.push_back(utils::model::Localized(ch));
}
else if(ch.name == "section")
{
Section *sec = new Section(ch);
subs.push_back(utils::refptr<Section>(sec));
}
}
}
Section::Section(const MXml &mx)
{
load(mx);
}
uint32_t Util::extract_bits(uint8_t *buffer, uint32_t offset_in_bits, uint32_t nbits)
{
uint32_t res = 0;
buffer += offset_in_bits / 8;
offset_in_bits &= 7;
/*************************************************************
* Hypoth�se :
*
* Si mot de 12 bits, d�cal� de 1 bit.
*
*
* [7 6 0] [7 5 4 0] [7 0]
* [11 0]
*
*************************************************************/
while(nbits > 0)
{
// Extract n bits from the first byte in the buffer
// n = max(nbits, 8 - offset)
uint16_t n = nbits;
if(n > 8 - offset_in_bits)
n = 8 - offset_in_bits;
//uint32_t extract = (((uint32_t) buffer[0]) << offset_in_bits) & 0xff;
uint32_t extract = ((uint32_t) buffer[0]) & (0x000000ff >> offset_in_bits);
// Append to result
res = (res << 8) | extract;
nbits -= n;
buffer++;
offset_in_bits = 0;
}
return res;
}
CmdeLine::CmdeLine()
{
}
void CmdeLine::operator =(const CmdeLine &cmdeline)
{
this->argv0 = cmdeline.argv0;
this->prms = cmdeline.prms;
}
CmdeLine::CmdeLine(const std::string args)
{
vector<string> lst;
string s;
istringstream is(args);
while(is >> s)
lst.push_back(s);
init(lst);
}
void CmdeLine::init(vector<string> &argv)
{
if(argv.size() > 0)
argv0 = std::string(argv[0]);
for(unsigned int i = 1; i < argv.size(); i++)
{
string opt = argv[i];
if(opt[0] == '-')
{
CmdeLinePrm prm;
prm.option = opt;
if(i + 1 < argv.size())
{
string val = argv[i + 1];
if(val[0] != '-')
{
prm.value = val;
i++;
}
}
prms.push_back(prm);
}
else
{
CmdeLinePrm prm;
prm.option = opt;
prms.push_back(prm);
}
}
}
void CmdeLine::init(int argc, const char **argv)
{
vector<string> lst;
for(unsigned int i = 0; i < (unsigned int) argc; i++)
lst.push_back(string(argv[i]));
init(lst);
}
CmdeLine::CmdeLine(int argc_, char **argv_)//: argc(argc_), argv((const char **) argv_)
{
init(argc_, (const char **) argv_);
}
CmdeLine::CmdeLine(int argc_, const char **argv)//: argc(argc_)
{
init(argc_, (const char **) argv);
}
bool CmdeLine::has_option(const std::string &name) const
{
for(unsigned int i = 0; i < prms.size(); i++)
{
if(prms[i].option.compare(name) == 0)
return true;
}
return false;
}
/*bool CmdeLine::get_boolean_option(const std::string &name,
bool default_value)
{
}*/
int CmdeLine::get_int_option(const std::string &name,
int default_value) const
{
std::string res = get_option(name, str::int2str(default_value));
return atoi(res.c_str());
}
std::string CmdeLine::get_option(const std::string &name,
const std::string &default_value) const
{
for(unsigned int i = 0; i < prms.size(); i++)
{
if(prms[i].option.compare(name) == 0)
{
if(prms[i].value.size() == 0)
return default_value;
return prms[i].value;
}
}
return default_value;
}
void CmdeLine::set_option(const std::string &name, const std::string &value)
{
for(unsigned int i = 0; i < prms.size(); i++)
{
if(prms[i].option.compare(name) == 0)
{
prms[i].value = value;
return;
}
}
CmdeLinePrm prm;
prm.option = name;
prm.value = value;
prms.push_back(prm);
}
namespace model
{
Localized::Localized()
{
}
Localized::Localized(const Localized &l)
{
*(this) = l;
}
void Localized::operator =(const Localized &l)
{
items = l.items;
descriptions = l.descriptions;
id = l.id;
}
void Localized::set_value(Language lg, std::string value)
{
if(value.size() == 0)
return;
if(lg == Localized::LANG_ID)
id = value;
for(unsigned int i = 0; i < items.size(); i++)
{
if(items[i].first == lg)
{
items[i].second = value;
return;
}
}
std::pair<Language, std::string> item;
item.first = lg;
item.second = value;
items.push_back(item);
}
std::string Localized::to_string() const
{
unsigned int i;
std::string s = "";
for(i = 0; i < items.size(); i++)
{
s += "name[" + str::int2str((int) items[i].first) + "] = " + items[i].second + "\n";
}
for(i = 0; i < descriptions.size(); i++)
{
s += "desc[" + str::int2str((int) descriptions[i].first) + "] = " + descriptions[i].second + "\n";
}
return s;
}
void Localized::set_description(Language lg, std::string desc)
{
if(desc.size() == 0)
return;
for(unsigned int i = 0; i < descriptions.size(); i++)
{
if(descriptions[i].first == lg)
{
descriptions[i].second = desc;
return;
}
}
std::pair<Language, std::string> item;
item.first = lg;
item.second = desc;
descriptions.push_back(item);
}
std::string Localized::get_value(Language lg) const
{
std::string default_value = "";
if(items.size() > 0)
default_value = items[0].second;
for(unsigned int i = 0; i < items.size(); i++)
{
if(items[i].first == lg)
{
return items[i].second;
}
if(items[i].first == LANG_EN)
default_value = items[i].second;
}
//auto l = Localized::language_id(lg);
//avertissement("Item loc non trouve : [%s], en langue [%s].", this->id.c_str(), l.c_str());
return default_value;
}
/** @brief Equivalent to get_value(LANG_CURRENT) */
std::string Localized::get_localized() const
{
return get_value(current_language);
}
/*std::string Localized::get_id() const
{
return id;//get_value(Localized::LANG_ID);
}*/
/** @brief Get the HTML description in the specified language */
std::string Localized::get_description(Language lg) const
{
std::string default_value = "";
if(lg == LANG_CURRENT)
lg = current_language;
if(descriptions.size() > 0)
default_value = descriptions[0].second;
for(unsigned int i = 0; i < descriptions.size(); i++)
{
if(descriptions[i].first == lg)
{
return descriptions[i].second;
}
if(descriptions[i].first == LANG_EN)
default_value = descriptions[i].second;
}
return default_value;
}
bool Localized::has_description() const
{
std::string s = get_description(LANG_CURRENT);
return (s.size() > 0);
}
std::vector<Localized::Language> Localized::language_list()
{
std::vector<Localized::Language> res;
for(auto i = 0u; i < NLANG; i++)
res.push_back((Localized::Language) (i + (int) Localized::LANG_FR));
return res;
}
std::string Localized::language_id(Localized::Language l)
{
int i = ((int) l) - (int) LANG_FR;
if(i >= NLANG)
return "?";
return lglist[i];
}
Localized::Language Localized::parse_language(std::string id)
{
for(auto i = 0; i < NLANG; i++)
if(id.compare(lglist[i]) == 0)
return (Localized::Language) (((int) LANG_FR) + i);
return LANG_UNKNOWN;
}
Localized::Localized(const MXml &mx)
{
if(mx.has_attribute("name"))
set_value(LANG_ID, mx.get_attribute("name").to_string());
else if(mx.has_attribute("type"))
set_value(LANG_ID, mx.get_attribute("type").to_string());
for(auto i = 0; i < NLANG; i++)
{
if(mx.has_attribute(lglist[i])) // e.g. fr, en, etc.
set_value((Language) ((int)LANG_FR + i),
mx.get_attribute(lglist[i]).to_string());
}
/*if(mx.has_attribute("fr"))
set_value(LANG_FR, mx.get_attribute("fr").to_string());
if(mx.has_attribute("en"))
set_value(LANG_EN, mx.get_attribute("en").to_string());*/
std::vector<MXml> lst = mx.get_children("description");
for(unsigned int i = 0; i < lst.size(); i++)
{
std::string contents = lst[i].dump_content();
if(lst[i].has_attribute("lang"))
{
set_description(parse_language(lst[i].get_attribute("lang").to_string()),
contents);
}
else
{
set_description(LANG_FR, contents);
}
}
}
}
TestUtil::TestUtil(const CmdeLine &cmdeline)
{
this->cmdeline = cmdeline;
}
TestUtil::TestUtil(const string &module, const string &prg, int argc, const char **argv):
cmdeline(argc, argv)
{
utils::init(cmdeline, module, prg);
}
int TestUtil::add_test(const string &name, int (*test_routine)())
{
TestUnit tu;
tu.name = name;
tu.test_routine = test_routine;
tu.test = nullptr;
units.push_back(tu);
return 0;
}
int TestUtil::add_test(const std::string &name, Test *test)
{
TestUnit tu;
tu.name = name;
tu.test_routine = nullptr;
tu.test = test;
units.push_back(tu);
return 0;
}
int TestUtil::check_value(float v, float ref, float precision, const std::string &refname)
{
// TODO: not true
if((ref < 0.000001) && (v < 0.000001))
return 0;
if(((ref == 0.0) || (ref == -0.0)) && (v == 0.0))
return 0;
float err = 100.0 * std::abs((v - ref) / ref);
if(err > precision)
{
erreur("%s: too much error. Value = %f, reference = %f, relative error = %f %%, max relative error = %f %%.", refname.c_str(), v, ref, err, precision);
return -1;
}
return 0;
}
int TestUtil::proceed()
{
int res = 0;
if(cmdeline.has_option("--help") || cmdeline.has_option("--usage"))
{
cout << "Usage for " << appdata.nom_projet << "/" << appdata.nom_appli << ":" << endl;
for(uint32_t i = 0; i < units.size(); i++)
{
cout << "-t " << (i+1) << ": \033[1m" << units[i].name << "\033[0m..." << endl;
}
return 0;
}
cout << "Proceeding tests of " << appdata.nom_projet << "/" << appdata.nom_appli << endl;
float t0 = hal::get_tick_count_us();
for(uint32_t i = 0; i < units.size(); i++)
{
if(cmdeline.has_option("-t"))
{
if(cmdeline.get_int_option("-t", 1) != (int) (i + 1))
continue;
}
cout << "-------------------------------\n";
cout << "Test[" << (i+1) << "/" << units.size() << "] \033[1m" << units[i].name << "\033[0m..." << endl;
float t00 = hal::get_tick_count_us();
int test_result;
if(units[i].test == nullptr)
test_result = units[i].test_routine();
else
test_result = units[i].test->proceed();
float t01 = hal::get_tick_count_us();
printf(" ... done, duration = %.2f ms.\n", (t01 - t00) / 1000.0);
if(test_result)
{
cerr << "Test[" << (i+1) << "/" << units.size() << "] \"" << units[i].name << "\": failed." << endl;
cerr << "Test process aborted." << endl;
break;
}
}
cout << "All tests done." << endl;
float t1 = hal::get_tick_count_us();
printf("\nDuration of the whole tests: %.2f ms.\n", (t1 - t0) / 1000.0);
uint32_t nb_warnings = journal::get_warning_count();
uint32_t nb_anomalies = journal::get_anomaly_count();
cout << nb_warnings << " warning(s), " << nb_anomalies << " anomalie(s)." << endl;
if(nb_anomalies > 0)
res = -1;
return res;
}
}
| 47,839
|
C++
|
.cc
| 1,948
| 20.761294
| 227
| 0.572371
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,949
|
mxml.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mxml.cc
|
#include "mxml.hpp"
#include "cutil.hpp"
#include "pugixml.hpp"
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
namespace utils
{
namespace model
{
using namespace utils;
static void load_from_pugi_node(MXml &mx, pugi::xml_node node);
XmlAttribute::XmlAttribute(const XmlAttribute &a)
{
*this = a;
}
XmlAttribute &XmlAttribute::operator =(const XmlAttribute &a)
{
name = a.name;
string_value = a.string_value;
return *this;
}
MXml::MXml()
{
name = "?";
}
MXml::MXml(const MXml &mx)
{
*this = mx;
}
MXml &MXml::operator =(const MXml &mx)
{
name = mx.name;
attributes = mx.attributes;
children = mx.children;
text = mx.text;
order = mx.order;
return *this;
}
std::string MXml::get_name() const
{
return name;
}
bool MXml::has_child(std::string balise_name,
std::string att_name,
std::string att_value) const
{
for(auto &child: children)
if((child.name == balise_name)
&& (child.has_attribute(att_name))
&& (child.get_attribute(att_name).string_value == att_value))
return true;
return false;
}
MXml MXml::get_child(std::string balise_name,
std::string att_name,
std::string att_value)
{
for(auto &child: children)
if((child.name == balise_name)
&& (child.get_attribute(att_name).string_value == att_value))
return child;
erreur("XML child not found: %s in %s where %s = %s.",
balise_name.c_str(), name.c_str(),
att_name.c_str(), att_value.c_str());
return MXml();
}
bool MXml::has_child(std::string name) const
{
for(auto &ch: children)
if(ch.name == name)
return true;
return false;
}
MXml MXml::get_child(std::string name) const
{
for(auto &ch: children)
if(ch.name == name)
return ch;
erreur("Child not found: %s in %s.",
name.c_str(), this->name.c_str());
return MXml();
}
void MXml::get_children(std::string name,
std::vector<const MXml *> &res) const
{
for(auto &ch: children)
{
if(ch.name == name)
res.push_back(&ch);
}
}
std::vector<MXml> MXml::get_children(std::string name) const
{
std::vector<MXml> res;
for(auto &ch: children)
{
if(ch.name == name)
res.push_back(ch);
}
return res;
}
bool MXml::has_attribute(std::string name) const
{
for(auto &att: attributes)
if(att.name == name)
return true;
return false;
}
XmlAttribute MXml::get_attribute(std::string name) const
{
for(auto &att: attributes)
if(att.name == name)
return att;
erreur("getAttribute(%s): attribute not found in %s.",
name.c_str(), this->name.c_str());
return XmlAttribute();
}
MXml::MXml(std::string name, std::vector<XmlAttribute> *attributes, std::vector<MXml> *children)
{
this->name = name;
this->attributes = *attributes;
delete attributes;
this->children = *children;
delete children;
}
static void load_from_pugi_node(MXml &mx, pugi::xml_node node)
{
mx.name = node.name();
for(auto att: node.attributes())
{
XmlAttribute xatt;
xatt.name = att.name();
xatt.string_value = att.value();
mx.attributes.push_back(xatt);
}
for(auto ch: node.children())
{
auto type = ch.type();
if(type == pugi::xml_node_type::node_pcdata)
{
mx.add_text(ch.text().get());
}
else if((type == pugi::xml_node_type::node_element)
|| (type == pugi::xml_node_type::node_element))
{
MXml child;
load_from_pugi_node(child, ch);
mx.add_child(child);
}
}
}
int MXml::from_file(std::string filename)
{
pugi::xml_document doc;
auto result = doc.load_file(filename.c_str());
if(result.status != pugi::xml_parse_status::status_ok)
{
erreur("Error occurred while parsing [%s]: %s.",
filename.c_str(), result.description());
return -1;
}
auto elt = doc.document_element();
//elt.print(std::cout);
load_from_pugi_node(*this, elt);
return 0;
}
int MXml::from_string(std::string s)
{
pugi::xml_document doc;
auto result = doc.load_buffer(s.c_str(), s.size());
if(result.status != pugi::xml_parse_status::status_ok)
{
erreur("Error occurred while parsing XML string: %s.", result.description());
return -1;
}
auto elt = doc.document_element();
load_from_pugi_node(*this, elt);
return 0;
}
void MXml::add_child(const MXml &mx)
{
order.push_back(true);
children.push_back(mx);
}
void MXml::add_text(std::string s)
{
order.push_back(false);
//this corrupts utf8 if it contains Cyrillic text.
//text.push_back(str::latin_to_utf8(s));
text.push_back(s);
}
std::string MXml::dump_content() const
{
std::string res = "";
int index_el = 0;
int index_tx = 0;
for(unsigned int i = 0; i < order.size(); i++)
{
if(order[i])
res += children[index_el++].dump();
else
res += text[index_tx++];
}
const char *s = res.c_str();
bool only_spaces = true;
for(unsigned int i = 0; i < strlen(s); i++)
{
if(s[i] != ' ')
{
only_spaces = false;
break;
}
}
if(only_spaces)
return "";
return res;
}
std::string MXml::dump() const
{
std::string res = "<" + name;
if((attributes.size() == 0) && (order.size() == 0))
return res + "/>";
for (auto &att: attributes)
res += " " + att.name + "=\"" + att.string_value + "\"";
res += ">";
int index_el = 0;
int index_tx = 0;
for(unsigned int i = 0; i < order.size(); i++)
{
if(order[i])
res += children[index_el++].dump();
else
res += text[index_tx++];
}
res += "</" + name + ">";
return res;
}
XmlAttribute::XmlAttribute()
{
this->string_value = "?";
name = "?";
}
XmlAttribute::XmlAttribute(std::string name, std::string value)
{
this->string_value = str::latin_to_utf8(value);
this->name = name;
}
int XmlAttribute::to_int() const
{
char temp[20];
sprintf(temp, "%s", string_value.c_str());
int val = -1;
sscanf(temp, "%d", &val);
return val;
}
std::string XmlAttribute::to_string() const
{
const char *s = string_value.c_str();
char buf[1000];
unsigned int n = strlen(s);
unsigned int j = 0;
for(unsigned int i = 0; i < n; i++)
{
if((s[i] == '\\') && (i < n - 1) && (s[i+1] == 'G'))
{
buf[j++] = '"';
i++;
}
else
{
buf[j++] = s[i];
}
}
buf[j] = 0;
return std::string(buf);
}
bool XmlAttribute::to_bool() const
{
return string_value == "true";
}
double XmlAttribute::to_double() const
{
char temp[30];
sprintf(temp, "%s", string_value.c_str());
float val = -1;
sscanf(temp, "%f", &val);
return val;
}
void yyerror(const char *s)
{
//printf("Error : %s\n", s);
}
std::string MXml::xml_string_to_ascii(std::string s)
{
char *res = (char *) malloc(s.size()+1);
const char *s2 = s.c_str();
unsigned int di = 0;
for(unsigned int i = 0; i < strlen(s2); i++)
{
if(((i+4) < strlen(s2)) && (s2[i] == '&') && (s2[i+1] == 'a') && (s2[i+2] == 'm') && (s2[i+3] == 'p') && (s2[i+4] == ';'))
{
i += 4;
res[di++] = '&';
}
else if(((i+1) < strlen(s2)) && (s2[i] == '\\') && (s2[i+1] == '\\'))
{
i++;
res[di++] = '\n';
}
else
res[di++] = s2[i];
}
res[di] = 0;
std::string sres = std::string(res);
free(res);
return sres;
}
std::string MXml::ascii_string_to_xml(std::string s)
{
char *res = (char *) malloc(s.size()+100);
const char *s2 = s.c_str();
unsigned int di = 0;
for(unsigned int i = 0; i < strlen(s2); i++)
{
if(s2[i] == '&')
{
res[di++] = '&';
res[di++] = 'a';
res[di++] = 'm';
res[di++] = 'p';
res[di++] = ';';
}
else if(s2[i] == '\n')
{
res[di++] = '\\';
res[di++] = '\\';
}
else
res[di++] = s2[i];
}
res[di] = 0;
std::string sres = std::string(res);
free(res);
return sres;
}
}
}
| 8,030
|
C++
|
.cc
| 350
| 19.025714
| 130
| 0.579929
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,951
|
bytearray.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/bytearray.cc
|
#include "bytearray.hpp"
#ifdef LINUX
#include <cstdio>
#endif
#include <stdio.h>
#include "cutil.hpp"
#include <malloc.h>
#include <string.h>
#include <sys/stat.h>
namespace utils
{
namespace model
{
using namespace utils;
ByteArray::ByteArray(std::string str, bool is_decimal)
{
const char *s = str.c_str();
unsigned char current = 0;
if(!str::is_deci(s[0]))
{
return;
}
while(strlen(s) > 0)
{
if(str::is_deci(s[0]))
{
current = current * 10 + (s[0] - '0');
}
else
{
if(strlen(s) > 1)
{
putc(current);
current = 0;
}
}
s++;
}
putc(current);
}
std::string ByteArray::to_string(bool hexa) const
{
std::string s = "";
if(data.size() == 0)
return "(empty)";
for(unsigned int i = 0; i < data.size(); i++)
{
char buf[10];
if(hexa)
sprintf(buf, "%02x", data[i]);
else
sprintf(buf, "%d", data[i]);
s += std::string(buf);
if(i + 1 < data.size())
s += ".";
/*if((i > 0) && ((i & 15) == 0))
s += std::string("\n");*/
}
return s;
}
/*ByteArray::ByteArray(unsigned char x)
{
putc(x);
}*/
const unsigned char &ByteArray::operator[](unsigned int i) const
{
return data[i];
}
unsigned char &ByteArray::operator[](unsigned int i)
{
return data[i];
}
ByteArray::ByteArray(/*bool bigendian*/)
{
this->bigendian = false;
}
void ByteArray::lis_fichier(FILE *fi, uint32_t n)
{
uint8_t *tmp = (uint8_t *) malloc(n);
fread(tmp, 1, n, fi);
for(auto i = 0u; i < n; i++)
data.push_back(tmp[i]);
free(tmp);
}
static int32_t fsize(std::string filename)
{
struct stat st;
if (stat(filename.c_str(), &st) == 0)
return st.st_size;
return -1;
}
int ByteArray::lis_fichier(const std::string &fn)
{
FILE *fi = fopen(fn.c_str(), "rb");
if(fi == nullptr)
{
erreur("Erreur lors de l'ouverture du fichier [%s] en lecture.", fn.c_str());
return -1;
}
auto lon = fsize(fn);
if(lon < 0)
return -1;
lis_fichier(fi, lon);
fclose(fi);
return 0;
}
int ByteArray::ecris_fichier(const std::string &fn)
{
FILE *fo = fopen(fn.c_str(), "wb");
if(fo == nullptr)
{
erreur("Erreur lors de l'ouverture du fichier [%s] en écriture.", fn.c_str());
return -1;
}
ecris_fichier(fo);
fclose(fo);
return 0;
}
void ByteArray::ecris_fichier(FILE *fo)
{
uint32_t n = data.size();
uint8_t *tmp = (uint8_t *) malloc(n);
auto ptr = data.begin();
for(auto i = 0u; i < n; i++)
tmp[i] = *ptr++;
fwrite(tmp, 1, n, fo);
free(tmp);
}
ByteArray::ByteArray(int len)
{
this->bigendian = false;
data.resize(len);
}
ByteArray::ByteArray(const unsigned char *buffer, unsigned int len, bool bigendian)
{
this->bigendian = bigendian;
put(buffer, len);
}
ByteArray::ByteArray(const ByteArray &ba)
{
*this = ba;
}
void ByteArray::clear()
{
data.clear();
}
bool ByteArray::operator ==(const ByteArray &ba) const
{
return data == ba.data;
}
bool ByteArray::operator !=(const ByteArray &ba) const
{
return data != ba.data;
}
void ByteArray::operator =(const ByteArray &ba)
{
//clear();
data = ba.data;
//for(unsigned int i = 0; i < ba.size(); i++)
// putc(ba.data[i]);
}
ByteArray ByteArray::operator +(const ByteArray &ba) const
{
ByteArray res(*this);
for(unsigned int i = 0; i < ba.size(); i++)
res.putc(ba[i]);
return res;
}
ByteArray ByteArray::operator +(unsigned char c) const
{
ByteArray res(*this);
res.putc(c);
return res;
}
void ByteArray::putc(uint8_t c)
{
data.push_back(c);
}
void ByteArray::putw(uint16_t w)
{
putc((uint8_t) (w & 0xff));
putc((uint8_t) ((w >> 8) & 0xff));
}
void ByteArray::putl(uint32_t l)
{
putw((uint16_t) (l & 0xffff));
putw((uint16_t) ((l >> 16) & 0xffff));
}
void ByteArray::putL(uint64_t l)
{
putl((uint32_t) (l & 0xffffffff));
putl((uint32_t) ((l >> 32) & 0xffffffff));
}
void ByteArray::putf(float f)
{
/*uint32_t *ptr = (uint32_t *) &f;
putl(*ptr);*/
uint32_t ival = *((uint32_t *) &f);
putc(ival & 0xff);
putc((ival >> 8) & 0xff);
putc((ival >> 16) & 0xff);
putc((ival >> 24) & 0xff);
}
float ByteArray::popf()
{
uint32_t val;
float *tmp = (float *) &val;
uint32_t a0, a1, a2, a3;
a0 = popc();
a1 = popc();
a2 = popc();
a3 = popc();
val = (a3 << 24) | (a2 << 16) | (a1 << 8) | a0;
return *tmp;
}
void ByteArray::put(const void *buffer_, unsigned int len)
{
auto buffer = (const unsigned char *) buffer_;
for(unsigned int i = 0; i < len; i++)
putc(buffer[i]);
}
void ByteArray::put(const ByteArray &ba)
{
for(unsigned int i = 0; i < ba.size(); i++)
putc(ba[i]);
}
void ByteArray::puts_zt(std::string s)
{
for(unsigned int i = 0; i < s.size(); i++)
putc(s[i]);
putc(0x00);
}
void ByteArray::puts(std::string s)
{
uint32_t n = s.size();
if(s.size() <= 254)
{
putc(n);
}
else if(s.size() <= 65534)
{
putc(0xff);
putw(n);
}
else
{
putc(0xff);
putc(0xff);
putc(0xff);
putl(n);
}
for(unsigned int i = 0; i < n; i++)
putc(s[i]);
}
uint32_t ByteArray::size() const
{
return data.size();
}
uint8_t ByteArray::popc()
{
if(size() == 0)
{
erreur("ByteArray::popc: size = 0.");
return 0xff;
}
uint8_t res = data[0];
data.erase(data.begin());
return res;
}
std::string ByteArray::pops()
{
if(size() == 0)
return "";
uint32_t i, n0 = popc();
if(n0 == 0xff)
{
n0 = popw();
if(n0 == 0xffff)
{
n0 = popl();
if(n0 == 0xffffffff)
{
erreur("invalid string");
return "";
}
}
}
char *buf = (char *) malloc(n0 + 1);
for(i = 0; i < n0; i++)
{
buf[i] = popc();
}
buf[i] = 0;
std::string res = std::string(buf);
free(buf);
return res;
}
void ByteArray::insert(uint8_t c)
{
std::deque<unsigned char>::iterator it;
it = data.begin();
data.insert(it, c);
}
uint16_t ByteArray::popw()
{
uint16_t l = popc() & 0xff;
uint16_t b = popc() & 0xff;
return ((b << 8) | l);
}
uint32_t ByteArray::popl()
{
uint32_t l = popw() & 0xffff;
uint32_t b = popw() & 0xffff;
return ((b << 16) | l);
}
uint64_t ByteArray::popL()
{
uint64_t l = popl() & 0xffffffff;
uint64_t b = popl() & 0xffffffff;
return ((b << 32) | l);
}
void ByteArray::pop_data(void *buffer_, unsigned int len)
{
unsigned char *buffer = (unsigned char *) buffer_;
if(len > size())
{
erreur("pop_data(%d), size = %d.", len, size());
return;
}
for(unsigned int i = 0; i < len; i++)
{
buffer[i] = popc();
}
}
void ByteArray::pop(ByteArray &ba, uint32_t len)
{
for(uint32_t i = 0; i < len; i++)
ba.putc(popc());
}
}
}
| 6,695
|
C++
|
.cc
| 341
| 16.580645
| 83
| 0.589059
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
753,952
|
hal.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/hal.cc
|
#include "hal.hpp"
#include <stdio.h>
#include <string.h> // for memcpy
#include <unistd.h> // for usleep
#include "../include/journal.hpp"
#if 0
typedef void (*WAITORTIMERCALLBACK)(void *prm, bool TimerOrWaitFired);
WINBASEAPI HANDLE WINAPI CreateTimerQueue(void);
WINBASEAPI void WINAPI DeleteTimerQueue(HANDLE);
WINBASEAPI BOOL WINAPI CreateTimerQueueTimer(PHANDLE,HANDLE,WAITORTIMERCALLBACK,PVOID,DWORD,DWORD,ULONG);
#endif
namespace utils { namespace hal{
void os_thread_start(void *prm)
{
((utils::hal::ThreadFunctor *) prm)->call();
}
uint64_t get_native_tick_counter()
{
# ifdef SDPOS
return arch_counter_get();
# elif defined(WIN)
LARGE_INTEGER tick;
QueryPerformanceCounter(&tick);
return tick.QuadPart;
# else
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
perror("clock_gettime().");
return 0;
}
return (uint64_t) (ts.tv_nsec / 1000) + (((uint64_t) ts.tv_sec) * 1000 * 1000);
# endif
}
uint32_t ticks_to_ms(uint64_t ticks)
{
# ifdef SDPOS
return arch_counter_to_ms(ticks);
# elif defined(WIN)
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
uint32_t result = (uint32_t) (ticks / (frequency.QuadPart / 1000));
return result;
# else
return (uint32_t) ticks / 1000;
# endif
}
uint64_t ticks_to_us(uint64_t ticks)
{
# ifdef SDPOS
return arch_counter_to_us(ticks);
# elif defined(WIN)
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
uint64_t result = ticks / (frequency.QuadPart / (1000 * 1000));
return result;
# else
return ticks;
# endif
}
#if 0
Timer::Timer()
{
functor = nullptr;
# ifdef WIN
this->h_timer_queue = CreateTimerQueue();
# endif
}
Timer::~Timer()
{
# ifdef WIN
::DeleteTimerQueue(h_timer_queue);
# endif
}
static void timer_routine(void *prm, bool TimerOrWaitFired)
{
if(prm == nullptr)
{
log_anomaly(0, "TimerRoutine lpParam is NULL.");
}
else
{
Timer *tim = (Timer *) prm;
tim->signal.raise();
if(tim->functor != nullptr)
tim->functor->call();
}
}
void Timer::start(uint32_t period)
{
if(!::CreateTimerQueueTimer(&h_timer, h_timer_queue,
(WAITORTIMERCALLBACK) timer_routine, &signal, period, 0, 0))
{
log_anomaly(0, "CreateTimerQueueTimer failed");
}
}
#endif
/////////////////////////////////////////////////////
/// Mutex implementation
/////////////////////////////////////////////////////
Mutex::Mutex()
{
# ifdef SDPOS
mutex = new_mutex();
# elif defined(LINUX)
if(pthread_mutex_init(&mutex, nullptr))
{
perror("pthread_mutex_init");
}
# else
::InitializeCriticalSectionAndSpinCount(&critical, 0);
# endif
}
Mutex::~Mutex()
{
# ifdef SDPOS
// TODO
# elif defined(LINUX)
pthread_mutex_destroy(&mutex);
# else
::DeleteCriticalSection(&critical);
# endif
}
void Mutex::lock()
{
# ifdef SDPOS
require(mutex);
# elif defined(LINUX)
pthread_mutex_lock(&mutex);
# else
::EnterCriticalSection(&critical);
# endif
}
void Mutex::unlock()
{
# ifdef SDPOS
release(mutex);
# elif defined(LINUX)
pthread_mutex_unlock(&mutex);
# else
::LeaveCriticalSection(&critical);
# endif
}
/////////////////////////////////////////////////////
/// Signal implementation
/////////////////////////////////////////////////////
Signal::Signal()
{
# ifdef SDPOS
handle = new_signal();
# elif defined(LINUX)
if(pthread_cond_init(&cvar, nullptr))
{
perror("pthread_cond_init");
}
if(pthread_mutex_init(&mutex, nullptr))
{
perror("pthread_mutex_init");
}
cnt = 0;
# else
handle = ::CreateEvent(0,true,false,0);
# endif
}
Signal::~Signal()
{
# ifdef SDPOS
// TODO
# elif defined(LINUX)
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cvar);
# else
::CloseHandle(handle);
# endif
}
#ifdef WIN
HANDLE Signal::get_handle()
{
return handle;
}
#endif
void Signal::raise()
{
# ifdef SDPOS
signal(handle);
# elif defined(LINUX)
pthread_mutex_lock(&mutex);
cnt++;
pthread_cond_signal(&cvar);
pthread_mutex_unlock(&mutex);
# else
::SetEvent(handle);
# endif
}
void Signal::clear()
{
# ifdef SDPOS
signal_clear(handle);
# elif defined(LINUX)
cnt = 0;
# else
::ResetEvent(handle);
# endif
}
void Signal::wait()
{
# ifdef SDPOS
wait(handle);
# elif defined(LINUX)
for(;;)
{
pthread_mutex_lock(&mutex);
if(cnt > 0)
{
cnt--;
pthread_mutex_unlock(&mutex);
return;
}
pthread_cond_wait(&cvar, &mutex);
pthread_mutex_unlock(&mutex);
}
# else
::WaitForSingleObject(handle, INFINITE);
::ResetEvent(handle);
# endif
}
int Signal::wait(unsigned int timeout)
{
if(timeout == 0)
{
wait();
return 0;
}
# ifdef SDPOS
return wait_with_timeout(handle, timeout);
# elif defined(LINUX)
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
if(timeout >= 1000)
{
ts.tv_sec += timeout / 1000;
timeout = timeout % 1000;
}
ts.tv_nsec += ((uint64_t) timeout) * 1000 * 1000;
if(ts.tv_nsec >= 1000000000l)
{
ts.tv_sec++;
ts.tv_nsec -= 1000000000ul;
}
for(;;)
{
pthread_mutex_lock(&mutex);
if(cnt > 0)
{
cnt--;
pthread_mutex_unlock(&mutex);
return 0;
}
if(pthread_cond_timedwait(&cvar, &mutex, &ts))
{
if(cnt > 0)
{
cnt--;
pthread_mutex_unlock(&mutex);
return 0;
}
pthread_mutex_unlock(&mutex);
return -1;
}
pthread_mutex_unlock(&mutex);
}
# else
if(::WaitForSingleObject(handle, timeout) != WAIT_OBJECT_0)
return -1;
::ResetEvent(handle);
return 0;
# endif
}
int Signal::wait_multiple(unsigned int timeout, std::vector<Signal *> sigs)
{
unsigned int nsigs = sigs.size();
if(nsigs == 0)
return 0;
# ifndef WIN
// TODO : without polling...
float cible = utils::hal::get_tick_count_ms() + timeout;
for(;;)
{
for(auto i = 0u; i < sigs.size(); i++)
{
if(sigs[i]->cnt > 0)
{
sigs[i]->cnt--;
return i;
}
}
if(timeout > 0)
{
float temps = utils::hal::get_tick_count_ms();
if(temps >= cible)
return -1;
}
utils::hal::sleep(1);
}
# else
HANDLE handles[nsigs];
for(auto i = 0u; i < nsigs; i++)
handles[i] = sigs[i]->handle;
int res = ::WaitForMultipleObjects(nsigs, handles, false, timeout == 0 ? INFINITE : timeout);
if((res < (int) WAIT_OBJECT_0) || (res >= (int) (WAIT_OBJECT_0 + nsigs)))
return -1;
::ResetEvent(handles[res - WAIT_OBJECT_0]);
return res - WAIT_OBJECT_0;
# endif
}
bool Signal::is_raised()
{
# ifdef SDPOS
return ::is_raised(handle);
# elif defined(LINUX)
return cnt > 0;
# else
if(::WaitForSingleObject(handle, 0) == WAIT_OBJECT_0)
{
::SetEvent(handle);
return true;
}
return false;
# endif
}
static void my_sleep(uint32_t ms)
{
# ifdef LINUX
usleep(ms * 1000);
# else
::Sleep(ms);
# endif
}
void sleep(uint32_t ms)
{
my_sleep(ms);
}
RawFifo::RawFifo(uint32_t capacity)
{
this->capacity = capacity;
fifo_first = 0;
fifo_size = 0;
buffer = (uint8_t *) malloc(capacity);
deblocked = false;
if(buffer == nullptr)
{
fprintf(stderr, "rawfifo(capacity = %d): malloc error.\n", capacity);
fflush(stderr);
this->capacity = 0;
}
}
void RawFifo::deblock()
{
deblocked = true;
h_not_full.raise();
h_not_empty.raise();
}
void RawFifo::reblock()
{
deblocked = false;
h_not_full.clear();
h_not_empty.clear();
}
void RawFifo::clear()
{
mutex.lock();
fifo_first = 0;
fifo_size = 0;
mutex.unlock();
}
RawFifo::~RawFifo()
{
if(buffer != nullptr)
free(buffer);
}
uint32_t RawFifo::write(void *data_, uint32_t size)
{
uint8_t *data = (uint8_t *) data_;
uint32_t a = size;
uint32_t b = capacity;
if(a > b)
{
//size = capacity;
/* Write by chunk of capacity */
while(size > capacity)
{
write(data, capacity);
data += capacity;
size -= capacity;
}
}
/*if(size > capacity)
size = capacity;*/
for(;;)
{
uint32_t lsize;
mutex.lock();
lsize = this->fifo_size;
mutex.unlock();
if(lsize + size < capacity)
break;
h_not_full.wait();
}
mutex.lock();
uint32_t ffirst = fifo_first;
mutex.unlock();
if(size + ffirst < capacity)
{
memcpy(&(buffer[ffirst]), data, size);
}
else
{
memcpy(&(buffer[ffirst]), data, capacity - ffirst);
memcpy(&(buffer[0]), &(data[capacity - ffirst]), size - (capacity - ffirst));
}
mutex.lock();
fifo_first = (fifo_first + size) % capacity;
fifo_size += size;
mutex.unlock();
h_not_full.raise();
h_not_empty.raise();
return size;
}
uint32_t RawFifo::read(void *data_, uint32_t size, uint32_t timeout)
{
uint8_t *data = (uint8_t *) data_;
uint32_t N = 0;
if(size > capacity)
{
//size = capacity;
/* Read by chunk of capacity */
while(size > capacity)
{
uint32_t n = read(data, capacity, timeout);
N += n;
if(n != capacity)
return N;
data += capacity;
size -= capacity;
}
if(size == 0)
return N;
}
for(;;)
{
if(deblocked)
return 0;
uint32_t lsize;
mutex.lock();
lsize = this->fifo_size;
mutex.unlock();
if(lsize >= size)
break;
if(timeout > 0)
{
if(h_not_empty.wait(timeout))
{
//printf(">>>>>>>>>>>>>>>>>>>>>>\nTIMEOUT FIFO READ: size=%d, requested=%d, timeout=%d ms.\n", fifo_size, size, timeout);
//fflush(0);
mutex.lock();
lsize = this->fifo_size;
mutex.unlock();
//printf(">>>>> lsize = %d.\n", lsize);
//fflush(0);
if(lsize >= size)
break;
return 0;
}
}
else
h_not_empty.wait();
}
mutex.lock();
uint32_t ffirst = fifo_first;
uint32_t fsize = fifo_size;
mutex.unlock();
// Now fsize >= size
/* (1) */
if(fsize <= ffirst)
{
memcpy(data, &(buffer[ffirst - fsize]), size);
}
else
{
/* (2b) */
if(size > fsize - ffirst)
{
memcpy(data, &(buffer[capacity - (fsize - ffirst)]), fsize - ffirst);
memcpy(&(data[fsize - ffirst]), buffer, size - (fsize - ffirst));
}
/* (2a) */
else
{
memcpy(data, &(buffer[capacity - (fsize - ffirst)]), size);
}
}
mutex.lock();
fifo_size -= size;
mutex.unlock();
h_not_full.raise();
h_not_empty.raise();
return size + N;
}
int RawFifo::size()
{
return fifo_size;
}
bool RawFifo::full()
{
bool res;
mutex.lock();
res = (fifo_size == capacity);
mutex.unlock();
return res;
}
bool RawFifo::empty()
{
bool res;
mutex.lock();
res = (fifo_size == 0);
mutex.unlock();
return res;
}
#ifdef WIN
static LARGE_INTEGER base_tick;
static LARGE_INTEGER frequency;
static bool tick_init_done = false;
#endif
uint64_t get_tick_count_us()
{
# ifdef WIN
LARGE_INTEGER tick;
if(!tick_init_done)
{
if(!QueryPerformanceFrequency(&frequency))
{
printf("Failed to initialize 64 bits counter.\n");
frequency.QuadPart = 1000 * 1000;
}
QueryPerformanceCounter(&base_tick);
tick_init_done = true;
}
QueryPerformanceCounter(&tick);
uint64_t result = (uint64_t) ((float)(tick.QuadPart-base_tick.QuadPart)*1000.0*1000.0 / frequency.QuadPart);
return result;
# else
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
perror("clock_gettime().");
return 0;
}
return (uint64_t) (ts.tv_nsec / 1000) + (((uint64_t) ts.tv_sec) * 1000 * 1000);
# endif
}
uint64_t get_tick_count_ms()
{
# ifdef WIN
//return GetTickCount();
LARGE_INTEGER tick;
if(!tick_init_done)
{
if(!QueryPerformanceFrequency(&frequency))
{
printf("Failed to initialize 64 bits counter.\n");
frequency.QuadPart = 1000 * 1000;
}
QueryPerformanceCounter(&base_tick);
tick_init_done = true;
}
QueryPerformanceCounter(&tick);
uint64_t result = (uint64_t) ((float)(tick.QuadPart-base_tick.QuadPart)*1000.0 / frequency.QuadPart);
return result;
# else
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
perror("clock_gettime().");
return 0;
}
return (uint64_t) (ts.tv_nsec / (1000 * 1000)) + ts.tv_sec * 1000;
# endif
}
}}
| 12,247
|
C++
|
.cc
| 589
| 17.466893
| 129
| 0.623345
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,953
|
schema2doc.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/utilities/schema2doc.cc
|
/*
* schema2doc.cc
*
* Created on: 27 août 2013
* Author: A
*/
#include "cutil.hpp"
#include "mxml.hpp"
#include "modele.hpp"
#include <stdio.h>
#include <iostream>
using namespace utils;
using namespace model;
using namespace std;
void print_usage()
{
cerr << "Usage:\nschema2doc -i (schema_filename.xml) -f latex|html [-o ofilename]" << endl;
}
int main(int argc, char **argv)
{
CmdeLine cmdeline(argc, argv);
utils::init(cmdeline, "libcutil", "schema2doc");
if(!cmdeline.has_option("-i"))
{
print_usage();
return -1;
}
string fp = cmdeline.get_option("-i", "");
string fmt = cmdeline.get_option("-f", "latex");
string ofile = cmdeline.get_option("-o", "./a.out");
/*FileSchema fs;
if(fs.from_file(Util::get_fixed_data_path() + PATH_SEP + "std-schema.xml"))
return -1;*/
/*Node n;
if(n.load(Util::get_fixed_data_path() + PATH_SEP + "std-schema.xml", fp))
return -1;*/
FileSchema fs;
if(fs.from_file(utils::get_fixed_data_path() + PATH_SEP + "std-schema.xml"))
return -1;
Node n = Node::create_ram_node(fs.root, fp);
Node root = n.get_child_at("node", 0);
if(fmt.compare("html") == 0)
{
DotTools du;
string res;
if(du.export_html_att_table(res, root))
return -1;
string main_title = "";
string header = "<html><head><title>" + main_title + "</title>"
"<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"
"</head><body style=\"text-align:center;\">";
res = header + res + "</body></html>";
return files::save_txt_file(ofile, res);
}
else if(fmt.compare("latex") == 0)
{
LatexWrapper du;
string res;
if(du.export_att_table(res, root))
return -1;
return files::save_txt_file(ofile, str::to_latex(str::utf8_to_latin(res)));
}
else
{
print_usage();
return -1;
}
}
| 1,982
|
C++
|
.cc
| 69
| 24.434783
| 94
| 0.610493
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,954
|
preprocess.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/utilities/preprocess.cc
|
#include "cutil.hpp"
#include "mxml.hpp"
#include <stdio.h>
#include <iostream>
#include <ostream>
#include <string>
#include <fstream>
//FILE *os, *toc_os;
/*std::string handle_item(const MXml &mx)
{
if(mx.name.compare("em") == 0)
{
return std::string("<i>") + handle_children(mx) + "</i>";
}
}
std::string handle_children(const MXml &mx)
{
int i, j, k;
j = 0;
k = 0;
for(i = 0; i < mx.order.size(); i++)
{
if(mx.order[i])
{
handle_element(mx.children[j]);
j++;
}
else
{
fprintf(os, "%s", mx.text[k].c_str());
k++;
}
}
}*/
using namespace utils;
using namespace utils::model;
using namespace std;
ofstream os, toc_os;
char current_section[255];
char current_part[255];
void handle_element(const MXml &mx)
{
if(mx.name.compare("include") == 0)
{
std::string fn = mx.get_attribute("path").to_string();
MXml xinc;
infos("Loading included file: %s...", fn.c_str());
int ret = xinc.from_file(fn);
infos("Done.");
if(ret == 0)
handle_element(xinc);
else
{
erreur("Unable to open %s.\n", fn.c_str());
}
return;
}
int i, j, k;
/** Add labels to TOC */
if(mx.name.compare("label") == 0)
{
toc_os << " <toc-label name=\"" << str::utf8_to_latin(mx.get_attribute("name").to_string()) << "\" ";
toc_os << "section=\"" << str::utf8_to_latin(current_section) << "\" ";
toc_os << "part=\"" << str::utf8_to_latin(current_part) << "\"/>\n";
}
if(mx.name.compare("section") == 0)
{
std::string lname, name;
name = mx.get_attribute("name").to_string();
if(mx.has_attribute("label"))
lname = mx.get_attribute("label").to_string();
else
{
lname = name;
avertissement("Section without label: '%s'.\n", lname.c_str());
}
sprintf(current_section, "%s", lname.c_str());
toc_os <<// " <toc-section label=\"%s\" name=\"%s\"/>\n", lname.c_str(), name.c_str());
" <toc-section label=\"" << lname << "\" name=\"" << name << "\"/>\n";
}
if(mx.name.compare("sub-section") == 0)
{
std::string lname, name;
name = str::utf8_to_latin(mx.get_attribute("name").to_string());
if(mx.has_attribute("label"))
lname = str::utf8_to_latin(mx.get_attribute("label").to_string());
else
{
lname = name;
avertissement("Sub-section without label: '%s'.\n", lname.c_str());
}
toc_os << // " <toc-sub-section label=\"%s\" name=\"%s\" section=\"%s\"/>\n",
//lname.c_str(), name.c_str(), current_section);
" <toc-sub-section label=\"" << lname << "\" name=\"" << name << "\" section=\"" << current_section << "\"/>\n";
}
if(mx.name.compare("part") == 0)
{
std::string lname, name;
name = str::utf8_to_latin(mx.get_attribute("name").to_string());
if(mx.has_attribute("label"))
lname = str::utf8_to_latin(mx.get_attribute("label").to_string());
else
{
lname = name;
avertissement("Part without label: '%s'.\n", lname.c_str());
}
sprintf(current_part, "%s", lname.c_str());
toc_os << //"<toc-part label=\"%s\" name=\"%s\"/>\n", lname.c_str(), name.c_str());
"<toc-part label=\"" << lname << "\" name=\"" << name << "\"/>\n";
}
os << "<" << str::utf8_to_latin(mx.name) << " ";
for(i = 0; i < (int) mx.attributes.size(); i++)
{
os << str::utf8_to_latin(mx.attributes[i].name)
<< " = \"" << str::utf8_to_latin(mx.attributes[i].string_value) << "\" ";
}
os << ">";
j = 0;
k = 0;
for(i = 0; i < (int) mx.order.size(); i++)
{
if(mx.order[i])
{
handle_element(mx.children[j]);
j++;
}
else
{
os << str::utf8_to_latin(mx.text[k]);
k++;
}
}
os << "</" << mx.name << ">";
if(mx.name.compare("section") == 0)
{
sprintf(current_section, "no section");
}
}
int main(int argc, char **argv)
{
CmdeLine cmdeline(argc, argv);
utils::init(cmdeline, "lcutil", "preprocess");
current_part[0] = 0x00;
current_section[0] = 0x00;
if(argc < 2)
argv[1] = "./root.xml";
if(argc < 3)
argv[2] = "./tmp.xml";
printf("preprocess %s -> %s\n", argv[1], argv[2]);
MXml mx;
infos("Loading %s...", argv[1]);
mx.from_file(argv[1]);
infos("Done.");
os.open(argv[2], std::ofstream::out);
toc_os.open("./toc.xml", std::ofstream::out);
//os = fopen(argv[2], "wt");
//toc_os = fopen("./toc.xml", "wt");
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
toc_os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
toc_os << "<toc>\n";
handle_element(mx);
toc_os << "</toc>\n";
os.close();
toc_os.close();
printf("Done.\n");
return 0;
}
| 4,741
|
C++
|
.cc
| 167
| 23.886228
| 123
| 0.543016
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,955
|
model-editor.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/utilities/model-editor.cc
|
#include "model-editor.hpp"
#include "mmi/stdview.hpp"
#include "cutil.hpp"
#include <stdio.h>
#include <iostream>
ModelEditor *ModelEditor::instance = nullptr;
ModelEditor *ModelEditor::get_instance()
{
if(instance == nullptr)
instance = new ModelEditor();
return instance;
}
void ModelEditor::on_b_infos()
{
Gtk::AboutDialog ad;
ad.set_copyright("(C) 2012 J.A.");
Glib::RefPtr<Gdk::Pixbuf> pix = Gdk::Pixbuf::create_from_file(utils::get_img_path() + "/TODO.png");
ad.set_logo(pix);
ad.set_name(langue.get_item("main-wnd-title") + "\n");
ad.set_version("revision 0.00");
std::vector<Glib::ustring> v;
v.push_back("(C) 2012 J.A.");
ad.set_authors(v);
ad.set_position(Gtk::WIN_POS_CENTER);
ad.run();
}
void ModelEditor::on_b_save_as()
{
}
void ModelEditor::on_b_new()
{
std::string path, name;
files::split_path_and_filename(model_path, path, name);
std::string fn = dialogs::nouveau_fichier("Nouvelle configuration", "*.xml", "Fichier XML", name, path);
if(fn.size() == 0)
return;
Node mod = Node::create_ram_node(root_schema);
if(ev != nullptr)
{
infos("Delete old widget...");
model.remove_listener(this);
vboxi.remove(*(ev->get_widget()));
delete ev;
}
model_path = fn;
infos("Model switch..");
model = mod;
model.add_listener(this);
model.save(fn);
infos("Model view creation..");
NodeViewConfiguration vconfig;
//vconfig.show_children = true;
//vconfig.show_separator = false;
//vconfig.nb_attributes_by_column = 20;
//vconfig.nb_columns = 2;
ev = new utils::mmi::NodeView(this, model, vconfig);
infos("Adding to current view..");
vboxi.pack_start(*(ev->get_widget()), Gtk::PACK_EXPAND_WIDGET);
this->show_all_children(true);
config.set_attribute("last-file", fn);
update_view();
DialogManager::setup_window(this);
}
void ModelEditor::save_as(const string &filename)
{
}
void ModelEditor::on_b_save()
{
if(!files::file_exists(model_path))
{
return;
}
model.save(model_path, true);
model_saved = true;
update_view();
}
void ModelEditor::on_b_exit()
{
if(!model_saved)
{
if(!dialogs::check_dialog("Quitter",
"Certaines modifications n'ont pas été sauvegardées.",
"Voulez-vous vraiment fermer l'application et\nperdre les dernières modifications ?"))
{
return;
}
}
std::string cfg_file = utils::get_current_user_path() + PATH_SEP + "cfg.xml";
config.save(cfg_file);
infos("Bye.");
exit(0);
}
void ModelEditor::on_b_open()
{
std::string path, name;
files::split_path_and_filename(config.get_attribute_as_string("last-file"), path, name);
std::string fn = dialogs::ouvrir_fichier("Ouvrir", /*"*.xml"*/ext, /*"Fichier XML"*/extname, name, path);
if(fn.size() > 0)
this->open(fn);
}
void ModelEditor::on_b_param()
{
if(NodeDialog::display_modal(config) == 0)
{
std::string cfg_file = utils::get_current_user_path() + PATH_SEP + "cfg.xml";
config.save(cfg_file);
}
}
void ModelEditor::on_b_comp()
{
}
void ModelEditor::on_event(const ChangeEvent &ce)
{
if(ce.type == ChangeEvent::COMMAND_EXECUTED)
{
}
else
{
model_saved = false;
//infos("Change event detected: %s", ce.to_string().c_str());
update_view();
}
}
void ModelEditor::update_view()
{
std::string s;
if(ev == nullptr)
{
s = "Edition modéle XML";
}
else
{
s = "Edition [";
s += model_path;
s += "]";
}
set_title(s);
b_save.set_sensitive(!model_saved);
}
void ModelEditor::on_event(const EVSelectionChangeEvent &evse)
{
infos("Sel change detected.");
#if 0
if(!model_saved)
{
if(Gide::check_dialog("Changement de sélection",
"Voulez-vous enregistrer les modification effectuées ?",
"Les modifications n'ont pas été sauvegardées."))
{
on_b_save();
}
else
{
model_saved = true;
update_view();
}
}
std::string type = evse.selection.schema()->name.get_id();
std::string dbpath = config.get_attribute_as_string("db-path");
std::string name = evse.selection.get_attribute_as_string("name");
if(type.compare("card") == 0)
{
infos("Selection = card %s.", name.c_str());
open(dbpath
+ Util::get_path_separator()
+ "cards"
+ Util::get_path_separator()
+ name
+ ".xml");
}
else if(type.compare("fpga-lib") == 0)
{
infos("Selection = fpga lib %s.", name.c_str());
open(dbpath
+ Util::get_path_separator()
+ "fpga"
+ Util::get_path_separator()
+ name
+ ".xml");
}
else if(type.compare("mod") == 0)
{
infos("Selection = module %s.", name.c_str());
open(dbpath
+ Util::get_path_separator()
+ "modules"
+ Util::get_path_separator()
+ name
+ ".xml");
}
#endif
}
ModelEditor::ModelEditor()
{
ev = nullptr;
mainWindow = this;
set_title("Model editor");
model_saved = true;
appli_view_prm.use_touchscreen = false;
appli_view_prm.inverted_colors = false;
//root_fs = new FileSchema(exec_dir + Util::get_path_separator() + "std-schema.xml");
FileSchema *fs = new FileSchema(utils::get_fixed_data_path() + PATH_SEP + "model-editor-config-schema.xml");
std::string cfg_file = utils::get_current_user_path() + PATH_SEP + "cfg.xml";
if(!files::file_exists(cfg_file))
{
config = Node::create_ram_node(fs->get_schema("model-editor"));
config.save(cfg_file);
}
else
{
config = Node::create_ram_node(fs->get_schema("model-editor"), cfg_file);
if(config.is_nullptr())
{
config = Node::create_ram_node(fs->get_schema("model-editor"));
config.save(cfg_file);
}
}
infos("Application configuration:\n%s\n", config.to_xml().c_str());
add(vbox);
vbox.pack_start(tools, Gtk::PACK_SHRINK);
/*NodeViewConfiguration cfg;
cfg.show_children = true;
cfg.display_only_tree = false;
cfg.expand_all = false;
Node nv;
ev_root = new NodeView(this, nv, cfg);
ev_root->Provider<EVSelectionChangeEvent>::add_listener(this);
scroll.add(*ev_root->get_widget());*/
//vbox.pack_start(scroll, Gtk::PACK_EXPAND_WIDGET);
vbox.pack_start(vboxi, Gtk::PACK_SHRINK);
//scroll.add(vboxi);
tools.add(b_new);
tools.add(b_open);
tools.add(b_save);
tools.add(b_param);
tools.add(b_infos);
tools.add(b_exit);
b_new.set_stock_id(Gtk::Stock::NEW);
b_open.set_stock_id(Gtk::Stock::OPEN);
b_save.set_stock_id(Gtk::Stock::SAVE);
b_exit.set_stock_id(Gtk::Stock::QUIT);
b_infos.set_stock_id(Gtk::Stock::ABOUT);
b_param.set_stock_id(Gtk::Stock::PREFERENCES);
b_infos.set_label("A propos");
b_infos.set_tooltip_markup("A propos");
tools.set_icon_size(Gtk::ICON_SIZE_LARGE_TOOLBAR);
tools.set_toolbar_style(Gtk::TOOLBAR_ICONS);//TOOLBAR_BOTH);
b_new.set_tooltip_markup(langue.get_item("new"));
b_open.set_tooltip_markup(langue.get_item("open"));
b_save.set_tooltip_markup(langue.get_item("save"));
b_exit.set_tooltip_markup(langue.get_item("exit"));
b_param.set_tooltip_markup(langue.get_item("params"));
b_new.signal_clicked().connect(sigc::mem_fun(*this, &ModelEditor::on_b_new));
b_open.signal_clicked().connect(sigc::mem_fun(*this, &ModelEditor::on_b_open));
b_save.signal_clicked().connect(sigc::mem_fun(*this, &ModelEditor::on_b_save));
b_exit.signal_clicked().connect(sigc::mem_fun(*this, &ModelEditor::on_b_exit));
b_param.signal_clicked().connect(sigc::mem_fun(*this, &ModelEditor::on_b_param));
b_infos.signal_clicked().connect(sigc::mem_fun(*this, &ModelEditor::on_b_infos));
infos("Construction terminée.");
show_all_children(true);
update_view();
//set_size_request(1000,780);
DialogManager::setup_window(this);
// TODO
//nv.add_listener(this);
}
ModelEditor::~ModelEditor()
{
}
int ModelEditor::open(std::string filename)
{
MXml mx;
if(!files::file_exists(filename))
{
// CREATION DU FICHIER SI IL N'EXISTE PAS ?
erreur("File not found: %s.", filename.c_str());
dialogs::affiche_erreur("Ouverture", "Le fichier n'existe pas.", filename + " n'est pas accessible.");
return -1;
}
if(mx.from_file(filename))
{
erreur("Parse error in %s.", filename.c_str());
dialogs::affiche_erreur("Ouverture", "Le format du fichier est invalide", "");
return -2;
}
model_path = filename;
infos("Loading model...");
Node mod = Node::create_ram_node(root_fs->get_schema(mx.name), filename);
if(ev != nullptr)
{
infos("Delete old widget...");
model.remove_listener(this);
vboxi.remove(*(ev->get_widget()));
delete ev;
}
infos("Model switch..");
model = mod;
model.add_listener(this);
infos("Model view creation..");
NodeViewConfiguration vconfig;
vconfig.display_only_tree = false;
vconfig.show_children = true;
vconfig.expand_all = true;
//vconfig.show_children = true;
//vconfig.show_separator = false;
//vconfig.nb_attributes_by_column = 20;
//vconfig.nb_columns = 2;
ev = new NodeView(this, model, vconfig);
infos("Adding to current view..");
vboxi.pack_start(*(ev->get_widget()), Gtk::PACK_EXPAND_WIDGET);
this->show_all_children(true);
config.set_attribute("last-file", filename);
update_view();
DialogManager::setup_window(this);
return 0;
}
static void usage()
{
cout << "Usage:" << endl;
cout << "model-editor.exe [-f schema.xml -s root-node [-d data-file.xml]]" << endl << endl;
}
int ModelEditor::main(CmdeLine &cmdeline)
{
langue.load(utils::get_fixed_data_path() + PATH_SEP + "std-lang.xml");
//GtkUtil::set_theme("dark-nimbus");
std::string filename;
std::string schema_path;
if(cmdeline.has_option("--help"))
{
usage();
return 0;
}
if(cmdeline.has_option("-f"))
{
schema_path = cmdeline.get_option("-f");
}
else
{
avertissement("no schema specified.");
schema_path = dialogs::ouvrir_fichier(str::latin_to_utf8("Schéma de données"),
"*.xml",
"Fichier XML",
"",
last_schema_dir);
if(schema_path.size() == 0)
return -1;
}
if(!files::file_exists(schema_path))
{
avertissement("Schema file not found: %s.", schema_path.c_str());
return -1;
}
root_fs = new FileSchema(schema_path);
string rschema;
if(cmdeline.has_option("-s"))
{
rschema = cmdeline.get_option("-s");
}
else
{
erreur("TODO: root schema selection.");
return -1;
}
root_schema = root_fs->get_schema(rschema);
ext = std::string("*.") + cmdeline.get_option("-e", "xml");
extname = cmdeline.get_option("-n", "Fichier XML (*.xml)");
if(cmdeline.has_option("-d"))
open(cmdeline.get_option("-d"));
else
{
avertissement("no file specified.");
/*string file_path = Gide::open_dialog(Util::latin_to_utf8("Fichier de parametres"),
ext,
extname,
"",
last_schema_dir);
if(file_path.size() == 0)
return -1;
open(file_path);*/
}
Gtk::Main::run(*this);
return 0;
}
int main(int argc, char **argv)
{
CmdeLine cmdeline(argc, argv);
utils::init(cmdeline, "utils", "model-editor");
//Glib::thread_init();
Gtk::Main kit(argc, argv);
ModelEditor *editor = ModelEditor::get_instance();
return editor->main(cmdeline);
}
| 11,322
|
C++
|
.cc
| 392
| 24.964286
| 110
| 0.649014
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,956
|
rcgene.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/utilities/rcgene.cc
|
#include "cutil.hpp"
#include "mxml.hpp"
#include <stdio.h>
using namespace utils;
using namespace model;
int main(int argc, char **argv)
{
CmdeLine cmdeline(argc, argv);
utils::init(cmdeline, "libcutil", "rcgene");
MXml mx;
if(mx.from_file(cmdeline.get_option("-i").c_str()))
{
printf("rggene: no version.xml file found.\n");
return -1;
}
int maj, min, build;
std::string company, copyright, file_desc, original_file;
maj = mx.get_attribute("maj").to_int();
min = mx.get_attribute("min").to_int();
build = mx.get_attribute("build").to_int();
company = mx.get_attribute("company").to_string();
copyright = mx.get_attribute("copyright").to_string();
file_desc = mx.get_attribute("file_desc").to_string();
original_file = mx.get_attribute("original_file").to_string();
printf("rcgene: revision = %d.%d...\n", maj, min);
std::string name = cmdeline.get_option("-n", "version");
std::string orc = cmdeline.get_option("-o") + PATH_SEP + name + ".rc";
FILE *of = fopen(orc.c_str(), "wt");
fprintf(of,
"1 VERSIONINFO\n"
"FILEVERSION 0,%d,%d,%d\n"
"PRODUCTVERSION 0,%d,%d,%d\n"
"FILEFLAGSMASK 0x17L\n"
"FILEOS 0x4L\n"
"FILETYPE 0x01\n"
"FILESUBTYPE 0x0L\n"
"BEGIN\n"
" BLOCK \"StringFileInfo\"\n"
" BEGIN\n"
" BLOCK \"040c04b0\"\n"
" BEGIN\n"
" VALUE \"CompanyName\", \"%s\"\n"
" VALUE \"FileDescription\", \"%s\"\n"
" VALUE \"FileVersion\", \"0, %d, %d, %d\"\n"
" VALUE \"InternalName\", \"%s\"\n"
" VALUE \"LegalCopyright\", \"%s\"\n"
" VALUE \"OriginalFilename\", \" %s\"\n"
" VALUE \"ProductName\", \"%s\"\n"
" VALUE \"ProductVersion\", \"0, %d, %d, %d\"\n"
" END\n"
" END\n"
" BLOCK \"VarFileInfo\"\n"
" BEGIN\n"
" VALUE \"Translation\", 0x40c, 1200\n"
" END\n"
"END\n", maj, min, build, maj, min, build, company.c_str(), file_desc.c_str(), maj, min, build, file_desc.c_str(),
copyright.c_str(), original_file.c_str(), original_file.c_str(), maj, min, build);
fclose(of);
std::string oh = cmdeline.get_option("-o") + PATH_SEP + name + ".h";
of = fopen(oh.c_str(), "wt");
fprintf(of, "#define VERSION_MAJ %d\n", maj);
fprintf(of, "#define VERSION_MIN %d\n", min);
fclose(of);
return 0;
}
| 2,328
|
C++
|
.cc
| 65
| 31.261538
| 118
| 0.592064
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,957
|
test-multithread.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/utilities/test-multithread.cc
|
class Essai
{
public:
utils::model::Node noeud;
unsigned int cnt[2];
utils::hal::Signal sig[2];
Essai()
{
cnt[0] = cnt[1] = 0;
}
void essai1()
{
for(;;)
{
noeud.get_attribute_as_int("config/general/langue");
cnt[0]++;
if(cnt[0] > 500000)
{
utils::infos("Fin thread 1");
sig[0].raise();
return;
}
}
}
void essai2()
{
for(;;)
{
noeud.set_attribute("config/general/langue", (int) cnt[1]);
cnt[1]++;
if(cnt[1] > 500000)
{
utils::infos("Fin thread 2");
sig[1].raise();
return;
}
}
}
};
int main()
{
Essai essai;
essai.noeud = utils::model::Node::create_ram_node(mgc_schema);
utils::infos("Début test concurrence et modèle...");
utils::hal::thread_start(&essai, &Essai::essai1);
utils::hal::thread_start(&essai, &Essai::essai2);
essai.sig[0].wait();
essai.sig[1].wait();
}
| 957
|
C++
|
.cc
| 49
| 14.653061
| 65
| 0.550448
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,958
|
socket.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/socket.cc
|
#include "comm/socket.hpp"
#include "cutil.hpp"
#ifdef WIN
#include <windows.h>
#include <process.h>
#endif
#include <malloc.h>
#include <stdio.h>
#ifdef LINUX
#include <errno.h>
#include <strings.h>
#include <fcntl.h>
#include <netinet/tcp.h>
static int WSAGetLastError(){return errno;}
#endif
#include <string.h>
namespace utils
{
namespace comm
{
#ifdef WIN
static WSAData wsa;
static bool winsock_init = false;
void winsock_startup()
{
if(!winsock_init)
{
winsock_init = true;
WSAStartup(MAKEWORD(1, 1), &wsa);
}
}
#else
# define winsock_startup()
# endif
Socket::Socket(): rx_fifo(1024 * 1024)
{
log.setup("comm/socket");
connected = false;
}
Socket::~Socket()
{
infos("Socket delete..");
if(connected)
{
disconnect();
hal::sleep(1);
}
infos("done.");
}
bool Socket::is_connected() const
{
return connected;
}
int Socket::get_nb_rx_available()
{
return rx_fifo.size();
}
int Socket::disconnect()
{
infos("closing socket..");
connected = false;
shutdown(sock, 2);
int res = closesocket(sock);
if(res)
erreur("closesocket error 0x%x.", res);
char c = 0;
rx_fifo.write(&c, 1);
return 0;
}
int Socket::connect(std::string target_ip,
uint16_t target_port,
socket_type_t type)
{
if(is_connected())
disconnect();
this->connected = false;
winsock_startup();
infos("connect(%s:%d)...", target_ip.c_str(), target_port);
/* Socket creation */
sockaddr_in local, remote;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
/* This is the port to connect from. Setting 0 means use random port */
local.sin_port = htons(0);
remote.sin_family = AF_INET;
remote.sin_port = htons(target_port);
if(target_ip.compare("localhost") == 0)
{
//remote.sin_addr.s_addr/*.S_un.S_addr*/ = INADDR_ANY;
//remote.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
target_ip = "127.0.0.1";
infos("(localhost)");
}
# ifdef WIN
if((remote.sin_addr.S_un.S_addr = inet_addr(target_ip.c_str())) == INADDR_NONE)
{
erreur("Error setting IP.");
return -1;
}
# else
struct hostent *server;
server = gethostbyname(target_ip.c_str());
if (!server)
{
erreur("Impossible de résoudre \"%s\"", target_ip.c_str());
return -1;
}
bzero(&remote, sizeof(remote));
remote.sin_family = AF_INET;
bcopy(server->h_addr, &remote.sin_addr.s_addr, server->h_length);
remote.sin_port = htons(target_port);
# endif
if(type == SOCKET_UDP)
{
int res = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(res == SOCKET_ERROR)
{
erreur("Error creating socket.");
return -1;
}
sock = res;
}
else if(type == SOCKET_TCP)
{
int res = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(res == SOCKET_ERROR)
{
erreur("Error creating socket.");
return -1;
}
sock = res;
}
else
{
erreur("Unknown socket type: %d.", type);
return -1;
}
if(::bind(sock, (sockaddr *)&local, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
int err = WSAGetLastError();
erreur("Error binding socket, err = %x.", err);
return -1;
}
infos("Now connecting to server...");
if(::connect(sock, (sockaddr *)&remote, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
int err = WSAGetLastError();
avertissement("Error connecting.");
printf("Last error = 0x%x = %d.\n", err, err);
return -1;
}
this->connected = true;
# ifdef WIN
u_long on = 1;
ioctlsocket(sock, FIONBIO, &on);
# else
const int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
//fcntl(sock, F_SETFL, O_NONBLOCK);
# endif
infos("Connected ok.");
rx_fifo.reblock();
hal::thread_start(this, &Socket::rx_thread, "socket/client");
return 0;
}
void SocketServer::stop()
{
if(listening)
{
infos("stop()...");
listening = 0;
shutdown(listen_socket, 2);
thread_finished.wait(100);
}
}
SocketServer::~SocketServer()
{
stop();
}
void SocketServer::thread_handler()
{
infos("Socket server thread running..");
for(;;)
{
Socket *the_socket = new Socket();
SOCKET accept_socket;
sockaddr_in address;
int remote_port;
infos("Wait for client..");
# ifdef LINUX
socklen_t len = sizeof(sockaddr_in);
accept_socket = ::accept(listen_socket, (struct sockaddr *) &address, &len);
# else
accept_socket = ::accept(listen_socket, nullptr, nullptr);
# endif
if(!listening)
{
thread_finished.raise();
infos("accept thread terminated.");
return;
}
if(((int) accept_socket) == -1)
{
thread_finished.raise();
infos("accept thread terminated (ext).");
return;
}
remote_port = ntohl(address.sin_port);
infos("Connection accepted, sock = %x, remote port = %d.",
accept_socket, listening, remote_port);
the_socket->remote_port = remote_port;
the_socket->local_port = local_port;
the_socket->sock = accept_socket;
the_socket->connected = true;
the_socket->socket_type = Socket::SOCKET_TCP;
# ifdef WIN
u_long on = 1;
ioctlsocket(the_socket->sock, FIONBIO, &on);
# else
const int flags = fcntl(the_socket->sock, F_GETFL, 0);
fcntl(the_socket->sock, F_SETFL, flags | O_NONBLOCK);
# endif
hal::thread_start(the_socket, &Socket::rx_thread, "socket/server");
SocketOpenedEvent soe;
soe.socket = the_socket;
dispatch(soe);
}
}
SocketServer::SocketServer()
{
log.setup("comm/socket-server");
listening = 0;
}
int SocketServer::listen(uint16_t port, Socket::socket_type_t type)
{
winsock_startup();
local_port = port;
infos("listen(port = %d).", port);
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(port);
listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(type == Socket::SOCKET_UDP)
{
listen_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if(type == Socket::SOCKET_TCP)
{
listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
else
{
erreur("Unknown socket type: %d.", type);
return -1;
}
if (listen_socket == INVALID_SOCKET)
{
erreur("Error at socket(): %ld\n", WSAGetLastError());
return -1;
}
{
int flag = 1;
if(setsockopt(listen_socket, SOL_SOCKET,
SO_REUSEADDR, (char *) &flag, sizeof(int)))
erreur("Failed to set SO_REUSEADDR socket option.");
}
if (::bind(listen_socket,
(SOCKADDR*) &service,
sizeof(service)) == SOCKET_ERROR)
{
erreur("bind() failed.\n");
uint32_t err = WSAGetLastError();
erreur("Last system error: %d = 0x%x\n", err, err);
# ifdef LINUX
if(err == 98)
{
avertissement("errno 98: Address already in use.");
}
# endif
closesocket(listen_socket);
return -1;
}
infos("Now listening for connection...");
// Listen for incoming connection requests
// on the created socket
if (::listen(listen_socket, SOMAXCONN ) == SOCKET_ERROR)
{
int error = WSAGetLastError();
erreur("Error listening on socket: %d = 0x%x.\n", error, error);
if(error == 10013)
{
erreur("WSAEACCES: permission denied.");
}
return -1;
}
listening = 1;
hal::thread_start(this, &SocketServer::thread_handler, "socket/server");
return 0;
}
void Socket::rx_thread()
{
# define TMP_BUF_SIZE (32*1024)
uint8_t *tmp_buf;
//bool disable_timeout = false;
infos("rx thread running.");
if(!connected)
{
infos("rx thread canceled.");
return;
}
tmp_buf = (uint8_t *) malloc(TMP_BUF_SIZE);
if(tmp_buf == nullptr)
{
erreur("Unable to allocate rx buffer.");
return;
}
for(;;)
{
/* 5 ms */
//timeval tv = { 0, 5 * 1000};
//disable_timeout = true;
# ifdef WIN
FD_ZERO(&read_fs);
FD_SET(sock, &read_fs);
int res = select(1, &read_fs, 0, 0, nullptr/*disable_timeout ? nullptr : &tv*/);
//disable_timeout = false;
/* timeout */
if(res == 0)
{
erreur("Timeout");
continue;
//return -1;
}
# else
FD_ZERO(&read_fs);
FD_SET(sock, &read_fs);
//verbose("select...");
int res = select(sock + 1, &read_fs, 0, 0, nullptr);
//verbose("select done.");
/* timeout */
if(res == 0)
{
erreur("Timeout");
continue;
}
# endif
/*if(feof(sock))
{
warning("EOF detected.");
connected = false;
SocketClosedEvent sce;
sce.socket = this;
char tmp = 0;
rx_fifo.write(&tmp, 1);
dispatch(sce);
free(tmp_buf);
return;
}*/
{
int result = recv(sock, (char *) tmp_buf, TMP_BUF_SIZE, 0);
if(result > 0)
{
//if(result == TMP_BUF_SIZE)
// disable_timeout = true;
//ByteArray ba(tmp_buf, result);
//verbose("Rx: %s.", ba.to_string().c_str());
rx_fifo.write(tmp_buf, result);
}
else if(result == 0)
{
avertissement("Connection closed.");
connected = false;
SocketClosedEvent sce;
sce.socket = this;
char tmp = 0;
rx_fifo.write(&tmp, 1);
this->rx_fifo.deblock();
dispatch(sce);
free(tmp_buf);
return;
}
else
{
# ifdef LINUX
if(errno == EAGAIN)
{
avertissement("recv: EAGAIN.");
continue;
}
# endif
avertissement("recv: returned %d.", result);
int error = WSAGetLastError();
if(!connected)
{
char c = 0xff;
free(tmp_buf);
infos("rx thread exit.");
rx_fifo.write(&c, 1);
this->rx_fifo.deblock();
return;
}
avertissement("recv error: %d/%d (socket closed).", result, error);
# ifdef WIN
if(error == WSAEWOULDBLOCK)
{
erreur("no data.");
continue;
}
# endif
if(result == -1)
{
avertissement("Connection closed.");
connected = false;
this->rx_fifo.deblock();
SocketClosedEvent sce;
sce.socket = this;
dispatch(sce);
free(tmp_buf);
return;
}
}
}
}
}
int Socket::read(uint8_t *buffer, uint32_t length, int timeout)
{
int res = rx_fifo.read(buffer, length, timeout);
//utils::model::ByteArray ba(buffer, length);
//std::string s = ba.to_string();
//infos("Read: %s.", s.c_str());
return res;
}
int Socket::getc(int timeout)
{
uint8_t c;
int res;
if(!connected)
{
if(timeout > 0)
hal::sleep(timeout);
hal::sleep(10);
return -1;
}
// TODO: must be able to exit if the connection is closed.
res = rx_fifo.read(&c, 1, timeout);
if(!connected)
return -1;
//verbose("getc: %x, res = %d.", c, res);
if(res == 1)
return ((int) c) & 0xff;
else
return -1;
}
uint16_t Socket::get_local_port() const
{
return local_port;
}
uint16_t Socket::get_remote_port() const
{
return remote_port;
}
std::string Socket::get_remote_ip() const
{
return remote_ip;
}
void Socket::putc(char c)
{
write((uint8_t *) &c, 1);
}
void Socket::flush()
{
int flag = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
flag = 0;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
}
void Socket::write(const uint8_t *buffer, uint32_t len)
{
uint32_t nb_tries = 0;
const char *ptr = (const char *) buffer;
bool inc_transmission = false;
//ByteArray ba(buffer, len);
//infos("Tx: %s.", ba.to_string().c_str());
retry:
if(this->connected)
{
int res = send(sock, ptr, len, 0);
if(res < 0)
{
int err = WSAGetLastError();
if(err == 10035)
{
if(nb_tries == 0)
avertissement("TCP bandwidth overflow.");
if(nb_tries > 50)
{
erreur("Unable to write to TCP socket.");
disconnect();
return;
}
/*FD_ZERO(&write_fs);
FD_SET(sock, &write_fs);
int res = select(1, &write_fs, 0, 0, nullptr);*/
hal::sleep(20);
nb_tries++;
goto retry;
}
erreur("send error: %d.", err);
}
/*else if(res == 0)
{
erreur("Incomplete send: %d / %d.", res, len);
}*/
else if(res < (int) len)
{
infos("Incomplete send: %d / %d.", res, len);
hal::sleep(20);
ptr += res;
len -= res;
inc_transmission = true;
goto retry;
}
else if(inc_transmission)
{
infos("Finnaly transmitted all buffer.");
}
}
}
/*extern "C"
{
# ifdef WIN
extern int bt_server_start(SOCKET *socket);
extern int bt_client_connect(const char *target_mac, SOCKET *socket);
# if(defined(BT_SOCKET_DISABLE) && (BT_SOCKET_DISABLE == 1))
int bt_server_start(SOCKET *socket){return -1;}
int bt_client_connect(const char *target_mac, SOCKET *socket){return -1;}
# endif
# endif
};*/
typedef int (*bt_server_start_t)(SOCKET *socket,
const char *service_name,
const char *comment);
BluetoothClient::BluetoothClient()
{
setup("comm/bluetooth-client");
}
BluetoothClient::~BluetoothClient()
{
}
int BluetoothClient::connect(const model::ByteArray &target_mac, Socket **socket)
{
//int res;
infos("Connect to %s...", target_mac.to_string().c_str());
*socket = nullptr;
# if 0
# ifdef WIN
SOCKET socket_windows;
res = bt_client_connect(target_mac.to_string().c_str(), &socket_windows);
if(res != 0)
{
erreur("bt client connexion failed: %d.", res);
return -1;
}
Socket *the_socket = new Socket();
infos("Wait for client..");
infos("Connection accepted.");
warning("TODO: get remote port.");
the_socket->remote_port = 0x00;
the_socket->local_port = 0;
the_socket->sock = socket_windows;
the_socket->connected = true;
the_socket->socket_type = Socket::SOCKET_BT;
u_long on = 1;
ioctlsocket(the_socket->sock, FIONBIO, &on);
OSThread::thread_start(the_socket, &Socket::rx_thread);
return 0;
# else
warning("connect: not implemented.");
return -1;
# endif
# endif
return -1;
}
BluetoothServer::BluetoothServer(const std::string &service_name,
const std::string &comment)
{
setup("comm/bluetooth-server");
this->service_name = service_name;
this->comment = comment;
}
int BluetoothServer::listen()
{
//OSThread::thread_start(this, &BluetoothServer::thread_handler);
int res;
infos("Listen...");
# ifdef WIN
HINSTANCE hdll;
hdll = LoadLibrary("blue.dll");
if(hdll == nullptr)
{
erreur("Error while loading dll.\n");
return -254;
}
bt_server_start_t bt_server_start = (bt_server_start_t) GetProcAddress(hdll, (LPCSTR) 2);
//"_bt_server_start");
if(bt_server_start == nullptr)
{
erreur("Error while loading DLL function.\n");
return -253;
}
infos("calling DLL..");
res = bt_server_start(&listen_socket,
service_name.c_str(),
comment.c_str());
# else
res = -255;
# endif
if(res == 0)
{
infos("Bluetooth server successfully started.");
hal::thread_start(this, &BluetoothServer::thread_handler, "btsocket/server");
/*Socket *the_socket = new Socket();
the_socket->remote_port = 0x00;
the_socket->local_port = 0;
the_socket->sock = socket_windows;
the_socket->connected = true;
the_socket->socket_type = Socket::SOCKET_BT;
u_long on = 1;
ioctlsocket(the_socket->sock, FIONBIO, &on);
OSThread::thread_start(the_socket, &Socket::rx_thread);
SocketOpenedEvent soe;
soe.socket = the_socket;
dispatch(soe);*/
}
else if(res == -3)
{
erreur("Bluetooth driver not detected.");
}
else
{
erreur("Bluetooh server error: %d.", res);
}
return res;
}
void BluetoothServer::stop()
{
}
void BluetoothServer::thread_handler()
{
infos("bluetooth server is running.");
for(;;)
{
Socket *the_socket = new Socket();
SOCKET accept_socket;
infos("Wait for client..");
accept_socket = ::accept(listen_socket, nullptr, nullptr);
infos("Connection accepted.");
the_socket->remote_port = 0x00;
//the_socket->local_port = local_port;
the_socket->sock = accept_socket;
the_socket->connected = true;
the_socket->socket_type = Socket::SOCKET_BT;
# ifdef WIN
u_long on = 1;
ioctlsocket(the_socket->sock, FIONBIO, &on);
# else
fcntl(the_socket->sock, F_SETFL, O_NONBLOCK);
# endif
hal::thread_start(the_socket, &Socket::rx_thread, "btsocket/server");
SocketOpenedEvent soe;
soe.socket = the_socket;
dispatch(soe);
}
}
int send_udp_packet(const std::string &host,
uint16_t port,
utils::model::ByteArray &data_)
{
struct hostent *hp; /* host information */
struct sockaddr_in servaddr; /* server address */
uint32_t len = data_.size();
uint8_t *data = (uint8_t *) malloc(len);
if(data == nullptr)
{
erreur("malloc failed (%d).", len);
return -1;
}
data_.pop_data(data, len);
winsock_startup();
/* fill in the server's address and data */
memset((char*)&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
/* look up the address of the server given its name */
hp = gethostbyname(host.c_str());
if(!hp)
{
free(data);
erreur("could not obtain address of %s.", host.c_str());
return -1;
}
/* put the host's address into the server address structure */
memcpy((void *)&servaddr.sin_addr, hp->h_addr_list[0], hp->h_length);
SOCKET fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(fd == INVALID_SOCKET)
{
free(data);
erreur("socket creation failed with error: %ld", WSAGetLastError());
return -1;
}
/* send a message to the server */
if(sendto(fd,
(const char *) data,
len,
0,
(struct sockaddr *)&servaddr,
sizeof(servaddr)) == SOCKET_ERROR)
{
free(data);
perror("sendto failed");
erreur("Failed to send udp packet.");
return -1;
}
closesocket(fd);
free(data);
return 0;
}
UDPListener::UDPListener()
{
log.setup("udp/listener");
listening = false;
}
int UDPListener::listen(uint16_t port, uint32_t mps)
{
winsock_startup();
if(listening)
{
erreur("%s: already listening.", __func__);
return -1;
}
infos("listen(port = %d)..", port);
this->mps = mps;
struct sockaddr_in myaddr; /* our address */
/* create a UDP socket */
//if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(fd == SOCKET_ERROR)
{
perror("");
erreur("cannot create socket: %ld.", WSAGetLastError());
return -1;
}
/* bind the socket to any valid IP address and a specific port */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(port);
if(bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) == SOCKET_ERROR)
{
perror("");
erreur("bind failed: %ld.", WSAGetLastError());
closesocket(fd);
return -1;
}
buf = (uint8_t *) malloc(mps);
if(buf == nullptr)
{
erreur("malloc failed.");
closesocket(fd);
return -1;
}
listening = true;
utils::hal::thread_start(this, &UDPListener::thread_entry);
return 0;
}
UDPListener::~UDPListener()
{
if(listening)
{
// TODO
closesocket(fd);
}
}
void UDPListener::thread_entry()
{
/* # bytes received */
int len;
/* remote address */
struct sockaddr_in remaddr;
/* length of addresses */
#ifdef LINUX
socklen_t
# else
int
# endif
addrlen = sizeof(remaddr);
for(;;)
{
len = recvfrom(fd,
(char *) buf,
mps, 0,
(struct sockaddr *)&remaddr, &addrlen);
if(len == (int) INVALID_SOCKET)
{
erreur("WSA error: %ld", WSAGetLastError());
}
trace_verbeuse("received a packet of %d bytes.", len);
if(len > 0)
{
UDPPacket packet;
packet.data.put(buf, len);
packet.ip_address = inet_ntoa(remaddr.sin_addr);
dispatch(packet);
}
}
/* never exits */
}
}
}
| 20,494
|
C++
|
.cc
| 819
| 20.494505
| 91
| 0.607387
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
753,959
|
serial-session.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/serial-session.cc
|
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBSERIAL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#include "comm/serial-session.hpp"
#include <stdarg.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#ifdef WIN
#ifndef VSTUDIO
#include <unistd.h>
#else
#include <process.h>
#endif
#endif
namespace utils
{
using namespace model;
namespace comm
{
#define FLAG_ACK 0x80
#define FLAG_LF 0x40
#define FLAG_RSP 0x20
#define FLAG_NCRC 0x10
//static void session_thread_entry(void *prm);
journal::Logable Transport::log("comm");
journal::Logable DataLink::log("comm");
journal::Logable Session::log("comm");
Packet::Packet()
{
length = 0;
}
Packet::Packet(uint8_t flags, uint32_t length)
{
this->length = length;
this->flags = flags;
if(length != 0)
{
data = (uint8_t *) malloc(length);
if(data == nullptr)
{
fprintf(stderr, "Malloc failed (%d).\nAborting...\n", length);
fflush(stderr);
exit(-1);
}
}
}
Packet::Packet(uint32_t length)
{
this->length = length;
this->flags = 0;
if(length != 0)
{
data = (uint8_t*) malloc(length);
if(data == nullptr)
{
fprintf(stderr, "Malloc failed (%d).\nAborting...\n", length);
fflush(stderr);
exit(-1);
}
}
}
std::string Packet::to_string() const
{
char bf[50];
uint32_t i;
std::string s = "packet flags = ";
if(this->flags & FLAG_ACK)
s += "ACK ";
if(this->flags & FLAG_LF)
s += "LF ";
if(this->flags & FLAG_RSP)
s += "RSP ";
if(this->flags & FLAG_NCRC)
s += "NCRC ";
s += "; len = ";
uint32_t ln = length;
s += str::int2str(ln) + "\n";
for(i = 0; i < ln; i++)
{
if((i & 15) == 0)
{
sprintf(bf, "%6d", i);
s += "[" + std::string(bf) + "] ";
}
sprintf(bf, "%2x.", data[i]);
s += std::string(bf);
if((i > 0) && (((i + 1) & 15) == 0))
{
s += "\n";
}
}
sprintf(bf, " -- total len = %d.", ln);
s += std::string(bf);
return s;
}
Packet::~Packet()
{
if(length != 0)
free(data);
}
Packet::Packet(const Packet &p)
{
length = p.length;
flags = p.flags;
if(length != 0)
{
data = (uint8_t *) malloc(length);
if(data == nullptr)
{
fprintf(stderr, "Malloc failed (%d).\nAborting...\n", length);
exit(-1);
}
memcpy(data, p.data, length);
}
}
void Packet::operator =(const Packet &p)
{
if(length != 0)
free(data);
length = p.length;
flags = p.flags;
if(length != 0)
{
data = (uint8_t*) malloc(length);
if(data == nullptr)
{
printf("Malloc failed (%d).\nAborting...\n", length);
exit(-1);
}
memcpy(data, p.data, length);
}
}
Packet Packet::operator +(const Packet &p)
{
Packet res(flags, length + p.length);
memcpy(res.data, data, length);
memcpy(&(res.data[length]), p.data, p.length);
return res;
}
int DataLink::start()
{
if(!started)
{
hal::thread_start(this, &DataLink::com_thread, "datalink/com-thread");
hal::thread_start(this, &DataLink::client_thread, "datalink/client-thread");
started = true;
}
return 0;
}
DataLink::DataLink(IOStream *s, uint32_t max_packet_length)
: cstream(s), packets(8)
{
log.setup("datalink");
do_terminate = false;
stream = s;
started = false;
packet_counter = 0;
this->max_packet_length = max_packet_length;
buffer = (uint8_t*) malloc(max_packet_length);
if(buffer == nullptr)
{
erreur("Malloc failed (%d).", max_packet_length);
}
}
DataLink::~DataLink()
{
infos("delete.");
if(started)
{
/* Tell the two threads that they must terminate */
do_terminate = true;
/* To unblock the first thread, if waiting for ack */
signal_ack.raise();
/* Push some data in the FIFO to unblock the first thread */
Packet p;
if(!packets.full())
packets.push(p);
/* Wait until first thread is finished. */
if(signal_terminated1.wait(500))
erreur("Unable to terminate thread 1.");
/* Push some data in the rx queue to unblock the second thread */
for(unsigned int i = 0; i < 1000; i++)
cstream.putc(0xff);
/* Wait until second thread is finished. */
if(signal_terminated2.wait(500))
erreur("Unable to terminate thread 2.");
infos("Threads killed.");
}
free(buffer);
}
int DataLink::wait_ack(uint16_t packet_number, uint16_t timeout)
{
for(;;)
{
// Attente réception acquittement
//infos("Waiting ack %d timeout = %d ms.", packet_number, timeout);
if(signal_ack.wait(timeout) != 0)
{
return -1;
}
if(do_terminate)
{
return -1;
}
signal_ack.clear();
if(ack_packet_number == packet_number)
{
//::LeaveCriticalSection(&mutex_ack);
mutex_ack.unlock();
return 0;
}
else
{
//::LeaveCriticalSection(&mutex_ack);
mutex_ack.unlock();
erreur("Bad packet number for ack %d != %d.", ack_packet_number, packet_number);
//continue;
return 0;
}
}
// not reached
return -1;
}
int DataLink::put_packet(const Packet &p, uint16_t timeout)
{
/*uint32_t i;*/
uint8_t nb_tries = 0;
int status = -1;
signal_ack.clear();
mutex_put.lock();
//infos("put_packet(flags = 0x%x, len = %d, timeout = %d).", p.flags, p.length, timeout);
do
{
if(p.flags & FLAG_ACK)
{
erreur("Acq bit already set.");
mutex_put.unlock();
return -1;
}
nb_tries++;
mutex_tx.lock();
cstream.start_tx();
cstream.putc(p.flags);
cstream.putc(packet_counter);
uint32_t n = p.length;
if(n > max_packet_length)
{
erreur("Packet too long: %d > %d.", n, max_packet_length);
n = max_packet_length;
}
//cstream.putw(n);
// TODO: ...
/*for(i = 0; (i < p.length) && (i < max_packet_length); i++)
cstream.putc(p.data[i]);*/
ByteArray ba;
ba.putl(n);
cstream.put(ba);
cstream.write(p.data, n);
uint16_t tcrc = cstream.get_current_tx_crc();
cstream.flush();
mutex_tx.unlock();
//verbose("wait ack...");
status = wait_ack(packet_counter, timeout);
//verbose("ack = ...");
if(status != 0)
{
erreur("Failed to get ACK (%d).", nb_tries);
infos("failed packet length = %d.", p.length);
infos("sent crc = %x.", tcrc);
//infos("failed tx packet:\n%s\n", p.to_string().c_str());
/*FILE *tmp = fopen("./tx_fail.txt", "wt");
fprintf(tmp, "%s", p.to_string().c_str());
fclose(tmp);*/
//exit(-1);
if(nb_tries > 2)
{
erreur("Aborting request.");
break;
}
}
} while(status != 0);
packet_counter = (packet_counter + 1) % 256;
mutex_put.unlock();
if(status != 0)
status = -1;
return status;
}
void DataLink::client_thread()
{
for(;;)
{
//infos("waiting new packet for client..");
Packet p = packets.pop();
if(do_terminate)
{
signal_terminated1.raise();
infos("client thread terminated.");
return;
}
//infos("new packet >> higher layer.");
CProvider<Packet>::dispatch(p);
}
}
void DataLink::com_thread()
{
//infos("Com thread started.");
for(;;)
{
uint8_t flags;
int retcode;
start:
// Reset CRC
cstream.start_rx();
//trace_verbeuse("Ready...");
retcode = cstream.getc(0);
if(do_terminate)
{
infos("com thread terminated.");
signal_terminated2.raise();
return;
}
if(retcode == -1)
{
// (can occur during disconnection)
infos("Timeout from lower layer");
signal_terminated2.raise();
return;
}
flags = (uint8_t) (retcode & 0xff);
//infos("Got flags = %x.", flags);
retcode = cstream.getc(200);
if(retcode == -1)
{
erreur("cnt timeout");
continue;
}
if(do_terminate)
{
infos("com thread terminated.");
signal_terminated2.raise();
return;
}
uint8_t pack_cnt = (uint8_t) (retcode & 0xff);
# if 0
//infos("Got cnt = %x.", pack_cnt);
{
retcode = cstream.getc(50);
if(retcode == -1)
{
erreur("len timeout 1");
continue;
}
r2 = cstream.getc(50);
if(r2 == -1)
{
anomaly("len timeout 2");
continue;
}
}
uint16_t len = (((uint16_t) (retcode & 0xff)) << 8) | ((uint16_t) (r2 & 0xff));
# endif
uint32_t len;
uint8_t tb_len[4];
if(cstream.read(tb_len, 4, 50) != 4)
{
erreur("len timeout");
continue;
}
ByteArray ba(tb_len, 4);
len = ba.popl();
if(len > this->max_packet_length)
{
if(do_terminate)
{
infos("com thread terminated.");
signal_terminated2.raise();
return;
}
else
{
avertissement("Length too long: %d (= 0x%x), doterm = %d",
len, len, do_terminate);
stream->discard_rx_buffer();
utils::hal::sleep(20);
}
continue;
}
//verbose("Got type = 0x%x, len = %d.", flags, len);
/* Acquittement ? */
if(flags & FLAG_ACK)
{
// Check CRC
if(cstream.check_crc() == 0)
{
//infos("ACK received.");
//::EnterCriticalSection(&mutex_ack);
ack_packet_number = pack_cnt;
signal_ack.raise();
//infos("rx ack %d", ack_packet_number);
}
else
erreur("Bad ACK CRC.");
}
else
{
Packet p(flags, len);
int timout = len / 2;
if(timout < 100)
timout = 100;
uint32_t rlen;
//verbose("read %d bytes..", len);
rlen = cstream.read(p.data, len, timout);
//verbose("done.");
if(rlen != len)
{
erreur("data timeout (%d ms, %d bytes), rlen = %d.", timout, len, rlen);
stream->discard_rx_buffer();
goto start;
}
//infos("check CRC..");
if(cstream.check_crc() == 0)
{
//infos("tx ack.");
// Send ACK
mutex_tx.lock();
cstream.start_tx();
cstream.putc(FLAG_ACK);
cstream.putc(pack_cnt);
cstream.putc(0x00);
cstream.putc(0x00);
cstream.putc(0x00);
cstream.putc(0x00);
//verbose("ack flush..");
cstream.flush();
//verbose("done flush.");
mutex_tx.unlock();
// Dispatch to higher layer
if(packets.full())
avertissement("Output fifo is full.");
//verbose("Packet to fifo..");
packets.push(p);
}
else
{
erreur("Bad data crc, len = %d.", len);
//infos("Damaged packet:\n%s\n", p.to_string().c_str());
FILE *tmp = fopen("./rx_fail.txt", "wt");
fprintf(tmp, "%s", p.to_string().c_str());
fclose(tmp);
//exit(-1);
stream->discard_rx_buffer();
ComError ce;
CProvider<ComError>::dispatch(ce);
}
}
}
}
void Transport::on_event(const ComError &ce)
{
infos("event(ComError)");
CProvider<ComError>::dispatch(ce);
}
Transport::Transport(DataLink *stream, uint32_t tx_segmentation, uint32_t max_packet_length)
{
log.setup("transport");
rx_buffer_offset = 0;
this->max_packet_length = max_packet_length;
this->tx_segmentation = tx_segmentation;
this->stream = stream;
buffer = (uint8_t *) malloc(max_packet_length);
if(buffer == nullptr)
{
erreur("Failed to allocate transport rx buffer (%d kbytes).", max_packet_length / 1024);
}
stream->CProvider<Packet>::add_listener(this);
stream->CProvider<ComError>::add_listener(this);
}
Transport::~Transport()
{
infos("Delete..");
stream->CProvider<Packet>::remove_listener(this);
stream->CProvider<ComError>::remove_listener(this);
free(buffer);
}
int Transport::put_packet(const Packet &pin, void (*notification)(float percent))
{
int status;
uint32_t offset = 0;
mutex.lock();
//verbose("put_packet(size=%d)...", pin.length);
status = 0;
while(offset < pin.length)
{
uint8_t flags = pin.flags;
/* Nb donn�es utiles */
uint16_t size = tx_segmentation - 3;
/* Last frame ? */
if(pin.length - offset < size)
{
size = pin.length - offset;
flags |= FLAG_LF;
}
Packet p(flags, size + 3);
/* Offset */
p.data[0] = (offset >> 16) & 0xff;
p.data[1] = (offset >> 8) & 0xff;
p.data[2] = offset & 0xff;
/*for(i = 0; i < size; i++)
p.data[3+i] = pin.data[i+offset];*/
memcpy(&(p.data[3]), &(pin.data[offset]), size);
//strace("write packet %d/%d: %d bytes.", offset, pin.length, size);
status = stream->put_packet(p);
if(status != 0)
{
erreur("put_packet() failed: status = %d.\n", status);
mutex.unlock();
return status;
}
offset += size;
float percent = ((float) offset) / pin.length;
if(notification != nullptr)
notification(percent);
}
mutex.unlock();
//infos("put_packet() successfully done\n");
return status;
}
void Transport::on_event(const Packet &p)
{
uint32_t i;
uint32_t offset;
//trace_verbeuse("got packet.");
offset =
((((uint32_t) p.data[0]) << 16) & 0x00ff0000)
| ((((uint32_t) p.data[1]) << 8) & 0x0000ff00)
| ((((uint32_t) p.data[2]) ) & 0x000000ff);
if(offset < rx_buffer_offset)
{
erreur("offset < rx_buffer_offset (%d < %d).", offset, rx_buffer_offset);
rx_buffer_offset = offset;
}
else if(offset > rx_buffer_offset)
{
erreur("offset > rx_buffer_offset (%d > %d).", offset, rx_buffer_offset);
return;
}
else
{
//infos("Got offset = %d.", offset);
}
if(((rx_buffer_offset + p.length) - 3) > max_packet_length)
{
erreur("Received packet too big for receive window (mpl = %d bytes, o = %d.)",
max_packet_length, (rx_buffer_offset + p.length) - 3);
avertissement("Aborting reception of the packet.");
rx_buffer_offset = 0;
return;
}
rx_buffer_offset = offset;
for(i = 3; i < p.length; i++)
buffer[i+rx_buffer_offset-3] = p.data[i];
rx_buffer_offset += p.length - 3;
if(p.flags & FLAG_LF)
{
Packet pout(p.flags & ~FLAG_LF, rx_buffer_offset);
memcpy(pout.data, buffer, rx_buffer_offset);
//infos("Got last frame. size = %d bytes.", rx_buffer_offset);
CProvider<Packet>::dispatch(pout);
rx_buffer_offset = 0;
}
}
Session::Session(Transport *device, uint32_t max_buffer_size):
client_packets(8)
{
log.setup("session");
do_terminate = false;
this->max_buffer_size = max_buffer_size;
service_waited = 0xff;
tp = device;
session_error = false;
if(tp != nullptr)
tp->CProvider<Packet>::add_listener(this);
hal::thread_start(this, &Session::client_thread, "session/client-thread");
CListener<Packet>::listener_name = "session(packet)";
CListener<ComError>::listener_name = "session(comError)";
}
void Session::set_transport(Transport *device)
{
tp = device;
tp->CProvider<Packet>::add_listener(this);
}
Session::~Session()
{
infos("Delete..");
tp->CProvider<Packet>::remove_listener(this);
signal_terminated.clear();
do_terminate = true;
/* Wake-up client thread */
Packet p;
client_packets.push(p);
signal_terminated.wait();
infos("Thread killed.");
}
void Session::client_thread()
{
uint32_t i, j;
uint8_t service, cmde;
for(;;)
{
//infos("client::pop...");
Packet p = client_packets.pop();
if(do_terminate)
{
infos("client thread: terminate.");
signal_terminated.raise();
/* kill thread */
return;
}
service = p.data[0];
cmde = p.data[1];
//trace_verbeuse("client::pop ok.");
for(i = 0; i < cmde_handlers.size(); i++)
{
CmdeStorage cs = cmde_handlers[i];
if((cs.service == service) && (cs.cmde == cmde))
{
ByteArray in(&(p.data[2]), p.length - 2), out;
//verbose("Higher layer service..");
int retcode = cs.functor->call(in, out);
//verbose("Higher layer service done, res = %d.", retcode);
if(in.size() > 0)
{
if(retcode == 0)
erreur("Not all data handled by higher layer (%d bytes remaining).", in.size());
else
avertissement("Not all data handled by higher layer (%d bytes remaining).", in.size());
}
/* Send response */
Packet p2(out.size() + 2 + 4);
p2.flags = FLAG_RSP;
p2.data[0] = service;
p2.data[1] = cmde;
p2.data[2] = (retcode >> 24) & 0xff;
p2.data[3] = (retcode >> 16) & 0xff;
p2.data[4] = (retcode >> 8) & 0xff;
p2.data[5] = (retcode ) & 0xff;
for(j = 0; j < out.size(); j++)
p2.data[j+2+4] = out[j];
int res = tp->put_packet(p2, nullptr);
if(res != 0)
{
erreur("Error 0x%x while putting response.", res);
break;
}
break;
} // if service ok
} // for(i = ...)
if(i != cmde_handlers.size())
continue;
else
{
erreur("Got unwaited data (service %x, cmde %x). Dispatching to higher layer..", service, cmde);
dispatch(p);
}
} // for(;;)
}
void Session::on_event(const ComError &ce)
{
infos("event(ComError)");
/*if(service_waited != 0xff)
{
EnterCriticalSection(&response_lock);
service_waited = 0xff;
session_error = true;
::SetEvent(signal_answer);
}*/
}
void Session::on_event(const Packet &p)
{
//uint8_t service, cmde;
if(p.length < 2)
{
erreur("Invalid packet size received: %d.", p.length);
return;
}
//service = p.data[0];
//cmde = p.data[1];
//infos("Rx packet: flags=0x%x, service=%x, cmde=%x, len=%d...", p.flags, service, cmde, p.length - 2);
// Handle answers
if(p.flags & FLAG_RSP)
{
if(p.length < 2 + 4)
{
erreur("Invalid packet size (missing result code).");
return;
}
// Answer to the last request ?
if(service_waited == p.data[0])
{
response_lock.lock();
service_waited = 0xff;
response = p;
response.flags &= 0x0f;
signal_answer.raise();
//infos("Got answer.");
}
else
{
erreur("Unwaited answer: %d bytes.", p.length);
//infos("%s", p.to_string().c_str());
}
}
else
{
//infos(">> To client FIFO.");
if(client_packets.full())
avertissement("client fifo is full.");
client_packets.push(p);
}
}
int Session::request(uint8_t service, uint8_t cmde,
const ByteArray &data_in,
ByteArray &data_out,
uint32_t timeout,
void (*notification)(float percent))
{
Packet p2;
Packet p(data_in.size());
for(unsigned int i = 0; i < data_in.size(); i++)
p.data[i] = data_in[i];
int res = request(service, cmde, p, p2, timeout, notification);
if(res == 0)
data_out = ByteArray(p2.data, p2.length);
else
{
avertissement("Request failed, status = %d.", res);
data_out.clear();
}
return res;
}
int Session::request(uint8_t service, uint8_t cmde, const ByteArray &data_in, uint32_t timeout)
{
ByteArray out;
return request(service, cmde, data_in, out, timeout, nullptr);
}
int Session::request(uint8_t service,
uint8_t cmde,
const Packet &data_in, Packet &data_out,
uint32_t timeout,
void (*notification)(float percent))
{
uint32_t i;
int res;
request_lock.lock();
//infos("request(service=0x%x, cmde 0x%x, tx_len = %d, timeout = %d).", service, cmde, data_in.length, timeout);
service_waited = service;
//p.flags |= FLAG_REQUEST;
Packet p(data_in.length + 2);
p.data[0] = service;
p.data[1] = cmde;
for(i = 0; i < data_in.length; i++)
p.data[i+2] = data_in.data[i];
res = tp->put_packet(p, notification);
if(res != 0)
{
request_lock.unlock();
service_waited = 0xff;
erreur("Error 0x%x while putting request.", res);
return res;
}
//infos("Put done, now waiting read answer...");
if(signal_answer.wait(timeout) == 0)
{
service_waited = 0xff;
signal_answer.clear();
request_lock.unlock();
/* Remove service_id, cmde_id and status */
data_out = Packet(response.length - 6);
int status = (((int) response.data[2] << 24) & 0xff000000)
| (((int) response.data[3] << 16) & 0x00ff0000)
| (((int) response.data[4] << 8) & 0x0000ff00)
| (((int) response.data[5]) & 0x000000ff);
for(i = 0; i < response.length - 6; i++)
data_out.data[i] = response.data[i+6];
response_lock.unlock();
if(session_error)
{
service_waited = 0xff;
session_error = false;
erreur("Session error.");
return -1;
}
//infos("Read: status = %d.", status);
return status;
}
else
{
service_waited = 0xff;
erreur("No response.");
// timeout
request_lock.unlock();
return -1;
}
}
int Session::register_cmde(uint8_t service, uint8_t cmde, CmdeFunctor *functor)
{
CmdeStorage storage;
storage.service = service;
storage.cmde = cmde;
storage.functor = functor;
cmde_handlers.push_back(storage);
return 0;
}
}
}
| 21,810
|
C++
|
.cc
| 832
| 21.233173
| 114
| 0.585793
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,961
|
fdserial.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/fdserial.cc
|
/**
* This file is part of LIBSERIAL.
*
* LIBSERIAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBSERIAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBSERIAL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#include "comm/serial.hpp"
#include "cutil.hpp"
#include <stdio.h>
#include <assert.h>
#ifdef WIN
#ifndef VSTUDIO
#include <unistd.h>
#else
#include <process.h>
#endif
#include <windows.h>
#else
#endif
#include <sys/types.h>
#include <malloc.h>
#define DBG(aaa)
namespace utils
{
namespace comm
{
FDSerial::FDSerial()
{
serial_is_connected = false;
input_buffer = (char*) malloc(FD_BUFFER_SIZE);
output_buffer = (char*) malloc(FD_BUFFER_SIZE);
assert(input_buffer);
assert(output_buffer);
hal::thread_start(this, &FDSerial::com_thread, "fdserial/com-thread");
}
FDSerial::~FDSerial()
{
disconnect();
}
void FDSerial::putc(char c)
{
if(!serial_is_connected)
{
erreur("putc while not connected.");
return;
}
while(output_buffer_size >= FD_BUFFER_SIZE-1)
hevt_tx_done.wait();
mutex_output.lock();
output_buffer[(output_buffer_offset+output_buffer_size)%FD_BUFFER_SIZE] = c;
output_buffer_size++;
mutex_output.unlock();
hevt_tx_available.raise();
}
void FDSerial::flush()
{
for(;;)
{
mutex_output.lock();
if(output_buffer_size == 0)
{
printf("Flush : obs = 0.\n");
mutex_output.unlock();
return;
}
mutex_output.unlock();
printf("flush / tx size = %d.\n", output_buffer_size);
hevt_tx_done.wait();
hevt_tx_done.clear();
}
//fflush(hfile);
//FlushFileBuffers(hfile);
}
unsigned int FDSerial::nb_rx_available()
{
return input_buffer_size;
}
void FDSerial::discard_rx_buffer()
{
infos("Vidange de la FIFO de réception...");
mutex_input.lock();
if(input_buffer_size > 0)
{
input_buffer_offset = (input_buffer_offset + input_buffer_size) % FD_BUFFER_SIZE;
input_buffer_size = 0;
}
/*while(input_buffer_size > 0)
{
input_buffer_offset = (input_buffer_offset + input_buffer_size) % FD_BUFFER_SIZE;
input_buffer_size = 0;
mutex_input.unlock();
hal::sleep(100);
mutex_input.lock();
}*/
mutex_input.unlock();
infos("Ok.");
}
void FDSerial::debloquer_reception()
{
trace_verbeuse("FDSerial::%s", __func__);
signal_debloquer_reception.raise();
}
int FDSerial::getc(int timeout)
{
if(!serial_is_connected)
{
infos("Read suspended until serial port is opened.");
while(!serial_is_connected)
{
hevt_connection.wait();
hevt_connection.clear();
infos("+");
}
infos("Read enabled.");
}
std::vector<utils::hal::Signal *> sigs;
sigs.push_back(&hevt_rx_available);
sigs.push_back(&signal_debloquer_reception);
mutex_input.lock();
while(input_buffer_size == 0)
{
mutex_input.unlock();
//utils::verbose("GETC WAIT %d ms...", timeout);
int res = utils::hal::Signal::wait_multiple(timeout, sigs);
//utils::verbose("GETC RES = %d.", res);
if((res == 1) || (signal_debloquer_reception.is_raised()))
{
trace_verbeuse("FDSerial::getc: reception annulee sur ordre.");
return -1;
}
if(res != 0)
return -1;
//if(hevt_rx_available.wait(timeout))
// return -1;
mutex_input.lock();
}
char c = input_buffer[input_buffer_offset];
input_buffer_offset = (input_buffer_offset + 1) % FD_BUFFER_SIZE;
input_buffer_size--;
mutex_input.unlock();
return (((int) c) & 0xff);
}
int FDSerial::connect(std::string port_name,
int baudrate,
serial_parity_t parity,
bool flow_control)
{
# ifdef LINUX
return -1;
# else
try
{
infos("Connection %s @ %d bauds, ctrl de flux = %s...",
port_name.c_str(), baudrate, flow_control ? "oui" : "non");
char port[50];
sprintf(port, "%s", port_name.c_str());
if(strlen(port) > 4)
{
sprintf(port, "%s%s", "\\\\.\\", port_name.c_str());
infos("Added prefix.");
}
if(serial_is_connected)
{
erreur("Already connected.");
return 0;
}
# ifdef VSTUDIO
wchar_t temp[100];
mbstowcs(temp, port, 100);
# endif
hfile = ::CreateFile(
#ifdef VSTUDIO
temp,
#else
port,
#endif
GENERIC_READ|GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if(hfile == nullptr)
{
erreur("CreateFile error.");
return -1;
}
if(hfile == INVALID_HANDLE_VALUE)
{
int err = ::GetLastError();
avertissement("Erreur CreateFile (erreur = %d = 0x%x).", err, err);
return -1;
}
infos("CreateFile ok.");
if(!::SetCommMask(hfile, EV_RXCHAR))
{
int err = ::GetLastError();
avertissement("Erreur SetCommMask (erreur = %d = 0x%x).", err, err);
return -1;
}
infos("Set Comm mask ok.");
COMMTIMEOUTS cto = { 0, 0, 0, 0, 0 };
if(!SetCommTimeouts(hfile, &cto))
{
int err = ::GetLastError();
avertissement("Unable to set comm timeouts (erreur = %d = 0x%x).", err, err);
return -1;
}
infos("Set Comm timeouts ok.");
DCB dcb;
memset(&dcb,0,sizeof(dcb));
// set DCB to configure the serial port
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = baudrate;
switch(parity)
{
case PAR_NONE:
dcb.Parity = NOPARITY;
dcb.fParity = 0;
break;
case PAR_EVEN:
dcb.Parity = EVENPARITY;
dcb.fParity = 1;
break;
case PAR_ODD:
dcb.Parity = ODDPARITY;
dcb.fParity = 1;
break;
}
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = flow_control ? DTR_CONTROL_HANDSHAKE : DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = 0;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fOutX = 0;
dcb.fInX = 0;
/* ----------------- misc parameters ----- */
dcb.fErrorChar = 0;
dcb.fBinary = 1;
dcb.fNull = 0;
dcb.fAbortOnError = 0;
dcb.wReserved = 0;
dcb.XonLim = 2;
dcb.XoffLim = 4;
dcb.XonChar = 0x13;
dcb.XoffChar = 0x19;
dcb.EvtChar = 0;
// set DCB
if(!SetCommState(hfile,&dcb))
{
erreur("Error while setting comm state.");
CloseHandle(hfile);
return -1;
}
infos("Set DCB ok.");
HANDLE h_evt_overlapped;
h_evt_overlapped = ::CreateEvent(0,true,false,0);
memset(&ov,0,sizeof(ov));
ov.hEvent = h_evt_overlapped;
assert(ov.hEvent);
input_buffer_offset = 0;
input_buffer_size = 0;
output_buffer_offset = 0;
output_buffer_size = 0;
hevt_start.raise();
serial_is_connected = true;
hevt_connection.raise();
}
catch(...)
{
return -1;
}
return 0;
# endif
}
bool FDSerial::is_connected()
{
return serial_is_connected;
}
void FDSerial::disconnect()
{
if(serial_is_connected)
{
infos("Arret thread de reception fdserial...");
hevt_stop.raise();
hevt_stopped.wait();
infos("Thread arrete.");
# ifdef LINUX
# else
infos("Vidange des tampons rx/tx...");
::FlushFileBuffers(hfile);
infos("Fermeture handle...");
CloseHandle(hfile);
# endif
serial_is_connected = false;
infos("Deconnexion terminee.");
}
}
void FDSerial::com_thread(void)
{
infos("Com thread started.");
hevt_start.wait();
infos("Com thread resumed.");
# ifdef LINUX
# else
bool is_reading;
for(;;)
{
start:
is_reading = true;
// par d�faut: lance une lecture
char c;
DWORD nb_read;
if (!::ReadFile(hfile,&c,1,&nb_read,&ov))
{
DBG(printf("Read deffered.\n"));
DBG(fflush(stdout));
}
else
{
DBG(printf("Read succeedded immediatly : '%x'!!!\n", (unsigned char) c));
DBG(fflush(stdout));
mutex_input.lock();
if(input_buffer_size >= FD_BUFFER_SIZE)
{
erreur("Input buffer overflow.");
}
else
{
input_buffer[(input_buffer_offset+input_buffer_size)%FD_BUFFER_SIZE] = c;
input_buffer_size++;
}
mutex_input.unlock();
hevt_rx_available.raise();
goto start;
}
HANDLE ahWait[3];
ahWait[0] = ov.hEvent;
ahWait[1] = hevt_stop.get_handle();
ahWait[2] = hevt_tx_available.get_handle();
wait_event:
switch (::WaitForMultipleObjects(sizeof(ahWait)/sizeof(*ahWait),ahWait,FALSE,INFINITE))
{
case WAIT_OBJECT_0:
{
if(is_reading)
{
DBG(printf("Evt overlapped, on peut faire maintenant un vrai 'read'...\n");
fflush(stdout);)
DWORD nb_readen;
if(!::GetOverlappedResult(hfile,&ov,&nb_readen,FALSE))
erreur("Error %d\n", GetLastError());
else
{
if(nb_readen > 0)
{
mutex_input.lock();
if(input_buffer_size >= FD_BUFFER_SIZE)
{
erreur("Input buffer overflow.");
}
else
{
input_buffer[(input_buffer_offset+input_buffer_size)%FD_BUFFER_SIZE] = c;
input_buffer_size++;
if(nb_readen > 1)
{
erreur("nb readen = %d.", nb_readen);
}
}
mutex_input.unlock();
hevt_rx_available.raise();
DBG(printf("Read %d bytes succeeded : '%x'.\n", nb_readen, (unsigned char) c));
DBG(fflush(stdout));
}
}
}
else
{
DWORD nb_wrote;
if(!::GetOverlappedResult(hfile,&ov,&nb_wrote,FALSE))
{
erreur("Error write %d\n", GetLastError());
}
else
{
bool relance = false;
// Termin� une �criture, on en lance �ventuellement une autre
mutex_output.lock();
if(output_buffer_size > 0)
relance = true;
mutex_output.unlock();
DBG(printf("Evt overlapped, le write %d bytes est termin�...\n", nb_wrote));
DBG(fflush(stdout));
if(relance)
{
DBG(printf("On relance une �criture...\n"));
DBG(fflush(stdout));
hevt_tx_available.raise();
}
else
{
hevt_tx_done.raise();
//::SetEvent(hevt_tx_done);
}
}
DBG(fflush(stdout));
}
break;
}
case WAIT_OBJECT_0+1:
{
hevt_stop.clear();
infos("Recu stop: PurgeComm...");
::PurgeComm(hfile, PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR);
//assert(CancelIo(hfile));
//hal::sleep(100);
infos("Cancel io...");
CancelIo(hfile);
hevt_stopped.raise();
infos("Serial port stopped.");
hevt_start.wait();
infos("Received Start");
break;
}
case WAIT_OBJECT_0+2:
{
DBG(printf("Evt write\n"));
DBG(fflush(stdout));
hevt_tx_available.clear();
if(is_reading)
{
DWORD n = 0;
// Attention perte d'un octet en lecture
////////assert(CancelIo(hfile));
/////////////////////////
/// V�rifie rien � lire sur l'entr�e avant d'annuler l'�criture
DWORD nb_readen;
if(::GetOverlappedResult(hfile,&ov,&nb_readen,FALSE))
{
if(nb_readen > 0)
{
mutex_input.lock();
if(input_buffer_size >= FD_BUFFER_SIZE)
erreur("Input buffer overflow.");
else
{
input_buffer[(input_buffer_offset+input_buffer_size)%FD_BUFFER_SIZE] = c;
input_buffer_size++;
if(nb_readen > 1)
erreur("nb readen = %d.", nb_readen);
}
mutex_input.unlock();
hevt_rx_available.raise();
}
}
else
assert(CancelIo(hfile));
/////////////////////////
mutex_output.lock();
// Ecriture en deux temps ?
unsigned long lg = output_buffer_size;
if(output_buffer_offset + output_buffer_size > FD_BUFFER_SIZE)
lg = FD_BUFFER_SIZE - output_buffer_offset;
if(!WriteFile(hfile, &(output_buffer[output_buffer_offset]), lg, &n, &ov))
{
DBG(printf("Write deffered.\n"));
DBG(fflush(stdout));
is_reading = false;
output_buffer_offset = (output_buffer_offset + lg) % FD_BUFFER_SIZE;
output_buffer_size -= lg;
mutex_output.unlock();
if(output_buffer_size == 0)
hevt_tx_done.raise();
goto wait_event;
}
else
{
output_buffer_offset = (output_buffer_offset + lg) % FD_BUFFER_SIZE;
output_buffer_size -= lg;
if(output_buffer_size == 0)
hevt_tx_done.raise();
//::SetEvent(hevt_tx_done);
mutex_output.unlock();
DBG(printf("Write finished immediatly.\n"));
DBG(fflush(stdout));
}
}
// On est d�j� en train d'�crire: on fait rien
else
{
DBG(printf("Write alors qu'on �crit d�j�.\n"));
DBG(fflush(stdout));
goto wait_event;
}
break;
}
default:
{
erreur("Evt inconnu");
break;
}
}
}
# endif
}
}
}
| 13,841
|
C++
|
.cc
| 522
| 20.605364
| 91
| 0.578967
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,962
|
iostreams.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/iostreams.cc
|
#include "comm/iostreams.hpp"
#include <malloc.h>
namespace utils
{
namespace comm
{
int InputStream::read(model::ByteArray &ba, uint32_t length, int timeout)
{
uint8_t *buf = (uint8_t *) malloc(length);
ba.clear();
int nr = read(buf, length, timeout);
if(nr > 0)
ba.put(buf, nr);
free(buf);
return nr;
}
// a cos theta + b sin theta = d
// a² cos² + b² sin² = d²
// a² cos² + a² sin² + (b² - a²) sin² = d²
// sin² = (d² - a²) / (b² - a²)
//
int InputStream::read(uint8_t *buffer, uint32_t length, int timeout)
{
uint32_t i;
int retcode;
for(i = 0; i < length; i++)
{
retcode = getc(timeout);
if(retcode == -1)
return i;
buffer[i] = (uint8_t) (retcode & 0xff);
}
return length;
}
void OutputStream::put(const model::ByteArray &ba)
{
if(ba.size() == 0)
return;
unsigned char *tmp = (unsigned char *) malloc(ba.size());
for(unsigned int i = 0; i < ba.size(); i++)
tmp[i] = ba[i];
write(tmp, ba.size());
free(tmp);
}
unsigned short InputStream::getw()
{
unsigned char c1 = (unsigned char) getc();
unsigned char c2 = (unsigned char) getc();
return (((unsigned short) c1) << 8) | ((unsigned short) c2 & 0x00ff);
}
void OutputStream::putw(unsigned short s)
{
putc((s >> 8) & 0xff);
putc(s & 0xff);
}
void InputStream::discard_rx_buffer()
{
while(getc(1) != -1)
;
}
void OutputStream::put_string(std::string s)
{
const char *ss = s.c_str();
put_data(ss, s.size());
}
void InputStream::get_data(char *buffer, int len)
{
for(int i = 0; i < len; i++)
buffer[i] = getc();
}
int InputStream::get_line(std::string &res, int timeout)
{
res = "";
int retcode;
for(;;)
{
retcode = getc(timeout);
if(retcode == -1)
return -1;
char c[2];
c[0] = (char) retcode;
c[1] = 0;
if(c[0] == '\n')
return 0;
res += std::string((const char *) &c[0]);
}
/* not reached */
return 0;
}
void OutputStream::put_data(const void *buffer_, int len)
{
const char *buffer = (const char *) buffer_;
for(int i = 0; i < len; i++)
putc(buffer[i]);
}
void OutputStream::write(const uint8_t *buffer, uint32_t len)
{
for(uint32_t i = 0; i < len; i++)
putc(buffer[i]);
}
}
}
| 2,223
|
C++
|
.cc
| 102
| 18.882353
| 73
| 0.610365
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,963
|
serial-enumeration.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/serial-enumeration.cc
|
#include "../../include/journal.hpp"
#include "comm/serial.hpp"
#ifdef WIN
#include <windows.h>
#endif
namespace utils
{
namespace comm
{
#ifdef WIN
int reg_open_subkey_at(HKEY hKey, uint32_t index, REGSAM samDesired,
PHKEY phkResult, std::string *subkey_name = nullptr)
{
uint32_t size = 256;
char *buffer;
int errcode;
DWORD cbSubkeyName = 128 * sizeof(TCHAR);
FILETIME filetime;
/* loop asking for the subkey name til we allocated enough memory */
for (;;)
{
buffer = (char *) malloc(size);
if(buffer == nullptr)
{
return -1;
}
errcode = RegEnumKeyEx(hKey, index, buffer, &cbSubkeyName,
0, nullptr, nullptr, &filetime);
if(errcode == ERROR_MORE_DATA)
{
free(buffer);
size *= 2;
continue;
}
if(errcode != 0)
{
if(errcode != ERROR_NO_MORE_ITEMS)
erreur("RegEnumKeyEx error %d, index = %d.\n", errcode, index);
free(buffer);
return errcode;
}
break;
}
if(subkey_name != nullptr)
*subkey_name = std::string(buffer);
errcode = RegOpenKeyEx(hKey, buffer, 0, samDesired, phkResult);
if(errcode != 0)
erreur("RegOpenKeyEx error %d.\n", errcode);
free(buffer);
return errcode;
}
int reg_query_string_value(HKEY hKey, std::string name, std::string &value)
{
uint32_t size = 256;
int errcode;
char *buffer;
for(;;)
{
buffer = (char *) malloc(size);
if(buffer == nullptr)
{
return -1;
}
errcode = RegQueryValueEx(hKey, name.c_str(), nullptr, nullptr,
(uint8_t *) buffer, (DWORD*)&size);
if(errcode == 0)
{
value = std::string(buffer);
free(buffer);
return 0;
}
else if(errcode == ERROR_MORE_DATA)
{
size *= 2;
free(buffer);
continue;
}
free(buffer);
return -1;
}
}
#endif
int Serial::enumerate(std::vector<SerialInfo> &infos)
{
# ifdef LINUX
return 0;
# else
std::vector<SerialInfo> tmp;
OSVERSIONINFO os;
uint32_t i, j, k, errcode;
HKEY key_enum, key1, key2, key3;
std::string port_name, friendly_name, technology;
infos("Serial port enumeration...");
memset(&os, 0, sizeof(os));
os.dwOSVersionInfoSize = sizeof(os);
GetVersionEx(&os);
if ((os.dwPlatformId != VER_PLATFORM_WIN32_NT) || (os.dwMajorVersion <= 4))
{
erreur("Unsupported os.");
return -1;
}
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CURRENTCONTROLSET\\ENUM", 0,
KEY_ENUMERATE_SUB_KEYS, &key_enum) != 0)
{
erreur("enumerate: RegOpenKeyEx error.");
return -1;
}
for(i = 0;; i++)
{
errcode = reg_open_subkey_at(key_enum, i, KEY_ENUMERATE_SUB_KEYS, &key1, &technology);
if(errcode == ERROR_NO_MORE_ITEMS)
break;
else if(errcode != 0)
{
erreur("enumerate: reg_open_subkey_at(1) error.");
return -1;
}
for(j = 0; ; j++)
{
errcode = reg_open_subkey_at(key1, j, KEY_ENUMERATE_SUB_KEYS, &key2, nullptr);
if(errcode == ERROR_NO_MORE_ITEMS)
break;
else if(errcode != 0)
{
erreur("enumerate: reg_open_subkey_at(2) error.");
RegCloseKey(key1);
RegCloseKey(key_enum);
return -1;
}
for(k = 0;; k++)
{
errcode = reg_open_subkey_at(key2, k, KEY_READ, &key3, nullptr);
if (errcode == ERROR_NO_MORE_ITEMS)
break;
else if(errcode != 0)
{
erreur("enumerate: reg_open_subkey_at(3) error.");
RegCloseKey(key1);
RegCloseKey(key2);
RegCloseKey(key_enum);
return -1;
}
char buf[50];
uint32_t bsize = 50;
if ((RegQueryValueEx(key3, "CLASS", nullptr, nullptr, (uint8_t*) buf, (DWORD*)&bsize) == 0)
&& (strcmp(buf, "PORTS")))
{
// Ok
}
else if ((RegQueryValueEx(key3, "CLASSGUID", nullptr, nullptr, (uint8_t*) buf,
(DWORD*)&bsize) == 0) && (strcmp(buf,
"{4D36E978-E325-11CE-BFC1-08002BE10318}")))
{
}
else
{
continue;
}
if(reg_query_string_value(key3, "PORTNAME", port_name) != 0)
{
HKEY key_dev_param;
if (RegOpenKeyEx(key3,
"DEVICE PARAMETERS",
0,
KEY_READ,
&key_dev_param) != 0)
{
continue;
}
if(reg_query_string_value(key_dev_param, "PORTNAME", port_name) != 0)
{
RegCloseKey(key_dev_param);
continue;
}
RegCloseKey(key_dev_param);
}
/* check if it is a serial port (instead of, say, a parallel port) */
if ((port_name[0] != 'C') || (port_name[1] != 'O') || (port_name[2]
!= 'M'))
continue;
reg_query_string_value(key3, "FRIENDLYNAME", friendly_name);
SerialInfo serial_info;
serial_info.name = port_name;
serial_info.complete_name = (friendly_name.size() == 0) ? serial_info.name : std::string(friendly_name);
serial_info.techno = technology;
tmp.push_back(serial_info);
RegCloseKey(key3);
} // for k
RegCloseKey(key2);
} // for j
RegCloseKey(key1);
} // for i
RegCloseKey(key_enum);
// Vérifie que les ports COM sont bien actifs
for(auto &si: tmp)
{
char port[50];
sprintf(port, "%s", si.name.c_str());
if(strlen(port) > 4)
{
sprintf(port, "%s%s", "\\\\.\\", si.name.c_str());
}
HANDLE h = ::CreateFile(
port,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(h == INVALID_HANDLE_VALUE)
{
avertissement("Enumeration : port COM [%s] non actif.", si.name.c_str());
}
else
{
infos("Enumeration : port COM [%s] actif.", si.name.c_str());
infos.push_back(si);
::CloseHandle(h);
}
}
return 0;
# endif
}
}
}
| 6,169
|
C++
|
.cc
| 226
| 20.128319
| 112
| 0.547655
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,964
|
btsocket_vsudio.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/btsocket_vsudio.cc
|
/** @file btsocket_vsudio.cc */
#include <stdafx.h>
#include <stdio.h>
#include <initguid.h>
#include <winsock2.h>
#include <ws2bth.h>
#include <strsafe.h>
#include <intsafe.h>
#include <stdio.h>
#include <Objbase.h>
#include "blue.h"
#include <string.h>
#include <cguid.h>
//static FILE *flog;
#define infos(...)
int _bt_server_start(SOCKET *socket_,
const char *service_name,
const char *comment)
{
//flog = fopen("bluelog.txt", "wt");
infos("Bluetooth socket server test, peripheral = '%s'.\n", "peripheral");
WSADATA m_data;
/* Load the winsock2 library */
if (WSAStartup(MAKEWORD(2,2), &m_data) != 0)
{
infos("wsastartup error.\n");
return -1;
}
SOCKET s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (s == INVALID_SOCKET)
{
infos("Could not create socket: error %d\n", WSAGetLastError());
return -1;
}
WSAPROTOCOL_INFO protocolInfo;
int protocolInfoSize = sizeof(protocolInfo);
if (0 != getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFO,
(char*)&protocolInfo, &protocolInfoSize))
{
infos("getsockopt: error %d\n", WSAGetLastError());
return -1;
}
SOCKADDR_BTH address;
int sa_len = sizeof(SOCKADDR_BTH);
address.addressFamily = AF_BTH;
address.btAddr = 0;
address.serviceClassId = GUID_nullptr;
address.port = BT_PORT_ANY;
sockaddr *pAddr = (sockaddr*)&address;
if (bind(s, pAddr, sizeof(SOCKADDR_BTH)))
{
infos("bind error %d\n", WSAGetLastError());
closesocket(s);
return -3;
}
if(listen(s, 10))//5))
{
infos("listen error %d\n", WSAGetLastError());
closesocket(s);
return -1;
}
// check which port were listening on
if(getsockname(s, (SOCKADDR*)&address, &sa_len))
{
infos("getsockname error %d\n", WSAGetLastError());
closesocket(s);
return -1;
}
infos("listening on RFCOMM port: %d\n" , address.port) ;
infos("Registering SDP service (METHOD 0)...\n");
WSAQUERYSET service;
memset(&service, 0, sizeof(service));
service.dwSize = sizeof(service);
service.lpszServiceInstanceName = strdup(service_name);
//_T("My Service");
service.lpszComment = strdup(comment);
//_T("My comment");
// UUID for SPP is 00001101-0000-1000-8000-00805F9B34FB
GUID serviceID = /*(GUID)*/SerialPortServiceClass_UUID;
service.lpServiceClassId = &serviceID;
service.dwNumberOfCsAddrs = 1;
service.dwNameSpace = NS_BTH;
CSADDR_INFO csAddr;
memset(&csAddr, 0, sizeof(csAddr));
csAddr.LocalAddr.iSockaddrLength = sizeof(SOCKADDR_BTH);
csAddr.LocalAddr.lpSockaddr = pAddr;//(LPSOCKADDR) &sa;
csAddr.iSocketType = SOCK_STREAM;
csAddr.iProtocol = BTHPROTO_RFCOMM;
service.lpcsaBuffer = &csAddr;
if (0 != WSASetService(&service, RNRSERVICE_REGISTER, 0))
{
infos("set service error:%d\n", WSAGetLastError());
closesocket(s);
return -6;
}
infos("Waiting for client connection...\n");
//fflush(flog);
// Sur la carte d'évaluation, faire :
// CALL 00:0A:3A:7F:24:69 1101 RFCOMM
# if 0
SOCKADDR_BTH sa2;
int size = sizeof(sa2);
SOCKET s2 = accept(s, (SOCKADDR *)&sa2, &size);
if(s2 == INVALID_SOCKET)
{
fprintf(flog, "accept error %d\n", WSAGetLastError());
closesocket(s);
return -7;
}
fprintf(flog, "Connected!\n");
fflush(flog);
# endif
*socket_ = s;
//fclose(flog);
return 0;
}
#if 0
int _bt_server_start(SOCKET *socket_,
const char *service_name,
const char *comment)
{
flog = fopen("bluelog.txt", "wt");
fprintf(flog, "Bluetooth socket server test, peripheral = '%s'.\n", "peripheral");
fflush(flog);
WSADATA m_data;
/* Load the winsock2 library */
if (WSAStartup(MAKEWORD(2,2), &m_data) != 0)
{
fprintf(flog, "wsastartup error.\n");
fclose(flog);
return -1;
}
SOCKET s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (s == INVALID_SOCKET)
{
fprintf(flog, "Could not create socket: error %d\n", WSAGetLastError());
return -1;
}
SOCKADDR_BTH sa;
int sa_len = sizeof(sa);
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.port = BT_PORT_ANY;
if (bind(s, (SOCKADDR *)&sa, sizeof(sa)))
{
fprintf(flog, "bind error %d\n", WSAGetLastError());
closesocket(s);
return -3;
}
if(listen(s, 5))
{
fprintf(flog, "listen error %d\n", WSAGetLastError());
closesocket(s);
return -1;
}
// check which port were listening on
if(getsockname(s, (SOCKADDR*)&sa, &sa_len))
{
fprintf(flog, "getsockname error %d\n", WSAGetLastError());
closesocket(s);
return -1;
}
fprintf(flog, "listening on RFCOMM port: %d\n" , sa.port) ;
fflush(flog);
fprintf(flog, "Registering SDP service (METHOD 0)...\n");
fflush(flog);
WSAQUERYSET service;
memset(&service, 0, sizeof(service));
service.dwSize = sizeof(service);
service.lpszServiceInstanceName = strdup(service_name);
//_T("My Service");
service.lpszComment = strdup(comment);
//_T("My comment");
// UUID for SPP is 00001101-0000-1000-8000-00805F9B34FB
GUID serviceID = (GUID)SerialPortServiceClass_UUID;
service.lpServiceClassId = &serviceID;
service.dwNumberOfCsAddrs = 1;
service.dwNameSpace = NS_BTH;
CSADDR_INFO csAddr;
memset(&csAddr, 0, sizeof(csAddr));
csAddr.LocalAddr.iSockaddrLength = sizeof(SOCKADDR);
csAddr.LocalAddr.lpSockaddr = (LPSOCKADDR) &sa;
csAddr.iSocketType = SOCK_STREAM;
csAddr.iProtocol = BTHPROTO_RFCOMM;
service.lpcsaBuffer = &csAddr;
if (0 != WSASetService(&service, RNRSERVICE_REGISTER, 0))
{
printf("set service error:%d\n", WSAGetLastError());
closesocket(s);
return -6;
}
fprintf(flog, "Waiting for client connection...\n");
fflush(flog);
// Sur la carte d'évaluation, faire :
// CALL 00:0A:3A:7F:24:69 1101 RFCOMM
# if 1
SOCKADDR_BTH sa2;
int size = sizeof(sa2);
SOCKET s2 = accept(s, (SOCKADDR *)&sa2, &size);
if(s2 == INVALID_SOCKET)
{
fprintf(flog, "accept error %d\n", WSAGetLastError());
closesocket(s);
return -7;
}
# endif
fprintf(flog, "Connected!\n");
fflush(flog);
*socket_ = s;
fclose(flog);
return 0;
}
#endif
int _bt_client_connect(const char *target_mac, SOCKET *socket_)
{
printf("Bluetooth socket client test, peripheral = '%s'.\n", "peripheral");
WSADATA m_data;
/* Load the winsock2 library */
if (WSAStartup(MAKEWORD(2,2), &m_data) != 0)
{
printf("wsastartup error.\n");
return -1;
}
SOCKET s = socket (AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (s == INVALID_SOCKET)
{
printf("Could not create socket: error %d\n", WSAGetLastError());
return -2;
}
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
/** Adresse de la carte d'évaluation bluegiga (inversée) */
unsigned char peripheral_address[6] = {0x75,0x2b,0x81,0x80,0x07,0x00};
memcpy(&(sa.btAddr), peripheral_address, 6);
unsigned char service_guid[16] = {0x0,0x1,0,0,0,0,0,0x10,0x80,0,0,0x80,0x5f,0x9b,0x34,0xfb};
memcpy(&(sa.serviceClassId), service_guid, 16);
if(connect(s, (SOCKADDR *) &sa, sizeof(sa)) != 0)
{
printf("Error during connection: %d\n", WSAGetLastError());
return -3;
}
printf("Successfully connected.\n");
*socket_ = s;
return 0;
}
| 7,341
|
C++
|
.cc
| 246
| 25.784553
| 96
| 0.661584
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,965
|
serial.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/comm/serial.cc
|
/**
* This file is part of LIBSERIAL.
*
* LIBSERIAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBSERIAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBSERIAL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#include "comm/serial.hpp"
#include "comm/crc.hpp"
//#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN
#include <process.h>
#include <conio.h>
#include <windows.h>
#endif
namespace utils
{
namespace comm
{
//#define serial_trace(...)
#ifndef serial_trace
static void serial_trace(const char *s, ...)
{
va_list ap;
va_start(ap, s);
printf("\033[32m[serial] \033[0m");
vprintf(s, ap);
printf("\r\n");
fflush(stdout);
va_end(ap);
}
#endif
EscapedIOStream::EscapedIOStream(IOStream *c)
{
compo = c;
}
void EscapedIOStream::start_frame()
{
compo->putc(0xff);
tx_crc = 0xffff;
}
void EscapedIOStream::end_frame()
{
// Write CRC
unsigned short the_crc = tx_crc;
putc(the_crc & 0xff);
putc((the_crc >> 8) & 0xff);
compo->putc(0xfe);
}
void EscapedIOStream::putc(char c)
{
unsigned char cc = (unsigned char) c;
// update crc
tx_crc = crc_update(tx_crc, c);
if(cc == 0xff)
{
compo->putc(0xfd);
compo->putc(0x02);
}
else if(cc == 0xfe)
{
compo->putc(0xfd);
compo->putc(0x01);
}
else if(cc == 0xfd)
{
compo->putc(0xfd);
compo->putc(0x00);
}
else
compo->putc(c);
}
int EscapedIOStream::getc(int timeout)
{
int c = compo->getc(timeout);
return c;
}
static void print_frame(char *buffer, unsigned int len)
{
printf("Frame(%d): ", len);
for(unsigned int i = 0; i < len; i++)
printf("%x.", (unsigned char) buffer[i]);
printf("\n");
fflush(stdout);
}
int EscapedIOStream::get_frame(char *buffer, unsigned int max_len)
{
unsigned int frame_size;
unsigned char c;
//wait_sof:
do
{
c = getc();
} while(c != 0xff);
//sof:
frame_size = 0;
for(;;)
{
c = getc();
if((unsigned char) c == 0xff)
{
printf("EIOStream::unexpected sof\n");
return -1;
//goto sof;
}
if((unsigned char) c == 0xfe)
break;
if((unsigned char) c == 0xfd)
{
c = getc() + 0xfd;
}
if(frame_size == max_len)
{
printf("EIOStream::frame too large (> %d)\n", max_len);
fflush(stdout);
return -1;
//goto wait_sof;
}
buffer[frame_size++] = c;
}
if(frame_size < 2)
{
printf("Frame too short.\n");
fflush(stdout);
return -1;
//goto wait_sof;
}
unsigned short crc = 0xffff;
unsigned short i;
for(i = 0; i < frame_size - 2; i++)
crc = crc_update(crc, buffer[i]);
if((unsigned char) (crc & 0xff) != (unsigned char) buffer[frame_size-2])
{
printf("*******************************\nBad CRC (lsb)\n");
printf("Expected: %x, received: %x%x.\n", crc, (unsigned char) buffer[frame_size-2], (unsigned char) buffer[frame_size-1]);
print_frame(buffer, frame_size);
fflush(stdout);
return -1;
//goto wait_sof;
}
if((unsigned char) ((crc>>8)&0xff) != (unsigned char) buffer[frame_size-1])
{
printf("Bad CRC (msb)\n");
printf("Expected: %x, received: %x%x.\n", crc, (unsigned char) buffer[frame_size-2], (unsigned char) buffer[frame_size-1]);
//print_frame(buffer, frame_size);
fflush(stdout);
return -1;
//goto wait_sof;
}
//printf("GOOD FRAME:\n");
//print_frame(buffer, frame_size);
//fflush(stdout);
// - 2 : CRC
return frame_size - 2;
}
bool Serial::is_connected()
{
return connected;
}
Serial::Serial()
{
parity = PAR_NONE;
port_name = "";
baudrate = 0;
# ifdef WIN
serial_handle = INVALID_HANDLE_VALUE;
# endif
connected = false;
}
Serial::~Serial()
{
# ifdef WIN
if (serial_handle!=INVALID_HANDLE_VALUE)
CloseHandle(serial_handle);
serial_handle = INVALID_HANDLE_VALUE;
# endif
}
void Serial::disconnect(void)
{
# ifdef WIN
if (serial_handle!=INVALID_HANDLE_VALUE)
CloseHandle(serial_handle);
serial_handle = INVALID_HANDLE_VALUE;
# endif
}
void Serial::set_timeout(int tm)
{
# ifdef WIN
COMMTIMEOUTS cto = { tm, 0, 0, 0, 0 };
if(serial_handle != INVALID_HANDLE_VALUE)
{
if(!SetCommTimeouts(serial_handle,&cto))
;
}
# endif
}
int Serial::connect(std::string port_name, int baudrate,
serial_parity_t parity)
{
# ifdef WIN
int erreur;
DCB dcb;
COMMTIMEOUTS cto = { 0, 0, 0, 0, 0 };
if (serial_handle!=INVALID_HANDLE_VALUE)
CloseHandle(serial_handle);
serial_handle = INVALID_HANDLE_VALUE;
erreur = 0;
this->port_name = port_name;
this->baudrate = baudrate;
this->parity = parity;
memset(&dcb,0,sizeof(dcb));
// set DCB to configure the serial port
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = baudrate;
switch(parity)
{
case PAR_NONE:
dcb.Parity = NOPARITY;
dcb.fParity = 0;
break;
case PAR_EVEN:
dcb.Parity = EVENPARITY;
dcb.fParity = 1;
break;
case PAR_ODD:
dcb.Parity = ODDPARITY;
dcb.fParity = 1;
break;
}
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = 0;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fOutX = 0;
dcb.fInX = 0;
/* ----------------- misc parameters ----- */
dcb.fErrorChar = 0;
dcb.fBinary = 1;
dcb.fNull = 0;
dcb.fAbortOnError = 0;
dcb.wReserved = 0;
dcb.XonLim = 2;
dcb.XoffLim = 4;
dcb.XonChar = 0x13;
dcb.XoffChar = 0x19;
dcb.EvtChar = 0;
serial_handle = ::CreateFile(
#ifdef VSTUDIO
(LPCWSTR)
#endif
port_name.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
nullptr, OPEN_EXISTING,/*nullptr*/0,nullptr);
if(serial_handle != INVALID_HANDLE_VALUE)
{
if(!SetCommMask(serial_handle, 0))
erreur = 1;
// set timeouts
if(!SetCommTimeouts(serial_handle,&cto))
erreur = 2;
// set DCB
if(!SetCommState(serial_handle,&dcb))
erreur = 4;
}
else
erreur = 8;
if (erreur!=0)
{
CloseHandle(serial_handle);
serial_handle = INVALID_HANDLE_VALUE;
connected = false;
}
else
connected = true;
return(erreur);
# else
return -1;
# endif
}
void Serial::putc(char data)
{
# ifndef LINUX
unsigned long result;
if (serial_handle!=INVALID_HANDLE_VALUE)
WriteFile(serial_handle, &data, 1, &result, nullptr);
# endif
}
int Serial::getc(int timeout)
{
char c = 0;
# ifdef WIN
if(serial_handle == INVALID_HANDLE_VALUE)
return 0;
unsigned long read_nbr = 0;
ReadFile(serial_handle, &c, 1, &read_nbr, nullptr);
# endif
return c;
}
int Serial::get_nb_bytes_available(void)
{
# ifdef WIN
struct _COMSTAT status;
int n;
unsigned long etat;
n = 0;
if (serial_handle!=INVALID_HANDLE_VALUE)
{
ClearCommError(serial_handle, &etat, &status);
n = status.cbInQue;
}
return n;
# else
return 0;
# endif
}
CRCStream::CRCStream(IOStream *stream)
{
this->stream = stream;
current_tx_crc = 0;
current_rx_crc = 0;
}
void CRCStream::putc(char c)
{
// update crc
current_tx_crc = crc_update(current_tx_crc, c);
stream->putc(c);
}
void CRCStream::write(const uint8_t *buffer, uint32_t len)
{
if(len > 0)
{
uint32_t i;
for(i = 0; i < (uint32_t) len; i++)
current_tx_crc = crc_update(current_tx_crc, buffer[i]);
}
stream->write(buffer, len);
}
void CRCStream::start_tx()
{
current_tx_crc = 0xffff;
}
void CRCStream::flush()
{
stream->putc((current_tx_crc >> 8) & 0xff);
stream->putc(current_tx_crc & 0xff);
stream->flush();
}
uint16_t CRCStream::get_current_tx_crc()
{
return current_tx_crc;
}
int CRCStream::read(uint8_t *buffer, uint32_t length, int timeout)
{
int res = stream->read(buffer, length, timeout);
if(res > 0)
{
uint32_t i;
//printf("compute crc %d bytes..\n", length);
for(i = 0; i < (uint32_t) res; i++)
current_rx_crc = crc_update(current_rx_crc, buffer[i]);
//printf("done.\n");
}
return res;
}
int CRCStream::getc(int timeout)
{
int res = stream->getc(timeout);
if(res != -1)
current_rx_crc = crc_update(current_rx_crc, (unsigned char) (res & 0xff));
return res;
}
void CRCStream::start_rx()
{
current_rx_crc = 0xffff;
}
int CRCStream::check_crc()
{
unsigned short c1, c2;
int r;
r = stream->getc(250);
if(r == -1)
{
serial_trace("Error while reading crc (1).");
return -1;
}
c1 = r & 0xff;
c1 = c1 << 8;
r = stream->getc(250);
if(r == -1)
{
serial_trace("Error while reading crc (2).");
return -1;
}
c2 = r & 0xff;
c2 = c2 | c1;
if(c2 != current_rx_crc)
{
serial_trace("bad crc : computed = %x, got = %x.", current_rx_crc, c2);
return -1;
}
return 0;
}
}
}
| 9,520
|
C++
|
.cc
| 422
| 19.165877
| 127
| 0.628852
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,966
|
ColorCellEditable2.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/ColorCellEditable2.cc
|
#include "mmi/ColorCellEditable2.hpp"
#include <gtkmm.h>
//#include <gtk/gtkentry.h> /* see XXX below */
#include <sstream>
#include <iostream>
#include "cutil.hpp"
#include "modele.hpp"
#include "mmi/gtkutil.hpp"
#include "mmi/stdview.hpp"
namespace utils
{
namespace mmi
{
ColorCellEditable2::ColorCellEditable2(const Glib::ustring& path, std::vector<std::string> constraints) :
Glib::ObjectBase( typeid(ColorCellEditable2) ),
Gtk::EventBox(),
Gtk::CellEditable(),
path_( path ),
color_area_ptr_( 0 ),
entry_ptr_( 0 ),
button_ptr_( 0 ),
editing_cancelled_( false )
{
this->constraints = constraints;
Gtk::HBox *const hbox = new Gtk::HBox(false, 0);
add (*Gtk::manage( hbox ));
color_area_ptr_ = new ColorArea();
// TODO: expose color_area size for get_size_vfunc
color_area_ptr_->set_size_request (16, 16);
hbox->pack_start (*Gtk::manage( color_area_ptr_ ), Gtk::PACK_SHRINK, 2);
entry_ptr_ = new Gtk::Entry();
hbox->pack_start (*Gtk::manage(entry_ptr_), Gtk::PACK_EXPAND_WIDGET);
entry_ptr_->set_has_frame (false);
// TODO
//entry_ptr_->gobj()->is_cell_renderer = true; // XXX
button_ptr_ = new Gtk::Button();
hbox->pack_start (*Gtk::manage( button_ptr_ ), Gtk::PACK_SHRINK);
button_ptr_->add (*Gtk::manage(new Gtk::Arrow(Gtk::ARROW_DOWN, Gtk::SHADOW_OUT)));
//set_flags(Gtk::CAN_FOCUS);
set_can_focus(true);
show_all_children();
}
ColorCellEditable2::~ColorCellEditable2()
{
}
Glib::ustring ColorCellEditable2::get_path() const
{
return path_;
}
void ColorCellEditable2::set_text(const Glib::ustring& text)
{
int r = 0;
int g = 0;
int b = 0;
entry_ptr_->set_text (text);
/*std::stringstream ss;
ss << text;
ss >> r;
ss >> g;
ss >> b;*/
std::string s = text;
ByteArray ba(s);
r = ba[0];
g = ba[1];
b = ba[2];
color_.set_rgb(r * 256, g * 256, b * 256);
//color_.set_rgb_p (r/256.0, g/256.0, b/256.0);
color_area_ptr_->set_color (color_);
}
Glib::ustring ColorCellEditable2::get_text() const
{
std::stringstream ss;
ss << int(color_.get_red() / 256) << ".";
ss << int(color_.get_green() / 256) << ".";
ss << int(color_.get_blue() / 256);
return ss.str();
}
/* static */ int ColorCellEditable2::get_button_width()
{
Gtk::Window window (Gtk::WINDOW_POPUP);
Gtk::Button *const button = new Gtk::Button();
window.add(*Gtk::manage(button));
button->add(*Gtk::manage(new Gtk::Arrow(Gtk::ARROW_DOWN, Gtk::SHADOW_OUT)));
// Urgh. Hackish :/
window.move(-500, -500);
window.show_all();
//Gtk::Requisition requisition = window.size_request();
//return requisition.width;
int w,h;
window.get_preferred_width(w,h);
return w;
}
/* static */ int ColorCellEditable2::get_color_area_width()
{
return 16;
}
void ColorCellEditable2::start_editing_vfunc(GdkEvent*)
{
entry_ptr_->select_region(0, -1);
entry_ptr_->signal_activate().connect(sigc::mem_fun(*this, &ColorCellEditable2::on_entry_activate));
entry_ptr_->signal_key_press_event().connect(sigc::mem_fun(*this, &ColorCellEditable2::on_entry_key_press_event));
button_ptr_->signal_clicked().connect (sigc::mem_fun( *this, &ColorCellEditable2::on_button_clicked ));
}
void ColorCellEditable2::on_editing_done()
{
//std::cout << "on_editing_done " << editing_cancelled_ << std::endl;
if (!editing_cancelled_)
{
int r = 0;
int g = 0;
int b = 0;
/*std::stringstream ss;
ss << entry_ptr_->get_text();
ss >> r;
ss >> g;
ss >> b;*/
std::string s = entry_ptr_->get_text();
ByteArray ba(s);
r = ba[0];
g = ba[1];
b = ba[2];
color_.set_rgb(r * 256, g * 256, b * 256);
}
signal_editing_done_.emit();
}
void ColorCellEditable2::on_button_clicked()
{
//if(appli_view_prm.use_touchscreen)
{
ColorDialog dialog;
if(dialog.display(GColor(color_), constraints) == 0)//Gtk::RESPONSE_OK)
{
GColor col = dialog.get_color();
//printf("apply color: %s.", col.to_string().c_str()); fflush(0);
//color_ = col.to_gdk();
color_.set_rgb(col.red * 256, col.green * 256, col.blue * 256);
//editing_cancelled_ = true;
signal_editing_done_.emit();
}
}
/*else
{
Gtk::ColorSelectionDialog dialog( "Changing color" );
dialog.set_transient_for ((Gtk::Window&)(*this->get_toplevel()));
Gtk::ColorSelection* colorsel = dialog.get_colorsel();
colorsel->set_previous_color (color_);
colorsel->set_current_color (color_);
colorsel->set_has_palette (true);
if(dialog.run() == Gtk::RESPONSE_OK)
{
color_ = colorsel->get_current_color();
signal_editing_done_.emit();
}
}*/
}
bool ColorCellEditable2::on_entry_key_press_event(GdkEventKey* event)
{
if (event->keyval == GDK_KEY_Escape)
{
std::cout << "Press ESCAPE" << std::endl;
editing_cancelled_ = true;
editing_done();
remove_widget();
return true;
}
return false;
}
void ColorCellEditable2::on_entry_activate()
{
if(!appli_view_prm.use_touchscreen)
editing_done();
}
}
}
| 4,928
|
C++
|
.cc
| 174
| 25.551724
| 115
| 0.665884
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,967
|
ColorCellRenderer2.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/ColorCellRenderer2.cc
|
#include "mmi/ColorCellRenderer2.hpp"
#include "bytearray.hpp"
#include "mmi/stdview.hpp"
#include <sstream>
#include <iostream>
#include <memory>
namespace utils
{
namespace mmi
{
ColorCellRenderer2::ColorCellRenderer2(std::vector<std::string> constraints) :
Glib::ObjectBase( typeid(ColorCellRenderer2) ),
Gtk::CellRenderer(),
property_text_( *this, "text", "" ),
property_editable_( *this, "editable", true ),
color_cell_edit_ptr_( 0 ),
button_width_( -1 )
{
this->constraints = constraints;
property_mode() = Gtk::CELL_RENDERER_MODE_EDITABLE;
property_xpad() = 2;
property_ypad() = 2;
}
ColorCellRenderer2::~ColorCellRenderer2()
{
}
Glib::PropertyProxy< Glib::ustring > ColorCellRenderer2::property_text()
{
return property_text_.get_proxy();
}
Glib::PropertyProxy< bool > ColorCellRenderer2::property_editable()
{
return property_editable_.get_proxy();
}
/* override */void ColorCellRenderer2::get_size_vfunc (Gtk::Widget& widget, const Gdk::Rectangle* cell_area, int* x_offset, int* y_offset, int* width, int* height) const
{
// We cache this because it takes a really long time to get the width.
if(button_width_ < 0)
button_width_ = ColorCellEditable2::get_button_width();
// Compute text width
Glib::RefPtr<Pango::Layout> layout_ptr = widget.create_pango_layout (property_text_);
Pango::Rectangle rect = layout_ptr->get_pixel_logical_extents();
const int calc_width = property_xpad() * 4 + rect.get_width();
const int calc_height = property_ypad() * 4 + rect.get_height();
// Add button width and color area width
if( width )
*width = calc_width + button_width_ + ColorCellEditable2::get_color_area_width();
if( height )
*height = calc_height;
}
// TODO
#if 0
/* override */void ColorCellRenderer2::render_vfunc (const Glib::RefPtr<Gdk::Drawable>& window, Gtk::Widget& widget, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, const Gdk::Rectangle& expose_area, Gtk::CellRendererState flags)
{
// Get cell size
int x_offset = 0, y_offset = 0, width = 0, height = 0;
get_size (widget, cell_area, x_offset, y_offset, width, height);
// Create the graphic context
Glib::RefPtr< Cairo::Context > gc = Cairo::Context::create (window);
// Get cell state
//Gtk::StateType state;
Gtk::StateType text_state;
if ((flags & Gtk::CELL_RENDERER_SELECTED) != 0)
{
//state = Gtk::STATE_SELECTED;
text_state = (widget.has_focus()) ? Gtk::STATE_SELECTED : Gtk::STATE_ACTIVE;
}
else
{
//state = Gtk::STATE_NORMAL;
text_state = (widget.is_sensitive()) ? Gtk::STATE_NORMAL : Gtk::STATE_INSENSITIVE;
}
// Get cell color
int r = 0;
int g = 0;
int b = 0;
/*std::stringstream ss;
ss << property_text_;
ss >> r;
ss >> g;
ss >> b;*/
Glib::ustring us = property_text_;
std::string s = us;
ByteArray ba(s);
r = ba[0];
g = ba[1];
b = ba[2];
Gdk::Color color_value;
color_value.set_rgb(r * 256, g * 256, b * 256);
// Draw color area
gc->set_rgb_fg_color( color_value );
window->draw_rectangle(gc,
true,
cell_area.get_x(),
cell_area.get_y(),
ColorCellEditable2::get_color_area_width(),
cell_area.get_height());
// Draw color text
Glib::RefPtr< Gdk::Window > win = Glib::RefPtr<Gdk::Window>::cast_dynamic (window);
Glib::RefPtr<Pango::Layout> layout_ptr = widget.create_pango_layout( property_text_ );
widget.get_style()->paint_layout (win,
text_state,
true,
cell_area,
widget,
"cellrenderertext",
cell_area.get_x() + ColorCellEditable2::get_color_area_width() + x_offset + 2 * property_xpad(),
cell_area.get_y() + y_offset + 2 * property_ypad(),
layout_ptr);
}
#endif
/* override */bool ColorCellRenderer2::activate_vfunc (GdkEvent*, Gtk::Widget&, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags)
{
return true;
}
/* override */Gtk::CellEditable* ColorCellRenderer2::start_editing_vfunc(GdkEvent* event, Gtk::Widget& widget, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags)
{
if(appli_view_prm.use_touchscreen)
return 0;
// If the cell isn't editable we return 0.
#ifdef GLIBMM_PROPERTIES_ENABLED
if (!property_editable())
return 0;
#else
if (!(g_object_get_data(G_OBJECT(gobj()), "editable")))
return 0;
#endif
std::auto_ptr< ColorCellEditable2 > color_cell_edit_ptr( new ColorCellEditable2( path, constraints ) );
Glib::ustring text;
#ifdef GLIBMM_PROPERTIES_ENABLED
text = property_text();
#else
get_property("text", text);
#endif
color_cell_edit_ptr->set_text (text);
color_cell_edit_ptr->signal_editing_done().connect(sigc::mem_fun(*this, &ColorCellRenderer2::on_editing_done));
color_cell_edit_ptr->show();
color_cell_edit_ptr_ = Gtk::manage( color_cell_edit_ptr.release() );
return color_cell_edit_ptr_;
}
void ColorCellRenderer2::edited(const Glib::ustring& path, const Glib::ustring& new_text)
{
signal_edited_.emit (path, new_text);
}
void ColorCellRenderer2::on_editing_done()
{
if (color_cell_edit_ptr_->get_editing_cancelled())
{
std::cout << "ColorCellRenderer2 Editing cancelled" << std::endl;
stop_editing (true);
}
else
{
edited (color_cell_edit_ptr_->get_path(), color_cell_edit_ptr_->get_text());
}
}
}
}
| 5,508
|
C++
|
.cc
| 158
| 31.177215
| 253
| 0.684101
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,968
|
field-view.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/field-view.cc
|
#include "mmi/stdview.hpp"
#include "mmi/ColorCellRenderer2.hpp"
#include "mmi/renderers.hpp"
#include "mmi/stdview-fields.hpp"
#include "comm/serial.hpp"
#include <string.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
namespace utils
{
namespace mmi
{
namespace fields
{
static void update_text_color(Gtk::Widget &w, bool valid)
{
if (valid)
{
//# ifdef WIN
w.override_color(Gdk::RGBA("#000000"), Gtk::STATE_FLAG_NORMAL);
//# else
// w.override_color(Gdk::RGBA("#ffffff"), Gtk::STATE_FLAG_NORMAL);
//# endif
}
else
w.override_color(Gdk::RGBA("#ff0000"), Gtk::STATE_FLAG_NORMAL);
}
/*******************************************************************
* BYTES VIEW IMPLEMENTATION *
*******************************************************************/
VueOctets::VueOctets(Attribute *model) {
this->model = model;
valid = model->schema->is_valid(model->get_string());
lock = false;
label.set_use_markup(true);
update_langue();
entry.set_editable(true);
entry.set_width_chars(20);
entry.set_text(model->get_string());
entry.signal_changed().connect(
sigc::mem_fun(*this, &VueOctets::on_signal_changed));
entry.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
}
void VueOctets::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueOctets::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueOctets::get_widget(int index) {
if (index == 0)
return &label;
else
return &entry;
}
Gtk::Widget *VueOctets::get_gtk_widget()
{
return &entry;
}
void VueOctets::set_sensitive(bool b) {
entry.set_sensitive(b);
label.set_sensitive(b);
}
void VueOctets::on_signal_changed() {
if (!lock) {
lock = true;
//model->set_value(entry.get_text());
std::string s = entry.get_text();
valid = model->schema->is_valid(s);
model->set_value(entry.get_text());
update_text_color(entry, valid);
model->forward_change_event();
lock = false;
}
}
void VueOctets::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
entry.set_text(model->get_string());
lock = false;
}
}
/*******************************************************************
* HEXA VIEW IMPLEMENTATION *
*******************************************************************/
VueHexa::VueHexa(Attribute *model) {
this->model = model;
lock = false;
valid = model->schema->is_valid(model->get_string());
label.set_use_markup(true);
update_langue();
entry.set_editable(true);
entry.set_width_chars(20);
unsigned short offset = 0;
char buf[500];
unsigned int vl = model->get_int();
buf[offset++] = '0';
buf[offset++] = 'x';
unsigned char nb_digits = model->schema->size * 2;
if (vl > 0) {
unsigned long temp = vl;
while (temp > 0) {
temp = temp >> 4;
nb_digits--;
}
} else
nb_digits--;
for (unsigned char i = 0; i < nb_digits; i++)
buf[offset++] = '0';
sprintf(&(buf[offset]), "%x", vl);
//printf("Text : %s\n", buf);
entry.set_text(std::string(buf));
//entry.set_text(model->value);
entry.signal_changed().connect(
sigc::mem_fun(*this, &VueHexa::on_signal_changed));
}
void VueHexa::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueHexa::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueHexa::get_widget(int index) {
if (index == 0)
return &label;
else
return &entry;
}
Gtk::Widget *VueHexa::get_gtk_widget()
{
return &entry;
}
void VueHexa::set_sensitive(bool b) {
entry.set_sensitive(b);
label.set_sensitive(b);
}
void VueHexa::on_signal_changed() {
if (!lock) {
lock = true;
//model->set_value(entry.get_text());
std::string s = entry.get_text();
valid = model->schema->is_valid(s);
model->set_value(entry.get_text());
update_text_color(entry, valid);
model->forward_change_event();
lock = false;
}
}
void VueHexa::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
entry.set_text(model->get_string());
lock = false;
}
}
/*******************************************************************
* TEXT VIEW IMPLEMENTATION *
*******************************************************************/
VueTexte::VueTexte(Attribute *model, bool small_) {
lock = false;
this->model = model;
label.set_use_markup(true);
update_langue();
view.set_editable(true);
//entry.set_text(Util::latin_to_utf8(model->value));
//Glib::RefPtr< TextBuffer >
view.get_buffer()->set_text(model->get_string());
view.set_wrap_mode(Gtk::WRAP_WORD);
frame.set_shadow_type(Gtk::SHADOW_ETCHED_IN);
/*if(small_)
view.set_width_chars(12);
else
view.set_width_chars(30);*/
view.get_buffer()->signal_changed().connect(
sigc::mem_fun(*this, &VueTexte::on_signal_changed));
scroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
scroll.add(view);
scroll.set_size_request(350, 150); //225,75);
frame.add(scroll);
}
void VueTexte::update_langue() {
label.set_markup("<b>" + NodeView::mk_label(model->schema->name) + "</b>");
}
unsigned int VueTexte::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueTexte::get_widget(int index) {
if (index == 0)
return &label;
else
return &frame;
}
Gtk::Widget *VueTexte::get_gtk_widget()
{
return &frame;
}
void VueTexte::set_sensitive(bool b) {
view.set_sensitive(b);
label.set_sensitive(b);
}
void VueTexte::on_signal_changed() {
if (!lock) {
lock = true;
model->set_value(view.get_buffer()->get_text());
lock = false;
}
}
void VueTexte::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
view.get_buffer()->set_text(model->get_string());
lock = false;
}
}
/*******************************************************************
* DECIMAL SPIN VIEW IMPLEMENTATION *
*******************************************************************/
VueDecimal::VueDecimal(Attribute *model, int compatibility_mode)
{
tp = "decimal-spin";
is_sensitive = true;
lock = false;
this->model = model;
label.set_use_markup(true);
update_langue();
spin.set_editable(true);
spin.set_increments(1, 1);
valid = model->schema->is_valid(model->get_string());
//infos("decimal view(%s): min = %d, max = %d.", model->name.c_str(), model->schema.get_min(), model->schema.get_max());
spin.set_range(model->schema->get_min(), model->schema->get_max());
spin.set_value((double) model->get_float()); //atoi(model->get_string().c_str()));
if (model->schema->has_unit())
{
std::string unit = model->schema->unit;
if (langue.has_item(unit))
unit = langue.get_item(unit);
label_unit.set_text(std::string(" ") + unit + " ");
// To deprecate
if(compatibility_mode)
hbox.pack_start(spin, Gtk::PACK_SHRINK);
hbox.pack_start(align, Gtk::PACK_SHRINK);
align.add(label_unit);
align.set_padding(0, 0, 5, 0);
}
spin.signal_value_changed().connect(
sigc::mem_fun(*this, &VueDecimal::on_signal_changed));
spin.signal_editing_done().connect(
sigc::mem_fun(*this, &VueDecimal::on_signal_changed));
spin.signal_changed().connect(
sigc::mem_fun(*this, &VueDecimal::on_signal_changed));
spin.signal_focus_out_event().connect(
sigc::mem_fun(*this, &VueDecimal::on_signal_focus_out));
spin.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
update_valid();
}
void VueDecimal::update_langue() {
set_sensitive(is_sensitive);
//label.set_markup("<b>" + mk_label(&(model->schema)) + "</b>");
}
unsigned int VueDecimal::get_nb_widgets() {
//if(model->schema.has_unit())
//return 3;
return 2;
}
Gtk::Widget *VueDecimal::get_widget(int index) {
if (index == 0)
return &label;
else if (index == 1)
{
if (model->schema->has_unit())
return &hbox;
else
return &spin;
}
return nullptr;
}
Gtk::Widget *VueDecimal::get_gtk_widget()
{
return &spin;
}
void VueDecimal::set_sensitive(bool b) {
is_sensitive = b;
spin.set_sensitive(b);
label.set_sensitive(b);
label_unit.set_sensitive(b);
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
bool VueDecimal::on_signal_focus_out(GdkEventFocus *gef) {
//infos("focus out.");
//on_signal_changed();
return true;
}
void VueDecimal::update_valid()
{
update_text_color(spin, valid);
}
bool VueDecimal::is_valid() {
return valid;
}
void VueDecimal::on_signal_changed() {
if (!lock) {
lock = true;
std::string s = spin.get_text();
valid = model->schema->is_valid(s);
model->set_value(s);
update_valid();
model->forward_change_event();
lock = false;
}
}
void VueDecimal::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
spin.set_range(model->schema->get_min(), model->schema->get_max());
spin.set_value(model->get_int());
lock = false;
}
}
/*******************************************************************
* FLOAT VIEW IMPLEMENTATION *
*******************************************************************/
VueFloat::VueFloat(Attribute *model, Node modele_vue)
{
init(model, modele_vue);
}
VueFloat::VueFloat(Attribute *model)
{
init(model, Node());
}
void VueFloat::init(Attribute *model, Node modele_vue)
{
lock = false;
this->model = model;
label.set_use_markup(true);
valeur_label = model->schema->name;
if(!modele_vue.is_nullptr())
if(modele_vue.get_localized_name().size() > 0)
valeur_label = modele_vue.get_localized();
label.set_markup("<b>" + NodeView::mk_label_colon(valeur_label) + "</b>");
spin.set_editable(true);
int digits = model->schema->digits;
//utils::infos("float-view[%s]: digits = %d", model->schema->name.get_id().c_str(), digits);
if(digits <= 0)
digits = 6;
float increment = 1.0;
for(auto i = 0u; i < (unsigned int) digits; i++)
increment /= 10;
spin.set_increments(increment, 1);
spin.set_digits(digits);
//infos("decimal view(%s): min = %d, max = %d.", model->name.c_str(), model->schema.get_min(), model->schema.get_max());
spin.set_range(model->schema->get_min(), model->schema->get_max());
//infos("Setting spin value = %f, str = %s", atof(model->value.c_str()), model->value.c_str());
spin.set_value(model->get_float()); //atof(model->value.c_str()));
if (model->schema->has_unit())
{
std::string unit = model->schema->unit;
if (langue.has_item(unit))
unit = langue.get_item(unit);
label_unit.set_text(std::string(" ") + unit + " ");
}
spin.signal_value_changed().connect(
sigc::mem_fun(*this, &VueFloat::on_signal_changed));
}
void VueFloat::update_langue() {
label.set_markup("<b>" + NodeView::mk_label(valeur_label) + "</b>");
}
unsigned int VueFloat::get_nb_widgets() {
if (model->schema->has_unit())
return 3;
return 2;
}
Gtk::Widget *VueFloat::get_widget(int index) {
if (index == 0)
return &label;
else if (index == 1)
return &spin;
else
return &label_unit;
}
Gtk::Widget *VueFloat::get_gtk_widget()
{
return &spin;
}
void VueFloat::set_sensitive(bool b) {
spin.set_sensitive(b);
label.set_sensitive(b);
label_unit.set_sensitive(b);
}
void VueFloat::on_signal_changed() {
if (!lock) {
lock = true;
//printf("Spin change: %s\n", Util::int2str(spin.get_value_as_float()).c_str());
model->set_value((float) spin.get_value());
lock = false;
}
}
void VueFloat::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
spin.set_value(model->get_float());//atof(model->value.c_str()));
lock = false;
}
}
/*******************************************************************
* BOOLEAN VIEW IMPLEMENTATION *
*******************************************************************/
VueBouleen::~VueBouleen() {
}
VueBouleen::VueBouleen(Attribute *model, bool affiche_label)
{
lock = false;
this->model = model;
//Gtk::Label *lab = new Gtk::Label();
lab.set_use_markup(true);
if(affiche_label)
{
std::string s = NodeView::mk_label(model->schema->name);
lab.set_markup("<b>" + s + "</b>");
check.add(lab);
}
check.set_active(model->get_boolean());
check.signal_toggled().connect(
sigc::mem_fun(*this, &VueBouleen::on_signal_toggled));
check.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
}
void VueBouleen::update_langue()
{
std::string s = NodeView::mk_label(model->schema->name);
lab.set_markup("<b>" + s + "</b>");
}
unsigned int VueBouleen::get_nb_widgets() {
return 1;
}
Gtk::Widget *VueBouleen::get_widget(int index) {
return ✓
}
Gtk::Widget *VueBouleen::get_gtk_widget()
{
return ✓
}
void VueBouleen::set_sensitive(bool b) {
check.set_sensitive(b);
}
void VueBouleen::on_signal_toggled() {
if (!lock) {
lock = true;
model->set_value(check.get_active());
lock = false;
}
}
void VueBouleen::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
check.set_active(model->get_boolean());
lock = false;
}
}
/*******************************************************************
* COMBO VIEW IMPLEMENTATION *
*******************************************************************/
VueCombo::VueCombo(Attribute *model) {
lock = false;
//infos("comboview(%s)..", model->schema.name.get_id().c_str());
this->model = model;
label.set_use_markup(true);
tree_model = Gtk::ListStore::create(columns);
combo.set_model(tree_model);
combo.pack_start(columns.m_col_name);
if (model->schema->has_unit())
combo.pack_start(columns.m_col_unit);
update_langue();
combo.signal_changed().connect(
sigc::mem_fun(*this, &VueCombo::on_combo_changed));
combo.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
}
void VueCombo::update_langue() {
unsigned int imax;
bool old_lock = lock;
auto schema = model->schema;
lock = true;
//infos("combo: update langue...");
label.set_markup("<b>" + NodeView::mk_label_colon(schema->name) + "</b>");
tree_model->clear();
//imin = 0;
imax = schema->constraints.size();
if ((imax == 0) && (model->schema->has_max)) {
imax = schema->max - schema->min + 1;
}
unsigned int nb_enum = model->schema->enumerations.size();
/*if(nb_enum > 0)
infos("vue combo: %d enumerations (prem : %s)",
nb_enum, schema->enumerations[0].name.get_localized().c_str());*/
for (unsigned int i = 0; i < imax; i++)
{
std::string valeur;
if(schema->constraints.size() > i)
valeur = schema->constraints[i];
else
valeur = str::int2str(i);
std::string nom = valeur;
for (unsigned int j = 0; j < nb_enum; j++)
{
Enumeration e;
if (i >= schema->enumerations.size()) {
avertissement("enumeration %d not defined: attribute %s.", i,
schema->name.get_id().c_str());
infos("schema is: %s.\n", schema->to_string().c_str());
break;
}
e = schema->enumerations[j];
if ((e.value == valeur) || (e.name.get_id() == valeur))
{
nom = e.name.get_localized();
break;
}
}
if (langue.has_item(nom))
nom = langue.get_item(nom);
Gtk::TreeModel::Row row = *(tree_model->append());
if ((nom[0] >= 'a') && (nom[0] <= 'z'))
nom[0] += ('A' - 'a');
row[columns.m_col_name] = nom;
row[columns.m_col_real_name] = valeur;
if(schema->has_unit()) {
row[columns.m_col_unit] = "";
std::string unit = schema->unit;
if (langue.has_item(unit))
unit = langue.get_item(unit);
row[columns.m_col_unit] = unit;
}
}
unsigned int i;
for (i = 0; i < imax; i++) {
std::string valeur;
if (schema->constraints.size() > i)
valeur = schema->constraints[i];
else
valeur = str::int2str(i);
//std::string valeur = model->schema.constraints[i];
std::string nom = valeur;
for (unsigned int j = 0; j < schema->enumerations.size(); j++)
{
if (i >= schema->enumerations.size())
{
erreur("enumeration.");
break;
}
Enumeration e = schema->enumerations[i];
if (e.value.compare(valeur) == 0) {
nom = e.name.get_localized();
break;
}
}
if ((model->get_string().compare(nom) == 0)
|| (model->get_string().compare(valeur) == 0))
{
combo.set_active(i);
break;
}
}
if (i == /*model->schema.constraints.size()*/imax)
{
string s = model->get_string();
avertissement("Not found current value (%s, %s).",
schema->name.get_id().c_str(), s.c_str());
for (i = 0; i < schema->constraints.size(); i++) {
std::string valeur = schema->constraints[i];
infos("constraint[%d] = %s.", i, valeur.c_str());
}
}
//infos("combo: update langue done.");
lock = old_lock;
}
unsigned int VueCombo::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueCombo::get_widget(int index) {
if (index == 0)
return &label;
else
return &combo;
}
Gtk::Widget *VueCombo::get_gtk_widget()
{
return &combo;
}
void VueCombo::set_sensitive(bool b) {
label.set_sensitive(b);
combo.set_sensitive(b);
}
void VueCombo::on_combo_changed() {
if (!lock) {
lock = true;
Gtk::TreeModel::iterator iter = combo.get_active();
if (iter) {
Gtk::TreeModel::Row row = *iter;
if (row) {
Glib::ustring name = row[columns.m_col_name];
Glib::ustring real_name = row[columns.m_col_real_name];
model->set_value(real_name);
}
} else
erreur("combo view: none selected.");
lock = false;
}
}
// check.set_active(model->get_boolean());
void VueCombo::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
unsigned int imax = model->schema->constraints.size();
if ((imax == 0) && (model->schema->has_max)) {
imax = model->schema->max - model->schema->min + 1;
}
unsigned int i;
for (i = 0; i < imax; i++) {
std::string valeur;
if (model->schema->constraints.size() > i)
valeur = model->schema->constraints[i];
else
valeur = str::int2str(i);
std::string nom = valeur;
for (unsigned int j = 0; j < model->schema->enumerations.size(); j++) {
Enumeration &e = model->schema->enumerations[i];
if (e.value.compare(valeur) == 0) {
nom = e.name.get_localized();
break;
}
}
if ((model->get_string().compare(nom) == 0)
|| (model->get_string().compare(valeur) == 0)) {
combo.set_active(i);
break;
}
}
lock = false;
}
}
/*******************************************************************
* DATE VIEW IMPLEMENTATION *
*******************************************************************/
VueDate::VueDate(Attribute *model)
{
adj_year = Gtk::Adjustment::create(2000,0,2100);
adj_month = Gtk::Adjustment::create(1,1,12);
adj_day = Gtk::Adjustment::create(1,1,31);
year.set_adjustment(adj_year);
month.set_adjustment(adj_month);
day.set_adjustment(adj_day);
lock = false;
this->model = model;
valid = model->schema->is_valid(model->get_string());
label.set_use_markup(true);
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
hbox.pack_start(day, Gtk::PACK_SHRINK);
a_month.add(month);
a_month.set_padding(0, 0, 6, 6);
hbox.pack_start(a_month, Gtk::PACK_SHRINK);
hbox.pack_start(year, Gtk::PACK_SHRINK);
ChangeEvent ce;
on_event(ce);
if (appli_view_prm.use_touchscreen) {
day.set_snap_to_ticks(false);
month.set_snap_to_ticks(false);
year.set_snap_to_ticks(false);
}
day.signal_changed().connect(
sigc::mem_fun(*this, &VueDate::on_date_changed));
month.signal_changed().connect(
sigc::mem_fun(*this, &VueDate::on_date_changed));
year.signal_changed().connect(
sigc::mem_fun(*this, &VueDate::on_date_changed));
day.signal_editing_done().connect(
sigc::mem_fun(*this, &VueDate::on_date_changed));
day.signal_focus_out_event().connect(
sigc::mem_fun(*this, &VueDate::on_signal_focus_out));
month.signal_editing_done().connect(
sigc::mem_fun(*this, &VueDate::on_date_changed));
month.signal_focus_out_event().connect(
sigc::mem_fun(*this, &VueDate::on_signal_focus_out));
year.signal_editing_done().connect(
sigc::mem_fun(*this, &VueDate::on_date_changed));
year.signal_focus_out_event().connect(
sigc::mem_fun(*this, &VueDate::on_signal_focus_out));
day.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
month.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
year.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
}
void VueDate::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
if (appli_view_prm.use_touchscreen) {
day.set_snap_to_ticks(false);
month.set_snap_to_ticks(false);
year.set_snap_to_ticks(false);
}
}
unsigned int VueDate::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueDate::get_widget(int index) {
if (index == 0)
return &label;
else
return &hbox;
}
Gtk::Widget *VueDate::get_gtk_widget()
{
return &hbox;
}
void VueDate::set_sensitive(bool b) {
label.set_sensitive(b);
year.set_sensitive(b);
month.set_sensitive(b);
day.set_sensitive(b);
}
bool VueDate::on_signal_focus_out(GdkEventFocus *gef) {
on_date_changed();
return true;
}
void VueDate::on_date_changed() {
if (!lock) {
lock = true;
/*int vy = year.get_value_as_int();
int vm = month.get_value_as_int();
int vd = day.get_value_as_int();*/
int vy = atoi(year.get_text().c_str());
int vm = atoi(month.get_text().c_str());
int vd = atoi(day.get_text().c_str());
std::string s = str::int2str(vd) + "." + str::int2str(vm) + "."
+ str::int2str(vy);
//infos("new date: %s.", s.c_str());
//model->set_value(s);
valid = model->schema->is_valid(s);
model->set_value(s);
update_text_color(year, valid);
update_text_color(month, valid);
update_text_color(day, valid);
model->forward_change_event();
lock = false;
}
}
void VueDate::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
Gdk::Color c;
std::vector<int> lst;
str::parse_int_list(model->get_string(), lst);
while (lst.size() < 3)
lst.push_back(0);
year.set_value(lst[2]);
month.set_value(lst[1]);
day.set_value(lst[0]);
lock = false;
}
}
/*******************************************************************
* FOLDER VIEW IMPLEMENTATION *
*******************************************************************/
bool VueDossier::on_focus_in(GdkEventFocus *gef) {
infos("focus in");
//target_window->present();
if (appli_view_prm.fixed_size) {
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
fcd->set_size_request(appli_view_prm.dx, appli_view_prm.dy);
fcd->move(appli_view_prm.ox, appli_view_prm.oy);
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
}
return true;
}
bool VueDossier::on_frame_event(GdkEvent *gef) {
infos("frame event");
//target_window->present();
if (appli_view_prm.fixed_size)
{
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
fcd->move(appli_view_prm.ox, appli_view_prm.oy);
}
return true;
}
VueDossier::VueDossier(Attribute *model)
{
fcd = new Gtk::FileChooserDialog(langue.get_item("select-folder"),
Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
fcd->add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
fcd->add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
bouton = new Gtk::FileChooserButton(*fcd);
if (appli_view_prm.fixed_size) {
fcd->set_position(Gtk::WIN_POS_NONE);
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
fcd->move(appli_view_prm.ox, appli_view_prm.oy);
fcd->set_resizable(false);
fcd->set_size_request(appli_view_prm.dx, appli_view_prm.dy);
//fcd->set_resize_mode(Gtk::RESIZE_QUEUE);
fcd->signal_focus_in_event().connect(
sigc::mem_fun(*this, &VueDossier::on_focus_in));
//TODO fcd->signal_frame_event().connect(
// sigc::mem_fun(*this, &FolderView::on_frame_event));
} else {
fcd->set_position(Gtk::WIN_POS_CENTER_ALWAYS);
}
lock = false;
this->model = model;
label.set_use_markup(true);
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
bouton->set_action(Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
ChangeEvent ce;
on_event(ce);
# if ((GTKMM_MAJOR_VERSION * 100 + GTKMM_MINOR_VERSION) < 218)
# warning GTKMM version too old for signal_file_set
bouton->signal_selection_changed().connect(
sigc::mem_fun(*this, &VueDossier::on_folder_changed));
on_folder_changed();
# else
bouton->signal_file_set().connect(sigc::mem_fun(*this, &VueDossier::on_folder_changed));
# endif
}
void VueDossier::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueDossier::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueDossier::get_widget(int index) {
if (index == 0)
return &label;
else
return bouton;
}
Gtk::Widget *VueDossier::get_gtk_widget()
{
return bouton;
}
void VueDossier::set_sensitive(bool b) {
label.set_sensitive(b);
bouton->set_sensitive(b);
}
void VueDossier::on_folder_changed() {
if (!lock) {
lock = true;
Glib::ustring s = bouton->get_filename();
std::string s2 = s;
std::string s3 = str::utf8_to_latin(s2);
infos("Folder view changed: '%s'.", s2.c_str());
model->set_value(s3);
lock = false;
}
}
void VueDossier::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
bouton->set_current_folder(model->get_string());
lock = false;
}
}
/*******************************************************************
* FILE VIEW IMPLEMENTATION *
*******************************************************************/
bool VueFichier::on_focus_in(GdkEventFocus *gef) {
infos("focus in");
//target_window->present();
if (appli_view_prm.fixed_size) {
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
fcd->set_size_request(appli_view_prm.dx, appli_view_prm.dy);
fcd->move(appli_view_prm.ox, appli_view_prm.oy);
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
}
return true;
}
bool VueFichier::on_frame_event(GdkEvent *gef) {
infos("frame event");
//target_window->present();
if (appli_view_prm.fixed_size) {
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
fcd->move(appli_view_prm.ox, appli_view_prm.oy);
}
return true;
}
VueFichier::~VueFichier()
{
delete bouton;
delete fcd;
}
bool VueFichier::gere_bouton(GdkEventButton *non_ut)
{
infos("Detecte clic sur bouton vue fichier.");
//fcd->set_action(Gtk::FILE_CHOOSER_ACTION_SAVE);
if(fcd->run() == Gtk::RESPONSE_OK)
{
auto s = fcd->get_filename();
infos("Mise a jour du texte bouton [%s]...", s.c_str());
auto e = utils::files::get_extension(s);
if(e.size() == 0)
{
avertissement("Pas d'extension precisee.");
std::string ext = model->schema->extension;
if(ext.size() > 0)
{
s += "." + ext;
infos("ajoute extension [%s] >> ", ext.c_str(), s.c_str());
}
}
# ifdef ANCIEN_BOUTON
bouton->set_filename(s);
# else
auto s_resume = utils::str::get_filename_resume(s);
infos("Nouvelle valeur de fichier : [%s], RES = [%s]", s.c_str(), s_resume.c_str());
bouton->set_label(s_resume);
model->set_value(s);
# endif
}
fcd->hide();
infos("retour gere bouton.");
return true;
}
void VueFichier::BoutonFichier::gere_clic()
{
parent->gere_bouton(nullptr);
}
VueFichier::BoutonFichier::BoutonFichier(Gtk::FileChooserDialog *fcd, VueFichier *parent)
//: Gtk::FileChooserButton(*fcd)
{
this->fcd = fcd;
this->parent = parent;
this->signal_clicked().connect(sigc::mem_fun(*this, &VueFichier::BoutonFichier::gere_clic));
}
VueFichier::VueFichier(Attribute *model, bool fichier_existant)
{
this->fichier_existant = fichier_existant;
fcd = new Gtk::FileChooserDialog(langue.get_item("select-fichier"),
fichier_existant ? Gtk::FILE_CHOOSER_ACTION_OPEN : Gtk::FILE_CHOOSER_ACTION_SAVE);
fcd->add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
fcd->add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
bouton = new /*Gtk::FileChooserButton(*fcd)*/BoutonFichier(fcd, this);
std::string ext = model->schema->extension;
if (ext.size() > 0)
{
Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
filter->set_name(ext + " file");
filter->add_pattern(std::string("*.") + ext);
infos("Extension choisie : [%s]", ext.c_str());
fcd->add_filter(filter);
}
// TODO
//bouton->set_image()
if (appli_view_prm.fixed_size) {
fcd->set_position(Gtk::WIN_POS_NONE);
fcd->resize(appli_view_prm.dx, appli_view_prm.dy);
fcd->move(appli_view_prm.ox, appli_view_prm.oy);
fcd->set_resizable(false);
fcd->set_size_request(appli_view_prm.dx, appli_view_prm.dy);
//fcd->set_resize_mode(Gtk::RESIZE_QUEUE);
fcd->signal_focus_in_event().connect(
sigc::mem_fun(*this, &VueFichier::on_focus_in));
//TODO fcd->signal_frame_event().connect(
// sigc::mem_fun(*this, &FileView::on_frame_event));
} else {
fcd->set_position(Gtk::WIN_POS_CENTER_ALWAYS);
}
lock = false;
this->model = model;
label.set_use_markup(true);
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
maj_chemin(model->get_string());
# ifdef ANCIEN_BOUTON
bouton->set_action(Gtk::FILE_CHOOSER_ACTION_OPEN); // Ou Save impossible
bouton->set_width_chars(20);
bouton->signal_button_press_event().connect(sigc::mem_fun(*this, &VueFichier::gere_bouton));
std::string ext = model->schema->extension;
if (ext.size() > 0) {
Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
filter->set_name(ext + " file");
filter->add_pattern(std::string("*.") + ext);
bouton->add_filter(filter);
}
# endif
//ChangeEvent ce;
//on_event(ce);
//button->set_filename(model->get_string());
maj_chemin(model->get_string());
# ifdef ANCIEN_BOUTON
bouton->signal_selection_changed().connect(
sigc::mem_fun(*this, &VueFichier::gere_changement_fichier));
# endif
}
void VueFichier::maj_chemin(const std::string &s)
{
auto s2 = s;
//if(s.find("$DATA") != std::string::npos)
if(s.substr(0, 5) == "$DATA")
{
s2 = utils::get_fixed_data_path() + s.substr(5, s.size() - 5);
}
# ifdef ANCIEN_BOUTON
bouton->set_filename(s2);
# else
s2 = utils::str::get_filename_resume(s2);
bouton->set_label(s2);
# endif
}
void VueFichier::maj_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueFichier::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueFichier::get_widget(int index) {
if (index == 0)
return &label;
else
return bouton;
}
Gtk::Widget *VueFichier::get_gtk_widget()
{
return bouton;
}
void VueFichier::set_sensitive(bool b) {
label.set_sensitive(b);
bouton->set_sensitive(b);
}
void VueFichier::gere_changement_fichier()
{
# if 0
if (!lock) {
lock = true;
# ifdef ANCIEN_BOUTON
Glib::ustring s = bouton->get_filename();
# else
Glib::ustring s = bouton->get_label();
# endif
std::string s2 = s;
infos("Changement nom fichier sur bouton: [%s].", s2.c_str());
if(s2.size() > 0)
model->set_value(s);
lock = false;
}
# endif
}
void VueFichier::on_event(const ChangeEvent &ce) {
if (!lock)
{
lock = true;
auto s = model->get_string();
infos("Changement modele --> bouton [%s].", s.c_str());
maj_chemin(s);
//bouton->set_filename(s);
lock = false;
}
}
/*******************************************************************
* SERIAL VIEW IMPLEMENTATION *
*******************************************************************/
VueSelPortCOM::VueSelPortCOM(Attribute *model) {
lock = false;
this->model = model;
label.set_use_markup(true);
tree_model = Gtk::ListStore::create(columns);
combo.set_model(tree_model);
combo.pack_start(columns.m_col_name);
if (model->schema->has_unit())
combo.pack_start(columns.m_col_unit);
if(comm::Serial::enumerate(serials))
{
comm::SerialInfo si;
for(auto i = 0; i < 70; i++)
{
si.name = "COM" + utils::str::int2str(i);
si.complete_name = si.name;
si.techno = "";
serials.push_back(si);
}
}
update_langue();
combo.signal_changed().connect(
sigc::mem_fun(*this, &VueSelPortCOM::on_combo_changed));
}
void VueSelPortCOM::update_langue() {
bool old_lock = lock;
lock = true;
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
tree_model->clear();
for (unsigned int i = 0; i < serials.size(); i++) {
std::string valeur = serials[i].name;
std::string nom = serials[i].complete_name;
Gtk::TreeModel::Row row = *(tree_model->append());
row[columns.m_col_name] = str::latin_to_utf8(nom);
row[columns.m_col_real_name] = valeur;
}
for (unsigned int i = 0; i < serials.size(); i++) {
std::string valeur = serials[i].name;
std::string nom = serials[i].complete_name;
if ((model->get_string().compare(nom) == 0)
|| (model->get_string().compare(valeur) == 0)) {
combo.set_active(i);
break;
}
}
//if(i == serials.size())
//combo.set_active(0);
lock = old_lock;
}
unsigned int VueSelPortCOM::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueSelPortCOM::get_widget(int index) {
if (index == 0)
return &label;
else
return &combo;
}
Gtk::Widget *VueSelPortCOM::get_gtk_widget()
{
return &combo;
}
void VueSelPortCOM::set_sensitive(bool b) {
label.set_sensitive(b);
combo.set_sensitive(b);
}
void VueSelPortCOM::on_combo_changed() {
if (!lock) {
lock = true;
Gtk::TreeModel::iterator iter = combo.get_active();
if (iter) {
Gtk::TreeModel::Row row = *iter;
if (row) {
Glib::ustring name = row[columns.m_col_name];
Glib::ustring real_name = row[columns.m_col_real_name];
model->set_value(real_name);
}
} else
erreur("combo view: none selected.");
lock = false;
}
}
void VueSelPortCOM::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
for (unsigned int i = 0; i < serials.size(); i++) {
std::string valeur = serials[i].name;
std::string nom = serials[i].complete_name;
if ((model->get_string().compare(nom) == 0)
|| (model->get_string().compare(valeur) == 0)) {
combo.set_active(i);
break;
}
}
lock = false;
}
}
/*******************************************************************
* COLOR VIEW IMPLEMENTATION *
*******************************************************************/
VueChoixCouleur::VueChoixCouleur(Attribute *model) {
lock = false;
this->model = model;
label.set_use_markup(true);
update_langue();
Gdk::Color c;
std::vector<int> vec;
if(str::parse_int_list(model->get_string(), vec) == 0)
{
if(vec.size() == 3)
{
c.set_red(256 * vec[0]);
c.set_green(256 * vec[1]);
c.set_blue(256 * vec[2]);
}
}
color.set_color(c);
color.signal_color_set().connect(
sigc::mem_fun(*this, &VueChoixCouleur::on_color_changed));
//if(appli_view_prm.use_touchscreen)
{
cb = new ColorButton(model);
}
/*else
{
cb = nullptr;
}*/
}
void VueChoixCouleur::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueChoixCouleur::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueChoixCouleur::get_widget(int index) {
if (index == 0)
return &label;
else {
if (cb == nullptr)
return &color;
else
return cb;
}
}
Gtk::Widget *VueChoixCouleur::get_gtk_widget()
{
if (cb == nullptr)
return &color;
else
return cb;
}
void VueChoixCouleur::set_sensitive(bool b) {
label.set_sensitive(b);
color.set_sensitive(b);
}
void VueChoixCouleur::on_color_changed() {
if (!lock) {
lock = true;
Gdk::Color c = color.get_color();
char buf[100];
sprintf(buf, "%d.%d.%d", c.get_red() / 256, c.get_green() / 256,
c.get_blue() / 256);
model->set_value(std::string(buf));
lock = false;
}
}
void VueChoixCouleur::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
Gdk::Color c;
std::vector<int> vec;
str::parse_int_list(model->get_string(), vec);
if(vec.size() == 3)
{
c.set_red(256 * vec[0]);
c.set_green(256 * vec[1]);
c.set_blue(256 * vec[2]);
color.set_color(c);
}
lock = false;
}
}
/*******************************************************************
* STRING VIEW IMPLEMENTATION *
*******************************************************************/
VueChaine::VueChaine(Attribute *model, bool small_)
{
lock = false;
valid = model->schema->is_valid(model->get_string());
this->model = model;
label.set_use_markup(true);
update_langue();
entry.set_editable(true);
entry.set_text(model->get_string());
if (small_)
entry.set_width_chars(12);
else
entry.set_width_chars(30);
entry.signal_changed().connect(
sigc::mem_fun(*this, &VueChaine::on_signal_changed));
entry.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
update_valid();
}
VueChaine::~VueChaine()
{
//model->CProvider<ChangeEvent>::remove_listener(this);
}
void VueChaine::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueChaine::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueChaine::get_widget(int index) {
if (index == 0)
return &label;
else
return &entry;
}
Gtk::Widget *VueChaine::get_gtk_widget()
{
return &entry;
}
void VueChaine::set_sensitive(bool b)
{
entry.set_sensitive(b);
label.set_sensitive(b);
}
void VueChaine::update_valid()
{
update_text_color(entry, valid);
}
void VueChaine::on_signal_changed()
{
if (!lock) {
lock = true;
std::string s = entry.get_text();
valid = model->schema->is_valid(s);
model->set_value(entry.get_text());
update_valid();
model->forward_change_event();
lock = false;
}
}
bool VueChaine::is_valid() {
//infos("is_valid = %s.", valid ? "true" : "false");
return valid;
}
void VueChaine::on_event(const ChangeEvent &ce)
{
if (!lock)
{
lock = true;
entry.set_text(utils::str::latin_to_utf8(model->get_string()));
lock = false;
}
}
/*******************************************************************
* FIXED STRING VIEW IMPLEMENTATION *
*******************************************************************/
VueChaineConstante::VueChaineConstante(Attribute *model)
{
lock = false;
valid = model->schema->is_valid(model->get_string());
this->model = model;
label.set_use_markup(true);
update_langue();
//entry.set_editable(true);
ChangeEvent ce;
on_event(ce);
//entry.set_markup(model->get_string());
/*if (small_)
entry.set_width_chars(12);
else
entry.set_width_chars(30);*/
/*entry.signal_changed().connect(
sigc::mem_fun(*this, &StringView::on_signal_changed));
entry.signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));*/
update_valid();
}
void VueChaineConstante::update_langue() {
label.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueChaineConstante::get_nb_widgets() {
return 2;
}
Gtk::Widget *VueChaineConstante::get_widget(int index) {
if (index == 0)
return &label;
else
return &entry;
}
Gtk::Widget *VueChaineConstante::get_gtk_widget()
{
return &entry;
}
void VueChaineConstante::set_sensitive(bool b)
{
entry.set_sensitive(b);
label.set_sensitive(b);
}
void VueChaineConstante::update_valid()
{
//update_text_color(entry, valid);
}
/*void FixedStringView::on_signal_changed()
{
if (!lock) {
lock = true;
std::string s = entry.get_text();
valid = model->schema->is_valid(s);
model->set_value(entry.get_text());
update_valid();
model->forward_change_event();
lock = false;
}
}*/
bool VueChaineConstante::is_valid() {
//infos("is_valid = %s.", valid ? "true" : "false");
return valid;
}
void VueChaineConstante::on_event(const ChangeEvent &ce)
{
if (!lock)
{
lock = true;
std::string nom = model->get_string();
for (unsigned int j = 0; j < model->schema->enumerations.size(); j++)
{
Enumeration &e = model->schema->enumerations[j];
if (e.value.compare(nom) == 0) {
nom = e.name.get_localized();
break;
}
}
std::string s = utils::str::latin_to_utf8(nom);
//if(model->schema->has_unit())
// s += " " + model->schema->unit;
//if(model->schema->is_hexa)
// s = "0x" + s;
entry.set_markup(s);
lock = false;
}
}
}
}
}
| 41,776
|
C++
|
.cc
| 1,408
| 25.987216
| 122
| 0.602691
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,969
|
renderers.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/renderers.cc
|
#include "mmi/renderers.hpp"
#include "mmi/stdview.hpp"
#include "comm/serial.hpp"
#include <string.h>
//#include <malloc.h>
#include <stdlib.h>
#include <limits.h>
#include <memory>
#include <iostream>
using namespace std;
namespace utils
{
namespace mmi
{
RefCellEditable::RefCellEditable(const Glib::ustring& path/*,
Node model, std::string ref_name*/) :
Glib::ObjectBase( typeid(RefCellEditable) ),
Gtk::EventBox(),
Gtk::CellEditable(),
path_( path ),
entry_ptr_( 0 ),
button_ptr_( 0 ),
editing_cancelled_( false )
{
Gtk::HBox *const hbox = new Gtk::HBox(false, 0);
add (*Gtk::manage( hbox ));
// Find model and ref from path
// TODO
/*Gtk::TreeModel::iterator iter = tree_model->get_iter(path);
if(iter)
{
Gtk::TreeModel::Row row = *iter;
//setup_row_view(row[columns.m_col_ptr]);
update_view();
}*/
//entry_ptr_ = new Gtk::Entry();
//hbox->pack_start (*Gtk::manage(entry_ptr_), Gtk::PACK_EXPAND_WIDGET);
//entry_ptr_->set_has_frame (false);
//entry_ptr_->gobj()->is_cell_renderer = true;
entry_ptr_ = new Gtk::Label();
entry_ptr_->set_label("essai");
Gtk::Alignment *align1 = new Gtk::Alignment(0,0,1,1);
//Gtk::Alignment *align1 = new Gtk::Alignment(Gtk::ALIGN_START, Gtk::ALIGN_START, 1, 1);//(0,0,1,1);
//Gtk::Alignment *align2 = new Gtk::Alignment(Gtk::ALIGN_START, Gtk::ALIGN_START, 1, 1);//(0,0,1,1);
align1->add(*entry_ptr_);
hbox->pack_start (*align1, Gtk::PACK_EXPAND_WIDGET);
//hbox->pack_start (*Gtk::manage(entry_ptr_), Gtk::EXPAND_WIDGET);
//entry_ptr_->set_has_frame (false);
//entry_ptr_->gobj()->is_cell_renderer = true;
button_ptr_ = new Gtk::Button();
hbox->pack_start (*Gtk::manage( button_ptr_ ), Gtk::PACK_SHRINK);
button_ptr_->add (*Gtk::manage(new Gtk::Arrow(Gtk::ARROW_DOWN, Gtk::SHADOW_OUT)));
set_can_focus(true);
show_all_children();
}
RefCellEditable::~RefCellEditable()
{
}
Glib::ustring RefCellEditable::get_path() const
{
return path_;
}
void RefCellEditable::set_text(const Glib::ustring& text)
{
entry_ptr_->set_label(text);
}
Glib::ustring RefCellEditable::get_text() const
{
return "TODO";//model.get_reference(ref_name).get_localized().get_localized();
}
int RefCellEditable::get_button_width()
{
Gtk::Window window (Gtk::WINDOW_POPUP);
Gtk::Button *const button = new Gtk::Button();
window.add(*Gtk::manage(button));
button->add(*Gtk::manage(new Gtk::Arrow(Gtk::ARROW_DOWN, Gtk::SHADOW_OUT)));
window.move(-500, -500);
window.show_all();
//Gtk::Requisition requisition = window.size_request();
//return requisition.width;
int min,nat;
//Gtk::Requisition r0,r1;
window.get_preferred_width(min,nat);
return nat;
}
/* static */ int RefCellEditable::get_color_area_width()
{
return 16;
}
void RefCellEditable::start_editing_vfunc(GdkEvent*)
{
//entry_ptr_->select_region(0, -1);
//entry_ptr_->signal_activate().connect(sigc::mem_fun(*this, &RefCellEditable::on_entry_activate));
//entry_ptr_->signal_key_press_event().connect(sigc::mem_fun(*this, &RefCellEditable::on_entry_key_press_event));
button_ptr_->signal_clicked().connect (sigc::mem_fun( *this, &RefCellEditable::on_button_clicked ));
}
void RefCellEditable::on_editing_done()
{
//std::cout << "on_editing_done " << editing_cancelled_ << std::endl;
/*if (!editing_cancelled_)
{
int r = 0;
int g = 0;
int b = 0;
std::string s = entry_ptr_->get_text();
ByteArray ba(s);
r = ba[0];
g = ba[1];
b = ba[2];
color_.set_rgb(r * 256, g * 256, b * 256);
}*/
signal_editing_done_.emit();
}
void RefCellEditable::on_button_clicked()
{
infos("show ref. explorer..");
if(model.is_nullptr())
{
erreur("on_button_clicked(): nullptr model");
return;
}
RefSchema *rs = model.schema()->get_reference(ref_name);
if(rs != nullptr)
{
infos("find root..");
Node root = model.get_child(rs->path);
if(!root.is_nullptr())
{
infos("root found.");
RefExplorerWnd *re = new RefExplorerWnd(root, rs->child_str);
if(re->display() == 0)
{
infos("update ref..");
model.set_reference(ref_name, re->get_selection());
}
}
else
{
erreur("root not found.");
}
}
else
{
erreur("ref schema not found");
}
signal_editing_done_.emit();
}
bool RefCellEditable::on_entry_key_press_event(GdkEventKey* event)
{
if (event->keyval == GDK_KEY_Escape)
{
editing_cancelled_ = true;
editing_done();
remove_widget();
return true;
}
return false;
}
void RefCellEditable::on_entry_activate()
{
if(!appli_view_prm.use_touchscreen)
editing_done();
}
RefCellRenderer::RefCellRenderer(/*Node model, std::string ref_name*/) :
Glib::ObjectBase( typeid(RefCellRenderer) ),
Gtk::CellRenderer(),
property_text_( *this, "text", "" ),
property_editable_( *this, "editable", true ),
color_cell_edit_ptr_( 0 ),
button_width_( -1 )
{
//this->model = model;
//this->ref_name = ref_name;
property_mode() = Gtk::CELL_RENDERER_MODE_EDITABLE;
property_xpad() = 2;
property_ypad() = 2;
}
RefCellRenderer::~RefCellRenderer()
{
}
Glib::PropertyProxy< Glib::ustring > RefCellRenderer::property_text()
{
return property_text_.get_proxy();
}
Glib::PropertyProxy< bool > RefCellRenderer::property_editable()
{
return property_editable_.get_proxy();
}
/* override */void RefCellRenderer::get_size_vfunc (Gtk::Widget& widget, const Gdk::Rectangle* cell_area, int* x_offset, int* y_offset, int* width, int* height) const
{
// We cache this because it takes a really long time to get the width.
if(button_width_ < 0)
button_width_ = RefCellEditable::get_button_width();
// Compute text width
Glib::RefPtr<Pango::Layout> layout_ptr = widget.create_pango_layout (property_text_);
Pango::Rectangle rect = layout_ptr->get_pixel_logical_extents();
const int calc_width = property_xpad() * 4 + rect.get_width();
const int calc_height = property_ypad() * 4 + rect.get_height();
// Add button width and color area width
if( width )
*width = calc_width + button_width_ + RefCellEditable::get_color_area_width();
if( height )
*height = calc_height;
}
// TODO
#if 0
void RefCellRenderer::render_vfunc (const Glib::RefPtr<Gdk::Drawable>& window, Gtk::Widget& widget, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, const Gdk::Rectangle& expose_area, Gtk::CellRendererState flags)
{
// Get cell size
int x_offset = 0, y_offset = 0, width = 0, height = 0;
get_size (widget, cell_area, x_offset, y_offset, width, height);
// Create the graphic context
Glib::RefPtr< Cairo::Context > gc = Cairo::Context::create (window);
// Get cell state
//Gtk::StateType state;
Gtk::StateType text_state;
if ((flags & Gtk::CELL_RENDERER_SELECTED) != 0)
{
//state = Gtk::STATE_SELECTED;
text_state = (widget.has_focus()) ? Gtk::STATE_SELECTED : Gtk::STATE_ACTIVE;
}
else
{
//state = Gtk::STATE_NORMAL;
text_state = (widget.is_sensitive()) ? Gtk::STATE_NORMAL : Gtk::STATE_INSENSITIVE;
}
// Draw color text
Glib::RefPtr< Gdk::Window > win = Glib::RefPtr<Gdk::Window>::cast_dynamic (window);
Glib::RefPtr<Pango::Layout> layout_ptr = widget.create_pango_layout( property_text_ );
widget.get_style()->paint_layout (win,
text_state,
true,
cell_area,
widget,
"cellrenderertext",
cell_area.get_x() /*+ RefCellEditable::get_color_area_width()*/ + x_offset + /*2 **/ property_xpad(),
cell_area.get_y() + y_offset + 2 * property_ypad(),
layout_ptr);
}
#endif
bool RefCellRenderer::activate_vfunc (GdkEvent*, Gtk::Widget&, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags)
{
return true;
}
void RefCellEditable::setup_model(Node model, std::string ref_name)
{
infos("Setup model %s ok!", ref_name.c_str());
infos("model = %s.", model.to_xml().c_str());
this->model = model;
this->ref_name = ref_name;
}
Gtk::CellEditable* RefCellRenderer::start_editing_vfunc(GdkEvent *event,
Gtk::Widget &widget,
const Glib::ustring &path,
const Gdk::Rectangle &background_area,
const Gdk::Rectangle &cell_area,
Gtk::CellRendererState flags)
{
infos("start editing..");
//StringListView *slv = (StringListView *) &widget;
if(appli_view_prm.use_touchscreen)
return 0;
#ifdef GLIBMM_PROPERTIES_ENABLED
if (!property_editable())
return 0;
#else
if (!(g_object_get_data(G_OBJECT(gobj()), "editable")))
return 0;
#endif
//std::auto_ptr<RefCellEditable> color_cell_edit_ptr(new RefCellEditable(path));
auto color_cell_edit_ptr = new RefCellEditable(path);
Glib::ustring text;
#ifdef GLIBMM_PROPERTIES_ENABLED
text = property_text();
#else
get_property("text", text);
#endif
color_cell_edit_ptr->set_text (text);
color_cell_edit_ptr->signal_editing_done().connect(sigc::mem_fun(*this, &RefCellRenderer::on_editing_done));
color_cell_edit_ptr->show();
color_cell_edit_ptr_ = Gtk::manage(color_cell_edit_ptr);//.release() );
return color_cell_edit_ptr_;
}
void RefCellRenderer::edited(const Glib::ustring& path, const Glib::ustring& new_text)
{
signal_edited_.emit (path, new_text);
}
void RefCellRenderer::on_editing_done()
{
if (color_cell_edit_ptr_->get_editing_cancelled())
{
stop_editing (true);
}
else
{
edited (color_cell_edit_ptr_->get_path(), color_cell_edit_ptr_->get_text());
}
}
static bool has_child(NodeSchema *root, std::string type, std::vector<NodeSchema *> &already_checked)
{
unsigned int i;
for(i = 0; i < already_checked.size(); i++)
{
if(already_checked[i] == root)
return false;
}
already_checked.push_back(root);
if(root->name.get_id().compare(type) == 0)
return true;
for(i = 0; i < root->children.size(); i++)
{
if(root->children[i].name.get_id().compare(type) == 0)
return true;
if(has_child(root->children[i].ptr, type, already_checked))
return true;
}
return false;
}
static bool has_child(NodeSchema *root, std::string type)
{
std::vector<NodeSchema *> already_checked;
return has_child(root, type, already_checked);
}
RefExplorerWnd::RefExplorerWnd(Node model, const std::string &ref_name, const std::string &wnd_title):
GenDialog(GenDialog::GEN_DIALOG_VALID_CANCEL), explorer(model, ref_name)
{
if(wnd_title.size() > 0)
set_title(wnd_title);
else
set_title(langue.get_item("sel-ref"));
this->model = model;
this->ref_name = ref_name;
vbox->pack_start(explorer, Gtk::PACK_EXPAND_WIDGET);
explorer.add_listener(this, &RefExplorerWnd::on_change);
set_size_request(500, 400);
update_view();
show_all_children(true);
}
int RefExplorerWnd::display()
{
return display_modal();
}
void RefExplorerWnd::on_change(const RefExplorerChange &change)
{
update_view();
}
void RefExplorerWnd::update_view()
{
bool selection_ok = false;
Node sel = get_selection();
if(!sel.is_nullptr())
{
if((sel.schema()->name.get_id().compare(ref_name) == 0) || (ref_name.size() == 0))
selection_ok = true;
}
enable_validation(selection_ok);
}
Node RefExplorerWnd::get_selection()
{
return explorer.get_selection();
}
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
RefExplorer::RefExplorer()
{
valid = false;
init_done = false;
}
void RefExplorer::setup(Node model,
std::string ref_name,
const std::string &title)
{
this->model = model;
this->ref_name = ref_name;
set_label(title);
if(!init_done)
{
tree_view.set_headers_visible(false);
scroll.add(tree_view);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
scroll.set_border_width(5);
add(scroll);
}
tree_model = Gtk::TreeStore::create(columns);
tree_view.set_model(tree_model);
Gtk::TreeViewColumn *tvc = Gtk::manage(new Gtk::TreeViewColumn());
Gtk::CellRendererText *crt = new Gtk::CellRendererText();
tvc->pack_start(*crt, true);
tvc->add_attribute(crt->property_markup(), columns.m_col_name);
tree_view.append_column(*tvc);
tree_view.signal_row_activated().connect(sigc::mem_fun(*this,
&RefExplorer::on_treeview_row_activated));
Glib::RefPtr<Gtk::TreeSelection> refTreeSelection = tree_view.get_selection();
refTreeSelection->signal_changed().connect(
sigc::mem_fun(*this, &RefExplorer::on_selection_changed));
populate();
update_view();
show_all_children(true);
init_done = true;
}
RefExplorer::RefExplorer(Node model, std::string ref_name, const std::string &title)
{
valid = false;
init_done = false;
}
static bool has_such_child(Node root, const string &type)
{
unsigned int i, j, n, m;
if(root.schema()->name.get_id().compare(type) == 0)
return true;
if(root.has_child(type))
{
cout << "HAS SUCH CHILD: " << type << endl << root.to_xml() << endl;
return true;
}
n = root.schema()->children.size();
for(i = 0; i < n; i++)
{
string sname = root.schema()->children[i].name.get_id();
m = root.get_children_count(sname);
for(j = 0; j < m; j++)
{
if(has_such_child(root.get_child_at(sname, j), type))
return true;
}
}
return false;
}
void RefExplorer::populate()
{
unsigned int i, j, n;
tree_model->clear();
for(i = 0; i < model.schema()->children.size(); i++)
{
SubSchema ss = model.schema()->children[i];
NodeSchema *schema = ss.ptr;
bool candidate = has_child(schema, ref_name) || (ref_name.size() == 0);
infos("schema[%s]: candidate = %s.", schema->name.get_id().c_str(), candidate ? "true" : "false");
if(candidate)
{
n = model.get_children_count(schema->name.get_id());
for(j = 0; j < n; j++)
{
Node ch = model.get_child_at(schema->name.get_id(), j);
if((ref_name.size() == 0) || has_such_child(ch, ref_name) )
{
Gtk::TreeModel::Row subrow = *(tree_model->append());
subrow[columns.m_col_name] = ch.get_identifier(false);
subrow[columns.m_col_ptr] = ch;
populate(ch, subrow);
}
}
}
}
tree_view.expand_all();
}
void RefExplorer::populate(Node root, Gtk::TreeModel::Row row)
{
unsigned int i, j, n;
for(i = 0; i < root.schema()->children.size(); i++)
{
SubSchema ss = root.schema()->children[i];
NodeSchema *schema = ss.ptr;
n = root.get_children_count(schema->name.get_id());
for(j = 0; j < n; j++)
{
Node ch = root.get_child_at(schema->name.get_id(), j);
if((ref_name.size() == 0) || has_such_child(ch, ref_name))
{
Gtk::TreeModel::Row subrow = *(tree_model->append(row.children()));
subrow[columns.m_col_name] = ch.get_identifier(false);
subrow[columns.m_col_ptr] = ch;
populate(ch, subrow);
}
}
}
}
void RefExplorer::update_view()
{
valid = false;
Node sel = get_selection();
if(!sel.is_nullptr())
{
if((sel.schema()->name.get_id().compare(ref_name) == 0) || (ref_name.size() == 0))
valid = true;
}
}
bool RefExplorer::is_valid()
{
return valid;
}
void RefExplorer::clear_table()
{
}
void RefExplorer::on_treeview_row_activated(const Gtk::TreeModel::Path &path, Gtk::TreeViewColumn *)
{
Gtk::TreeModel::iterator iter = tree_model->get_iter(path);
if(iter)
{
//Gtk::TreeModel::Row row = *iter;
//setup_row_view(row[columns.m_col_ptr]);
update_view();
RefExplorerChange ch;
CProvider<RefExplorerChange>::dispatch(ch);
}
}
Node RefExplorer::get_selection()
{
Glib::RefPtr<Gtk::TreeSelection> refTreeSelection = tree_view.get_selection();
Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();
Node result;
if(iter)
{
Gtk::TreeModel::Row ligne = *iter;
result = ligne[columns.m_col_ptr];
}
return result;
}
void RefExplorer::on_selection_changed()
{
update_view();
RefExplorerChange ch;
CProvider<RefExplorerChange>::dispatch(ch);
}
}
}
| 16,574
|
C++
|
.cc
| 527
| 27.037951
| 236
| 0.641192
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,970
|
gtkutil.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/gtkutil.cc
|
#include "mmi/gtkutil.hpp"
#include "mmi/stdview.hpp"
#include "mxml.hpp"
#include <gdkmm/color.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <ctime>
#include <stdio.h>
#ifdef WIN
# include <windows.h>
# include <stdio.h>
#else
# include <sys/stat.h>
#endif
#define DEBOGUE_VUE_IMAGE(AA)
using namespace std;
#if 0
static uint32_t grayer(uint32_t val)
{
/*int32_t diff = 32768 - val;
diff = diff / 3;
return 32768 - diff;*/
return val / 3;
}
#endif
namespace utils
{
namespace mmi
{
using namespace utils;
Gtk::Window *mainWindow;
VideoView::VideoView(uint16_t dx, uint16_t dy, bool dim_from_parent)
: Gtk::DrawingArea(), dispatcher(16)
{
realise = false;
csx = 1;
csy = 1;
this->dim_from_parent = dim_from_parent;
signal_realize().connect(sigc::mem_fun(*this, &VideoView::on_the_realisation));
//signal_video_update.connect(sigc::mem_fun(*this, &VideoView::on_video_update));
dispatcher.add_listener(this, &VideoView::on_event);
change_dim(dx,dy);
if(!dim_from_parent)
set_size_request(csx,csy);
}
void VideoView::get_dim(uint16_t &sx, uint16_t &sy)
{
sx = get_allocated_width();
sy = get_allocated_height();
}
void VideoView::change_dim(uint16_t sx, uint16_t sy)
{
if((csx != sx) || (csy != sy))
{
csx = sx;
csy = sy;
if(!dim_from_parent)
set_size_request(csx,csy);
image_surface = Cairo::ImageSurface::create(Cairo::Format::FORMAT_RGB24, sx, sy);
}
}
void VideoView::update(void *img, uint16_t sx, uint16_t sy)
{
if(!realise)
{
avertissement("video view update : non realise.");
//return;
}
if(dispatcher.is_full())
{
avertissement("VideoView::maj: FIFO de sortie pleine, on va ignorer quelques trames...");
//return;
dispatcher.clear();
}
Trame t;
if((this->csx == sx) && (this->csy == sy))
{
t.img = nullptr;
memcpy(this->image_surface->get_data(), img, 4 * sx * sy);
}
else
{
t.img = malloc(sx*sy*4);
memcpy(t.img, img, sx*sy*4);
}
t.sx = sx;
t.sy = sy;
dispatcher.on_event(t);
}
void VideoView::on_event(const Trame &t)
{
uint16_t sx = t.sx, sy = t.sy;
change_dim(sx,sy);
if(t.img != nullptr)
{
memcpy(this->image_surface->get_data(), t.img, 4 * sx * sy);
free(t.img);
}
queue_draw();
}
void VideoView::draw_all()
{
GdkEventExpose evt;
evt.area.x = 0;
evt.area.y = 0;
evt.area.width = get_allocation().get_width();
evt.area.height = get_allocation().get_height();
on_expose_event(&evt);
}
// Pas vraiment utilsé
bool VideoView::on_expose_event(GdkEventExpose* event)
{
do_update_view();
return true;
}
void VideoView::do_update_view()
{
if(!realise)
return;
if(!cr)
{
auto wnd = get_window();
if(!wnd)
{
realise = false;
return;
}
cr = wnd->create_cairo_context();
}
//trace_verbeuse("dessine(%d,%d)", csx, csy);
cr->set_source(this->image_surface, 0, 0);
cr->rectangle (0.0, 0.0, csx, csy);
cr->clip();
cr->paint();
}
// C'est ici qu'on dessine !
bool VideoView::on_draw(const Cairo::RefPtr<Cairo::Context> &cr)
{
this->cr = cr;
do_update_view();
return true;
}
void VideoView::on_the_realisation()
{
infos("Vue video : realise.");
realise = true;
do_update_view();
}
void set_theme(std::string theme_name)
{
# if 0
std::string s = "include \"";
s += theme_name + "/gtk-2.0/gtkrc\"\n";
s += "gtk-theme-name = \"" + theme_name + "\"\n";
files::save_txt_file("./theme-sel.txt", s);
gtk_rc_add_default_file("./theme-sel.txt");
GtkSettings* settings = gtk_settings_get_default();
gtk_rc_reparse_all_for_settings(settings, true);
# endif
}
static std::vector<std::pair<Gtk::Widget *, Gtk::Window *> > wnd_list;
static uint32_t add_color(uint32_t corig,
float c,
uint8_t r, uint8_t g, uint8_t b)
{
int cr, cg, cb;
int ocb = (corig >> 16) & 0xff;
int ocg = (corig >> 8) & 0xff;
int ocr = corig & 0xff;
cr = (uint32_t) (c * r);
cg = (uint32_t) (c * g);
cb = (uint32_t) (c * b);
cr = ocr + cr;
cg = ocg + cg;
cb = ocb + cb;
if(cr > 255)
cr = 255;
if(cb > 255)
cb = 255;
if(cg > 255)
cg = 255;
uint32_t col = (cb << 16) | (cg << 8) | cr;
return col;
}
static uint32_t sub_color(uint32_t corig,
float c,
uint8_t r, uint8_t g, uint8_t b)
{
int cr, cg, cb;
int ocb = (corig >> 16) & 0xff;
int ocg = (corig >> 8) & 0xff;
int ocr = corig & 0xff;
cr = (uint32_t) (c * (255-r));
cg = (uint32_t) (c * (255-g));
cb = (uint32_t) (c * (255-b));
cr = ocr - cr;
cg = ocg - cg;
cb = ocb - cb;
if(cr < 0)
cr = 0;
if(cg < 0)
cg = 0;
if(cb < 0)
cb = 0;
uint32_t col = (cb << 16) | (cg << 8) | cr;
return col;
}
typedef uint32_t (*update_color_t)(uint32_t orig,
float c,
uint8_t r, uint8_t g, uint8_t b);
void AntiliasingDrawing::draw_line(uint32_t *img,
uint32_t img_width,
uint32_t img_height,
int x1, int y1,
int x2, int y2,
GColor color,
bool mat_on_white)
{
int x, y;
update_color_t update_color = mat_on_white ? &sub_color : &add_color;
if((fabs(y2 - y1) > (int) img_height)
|| (fabs(x2 - x1) > (int) img_width))
{
//anomaly("Y2 = %d, Y1 = %d.", y2, y1);
//::Sleep(1000);
return;
}
/* Ensure x2 >= x1 */
if(x2 < x1)
{
/* Swap (x1,y1) and (x2,y2) */
int tmp;
tmp = y1;
y1 = y2;
y2 = tmp;
tmp = x1;
x1 = x2;
x2 = tmp;
}
if(y2 == y1)
{
y = y1;
if((y1 >= 0) && (y1 < (int) img_height))
{
for(x = x1; (x < x2) && (x < (int) img_width) && (x >= 0); x++)
{
img[x+y*img_width] = update_color(img[x+y*img_width],
1.0, color.red, color.green, color.blue);
}
}
}
else if(x1 == x2)
{
x = x1;
if(y2 < y1)
{
int tmp;
tmp = y2;
y2 = y1;
y1 = tmp;
}
for(y = y1; (y >= 0) && (y < y2) && (y < (int) img_height); y++)
{
img[x+y*img_width] = update_color(img[x+y*img_width],
1.0, color.red, color.green, color.blue);
}
}
else if(fabs(y2 - y1) > (x2 - x1))
{
float gradient = fabs(((float) (x2 - x1)) / (y2 - y1));
float interx = x1;
if(y2 > y1)
{
for(int y = y1; (y <= y2) && (y < (int) img_height); y++)
{
x = (int) floor(interx);
float intensity = interx - x;
if((x < 0) || (y < 0) || (x >= (int) img_width))
continue;
img[x+y*img_width] = update_color(img[x+y*img_width],
1.0 - intensity, color.red, color.green, color.blue);
img[x+y*img_width] = update_color(img[x+y*img_width],
intensity, color.red, color.green, color.blue);
interx += gradient;
}
}
/* y1 > y2 */
else
{
interx = x2;
for(int y = y2; (y <= y1) && (y < (int) img_height); y++)
{
x = (int) floor(interx);
float intensity = interx - x;
if((x < 0) || (y < 0) || (x >= (int) img_width))
continue;
img[x+y*img_width] = update_color(img[x+y*img_width],
1.0 - intensity, color.red, color.green, color.blue);
img[x+y*img_width] = update_color(img[x+y*img_width],
intensity, color.red, color.green, color.blue);
interx += gradient;
}
}
}
/* x2 - x1 >= y2 - y1 */
else
{
float gradient = fabs(((float)(y2 - y1)) / (x2 - x1));
float intery = y1;
if(y2 < y1)
intery = y2;
for(x = x1; (x <= x2) && (x < (int) img_width); x++)
{
y = (int) floor(intery);
float intensity = intery - y;
if((x < 0) || (y < 0) || (y >= (int) img_height))
continue;
img[x+y*img_width] = update_color(img[x+y*img_width],
1.0 - intensity, color.red, color.green, color.blue);
img[x+y*img_width] = update_color(img[x+y*img_width],
intensity, color.red, color.green, color.blue);
intery += gradient;
}
}
# if 0
if(y2 > y1)
{
float gradient = 1.0 / (y2 - y1);
float interx = 0;
for(int y = y1; y <= y2; y++)
{
unsigned int *ptr = &(buffer[x1+y*2*x_width]);
if((x1 > 0) && (x1 + 1 < 2*MAXX) && (y > 0) && (y < MAXY))
{
draw_point(ptr, 1.0 - interx);
draw_point(ptr+1, interx);
}
interx += gradient;
}
}
else if(y2 < y1)
{
float gradient = 1.0 / (y1 - y2);
float interx = 0;
for(int y = y1; y >= y2; y--)
{
unsigned int *ptr = &(buffer[x1+y*2*x_width]);
if((x1 > 0) && (x1 + 1 < 2*MAXX) && (y > 0) && (y < MAXY))
{
draw_point(ptr, 1.0 - interx);
draw_point(ptr+1, interx);
}
interx += gradient;
}
}
else
{
if((x1 > 0) && (x1 + 1 < 2*MAXX) && (y1 > 0) && (y1 < MAXY))
{
unsigned int *ptr = &(buffer[x1+y1*2*x_width]);
draw_point(ptr, 1.0);
}
}
# endif
}
void show_frame_window(Gtk::Widget *frame, std::string name)
{
unsigned int i;
Gtk::Window *wnd = nullptr;
for(i = 0; i < wnd_list.size(); i++)
{
if(wnd_list[i].first == frame)
{
wnd = wnd_list[i].second;
break;
}
}
if(i == wnd_list.size())
{
wnd = new Gtk::Window();
wnd->add(*frame);
}
wnd->set_title(name);
wnd->show_all_children(true);
wnd->show();
}
class SimpleDialog: public Gtk::Dialog
{
public:
SimpleDialog(std::string title, bool modal, std::string dsc1, std::string dsc2, Gtk::BuiltinStockID sid);
~SimpleDialog();
void on_b_ok();
void on_b_cancel();
int result;
Gtk::HButtonBox hbbox;
Gtk::HBox hbox;
Gtk::VBox vbox;
Gtk::Label label1, label2;
Gtk::Image img;
Gtk::Button bt;
Gtk::Image *bim;
};
SimpleDialog::~SimpleDialog()
{
delete bim;
}
SimpleDialog::SimpleDialog(std::string title,
bool modal,
std::string dsc1,
std::string dsc2,
Gtk::BuiltinStockID sid):
Gtk::Dialog(title, modal),
img(Gtk::StockID(sid), Gtk::IconSize(Gtk::ICON_SIZE_DIALOG))
{
Gtk::Box *vb = get_vbox();
bt.set_label(langue.get_item("close"));
if(!appli_view_prm.use_decorations)
set_decorated(false);
if(sid == Gtk::Stock::DIALOG_ERROR)
{
if(appli_view_prm.img_cancel.size() > 0)
bim = new Gtk::Image(appli_view_prm.img_cancel);
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
}
else if(sid == Gtk::Stock::DIALOG_WARNING)
{
if(appli_view_prm.img_cancel.size() > 0)
bim = new Gtk::Image(appli_view_prm.img_cancel);
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::CLOSE), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
}
else if(sid == Gtk::Stock::DIALOG_INFO)
{
if(appli_view_prm.img_validate.size() > 0)
bim = new Gtk::Image(appli_view_prm.img_validate);
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::APPLY), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
}
bt.set_image(*bim);
bt.set_image_position(Gtk::POS_TOP);
label1.set_markup("<b>" + dsc1 + "</b>\n");
label2.set_markup(dsc2 + "\n");
//Gtk::Image *img = (Gtk::StockID(Gtk::DIALOG_ERROR));
hbox.pack_start(img);
hbox.pack_start(vbox);
vbox.pack_start(label1);
vbox.pack_start(label2);
hbbox.set_layout(Gtk::BUTTONBOX_END);
hbbox.pack_end(bt);
vb->pack_start(hbox);
vb->pack_start(hbbox);
set_position(Gtk::WIN_POS_CENTER);
bt.signal_clicked().connect(sigc::mem_fun(*this, &SimpleDialog::on_b_ok));
show_all_children(true);
}
void SimpleDialog::on_b_ok()
{
result = 0;
hide();
}
void SimpleDialog::on_b_cancel()
{
result = 1;
hide();
}
bool dialogs::check_dialog(std::string title,
std::string short_description,
std::string description)
{
Gtk::MessageDialog dial(short_description, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK_CANCEL, true);
dial.set_title(title);
dial.set_secondary_text(description);
DialogManager::setup_window(&dial);
int result = dial.run();
if(result == Gtk::RESPONSE_OK)
return true;
return false;
}
void dialogs::affiche_infos(std::string title, std::string short_description, std::string description)
{
if(appli_view_prm.img_cancel.size() == 0)
{
Gtk::MessageDialog dial(short_description, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, true);
dial.set_title(title);
dial.set_secondary_text(description);
dial.set_position(Gtk::WIN_POS_CENTER);
DialogManager::setup_window(&dial);
dial.run();
}
else
{
SimpleDialog dial(title,
true,
short_description,
description,
Gtk::Stock::DIALOG_INFO);
DialogManager::setup_window(&dial);
dial.run();
}
}
void dialogs::affiche_infos_localisee(const std::string &id_locale)
{
auto desc = utils::langue.get_localized(id_locale);
Gtk::MessageDialog dial(desc.get_description(utils::model::Localized::current_language),
false,
Gtk::MESSAGE_INFO,
Gtk::BUTTONS_CLOSE,
true);
dial.set_title(desc.get_localized());
//dial.set_secondary_text(description);
dial.set_position(Gtk::WIN_POS_CENTER);
DialogManager::setup_window(&dial);
dial.run();
}
void dialogs::affiche_avertissement_localise(const std::string &id_locale)
{
auto desc = utils::langue.get_localized(id_locale);
Gtk::MessageDialog dial(desc.get_description(utils::model::Localized::current_language),
false,
Gtk::MESSAGE_WARNING,
Gtk::BUTTONS_CLOSE,
true);
dial.set_title(desc.get_localized());
//dial.set_secondary_text(description);
dial.set_position(Gtk::WIN_POS_CENTER);
DialogManager::setup_window(&dial);
dial.run();
}
void dialogs::affiche_erreur_localisee(const std::string &id_locale)
{
auto desc = utils::langue.get_localized(id_locale);
Gtk::MessageDialog dial(desc.get_description(utils::model::Localized::current_language),
false,
Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE,
true);
dial.set_title(desc.get_localized());
//dial.set_secondary_text(description);
dial.set_position(Gtk::WIN_POS_CENTER);
DialogManager::setup_window(&dial);
dial.run();
}
void dialogs::affiche_erreur(std::string title,
std::string short_description,
std::string description)
{
if(appli_view_prm.img_cancel.size() == 0)
{
Gtk::MessageDialog dial(short_description,
false,
Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE,
true);
dial.set_title(title);
dial.set_secondary_text(description);
dial.set_position(Gtk::WIN_POS_CENTER);
DialogManager::setup_window(&dial);
dial.run();
}
else
{
SimpleDialog dial(title,
true,
short_description,
description,
Gtk::Stock::DIALOG_ERROR);
DialogManager::setup_window(&dial);
dial.run();
}
}
void dialogs::affiche_avertissement(std::string title,
std::string short_description,
std::string description,
bool blocking)
{
if(appli_view_prm.img_cancel.size() == 0)
{
Gtk::MessageDialog dial(short_description, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK, true);
dial.set_title(title);
dial.set_secondary_text(description);
dial.set_position(Gtk::WIN_POS_CENTER);
DialogManager::setup_window(&dial);
if(blocking)
dial.run();
else
dial.show();
}
else
{
SimpleDialog dial(title,
true,
short_description,
description,
Gtk::Stock::DIALOG_WARNING);
DialogManager::setup_window(&dial);
if(blocking)
dial.run();
else
dial.show();
}
}
std::string dialogs::ouvrir_fichier_loc(const std::string &id_locale,
const std::string &filtre, const std::string &id_filtre,
std::string default_dir)
{
auto desc = utils::langue.get_localized(id_locale);
auto filt = utils::langue.get_localized(id_filtre);
return ouvrir_fichier(desc.get_localized(),
filtre,
filt.get_localized(), "", default_dir);
}
std::string dialogs::enregistrer_fichier_loc(const std::string &id_locale,
const std::string filtre, const std::string &id_filtre,
const std::string &default_dir)
{
auto desc = utils::langue.get_localized(id_locale);
auto filt = utils::langue.get_localized(id_filtre);
return enregistrer_fichier(desc.get_localized(),
filtre,
filt.get_localized(), "", default_dir);
}
std::string dialogs::enregistrer_fichier(std::string title, std::string filter, std::string filter_name,
std::string default_name, std::string default_dir)
{
Gtk::FileChooserDialog dialog(title, Gtk::FILE_CHOOSER_ACTION_SAVE);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
if(mainWindow != nullptr)
dialog.set_transient_for(*mainWindow);
dialog.set_modal(true);
//Add response buttons the the dialog:
dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
//Add filters, so that only certain file types can be selected:
Glib::RefPtr<Gtk::FileFilter> filter_xml = Gtk::FileFilter::create();
filter_xml->set_name(filter_name);
filter_xml->add_mime_type(std::string("*") + filter);
dialog.add_filter(filter_xml);
if(default_dir.size() > 0)
dialog.set_current_folder(default_dir);
//Show the dialog and wait for a user response:
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::string filename = dialog.get_filename();
std::string ext = utils::files::get_extension(filename);
if(ext.size() == 0)
{
//auto ext2 = utils::files::get_extension(ext);
infos("Pas d'extension precisee, ajout de %s", filter.c_str());
if((filter.size() > 0) && (filter[0] == '.'))
filename += filter;
}
dialog.hide();
return filename;
}
case(Gtk::RESPONSE_CANCEL):
{
return "";
}
default:
{
return "";
}
}
return "";
}
std::string dialogs::selection_dossier(const std::string &titre)
{
Gtk::FileChooserDialog dialog(titre, Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
if(mainWindow != nullptr)
dialog.set_transient_for(*mainWindow);
dialog.set_modal(true);
dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
dialog.set_select_multiple(false);
dialog.set_show_hidden(false);
//Show the dialog and wait for a user response:
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::string filename = dialog.get_filename();
dialog.hide();
return filename;
}
case(Gtk::RESPONSE_CANCEL):
{
return "";
}
default:
{
return "";
}
}
return "";
}
std::string dialogs::ouvrir_fichier(std::string title, std::string filter, std::string filter_name,
std::string default_name, std::string default_dir)
{
Gtk::FileChooserDialog dialog(title, Gtk::FILE_CHOOSER_ACTION_OPEN);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
if(mainWindow != nullptr)
dialog.set_transient_for(*mainWindow);
dialog.set_modal(true);
//Add response buttons the the dialog:
dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
//Add filters, so that only certain file types can be selected:
//Gtk::FileFilter filter_xml;
Glib::RefPtr<Gtk::FileFilter> filter_xml = Gtk::FileFilter::create();
filter_xml->set_name(filter_name);
//filter_xml.add_mime_type(filter);
filter_xml->add_pattern(filter);
dialog.add_filter(filter_xml);
Glib::RefPtr<Gtk::FileFilter> filter_any = Gtk::FileFilter::create();
filter_any->set_name("Any files");
filter_any->add_pattern("*");
dialog.add_filter(filter_any);
dialog.set_select_multiple(false);
dialog.set_show_hidden(false);
if(default_dir.size() > 0)
dialog.set_current_folder(default_dir);
//Show the dialog and wait for a user response:
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::string filename = dialog.get_filename();
dialog.hide();
return filename;
}
case(Gtk::RESPONSE_CANCEL):
{
return "";
}
default:
{
return "";
}
}
return "";
}
std::string dialogs::nouveau_fichier(std::string title, std::string filter, std::string filter_name,
std::string default_name, std::string default_dir)
{
Gtk::FileChooserDialog dialog(title, Gtk::FILE_CHOOSER_ACTION_SAVE);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
if(mainWindow != nullptr)
dialog.set_transient_for(*mainWindow);
dialog.set_modal(true);
//Add response buttons the the dialog:
dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
//Add filters, so that only certain file types can be selected:
Glib::RefPtr<Gtk::FileFilter> filter_xml = Gtk::FileFilter::create();
filter_xml->set_name(filter_name);
filter_xml->add_mime_type(filter);
dialog.add_filter(filter_xml);
Glib::RefPtr<Gtk::FileFilter> filter_any = Gtk::FileFilter::create();
filter_any->set_name("Any files");
filter_any->add_pattern("*");
dialog.add_filter(filter_any);
//dialog.set_filename(default_name + ".xml");
//Show the dialog and wait for a user response:
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::string filename = dialog.get_filename();
std::string ext = files::get_extension(filename);
if(ext.compare("") == 0)
filename += ".xml";
dialog.hide();
return filename;
}
case(Gtk::RESPONSE_CANCEL):
{
return "";
}
default:
{
return "";
}
}
return "";
}
Glib::ustring request_user_string(Gtk::Window *parent,
Glib::ustring mainMessage,
Glib::ustring subMessage)
{
Gtk::MessageDialog dialog(*parent, mainMessage,
false /* use_markup */, Gtk::MESSAGE_QUESTION,
Gtk::BUTTONS_OK_CANCEL);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
dialog.set_secondary_text(subMessage);
Gtk::Box *vb = dialog.get_vbox();
Gtk::Entry entry;
entry.set_text("");
vb->pack_start(entry);
vb->show_all();
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::cout << "OK clicked." << std::endl;
return entry.get_text();
}
case(Gtk::RESPONSE_CANCEL):
{
std::cout << "Cancel clicked." << std::endl;
return "";
}
default:
{
std::cout << "Unexpected button clicked." << std::endl;
return "";
}
}
}
#if 0
void CException::affiche_erreur() const
{
std::cout << "Fatal error: " << cat << std::endl << desc << std::endl;
Gtk::MessageDialog dial(cat, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true);
dial.set_title(cat);
dial.set_secondary_text(desc);
dial.run();
}
#endif
JComboBox::JComboBox()
{
m_refTreeModel = Gtk::ListStore::create(m_Columns);
set_model(m_refTreeModel);
//pack_start(m_Columns.m_col_id);
pack_start(m_Columns.m_col_name, Gtk::PACK_SHRINK);
}
void JComboBox::remove_all()
{
keys.clear();
m_refTreeModel->clear();
//clear();
}
void JComboBox::add_key(std::string key)
{
keys.push_back(key);
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_name] = key;
}
void JComboBox::set_current_key(std::string s)
{
for(unsigned int i = 0; i < keys.size(); i++)
{
if(keys[i].compare(s) == 0)
{
set_active(i);
return;
}
}
}
std::string JComboBox::get_current_key()
{
Gtk::TreeModel::iterator iter = get_active();
if(iter)
{
Gtk::TreeModel::Row row = *iter;
if(row)
{
Glib::ustring res = row[m_Columns.m_col_name];
return res;
}
}
return "";
}
void JFrame::set_label(const Glib::ustring &s)
{
Gtk::Label *old = lab;
lab = new Gtk::Label();
if(appli_view_prm.inverted_colors)
lab->set_label(std::string("<span color=\"#00ff00\">") + s + "</span>");
else
lab->set_label(std::string("<span color=\"#006000\">") + s + "</span>");
lab->set_use_markup(true);
set_label_widget(*lab);
lab->show();
if(old != nullptr)
delete old;
}
JFrame::JFrame(std::string label)
{
lab = nullptr;
set_border_width(20);
set_label(label);
}
GtkKey::GtkKey(unsigned short size_x, unsigned short size_y, std::string s, bool toggle)
{
text = s;
this->size_x = size_x;
this->size_y = size_y;
this->toggle = toggle;
sensitive = true;
realized = false;
clicking = false;
set_size_request(size_x,size_y);
signal_realize().connect(sigc::mem_fun(*this, &GtkKey::on_the_realisation));
signal_button_press_event().connect(sigc::mem_fun(*this, &GtkKey::on_mouse));
signal_button_release_event().connect( sigc::mem_fun( *this, &GtkKey::on_mouse));
add_events(Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK);
}
bool GtkKey::on_mouse(GdkEventButton *event)
{
//infos("mouse event.");
if(!sensitive)
return true;
bool old_clicking = clicking;
if(event->type == GDK_BUTTON_PRESS)
{
if(!toggle)
this->clicking = true;
else
clicking = !clicking;
}
else if(event->type == GDK_BUTTON_RELEASE)
{
if(!toggle)
this->clicking = false;
}
Glib::RefPtr<Gdk::Window> win = get_window();
if (win)
{
Gdk::Rectangle r(0, 0, get_allocation().get_width(),
get_allocation().get_height());
win->invalidate_rect(r, false);
}
if((((old_clicking != clicking) && !clicking)) || (this->text.compare("SHIFT") == 0))
{
KeyChangeEvent kce;
kce.active = clicking;
kce.key = this->text;
kce.source = this;
infos("dispatch kce..");
CProvider<KeyChangeEvent>::dispatch(kce);
}
return true;
}
void GtkKey::on_the_realisation()
{
wnd = get_window();
gc = wnd->create_cairo_context();
ctx = wnd->create_cairo_context();
lay = Pango::Layout::create(ctx);
realized = true;
update_view();
}
bool GtkKey::on_expose_event(GdkEventExpose* event)
{
//infos("expose event.");
update_view();
return true;
}
void GtkKey::set_sensitive(bool sensitive)
{
if(this->sensitive != sensitive)
{
this->sensitive = sensitive;
Glib::RefPtr<Gdk::Window> win = get_window();
if (win)
{
Gdk::Rectangle r(0, 0, get_allocation().get_width(),
get_allocation().get_height());
win->invalidate_rect(r, false);
}
}
}
void GtkKey::update_view()
{
if(!realized)
return;
Gdk::Color white, black;
white.set_red(65535);
white.set_blue(65535);
white.set_green(65535);
black.set_red(0);
black.set_blue(0);
black.set_green(0);
float x = 0, y = 0,
radius = size_y / 4;
float degrees = 3.1415926 / 180.0;
// This is where we draw on the window
Glib::RefPtr<Gdk::Window> window = get_window();
if(window)
{
Gtk::Allocation allocation = get_allocation();
int width = allocation.get_width();
int height = allocation.get_height();
//infos("width = %d, height = %d.", width, height);
Cairo::RefPtr<Cairo::Context> cr = window->create_cairo_context();
cr->set_line_width(1.5);
// clip to the area indicated by the expose event so that we only redraw
// the portion of the window that needs to be redrawn
cr->rectangle(0, 0,
width, height);
cr->set_source_rgb(0, 0, 0);
cr->clip();
float foreground;
float background;
float coef;
if(sensitive)
coef = 1.0;
else
coef = 0.25;
// Fond noir
if(appli_view_prm.inverted_colors)
{
background = 0.0;
foreground = coef;
}
else
{
background = 1.0;
foreground = 1.0 - coef;
}
cr->set_source_rgb(foreground, foreground, foreground);
cr->arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees);
cr->arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees);
cr->arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees);
cr->arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
cr->close_path();
cr->stroke();
//cr->set_source_rgb(1, 1, 1);
if(clicking)
{
//cr->set_source_rgb(0.7, 0.9, 0.7);
cr->set_source_rgb(0.7 * foreground + 0.3 * background, 0.9 * foreground + 0.1 * background, 0.7 * foreground + 0.3 * background);
x = x + width / 10;
y = y + height / 10;
width = (width * 8) / 10;
height = (height * 8) / 10;
radius = (radius * 8) / 10;
cr->arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees);
cr->arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees);
cr->arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees);
cr->arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
cr->close_path();
cr->fill();
cr->set_source_rgb(background, background, background);
}
lay->set_text(text);
lay->update_from_cairo_context(cr); // gets cairo cursor position
int tx, ty;
lay->get_pixel_size(tx, ty);
cr->move_to((size_x - tx) / 2, (size_y - ty) / 2);
lay->add_to_cairo_context(cr); // adds text to cairos stack of stuff to be drawn
cr->stroke(); // tells Cairo to render it's stack
//infos("Done drawing gtkkey.");
}
}
//GtkKeyboard *GtkKeyboard::instance = nullptr;
#if 0
GtkKeyboard *GtkKeyboard::get_instance()
{
if(instance == nullptr)
instance = new GtkKeyboard();
return instance;
}
#endif
#if 0
GtkKey *GtkKeyboard::add_key(std::string s)
{
GtkKey *key;
key = new GtkKey(kw, kw, s);
fixed.put(*key, cx, cy);
//infos("Add key [%s] @ %d, %d.", s.c_str(), cx, cy);
keys.push_back(key);
cx += (kw + 5);
key->add_listener(this);
return key;
}
#endif
GtkKey *VirtualKeyboard::add_key(std::string s)
{
GtkKey *key;
key = new GtkKey(kw, kw, s);
fixed.put(*key, cx, cy);
//infos("Add key [%s] @ %d, %d.", s.c_str(), cx, cy);
keys.push_back(key);
cx += (kw + 5);
key->add_listener(this);
return key;
}
std::string GtkKey::get_text()
{
return text;
}
#if 0
void GtkKeyboard::update_keyboard()
{
unsigned int i;
if(maj_on)
{
char buf[2];
buf[1] = 0;
buf[0] = 0xc9;
keys[1]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xc8;
keys[6]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xc7;
keys[8]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xc0;
keys[9]->set_text(Util::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('A');
keys[i++]->set_text('Z');
keys[i++]->set_text('E');
keys[i++]->set_text('R');
keys[i++]->set_text('T');
keys[i++]->set_text('Y');
keys[i++]->set_text('U');
keys[i++]->set_text('I');
keys[i++]->set_text('O');
keys[i++]->set_text('P');
i = 26;
keys[i++]->set_text('Q');
keys[i++]->set_text('S');
keys[i++]->set_text('D');
keys[i++]->set_text('F');
keys[i++]->set_text('G');
keys[i++]->set_text('H');
keys[i++]->set_text('J');
keys[i++]->set_text('K');
keys[i++]->set_text('L');
keys[i++]->set_text('M');
keys[i++]->set_text('W');
keys[i++]->set_text('X');
keys[i++]->set_text('C');
keys[i++]->set_text('V');
keys[i++]->set_text('B');
keys[i++]->set_text('N');
}
else
{
char buf[3];
buf[0] = 0xe9;
buf[1] = 0;
keys[1]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xe8;
keys[6]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xe7;
keys[8]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xe0;
keys[9]->set_text(Util::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('a');
keys[i++]->set_text('z');
keys[i++]->set_text('e');
keys[i++]->set_text('r');
keys[i++]->set_text('t');
keys[i++]->set_text('y');
keys[i++]->set_text('u');
keys[i++]->set_text('i');
keys[i++]->set_text('o');
keys[i++]->set_text('p');
i = 26;
keys[i++]->set_text('q');
keys[i++]->set_text('s');
keys[i++]->set_text('d');
keys[i++]->set_text('f');
keys[i++]->set_text('g');
keys[i++]->set_text('h');
keys[i++]->set_text('j');
keys[i++]->set_text('k');
keys[i++]->set_text('l');
keys[i++]->set_text('m');
keys[i++]->set_text('w');
keys[i++]->set_text('x');
keys[i++]->set_text('c');
keys[i++]->set_text('v');
keys[i++]->set_text('b');
keys[i++]->set_text('n');
}
}
void GtkKeyboard::on_event(const KeyChangeEvent &kce)
{
if(kce.key.compare("SHIFT") == 0)
{
infos("shift detected.");
if(kce.active)
{
maj_on = true;
# if 0
char buf[2];
buf[1] = 0;
buf[0] = 0xc9;
keys[1]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xc8;
keys[6]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xc7;
keys[8]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xc0;
keys[9]->set_text(Util::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('A');
keys[i++]->set_text('Z');
keys[i++]->set_text('E');
keys[i++]->set_text('R');
keys[i++]->set_text('T');
keys[i++]->set_text('Y');
keys[i++]->set_text('U');
keys[i++]->set_text('I');
keys[i++]->set_text('O');
keys[i++]->set_text('P');
i = 26;
keys[i++]->set_text('Q');
keys[i++]->set_text('S');
keys[i++]->set_text('D');
keys[i++]->set_text('F');
keys[i++]->set_text('G');
keys[i++]->set_text('H');
keys[i++]->set_text('J');
keys[i++]->set_text('K');
keys[i++]->set_text('L');
keys[i++]->set_text('M');
keys[i++]->set_text('W');
keys[i++]->set_text('X');
keys[i++]->set_text('C');
keys[i++]->set_text('V');
keys[i++]->set_text('B');
keys[i++]->set_text('N');
# endif
}
else
{
maj_on = false;
# if 0
char buf[3];
buf[0] = 0xe9;
buf[1] = 0;
keys[1]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xe8;
keys[6]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xe7;
keys[8]->set_text(Util::latin_to_utf8(buf));
buf[0] = 0xe0;
keys[9]->set_text(Util::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('a');
keys[i++]->set_text('z');
keys[i++]->set_text('e');
keys[i++]->set_text('r');
keys[i++]->set_text('t');
keys[i++]->set_text('y');
keys[i++]->set_text('u');
keys[i++]->set_text('i');
keys[i++]->set_text('o');
keys[i++]->set_text('p');
i = 26;
keys[i++]->set_text('q');
keys[i++]->set_text('s');
keys[i++]->set_text('d');
keys[i++]->set_text('f');
keys[i++]->set_text('g');
keys[i++]->set_text('h');
keys[i++]->set_text('j');
keys[i++]->set_text('k');
keys[i++]->set_text('l');
keys[i++]->set_text('m');
keys[i++]->set_text('w');
keys[i++]->set_text('x');
keys[i++]->set_text('c');
keys[i++]->set_text('v');
keys[i++]->set_text('b');
keys[i++]->set_text('n');
# endif
}
update_keyboard();
//if(target_window != nullptr)
//target_window->present();
}
else
{
/*Gdk::Event event;
event.*/
//if(target_window != nullptr)
//target_window->present();
const char *cs = kce.key.c_str();
if(target_window != nullptr)
{
Gtk::Widget *widget = target_window->get_focus();
if(widget != nullptr)
{
GdkEvent *ge = new GdkEvent();
GdkEventKey gek;
gek.type = GDK_KEY_PRESS;
gek.window = Gdk::Screen::get_default()->get_root_window()->gobj();//nullptr;//this->target_window;
gek.send_event = true;
gek.state = 0;
gek.keyval = cs[0];
if(cs[1] != 0)
{
//gek.keyval = (((unsigned short) cs[0]) << 8) | cs[1];
gek.keyval = (((unsigned short) cs[1]) << 8) | cs[0];
}
gek.length = 0;
gek.is_modifier = 0;
if(kce.key.compare(langue.get_item("key-space")) == 0)
{
gek.keyval = ' ';
}
else if(kce.key.compare(langue.get_item("key-tab")) == 0)
{
gek.keyval = 0xff09;//GDK_Tab;
//gek.state |= GDK_CONTROL_MASK;
gek.is_modifier = 0;//1;
//gek.hardware_keycode = 0x09;
}
char buf[2];
buf[1] = 0;
if(kce.key.compare(langue.get_item("key-del")) == 0)
{
gek.keyval = 0xff08;
}
buf[0] = 0xe9;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe9;
}
buf[0] = 0xe8;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe8;
}
buf[0] = 0xe0;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe0;
}
buf[0] = 0xe7;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe7;
}
buf[0] = 0xc9;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc9;
}
buf[0] = 0xc8;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc8;
}
buf[0] = 0xc7;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc7;
}
buf[0] = 0xc0;
if(kce.key.compare(Util::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc0;
}
gek.hardware_keycode = (gek.keyval & 0xff);
gek.group = 0;
ge->key = gek;
if(target_window != nullptr)
target_window->event(ge);
infos("Key event sent = '%c'.", (char) gek.keyval);
}
}
}
}
bool GtkKeyboard::on_key(GdkEventKey *event)
{
infos("EVENT KEY: state=%x, keyval=%x, length=%x, ismod=%x, hw=%x.", event->state, event->keyval, event->length, event->is_modifier, event->hardware_keycode);
return true;
}
#endif
void VirtualKeyboard::update_keyboard()
{
unsigned int i;
if(maj_on)
{
char buf[2];
buf[1] = 0;
buf[0] = 0xc9;
keys[1]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xc8;
keys[6]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xc7;
keys[8]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xc0;
keys[9]->set_text(utils::str::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('A');
keys[i++]->set_text('Z');
keys[i++]->set_text('E');
keys[i++]->set_text('R');
keys[i++]->set_text('T');
keys[i++]->set_text('Y');
keys[i++]->set_text('U');
keys[i++]->set_text('I');
keys[i++]->set_text('O');
keys[i++]->set_text('P');
i = 26;
keys[i++]->set_text('Q');
keys[i++]->set_text('S');
keys[i++]->set_text('D');
keys[i++]->set_text('F');
keys[i++]->set_text('G');
keys[i++]->set_text('H');
keys[i++]->set_text('J');
keys[i++]->set_text('K');
keys[i++]->set_text('L');
keys[i++]->set_text('M');
keys[i++]->set_text('W');
keys[i++]->set_text('X');
keys[i++]->set_text('C');
keys[i++]->set_text('V');
keys[i++]->set_text('B');
keys[i++]->set_text('N');
}
else
{
char buf[3];
buf[0] = 0xe9;
buf[1] = 0;
keys[1]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xe8;
keys[6]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xe7;
keys[8]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xe0;
keys[9]->set_text(utils::str::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('a');
keys[i++]->set_text('z');
keys[i++]->set_text('e');
keys[i++]->set_text('r');
keys[i++]->set_text('t');
keys[i++]->set_text('y');
keys[i++]->set_text('u');
keys[i++]->set_text('i');
keys[i++]->set_text('o');
keys[i++]->set_text('p');
i = 26;
keys[i++]->set_text('q');
keys[i++]->set_text('s');
keys[i++]->set_text('d');
keys[i++]->set_text('f');
keys[i++]->set_text('g');
keys[i++]->set_text('h');
keys[i++]->set_text('j');
keys[i++]->set_text('k');
keys[i++]->set_text('l');
keys[i++]->set_text('m');
keys[i++]->set_text('w');
keys[i++]->set_text('x');
keys[i++]->set_text('c');
keys[i++]->set_text('v');
keys[i++]->set_text('b');
keys[i++]->set_text('n');
}
}
void VirtualKeyboard::on_event(const KeyChangeEvent &kce)
{
infos("kc detected.");
if(kce.key.compare("SHIFT") == 0)
{
infos("shift detected.");
if(kce.active)
{
maj_on = true;
# if 0
char buf[2];
buf[1] = 0;
buf[0] = 0xc9;
keys[1]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xc8;
keys[6]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xc7;
keys[8]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xc0;
keys[9]->set_text(utils::str::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('A');
keys[i++]->set_text('Z');
keys[i++]->set_text('E');
keys[i++]->set_text('R');
keys[i++]->set_text('T');
keys[i++]->set_text('Y');
keys[i++]->set_text('U');
keys[i++]->set_text('I');
keys[i++]->set_text('O');
keys[i++]->set_text('P');
i = 26;
keys[i++]->set_text('Q');
keys[i++]->set_text('S');
keys[i++]->set_text('D');
keys[i++]->set_text('F');
keys[i++]->set_text('G');
keys[i++]->set_text('H');
keys[i++]->set_text('J');
keys[i++]->set_text('K');
keys[i++]->set_text('L');
keys[i++]->set_text('M');
keys[i++]->set_text('W');
keys[i++]->set_text('X');
keys[i++]->set_text('C');
keys[i++]->set_text('V');
keys[i++]->set_text('B');
keys[i++]->set_text('N');
# endif
}
else
{
maj_on = false;
# if 0
char buf[3];
buf[0] = 0xe9;
buf[1] = 0;
keys[1]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xe8;
keys[6]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xe7;
keys[8]->set_text(utils::str::latin_to_utf8(buf));
buf[0] = 0xe0;
keys[9]->set_text(utils::str::latin_to_utf8(buf));
i = 15;
keys[i++]->set_text('a');
keys[i++]->set_text('z');
keys[i++]->set_text('e');
keys[i++]->set_text('r');
keys[i++]->set_text('t');
keys[i++]->set_text('y');
keys[i++]->set_text('u');
keys[i++]->set_text('i');
keys[i++]->set_text('o');
keys[i++]->set_text('p');
i = 26;
keys[i++]->set_text('q');
keys[i++]->set_text('s');
keys[i++]->set_text('d');
keys[i++]->set_text('f');
keys[i++]->set_text('g');
keys[i++]->set_text('h');
keys[i++]->set_text('j');
keys[i++]->set_text('k');
keys[i++]->set_text('l');
keys[i++]->set_text('m');
keys[i++]->set_text('w');
keys[i++]->set_text('x');
keys[i++]->set_text('c');
keys[i++]->set_text('v');
keys[i++]->set_text('b');
keys[i++]->set_text('n');
# endif
}
update_keyboard();
//if(target_window != nullptr)
//target_window->present();
}
else
{
/*Gdk::Event event;
event.*/
//if(target_window != nullptr)
//target_window->present();
const char *cs = kce.key.c_str();
if(target_window != nullptr)
{
Gtk::Widget *widget = target_window->get_focus();
if(widget != nullptr)
{
GdkEvent *ge = new GdkEvent();
GdkEventKey gek;
gek.type = GDK_KEY_PRESS;
gek.window = Gdk::Screen::get_default()->get_root_window()->gobj();//nullptr;//this->target_window;
gek.send_event = true;
gek.state = 0;
gek.keyval = cs[0];
if(cs[1] != 0)
{
//gek.keyval = (((unsigned short) cs[0]) << 8) | cs[1];
gek.keyval = (((unsigned short) cs[1]) << 8) | cs[0];
}
gek.length = 0;
gek.is_modifier = 0;
if(kce.key.compare(langue.get_item("key-space")) == 0)
{
gek.keyval = ' ';
}
else if(kce.key.compare(langue.get_item("key-tab")) == 0)
{
gek.keyval = 0xff09;//GDK_Tab;
//gek.state |= GDK_CONTROL_MASK;
gek.is_modifier = 0;//1;
//gek.hardware_keycode = 0x09;
}
char buf[2];
buf[1] = 0;
if(kce.key.compare(langue.get_item("key-del")) == 0)
{
gek.keyval = 0xff08;
}
buf[0] = 0xe9;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe9;
}
buf[0] = 0xe8;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe8;
}
buf[0] = 0xe0;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe0;
}
buf[0] = 0xe7;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xe7;
}
buf[0] = 0xc9;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc9;
}
buf[0] = 0xc8;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc8;
}
buf[0] = 0xc7;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc7;
}
buf[0] = 0xc0;
if(kce.key.compare(utils::str::latin_to_utf8(buf)) == 0)
{
gek.keyval = 0xc0;
}
gek.hardware_keycode = (gek.keyval & 0xff);
gek.group = 0;
ge->key = gek;
if(target_window != nullptr)
target_window->event(ge);
infos("Key event sent = '%c'.", (char) gek.keyval);
}
}
}
}
bool VirtualKeyboard::on_key(GdkEventKey *event)
{
infos("EVENT KEY: state=%x, keyval=%x, length=%x, ismod=%x, hw=%x.", event->state, event->keyval, event->length, event->is_modifier, event->hardware_keycode);
return true;
}
void GtkKey::set_text(char c)
{
char tmp[2];
tmp[0] = c;
tmp[1] = 0;
std::string s(tmp);
set_text(tmp);
}
void GtkKey::set_text(std::string s)
{
this->text = s;
Glib::RefPtr<Gdk::Window> win = get_window();
if (win)
{
Gdk::Rectangle r(0, 0, get_allocation().get_width(),
get_allocation().get_height());
win->invalidate_rect(r, false);
}
}
#if 0
void GtkKeyboard::display(Gtk::Window *target_window)
{
infos("Display(target_window).");
currently_active = true;
this->target_window = target_window;
show_all_children(true);
show();
}
void GtkKeyboard::close()
{
currently_active = false;
target_window = nullptr;
hide();
}
bool GtkKeyboard::is_currently_active()
{
return currently_active;
}
void GtkKeyboard::set_valid_chars(std::vector<std::string> &vchars)
{
infos("update vchars..");
bool all_maj = true, has_maj = false;
for(unsigned int i = 0; i < vchars.size(); i++)
{
char c = (vchars[i])[0];
if((c >= 'a') && (c <= 'z'))
{
all_maj = false;
break;
}
if((c >= 'A') && (c <= 'Z'))
{
has_maj = true;
break;
}
}
if(all_maj & has_maj)
{
KeyChangeEvent kce;
kce.key = "SHIFT";
kce.active = true;
on_event(kce);
}
for(unsigned int i = 0; i < keys.size(); i++)
{
bool found = false;
std::string ks = keys[i]->get_text();
if(ks.compare(langue.get_item("key-space")) == 0)
ks = ' ';
if(ks.compare(langue.get_item("key-tab")) == 0)
continue;
if(ks.compare(langue.get_item("key-del")) == 0)
continue;
if(ks.compare("SHIFT") == 0)
continue;
for(unsigned int j = 0; j < vchars.size(); j++)
{
if(ks.compare(vchars[j]) == 0)
{
found = true;
break;
}
}
keys[i]->set_sensitive(found);
}
}
#endif
void VirtualKeyboard::set_valid_chars(const std::vector<std::string> &vchars)
{
infos("update vchars..");
bool all_maj = true, has_maj = false;
for(unsigned int i = 0; i < vchars.size(); i++)
{
char c = (vchars[i])[0];
if((c >= 'a') && (c <= 'z'))
{
all_maj = false;
break;
}
if((c >= 'A') && (c <= 'Z'))
{
has_maj = true;
break;
}
}
if(all_maj & has_maj)
{
KeyChangeEvent kce;
kce.key = "SHIFT";
kce.active = true;
on_event(kce);
}
for(unsigned int i = 0; i < keys.size(); i++)
{
bool found = false;
std::string ks = keys[i]->get_text();
if(ks.compare(langue.get_item("key-space")) == 0)
ks = ' ';
if(ks.compare(langue.get_item("key-tab")) == 0)
continue;
if(ks.compare(langue.get_item("key-del")) == 0)
continue;
if(ks.compare("SHIFT") == 0)
continue;
for(unsigned int j = 0; j < vchars.size(); j++)
{
if(ks.compare(vchars[j]) == 0)
{
found = true;
break;
}
}
keys[i]->set_sensitive(found);
}
}
#if 0
GtkKeyboard::GtkKeyboard()
{
GtkKey *key;
this->target_window = nullptr;//target_window;
currently_active = false;
maj_on = false;
set_decorated(false);
add(frame);
frame.add(hbox);
kw = 40;
int ox = 5, oy = 5;
cx = ox + kw/2;
cy = oy;
add_key(utils::str::latin_to_utf8("&"));
add_key(utils::str::latin_to_utf8("�"));//langue.getItem("e-aigu"));
add_key("\"");
add_key("'");
add_key("(");
add_key("-");
add_key(utils::str::latin_to_utf8("�"));//langue.getItem("e-grave"));
add_key("_");
add_key(utils::str::latin_to_utf8("�"));//langue.getItem("cedille"));
add_key(utils::str::latin_to_utf8("�"));//(langue.getItem("a-grave"));
add_key(")");
add_key("=");
add_key(".");
key = new GtkKey(3*kw/2, kw, langue.get_item("key-del"));
fixed.put(*key, cx, cy);
keys.push_back(key);
key->add_listener(this);
oy += kw + 5;
cx = ox;
cy = oy;
key = new GtkKey(3*kw/2, kw, langue.get_item("key-tab"));
fixed.put(*key, cx, cy);
keys.push_back(key);
key->add_listener(this);
cx += (3*kw/2+5);
//cx = ox+3*kw/2;// - kw /3;
cy = oy;
add_key("a");
add_key("z");
add_key("e");
add_key("r");
add_key("t");
add_key("y");
add_key("u");
add_key("i");
add_key("o");
add_key("p");
cx = ox;
cy = oy + kw + 5;
key = new GtkKey(3*kw/2, kw, "SHIFT", true);
fixed.put(*key, cx, cy);
keys.push_back(key);
cx += (3*kw/2+5);
key->add_listener(this);
add_key("q");
add_key("s");
add_key("d");
add_key("f");
add_key("g");
add_key("h");
add_key("j");
add_key("k");
add_key("l");
add_key("m");
cx = ox + kw/2 + kw / 3;
cy = oy + 2 * (kw + 5);
add_key("w");
add_key("x");
add_key("c");
add_key("v");
add_key("b");
add_key("n");
//cy = 3 * (kw + 5);
//cx = 4*kw;
key = new GtkKey(4*kw, kw, langue.get_item("key-space"));
fixed.put(*key, cx, cy);
keys.push_back(key);
key->add_listener(this);
cx = ox+11*(kw+5) + 25;
cy = oy;
add_key("7");
add_key("8");
add_key("9");
cx = ox+11*(kw+5) + 25;
cy = oy+kw + 5;
add_key("4");
add_key("5");
add_key("6");
cx = ox+10*(kw+5) + 25;
cy = oy+2 * (kw + 5);
add_key("0");
add_key("1");
add_key("2");
add_key("3");
update_keyboard();
/*cx = 11*(kw+5) + 30;
cy = 3 * (kw + 5);
key = new GtkKey(2*kw, kw, "0");
fixed.put(*key, cx, cy);
keys.push_back(key);*/
//frame.set_label("toto");
frame.set_border_width(3);
fixed.set_size_request((kw + 5) * 14 + 40, (kw + 5) * 4 + 5);
hbox.pack_start(fixed, Gtk::PACK_SHRINK);
show_all_children(true);
//signal_key_press_event().connect(sigc::mem_fun( *this, &GtkKeyboard::on_key));
signal_key_release_event().connect(sigc::mem_fun( *this, &GtkKeyboard::on_key));
add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
//this->signal_set_focus().connect(sigc::mem_fun(*this, &GtkKeyboard::on_focus));
//this->signal_focus_out_event().connect(sigc::mem_fun(*this, &GtkKeyboard::on_focus_out));
this->signal_focus_in_event().connect(sigc::mem_fun(*this, &GtkKeyboard::on_focus_in));
}
#endif
VirtualKeyboard::~VirtualKeyboard()
{
}
VirtualKeyboard::VirtualKeyboard(Gtk::Window *target_window)
{
GtkKey *key;
this->target_window = target_window;
maj_on = false;
add(hbox);
kw = 40;
int ox = 5, oy = 5;
cx = ox + kw/2;
cy = oy;
add_key(utils::str::latin_to_utf8("&"));
add_key(utils::str::latin_to_utf8("�"));//langue.getItem("e-aigu"));
add_key("\"");
add_key("'");
add_key("(");
add_key("-");
add_key(utils::str::latin_to_utf8("�"));//langue.getItem("e-grave"));
add_key("_");
add_key(utils::str::latin_to_utf8("�"));//langue.getItem("cedille"));
add_key(utils::str::latin_to_utf8("�"));//(langue.getItem("a-grave"));
add_key(")");
add_key("=");
add_key(".");
key = new GtkKey(3*kw/2, kw, langue.get_item("key-del"));
fixed.put(*key, cx, cy);
keys.push_back(key);
key->add_listener(this);
oy += kw + 5;
cx = ox;
cy = oy;
key = new GtkKey(3*kw/2, kw, langue.get_item("key-tab"));
fixed.put(*key, cx, cy);
keys.push_back(key);
key->add_listener(this);
cx += (3*kw/2+5);
//cx = ox+3*kw/2;// - kw /3;
cy = oy;
add_key("a");
add_key("z");
add_key("e");
add_key("r");
add_key("t");
add_key("y");
add_key("u");
add_key("i");
add_key("o");
add_key("p");
cx = ox;
cy = oy + kw + 5;
key = new GtkKey(3*kw/2, kw, "SHIFT", true);
fixed.put(*key, cx, cy);
keys.push_back(key);
cx += (3*kw/2+5);
key->add_listener(this);
add_key("q");
add_key("s");
add_key("d");
add_key("f");
add_key("g");
add_key("h");
add_key("j");
add_key("k");
add_key("l");
add_key("m");
cx = ox + kw/2 + kw / 3;
cy = oy + 2 * (kw + 5);
add_key("w");
add_key("x");
add_key("c");
add_key("v");
add_key("b");
add_key("n");
//cy = 3 * (kw + 5);
//cx = 4*kw;
key = new GtkKey(4*kw, kw, langue.get_item("key-space"));
fixed.put(*key, cx, cy);
keys.push_back(key);
key->add_listener(this);
cx = ox+11*(kw+5) + 25;
cy = oy;
add_key("7");
add_key("8");
add_key("9");
cx = ox+11*(kw+5) + 25;
cy = oy+kw + 5;
add_key("4");
add_key("5");
add_key("6");
cx = ox+10*(kw+5) + 25;
cy = oy+2 * (kw + 5);
add_key("0");
add_key("1");
add_key("2");
add_key("3");
update_keyboard();
/*cx = 11*(kw+5) + 30;
cy = 3 * (kw + 5);
key = new GtkKey(2*kw, kw, "0");
fixed.put(*key, cx, cy);
keys.push_back(key);*/
//frame.set_label("toto");
set_border_width(3);
fixed.set_size_request((kw + 5) * 14 + 40, (kw + 5) * 4 + 5);
hbox.pack_start(fixed, Gtk::PACK_SHRINK);
show_all_children(true);
//signal_key_press_event().connect(sigc::mem_fun( *this, &GtkKeyboard::on_key));
signal_key_release_event().connect(sigc::mem_fun( *this, &VirtualKeyboard::on_key));
add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
//this->signal_set_focus().connect(sigc::mem_fun(*this, &GtkKeyboard::on_focus));
//this->signal_focus_out_event().connect(sigc::mem_fun(*this, &GtkKeyboard::on_focus_out));
//this->signal_focus_in_event().connect(sigc::mem_fun(*this, &VirtualKeyboard::on_focus_in));
}
#if 0
void GtkKeyboard::on_focus(Gtk::Widget *w)
{
if(target_window != nullptr)
target_window->present();
}
bool GtkKeyboard::on_focus_in(GdkEventFocus *gef)
{
infos("focus in.");
if(target_window != nullptr)
{
target_window->present();
}
return true;
}
#endif
Gtk::Frame *WizardStep::get_frame()
{
return &(parent->mid);
}
void Wizard::start()
{
current_index = 0;
state = -1;
dialog.set_title(title);
dialog.set_default_size(600,350);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
b_cancel.set_label(langue.get_item("Cancel"));
b_prec.set_label(langue.get_item("Previous"));
b_next.set_label(langue.get_item("Next"));
b_prec.set_border_width(1);
b_next.set_border_width(1);
b_cancel.set_border_width(1);
low_buts.pack_start(b_prec);
low_buts.pack_start(b_next);//, Gtk::PACK_EXPAND_PADDING, 50,10);
low_buts.pack_start(b_cancel);//, Gtk::PACK_EXPAND_PADDING, 10,10);
//low_buts.set_child_secondary(b_cancel, true);
low_buts.set_border_width(5);
low_buts.set_layout(Gtk::BUTTONBOX_END);
//high.add(hvbox);
hvbox.pack_start(main_label, Gtk::PACK_SHRINK, 5);
hvbox.pack_start(description_label, Gtk::PACK_SHRINK, 10);
dialog.add(vbox);
//wizlab.set_border_width(5);
hhvbox.pack_start(hvbox, Gtk::PACK_EXPAND_WIDGET);
//Gtk::Image *buttonImage_ = new Gtk::Image("img/wiznew.png");
//wizlab.set_image(*buttonImage_);
hhvbox.pack_end(wizlab, Gtk::PACK_SHRINK, 10);
Gtk::EventBox *eventBox = new Gtk::EventBox();
eventBox->add(hhvbox);
// TODO
//eventBox->modify_bg(Gtk::STATE_NORMAL, Gdk::Color("white"));
vbox.pack_start(*eventBox, Gtk::PACK_SHRINK);
vbox.pack_start(mid, Gtk::PACK_EXPAND_WIDGET);
vbox.pack_start(low_buts, Gtk::PACK_SHRINK);
b_cancel.signal_clicked().connect(sigc::mem_fun(*this,&Wizard::on_cancel) );
b_prec.signal_clicked().connect(sigc::mem_fun(*this,&Wizard::on_prec) );
b_next.signal_clicked().connect(sigc::mem_fun(*this,&Wizard::on_next) );
// TODO
//b_cancel.set_flags(Gtk::CAN_DEFAULT);
//b_next.set_flags(Gtk::CAN_DEFAULT);
current = first;
update_view();
hvbox.set_border_width(2);
description_label.set_single_line_mode(false);
main_label.set_selectable(false);
description_label.set_selectable(false);
description_label.set_justify(Gtk::JUSTIFY_LEFT);
main_label.set_justify(Gtk::JUSTIFY_LEFT);
current->enter();
dialog.show_all_children(true);
Gtk::Main::run(dialog);
}
void Wizard::update_view()
{
printf("Current step = %s.\n", current->name.c_str());
b_prec.set_sensitive(current->enable_prec() && (current != steps[0]));
b_next.set_sensitive(current->enable_next());
//b_end.set_sensitive(current->enable_end());
if(current->enable_end())
{
b_cancel.set_label(langue.get_item("Terminate"));
if(current->enable_next())
b_next.grab_default();
else
b_cancel.grab_default();
}
else
{
b_cancel.set_label(langue.get_item("Cancel"));
if(current->enable_next())
b_next.grab_default();
}
main_label.set_markup("<b>" + current->title + "</b>");
description_label.set_text(current->description);
}
void Wizard::set_icon(const string &ipath)
{
wizlab.set(ipath);
}
void Wizard::add_step(WizardStep *step)
{
if(steps.size() == 0)
first = step;
steps.push_back(step);
step->parent = this;
}
WizardStep *Wizard::get_step(std::string name)
{
for(unsigned int i = 0; i < steps.size(); i++)
{
if(steps[i]->name.compare(name) == 0)
return steps[i];
}
printf("Step %s not found.\n", name.c_str());
return nullptr;
}
void Wizard::set_current(std::string name)
{
WizardStep *ws = get_step(name);
printf("Going to step \"%s\"...\n", name.c_str());
if(ws == nullptr)
{
printf("Step not defined !\n");
return;
}
mid.remove();
current = ws;
update_view();
current->enter();
mid.show_all_children(true);
}
void Wizard::on_cancel()
{
dialog.hide();
if(current->enable_end())
{
current->validate();
state = 0;
}
}
void Wizard::on_prec()
{
on_prec_step(current->name);
}
void Wizard::on_next()
{
current->validate();
on_next_step(current->name);
}
const int NotebookManager::POS_FIRST = 0xffff;
const int NotebookManager::POS_LAST = 0xfffe;
#ifndef LINUX
static bool registered_icon_size = false;
#endif
NotebookManager::NotebookManager()
{
current_page = 0;
this->signal_switch_page().connect(
sigc::mem_fun(*this, &NotebookManager::on_switch_page));
}
unsigned int NotebookManager::nb_pages() const
{
return pages.size();
}
void NotebookManager::on_switch_page(Gtk::Widget *page, int page_num)
{
if(pages.size() > 0)
{
PageChange pc;
pc.previous_widget = nullptr;
pc.new_widget = nullptr;
if(current_page != -1)
pc.previous_widget = pages[current_page]->widget;
if((page_num < 0) || (page_num >= (int) pages.size()))
{
erreur("Invalid page num: %d.", page_num);
return;
}
current_page = page_num;
pc.new_widget = pages[current_page]->widget;
CProvider<PageChange>::dispatch(pc);
}
}
void NotebookManager::on_b_close(Page *page)
{
infos("on close(%s).", page->name.c_str());
current_page = -1;
/*Gtk::Notebook::remove_page(*page->align);*/
this->remove_page(*page->widget);
PageClose pc;
pc.closed_widget = page->widget;
CProvider<PageClose>::dispatch(pc);
}
int NotebookManager::add_page(int position,
Gtk::Widget &widget,
std::string name,
std::string icon_path,
std::string description)
{
Page *p = new Page();
p->widget = &widget;
p->name = name;
p->icon_path = icon_path;
p->index = -1;
//p->scroll.add(widget);
p->scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
pages.push_back(p);
if(position == POS_FIRST)
{
}
else if(position == POS_LAST)
{
}
else
{
}
Gtk::HBox *ybox = new Gtk::HBox();
if(icon_path.size() > 0)
{
if(!files::file_exists(icon_path))
erreur("Image not found: %s.", icon_path.c_str());
else
ybox->pack_start(*(new Gtk::Image(icon_path)));
}
ybox->pack_start(*(new Gtk::Label(" " + name)));
Gtk::Button *button = new Gtk::Button();
ybox->pack_start(*button);
Gtk::IconSize icon_size;
# ifdef LINUX
icon_size = Gtk::ICON_SIZE_MENU;
# else
std::string isize = "tiny";
isize = "";
if(!registered_icon_size)
{
icon_size = Gtk::IconSize::register_new(isize, 6, 6);
registered_icon_size = true;
}
else
icon_size = Gtk::IconSize::from_name(isize);
# endif
Gtk::Image *img = new Gtk::Image(Gtk::Stock::CLOSE, icon_size);//Gtk::ICON_SIZE_MENU);
button->add(*img);
button->signal_clicked().connect(
sigc::bind(
sigc::mem_fun(*this,
&NotebookManager::on_b_close),
p));
//p->align = new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_TOP, 1.0, 1.0);
//p->align->add(p->scroll);
//p->scroll.add(widget);
//p->align->add(widget);
//append_page(*p->align, *ybox);
append_page(widget, *ybox);
ybox->show_all_children();
if(description.size() > 0)
{
ybox->set_has_tooltip();
ybox->set_tooltip_markup(description);
}
//this->append_page(p->scroll);
return p->index;
}
NotebookManager::Page::~Page()
{
delete align;
}
int NotebookManager::remove_page(Gtk::Widget &widget)
{
infos("Remove page..");
current_page = -1;
for(uint32_t i = 0; i < pages.size(); i++)
{
if(pages[i]->widget == &widget)
{
//this->remove(widget);
Gtk::Notebook::remove_page(*pages[i]->align);
std::deque<Page *>::iterator it;
for(it = pages.begin(); it != pages.end(); it++)
{
Page *cur = *it;
if(cur->widget == pages[i]->widget)
{
pages.erase(it);
infos("Delete page..");
delete pages[i];
return 0;
}
}
erreur("Could not remove page from deque.");
return -1;
}
}
erreur("Page not found.");
return -1;
}
Gtk::Widget *NotebookManager::get_current_page()
{
if((unsigned int) current_page >= pages.size())
return nullptr;
return pages[current_page]->widget;
}
int NotebookManager::set_current_page(Gtk::Widget &widget)
{
current_page = 0;//...;
for(uint32_t i = 0; i < pages.size(); i++)
{
if(pages[i]->widget == &widget)
{
// TODO
return 0;
}
}
return -1;
}
void TreeManager::maj_langue()
{
populate();
}
bool TreeManager::verifie_type_gere(const std::string &s)
{
if(s == "action")
return false;
if(ids.size() == 0)
return true;
for(const auto &id: ids)
if(s == id)
return true;
return false;
}
bool TreeManager::a_enfant_visible(const utils::model::Node noeud)
{
for(const auto &ch: noeud.schema()->children)
if(verifie_type_gere(ch.child_str))
return true;
return false;
}
void TreeManager::populate()
{
tree_model->clear();
populate(model, nullptr);
tree_view.expand_all();
}
void TreeManager::populate(Node m, const Gtk::TreeModel::Row *row)
{
//for(unsigned int i = 0; i < m.schema()->children.size(); i++)
for(const auto &ss: m.schema()->children)
{
//SubSchema ss = m.schema()->children[i];
const NodeSchema *schema = ss.ptr;
if(!verifie_type_gere(schema->name.get_id()))
continue;
unsigned int n = m.get_children_count(schema->name.get_id());
for(unsigned int j = 0; j < n; j++)
{
Node no = m.get_child_at(schema->name.get_id(), j);
const Gtk::TreeModel::Row *subrow;
//Gtk::TreeModel::iterator subrow;
if(row == nullptr)
subrow = &(*(tree_model->append()));
else
subrow = &(*(tree_model->append(row->children())));
std::string s = no.get_identifier(false);
if(a_enfant_visible(no))
s = "<b>" + s + "</b>";
(*subrow)[columns.m_col_name] = s;
(*subrow)[columns.m_col_ptr] = no;
if(has_pic(schema))
(*subrow)[columns.m_col_pic] = get_pics(schema);
populate(no, subrow);
}
}
}
void TreeManager::on_event(const ChangeEvent &e)
{
infos("Model change.");
populate();
}
/*void TreeManager::on_event(const StructChangeEvent &e)
{
infos("Model structural change.");
populate();
}*/
Node TreeManager::get_selection()
{
Glib::RefPtr<Gtk::TreeSelection> refTreeSelection = tree_view.get_selection();
Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();
Node result;
if(iter)
{
Gtk::TreeModel::Row ligne = *iter;
result = ligne[columns.m_col_ptr];
}
return result;
}
void TreeManager::on_selection_changed()
{
if(!lock)
{
lock = true;
Node m = get_selection();
if(!m.is_nullptr())
setup_row_view(m);
lock = false;
}
}
bool TreeManager::MyTreeView::on_button_press_event(GdkEventButton *event)
{
bool return_value = TreeView::on_button_press_event(event);
/* Right click */
if((event->type == GDK_BUTTON_PRESS) && (event->button == 3))
{
infos("bpress event");
Node m = parent->get_selection();
if(m.is_nullptr())
{
infos("no selection");
return return_value;
}
Gtk::Menu *popup = new Gtk::Menu();
//Gtk::Menu::MenuList &menulist = parent->popup_menu.items();
// TODO
//menulist.clear();
if(m.has_child("action"))
{
for(const Node &action: m.children("action"))
{
if(!action.get_attribute_as_boolean("enable"))
continue;
std::string aname = action.get_attribute_as_string("name");
if(action.get_attribute_as_string("fr").size() > 0)
{
aname = action.get_attribute_as_string("fr");
}
aname = utils::str::latin_to_utf8(aname);
std::pair<Node, std::string> pr;
pr.first = m;
pr.second = action.get_attribute_as_string("name");
infos("add action: %s", pr.second.c_str());
/*menulist.push_back(
Gtk::Menu_Helpers::MenuElem(aname,
sigc::bind<std::pair<Node, std::string> >(
sigc::mem_fun(parent, &TreeManager::on_menup), pr)));*/
Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem(aname, true));
item->signal_activate().connect(
sigc::bind<std::pair<Node, std::string>>(
sigc::mem_fun(parent, &TreeManager::on_menup), pr));
popup->append(*item);
}
}
infos("Show popup...");
popup->accelerate(*this);
popup->show_all();
popup->show_all_children(true);
/*parent->popup_menu*/popup->popup(event->button, event->time);
}
/* Double click */
else if((event->type == GDK_2BUTTON_PRESS) && (event->button == 1))
{
//infos("dclick event");
Node m = parent->get_selection();
if(m.is_nullptr())
{
//infos("no selection");
return return_value;
}
if(m.has_child("action"))
{
for(uint32_t i = 0; i < m.get_children_count("action"); i++)
{
Node action = m.get_child_at("action", i);
if(!action.get_attribute_as_boolean("enable"))
continue;
if(!action.get_attribute_as_boolean("default"))
continue;
std::string aname = action.get_attribute_as_string("name");
//parent->infos("action: %s", aname.c_str());
parent->on_menu(m, aname);
return return_value;
}
}
}
return return_value;
}
void TreeManager::on_menup(std::pair<Node, std::string> pr)
{
on_menu(pr.first, pr.second);
}
void TreeManager::on_menu(Node elt, std::string action)
{
for(uint32_t i = 0; i < menu_functors.size(); i++)
{
if(menu_functors[i]->action.compare(action) == 0)
{
menu_functors[i]->call(elt);
}
}
}
void TreeManager::set_selection(Gtk::TreeModel::Row &root, Node reg)
{
typedef Gtk::TreeModel::Children type_children;
type_children children = root.children();
for(type_children::iterator iter = children.begin();
iter != children.end(); ++iter)
{
Gtk::TreeModel::Row row = *iter;
Node e = row[columns.m_col_ptr];
if(e == reg)
{
tree_view.get_selection()->select(row);
return;
}
set_selection(row, reg);
}
}
int TreeManager::set_selection(Node reg)
{
typedef Gtk::TreeModel::Children type_children;
type_children children = tree_model->children();
for(type_children::iterator iter = children.begin();
iter != children.end(); ++iter)
{
Gtk::TreeModel::Row row = *iter;
Node e = row[columns.m_col_ptr];
if(e == reg)
{
tree_view.get_selection()->select(row);
return 0;
}
set_selection(row, reg);
}
return -1;
}
TreeManager::MyTreeView::MyTreeView(TreeManager *parent) : Gtk::TreeView()
{
this->parent = parent;
}
void TreeManager::on_treeview_row_activated(const Gtk::TreeModel::Path &path, Gtk::TreeViewColumn *)
{
Gtk::TreeModel::iterator iter = tree_model->get_iter(path);
if(iter)
{
Gtk::TreeModel::Row row = *iter;
setup_row_view(row[columns.m_col_ptr]);
}
}
void TreeManager::setup_row_view(Node ptr)
{
SelectionChangeEvent sce;
sce.new_selection = ptr;
dispatch(sce);
}
Glib::RefPtr<Gdk::Pixbuf> TreeManager::get_pics(const NodeSchema *schema)
{
for(unsigned int i = 0; i < pics.size(); i++)
{
if(pics[i].second == schema)
{
//infos("Returning pic.");
return pics[i].first;
}
}
erreur("pic not found for %s", schema->name.get_id().c_str());
return Glib::RefPtr<Gdk::Pixbuf>();
}
bool TreeManager::has_pic(const NodeSchema *schema)
{
for(unsigned int i = 0; i < pics.size(); i++)
{
if(pics[i].second == schema)
return true;
}
return false;
}
void TreeManager::load_pics(const NodeSchema *sc)
{
//assert(sc != nullptr);
//infos("load pics...");
//auto s = sc->to_string();
//infos(string("schem = ") + s);
for (uint32_t i = 0; i < pics_done.size(); i++) {
if (pics_done[i] == sc)
return;
}
pics_done.push_back(sc);
if((!has_pic(sc))
&& sc->has_icon())
{
std::pair<Glib::RefPtr<Gdk::Pixbuf>, const NodeSchema *> p;
p.second = sc;
std::string filename = utils::get_img_path()
+ files::get_path_separator() + sc->icon_path;
infos(std::string("Loading pic: ") + filename);
if(!files::file_exists(filename))
erreur("picture loading: " + filename + " not found.");
else
{
p.first = Gdk::Pixbuf::create_from_file(filename);
pics.push_back(p);
//infos("ok.");
}
}
for(unsigned int i = 0; i < sc->children.size(); i++)
load_pics(sc->children[i].ptr);
}
TreeManager::TreeManager(): tree_view(this)
{
}
void TreeManager::set_liste_noeuds_affiches(const std::vector<std::string> &ids)
{
this->ids = ids;
}
void TreeManager::set_model(Node model)
{
lock = false;
this->model = model;
load_pics(model.schema());
tree_view.set_headers_visible(false);
add(scroll);
scroll.add(tree_view);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
scroll.set_border_width(5);
tree_model = Gtk::TreeStore::create(columns);
tree_view.set_model(tree_model);
populate();
Gtk::TreeViewColumn *tvc = Gtk::manage(new Gtk::TreeViewColumn());
Gtk::CellRendererPixbuf *crp = Gtk::manage(new Gtk::CellRendererPixbuf());
tvc->pack_start(*crp, false);
tvc->add_attribute(crp->property_pixbuf(), columns.m_col_pic);
Gtk::CellRendererText *crt = new Gtk::CellRendererText();
tvc->pack_start(*crt, true);
tvc->add_attribute(crt->property_markup(), columns.m_col_name);
tree_view.append_column(*tvc);
tree_view.signal_row_activated().connect(sigc::mem_fun(*this,
&TreeManager::on_treeview_row_activated));
Glib::RefPtr<Gtk::TreeSelection> refTreeSelection = tree_view.get_selection();
refTreeSelection->signal_changed().connect(
sigc::mem_fun(*this, &TreeManager::on_selection_changed));
popup_menu.accelerate(tree_view);
model.add_listener((CListener<ChangeEvent> *) this);
//model.add_listener((Listener<StructChangeEvent> *) this);
}
TreeManager::TreeManager(Node model): tree_view(this)
{
set_model(model);
}
#if 0
DialogManager *DialogManager::instance;
DialogManager::Placable *DialogManager::current_window = nullptr;
DialogManager *DialogManager::get_instance()
{
if(instance == nullptr)
instance = new DialogManager();
return instance;
}
DialogManager::DialogManager()
{
setup("view", "dialog-manager");
lock = false;
last_resize_tick = 0;
last_focus_tick = 0;
}
bool DialogManager::on_timeout(int tn)
{
infos("timeout.");
if(current_window != nullptr)
{
if(appli_view_prm.use_touchscreen)
{
infos("present kb.");
//GtkKeyboard::get_instance()->set_keep_above();
}
infos("present kw.");
//current_window->raise();//show();//present();
current_window->set_keep_above();
}
/* stop timer */
return false;
}
void DialogManager::forward_focus()
{
DialogManager *dm = DialogManager::get_instance();
if(!appli_view_prm.use_touchscreen)
return;
if(dm->lock)
{
dm->warning("locked.");
}
if(!dm->lock)
{
dm->lock = true;
uint64_t tick = OSThread::get_tick_count_ms();
if(tick - dm->last_focus_tick < 200)
{
dm->infos("forward focus: differed.");
dm->lock = false;
return;
}
dm->infos("forward focus: now.");
dm->last_focus_tick = tick;
// Creation of a new object prevents long lines and shows us a little
// how slots work. We have 0 parameters and bool as a return value
// after calling sigc::bind.
sigc::slot<bool> my_slot = sigc::bind(sigc::mem_fun(*dm,
&DialogManager::on_timeout), 0);
// This is where we connect the slot to the Glib::signal_timeout()
sigc::connection conn = Glib::signal_timeout().connect(my_slot,
50);
/*if(current_window != nullptr)
{
if(appli_view_prm.use_touchscreen)
{
GtkKeyboard::get_instance()->present();
}
current_window->present();
}*/
dm->lock = false;
}
}
void DialogManager::dispose()
{
if(current_window == nullptr)
return;
std::deque<Placable *>::iterator it;
for (it = windows_stack.begin(); it != windows_stack.end(); it++)
{
if(current_window == *it)
{
windows_stack.erase(it);
break;
}
}
current_window = nullptr;
if(appli_view_prm.use_touchscreen)
{
//GtkKeyboard::get_instance()->close();
}
if(windows_stack.size() > 0)
{
DialogManager::setup(windows_stack[windows_stack.size() - 1]);
}
}
void DialogManager::update_sizes()
{
# if 0
uint32_t ox, oy;
if(!lock)
{
lock = true;
uint64_t tick = OSThread::get_tick_count_ms();
if(tick - last_resize_tick < 200)
{
lock = false;
return;
}
last_resize_tick = tick;
uint32_t screen_x, screen_y;
int sx1, sy1, sx2, sy2;
bool show_keyboard = appli_view_prm.use_touchscreen;
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
int delta = 0;//25;
if(current_window == nullptr)
{
lock = false;
return;
}
infos("Re-setup window..");
if(!show_keyboard)
{
lock = false;
return;
}
//current_window->show();
current_window->resize(10,10);
//screen_x = current_window->get_screen()->get_width();
//screen_y = current_window->get_screen()->get_height();
get_screen(current_window, ox, oy, screen_x, screen_y);
current_window->get_size(sx1, sy1);
if(show_keyboard)
GtkKeyboard::get_instance()->get_size(sx2, sy2);
else
{
sx2 = sy2 = 0;
}
current_window->set_position(Gtk::WIN_POS_NONE);
current_window->resize(sx1, sy1);
if(show_keyboard)
{
///GtkKeyboard::get_instance()->show();
//GtkKeyboard::get_instance()->display(current_window);
/* ------------------------------
* sx1 ^
* ------------------- |
* | | sy1 |
* | | |
* ------------------- |
* delta | screen_y
* ------------------- |
* | | sy2 |
* | | |
* ------------------- |
* sx2 |
* -------------------------------
* screen_x
*/
/* y1 + sy1 + delta + sy2 + y1 = screen_y */
if(sy1 + sy2 + 2 * delta <= (int) screen_y)
{
y1 = (screen_y - sy1 - 2 * delta - sy2) / 2;
infos("Screen is large enough.");
}
else
{
warning("Screen is too small: scroll bar is mandatory.");
// Force the y dimension:
// delta * 3 + sy1 + sy2 = screen_y
sy1 = screen_y - (delta * 3 + sy2);
y1 = delta;
// Adjust sx1 to take the scroll into account
sx1 += delta;
current_window->force_scroll(sx1, sy1);
current_window->resize(sx1, sy1);
}
x2 = (screen_x - sx2) / 2;
y2 = y1 + sy1 + delta;
GtkKeyboard::get_instance()->move(ox + x2, oy + y2);
}
else
{
if((sy1 + delta) <= (int) screen_y)
{
infos("Screen is large enough.");
y1 = (screen_y - sy1) / 2;
}
else
{
warning("Screen is too small: scroll bar is mandatory.");
// Force the y dimension:
// delta * 3 + sy1 + sy2 = screen_y
sy1 = screen_y - delta * 2;
y1 = delta;
// Adjust sx1 to take the scroll into account
sx1 += delta;
current_window->force_scroll(sx1, sy1);
current_window->resize(sx1, sy1);
}
}
x1 = (screen_x - sx1) / 2;
current_window->move(x1 + ox, y1 + oy);
infos("SCR=(%d,%d), W1=(%d,%d), W2=(%d,%d).",
screen_x, screen_y,
sx1, sy1,
sx2, sy2);
infos("--> P1=(%d,%d), P2=(%d,d).",
x1, y1, x2, y2);
lock = false;
}
# endif
//wnd->present();
}
#endif
void DialogManager::get_screen(Gtk::Window *wnd, uint32_t &ox, uint32_t &oy, uint32_t &dx, uint32_t &dy)
{
if(appli_view_prm.fixed_size)
{
ox = appli_view_prm.ox;
oy = appli_view_prm.oy;
dx = appli_view_prm.dx;
dy = appli_view_prm.dy;
}
else
{
ox = 0;
oy = 0;
dx = wnd->get_screen()->get_width();
dy = wnd->get_screen()->get_height();
/* for task bar */
dy -= 40;
}
}
class DefaultPlacable: public DialogManager::Placable
{
public:
DefaultPlacable(Gtk::Window *wnd){this->wnd = wnd;}
Gtk::Window *get_window(){return wnd;}
void force_scroll(int dx, int dy){}
void unforce_scroll(){}
private:
Gtk::Window *wnd;
};
void DialogManager::setup_window(Gtk::Window *wnd, bool fullscreen)
{
DefaultPlacable dp(wnd);
setup_window(&dp, fullscreen);
# if 0
uint32_t screen_x, screen_y;
int sx1, sy1;
int x1 = 0, y1 = 0;
uint32_t ox, oy;
wnd->show_all_children(true);
wnd->resize(10,10);
get_screen(wnd, ox, oy, screen_x, screen_y);
TraceManager::infos(TraceManager::AL_NORMAL, "view", "SETUP WND: ox=%d,oy=%d,sx=%d,sy=%d.", ox,oy,screen_x,screen_y);
wnd->get_size(sx1, sy1);
if(fullscreen)
{
if(sx1 < (int) screen_x)
sx1 = screen_x;
if(sy1 < (int) screen_y)
sy1 = screen_y;
}
wnd->set_position(Gtk::WIN_POS_NONE);
wnd->resize(sx1, sy1);
y1 = (screen_y - sy1) / 2;
x1 = (screen_x - sx1) / 2;
if((sy1 <= (int) screen_y) && ((sx1 <= (int) screen_x)))
{
TraceManager::infos(TraceManager::AL_NORMAL, "view", "Screen is large enough.");
}
else
{
TraceManager::infos(TraceManager::AL_WARNING, "view", "Screen is too small: scroll bar is mandatory.");
// Force the y dimension:
// delta * 3 + sy1 + sy2 = screen_y
if(sy1 > (int) screen_y)
{
y1 = 0;
sy1 = screen_y;
// Adjust sx1 to take the scroll into account
sx1 += 30;
}
if(sx1 > (int) screen_x)
{
x1 = 0;
sx1 = screen_x;
// Adjust sx1 to take the scroll into account
sy1 += 30;
}
wnd->resize(sx1, sy1);
}
wnd->move(ox + x1, oy + y1);
TraceManager::infos(TraceManager::AL_NORMAL, "view", "SCR=(%d,%d), WREQ=(%d,%d).",
screen_x, screen_y,
sx1, sy1);
TraceManager::infos(TraceManager::AL_NORMAL, "view", "--> POS=(%d,%d).",
x1, y1);
wnd->present();
# endif
}
void DialogManager::setup_window(Placable *wnd, bool fullscreen)
{
uint32_t screen_x, screen_y;
int sx1, sy1;
int x1 = 0, y1 = 0;
uint32_t ox, oy;
wnd->get_window()->show_all_children(true);
wnd->get_window()->resize(10,10);
get_screen(wnd->get_window(), ox, oy, screen_x, screen_y);
/*TraceManager::infos(AL_NORMAL, "view",
"SETUP WND (FS = %s): ox=%d,oy=%d,sx=%d,sy=%d.",
fullscreen ? "true" : "false",
ox,oy,screen_x,screen_y);*/
wnd->get_window()->get_size(sx1, sy1);
if(fullscreen)
{
if(sx1 < (int) screen_x)
sx1 = screen_x;
if(sy1 < (int) screen_y)
sy1 = screen_y;
}
wnd->get_window()->set_position(Gtk::WIN_POS_NONE);
wnd->get_window()->resize(sx1, sy1);
y1 = (screen_y - sy1) / 2;
x1 = (screen_x - sx1) / 2;
if((sy1 <= (int) screen_y) && ((sx1 <= (int) screen_x)))
{
//TraceManager::infos(AL_NORMAL, "view",
// "Screen is large enough.");
}
else
{
avertissement("Screen is too small: scroll bar is mandatory.");
// Force the y dimension:
// delta * 3 + sy1 + sy2 = screen_y
if(sy1 > (int) screen_y)
{
y1 = 0;
sy1 = screen_y;
// Adjust sx1 to take the scroll into account
sx1 += 30;
}
if(sx1 > (int) screen_x)
{
x1 = 0;
sx1 = screen_x;
// Adjust sx1 to take the scroll into account
sy1 += 30;
if(sy1 > (int) screen_y)
{
sy1 = screen_y;
y1 = 0;
}
}
wnd->force_scroll(sx1, sy1);
wnd->get_window()->resize(sx1, sy1);
}
wnd->get_window()->move(ox + x1, oy + y1);
/*TraceManager::infos(AL_NORMAL, "view", "SCR=(%d,%d,%d,%d), WREQ=(%d,%d).",
ox, oy,
screen_x, screen_y,
sx1, sy1);
TraceManager::infos(AL_NORMAL, "view", "--> POS=(%d,%d).",
x1, y1);*/
wnd->get_window()->present();
}
#if 0
void DialogManager::setup(Placable *wnd)
{
# if 0
unsigned int i;
uint32_t screen_x, screen_y;
int sx1, sy1, sx2, sy2;
bool show_keyboard = appli_view_prm.use_touchscreen;
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
int delta = 0;//25;
uint32_t ox, oy;
for(i = 0; i < windows_stack.size(); i++)
{
if(windows_stack[i] == wnd)
break;
}
if(i == windows_stack.size())
windows_stack.push_back(wnd);
infos("setup window..");
current_window = wnd;
wnd->show_all_children(true);
wnd->resize(10,10);
//screen_x = wnd->get_screen()->get_width();
//screen_y = wnd->get_screen()->get_height();
get_screen(wnd, ox, oy, screen_x, screen_y);
wnd->get_size(sx1, sy1);
if(show_keyboard)
GtkKeyboard::get_instance()->get_size(sx2, sy2);
else
{
sx2 = sy2 = 0;
}
wnd->set_position(Gtk::WIN_POS_NONE);
wnd->resize(sx1, sy1);
if(show_keyboard)
{
///GtkKeyboard::get_instance()->show();
GtkKeyboard::get_instance()->display(wnd);
/* ------------------------------
* d1 sx1 ^
* ------------------- |
* | | sy1 |
* | | |
* ------------------- |
* d2 delta | screen_y
* ------------------- |
* | | sy2 |
* | | |
* ------------------- |
* d3 sx2 |
* -------------------------------
* screen_x
*/
/* y1 + sy1 + delta + sy2 + y1 = screen_y */
if(sy1 + sy2 + delta <= (int) screen_y)
{
y1 = (screen_y - sy1 - delta - sy2) / 2;
infos("Screen is large enough.");
}
else
{
warning("Screen is too small: scroll bar is mandatory.");
// Force the y dimension:
// delta * 3 + sy1 + sy2 = screen_y
sy1 = screen_y - (delta * 3 + sy2);
y1 = delta;
// Adjust sx1 to take the scroll into account
sx1 += delta;
wnd->force_scroll(sx1, sy1);
wnd->resize(sx1, sy1);
}
x2 = (screen_x - sx2) / 2;
y2 = y1 + sy1 + delta;
GtkKeyboard::get_instance()->move(ox + x2, oy + y2);
GtkKeyboard::get_instance()->present();
}
else
{
if((sy1 + delta) <= (int) screen_y)
{
infos("Screen is large enough.");
y1 = (screen_y - sy1) / 2;
}
else
{
warning("Screen is too small: scroll bar is mandatory.");
// Force the y dimension:
// delta * 3 + sy1 + sy2 = screen_y
sy1 = screen_y - delta * 2;
y1 = delta;
// Adjust sx1 to take the scroll into account
sx1 += delta;
wnd->force_scroll(sx1, sy1);
wnd->resize(sx1, sy1);
}
}
x1 = (screen_x - sx1) / 2;
wnd->move(ox + x1, oy + y1);
infos("SCR=(%d,%d), W1=(%d,%d), W2=(%d,%d).",
screen_x, screen_y,
sx1, sy1,
sx2, sy2);
infos("--> P1=(%d,%d), P2=(%d,%d).",
x1, y1, x2, y2);
wnd->present();
# endif
}
#endif
ColorRectangle::ColorRectangle(const GColor &col, uint16_t width, uint16_t height)
{
this->width = width;
this->height = height;
this->col = col;
realized = false;
set_size_request(width, height);
signal_realize().connect(sigc::mem_fun(*this, &ColorRectangle::on_the_realisation));
signal_draw().connect(sigc::mem_fun(*this,&ColorRectangle::on_expose_event));
}
void ColorRectangle::update_color(const GColor &col)
{
this->col = col;
update_view();
}
ColorRectangle::~ColorRectangle()
{
}
bool ColorRectangle::on_expose_event(const Cairo::RefPtr<Cairo::Context> &cr)
{
//infos("exposed");
update_view();
//sc_instance->show_all_children(true);
return true;
}
void ColorRectangle::on_the_realisation()
{
//infos("realized.");
wnd = get_window();
gc = wnd->create_cairo_context();
realized = true;
update_view();
sigc::slot<bool> my_slot = sigc::bind(sigc::mem_fun(*this,
&ColorRectangle::on_timer), 0);
//Glib::signal_timeout().connect(my_slot, 250);
}
bool ColorRectangle::on_timer(int unused)
{
update_view();
return true;
}
void ColorRectangle::update_view()
{
if(!realized)
return;
//infos("update_view..");
Gdk::Color gdkcolor = col.to_gdk();
gc->set_source_rgb(gdkcolor.get_red(), gdkcolor.get_green(), gdkcolor.get_blue());
uint16_t y;
for(y = 0; y < height; y++)
{
gc->move_to(0, y);
gc->line_to(width, y);
}
//infos("done.");
}
ColorButton::ColorButton(Attribute *model):
al(Gtk::ALIGN_CENTER, Gtk::ALIGN_CENTER, 0, 0)
{
lock = false;
this->model = model;
std::string col = model->get_string();
if(appli_view_prm.use_touchscreen)
crec = new ColorRectangle(GColor(col), 90, 20);
else
crec = new ColorRectangle(GColor(col), 90, 12);
al.add(*crec);
box.set_border_width(2);
box.pack_start(al, false, false, 3);
box.show_all();
add(box);
show_all_children(true);
signal_clicked().connect(
sigc::mem_fun(*this,
&ColorButton::on_b_pressed));
model->add_listener(this);
}
void ColorButton::on_b_pressed()
{
infos("on_b_pressed..");
# if 0
if(model->schema.constraints.size() > 0)
{
std::vector<GColor> colors;
for(i = 0; i < model->schema.constraints.size(); i++)
{
colors.push_back(GColor(model->schema.constraints[i]));
}
// Initial color selection.
uint32_t initial;
for(i = 0; i < colors.size(); i++)
{
if(colors[i].to_string().compare(model->value) == 0)
{
initial = i;
break;
}
}
if(i == colors.size())
{
anomaly("Initial color not found in palette: %s.", model->value.c_str());
initial = 0;
}
ColorPaletteDialog dialog(colors, initial);
if(dialog.display_modal() == 0)
{
if(dialog.color_index >= model->schema.constraints.size())
{
erreur("Invalid color index: %d >= %d.", dialog.color_index, model->schema.constraints.size());
}
infos("color change confirmed: %d -> %s.",
dialog.color_index,
model->schema.constraints[dialog.color_index].c_str());
model->set_value(model->schema.constraints[dialog.color_index]);
}
return;
}
#endif
ColorDialog dlg;
if(dlg.display(GColor(model->get_string()), model->schema->constraints) == 0)
{
infos("user response = ok.");
GColor csel = dlg.get_color();
std::string scol = csel.to_string();
model->set_value(scol);
}
else
{
infos("user response = cancel.");
}
/*Gtk::ColorSelectionDialog dlg;
if(!appli_view_prm.use_decorations)
{
dlg.set_decorated(false);
}
if(appli_view_prm.img_validate.size() > 0)
{
Gtk::Button *b_close_ptr = dlg.add_button(langue.getItem("cancel"), Gtk::RESPONSE_CANCEL);
Gtk::Button *b_apply_ptr = dlg.add_button(langue.getItem("valid"), Gtk::RESPONSE_ACCEPT);
Gtk::Image *bim = new Gtk::Image(appli_view_prm.img_cancel);
b_close_ptr->set_image(*bim);
b_close_ptr->set_image_position(Gtk::POS_TOP);
bim = new Gtk::Image(appli_view_prm.img_validate);
b_apply_ptr->set_image(*bim);
b_apply_ptr->set_image_position(Gtk::POS_TOP);
}
if(appli_view_prm.use_touchscreen)
{
dlg.set_keep_above();
}
{
Gtk::ColorSelection *csel = dlg.get_colorsel();
csel->set_current_color(GColor(model->value).to_gdk());
}
if(dlg.run() == Gtk::RESPONSE_OK)
{
infos("user response = ok.");
Gtk::ColorSelection *csel = dlg.get_colorsel();
Gdk::Color col = csel->get_current_color();
GColor col2(col);
std::string scol = col2.to_string();
model->set_value(scol);
}
else
{
infos("user response = cancel.");
}*/
}
void ColorButton::on_event(const ChangeEvent &ce)
{
if(!lock)
{
lock = true;
//if((ce.type == ChangeEvent::ATTRIBUTE_CHANGED)
// && (ce.source == model))
if(ce.type == ChangeEvent::ATTRIBUTE_CHANGED)
{
infos("model change.");
crec->update_color(GColor(model->get_string()));
}
lock = false;
}
}
ColorButton::~ColorButton()
{
delete crec;
}
ColorDialog::ColorDialog()
: GenDialog(GenDialog::GEN_DIALOG_VALID_CANCEL, langue.get_item("title-sel-color"))
{
//set_title(langue.getItem("color-selection"));
//add(vbox);
vbox->pack_start(cs, Gtk::PACK_SHRINK);
/*vbox.pack_start(toolbar, Gtk::PACK_SHRINK);
Gtk::Image *bim;
if(appli_view_prm.img_validate.size() > 0)
bim = new Gtk::Image(appli_view_prm.img_validate);
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::APPLY), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
tool_valid.set_icon_widget(*bim);
if(appli_view_prm.img_cancel.size() > 0)
{
bim = new Gtk::Image(appli_view_prm.img_cancel);
}
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
tool_cancel.set_icon_widget(*bim);
toolbar.insert(tool_cancel, -1,
sigc::mem_fun(*this, &ColorDialog::on_b_cancel));
toolbar.insert(sep2, -1);
sep2.set_expand(true);
sep2.set_property("draw", false);
toolbar.insert(tool_valid, -1,
sigc::mem_fun(*this, &ColorDialog::on_b_apply));
tool_valid.set_label(langue.getItem("b-valid"));
tool_cancel.set_label(langue.getItem("b-cancel"));*/
show_all_children(true);
}
int ColorDialog::display(GColor initial_color, std::vector<std::string> constraints)
{
unsigned int i;
if(constraints.size() > 0)
{
std::vector<GColor> colors;
for(i = 0; i < constraints.size(); i++)
{
colors.push_back(GColor(constraints[i]));
}
// Initial color selection.
uint32_t initial = 0;
for(i = 0; i < colors.size(); i++)
{
if(colors[i].to_string().compare(initial_color.to_string()) == 0)
{
initial = i;
break;
}
}
if(i == colors.size())
{
erreur("Initial color not found in palette: %s.", initial_color.to_string().c_str());
initial = 0;
}
ColorPaletteDialog dialog(colors, initial);
if(dialog.display_modal() == 0)
{
if(dialog.color_index >= constraints.size())
{
erreur("Invalid color index: %d >= %d.", dialog.color_index, constraints.size());
return -1;
}
infos("color change confirmed: %d -> %s.",
dialog.color_index,
constraints[dialog.color_index].c_str());
//model->set_value(model->schema.constraints[dialog.color_index]);
selected = constraints[dialog.color_index];
return 0;
}
else
return -1;
}
else
{
cs.set_current_color(initial_color.to_gdk());
int res = this->display_modal();
if(res == 0)
selected = GColor(cs.get_current_color());
return res;
}
}
void ColorDialog::on_valid()
{
//result_ok = true;
//hide();
//DialogManager::get_instance()->dispose();
//GtkKeyboard::get_instance()->close();
}
void ColorDialog::on_cancel()
{
//hide();
//DialogManager::get_instance()->dispose();
//GtkKeyboard::get_instance()->close();
}
GColor ColorDialog::get_color()
{
return selected;//GColor(cs.get_current_color());
}
void ColorDialog::force_scroll(int dx, int dy)
{
}
void ColorDialog::unforce_scroll()
{
}
GenDialog::GenDialog(GenDialogType type, std::string title)
{
result_ok = false;
this->type = type;
set_position(Gtk::WIN_POS_CENTER);
set_decorated(appli_view_prm.use_decorations);
vbox = get_vbox();
if(title.size() > 0)
{
if(appli_view_prm.use_decorations)
{
set_title(title);
}
else
{
label_title.set_markup(std::string("<b>") + title + "</b>");
vbox->pack_start(label_title, Gtk::PACK_SHRINK);
}
}
if(appli_view_prm.use_button_toolbar)
{
vbox->pack_end(toolbar, Gtk::PACK_SHRINK);
Gtk::Image *bim;
if(appli_view_prm.img_validate.size() > 0)
bim = new Gtk::Image(appli_view_prm.img_validate);
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::APPLY), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
tool_valid.set_icon_widget(*bim);
if(appli_view_prm.img_cancel.size() > 0)
{
bim = new Gtk::Image(appli_view_prm.img_cancel);
}
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
tool_cancel.set_icon_widget(*bim);
if(!((type == GEN_DIALOG_APPLY_CANCEL) || (type == GEN_DIALOG_VALID_CANCEL)))
toolbar.insert(sep2, -1);
toolbar.insert(tool_cancel, -1,
sigc::mem_fun(*this, &GenDialog::on_b_cancel_close));
if((type == GEN_DIALOG_APPLY_CANCEL) || (type == GEN_DIALOG_VALID_CANCEL))
toolbar.insert(sep2, -1);
sep2.set_expand(true);
sep2.set_property("draw", false);
if((type == GEN_DIALOG_APPLY_CANCEL) || (type == GEN_DIALOG_VALID_CANCEL))
toolbar.insert(tool_valid, -1,
sigc::mem_fun(*this, &GenDialog::on_b_apply_valid));
tool_valid.set_label(langue.get_item("b-valid"));
tool_cancel.set_label(langue.get_item("b-cancel"));
}
else
{
hbox.pack_end(b_cancel, Gtk::PACK_SHRINK);
if((type == GEN_DIALOG_APPLY_CANCEL) || (type == GEN_DIALOG_VALID_CANCEL))
hbox.pack_end(b_valid, Gtk::PACK_SHRINK);
hbox.set_layout(Gtk::BUTTONBOX_END);
b_cancel.set_border_width(4);
b_valid.set_border_width(4);
b_cancel.set_label(langue.get_item("b-cancel"));
b_valid.set_label(langue.get_item("b-valid"));
vbox->pack_end(hbox, Gtk::PACK_SHRINK);
b_valid.signal_clicked().connect(sigc::mem_fun(*this, &GenDialog::on_b_apply_valid));
b_cancel.signal_clicked().connect(sigc::mem_fun(*this, &GenDialog::on_b_cancel_close));
}
show_all_children(true);
}
/*if(appli_view_prm.use_touchscreen)
set_keep_above();*/
void GenDialog::on_b_apply_valid()
{
result_ok = true;
infos("on_b_apply_valid: hide...");
hide();
infos("Will call on_apply...");
if(type == GEN_DIALOG_APPLY_CANCEL)
on_apply();
else if(type == GEN_DIALOG_VALID_CANCEL)
on_valid();
else
erreur("unmanaged dialog type.");
infos("done.");
}
void GenDialog::on_b_cancel_close()
{
result_ok = false;
hide();
if(type == GEN_DIALOG_CLOSE)
on_close();
else
on_cancel();
}
void GenDialog::enable_validation(bool enable)
{
if(appli_view_prm.use_touchscreen)
tool_valid.set_sensitive(enable);
else
b_valid.set_sensitive(enable);
}
int GenDialog::display_modal()
{
DialogManager::setup_window((Placable *) this, false);
run();
if(result_ok)
return 0;
return 1;
}
Gtk::Window *GenDialog::get_window()
{
return this;
}
ColorPaletteDialog::ColorPaletteDialog(const std::vector<GColor> &colors,
uint32_t initial_color)
: GenDialog(GenDialog::GEN_DIALOG_VALID_CANCEL,
langue.get_item("title-sel-color")),
palette(colors, initial_color)
{
this->colors = colors;
this->vbox->pack_start(palette, Gtk::PACK_SHRINK);
show_all_children(true);
}
ColorPaletteDialog::~ColorPaletteDialog()
{
}
void ColorPaletteDialog::on_valid()
{
color_index = palette.current_color;
infos("on valid.");
}
void ColorPaletteDialog::on_cancel()
{
infos("on cancel");
}
ColorPalette::ColorPalette(const std::vector<GColor> &colors,
uint32_t initial_color)
{
this->colors = colors;
ncols = 5;
if(colors.size() < (unsigned int) ncols)
ncols = colors.size();
nrows = (colors.size() + ncols - 1) / ncols;
realized = false;
current_color = initial_color;
c_width = 60;
c_height = 50;
width = c_width * ncols;
height = c_height * nrows;
infos("ncolors = %d, ncolumns = %d, nrows = %d.", colors.size(), ncols, nrows);
infos("set_size_request(%d,%d)", width, height);
set_size_request(width, height);
signal_realize().connect(sigc::mem_fun(*this, &ColorPalette::on_the_realisation));
//signal_expose_event().connect(sigc::mem_fun(*this,&ColorPalette::on_expose_event));
signal_button_press_event().connect(sigc::mem_fun( *this, &ColorPalette::on_mouse ) );
//signal_button_release_event().connect(sigc::mem_fun( *this, &ColorPalette::on_mouse_release ) );
set_events(Gdk::BUTTON_PRESS_MASK | Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_RELEASE_MASK);
set_double_buffered(true);
# ifndef GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
//Connect the signal handler if it isn't already a virtual method override:
signal_draw().connect(sigc::mem_fun(*this, &ColorPalette::on_draw), false);
# endif //GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
}
bool ColorPalette::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
update_view();
return true;
}
bool ColorPalette::on_mouse(GdkEventButton *event)
{
int x = (int) event->x;
int y = (int) event->y;
/* Left click? */
if(event->button == 1)
{
infos("left click @%d, %d.", x, y);
unsigned int col, row;
col = x / c_width;
row = y / c_height;
infos("col = %d, row = %d.", col, row);
if((col < (unsigned int) ncols) && (row < (unsigned int) nrows))
{
unsigned int color = col + row * ncols;
if(color < colors.size())
{
infos("color = %d.", color);
current_color = color;
update_view();
}
else
{
erreur("invalid color index: %d.", color);
}
}
}
return true;
}
ColorPalette::~ColorPalette()
{
}
void ColorPalette::update_view()
{
if(!realized)
{
infos("update view: not realized.");
return;
}
//GColor background = appli_view_prm.background_color;
infos("update view..");
float degrees = 3.1415926 / 180.0;
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
infos("width = %d, height = %d.", width, height);
Glib::RefPtr<Gdk::Window> wnd = get_window();
Cairo::RefPtr<Cairo::Context> cr = wnd->create_cairo_context();
cr->set_line_width(1.5);
cr->set_source_rgb(1, 0, 1);
cr->rectangle(0, 0, width, height);
cr->clip();
float foreground;
float background;
// Fond noir
if(appli_view_prm.inverted_colors)
{
background = 0.0;
foreground = 1.0;
}
else
{
background = 0.8;
foreground = 0.0;
}
// Clear display
cr->set_source_rgb(background, background, background);
cr->rectangle(0, 0, width, height);
cr->fill();
//cr->stroke();
for(unsigned int col = 0; col < (unsigned int) ncols; col++)
{
for(unsigned int row = 0; row < (unsigned int) nrows; row++)
{
unsigned int x, y, width, height;
GColor color = colors[col + row * ncols];
x = col * c_width;
y = row * c_height;
float radius = c_height / 4.0;
width = c_width;
height = c_height;
if(current_color == col + row * ncols)
{
infos("SEL col %d row %d ccol %d.", col, row, current_color);
cr->set_source_rgb(foreground, foreground, foreground);
cr->arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees);
cr->arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees);
cr->arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees);
cr->arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
cr->close_path();
cr->stroke();
}
//cr->set_source_rgb(0.7 * foreground + 0.3 * background, 0.9 * foreground + 0.1 * background, 0.7 * foreground + 0.3 * background);
infos("color(%d) = %d.%d.%d.", col + row * ncols, color.red, color.green, color.blue);
cr->set_source_rgb(((float) color.red) / 256.0, ((float) color.green) / 256.0, ((float) color.blue) / 256.0);
x = x + width / 10;
y = y + height / 10;
width = (width * 8) / 10;
height = (height * 8) / 10;
radius = (radius * 8) / 10;
cr->arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees);
cr->arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees);
cr->arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees);
cr->arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
cr->close_path();
cr->fill();
cr->stroke();
}
}
cr->stroke();
}
bool ColorPalette::on_expose_event(GdkEventExpose *event)
{
infos("exposed");
update_view();
return true;
}
void ColorPalette::on_the_realisation()
{
infos("realized.");
realized = true;
}
SensitiveLabel::SensitiveLabel(std::string path)
{
this->path = path;
add(label);
set_events(Gdk::BUTTON_PRESS_MASK | Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_RELEASE_MASK);
signal_button_press_event().connect(sigc::mem_fun(this, &SensitiveLabel::on_button_press_event));
}
bool SensitiveLabel::on_button_press_event(GdkEventButton *event)
{
if((event->type == GDK_2BUTTON_PRESS) && (event->button == 1))
{
//printf("dispatch(%s)..\n", path.c_str());
LabelClick lc;
lc.path = path;
lc.type = LabelClick::VAL_CLICK;
dispatch(lc);
}
else if((event->type == GDK_BUTTON_PRESS) && (event->button == 1))
{
//printf("dispatch(%s)..\n", path.c_str());
LabelClick lc;
lc.path = path;
lc.type = LabelClick::SEL_CLICK;
dispatch(lc);
}
return true;
}
void ProgressDialog::set_widget(Gtk::Widget *wid)
{
this->wid = wid;
iframe.add(*wid);
}
void ProgressDialog::maj_texte(const std::string &s)
{
label.set_markup(s);
}
ProgressDialog::ProgressDialog(): event_fifo(4)
{
wid = nullptr;
set_position(Gtk::WIN_POS_CENTER);
if(!appli_view_prm.use_decorations)
set_decorated(false);
progress.set_pulse_step(0.01);
set_default_size(300,200);
Gtk::Box *box = this->get_vbox();
Gtk::Image *bim;
if(appli_view_prm.img_cancel.size() > 0)
bim = new Gtk::Image(appli_view_prm.img_cancel);
else
bim = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL), Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
bt.set_icon_widget(*bim);
toolbar.insert(sep, -1);
sep.set_expand(true);
sep.set_property("draw", false);
toolbar.insert(bt, -1,
sigc::mem_fun(*this, &ProgressDialog::on_b_cancel));
box->pack_start(label, Gtk::PACK_SHRINK);
box->pack_start(progress, Gtk::PACK_SHRINK);
box->pack_start(iframe, Gtk::PACK_EXPAND_WIDGET);
box->pack_end(toolbar, Gtk::PACK_SHRINK);
label.set_line_wrap(true);
gtk_dispatcher.add_listener(this, &ProgressDialog::on_event);
utils::hal::thread_start(this, &ProgressDialog::thread_entry);
}
ProgressDialog::~ProgressDialog()
{
iframe.remove();
event_fifo.push(Event::EXIT);
exit_done.wait();
}
void ProgressDialog::on_b_cancel()
{
canceled = true;
hide();
}
bool ProgressDialog::on_timer(int index)
{
//trace_verbeuse("on timer: in_pr = %d.", (int) in_progress);
if(!in_progress || canceled)
return false;
progress.pulse();
return true;
}
void ProgressDialog::on_event(const Bidon &bidon)
{
trace_verbeuse("Now stopping.");
hide();
}
void ProgressDialog::thread_entry()
{
for(;;)
{
Event e = event_fifo.pop();
switch(e)
{
case Event::START:
{
in_progress = true;
//can_start.wait();
//callback_done.clear();
functor->call();
//callback_done.raise();
in_progress = false;
if(!canceled)
{
Bidon bidon;
gtk_dispatcher.on_event(bidon);
}
break;
}
case Event::EXIT:
infos("Exit thread...");
exit_done.raise();
return;
}
}
}
void ProgressDialog::setup(std::string title, std::string text)
{
trace_verbeuse("setup(%s)...", title.c_str());
canceled = false;
this->set_title(title);
label.set_markup(text);
if(utils::mmi::mainWindow != nullptr)
set_transient_for(*utils::mmi::mainWindow);
bt.set_label(langue.get_item("cancel"));
show_all_children(true);
sigc::slot<bool> my_slot = sigc::bind(sigc::mem_fun(*this,
&ProgressDialog::on_timer), 0);
// This is where we connect the slot to the Glib::signal_timeout()
/*sigc::connection conn = */
Glib::signal_timeout().connect(my_slot, 50);
DialogManager::setup_window(this);
trace_verbeuse("raising...");
//can_start.raise();
event_fifo.push(Event::START);
int res = run();
trace_verbeuse("Progress dialog done, res = %d.", res);
if(res == Gtk::RESPONSE_CANCEL)
{
}
}
GtkLed::GtkLed(unsigned int size, bool is_red, bool is_mutable)
{
this->is_yellow = false;
this->size = size;
this->is_red = is_red;
this->is_mutable = is_mutable;
this->is_sensitive = true;
realized = false;
is_lighted = false;
set_size_request(size,size);
//signal_realize().connect(sigc::mem_fun(*this, &GtkLed::on_the_realisation));
signal_button_press_event().connect( sigc::mem_fun( *this, &GtkLed::on_mouse));
add_events(Gdk::BUTTON_PRESS_MASK);
}
bool GtkLed::on_draw(const Cairo::RefPtr<Cairo::Context> &cr)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
int rayon = width < height ? width : height;
float b, g, r;
float other, main;
if(is_lighted)
{
other = 0.1;
main = 0.9;
}
else
{
other = 0;
main = 0.2;
}
if(is_yellow)
{
b = other;
g = (main * 2) / 3;
r = main;
}
else if(is_red)
{
b = other;
g = other;
r = main;
}
else
{
b = other;
g = main;
r = other;
}
if(!this->is_sensitive)
{
b /= 3;
g /= 3;
r /= 3;
}
cr->set_source_rgb(r, g, b);
cr->arc(width/2, height/2, rayon/2, 0, 6.29);
cr->fill();
cr->set_source_rgb(1.0, 1.0, 1.0);
cr->arc(width/2, height/2, rayon/2, 0, 6.29);
return true;
}
void GtkLed::set_mutable(bool is_mutable)
{
this->is_mutable = is_mutable;
}
bool GtkLed::is_on()
{
return is_lighted;
}
bool GtkLed::on_mouse(GdkEventButton *event)
{
//printf("on_mouse, is_mut = %d.\n", is_mutable); fflush(0);
if(is_mutable)
{
is_lighted = !is_lighted;
update_view();
LedEvent le;
le.source = this;
dispatch(le);
}
return true;
}
void GtkLed::light(bool on)
{
is_lighted = on;
update_view();
}
void GtkLed::set_red(bool is_red)
{
this->is_red = is_red;
update_view();
}
void GtkLed::set_sensitive(bool sensistive)
{
this->is_sensitive = sensistive;
update_view();
}
void GtkLed::set_yellow()
{
this->is_yellow = true;
update_view();
}
/*void GtkLed::on_the_realisation()
{
wnd = get_window();
gc = wnd->create_cairo_context();
realized = true;
printf("GTKLED : realize.\n"); fflush(0);
update_view();
}*/
/*bool GtkLed::on_expose_event(GdkEventExpose* event)
{
update_view();
return true;
}*/
void GtkLed::update_view()
{
//queue_draw();
auto win = get_window();
if(win)
{
auto w = get_allocation().get_width(), h = get_allocation().get_height();
Gdk::Rectangle r(0, 0, w, h);
//printf("Invalidate rect %d, %d\n", w, h); fflush(0);
win->invalidate_rect(r, false);
}
}
FenetreVisibiliteToggle::FenetreVisibiliteToggle()
{
lock = false;
visible = false;
this->fenetre = nullptr;
}
bool FenetreVisibiliteToggle::est_visible() const
{
return visible;
}
void FenetreVisibiliteToggle::config(Gtk::Window *fenetre,
Glib::RefPtr<Gtk::ActionGroup> agroup,
const std::string &id)
{
this->fenetre = fenetre;
this->toggle = Gtk::ToggleAction::create(id, langue.get_section("menu").get_item(id), "", false);
agroup->add(toggle, sigc::mem_fun(*this, &FenetreVisibiliteToggle::on_toggle));
fenetre->signal_delete_event().connect(sigc::mem_fun(*this, &FenetreVisibiliteToggle::gere_evt_delete));
}
bool FenetreVisibiliteToggle::gere_evt_delete(GdkEventAny *evt)
{
infos("DELETE detecte sur fenetre.");
visible = false;
lock = true;
fenetre->hide();
toggle->set_active(false);
lock = false;
return true;
}
void FenetreVisibiliteToggle::affiche(bool visible_)
{
infos("Toggle affiche (%d)", (int) visible_);
visible = visible_;
lock = true;
toggle->set_active(visible);
lock = false;
if(visible)
{
infos("Show (fenetre).");
fenetre->show();
}
else
fenetre->hide();
}
void FenetreVisibiliteToggle::on_toggle()
{
if(!lock)
{
visible = !visible;
if(visible)
fenetre->show();
else
fenetre->hide();
}
}
}
}
namespace utils
{
void Util::show_error(std::string title, std::string content)
{
Gtk::MessageDialog dial(title, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true);
dial.set_title(title);
dial.set_secondary_text(content);
dial.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
dial.run();
}
void Util::show_warning(std::string title, std::string content)
{
Gtk::MessageDialog dial(title, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_CLOSE, true);
dial.set_title(title);
dial.set_secondary_text(content);
dial.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
dial.run();
}
}
| 114,265
|
C++
|
.cc
| 4,089
| 23.028613
| 160
| 0.583612
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,971
|
stdview.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/stdview.cc
|
#include "mmi/stdview.hpp"
#include "mmi/ColorCellRenderer2.hpp"
#include "mmi/renderers.hpp"
#include "mmi/stdview-fields.hpp"
#include <gtkmm/cellrenderercombo.h>
#include "comm/serial.hpp"
#include <string.h>
//#include <malloc.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
namespace utils
{
namespace mmi
{
using namespace fields;
static string wtypes[((int) VueGenerique::WIDGET_MAX) + 1] =
{
"vue-modele",
"nullptr-widget",
"champs",
"liste-champs",
"indicateur",
"bouton",
"disposition-bordure",
"disposition-grille",
"disposition-fixe",
"disposition-trig",
"notebook",
"panneau", // ?
"image",
"label",
"combo",
"decimal",
"hexa",
"float",
"radio",
"switch",
"cadre",
"choice",
"bytes",
"text",
"string",
"color",
"date",
"folder",
"file",
"serial",
"list-layout",
"disposition-verticale",
"disposition-horizontale",
"boite-boutons",
"vue-speciale",
"separateur-horizontal",
"separateur-vertical",
"table",
"led",
"invalide"
};
#define AFFICHAGE_REGLIST 0
#define AFFICHAGE_DESCRIPTION_REGLIST 1
#define AFFICHAGE_TREE 2
#define AFFICHAGE_OPTIONS 3
#define AFFICHAGE_MAX 3
static const std::string aff_mode_names[4] = { "REGLIST", "DESC_REGLIST",
"TREE", "OPTIONS" };
AppliViewPrm appli_view_prm;
AppliViewPrm::AppliViewPrm() {
fixed_size = false;
ox = 0;
oy = 0;
dx = 500;
dy = 500;
fullscreen = false;
use_touchscreen = false;
inverted_colors = false;
use_decorations = true;
vkeyboard_below = false;
background_color.red = 255;
background_color.green = 255;
background_color.blue = 255;
use_button_toolbar = false;
overwrite_system_label_color = false;
}
static void update_description_label(Gtk::Label *res, Localized &loc)
{
res->set_line_wrap(true);
res->set_justify(Gtk::JUSTIFY_FILL);
res->set_use_markup(true);
//res->set_vexpand(false);
res->set_size_request(250,-1);
res->set_markup(loc.get_description(Localized::LANG_CURRENT));
}
static Gtk::Label *make_description_label(Localized &loc)
{
Gtk::Label *label = new Gtk::Label();
update_description_label(label, loc);
return label;
}
// Pas d'enfants et moins de deux attributs
static bool is_tabular(NodeSchema *&es)
{
if (es->children.size() > 0)
return false;
if (es->attributes.size() > 4)
return false;
return true;
}
string NodeView::mk_label(const Localized &l)
{
string traduction = l.get_localized();
/*if (langue.has_item(traduction))
traduction = langue.getItem(traduction);*/
if ((traduction[0] >= 'a') && (traduction[0] <= 'z'))
traduction[0] += 'A' - 'a';
if ((uint8_t) traduction[0] == /*'é'*/0x82)
traduction[0] = 'E';
return traduction;
}
std::string NodeView::mk_label_colon(const Localized &l)
{
std::string traduction = mk_label(l);
if(Localized::current_language == Localized::LANG_FR)
return traduction + " : ";
return traduction + ": ";
}
static std::string mk_html_tooltip(refptr<AttributeSchema> as)
{
std::string desc = as->name.get_description(Localized::LANG_CURRENT);
std::string title = NodeView::mk_label(as->name);
# ifdef LINUX
/* Black background on linux */
std::string color = "#60f0ff";
# else
std::string color = "#006080";
# endif
std::string tooltip = std::string("<b><span foreground='" + color + "'>") + title
+ std::string("</span></b>\n") + desc;
if (as->enumerations.size() > 0)
{
for (unsigned int k = 0; k < as->enumerations.size(); k++)
{
Enumeration &e = as->enumerations[k];
if (e.name.has_description())
tooltip += std::string("\n<b>") + e.name.get_localized()
+ " : </b>" + e.name.get_description();
}
}
return tooltip;
}
NodeViewConfiguration::NodeViewConfiguration() {
show_desc = false;
show_main_desc = false;
show_children = false;
small_strings = false;
show_separator = true;
disable_all_children = false;
display_only_tree = false;
expand_all = false;
nb_attributes_by_column = 8;
nb_columns = 1;
horizontal_splitting = true;
table_width = -1;
table_height = -1;
}
std::string NodeViewConfiguration::to_string() const {
char buf[300];
sprintf(buf, "show children = %s, disable all child = %s, n cols = %d.",
show_children ? "true" : "false", disable_all_children ? "true" : "false",
nb_columns);
return std::string(buf);
}
AttributeView::~AttributeView()
{
model->CProvider<ChangeEvent>::remove_listener(this);
}
bool AttributeView::is_valid()
{
return true;
}
bool AttributeView::on_focus_in(GdkEventFocus *gef)
{
if(appli_view_prm.use_touchscreen)
{
std::vector < std::string > vchars;
model->schema->get_valid_chars(vchars);
KeyPosChangeEvent kpce;
kpce.vchars = vchars;
CProvider < KeyPosChangeEvent > ::dispatch(kpce);
}
return true;
}
VueGenerique::WidgetType AttributeView::choose_view_type(refptr<AttributeSchema> as, bool editable)
{
if((as->type == TYPE_BOOLEAN) && (!editable))
return VueGenerique::WIDGET_LED;
if(!editable)
return VueGenerique::WIDGET_FIXED_STRING;
if((as->constraints.size() > 0) && (as->type != TYPE_COLOR))
return VueGenerique::WIDGET_COMBO;
else if ((as->enumerations.size() > 0) && (as->has_max)
&& (as->max < 100))
return VueGenerique::WIDGET_COMBO;
switch (as->type)
{
case TYPE_INT:
if (as->is_bytes)
return VueGenerique::WIDGET_BYTES;
else if (as->is_hexa)
return VueGenerique::WIDGET_HEXA_ENTRY;
else
return VueGenerique::WIDGET_DECIMAL_ENTRY;
case TYPE_STRING:
if (as->formatted_text)
return VueGenerique::WIDGET_TEXT;
else
return VueGenerique::WIDGET_STRING;
case TYPE_BOOLEAN:
return VueGenerique::WIDGET_SWITCH;
case TYPE_FLOAT:
return VueGenerique::WIDGET_FLOAT_ENTRY;
case TYPE_COLOR:
return VueGenerique::WIDGET_COLOR;
case TYPE_DATE:
return VueGenerique::WIDGET_DATE;
case TYPE_FOLDER:
return VueGenerique::WIDGET_FOLDER;
case TYPE_FILE:
return VueGenerique::WIDGET_FILE;
case TYPE_SERIAL:
return VueGenerique::WIDGET_SERIAL;
default:
{
string s = as->to_string();
avertissement("choose view type: unable to select one, schema:\n%s", s.c_str());
return VueGenerique::WIDGET_NULL;
}
}
}
AttributeView *AttributeView::factory(Node model, Node view)
{
XPath path;
if(view.has_attribute("model"))
path = view.get_attribute_as_string("model");
else
path = view.get_attribute_as_string("modele");
Node owner = model.get_child(path.remove_last());
refptr<AttributeSchema> as = owner.schema()->get_attribute(path.get_last());
Attribute *att = owner.get_attribute(path.get_last());
VueGenerique::WidgetType type = VueGenerique::WIDGET_AUTO;
bool editable = view.get_attribute_as_boolean("editable");
std::string type_str = view.get_attribute_as_string("type");
if(type_str.size() > 0)
type = VueGenerique::desc_vers_type(type_str);
if(type == VueGenerique::WIDGET_AUTO)
type = choose_view_type(as, editable);
//if(!editable)
//type = VueGenerique::WIDGET_INDICATOR;
std::string s = VueGenerique::type_vers_desc(type);
trace_verbeuse("factory(): att type: %d (%s).", (int) type, s.c_str());
AttributeView *res = nullptr;
switch(type)
{
case VueGenerique::WIDGET_LED:
{
res = new VueLed(att, editable);
break;
}
case VueGenerique::WIDGET_FIXED_STRING:
{
res = new VueChaineConstante(att);
break;
}
case VueGenerique::WIDGET_STRING:
{
res = new VueChaine(att);
break;
}
case VueGenerique::WIDGET_TEXT:
{
erreur("A FAIRE : vue texte.");
//res = new VueTexte(att);
break;
}
case VueGenerique::WIDGET_DECIMAL_ENTRY:
{
res = new VueDecimal(att);
break;
}
case VueGenerique::WIDGET_FLOAT_ENTRY:
{
res = new VueFloat(att, view);
break;
}
case VueGenerique::WIDGET_HEXA_ENTRY:
{
res = new VueHexa(att);
break;
}
case VueGenerique::WIDGET_SWITCH:
{
res = new utils::mmi::fields::VueBouleen(att, false);
break;
}
case VueGenerique::WIDGET_COMBO:
{
res = new VueCombo(att);
break;
}
case VueGenerique::WIDGET_FILE:
{
res = new VueFichier(att, false);
break;
}
default:
avertissement("factory(): unamanaged att type: %d (%s).", (int) type, s.c_str());
}
if(res != nullptr)
att->CProvider<ChangeEvent>::add_listener(res);
return res;
}
AttributeView *AttributeView::build_attribute_view(Attribute *model,
const NodeViewConfiguration &config,
Node parent)
{
AttributeView *res = nullptr;
AttributeSchema &schema = *(model->schema);
bool has_sub_schema = false;
for(unsigned int i = 0; i < schema.enumerations.size(); i++)
{
if(schema.enumerations[i].schema != nullptr)
{
has_sub_schema = true;
break;
}
}
if(has_sub_schema)
{
res = new VueChoix(model, parent, config);
}
else if((schema.constraints.size() > 0) && (schema.type != TYPE_COLOR))
{
res = new VueCombo(model);
}
else if ((schema.enumerations.size() > 0) && (schema.has_max)
&& (schema.max < 100))
{
res = new VueCombo(model);
}
else
{
switch (schema.type)
{
case TYPE_INT:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else if (schema.is_bytes)
res = new VueOctets(model);
else if (schema.is_hexa)
res = new VueHexa(model);
else
res = new VueDecimal(model, 1);
break;
}
case TYPE_STRING:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else if(schema.formatted_text)
res = new VueTexte(model, config.small_strings);
else
res = new VueChaine(model, config.small_strings);
break;
}
case TYPE_BOOLEAN:
{
if (schema.is_instrument)
res = new VueLed(model);
else
res = new VueBouleen(model);
break;
}
case TYPE_FLOAT:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else
res = new VueFloat(model);
break;
}
case TYPE_COLOR:
{
res = new VueChoixCouleur(model);
break;
}
case TYPE_DATE:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else
res = new VueDate(model);
break;
}
case TYPE_FOLDER:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else
res = new VueDossier(model);
break;
}
case TYPE_FILE:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else
res = new VueFichier(model);
break;
}
case TYPE_SERIAL:
{
if(schema.is_instrument)
res = new VueChaineConstante(model);
else
res = new VueSelPortCOM(model);
break;
}
default:
break;
}
}
model->CProvider < ChangeEvent > ::add_listener(res);
return res;
}
void NodeView::load_pics(NodeSchema *&sc)
{
for (uint32_t i = 0; i < pics_done.size(); i++) {
if (pics_done[i] == sc)
return;
}
pics_done.push_back(sc);
if ((!has_pic(sc)) && sc->has_icon()) {
std::pair<Glib::RefPtr<Gdk::Pixbuf>, NodeSchema *> p;
p.second = sc;
std::string filename = utils::get_img_path() + files::get_path_separator()
+ sc->icon_path;
//infos(std::string("Loading pic: ") + filename);
if (!files::file_exists(filename))
avertissement("picture loading: " + filename + " not found.");
else {
p.first = Gdk::Pixbuf::create_from_file(filename.c_str());
pics.push_back(p);
}
}
for (unsigned int i = 0; i < sc->children.size(); i++)
load_pics(sc->children[i].ptr);
/*if((!has_pic(sc)) && sc->has_icon())
{
std::pair<Glib::RefPtr<Gdk::Pixbuf>, NodeSchema *> p;
p.second = sc;
std::string filename = IMG_DIR + "/img/" + sc->icon_path;
infos(std::string("Loading pic: ") + filename);
if(!Util::file_exists(filename))
erreur("picture loading: " + filename + " not found.");
else
{
p.first = Gdk::Pixbuf::create_from_file(filename);
pics.push_back(p);
}
for(unsigned int i = 0; i < sc->children.size(); i++)
load_pics(sc->children[i].ptr);
}*/
}
void NodeView::maj_langue()
{
table.update_langue();
for (unsigned int i = 0; i < sub_views.size(); i++)
sub_views[i]->update_langue();
}
void NodeView::update_langue() {
maj_langue();
}
void NodeView::set_sensitive(bool sensitive)
{
table.set_sensitive(sensitive);
for(unsigned int i = 0; i < sub_views.size(); i++)
sub_views[i]->set_sensitive(sensitive);
}
static bool is_notebook_display(const SubSchema &ss)
{
if(ss.display_tree)
return false;
if ((ss.min == ss.max) && (ss.min >= 1) && (ss.min <= 2))
return true;
if ((ss.min == 0) && (ss.max == 1))
return true;
return false;
}
static bool can_tab_display(const SubSchema &ss)
{
if (ss.display_tree)
return false;
if (ss.ptr->children.size() > 0)
return false;
if(ss.ptr->attributes.size() > 4)
return false;
return true;
}
void NodeView::on_event(const KeyPosChangeEvent &kpce)
{
utils::CProvider<KeyPosChangeEvent>::dispatch(kpce);
}
NodeView::MyTreeModel::MyTreeModel(NodeView *parent, ModelColumns *cols)
{
this->parent = parent;
set_column_types(*cols);
}
bool NodeView::MyTreeModel::row_draggable_vfunc(
const Gtk::TreeModel::Path& path) const {
return true;
}
bool NodeView::MyTreeModel::row_drop_possible_vfunc(
const Gtk::TreeModel::Path& dest,
const Gtk::SelectionData& selection_data) const {
// TODO: check if droppable
Gtk::TreeModel::Path dest_parent = dest;
NodeView::MyTreeModel* unconstThis = const_cast<NodeView::MyTreeModel*>(this);
const_iterator iter_dest_parent = unconstThis->get_iter(dest_parent);
if (iter_dest_parent) {
Row row = *iter_dest_parent;
Node target = row[parent->columns.m_col_ptr];
//target = target.parent();
//infos("drop to: ");
//utils::infos("me.");
Glib::RefPtr<Gtk::TreeModel> refThis = Glib::RefPtr<Gtk::TreeModel> (const_cast<NodeView::MyTreeModel*>(this));
refThis->reference(); //, true /* take_copy */)
Gtk::TreeModel::Path path_dragged_row;
Gtk::TreeModel::Path::get_from_selection_data(selection_data, refThis,
path_dragged_row);
const_iterator iter = refThis->get_iter(path_dragged_row);
Row row2 = *iter;
Node src = row2[parent->columns.m_col_ptr];
//infos("drop from: ");
//src.infos("me.");
std::string src_type = src.schema()->name.get_id();
if (target.schema()->has_child(src_type)) {
infos("%s -> %s: ok.", src_type.c_str(),
target.schema()->name.get_id().c_str());
return true;
}
infos("%s -> %s: nok.", src_type.c_str(),
target.schema()->name.get_id().c_str());
return false;
}
return false;
}
bool NodeView::MyTreeModel::drag_data_received_vfunc(
const TreeModel::Path& dest, const Gtk::SelectionData& selection_data) {
infos("drag data received.");
Gtk::TreeModel::Path dest_parent = dest;
NodeView::MyTreeModel* unconstThis = const_cast<NodeView::MyTreeModel*>(this);
const_iterator iter_dest_parent = unconstThis->get_iter(dest_parent);
if (iter_dest_parent) {
Row row = *iter_dest_parent;
Node target = row[parent->columns.m_col_ptr];
//infos("drop to: ");
//target.infos("me.");
Glib::RefPtr < Gtk::TreeModel > refThis = Glib::RefPtr < Gtk::TreeModel
> (const_cast<NodeView::MyTreeModel*>(this));
refThis->reference(); //, true /* take_copy */)
Gtk::TreeModel::Path path_dragged_row;
Gtk::TreeModel::Path::get_from_selection_data(selection_data, refThis,
path_dragged_row);
const_iterator iter = refThis->get_iter(path_dragged_row);
Row row2 = *iter;
Node src = row2[parent->columns.m_col_ptr];
//infos("drop from: ");
//src.infos("me.");
infos("dragging..");
src.parent().remove_child(src);
Node nv = target.add_child(src);
infos("done.");
parent->populate(); //update_view();
parent->set_selection(nv);
return true;
}
return false;
}
NodeView::NodeView(Gtk::Window *mainWin, Node model)//: tree_view(this)
: table(model, NodeViewConfiguration())//, tree_view(this)
{
NodeViewConfiguration config;
init(mainWin, model, config);
}
NodeView::NodeView()
{
}
NodeView::NodeView(Node model) :
table(model, NodeViewConfiguration())
{
NodeViewConfiguration config;
init(mainWindow, model, config);
}
NodeView::NodeView(Gtk::Window *mainWin, Node model,
const NodeViewConfiguration &config) :
table(model, config)
{
init(mainWin, model, config);
}
// public
int NodeView::init(Node modele,
const NodeViewConfiguration &config,
Gtk::Window *mainWin)
{
table.init(modele, config);
return init(mainWin, modele, config);
}
// private
int NodeView::init(Gtk::Window *mainWin,
Node model,
const NodeViewConfiguration &config)
{
tree_view.init(this);
this->config = config;
// (1) Inits diverses
//infos("Creation...");
this->nb_columns = config.nb_columns;
this->show_children = config.show_children;
this->mainWin = mainWin;
this->model = model;
this->schema = model.schema();
this->show_desc = config.show_desc;
this->small_strings = false;
lock = false;
only_attributes = true;
this->show_separator = config.show_separator;
has_optionnals = false;
bool tree_display = false;
if ((schema->children.size() > 0)
&& !config.disable_all_children)
{
for (unsigned int i = 0; i < schema->children.size(); i++)
{
SubSchema &ss = schema->children[i];
if ((!is_notebook_display(ss)) && (!ss.is_hidden)
&& !config.disable_all_children && !can_tab_display(ss))
{
tree_display = true;
/*infos("Tree display because of %s, min = %d, max = %d.",
ss.name.get_id().c_str(), ss.min, ss.max);*/
}
if ((ss.min == 0) && (ss.max == 1))
has_optionnals = true;
}
}
// (2) Determine le type d'affichage
// Avec des enfant (le + prioritaire), HPANE(arbre,rpanel)
if (tree_display)
{
affichage = AFFICHAGE_TREE;
//infos("Aff tree");
}
else
{
affichage = AFFICHAGE_TREE;
if (!config.disable_all_children)
{
for (unsigned int i = 0; i < schema->children.size(); i++)
{
SubSchema ss = schema->children[i];
if (!ss.is_exclusive)
affichage = AFFICHAGE_OPTIONS;
}
} else
{
}
// Mode options
//if((schema->optionals.size() > 0) || ((schema->children.size() > 0) && show_children))
{
//affichage = AFFICHAGE_OPTIONS;
//model->infos("Aff options");
}
if (affichage == AFFICHAGE_TREE)
{
// Attributs + description dans leur frame
if (schema->has_description())
{
affichage = AFFICHAGE_REGLIST;
//model.infos("Aff reg desc list");
}
// Juste attributs, sans frame (table)
else
{
affichage = AFFICHAGE_REGLIST;
//model.infos("Aff reg list");
}
}
}
//////////////////////////////////////////////////////////////
/////// AFFICHAGE ARBRE UNIQUEMENT ///////
//////////////////////////////////////////////////////////////
if (affichage == AFFICHAGE_TREE)
{
//infos("Creation: arbre...");
pics_done.clear();
load_pics(schema);
//infos("Creation: load pics ok.");
rp = nullptr;
if (!config.display_only_tree)
{
//infos("display_only_tree = false.");
//hpane.add1(tree_frame);
//hpane.add2(properties_frame);
//hpane.pack1(tree_frame, Gtk::FILL);
//hpane.pack2(properties_frame, Gtk::EXPAND);
//hpane.pack1(tree_frame, true, false);
hpane.pack1(tree_frame, false, /*false*/true);
hpane.pack2(properties_frame, true, /*false*/true);
tree_frame.set_size_request(300, 300); //-1);
hpane.set_border_width(5);
hpane.set_position(300);
}
//else
//infos("display_only_tree = true.");
tree_view.set_headers_visible(false);
tree_view.set_enable_tree_lines(true);
scroll.add(tree_view);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
scroll.set_border_width(5);
tree_frame.add(scroll);
//tree_model = Gtk::TreeStore::create(columns);
tree_model = Glib::RefPtr < MyTreeModel > (new MyTreeModel(this, &columns));
tree_view.set_model(tree_model);
populate();
Gtk::TreeViewColumn *tvc = Gtk::manage(new Gtk::TreeViewColumn());
Gtk::CellRendererPixbuf *crp = Gtk::manage(new Gtk::CellRendererPixbuf());
tvc->pack_start(*crp, false);
tvc->add_attribute(crp->property_pixbuf(), columns.m_col_pic);
Gtk::CellRendererText *crt = new Gtk::CellRendererText();
tvc->pack_start(*crt, true);
tvc->add_attribute(crt->property_markup(), columns.m_col_name);
tree_view.append_column(*tvc);
# if 0
tree_view.append_column("", columns.m_col_pic);
{
Gtk::CellRendererText *render = Gtk::manage(new Gtk::CellRendererText());
Gtk::TreeView::Column *viewcol = Gtk::manage(new Gtk::TreeView::Column ("", *render));
viewcol->add_attribute(render->property_markup(), columns.m_col_name);
tree_view.append_column(*viewcol);
}
# endif
tree_view.signal_row_activated().connect(
sigc::mem_fun(*this, &NodeView::on_treeview_row_activated));
Glib::RefPtr < Gtk::TreeSelection > refTreeSelection =
tree_view.get_selection();
refTreeSelection->signal_changed().connect(
sigc::mem_fun(*this, &NodeView::on_selection_changed));
popup_menu.accelerate(tree_view);
//infos("Creation: arbre ok.");
}
//////////////////////////////////////////////////////////////
/////// AFFICHAGE OPTIONS UNIQUEMENT ///////
//////////////////////////////////////////////////////////////
if (affichage == AFFICHAGE_OPTIONS) {
only_attributes = false;
}
tree_view.enable_model_drag_source();
tree_view.enable_model_drag_dest();
//////////////////////////////////////////////////////////////
/////// CODE COMMUN ///////
//////////////////////////////////////////////////////////////
# if 0
frame_attributs.set_label("Attributs");
frame_attributs.set_border_width(7);
has_attributes = (model.get_attribute_count() > 0);
if(schema->has_description())
{
if((affichage == AFFICHAGE_OPTIONS) && (!has_attributes))
;
else
{
label_description.set_use_markup(true);
label_description.set_markup(schema->description);
vbox.pack_start(label_description, Gtk::PACK_SHRINK);
only_attributes = false;
}
}
// Si il y a des attributs, on ajoute la frame
if(has_attributes)
vbox.pack_start(frame_attributs, Gtk::PACK_SHRINK);
// Si seulement des attributs, on retourne la table, pas la frame !
if(!only_attributes)
frame_attributs.add(table);
# endif
has_attributes = (model.schema()->attributes.size() > 0);
if (schema->has_description()) {
if ((affichage == AFFICHAGE_OPTIONS) && (!has_attributes))
;
else {
only_attributes = false;
}
}
/*if(model.schema()->name.has_description())
{
auto l = make_description_label(model.schema()->name);
table.pack_end(*l, Gtk::PACK_SHRINK);
//infos("Ajout description node.");
}*/
//////////////////////////////////////////////////////////////
/////// AFFICHAGE OPTIONS UNIQUEMENT ///////
//////////////////////////////////////////////////////////////
if (affichage == AFFICHAGE_OPTIONS)
{
if (has_optionnals)
{
vbox.pack_start(table, Gtk::PACK_SHRINK);
infos("Create option view...");
option_view = new SelectionView(model);
vbox.pack_start(*option_view, Gtk::PACK_EXPAND_WIDGET);
bool display_notebook = false;
// check if something to configure...
for(unsigned int i = 0; i < schema->children.size(); i++)
{
SubSchema &ss = schema->children[i];
if((ss.min == 0) && (ss.max == 1) && !(ss.ptr->is_empty()))
{
display_notebook = true;
break;
}
}
if(display_notebook)
{
hbox.pack_start(vbox, Gtk::PACK_SHRINK);
hbox.pack_start(notebook, Gtk::PACK_EXPAND_WIDGET);
}
else
{
hbox.pack_start(vbox, Gtk::PACK_EXPAND_WIDGET);
}
notebook.set_scrollable(true);
}
else
{
if (config.horizontal_splitting)
{
hbox.pack_start(table, Gtk::PACK_SHRINK);
hbox.pack_start(notebook, Gtk::PACK_SHRINK);
}
else
{
hbox.pack_start(vbox, Gtk::PACK_SHRINK);
vbox.pack_start(table, Gtk::PACK_SHRINK);
vbox.pack_start(notebook, Gtk::PACK_SHRINK);
}
}
populate_notebook();
}
table.CProvider < KeyPosChangeEvent > ::add_listener(this);
model.add_listener((CListener<ChangeEvent> *) this);
/*infos("EVIEW for %s:\nconfig = %s,\nres = %s, has optionnals = %s",
model.get_identifier().c_str(),
config.to_string().c_str(),
aff_mode_names[affichage].c_str(),
has_optionnals ? "true" : "false");*/
return 0;
}
bool NodeView::is_valid() {
//infos("is_valid()...");
for (unsigned int i = 0; i < sub_views.size(); i++) {
if (!sub_views[i]->is_valid()) {
avertissement("sub_view[%d] not valid.", i);
return false;
}
}
bool tvalid = table.is_valid();
if (!tvalid) {
avertissement("attribute list is not valid.");
}
return tvalid;
}
NodeView::~NodeView() {
//infos("~NodeView..");
model./*CProvider<ChangeEvent>::*/remove_listener(
(CListener<ChangeEvent> *) this);
//model./*CProvider<StructChangeEvent>::*/remove_listener((CListener<StructChangeEvent> *)this);
for (unsigned int i = 0; i < sub_views.size(); i++)
delete sub_views[i];
sub_views.clear();
//infos("~NodeView done.");
}
void NodeView::populate_notebook() {
if (affichage != AFFICHAGE_OPTIONS)
return;
//infos("Populate notebook...");
/* Remove old pages */
int n = notebook.get_n_pages();
for (int i = 0; i < n; i++)
notebook.remove_page(0);
/* Delete node views */
for (unsigned int i = 0; i < sub_views.size(); i++) {
delete sub_views[i];
}
sub_views.clear();
/* Place sub-panels */
for (unsigned int i = 0; i < schema->children.size(); i++)
{
SubSchema os = schema->children[i];
//if (!(is_notebook_display(os) && model.has_child(os.name.get_id())
// && (!os.is_exclusive)))
//{
//infos("not for notebook: %s.", os.name.get_id().c_str());
//infos("OS = %s.", os.to_string().c_str());
//if (!is_notebook_display(os))
// infos("!is_notebook_display");
//if (!model.has_child(os.name.get_id()))
// infos("no such child");
//}
if (is_notebook_display(os) && model.has_child(os.name.get_id())
&& (!os.is_exclusive))
{
if(os.ptr->is_empty())
continue;
uint32_t n = model.get_children_count(os.name.get_id());
//infos("notebook of for %s: %d children.", os.name.get_id().c_str(), n);
for (unsigned int j = 0; j < n; j++) {
Node child = model.get_child_at(os.name.get_id(), j);
NodeViewConfiguration vconfig = config;
if (has_attributes)
vconfig.horizontal_splitting = !vconfig.horizontal_splitting;
NodeView *mv = new NodeView(mainWin, child, vconfig);
NodeSchema *schem = schema->children[i].ptr;
std::string tname;
mv->CProvider < KeyPosChangeEvent > ::add_listener(this);
tname = NodeView::mk_label(schem->name);
if (n > 1)
tname += std::string(" ") + utils::str::int2str(j + 1);
sub_views.push_back(mv);
Gtk::Alignment *align;
align = new Gtk::Alignment(Gtk::ALIGN_START, Gtk::ALIGN_START, 1.0, 1.0);
//0.0, 0.0);
align->add(*(mv->get_widget()));
Gtk::HBox *ybox;
ybox = new Gtk::HBox();
if (child.schema()->has_description()) {
ybox->set_has_tooltip();
ybox->set_tooltip_markup(child.schema()->name.get_description());
}
if (!schem->has_icon()) {
ybox->pack_start(*(new Gtk::Label(" " + tname)));
notebook.append_page(*align, *ybox);
ybox->show_all_children();
} else {
std::string filename = utils::get_img_path()
+ files::get_path_separator() + schem->icon_path;
//infos("img filename: %s.", filename.c_str());
ybox->pack_start(*(new Gtk::Image(filename)));
ybox->pack_start(*(new Gtk::Label(" " + tname)));
notebook.append_page(*align, *ybox);
ybox->show_all_children();
}
}
}
}
hbox.show_all_children();
}
Gtk::Widget *NodeView::get_widget() {
// Avec des enfant, HPANE(arbre,rpanel)
if (affichage == AFFICHAGE_TREE) {
if (config.display_only_tree)
return &tree_frame;
else
return &hpane;
}
// Juste attributs, meme pas de description
else if (affichage == AFFICHAGE_REGLIST)
return &table;
// Description + attributs dans leur frame
else if (affichage == AFFICHAGE_DESCRIPTION_REGLIST)
return &table;
// Attributs + options a cocher + onglets
else if (affichage == AFFICHAGE_OPTIONS)
return &hbox;
erreur("Type d'affichage inconnu.");
return nullptr;
}
void NodeView::populate() {
tree_model->clear();
Gtk::TreeModel::Row row = *(tree_model->append());
row[columns.m_col_name] = model.get_identifier(true, true);
row[columns.m_col_ptr] = model;
if (has_pic(schema))
row[columns.m_col_pic] = get_pics(schema);
populate(model, row);
}
static bool has_tree_child(Node m) {
unsigned int i;
for (i = 0; i < m.schema()->children.size(); i++) {
SubSchema ss = m.schema()->children[i];
if (ss.display_tab
|| (is_tabular(ss.ptr) && ((ss.min != 1) || (ss.max != 1))
&& (!ss.display_tree)))
continue;
if (m.has_child(ss.name.get_id()))
return true;
}
return false;
}
void NodeView::populate(Node m, Gtk::TreeModel::Row row) {
/* Add all the child of "m" node below the "row" */
for (unsigned int i = 0; i < m.schema()->children.size(); i++) {
SubSchema ss = m.schema()->children[i];
NodeSchema *&schema = ss.ptr;
//if((schema->attributes.size() == 1)
// && (schema->children.size() == 0))
//continue;
if (ss.display_tab
|| (is_tabular(schema) && ((ss.min != 1) || (ss.max != 1))
&& (!ss.display_tree)))
continue;
//if(ss.is_command)
//continue;
if (ss.is_exclusive)
continue;
//infos("populate: child %s..", ss.name.get_id().c_str());
unsigned int n = m.get_children_count(ss.name.get_id());
for (unsigned int j = 0; j < n; j++) {
Node child = m.get_child_at(ss.name.get_id(), j);
Gtk::TreeModel::Row subrow = *(tree_model->append(row.children()));
std::string s = child.get_identifier(true, false);
// if schema name equals sub node schema name ?????
if (ss.name.get_id().compare(child.schema()->name.get_id())) {
infos("apply localized.");
s = ss.name.get_localized();
}
/* If has at least one child, display in bold font. */
if (has_tree_child(child))
s = "<b>" + s + "</b>";
/*if(lst[j].get_children_count() > 0)
{
for(unsigned int k = 0; k < lst[j].get_children_count(); k++)
{
SubSchema &ss
}*/
/*SubSchema &ss = *(m.schema()->get_child(lst[j].schema()->name.get_id()));
if(ss.display_tab
|| (is_tabular(schema)
&& ((ss.min != 1) || (ss.max != 1))
&& (!ss.display_tree)))
;
else
s = "<b>" + s + "</b>";*/
//}
subrow[columns.m_col_name] = s;
subrow[columns.m_col_ptr] = child;
if (has_pic(schema)) {
//infos("Set pic for %s.", lst[j].get_identifier().c_str());
subrow[columns.m_col_pic] = get_pics(schema);
}
populate(child, subrow);
if (ss.display_unfold)
//tree_view.expand_to_path(tree_model->get_path(subrow));
tree_view.expand_row(tree_model->get_path(subrow), true);
/*else
m.erreur("NO UNFOLD.");*/
}
}
if (config.expand_all)
tree_view.expand_all();
}
void NodeView::on_event(const ChangeEvent &e)
{
if ((e.type == ChangeEvent::CHILD_ADDED)
|| (e.type == ChangeEvent::CHILD_REMOVED))
{
string s = e.to_string();
infos("got add/rem event: %s", s.c_str());
if (e.path.length() == 2)
{
infos("on_event(StructChangeEvent)");
if (affichage == AFFICHAGE_TREE)
populate();
else if (affichage == AFFICHAGE_OPTIONS)
populate_notebook();
}
}
}
#if 0
void NodeView::on_event(const StructChangeEvent &e)
{
/*if(*(e.get_owner()) == this->model)
{
infos("on_event(StructChangeEvent)");
if(affichage == AFFICHAGE_TREE)
populate();
else if(affichage == AFFICHAGE_OPTIONS)
populate_notebook();
}*/
}
#endif
Node NodeView::get_selection() {
Glib::RefPtr < Gtk::TreeSelection > refTreeSelection =
tree_view.get_selection();
Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();
Node result;
if (iter) {
Gtk::TreeModel::Row ligne = *iter;
result = ligne[columns.m_col_ptr];
}
return result;
}
void NodeView::on_selection_changed() {
if (!lock) {
lock = true;
Node m = get_selection();
if (!m.is_nullptr())
setup_row_view(m);
lock = false;
}
}
void NodeView::on_down(Node child) {
infos("on_down..");
Node nv = child.parent().down(child);
populate();
set_selection(nv);
}
void NodeView::on_up(Node child) {
infos("on_up..");
Node nv = child.parent().up(child);
populate();
set_selection(nv);
}
bool NodeView::MyTreeView::on_button_press_event(GdkEventButton *event) {
//bool return_value = TreeView::on_button_press_event(event);
// TODO: gtk3 port
# if 0
if ((event->type == GDK_BUTTON_PRESS) && (event->button == 3)) {
Node m = parent->get_selection();
if (m.is_nullptr()) {
return TreeView::on_button_press_event(event);
//return return_value;
}
Gtk::MenuList &menulist = parent->popup_menu.items();
menulist.clear();
Gtk::MenuElem mr(
langue.get_item("Remove"),
sigc::bind < Node
> (sigc::mem_fun(parent, &NodeView::remove_element), m));
if (parent->model != m) {
menulist.push_back(mr);
menulist.push_back(Gtk::Menu_Helpers::SeparatorElem());
}
if (!m.parent().is_nullptr()) {
std::string sname = m.schema()->name.get_id();
int n = m.parent().get_children_count(sname);
if (n > 1) {
int index = -1;
for (int i = 0; i < n; i++) {
if (m.parent().get_child_at(sname, i) == m) {
index = i;
break;
}
}
if ((index != -1) && (index > 0))
menulist.push_back(
Gtk::MenuElem(
langue.get_item("up"),
sigc::bind < Node
> (sigc::mem_fun(parent, &NodeView::on_up), m)));
if ((index != -1) && (index + 1 < n))
menulist.push_back(
Gtk::MenuElem(
langue.get_item("down"),
sigc::bind < Node
> (sigc::mem_fun(parent, &NodeView::on_down), m)));
}
}
for (unsigned int i = 0; i < m.schema()->children.size(); i++) {
SubSchema &sub_schema = m.schema()->children[i];
NodeSchema *&ch = m.schema()->children[i].ptr;
std::pair<Node, SubSchema *> p;
p.first = m;
p.second = &sub_schema;
/** Name of sub-section */
std::string cname = ch->get_localized();
/** Name of sub-schema */
std::string sname = sub_schema.name.get_id();
if ((sname.size() > 0) && (ch->name.get_id().compare(sname) != 0))
cname = sub_schema.name.get_localized();
if (sub_schema.has_max()) {
uint32_t nb_max = sub_schema.max;
if (m.get_children_count(sub_schema.name.get_id()) >= nb_max)
/* Cannot add more children */
continue;
}
menulist.push_back(
Gtk::MenuElem(
langue.get_item("Add ") + cname + "...",
sigc::bind < std::pair<Node, SubSchema *>
> (sigc::mem_fun(parent, &NodeView::add_element), p)));
}
parent->popup_menu.popup(event->button, event->time);
return true;
}
# endif
return TreeView::on_button_press_event(event);
//return return_value;
}
void NodeView::remove_element(Node elt) {
if (elt.parent().is_nullptr())
erreur(std::string("Node without parent: ") + elt.schema()->name.get_id());
else {
Node parent = elt.parent();
elt.parent().remove_child(elt);
populate();
set_selection(parent);
}
}
int NodeView::set_selection(Gtk::TreeModel::Row &root, Node reg,
std::string path) {
uint32_t cnt = 0;
typedef Gtk::TreeModel::Children type_children;
type_children children = root.children();
for (type_children::iterator iter = children.begin(); iter != children.end();
++iter) {
Gtk::TreeModel::Row row = *iter;
Node e = row[columns.m_col_ptr];
std::string chpath = path + ":" + str::int2str(cnt);
if (e == reg) {
infos("set_selection: found(2).");
//void expand_to_path (const TreeModel::Path& path)
/*type_children::iterator it1 =
tree_model.get_iter( const Path& path);*/
//std::string path;
//path = "0:2";
tree_view.expand_to_path(Gtk::TreeModel::Path(chpath));
//tree_view.expand_all();
tree_view.get_selection()->select(row);
return 0;
}
if (set_selection(row, reg, chpath) == 0)
return 0;
cnt++;
}
return -1;
}
void NodeView::set_selection(Node reg) {
uint32_t cnt = 0;
infos("set_selection(%s)...", reg.get_localized_name().c_str());
typedef Gtk::TreeModel::Children type_children;
type_children children = tree_model->children();
for (type_children::iterator iter = children.begin(); iter != children.end();
++iter) {
std::string path = str::int2str(cnt);
Gtk::TreeModel::Row row = *iter;
Node e = row[columns.m_col_ptr];
if (e == reg) {
infos("set_selection: found(1).");
//tree_view.expand_all();
tree_view.expand_to_path(Gtk::TreeModel::Path(path));
tree_view.get_selection()->select(row);
return;
}
if (set_selection(row, reg, path) == 0)
return;
cnt++;
}
}
void NodeView::add_element(std::pair<Node, SubSchema *> p) {
Node m = p.first;
NodeSchema *&sc = p.second->ptr;
std::string nname = sc->get_localized();
Node nv;
if (sc->has_attribute("name")) {
std::string title = langue.get_item("Adding new ") + nname
+ langue.get_item(" into ") + m.get_identifier();
std::string sname = "";
if (sc->has_attribute("name")) {
std::string phrase = langue.get_item("Please enter ");
if(Localized::current_language == Localized::LANG_FR)
phrase += std::string("le nom du ") + nname + " :";
else
phrase += nname + " name:";
Glib::ustring res = utils::mmi::request_user_string(mainWin, title, phrase);
if (res == "")
return;
sname = res;
}
//infos("add_child of type %s..", p.second->name.get_id().c_str());
nv = Node::create_ram_node(sc);
if (nv.has_attribute("name"))
nv.set_attribute("name", sname);
nv = m.add_child(nv); //p.second->name.get_id());
populate();
set_selection(nv);
} else {
nv = Node::create_ram_node(sc);
//model.add_child(schema);
if (NodeDialog::display_modal(nv) == 0) {
nv = m.add_child(nv);
populate();
set_selection(nv);
}
}
//infos("Now m =\n%s", m.to_xml().c_str());
}
void NodeView::MyTreeView::init(NodeView *parent)
{
this->parent = parent;
}
NodeView::MyTreeView::MyTreeView()
{
}
NodeView::MyTreeView::MyTreeView(NodeView *parent)/* :
Gtk::TreeView()*/ {
init(parent);
}
void NodeView::on_treeview_row_activated(const Gtk::TreeModel::Path &path,
Gtk::TreeViewColumn *) {
Gtk::TreeModel::iterator iter = tree_model->get_iter(path);
if (iter) {
Gtk::TreeModel::Row row = *iter;
setup_row_view(row[columns.m_col_ptr]);
}
}
void NodeView::setup_row_view(Node ptr) {
Gtk::Widget *widget;
EVSelectionChangeEvent sce;
sce.selection = ptr;
CProvider < EVSelectionChangeEvent > ::dispatch(sce);
if (!config.display_only_tree) {
if (rp != nullptr) {
//infos("Removing prop. contents...");
properties_frame.remove();
delete rp;
rp = nullptr;
} else {
properties_frame.remove();
}
/*if(ptr == nullptr)
return;*/
if (ptr == model) {
if (only_attributes)
widget = &table;
else
widget = &vbox;
} else {
NodeViewConfiguration child_config = config;
//child_config.show_children = false;
child_config.disable_all_children = true;
rp = new NodeView(mainWin, ptr, child_config); //this->show_desc, false, this->small_strings, this->show_separator, nb_columns);
widget = rp->get_widget();
}
properties_frame.set_label(ptr.get_identifier());
properties_frame.add(*widget);
properties_frame.show();
properties_frame.show_all_children(true);
}
}
Glib::RefPtr<Gdk::Pixbuf> NodeView::get_pics(NodeSchema *&schema)
{
for (unsigned int i = 0; i < pics.size(); i++) {
if (pics[i].second == schema) {
//infos("Returning pic.");
return pics[i].first;
}
}
throw std::string("pic not found for ") + schema->name.get_id();
}
bool NodeView::has_pic(NodeSchema *&schema) {
for (unsigned int i = 0; i < pics.size(); i++) {
if (pics[i].second == schema)
return true;
}
return false;
}
void AttributeListView::update_langue() {
for (unsigned int i = 0; i < attributes_view.size(); i++) {
AttributeView *ev = attributes_view[i].av;
ev->update_langue();
}
}
bool AttributeListView::is_valid() {
for (unsigned int i = 0; i < attributes_view.size(); i++) {
if (!(attributes_view[i].av->is_valid()))
{
string s = attributes_view[i].av->model->get_string();
avertissement("Attribute view[%d] (%s = %s) not valid.", i,
attributes_view[i].av->model->schema->name.get_id().c_str(),
s.c_str());
return false;
}
}
return true;
}
AttributeListView::~AttributeListView() {
model.remove_listener(this);
for (unsigned int i = 0; i < attributes_view.size(); i++) {
delete attributes_view[i].av;
}
for (unsigned int i = 0; i < buttons.size(); i++)
delete buttons[i];
}
void AttributeListView::on_the_realisation() {
/*infos("realized.");
Glib::RefPtr<Gdk::Window> wnd;
wnd = get_window();
int w, h;
Gtk::Requisition requi = the_vbox.size_request();
w = requi.width;
h = requi.height;
infos("REQUI w = %d, h = %d.", w, h);
scroll.set_shadow_type(Gtk::SHADOW_NONE);
scroll.set_size_request(w + 30, h + 30);*/
}
AttributeListView::AttributeListView()
{
}
void AttributeListView::init(Node model,
const NodeViewConfiguration &config)
{
unsigned int natts_total = model.schema()->attributes.size();
table1.resize(((natts_total > 0) ? natts_total : 1),
3);
table1.set_homogeneous(false);
table2.resize(1, 1);
table2.set_homogeneous(false);
//infos("&&&&&&&&&&&&&&&&&&&&&&&& INIT ALV : natts = %d", natts_total);
this->config = config;
bool has_no_attributes = true;
bool indicators_detected = false;
list_is_sensitive = true;
this->show_separator = config.show_separator;
this->small_strings = config.small_strings;
this->model = model;
this->show_desc = config.show_desc;
set_border_width(5);
/*if(model.schema()->name.has_description())
{
auto l = make_description_label(model.schema()->name);
pack_start(*l, Gtk::PACK_SHRINK);
//infos("Ajout description node.");
}*/
unsigned int nrows = 0;
// TODO -> refactor (not using "Attribute" class anymore)
std::deque<Attribute *> atts; //= model.get_attributes();
unsigned int natts = 0;
for(uint32_t i = 0; i < natts_total; i++)
{
atts.push_back(model.get_attribute(model.schema()->attributes[i]->name.get_id()));
Attribute *att = atts[i];
if(!att->schema->is_hidden)
{
natts++;
nrows++;
if (show_desc && att->schema->has_description())
{
nrows++;
if(this->show_separator && ((i + 1) < natts_total))
nrows++; // Séparateur
}
}
}
if(nrows == 0)
nrows = 1;
table1.resize(nrows, 3);
nb_columns = config.nb_columns;
/*for (unsigned int i = 0; i < atts.size(); i++) {
Attribute *att = atts[i];
if (att->schema->is_hidden)
natts--;
}*/
//if((natts > 10) && (nb_columns == 1))
// nb_columns = 2;
if (((int) natts < (int) config.nb_attributes_by_column) && (nb_columns > 1))
nb_columns = 1;
unsigned int row = 0, row_indicators = 0;
unsigned int first_att = atts.size() + 1;
unsigned int natt1 = atts.size(), natt2 = 0;
if (config.show_main_desc && model.schema()->has_description())
{
update_description_label(&label_desc, model.schema()->name);
//label_desc.set_markup(
// model.schema()->name.get_description(Localized::LANG_CURRENT));
the_vbox.pack_start(label_desc, Gtk::PACK_SHRINK);
Gtk::HSeparator *sep = new Gtk::HSeparator();
the_vbox.pack_start(*sep, Gtk::PACK_SHRINK, 5 /* padding = 5 pixels */);
}
//hbox.pack_start(table1, Gtk::PACK_SHRINK);
hbox.pack_start(table1, Gtk::PACK_EXPAND_WIDGET);
//hbox.pack_start(table1, Gtk::PACK_SHRINK);
if (nb_columns == 2) {
first_att = (1 + atts.size()) / 2;
natt1 = first_att;
natt2 = atts.size() - natt1;
table1.resize(natt1, 3);
table2.resize(natt2, 3);
hbox.pack_start(separator, Gtk::PACK_SHRINK);
hbox.pack_start(table2, Gtk::PACK_SHRINK);
infos("n col = 2. n1 = %d, n2 = %d. f = %d.", natt1, natt2, first_att);
}
Gtk::Table *ctable = &table1;
Gtk::Table *otable = nullptr;
for (unsigned int i = 0; i < atts.size(); i++)
{
unsigned int *crow = &row;
Attribute *att = atts[i];
if (ctable == &table_indicators)
ctable = otable;
if (i == first_att)
{
ctable = &table2;
*crow = 0;
}
if (att->schema->is_hidden)
continue;
AttributeView *av = AttributeView::build_attribute_view(att, config, model);
av->CProvider<KeyPosChangeEvent>::add_listener(this);
if (att->schema->is_read_only && !att->schema->is_instrument)
{
av->set_sensitive(false);
}
else if(att->schema->is_read_only)
{
av->set_readonly(true);
}
if (!indicators_detected && att->schema->is_instrument)
{
indicators_detected = true;
//pack_start(frame_indicators, Gtk::PACK_SHRINK);
//frame_indicators.set_label(langue.get_item("indicators"));
//frame_indicators.add(table_indicators);
}
if (att->schema->is_instrument)
{
if (ctable != &table_indicators)
otable = ctable;
ctable = &table_indicators;
crow = &row_indicators;
}
else
has_no_attributes = false;
ViewElem ve;
ve.av = av;
ve.desc = nullptr;
//int row_description = *crow + 1;
for (unsigned int j = 0; j < av->get_nb_widgets(); j++)
{
unsigned int next_col = j + 1;
// Dernier widget de la ligne ?
if ((j == av->get_nb_widgets() - 1) && (next_col < 3))
{
next_col = 3;
/*if (show_desc && att->schema->has_description() && (next_col == 1))
{
//row_description--;
next_col = 3;
} else if (next_col == 1)
next_col = 3;*/
}
//infos("x=[%d,%d], y=[%d,%d]", j, next_col, row, row+1);
float xscale;
if (j >= 1)
xscale = 1.0;
else
xscale = 0.0;
Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_START,
Gtk::ALIGN_CENTER, xscale, 0);
align->add(*(av->get_widget(j)));
//infos("Attach(%d,%d).", j, next_col);
ctable->attach(*align, j, next_col, *crow, (*crow) + 1,
Gtk::FILL/* | Gtk::EXPAND*/, Gtk::FILL/* | Gtk::EXPAND*/, 5, 5);
if (!show_desc && att->schema->has_description())
{
av->get_widget(j)->set_has_tooltip();
std::string desc = att->schema->name.get_description(
Localized::LANG_CURRENT);
std::string title = NodeView::mk_label(att->schema->name);
# ifdef LINUX
/* Black background on linux */
std::string color = "#60f0ff";
# else
std::string color = "#006080";
# endif
std::string tooltip = std::string(
"<b><span foreground='" + color + "'>") + title
+ std::string("</span></b>\n") + desc;
if (att->schema->enumerations.size() > 0) {
for (unsigned int k = 0; k < att->schema->enumerations.size(); k++) {
Enumeration &e = att->schema->enumerations[k];
if (e.name.has_description()) {
tooltip += std::string("\n<b>") + e.name.get_localized()
+ " : </b>" + e.name.get_description();
}
}
}
av->get_widget(j)->set_tooltip_markup(tooltip);
}
/*else
{
erreur("not show tooltip: %s.", att->schema.name.get_id().c_str());
erreur("desc = <%s>.", att->schema.name.get_description().c_str());
}*/
}
(*crow)++;
if (show_desc && att->schema->has_description())
{
/*auto label_test = make_description_label(att->schema->name);
Gtk::Window wnd;
Gtk::VBox vb;
vb.pack_start(*label_test, Gtk::PACK_SHRINK);
wnd.add(vb);
wnd.show_all_children(true);
Gtk::Main::run(wnd);*/
auto label = make_description_label(att->schema->name);
ve.desc = label;
/*Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_START,
Gtk::ALIGN_START, 0, 0);
align->add(*label);*/
ctable->attach(*label, 0, 3, *crow, (*crow) + 1,
Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK, 5, 5);
if (att->schema->is_instrument)
row_indicators++;
else
(*crow)++;
//attach(*label, x0_description, x1_description, row_description, row_description+1);
//row = row_description; //+ 1;
}
if (show_desc && (i < atts.size() - 1) && show_separator && att->schema->has_description())
{
Gtk::HSeparator *sep = new Gtk::HSeparator();
ctable->attach(*sep, 0, 3, (*crow), (*crow) + 1, Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);
(*crow)++;
}
attributes_view.push_back(ve);
} // for(i);
/** Add string lists */
/*infos("%s has %d children.",
model.schema()->name.get_id().c_str(),
model.schema()->children.size());*/
if (model.schema() != nullptr)
{
for (unsigned int i = 0; i < model.schema()->children.size(); i++)
{
SubSchema ss = model.schema()->children[i];
/*infos("Examining potential tabular %s.",
ss.to_string().c_str());*/
if (ss.is_hidden) {
//verbose("(hidden).");
continue;
}
/* Conditions de bypass des tabulations:
*
*
*
*
* if(ss.display_tab || (is_tabular(schema)
&& ((ss.min != 1) || (ss.max != 1))
&& (!ss.display_tree)))
* Conditons de pass notepad:
*
if(is_notebook_display(os)
&& model.has_child(os.name.get_id())
//&& (!os.is_command)
&& (!os.is_exclusive))
*/
if ((ss.min == 0) && (ss.max == 1)) {
//verbose("(optionnal).");
continue;// Display as optionnal
}
NodeSchema *&es = ss.ptr;
if (es == nullptr)
{
erreur("ES is nullptr, for %s (child of %s) !", ss.child_str.c_str(),
model.schema()->name.get_id().c_str());
continue;
}
if (ss.display_tab
|| (is_tabular(es) && (!ss.display_tree)
&& ((ss.min != 1) || (ss.max != 1))))
{
/*if (!((is_notebook_display(ss)
&& model.has_child(ss.name.get_id())
&& (!ss.is_exclusive)))) */
{
//infos("Adding tabular for %s...", es->name.get_id().c_str());
//infos("Root schema is:\n%s\n", model.schema()->to_string().c_str());
VueTable *slv = new VueTable(model, es, config);
//table1.attach(*slv, 0, 3, row, row+1, Gtk::FILL, Gtk::FILL, 5, 5);//Gtk::FILL, Gtk::FILL, 5, 5);
the_vbox.pack_start(/**slv*/*(slv->get_gtk_widget()), Gtk::PACK_EXPAND_WIDGET);
row++;
has_no_attributes = false;
}
} else
{
//verbose("is_tabular = %s, display_tree = %s.", is_tabular(es) ? "true" : "false", ss.display_tree ? "true" : "false");
}
}
}
/*infos("%s: resize main(%d), indic(%d)",
model.schema()->name.get_id().c_str(),
row,
row_indicators);*/
if (row > 0)
{
table1.resize(row, 3);
//trace_verbeuse("Dim table1: %d * %d.", row, 3);
}
if (row_indicators > 0)
table_indicators.resize(row_indicators, 3);
/*pack_start(frame_att, Gtk::PACK_SHRINK);
frame_att.set_label(Util::latin_to_utf8(langue.getItem("Attributs")));*/
/** Add commands */
bool has_no_command = true;
# if 0
NodeSchema *schema = model.schema();
for (uint32_t i = 0; i < schema->commands.size(); i++) {
CommandSchema ss = schema->commands[i];
//if(ss.is_command)
{
if (has_no_command) {
has_no_command = false;
//trace_major("One action detected.");
box_actions.set_border_width(5);
box_actions.set_spacing(5);
box_actions.set_layout(Gtk::BUTTONBOX_EDGE); //Gtk::BUTTONBOX_END);
box_actions.set_homogeneous(false);
}
/*if(model.get_children_count(ss.name) == 0)
{
erreur("No command child.");
continue;
}*/
//NodeSchema *sub_schema = ss.input;
Gtk::Button *button;
button = new Gtk::Button();
//button->set_label(sub_schema->get_localized());
button->set_label(ss.name.get_localized());
if (ss.name.has_description()) {
button->set_tooltip_markup(ss.name.get_description());
/*Gtk::Label *label = new Gtk::Label();
label->set_line_wrap(true);
label->set_justify(Gtk::JUSTIFY_FILL);
label->set_use_markup(true);
label->set_markup(Util::latin_to_utf8(sub_schema->description));
table1.attach(*label, 1, 3, row, row+1, Gtk::FILL, Gtk::FILL, 5, 5);*/
}
box_actions.pack_start(*button, Gtk::PACK_SHRINK);
/*Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_CENTER, Gtk::ALIGN_CENTER, 0, 0);
align->add(*button);*/
//table1.attach(*align, 0, 1, row, row+1, Gtk::FILL, Gtk::FILL, 5, 5);
//row++;
buttons.push_back(button);
button->signal_clicked().connect(
sigc::bind(sigc::mem_fun(*this, &AttributeListView::on_b_command),
ss.name.get_id()));
}
}
# endif
if (!indicators_detected && has_no_command)
{
the_vbox.pack_start(hbox, Gtk::PACK_SHRINK);
}
else
{
frame_att.add(hbox);
if (!has_no_attributes)
{
the_vbox.pack_start(frame_att, Gtk::PACK_SHRINK);
frame_att.set_label(langue.get_item("attributes"));
}
if (indicators_detected)
{
//the_vbox.pack_start(frame_indicators, Gtk::PACK_SHRINK);
the_vbox.pack_start(table_indicators, Gtk::PACK_SHRINK);
}
if (!has_no_command)
{
the_vbox.pack_start(/*frame*/box_actions, Gtk::PACK_SHRINK);
}
}
//scroll.add(the_vbox);
//pack_start(scroll, Gtk::PACK_SHRINK);
//scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
pack_start(the_vbox, Gtk::PACK_SHRINK);
//scroll.set_min_placement_height(500);
//scroll.set_min_placement_width(500);
/*int w, h;
Gtk::Requisition requi = the_vbox.size_request();
w = requi.width;
h = requi.height;
infos("REQUI w = %d, h = %d.", w, h);
scroll.set_size_request(w + 30, h + 30);*/
model.add_listener(this);
ChangeEvent ce;
on_event(ce);
//signal_realize().connect(sigc::mem_fun(*this, &AttributeListView::on_the_realisation));
}
AttributeListView::AttributeListView(Node model,
const NodeViewConfiguration &config)
{
init(model, config);
}
static void exec_cmde(Node &model, std::string cmde_name)
{
CommandSchema *cs = model.schema()->get_command(cmde_name);
if (cs != nullptr)
{
ChangeEvent ce = ChangeEvent::create_command_exec(&model, cs->name.get_id());
model.dispatch_event(ce);
# if 0
/* has parameters ? */
if (!cs->input.is_nullptr()) {
//infos("Asking for command parameters..");
Node prm = Node::create_ram_node(cs->input.get_reference());
if (NodeDialog::display_modal(prm) == 0)
{
ChangeEvent ce = ChangeEvent::create_command_exec(&model,
cs->name.get_id(), &prm);
//infos("Dispatching command + parameters..");
model.dispatch_event(ce);
}
/*ChangeEvent ce = ChangeEvent::create_command_exec(&model,
cs->name.get_id());
model.dispatch_event(ce);*/
}
/* no parameters */
else
{
ChangeEvent ce = ChangeEvent::create_command_exec(&model,
cs->name.get_id());
model.dispatch_event(ce);
}
# endif
}
}
void AttributeListView::on_b_command(std::string name)
{
infos("B command detected: %s.", name.c_str());
CommandSchema *cs = model.schema()->get_command(name);
if (cs != nullptr)
{
ChangeEvent ce = ChangeEvent::create_command_exec(&model, cs->name.get_id());
model.dispatch_event(ce);
# if 0
/* has parameters ? */
if (!cs->input.is_nullptr())
{
infos("Asking for command parameters..");
Node prm = Node::create_ram_node(cs->input.get_reference());
if (NodeDialog::display_modal(prm) == 0)
{
ChangeEvent ce = ChangeEvent::create_command_exec(&model,
cs->name.get_id(), &prm);
infos("Dispatching command + parameters..");
model.dispatch_event(ce);
}
}
/* no parameters */
else
{
ChangeEvent ce = ChangeEvent::create_command_exec(&model,
cs->name.get_id(), nullptr);
model.dispatch_event(ce);
}
# endif
}
}
void AttributeListView::set_sensitive(bool sensitive)
{
list_is_sensitive = sensitive;
ChangeEvent ce;
on_event(ce);
/*for(auto i = 0u; i < attributes_view.size(); i++)
{
AttributeView *ev = attributes_view[i].av;
bool valid = model.is_attribute_valid(ev->model->schema->name.get_id());
bool sens = list_is_sensitive
&& valid
&& !(ev->model->schema->is_read_only && !ev->model->schema->is_instrument);
ev->set_sensitive(sens);
//if(ev->model->schema->is_read_only && ev->model->schema->is_instrument)
if(attributes_view[i].desc != nullptr)
attributes_view[i].desc->set_sensitive(sens);
}*/
}
void AttributeListView::on_event(const ChangeEvent &ce)
{
//infos(ce.to_string());
for (unsigned int i = 0; i < attributes_view.size(); i++)
{
AttributeView *av = attributes_view[i].av;
bool valid = model.is_attribute_valid(av->model->schema->name.get_id());
bool sens = list_is_sensitive && valid && !(av->model->schema->is_read_only && !av->model->schema->is_instrument);
av->set_sensitive(sens);
if(attributes_view[i].desc != nullptr)
attributes_view[i].desc->set_sensitive(sens);
}
}
SelectionView::SelectionView():
JFrame(langue.get_item("Options"))
{
init();
}
void SelectionView::init()
{
lock = false;
scroll.add(tree_view);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
tree_model = Gtk::TreeStore::create(columns);
tree_view.set_model(tree_model);
{
Gtk::CellRendererToggle *renderer_active = Gtk::manage(
new Gtk::CellRendererToggle());
renderer_active->signal_toggled().connect(
sigc::mem_fun(*this, &SelectionView::on_cell_toggled));
Gtk::TreeView::Column* column = Gtk::manage(
new Gtk::TreeView::Column(langue.get_item("Use it")));
column->pack_start(*renderer_active, false);
column->add_attribute(renderer_active->property_active(),
columns.m_col_use);
tree_view.append_column(*column);
}
{
Gtk::CellRendererText *render = Gtk::manage(new Gtk::CellRendererText());
Gtk::TreeView::Column *viewcol = Gtk::manage(
new Gtk::TreeView::Column("Option", *render));
viewcol->add_attribute(render->property_markup(), columns.m_col_name);
tree_view.append_column(*viewcol);
}
{
Gtk::CellRendererText *render = Gtk::manage(new Gtk::CellRendererText());
Gtk::TreeView::Column *viewcol = Gtk::manage(
new Gtk::TreeView::Column("Description", *render));
viewcol->add_attribute(render->property_markup(), columns.m_col_desc);
//tree_view.append_column(*viewcol);
}
Glib::RefPtr < Gtk::TreeSelection > refTreeSelection =
tree_view.get_selection();
refTreeSelection->signal_changed().connect(
sigc::mem_fun(*this, &SelectionView::on_selection_changed));
add(scroll);
scroll.set_size_request(260, 200);
}
void SelectionView::setup(Node model)
{
this->model = model;
model.add_listener((CListener<ChangeEvent> *) this);
update_view();
}
SelectionView::SelectionView(Node model)
: JFrame(langue.get_item("Options"))
{
init();
setup(model);
update_view();
}
void SelectionView::update_view()
{
if (!lock)
{
lock = true;
NodeSchema *selected_schem = get_selected();
Gtk::TreeModel::Row row;
clear_table();
uint32_t nb_optionnals = 0;
for (unsigned int i = 0; i < model.schema()->children.size(); i++)
{
SubSchema ss = model.schema()->children[i];
if ((ss.min != 0) || (ss.max != 1))
continue;
nb_optionnals++;
NodeSchema *&scheme = ss.ptr;
std::string nm = ss.name.get_id();
std::string desc = scheme->name.get_description(Localized::LANG_CURRENT); //scheme->description;
nm = NodeView::mk_label(scheme->name);
/*if(langue.has_item(nm))
nm = langue.getItem(nm);*/
if (langue.has_item(desc))
desc = langue.get_item(desc);
bool in_use = model.has_child(ss.name.get_id());
row = *(tree_model->append());
row[columns.m_col_name] = (in_use ? "<b>" : "") + nm
+ (in_use ? "</b>" : "");
row[columns.m_col_use] = in_use;
row[columns.m_col_desc] = (!in_use ? "<span color=\"gray\">" : "") + desc
+ (!in_use ? "</span>" : "");
row[columns.m_col_ptr] = scheme;
//row[columns.m_col_ptr_opt] = &(model->schema->optionals[i]);
}
int dy = 40 + 22 * nb_optionnals;
if(dy > 350)
dy = 350;
//scroll.set_size_request(-1, dy);
scroll.set_size_request(250, dy);
tree_view.expand_all();
// If anything is selected
if (selected_schem != nullptr)
set_selection(selected_schem);
lock = false;
}
# if 0
for (unsigned int i = 0; i < model.schema()->optionals.size(); i++)
{
NodeSchema *scheme = model.schema()->optionals[i].ptr;
std::string nm = model.schema()->optionals[i].name;
std::string desc = scheme->description;
nm = mk_label2(scheme);
/*if(langue.has_item(nm))
nm = langue.getItem(nm);*/
if(langue.has_item(desc))
desc = langue.get_item(desc);
bool in_use = model.has_child(model.schema()->optionals[i].name);
row = *(tree_model->append());
row[columns.m_col_name] = (in_use ? "<b>" : "") + nm + (in_use ? "</b>" : "");
row[columns.m_col_use] = in_use;
row[columns.m_col_desc] = (!in_use ? "<span color=\"gray\">" : "") + desc + (!in_use ? "</span>" : "");
row[columns.m_col_ptr] = scheme;
//row[columns.m_col_ptr_opt] = &(model->schema->optionals[i]);
}
scroll.set_size_request(-1, 40 + 22 * model.schema()->optionals.size());
tree_view.expand_all();
// If anything is selected
if(selected_schem != nullptr)
set_selection(selected_schem);
lock = false;
}
# endif
}
void SelectionView::clear_table() {
while (1) {
typedef Gtk::TreeModel::Children type_children; //minimise code length.
type_children children = tree_model->children();
type_children::iterator iter = children.begin();
if (iter == children.end())
return;
Gtk::TreeModel::Row row = *iter;
tree_model->erase(row);
}
}
void SelectionView::on_selection_changed() {
}
NodeSchema *SelectionView::get_selected() {
Glib::RefPtr < Gtk::TreeSelection > refTreeSelection =
tree_view.get_selection();
Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();
NodeSchema *selected = nullptr;
if(iter)
{
Gtk::TreeModel::Row ligne = *iter;
selected = ligne[columns.m_col_ptr];
}
return selected;
}
void SelectionView::set_selection(NodeSchema *&option) {
if (option != nullptr)
return;
typedef Gtk::TreeModel::Children type_children;
type_children children = tree_model->children();
for (type_children::iterator iter = children.begin(); iter != children.end();
++iter) {
Gtk::TreeModel::Row row = *iter;
NodeSchema *opt = row[this->columns.m_col_ptr];
if(option == opt)
tree_view.get_selection()->select(row);
}
}
void SelectionView::on_cell_toggled(const Glib::ustring& path)
{
Gtk::TreeModel::iterator iter = tree_model->get_iter(path);
infos("cell toggled: %s", path.c_str());
if(iter && !lock)
{
NodeSchema *schem = (*iter)[columns.m_col_ptr];
string name = schem->name.get_id();
lock = true;
(*iter)[columns.m_col_use] = !(*iter)[columns.m_col_use];
bool in_use = (*iter)[columns.m_col_use];
if(in_use)
{
infos("Ajout option %s", name.c_str());
if(!model.has_child(name))
model.add_child(name);
else
infos("Mais déjà présente!");
}
else
{
infos("Retrait option %s", name.c_str());
if(model.has_child(name))
model.remove_child(model.get_child(name));
}
lock = false;
//update_view();
}
}
/******************************************************************
* STRING LIST VIEW
******************************************************************/
VueTable::MyTreeView::MyTreeView(VueTable *parent) :
Gtk::TreeView() {
this->parent = parent;
}
bool VueTable::MyTreeView::on_button_press_event(GdkEventButton *event)
{
infos("b press event");
if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) {
Node m = parent->get_selected();
if (m.is_nullptr()) {
return TreeView::on_button_press_event(event);
}
if (m.schema()->commands.size() > 0) {
//ChangeEvent ce = ChangeEvent::create_command_exec(Node *source, std::string name, Node *params);
exec_cmde(m, m.schema()->commands[0].name.get_id());
}
return true;
}
return TreeView::on_button_press_event(event);
}
Gtk::Widget *VueTable::get_gtk_widget()
{
return &hbox;//this;
}
VueTable::VueTable(Node &modele_donnees,
Node &modele_vue,
Controleur *controleur):
tree_view(this)
{
nb_lignes = -1;
Node md = modele_donnees;
std::string mod = modele_vue.get_attribute_as_string("modele");
if(mod.size() > 0)
{
md = md.get_child(mod);
if(md.is_nullptr())
{
erreur("hughjkjkjk");
return;
}
}
std::string type_sub = modele_vue.get_attribute_as_string("type-sub");
if(type_sub.size() == 0)
{
erreur("constructeur stringlistview : type-sub non précisé.");
return;
}
auto sub_schema = md.schema()->get_child(type_sub);
if(sub_schema == nullptr)
{
std::string s = md.to_xml();
erreur("Creation table : sous schema non trouve. Schema = \n%s\ntype sub = %s", s.c_str(), type_sub.c_str());
return;
}
NodeViewConfiguration cfg;
Config config;
config.affiche_boutons = modele_vue.get_attribute_as_boolean("affiche-boutons");
init(md, sub_schema->ptr, cfg, config);
}
VueTable::VueTable(Node model, NodeSchema *&sub,
const NodeViewConfiguration &cfg):
tree_view(this)
{
Config config;
init(model, sub, cfg, config);
}
void VueTable::init(Node model, NodeSchema *&sub,
const NodeViewConfiguration &cfg, Config &config)
{
this->config = config;
int ncols = 0;
unsigned int i;
this->model = model;
this->schema = sub;
lock = false;
std::string name = sub->name.get_localized();
can_remove = true;
for (i = 0; i < model.schema()->children.size(); i++) {
if (model.schema()->children[i].ptr == sub) {
sub_schema = model.schema()->children[i];
break;
}
}
if (langue.has_item(name))
name = langue.get_item(name);
if ((name[0] >= 'a') && (name[0] <= 'z'))
name[0] = name[0] + ('A' - 'a');
name += "s";
//set_label(name);
b_add.set_label(langue.get_item("Add..."));
b_remove.set_label(langue.get_item("Remove"));
bool has_v_scroll = true;
bool has_h_scroll = true;
scroll.set_policy(has_h_scroll ? Gtk::POLICY_AUTOMATIC : Gtk::POLICY_NEVER,
has_v_scroll ? Gtk::POLICY_AUTOMATIC : Gtk::POLICY_NEVER);
columns.add(columns.m_col_ptr);
for (unsigned int i = 0;
i < schema->attributes.size() + schema->references.size(); i++)
columns.add(columns.m_cols[i]);
tree_model = Gtk::TreeStore::create(columns);
tree_view.set_model(tree_model);
for (i = 0; i < schema->attributes.size(); i++)
{
refptr<AttributeSchema> as = schema->attributes[i];
std::string cname = as->name.get_localized();
if (langue.has_item(cname))
cname = langue.get_item(cname);
if ((cname[0] >= 'a') && (cname[0] <= 'z'))
cname[0] += 'A' - 'a';
if (as->is_hidden)
continue;
ncols++;
if (as->type == TYPE_COLOR)
{
ColorCellRenderer2 * const colrenderer = new ColorCellRenderer2(as->constraints);
Gtk::TreeViewColumn * const colcolumn = new Gtk::TreeViewColumn(cname,
*Gtk::manage(colrenderer));
tree_view.append_column(*Gtk::manage(colcolumn));
colcolumn->add_attribute(colrenderer->property_text(), columns.m_cols[i]);
colrenderer->property_editable() = true;
colrenderer->signal_edited().connect(
sigc::bind < std::string
> (sigc::mem_fun(*this, &VueTable::on_editing_done), as->name.get_id()));
if (appli_view_prm.use_touchscreen) {
colrenderer->signal_editing_started().connect(
sigc::bind < std::string
> (sigc::mem_fun(*this, &VueTable::on_editing_start), as->name.get_id()));
}
}
else
{
Gtk::CellRendererText *render;
if(as->enumerations.size() > 0)
{
infos("Creation cell combo...");
auto render_combo = Gtk::manage(new Gtk::CellRendererCombo());
render = render_combo;
//render->property_text() = 0;
render->property_editable() = true;
struct ModelColonneCombo: public Gtk::TreeModel::ColumnRecord
{
Gtk::TreeModelColumn<Glib::ustring> choice; // valeurs possibles
ModelColonneCombo()
{
add(choice);
}
};
ModelColonneCombo col_combo;
Glib::RefPtr<Gtk::ListStore> model_combo = Gtk::ListStore::create(col_combo);
for(auto &e : as->enumerations)
{
auto s = e.name.get_localized();
infos("Enumeration : %s", s.c_str());
(*model_combo->append())[col_combo.choice] = s;
}
//Glib::PropertyProxy< bool > prp;
//prp.set_value(true);
//render_combo->property_has_entry().set_value(false);
render_combo->property_model().set_value(model_combo);
render_combo->property_text_column().set_value(0);
render_combo->property_has_entry().set_value(false);
//render_combo->signal_changed().connect(
// sigc::bind<std::string>(sigc::mem_fun(*this, &VueTable::on_change), as->name.get_id()));
}
else
{
render = Gtk::manage(new Gtk::CellRendererText());
if (as->is_read_only)
{
render->property_editable() = false;
}
else
{
render->property_editable() = true;
render->signal_editing_started().connect(
sigc::bind<std::string>(sigc::mem_fun(*this, &VueTable::on_editing_start), as->name.get_id()));
}
}
render->signal_edited().connect(
sigc::bind<std::string>(sigc::mem_fun(*this, &VueTable::on_editing_done), as->name.get_id()));
cell_renderers.push_back(render);
Gtk::TreeView::Column *viewcol = Gtk::manage(
new Gtk::TreeView::Column(cname, *render));
viewcol->add_attribute(render->property_markup(), columns.m_cols[i]);
tree_view.append_column(*viewcol);
}
}
/*for(unsigned int i = 0; i < schema->commands.size(); i++)
{
CommandSchema cs = schema->commands[i];
std::string cname = cs.name.get_localized();
Gtk::CellRendererToggle *render = Gtk::manage(new Gtk::CellRendererToggle());
cell_renderers.push_back(render);
Gtk::TreeView::Column *viewcol = Gtk::manage(new Gtk::TreeView::Column(cname, *render));
//viewcol->add_attribute(render->property_markup(), columns.m_cols[i]);
tree_view.append_column(*viewcol);
}*/
for (i = 0; i < schema->references.size(); i++)
{
RefSchema as = schema->references[i];
std::string cname = as.name.get_localized();
if (langue.has_item(cname))
cname = langue.get_item(cname);
if ((cname[0] >= 'a') && (cname[0] <= 'z'))
cname[0] += 'A' - 'a';
if (as.is_hidden)
continue;
ncols++;
RefCellRenderer * const colrenderer = new RefCellRenderer();
Gtk::TreeViewColumn * const colcolumn = new Gtk::TreeViewColumn(cname,
*Gtk::manage(colrenderer));
tree_view.append_column(*Gtk::manage(colcolumn));
colcolumn->add_attribute(colrenderer->property_text(),
columns.m_cols[i + schema->attributes.size()]);
colrenderer->property_editable() = true;
colrenderer->signal_edited().connect(
sigc::bind < std::string
> (sigc::mem_fun(*this, &VueTable::on_editing_done), as.name.get_id()));
colrenderer->signal_editing_started().connect(
sigc::bind < std::string
> (sigc::mem_fun(*this, &VueTable::on_editing_start), as.name.get_id()));
}
Glib::RefPtr < Gtk::TreeSelection > refTreeSelection =
tree_view.get_selection();
refTreeSelection->signal_changed().connect(
sigc::mem_fun(*this, &VueTable::on_selection_changed));
Gtk::Image *buttonImage_ = new Gtk::Image(
utils::get_img_path() + files::get_path_separator() + "gtk-go-up16.png");
b_up.set_image(*buttonImage_);
buttonImage_ = new Gtk::Image(
utils::get_img_path() + files::get_path_separator() + "gtk-go-down16.png");
b_down.set_image(*buttonImage_);
b_remove.signal_clicked().connect(
sigc::mem_fun(*this, &VueTable::on_b_remove));
b_up.signal_clicked().connect(sigc::mem_fun(*this, &VueTable::on_b_up));
b_down.signal_clicked().connect(
sigc::mem_fun(*this, &VueTable::on_b_down));
b_add.signal_clicked().connect(
sigc::mem_fun(*this, &VueTable::on_b_add));
/*scroll.add(tree_view);
hbox.pack_start(scroll, Gtk::PACK_EXPAND_WIDGET);*/
//hbox.pack_start(tree_view, Gtk::PACK_EXPAND_WIDGET);
scroll.add(tree_view);
hbox.pack_start(scroll, Gtk::PACK_EXPAND_WIDGET);
for (i = 0; i < sub->commands.size(); i++)
{
CommandSchema &cs = sub->commands[i];
// TODO: smart pointer
Gtk::Button *b = new Gtk::Button();
button_box.pack_start(*b, Gtk::PACK_SHRINK);
b->set_label(cs.name.get_localized());
b->signal_clicked().connect(
sigc::bind < std::string
> (sigc::mem_fun(*this, &VueTable::on_b_command), cs.name.get_id()));
}
button_box.pack_start(b_up, Gtk::PACK_SHRINK);
button_box.pack_start(b_down, Gtk::PACK_SHRINK);
button_box.pack_start(b_add, Gtk::PACK_SHRINK);
button_box.pack_start(b_remove, Gtk::PACK_SHRINK);
if (!sub_schema.readonly || (sub->commands.size() > 1))
{
if(config.affiche_boutons)
hbox.pack_start(button_box, Gtk::PACK_SHRINK);
}
button_box.set_border_width(5);
button_box.set_layout(Gtk::BUTTONBOX_END);
hbox.set_border_width(5);
//add(hbox);
update_view();
//model->CProvider<ChangeEvent>::add_listener(this);
model.add_listener(this);
tree_view.set_headers_visible(sub_schema.show_header);
//set_size_request(130 + ncols * 120, 200);
//Gtk::Requisition minimum, natural;
int dx, dy;
/*tree_view.get_preferred_size(minimum, natural);
infos("req min = %d,%d, natural = %d,%d.",
minimum.width, minimum.height,
natural.width, natural.height);
int dx = minimum.width, dy = minimum.height;*/
tree_view.get_size_request(dx, dy);
//infos("tree view size request = %d,%d.", dx, dy);
dy = 200;
if (dx < 150)
dx = 150;
if (dx > 300)
dx = 300;
if (appli_view_prm.use_touchscreen) {
dx = 245 + ncols * 120;
dy = 200;
} else {
if (sub->name.get_id().compare("description") == 0) {
dx = 150 + ncols * 120;
dy = 150;
} else {
dx = 150 + ncols * 120;
dy = 200;
}
}
if (cfg.table_width != -1)
dx = cfg.table_width;
if (cfg.table_height != -1)
dy = cfg.table_height;
hbox.set_size_request(dx, dy);
tree_view.set_grid_lines(Gtk::TREE_VIEW_GRID_LINES_BOTH);
# if 0
if(appli_view_prm.use_touchscreen)
set_size_request(245 + ncols * 120, 200);
else
{
if(sub->name.get_id().compare("description") == 0)
set_size_request(150 + ncols * 120, 150);
else
set_size_request(150 + ncols * 120, 200);
}
# endif
//set_size_request(-1, 200);
}
void VueTable::on_b_command(std::string command) {
infos("command detected: %s.", command.c_str());
Node selection = get_selected();
exec_cmde(selection, command);
}
void VueTable::update_langue() {
b_add.set_label(langue.get_item("Add..."));
b_remove.set_label(langue.get_item("Remove"));
}
void VueTable::on_event(const ChangeEvent &ce)
{
if (!lock)
{
//infos(ce.to_string());
//lock = true;
//infos("event -> update_view..");
if(ce.type == ChangeEvent::GROUP_CHANGE)
{
auto s = ce.to_string();
infos("VueTable : change evt: %s.", s.c_str());
update_view();
}
//lock = false;
}
}
void VueTable::maj_ligne(Gtk::TreeModel::Row &trow, unsigned int row)
{
auto id_sub = schema->name.get_id();
Node sub = model.get_child_at(id_sub, row);
for(auto col = 0u; col < schema->attributes.size(); col++)
{
maj_cellule(trow, row, col);
}
for (auto j = 0u; j < schema->references.size(); j++)
{
Node ref = sub.get_reference(schema->references[j].name.get_id());
//ref.infos("one ref.");
std::string name = ref.get_localized().get_localized();
trow[columns.m_cols[schema->attributes.size() + j]] = name;
}
}
void VueTable::maj_cellule(Gtk::TreeModel::Row &trow, unsigned int row, unsigned int col)
{
auto id_sub = schema->name.get_id();
Node sub = model.get_child_at(id_sub, row);
std::string val, name;
auto &as = schema->attributes[col];
name = as->name.get_id();
val = as->get_ihm_value(sub.get_attribute_as_string(name));
if(as->has_unit())
val += " " + as->unit;
trow[columns.m_cols[col]] = val;
}
//int essai_plante = 0;
void VueTable::update_view()
{
uint32_t i;
//if(essai_plante)
//erreur("Vue table : update view innatendu.");
if (!lock)
{
infos("VueTable -> maj.");
auto id_sub = schema->name.get_id();
if((nb_lignes > 0) && ((int) model.get_children_count(id_sub) == nb_lignes))
{
infos("VueTable : maj slmt des valeurs.");
lock = true;
typedef Gtk::TreeModel::Children type_children;
type_children children = tree_model->children();
auto iter = children.begin();
// Only update the values
for(i = 0; i < (unsigned int) nb_lignes; i++)
{
auto r = *iter++;
maj_ligne(r, i);
}
lock = false;
return;
}
can_remove = true;
lock = true;
Node selected = get_selected();
Node first, last;
Gtk::TreeModel::Row row;
clear_table();
for (i = 0; i < model.get_children_count(id_sub); i++)
{
Node sub = model.get_child_at(id_sub, i);
row = *(tree_model->append());
maj_ligne(row, i);
row[columns.m_col_ptr] = sub;
}
//scroll.set_size_request(-1, 40 + 22 * model->schema->optionals.size());
tree_view.expand_all();
// If anything is selected
if (!selected.is_nullptr()) {
set_selection(selected);
b_remove.set_sensitive(true);
b_up.set_sensitive(selected != first);
b_down.set_sensitive(selected != last);
} else {
b_up.set_sensitive(false);
b_down.set_sensitive(false);
b_remove.set_sensitive(false);
}
b_add.set_sensitive(true);
int nchild = model.get_children_count(this->schema->name.get_id());
for (uint32_t i = 0; i < model.schema()->children.size(); i++) {
SubSchema ss = model.schema()->children[i];
if (ss.ptr == schema) {
if (ss.has_min() && (nchild <= ss.min)) {
b_remove.set_sensitive(false);
can_remove = false;
}
if (ss.has_max() && (nchild >= ss.max))
b_add.set_sensitive(false);
break;
}
}
lock = false;
}
if (sub_schema.readonly) {
b_add.set_sensitive(false);
b_down.set_sensitive(false);
b_up.set_sensitive(false);
b_remove.set_sensitive(false);
}
}
void VueTable::clear_table() {
while (1) {
typedef Gtk::TreeModel::Children type_children;
type_children children = tree_model->children();
type_children::iterator iter = children.begin();
if (iter == children.end())
return;
Gtk::TreeModel::Row row = *iter;
tree_model->erase(row);
}
}
void VueTable::on_selection_changed() {
//infos("selection changed.");
if (!lock) {
lock = true;
Node selected = get_selected();
if (selected.is_nullptr()) {
b_remove.set_sensitive(false);
b_up.set_sensitive(false);
b_down.set_sensitive(false);
} else {
b_remove.set_sensitive(can_remove);
unsigned int n = model.get_children_count(sub_schema.child_str);
Node first = model.get_child_at(sub_schema.child_str, 0);
Node last = model.get_child_at(sub_schema.child_str, n - 1);
b_up.set_sensitive(selected != first);
b_down.set_sensitive(selected != last);
}
lock = false;
}
}
Node VueTable::get_selected() {
Glib::RefPtr < Gtk::TreeSelection > refTreeSelection =
tree_view.get_selection();
Gtk::TreeModel::iterator iter = refTreeSelection->get_selected();
Node selected;
if (iter) {
Gtk::TreeModel::Row ligne = *iter;
selected = ligne[columns.m_col_ptr];
}
return selected;
}
void VueTable::set_selection(Node sub) {
if (sub.is_nullptr())
return;
typedef Gtk::TreeModel::Children type_children;
type_children children = tree_model->children();
for (type_children::iterator iter = children.begin(); iter != children.end();
++iter) {
Gtk::TreeModel::Row row = *iter;
Node e = row[columns.m_col_ptr];
if (e == sub)
tree_view.get_selection()->select(row);
}
}
void VueTable::on_editing_done(Glib::ustring path,
Glib::ustring text,
std::string col)
{
infos("edit done.");
bool display_editing_dialog = false;
if (appli_view_prm.use_touchscreen)
display_editing_dialog = true;
// Check if a column is a text view
for (unsigned int i = 0; i < schema->attributes.size(); i++)
{
refptr<AttributeSchema> &as = schema->attributes[i];
if ((as->type == TYPE_STRING) && (as->formatted_text))
{
display_editing_dialog = true;
break;
}
}
if (display_editing_dialog)
return;
//if(appli_view_prm.use_touchscreen)
// return;
if (!lock) {
lock = true;
std::string p = path;
std::string s = text;
//infos("slview : update val s = %s.", s.c_str());
int row = atoi(p.c_str());
infos("Editing done: col=%s, row=%d, path=%s, val=%s.",
col.c_str(), row,
p.c_str(), s.c_str());
if ((row < 0)
|| (row >= (int) model.get_children_count(schema->name.get_id()))) {
erreur("invalid row.");
return;
}
Node sub = model.get_child_at(schema->name.get_id(), row);
lock = false;
if (sub.has_attribute(col))
sub.set_attribute(col, s);
update_view();
}
}
void VueTable::on_editing_start(Gtk::CellEditable *ed, Glib::ustring path,
std::string col) {
infos("editing start: col = %s", col.c_str());
for (unsigned int i = 0; i < schema->references.size(); i++) {
if (schema->references[i].name.get_id().compare(col) == 0) {
infos("It is a reference column.");
RefCellEditable *rce = (RefCellEditable *) ed;
std::string p = path;
int row = atoi(p.c_str());
if ((row < 0)
|| (row >= (int) model.get_children_count(schema->name.get_id()))) {
erreur("invalid row.");
return;
}
Node sub = model.get_child_at(schema->name.get_id(), row);
//sub.infos("setup model..");
rce->setup_model(sub, col);
return;
}
}
bool display_editing_dialog = false;
if (appli_view_prm.use_touchscreen)
display_editing_dialog = true;
// Check if a column is a text view
for (unsigned int i = 0; i < schema->attributes.size(); i++) {
refptr<AttributeSchema> &as = schema->attributes[i];
if ((as->type == TYPE_STRING) && (as->formatted_text)) {
display_editing_dialog = true;
break;
}
}
if (!display_editing_dialog)
return;
if (!lock) {
lock = true;
std::string p = path;
int row = atoi(p.c_str());
infos("Editing start: col=%s, row=%d, path=%s.", col.c_str(), row,
p.c_str());
if ((row < 0)
|| (row >= (int) model.get_children_count(schema->name.get_id()))) {
erreur("invalid row.");
return;
}
Node sub = model.get_child_at(schema->name.get_id(), row);
NodeDialog::display_modal(sub);
for (unsigned int i = 0; i < cell_renderers.size(); i++) {
cell_renderers[i]->stop_editing(false);
}
tree_view.get_selection()->unselect_all();
//GtkKeyboard::get_instance()->present();
lock = false;
update_view();
}
}
bool VueTable::is_valid() {
return true;
}
void VueTable::on_b_remove() {
Node sub = get_selected();
model.remove_child(sub);
update_view();
}
void VueTable::on_b_up() {
Node sub = get_selected();
set_selection(sub.parent().up(sub));
}
void VueTable::on_b_down() {
Node sub = get_selected();
set_selection(sub.parent().down(sub));
}
void VueTable::on_b_add() {
Node nv = model.add_child(schema);
if (NodeDialog::display_modal(nv))
model.remove_child(nv);
else {
update_view();
set_selection(nv);
}
}
NodeDialog::~NodeDialog() {
window->hide();
delete ev;
}
void NodeDialog::maj_langue()
{
if(ev != nullptr)
ev->maj_langue();
tool_valid.set_label(langue.get_item("b-valid"));
tool_cancel.set_label(langue.get_item("b-cancel"));
auto titre = model.schema()->name.get_localized();
wnd.set_title(titre);
dlg.set_title(titre);
label_title.set_markup(titre);
b_apply.set_label(langue.get_item("b-apply"));
b_valid.set_label(langue.get_item("b-valid"));
b_close.set_label(langue.get_item("b-cancel"));
}
NodeDialog::NodeDialog(Node model, bool modal, Gtk::Window *parent_window) :
dlg("", modal), keyboard(&dlg), kb_align(Gtk::ALIGN_CENTER,
Gtk::ALIGN_CENTER, 0, 0) {
this->modal = modal;
this->fullscreen = false;
lastx = -1;
lasty = -1;
exposed = false;
//infos("CONS: modal = %s.", modal ? "true" : "false");
lock = false;
u2date = true;
this->model = model;
backup = Node::create_ram_node(model.schema());
backup.copy_from(model);
NodeViewConfiguration config;
config.show_desc = false;
config.show_children = false;
ev = new NodeView(mainWindow, backup, config);
ev->CProvider<KeyPosChangeEvent>::add_listener(this);
//trace_major("EV IS READY.");
if(!modal)
{
window = &wnd;
wnd.set_position(Gtk::WIN_POS_CENTER);
wnd.add(vbox);
vb = &vbox;
}
else
{
window = &dlg;
dlg.set_position(Gtk::WIN_POS_CENTER);
vb = dlg.get_vbox();
}
if (!appli_view_prm.use_decorations)
{
window->set_decorated(false);
vb->pack_start(label_title, Gtk::PACK_SHRINK);
}
/*vb->pack_start(scroll, Gtk::PACK_EXPAND_WIDGET);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
scroll.add(*(ev->get_widget()));*/
vb->pack_start(*(ev->get_widget()), Gtk::PACK_SHRINK);
Gtk::Image *img_valid, *img_cancel, *img_apply;
if (appli_view_prm.img_validate.size() > 0)
img_valid = new Gtk::Image(appli_view_prm.img_validate);
else
img_valid = new Gtk::Image(Gtk::StockID(Gtk::Stock::APPLY),
Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
if (appli_view_prm.img_cancel.size() > 0)
img_cancel = new Gtk::Image(appli_view_prm.img_cancel);
else
img_cancel = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL),
Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
img_apply = new Gtk::Image(Gtk::StockID(Gtk::Stock::APPLY),
Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
if (appli_view_prm.use_button_toolbar)
{
tool_valid.set_icon_widget(*img_valid);
tool_cancel.set_icon_widget(*img_cancel);
toolbar.insert(tool_cancel, -1,
sigc::mem_fun(*this, &NodeDialog::on_b_close));
toolbar.insert(sep2, -1);
sep2.set_expand(true);
sep2.set_property("draw", false);
toolbar.insert(tool_valid, -1,
sigc::mem_fun(*this, &NodeDialog::on_b_apply));
}
else
{
hbox.pack_end(b_close, Gtk::PACK_SHRINK);
hbox.pack_end(b_apply, Gtk::PACK_SHRINK);
hbox.pack_end(b_valid, Gtk::PACK_SHRINK);
hbox.set_layout(Gtk::BUTTONBOX_END);
b_close.set_border_width(4);
b_apply.set_border_width(4);
b_valid.set_border_width(4);
b_valid.set_image(*img_valid);
b_apply.set_image(*img_apply);
b_close.set_image(*img_cancel);
}
if (appli_view_prm.use_touchscreen) {
keyboard.target_window = window;
kb_align.add(keyboard);
}
maj_langue();
add_widgets();
/*
if(appli_view_prm.vkeyboard_below)
{
if(appli_view_prm.use_button_toolbar)
vb->pack_start(toolbar, Gtk::PACK_SHRINK);
else
vb->pack_start(hbox, Gtk::PACK_SHRINK);
vb->pack_start(keyboard_separator, Gtk::PACK_SHRINK);
vb->pack_start(keyboard, Gtk::PACK_SHRINK);
}
else
{
vb->pack_start(keyboard_separator, Gtk::PACK_SHRINK);
vb->pack_start(keyboard, Gtk::PACK_SHRINK);
if(appli_view_prm.use_button_toolbar)
vb->pack_start(toolbar, Gtk::PACK_SHRINK);
else
vb->pack_start(hbox, Gtk::PACK_SHRINK);
}
}
else
{
if(appli_view_prm.use_button_toolbar)
vb->pack_start(toolbar, Gtk::PACK_SHRINK);
else
vb->pack_start(hbox, Gtk::PACK_SHRINK);
}*/
window->show_all_children(true);
b_close_ptr = &b_close;
b_apply_ptr = &b_apply;
if (modal) {
if (parent_window != nullptr)
dlg.set_transient_for(*parent_window);
else if (mainWindow != nullptr)
dlg.set_transient_for(*mainWindow);
} else {
wnd.show();
}
b_valid.signal_clicked().connect(
sigc::mem_fun(*this, &NodeDialog::on_b_valid));
b_apply.signal_clicked().connect(
sigc::mem_fun(*this, &NodeDialog::on_b_apply));
b_close.signal_clicked().connect(
sigc::mem_fun(*this, &NodeDialog::on_b_close));
update_view();
backup.add_listener(this);
window->signal_draw().connect(
sigc::mem_fun(*this, &NodeDialog::on_expose_event2));
//infos("done cons.");
}
void NodeDialog::on_b_close() {
result_ok = false;
window->hide();
/*if(modal)
{
dlg.hide();
}
else
{
wnd.hide();
//if(vkb_displayed)
//GtkKeyboard::get_instance()->close();
}*/
}
#if 0
void NodeDialog::on_b_valid()
{
model.copy_from(backup);
u2date = true;
update_view();
wnd.hide();
if(vkb_displayed)
GtkKeyboard::get_instance()->close();
/*NodeChangeEvent ce;
ce.source = model;
dispatch(ce);*/
}
#endif
void NodeDialog::on_b_apply()
{
model.copy_from(backup);
u2date = true;
update_view();
NodeChangeEvent ce;
ce.source = model;
dispatch(ce);
}
void NodeDialog::on_b_valid()
{
model.copy_from(backup);
u2date = true;
update_view();
infos("On b apply.");
/*if(pseudo_dialog)
{
infos("& pseudo dialog.");
if(vkb_displayed)
GtkKeyboard::get_instance()->close();
result_ok = true;
wnd.hide();
}
else*/
{
NodeChangeEvent ce;
ce.source = model;
dispatch(ce);
}
result_ok = true;
window->hide();
/*if(modal)
{
dlg.hide();
}
else
{
wnd.hide();
//if(vkb_displayed)
//GtkKeyboard::get_instance()->close();
}*/
}
bool NodeDialog::on_expose_event2(const Cairo::RefPtr<Cairo::Context> &cr)
{
if (!lock)
{
lock = true;
int x = window->get_allocation().get_width();
int y = window->get_allocation().get_height();
if (/*exposed &&*/((x != (int) lastx) || (y != (int) lasty))) {
trace_verbeuse("Size of node-dialog changed: %d,%d -> %d,%d.", lastx, lasty, x,
y);
DialogManager::setup_window(this, fullscreen);
}
lastx = x;
lasty = y;
lock = false;
}
exposed = true;
return true;
}
void NodeDialog::update_view() {
bool val = ev->is_valid();
infos("update view..");
//infos("update view: u2date = %s, pseudo = %s, is_valid = %s.", u2date ? "true" : "false", pseudo_dialog ? "true" : "false", val ? "true" : "false");
# if 0
if(u2date)
{
//b_apply.set_sensitive(/*false*/pseudo_dialog);
b_apply_ptr->set_sensitive(/*false*/pseudo_dialog);
}
else
# endif
{
//infos("Is valid = %s.", val ? "true" : "false");
b_apply_ptr->set_sensitive(val);
tool_valid.set_sensitive(val);
}
//infos("update view done.");
}
static std::vector<NodeDialog *> dial_instances;
void NodeDialog::on_event(const ChangeEvent &ce) {
infos("change event...");
if (!lock) {
lock = true;
u2date = false;
update_view();
lock = false;
}
if (ce.type == ChangeEvent::COMMAND_EXECUTED)
{
/* Reroute the change source from the backup model to the original model */
/*XPath path;
backup.get_path_to(*(ce.source_node), path);
Node owner;
owner = model.get_child(path);
ChangeEvent ce2 = ChangeEvent::create_command_exec(&owner, ce.path.get_last(),
ce.cmd_params);
this->model.dispatch_event(ce2);*/
}
infos("done.");
}
Gtk::Window *NodeDialog::get_window() {
return window;
}
void NodeDialog::unforce_scroll() {
infos("Unforce scroll..");
scroll.remove();
vb->remove(scroll);
remove_widgets();
vb->pack_start(*(ev->get_widget()), Gtk::PACK_SHRINK);
add_widgets();
window->show_all_children(true);
}
void NodeDialog::remove_widgets() {
if (appli_view_prm.use_touchscreen) {
vb->remove(keyboard_separator);
vb->remove(kb_align);
}
if (appli_view_prm.use_button_toolbar)
vb->remove(toolbar);
else
vb->remove(hbox);
}
void NodeDialog::add_widgets()
{
if (appli_view_prm.use_touchscreen)
{
if (appli_view_prm.vkeyboard_below)
{
if (appli_view_prm.use_button_toolbar)
vb->pack_start(kb_align, Gtk::PACK_SHRINK);
else
vb->pack_start(hbox, Gtk::PACK_SHRINK);
vb->pack_start(keyboard_separator, Gtk::PACK_SHRINK);
vb->pack_start(keyboard, Gtk::PACK_SHRINK);
}
else
{
vb->pack_start(keyboard_separator, Gtk::PACK_SHRINK);
vb->pack_start(kb_align, Gtk::PACK_SHRINK);
if (appli_view_prm.use_button_toolbar)
vb->pack_start(toolbar, Gtk::PACK_SHRINK);
else
vb->pack_start(hbox, Gtk::PACK_SHRINK);
}
} else {
if (appli_view_prm.use_button_toolbar)
vb->pack_start(toolbar, Gtk::PACK_SHRINK);
else
vb->pack_start(hbox, Gtk::PACK_SHRINK);
}
}
void NodeDialog::force_scroll(int dx, int dy) {
infos("Force scroll(%d,%d)..", dx, dy);
vb->remove(*(ev->get_widget()));
remove_widgets();
vb->pack_start(scroll, Gtk::PACK_EXPAND_WIDGET);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
scroll.add(*(ev->get_widget()));
add_widgets();
window->show_all_children(true);
}
void NodeDialog::on_event(const KeyPosChangeEvent &kpce) {
if (appli_view_prm.use_touchscreen) {
infos("update kb valid chars...");
keyboard.set_valid_chars(kpce.vchars);
}
}
NodeDialog *NodeDialog::display(Node model) {
for (unsigned int i = 0; i < dial_instances.size(); i++)
{
if (dial_instances[i]->model == model)
{
//model.infos("show old window.");
dial_instances[i]->backup.copy_from(model);
dial_instances[i]->wnd.show();
return dial_instances[i];
}
}
NodeDialog *nv = new NodeDialog(model, false);
nv->fullscreen = false;
dial_instances.push_back(nv);
DialogManager::setup_window(nv);
//nv->vkb_displayed = false;
nv->wnd.show();
/*if(appli_view_prm.use_touchscreen)
{
GtkKeyboard *kb = GtkKeyboard::get_instance();
kb->display(&nv->wnd);
nv->vkb_displayed = true;
}*/
return nv;
}
int NodeDialog::display_modal(Node model, bool fullscreen,
Gtk::Window *parent_window) {
NodeDialog *nv = new NodeDialog(model, true, parent_window);
nv->fullscreen = fullscreen;
DialogManager::setup_window(nv, fullscreen);
nv->result_ok = false;
infos("run..");
int res = nv->dlg.run();
//int res = 0;
//Gtk::Main::run(nv->dlg);
infos("run done.");
infos("hide...");
nv->dlg.hide();
if ((res == Gtk::RESPONSE_ACCEPT) || (nv->result_ok)) {
infos("copy model..");
model.copy_from(nv->backup);
infos("delete dialog..");
nv->lock = true;
delete nv;
infos("done.");
return 0;
}
delete nv;
return 1;
# if 0
if(appli_view_prm.use_touchscreen)
{
NodeDialog *nv = new NodeDialog(model, false, false, true);
//GtkKeyboard *kb = GtkKeyboard::get_instance();
nv->vkb_displayed = true;
DialogManager::get_instance()->setup(&(nv->wnd));
nv->wnd.signal_focus_in_event().connect(sigc::mem_fun(*nv, &NodeDialog::on_focus_in));
nv->wnd.signal_focus_out_event().connect(sigc::mem_fun(*nv, &NodeDialog::on_focus_out));
nv->infos("running wnd..");
nv->result_ok = false;
Gtk::Main::run(nv->wnd);
nv->infos("gtk return.");
//int res = 0;
DialogManager::get_instance()->dispose();
//GtkKeyboard::get_instance()->close();
nv->wnd.hide();
//if(res == Gtk::RESPONSE_ACCEPT)
if(nv->result_ok)
{
model.copy_from(nv->backup);
delete nv;
return 0;
}
delete nv;
return 1;
}
else
{
NodeDialog *nv = new NodeDialog(model, true, true);
int res = nv->dlg.run();
nv->dlg.hide();
if(res == Gtk::RESPONSE_ACCEPT)
{
model.copy_from(nv->backup);
delete nv;
return 0;
}
delete nv;
return 1;
}
# endif
}
/*******************************************************************
* CHOICE VIEW IMPLEMENTATION *
*******************************************************************/
VueChoix::VueChoix(Attribute *model, Node parent,
NodeViewConfiguration config) {
tp = "choice";
lock = false;
this->model = model;
this->config = config;
model_parent = parent;
current_view = nullptr;
//parent.infos("parent.");
if (model->schema->enumerations.size() == 0) {
avertissement("no enumerations ?");
}
//infos("Schema = '%s'.", model->schema.enumerations[0].schema->name.get_id().c_str());
nb_choices = model->schema->enumerations.size();
radios = (Gtk::RadioButton **) malloc(
nb_choices * sizeof(Gtk::RadioButton *));
for (uint32_t j = 0; j < nb_choices; j++)
{
if (j == 0)
{
radios[j] = new Gtk::RadioButton();
group = radios[j]->get_group();
}
else
radios[j] = new Gtk::RadioButton(group);
//NodeSchema *sub_schema = model->schema.enumerations[j].schema;
infos(model->schema->name.get_id());
//infos("j = %d.", j);
radios[j]->set_label(model->schema->enumerations[j].name.get_localized());
//if (sub_schema != nullptr)
{
//radios[j]->set_label(sub_schema->get_localized());
vbox.pack_start(*radios[j], Gtk::PACK_SHRINK);
radios[j]->signal_toggled().connect(
sigc::bind(sigc::mem_fun(*this, &VueChoix::on_radio_activate), j));
//radios[j]->signal_toggled().connect(
// sigc::mem_fun(*this, &ChoiceView::on_radio_activate));
}
radios[j]->signal_focus_in_event().connect(
sigc::mem_fun(*this, &AttributeView::on_focus_in));
}
frame.add(vbox);
update_langue();
update_sub_view();
ChangeEvent ce;
on_event(ce);
}
VueChoix::~VueChoix() {
//infos("~ChoiceView(), model = %x...", (uint32_t) model);
lock = true;
if (this->current_view != nullptr) {
vbox.remove(*(current_view->get_widget()));
delete current_view;
current_view = nullptr;
}
for (uint32_t j = 0; j < nb_choices; j++) {
vbox.remove(*(radios[j]));
delete radios[j];
}
free(radios);
//infos("~ChoiceView() done.");
}
void VueChoix::on_radio_activate(unsigned int num)
{
//uint32_t j;
//infos("on radio activate.");
if (!lock) {
//lock = true;
if(radios[num]->get_active())
{
model->set_value(model->schema->enumerations[num].value);
}
/* get active radio */
/*for (j = 0; j < nb_choices; j++)
{
//NodeSchema *sub_schema = model->schema.enumerations[j].schema;
if (radios[j]->get_active())
{
model->set_value(model->schema->enumerations[j].value);
break;
}
}
if (j == nb_choices)
erreur("choice view: none selected.");*/
update_sub_view();
//lock = false;
}
}
void VueChoix::update_langue() {
bool old_lock = lock;
lock = true;
for (uint32_t j = 0; j < nb_choices; j++)
{
//NodeSchema *sub_schema = model->schema.enumerations[j].schema;
//if (sub_schema != nullptr)
//radios[j]->set_label(sub_schema->get_localized());
//else
radios[j]->set_label(model->schema->enumerations[j].name.get_localized());
}
frame.set_label(NodeView::mk_label(model->schema->name));
if (current_view != nullptr)
current_view->update_langue();
lock = old_lock;
}
unsigned int VueChoix::get_nb_widgets() {
return 1;
}
Gtk::Widget *VueChoix::get_widget(int index) {
return &frame;
}
Gtk::Widget *VueChoix::get_gtk_widget()
{
return &frame;
}
void VueChoix::set_sensitive(bool b) {
for (uint32_t j = 0; j < nb_choices; j++)
radios[j]->set_sensitive(b);
if (current_view != nullptr)
current_view->set_sensitive(b);
}
void VueChoix::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
unsigned int val = model->get_int();
if (val > nb_choices)
erreur("Invalid value: %d (n choices = %d).", val, nb_choices);
else
{
radios[val]->set_active(true);
for(auto i = 0u; i < nb_choices; i++)
if(i != val)
radios[i]->set_active(false);
}
update_sub_view();
lock = false;
}
}
bool VueChoix::is_valid() {
if (current_view == nullptr)
return true;
return current_view->is_valid();
}
void VueChoix::update_sub_view()
{
//infos("update_sub_view...");
if (current_view != nullptr)
{
vbox.remove(*(current_view->get_widget()));
delete current_view;
current_view = nullptr;
}
int model_val = model->get_int();
int nb_enums = model->schema->enumerations.size();
if (model_val >= nb_enums)
{
erreur("Model value = %d > number of enums = %d.", model_val, nb_enums);
return;
}
NodeSchema *specific_schema = model->schema->enumerations[model_val].schema;
if(specific_schema != nullptr)
{
std::string sname = specific_schema->name.get_id();
if (!model_parent.has_child(sname))
{
erreur("No child of type %s.", sname.c_str());
return;
}
Node sub = model_parent.get_child(sname);
if(sub.is_nullptr())
{
erreur("no such child: %s", sname.c_str());
}
else
{
current_view = new NodeView(mainWindow, sub, config);
current_view->CProvider < KeyPosChangeEvent > ::add_listener(this);
vbox.pack_start(*current_view->get_widget(), Gtk::PACK_SHRINK);
}
}
vbox.show_all_children(true);
}
/*******************************************************************
* LED VIEW IMPLEMENTATION *
*******************************************************************/
VueLed::~VueLed()
{
}
VueLed::VueLed(Attribute *model, bool editable, bool error)
{
lock = false;
this->model = model;
this->editable = editable;
lab.set_use_markup(true);
std::string s = NodeView::mk_label(model->schema->name);
update_langue();
led.set_mutable(!model->schema->is_read_only && editable);
led.set_red(model->schema->is_error || error);
led.light(model->get_boolean());
led.add_listener(this, &VueLed::on_signal_toggled);
led.show();
}
void VueLed::update_langue()
{
lab.set_markup("<b>" + NodeView::mk_label_colon(model->schema->name) + "</b>");
}
unsigned int VueLed::get_nb_widgets()
{
return 2;
}
Gtk::Widget *VueLed::get_widget(int index)
{
if(index == 0)
return &lab;
else
return &led;
}
Gtk::Widget *VueLed::get_gtk_widget()
{
return &led;
}
void VueLed::set_readonly(bool b)
{
led.set_mutable(!b);
}
void VueLed::set_sensitive(bool b) {
led.set_mutable(b && !model->schema->is_read_only);
lab.set_sensitive(b);
led.set_sensitive(b);
}
void VueLed::on_signal_toggled(const LedEvent &le) {
if (!lock) {
lock = true;
model->set_value(led.is_on());
lock = false;
}
}
void VueLed::on_event(const ChangeEvent &ce) {
if (!lock) {
lock = true;
led.light(model->get_boolean());
lock = false;
}
}
/*******************************************************************
*******************************************************************
* GENERIC VIEW *
*******************************************************************
*******************************************************************/
VueGenerique::VueGenerique()
{
is_sensitive = true;
}
void VueGenerique::set_sensitive(bool sensitive)
{
is_sensitive = sensitive;
for(auto &e: enfants)
{
if(e != nullptr)
e->set_sensitive(sensitive);
}
get_gtk_widget()->set_sensitive(sensitive);
}
VueGenerique::~VueGenerique()
{
for(auto e: enfants)
{
if(e != nullptr)
delete e;
}
enfants.clear();
}
void VueGenerique::maj_contenu_dynamique()
{
infos(" ++++ GenericView::maj_contenu_dynamique ++++");
for(auto &e: enfants)
{
if(e != nullptr)
e->maj_contenu_dynamique();
}
}
VueGenerique::WidgetType VueGenerique::desc_vers_type(const string &s)
{
infos("%s...", s.c_str());
for(unsigned int i = 0; i <= WIDGET_MAX; i++)
{
if(wtypes[i] == s)
{
infos("trouve (%d)", i);
return (WidgetType) i;
}
}
infos("Type de widget non reconnu: '%s'", s.c_str());
return WIDGET_NULL;
}
std::string VueGenerique::type_vers_desc(VueGenerique::WidgetType type)
{
unsigned int id = (unsigned int) type;
if(id > WIDGET_MAX)
{
erreur("invalid type conversion (%d).", id);
return "nullptr-widget";
}
return wtypes[id];
}
struct FabriqueWidgetElmt
{
FabriqueWidget *fab;
std::string id;
};
static std::vector<FabriqueWidgetElmt> fabriques;
int VueGenerique::enregistre_widget(std::string id, FabriqueWidget *fabrique)
{
FabriqueWidgetElmt fwe;
fwe.id = id;
fwe.fab = fabrique;
fabriques.push_back(fwe);
return 0;
}
class SepV: public VueGenerique
{
public:
SepV()
{
}
Gtk::VSeparator sep;
Gtk::Widget *get_gtk_widget(){return &sep;}
};
class SepH: public VueGenerique
{
public:
SepH()
{
}
Gtk::HSeparator sep;
Gtk::Widget *get_gtk_widget(){return &sep;}
};
VueGenerique *VueGenerique::fabrique(Node modele_donnees,
Node modele_vue,
Controleur *controler)
{
VueGenerique *res = nullptr;
if(modele_vue.is_nullptr())
{
erreur("Modele de vue vide.");
return nullptr;
}
auto id_widget = modele_vue.schema()->name.get_id();
infos("Fabique [%s]...", id_widget.c_str());
WidgetType type = desc_vers_type(id_widget);
switch(type)
{
case WIDGET_NULL:
{
bool trouve = false;
for(auto &fab: fabriques)
{
if(fab.id == id_widget)
{
infos("Appelle fabrique speciale [%s]...", id_widget.c_str());
res = fab.fab->fabrique(modele_donnees, modele_vue, controler);
trouve = true;
break;
}
}
if(!trouve)
erreur("Widget invalide : %s.", id_widget.c_str());
break;
}
case WIDGET_AUTO:
{
trace_verbeuse("Fabrique vue automatique");
XPath chemin = XPath(modele_vue.get_attribute_as_string("modele"));
if(chemin.length() == 0)
{
erreur("widget auto: l'attribut 'modele' doit etre specifie.");
return nullptr;
}
Node mod = modele_donnees.get_child(chemin);
if(mod.is_nullptr())
{
erreur("Modele non trouve.", chemin.c_str());
return nullptr;
}
res = new NodeView(mod);
break;
}
case WIDGET_TABLE:
{
trace_verbeuse("Fabrique vue table");
res = new VueTable(modele_donnees, modele_vue, controler);
break;
}
case WIDGET_VUE_SPECIALE:
{
trace_verbeuse("Fabrique vue speciale");
res = new CustomWidget(modele_donnees, modele_vue, controler);
break;
}
case WIDGET_TRIG_LAYOUT:
{
trace_verbeuse("Fabrique trig layout");
res = new TrigLayout(modele_donnees, modele_vue);
break;
}
case WIDGET_LIST_LAYOUT:
{
trace_verbeuse("Fabrique list layout");
res = new ListLayout(modele_donnees, modele_vue, controler);
break;
}
case WIDGET_FIELD_LIST:
{
trace_verbeuse("Fabrique field list");
res = new VueListeChamps(modele_donnees, modele_vue, controler);
break;
}
case WIDGET_VBOX:
res = new VueLineaire(1, modele_donnees, modele_vue, controler);
break;
case WIDGET_HBOX:
res = new VueLineaire(0, modele_donnees, modele_vue, controler);
break;
case WIDGET_NOTEBOOK:
res = new NoteBookLayout(modele_donnees, modele_vue, controler);
break;
case WIDGET_BUTTON_BOX:
res = new HButtonBox(modele_donnees, modele_vue, controler);
break;
case WIDGET_SEP_V:
res = new SepV();
break;
case WIDGET_SEP_H:
res = new SepH();
break;
case WIDGET_GRID_LAYOUT:
res = new SubPlot(modele_donnees, modele_vue, controler);
break;
case WIDGET_CADRE:
{
res = new VueCadre(modele_donnees, modele_vue, controler);
break;
}
case WIDGET_FIELD:
case WIDGET_FIXED_STRING:
case WIDGET_BUTTON:
case WIDGET_BORDER_LAYOUT:
case WIDGET_FIXED_LAYOUT:
case WIDGET_PANNEAU:
case WIDGET_IMAGE:
case WIDGET_LABEL:
default:
{
auto s = type_vers_desc(type);
erreur("Type de widget non gere (%d / %s)", (int) type, s.c_str());
}
}
if(res != nullptr)
{
res->modele_vue = modele_vue;
res->modele_donnees = modele_donnees;
}
return res;
}
SubPlot::SubPlot(Node &data_model, Node &view_model, Controleur *controler)
{
unsigned int n = view_model.get_children_count();
for(auto i = 0u; i < n; i++)
{
Node ch = view_model.get_child_at(i);
auto v = VueGenerique::fabrique(data_model, ch, controler);
enfants.push_back(v);
auto x = ch.get_attribute_as_int("x"),
y = ch.get_attribute_as_int("y"),
ncols = ch.get_attribute_as_int("ncols"),
nrows = ch.get_attribute_as_int("nrows");
grille.attach(*(v->get_gtk_widget()), x, y, ncols, nrows);
grille.set_column_homogeneous(true);
grille.set_row_homogeneous(true);
grille.set_row_spacing(5);
grille.set_column_spacing(5);
//vs.push_back(v);
//auto orient = ch.get_attribute_as_string("orientation");
//if(orient == "left")
// hpane.add1(*(v->get_gtk_widget()));
//else if(orient == "right")
// hpane.add2(*(v->get_gtk_widget()));
//else if(orient == "bottom")
// vbox.pack_start(*(v->get_gtk_widget()), Gtk::PACK_SHRINK);
//else
// erreur("Orientation invalide dans un triglayout ('%s')", orient.c_str());
}
}
Gtk::Widget *SubPlot::get_gtk_widget()
{
return &grille;
}
/*******************************************************************
*******************************************************************
* TRIG LAYOUT *
*******************************************************************
*******************************************************************/
TrigLayout::TrigLayout(Node &data_model, Node &view_model_)
{
this->modele_donnees = data_model;
this->modele_vue = view_model_;
//GenericView *v1 = nullptr, *v2 = nullptr, *v3 = nullptr;
string s = this->modele_vue.to_xml(0,true);
infos("trig layout, modele de vue = \n%s", s.c_str());
std::vector<VueGenerique *> vs;
vbox.pack_start(hpane, Gtk::PACK_EXPAND_WIDGET);
vbox.pack_start(vsep, Gtk::PACK_SHRINK);
unsigned int n = modele_vue.get_children_count();
for(auto i = 0u; i < n; i++)
{
Node ch = modele_vue.get_child_at(i);
auto v = VueGenerique::fabrique(data_model, ch);
enfants.push_back(v);
vs.push_back(v);
auto orient = ch.get_attribute_as_string("orientation");
if(orient == "left")
hpane.add1(*(v->get_gtk_widget()));
else if(orient == "right")
hpane.add2(*(v->get_gtk_widget()));
else if(orient == "bottom")
vbox.pack_start(*(v->get_gtk_widget()), Gtk::PACK_SHRINK);
else
erreur("Orientation invalide dans un triglayout ('%s')", orient.c_str());
}
}
Gtk::Widget *TrigLayout::get_gtk_widget()
{
return &vbox;
}
/*void set_sensitive(bool sensitive)
{
}*/
VueCadre::VueCadre(Node &data_model, Node &view_model, Controleur *controler)
{
if(view_model.get_children_count() == 0)
{
avertissement("Cadre sans enfant.");
return;
}
cadre.set_border_width(5);
cadre.set_label(view_model.get_localized_name());
VueGenerique *gv = VueGenerique::fabrique(data_model, view_model.get_child_at(0), controleur);
if(gv != nullptr)
{
enfants.push_back(gv);
cadre.add(*(gv->get_gtk_widget()));
}
}
Gtk::Widget *VueCadre::get_gtk_widget()
{
return &cadre;
}
VueCadre::~VueCadre()
{
}
/*******************************************************************
*******************************************************************
* BOX LAYOUT *
*******************************************************************
*******************************************************************/
VueLineaire::VueLineaire(int vertical,
Node &modele_donnees,
Node &modele_vue,
Controleur *controleur)
{
this->vertical = vertical;
if(vertical)
box = &vbox;
else
box = &hbox;
unsigned int n = modele_vue.get_children_count();
enfants.resize(n);
for(unsigned int i = 0u; i < n; i++)
enfants[i] = nullptr;
for(unsigned int i = 0u; i < n; i++)
{
auto child = modele_vue.get_child_at(i);
VueGenerique *gv = VueGenerique::fabrique(modele_donnees, child, controleur);
if(gv == nullptr)
{
auto s = child.to_xml();
erreur("Construction boite : echec lors de la construction d'un enfant:\n%s", s.c_str());
continue;
}
assert(!gv->modele_vue.is_nullptr());
unsigned int y;
if(vertical)
y = child.get_attribute_as_int("y");
else
y = child.get_attribute_as_int("x");
if(y >= n)
{
erreur("y > nombre d'elements dans la boite (y = %d, n = %d).", y, n);
return;
}
enfants[y] = gv;
}
// Classement suivant y
for(unsigned int i = 0u; i < n; i++)
{
//auto child = view_model.get_child_at(i);
VueGenerique *gv = enfants[i];//GenericView::fabrique(data_model, child, controler);
//elems.push_back(gv);
if(gv == nullptr)
{
avertissement("Vue boite : element de position %d non specifie.", i);
continue;
}
std::string pack = gv->modele_vue.get_attribute_as_string("pack");
bool pos_fin = gv->modele_vue.get_attribute_as_boolean("pos-end");
trace_verbeuse("disposition h/v : elem = %d, pack = %s, pos fin = %d",
i, pack.c_str(), pos_fin);
Gtk::PackOptions po = pack == "shrink" ? Gtk::PACK_SHRINK : Gtk::PACK_EXPAND_WIDGET;
if(pos_fin)
box->pack_end(*(gv->get_gtk_widget()), po);
else
box->pack_start(*(gv->get_gtk_widget()), po);
gv->get_gtk_widget()->show();
}
box->show_all_children(true);
}
VueLineaire::~VueLineaire()
{
for(VueGenerique *gv: enfants)
{
if(gv == nullptr)
continue;
//trace_verbeuse("remove de box...");
box->remove(*(gv->get_gtk_widget()));
//trace_verbeuse("supression widget...");
delete gv;
}
enfants.clear();
//trace_verbeuse("fin destructeur");
}
Gtk::Widget *VueLineaire::get_gtk_widget()
{
return box;
}
/*******************************************************************
*******************************************************************
* NOTEBOOK LAYOUT *
*******************************************************************
*******************************************************************/
NoteBookLayout::NoteBookLayout(Node &data_model, Node &view_model, Controleur *controler)
{
unsigned int n = view_model.get_children_count();
notebook.set_scrollable(true);
notebook.popup_enable();
for(unsigned int i = 0; i < n; i++)
{
Node child = view_model.get_child_at(i);
VueGenerique *gv = VueGenerique::fabrique(data_model, child, controler);
enfants.push_back(gv);
auto nom = child.get_localized_name();
// TODO: in elems to be able to delete
Gtk::HBox *ybox = new Gtk::HBox();
Gtk::Label *lab = new Gtk::Label();
lab->set_markup("<b> " + nom + "</b>");
ybox->pack_start(*lab);
notebook.append_page(*(gv->get_gtk_widget()), *ybox);
ybox->show_all_children();
}
notebook.show_all_children(true);
}
NoteBookLayout::~NoteBookLayout()
{
int n = notebook.get_n_pages();
for (int i = 0; i < n; i++)
notebook.remove_page(0);
for(VueGenerique *gv: enfants)
{
//notebook.remove(*(gv->get_gtk_widget()));
delete gv;
}
enfants.clear();
}
Gtk::Widget *NoteBookLayout::get_gtk_widget()
{
return ¬ebook;
}
/*******************************************************************
*******************************************************************
* HBBOX *
*******************************************************************
*******************************************************************/
HButtonBox::HButtonBox(Node &data_model, Node &view_model_, Controleur *controler)
{
this->data_model = data_model;
this->controler = controler;
this->view_model = view_model_;//.get_child("button-box");
unsigned int n = view_model.get_children_count("bouton");
actions.resize(n);
for(unsigned int i = 0; i < n; i++)
{
Node bouton = view_model.get_child_at("bouton", i);
actions[i].name = bouton.name();
actions[i].button = new Gtk::Button();
std::string s = bouton.get_localized_name();
actions[i].button->set_label(s);
hbox.pack_start(*(actions[i].button), Gtk::PACK_SHRINK);
actions[i].button->set_border_width(4);
actions[i].button->signal_clicked().connect(
sigc::bind<std::string> (
sigc::mem_fun(*this, &HButtonBox::on_button), actions[i].name));
}
hbox.set_layout(Gtk::BUTTONBOX_END);
}
Gtk::Widget *HButtonBox::get_gtk_widget()
{
return &hbox;
}
void HButtonBox::on_button(std::string action)
{
trace_verbeuse("Action requise: [%s]", action.c_str());
if(controler == nullptr)
{
avertissement("Pas de controleur.");
}
else
controler->gere_action(action, data_model);
}
/*******************************************************************
*******************************************************************
* CUSTOM WIDGET *
*******************************************************************
*******************************************************************/
CustomWidget::CustomWidget(Node &modele_donnees,
Node &modele_vue,
Controleur *controleur)
{
this->controler = controleur;
this->id = modele_vue.get_attribute_as_string("name");
widget = nullptr;
}
void CustomWidget::maj_contenu_dynamique()
{
infos(" ++++ CustomWidget::maj_contenu_dynamique ++++");
if(widget != nullptr)
{
evt_box.remove();
delete widget;
widget = nullptr;
}
controler->genere_contenu_dynamique(id, data_model, &widget);
if(widget == nullptr)
{
auto l = new Gtk::Label();
widget = l;
char bf[500];
sprintf(bf, "Widget à faire : %s", id.c_str());
l->set_label(bf);
}
evt_box.add(*widget);
}
Gtk::Widget *CustomWidget::get_gtk_widget()
{
maj_contenu_dynamique();
return &evt_box;
/*Gtk::Widget *res = nullptr;
controler->genere_contenu_dynamique(id, data_model, &res);
if(res == nullptr)
{
auto l = new Gtk::Label();
char bf[500];
sprintf(bf, "Widget à faire : %s", id.c_str());
l->set_label(bf);
return l;
}
return res;*/
}
/*******************************************************************
*******************************************************************
* LIST LAYOUT *
*******************************************************************
*******************************************************************/
void ListLayout::rebuild_view()
{
for(Elem &e: elems)
{
table.remove(*(e.frame));
delete e.frame;
//e.frame->remove();
delete e.label;
if(e.widget != nullptr)
delete e.widget;
}
//enfants.clear();
elems.clear();
std::string tp = modele_vue.get_attribute_as_string("child-type");
XPath ptp(tp);
XPath prefix = ptp.remove_last();
std::string postfix = ptp.get_last();
Node rnode = modele_donnees;
if(prefix.length() > 0)
rnode = rnode.get_child(prefix);
unsigned int i = 0, n = rnode.get_children_count(postfix);
/*trace_major("tp = %s, prefix = %s, n = %d.", tp.c_str(), prefix.c_str(), n);
auto ss = rnode.to_xml();
trace_verbeuse("rnode = %s.\n", ss.c_str());
ss = data_model.to_xml();
trace_verbeuse("data_model = %s.\n", ss.c_str());*/
unsigned int ncols = modele_vue.get_attribute_as_int("ncols");
uint16_t x = 0, y = 0;
uint16_t ny = (n + ncols - 1) / ncols;
table.resize(ncols, ny);
elems.resize(n);
for(i = 0; i < n; i++)
{
elems[i].id = i;
elems[i].label = new SensitiveLabel(utils::str::int2str(i));
elems[i].label->add_listener(this, &ListLayout::on_click);
elems[i].widget = nullptr;
elems[i].model = rnode.get_child_at(postfix, i);
controler->genere_contenu_dynamique(modele_vue.get_attribute_as_string("child-type"),
elems[i].model, &elems[i].widget);
//if(elems[i].widget != nullptr)
//enfants.push_back(elems[i].widget);
elems[i].vbox = new Gtk::VBox();
elems[i].frame = new Gtk::Frame();
elems[i].align = new Gtk::Alignment(0.5,0.5,0,0);
elems[i].align2 = new Gtk::Alignment(0.5,0.5,0,0);
elems[i].align2->set_padding(3,3,3,3);
//elems[i].align2->set_padding(10,10,10,10);
elems[i].evt_box = new Gtk::EventBox();
elems[i].evt_box->add(*(elems[i].align));
elems[i].evt_box->set_events(Gdk::BUTTON_PRESS_MASK /*| Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_RELEASE_MASK*/);
elems[i].evt_box->signal_button_press_event().connect(sigc::bind<Elem *>(sigc::mem_fun(this,
&ListLayout::on_button_press_event), &(elems[i])));;
table.attach(*(elems[i].evt_box), x, x+1, y, y+1);//, Gtk::SHRINK, Gtk::SHRINK);
elems[i].align->add(*(elems[i].frame));
elems[i].align2->add(*(elems[i].vbox));
elems[i].vbox->pack_start(*(elems[i].label), Gtk::PACK_SHRINK);
if(elems[i].widget != nullptr)
elems[i].vbox->pack_start(*(elems[i].widget), Gtk::PACK_SHRINK);
//elems[i].label->set_border_width(15); // test, to remove
elems[i].align2->set_border_width(5);//15);
elems[i].frame->add(*(elems[i].align2));
if(x == ncols - 1)
y++;
x = (x + 1) % ncols;
}
table.show_all_children(true);
if(current_selection >= (int) elems.size())
current_selection = -1;
update_view();
}
bool ListLayout::on_button_press_event(GdkEventButton *evt, Elem *elt)
{
trace_verbeuse("Bpress event sur element list layout (type = %d).", (int) evt->type);
current_selection = elt->id;
update_view();
if((evt->type == GDK_2BUTTON_PRESS) && (evt->button == 1))
{
trace_verbeuse("Double click.");
for(Action &a: actions)
{
if(a.is_default)
{
controler->gere_action(a.name,
get_selection());
return 0;
}
}
}
else if((evt->type == GDK_BUTTON_PRESS) && (evt->button == 1))
{
trace_verbeuse("simple clock");
}
return true;
}
void ListLayout::on_click(const LabelClick &click)
{
trace_verbeuse("click detected: %s, type = %s", click.path.c_str(), (click.type == LabelClick::VAL_CLICK) ? "val" : "sel");
int id = atoi(click.path.c_str());
current_selection = id;
update_view();
if(click.type == LabelClick::VAL_CLICK)
{
trace_verbeuse("Double click.");
for(Action &a: actions)
{
if(a.is_default)
{
controler->gere_action(a.name,
get_selection());
return;
}
}
}
}
/*#ifdef LINUX
# define BCOL_INACTIVE "#000080"
# define BCOL_ACTIVE "#FF00FF"
#else
# define BCOL_INACTIVE "#202020"
# define BCOL_ACTIVE "#400040"
#endif*/
# define BCOL_INACTIVE "#000080"
# define BCOL_ACTIVE "#FF00FF"
#if 0
# define BCOL_INACTIVE "#202020"
# define BCOL_ACTIVE "#400040"
#endif
#define OVERRIDE_COLORS
void ListLayout::update_view()
{
for(auto i = 0u; i < elems.size(); i++)
{
//elems[i].frame->set_border_width(0);
# ifdef OVERRIDE_COLORS
elems[i].frame->set_border_width(0);
elems[i].frame->set_shadow_type(Gtk::SHADOW_NONE);
elems[i].frame->override_color(Gdk::RGBA(BCOL_INACTIVE), Gtk::STATE_FLAG_NORMAL);
# endif
//elems[i].event_box->override_color(Gdk::RGBA(BCOL_INACTIVE),
// Gtk::STATE_FLAG_NORMAL);
Gtk::Widget *unused;
elems[i].label->label.set_markup(controler->genere_contenu_dynamique(
modele_vue.get_attribute_as_string("child-type"),
elems[i].model, &unused));
}
if(current_selection != -1)
{
/*assert(current_selection < (int) elems.size());
elems[current_selection].frame->set_border_width(5);*/
# ifdef OVERRIDE_COLORS
elems[current_selection].frame->set_border_width(5);
elems[current_selection].frame->set_shadow_type(Gtk::SHADOW_OUT);
elems[current_selection].frame->override_color(Gdk::RGBA(BCOL_ACTIVE), Gtk::STATE_FLAG_NORMAL);
# endif
Gtk::Widget *unused;
auto s = controler->genere_contenu_dynamique(this->modele_vue.get_attribute_as_string("child-type"),
elems[current_selection].model, &unused);
//s = "<big>"+s+"</big>";
//elems[current_selection].label->label.set_markup(s);
//elems[current_selection].event_box->modify_bg(Gtk::STATE_FLAG_NORMAL, Gdk::RGBA(BCOL_ACTIVE));
//elems[current_selection].event_box->override_color(Gdk::RGBA(BCOL_ACTIVE), Gtk::STATE_FLAG_NORMAL);
//
}
for(Action &a: actions)
{
if((current_selection == -1) && (a.need_sel))
a.button->set_sensitive(false);
else
a.button->set_sensitive(true);
}
}
void ListLayout::on_event(const ChangeEvent &ce)
{
auto s = ce.to_string();
switch(ce.type)
{
case ChangeEvent::CHILD_ADDED:
case ChangeEvent::CHILD_REMOVED:
//if(data_model_.get_child())
if(ce.path.length() <= 2) // Ne regarde que des changements qui le concerne directement
{
trace_verbeuse("Changement sur list layout: %s.", s.c_str());
rebuild_view();
}
break;
case ChangeEvent::GROUP_CHANGE:
//update_view();
break;
case ChangeEvent::ATTRIBUTE_CHANGED:
case ChangeEvent::COMMAND_EXECUTED:
break;
}
}
Node ListLayout::get_selection()
{
Node res;
if((current_selection == -1) || (current_selection >= (int) elems.size()))
return modele_donnees;
return elems[current_selection].model;
}
void ListLayout::on_button(std::string action)
{
trace_verbeuse("action detected: %s", action.c_str());
controler->gere_action(action, get_selection());
}
void ListLayout::maj_contenu_dynamique()
{
rebuild_view();
}
ListLayout::ListLayout(Node &data_model, Node &view_model_, Controleur *controler)
{
current_selection = -1;
this->controler = controler;
this->modele_donnees = data_model;
this->modele_vue = view_model_;
unsigned int n = modele_vue.get_children_count("bouton");
actions.resize(n);
for(unsigned int i = 0; i < n; i++)
{
Node bouton = modele_vue.get_child_at("bouton", i);
actions[i].need_sel = bouton.get_attribute_as_boolean("require-sel");
actions[i].is_default = bouton.get_attribute_as_boolean("default");
actions[i].name = bouton.name();
actions[i].button = new Gtk::Button();
std::string s = bouton.get_localized_name();
actions[i].button->set_label(s);
hbox.pack_start(*(actions[i].button), Gtk::PACK_SHRINK);
actions[i].button->set_border_width(4);
actions[i].button->signal_clicked().connect(
sigc::bind<std::string> (
sigc::mem_fun(*this, &ListLayout::on_button), actions[i].name));
}
hbox.set_layout(Gtk::BUTTONBOX_END);
vbox.pack_start(table, Gtk::PACK_EXPAND_WIDGET);
rebuild_view();
scroll.add(vbox);
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
scroll.set_min_content_width(500);
scroll.set_min_content_height(400);
/*vbox*/scroll.show_all_children(true);
vbox_ext.pack_start(scroll, Gtk::PACK_EXPAND_WIDGET);
vbox_ext.pack_start(vsep, Gtk::PACK_SHRINK);
vbox_ext.pack_start(hbox, Gtk::PACK_SHRINK);
data_model.add_listener(this);
}
ListLayout::~ListLayout()
{
modele_donnees.remove_listener(this);
}
Gtk::Widget *ListLayout::get_gtk_widget()
{
return &vbox_ext;
}
/*******************************************************************
*******************************************************************
* FIELD LIST VIEW *
*******************************************************************
*******************************************************************/
void VueListeChamps::set_sensitive(bool sensitive)
{
VueGenerique::set_sensitive(sensitive);
for(auto &f: champs)
{
if(f->av != nullptr)
{
f->av->set_sensitive(sensitive);
f->label.set_sensitive(sensitive);
f->label_unit.set_sensitive(sensitive);
}
}
}
VueListeChamps::VueListeChamps(Node &modele_donnees,
Node &modele_vue,
Controleur *controleur_)
{
this->modele_vue = modele_donnees;
this->modele_donnees = modele_vue;
this->controleur = controleur_;
unsigned int i, n = modele_vue.get_children_count("champs");
trace_verbeuse("Field list view: n rows = %d.", n);
table.resize(n, 3);
for(i = 0; i < n; i++)
{
Node modele_vue_champs = modele_vue.get_child_at("champs", i);
XPath chemin = XPath(modele_vue_champs.get_attribute_as_string("modele"));
std::string ctrl_id = modele_vue_champs.get_attribute_as_string("ctrl-id");
//bool editable = field.get_attribute_as_boolean("editable");
if(chemin.length() == 0)
{
erreur("%s: field-view: 'model' attribute not specified.");
continue;
}
Node att_owner = modele_donnees.get_child(chemin.remove_last());
string att_name = chemin.get_last();
if(att_owner.is_nullptr())
{
erreur("Field '%s': model not found.", chemin.c_str());
continue;
}
if(!att_owner.schema()->has_attribute(att_name))
{
auto s = att_owner.to_xml();
erreur("Field '%s': no such attribute in the model.\nModel = \n%s",
chemin.c_str(), s.c_str());
continue;
}
auto att_schema = att_owner.schema()->get_attribute(att_name);
ChampsCtx *fc = new ChampsCtx();
champs.push_back(fc);
fc->av = AttributeView::factory(modele_donnees, modele_vue_champs);
if(fc->av != nullptr)
fc->av->CProvider<KeyPosChangeEvent>::add_listener(this);
fc->label.set_use_markup(true);
Localized nom = att_schema->name;
if(modele_vue_champs.get_localized_name().size() > 0)
nom = modele_vue_champs.get_localized();
std::string s = NodeView::mk_label_colon(nom);
if(appli_view_prm.overwrite_system_label_color)
s = "<span foreground='" + appli_view_prm.att_label_color.to_html_string() + "'>" + s + "</span>";
s = "<b>" + s + "</b>";
fc->label.set_markup(s);
fc->align[0].set(Gtk::ALIGN_START, Gtk::ALIGN_CENTER, 0, 0);
fc->align[1].set(Gtk::ALIGN_START, Gtk::ALIGN_CENTER, 1, 0);
fc->align[2].set(Gtk::ALIGN_START, Gtk::ALIGN_CENTER, 1, 0);
fc->align[0].add(fc->label);
Gtk::Widget *widget = nullptr;
if(fc->av != nullptr)
widget = fc->av->get_gtk_widget();
if(widget != nullptr)
fc->align[1].add(*widget);
table.attach(fc->align[0], 0, 1, i, i + 1, Gtk::FILL, Gtk::FILL, 5, 5);
table.attach(fc->align[1], 1, 2, i, i + 1, Gtk::FILL, Gtk::FILL, 5, 5);
if(att_schema->has_unit())
{
fc->align[2].add(fc->label_unit);
fc->label_unit.set_label(att_schema->unit);
table.attach(fc->align[2], 2, 3, i, i + 1, Gtk::FILL, Gtk::FILL, 5, 5);
}
if(att_schema->has_description())
{
fc->label.set_has_tooltip();
fc->label.set_tooltip_markup(mk_html_tooltip(att_schema));
}
}
}
VueListeChamps::~VueListeChamps()
{
for(unsigned int i = 0; i < champs.size(); i++)
{
delete champs[i];
champs[i] = nullptr;
}
}
Gtk::Widget *VueListeChamps::get_gtk_widget()
{
return &table;
}
void VueListeChamps::on_event(const ChangeEvent &ce)
{
}
void VueListeChamps::update_langue()
{
}
}
}
| 135,810
|
C++
|
.cc
| 4,315
| 26.53905
| 152
| 0.601109
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,972
|
serial-ui.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/serial-ui.cc
|
#include "mmi/serial-ui.hpp"
#include "comm/serial.hpp"
namespace utils
{
namespace comm
{
SerialFrame::SerialFrame(std::vector<SerialInfo> &infos, const SerialConfig &sc)
: table(1,2)
{
config = sc;
m_refTreeModel = Gtk::ListStore::create(m_Columns);
combo.set_model(m_refTreeModel);
combo.pack_start(m_Columns.m_col_lgname, Gtk::PACK_SHRINK);
Gtk::TreeModel::Row row;
int is = 0;
for(unsigned int i = 0; i < infos.size(); i++)
{
row = *(m_refTreeModel->append());
row[m_Columns.m_col_name] = infos[i].name;
row[m_Columns.m_col_lgname] = infos[i].complete_name;
if(config.port.compare(infos[i].name) == 0)
is = i;
}
combo.set_active(is);
m_refTreeModel2 = Gtk::ListStore::create(m_Columns2);
combo2.set_model(m_refTreeModel2);
combo2.pack_start(m_Columns2.m_col_val, Gtk::PACK_SHRINK);
row = *(m_refTreeModel2->append());
row[m_Columns2.m_col_val] = 9600;
row = *(m_refTreeModel2->append());
row[m_Columns2.m_col_val] = 19200;
row = *(m_refTreeModel2->append());
row[m_Columns2.m_col_val] = 38400;
row = *(m_refTreeModel2->append());
row[m_Columns2.m_col_val] = 57600;
row = *(m_refTreeModel2->append());
row[m_Columns2.m_col_val] = 115200;
row = *(m_refTreeModel2->append());
row[m_Columns2.m_col_val] = 460800;
switch(config.baud_rate)
{
case 9600: combo2.set_active(0); break;
case 19200: combo2.set_active(1); break;
case 38400: combo2.set_active(2); break;
case 57600: combo2.set_active(3); break;
case 115200: combo2.set_active(4); break;
case 460800: combo2.set_active(5); break;
}
//combo.set_active(0);
//combo2.set_active(4);
table.attach(l_com, 0, 1, 0, 1);
table.attach(combo, 1, 2, 0, 1);
table.attach(l_deb, 0, 1, 1, 2);
table.attach(combo2, 1, 2, 1, 2);
add(table);
table.set_border_width(7);
update_view();
combo.signal_changed().connect( sigc::mem_fun(*this, &SerialFrame::on_combo_change));
combo2.signal_changed().connect( sigc::mem_fun(*this, &SerialFrame::on_combo2_change));
set_border_width(7);
}
void SerialFrame::on_combo_change()
{
std::string name = "";
Gtk::TreeModel::iterator iter = combo.get_active();
if(iter)
{
Gtk::TreeModel::Row row = *iter;
if(row)
{
Glib::ustring res = row[m_Columns.m_col_name];
name = res;
}
}
if(name.size() > 0)
{
config.port = name;
printf("Selected %s.\n", name.c_str());
fflush(stdout);
}
}
void SerialConfig::dump()
{
printf("Serial configuration: port = \"%s\", baud rate = %d.\n", port.c_str(), baud_rate);
fflush(stdout);
}
void SerialFrame::on_combo2_change()
{
int speed = 115200;
Gtk::TreeModel::iterator iter = combo2.get_active();
if(iter)
{
Gtk::TreeModel::Row row = *iter;
if(row)
{
speed = row[m_Columns2.m_col_val];
config.baud_rate = speed;
}
}
printf("Selected %d bauds.\n", speed);
fflush(stdout);
}
void SerialFrame::update_view()
{
set_label(langue.get_item("com config"));
l_com.set_label(langue.get_item("Liaison :"));
l_deb.set_label(langue.get_item("debit"));
}
}
}
| 3,110
|
C++
|
.cc
| 110
| 24.909091
| 92
| 0.654143
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,973
|
misc.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/misc.cc
|
#include "mmi/gtkutil.hpp"
namespace utils{ namespace mmi{
static std::string chemin_fichier_lock;
int verifie_dernier_demarrage()
{
chemin_fichier_lock = utils::get_current_user_path() + PATH_SEP + "lock.dat";
if(utils::files::file_exists(chemin_fichier_lock))
{
# if MODE_RELEASE
auto &sec = utils::langue.get_section("svg-log");
if(utils::mmi::dialogs::check_dialog(
sec.get_item("check-lock-1"),
sec.get_item("check-lock-2"),
sec.get_item("check-lock-3")))
{
auto s = utils::mmi::dialogs::enregistrer_fichier(sec.get_item("svg-log-titre"),
".txt", "Log file");
if(s.size() > 0)
{
if(utils::files::get_extension(s).size() == 0)
s += ".txt";
//std::string src = utils::get_current_user_path() + PATH_SEP + appdata.nom_appli + "-log.txt";
//std::string src = utils::get_current_user_path() + PATH_SEP + "-log.txt.old";
//trace_majeure("Copie [%s] <- [%s]...", s.c_str(), src.c_str());
//utils::files::copy_file(s, src);
}
}
# endif
return -1;
}
else
{
utils::files::save_txt_file(chemin_fichier_lock, "En cours d'execution.");
return 0;
}
}
int termine_appli()
{
utils::files::delete_file(chemin_fichier_lock);
return 0;
}
}}
| 1,293
|
C++
|
.cc
| 42
| 25.928571
| 103
| 0.600965
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,974
|
mmi-gen.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/mmi-gen.cc
|
#include "mmi/mmi-gen.hpp"
#include <stdio.h>
#ifdef WIN
#include <process.h>
#endif
#include <cairomm/context.h>
#include <gdkmm/pixbuf.h>
#include <gdkmm/general.h>
#include <gtkmm/drawingarea.h>
#include <gtkmm/imagemenuitem.h>
#include <gtkmm/uimanager.h>
using namespace std;
using namespace utils;
using namespace utils::model;
namespace utils { namespace mmi {
static MMIGen *instance = NULL;
Node configuration;
FileSchema *fs;
MMIGen *MMIGen::get_instance()
{
return instance;
}
MMIGenSection::MMIGenSection(Node modele)
{
this->modele = modele;
frame.set_border_width(5);
frame.add(vbox);
bbox.set_spacing(4);
bbox.set_border_width(4);
bbox.set_layout(Gtk::BUTTONBOX_END);
if(modele.is_nullptr())
{
erreur("MMIGenSection : sans modele ?");
}
else
{
trace_majeure("toxml...");
auto s = modele.to_xml(true, true);
trace_majeure("Creation vue noeud :\n%s\n", s.c_str());
}
vue = new NodeView(instance, modele);
vbox.pack_start(*(vue->get_widget()), Gtk::PACK_SHRINK);
vbox.pack_start(bbox, Gtk::PACK_SHRINK);
vbox.show_all_children(true);
frame.set_label(modele.schema()->get_localized());
}
MMIGen::Action *MMIGen::recherche_action(const std::string &id)
{
for(auto act: actions)
if(act->id == id)
return act;
erreur("Action non trouvee : %s.", id.c_str());
return nullptr;
}
void MMIGen::init()
{
}
MMIGen::MMIGen()
{
init();
}
void MMIGen::gere_bouton(std::string id)
{
auto act = recherche_action(id);
if(act == nullptr)
return;
ActionEvent ae;
act->dispatch(ae);
}
int MMIGen::setup(utils::CmdeLine &cmdline, utils::model::Node modele_mmi, FileSchema *root)
{
std::string s1 = modele_mmi.to_xml(true, true);
infos("Construction MMI GEN (modèle [%s])", s1.c_str());
this->sections = sections;
lock = 0;
this->modele_mmi = modele_mmi;
this->cmdline = cmdline;
instance = this;
set_title(modele_mmi.get_localized_name());
set_border_width(5);
set_default_size(modele_mmi.get_attribute_as_int("largeur-par-defaut"),
modele_mmi.get_attribute_as_int("hauteur-par-defaut"));
//configuration.add_listener(this);
barre_outils.set_icon_size(Gtk::ICON_SIZE_SMALL_TOOLBAR);
//barre_outils.set_icon_size(Gtk::ICON_SIZE_SMALL_TOOLBAR);
barre_outils.set_toolbar_style(Gtk::TOOLBAR_BOTH);
barre_outils.set_has_tooltip(false);
vbox_princ.pack_start(frame_menu, Gtk::PACK_SHRINK);
vbox_princ.pack_start(barre_outils, Gtk::PACK_SHRINK);
barre_outils.add(b_open);
barre_outils.add(b_save);
for(auto &ch: modele_mmi.children("mmi-gen-action"))
{
Action *a = new Action();
a->id = ch.get_attribute_as_string("name");
a->bouton.set_label(ch.get_localized_name());
auto icp = ch.get_attribute_as_string("icone");
if(icp.size() > 0)
{
auto s = utils::get_fixed_data_path() + "/img/" + icp;
if(!utils::files::file_exists(s))
{
erreur("Fichier icone non trouve : %s", s.c_str());
}
else
{
auto img = new Gtk::Image(s);
a->bouton.set_icon_widget(*img);
}
}
barre_outils.add(a->bouton);
a->bouton.signal_clicked().connect(sigc::bind(sigc::mem_fun(*this, &MMIGen::gere_bouton), a->id));
actions.push_back(a);
}
barre_outils.add(b_infos);
barre_outils.add(b_exit);
b_open.set_stock_id(Gtk::Stock::OPEN);
b_save.set_stock_id(Gtk::Stock::SAVE);
b_infos.set_stock_id(Gtk::Stock::ABOUT);
b_exit.set_stock_id(Gtk::Stock::QUIT);
//auto img = new Gtk::Image(utils::get_fixed_data_path() + "/img/zones.png");
//b_zones.set_icon_widget(*img);
b_open.signal_clicked().connect(sigc::mem_fun(*this, &MMIGen::on_b_open));
b_save.signal_clicked().connect(sigc::mem_fun(*this, &MMIGen::on_b_save));
b_exit.signal_clicked().connect(sigc::mem_fun(*this, &MMIGen::on_b_exit));
b_infos.signal_clicked().connect(sigc::mem_fun(*this, &MMIGen::on_b_infos));
add(vbox_princ);
vbox_princ.pack_start(hbox, Gtk::PACK_EXPAND_WIDGET);
ncolonnes = modele_mmi.get_attribute_as_int("ncolonnes");
for(auto i = 0u; i < ncolonnes; i++)
{
vboxes.push_back(new Gtk::VBox());
hbox.pack_start(*(vboxes[i]), Gtk::PACK_EXPAND_WIDGET);//Gtk::PACK_SHRINK);
}
schema_vue = new utils::model::NodeSchema();
schema_vue->name.set_value(Localized::LANG_ID, "modele");
for(auto &s: modele_mmi.children("mmi-gen-section"))
{
utils::model::SubSchema ss;
utils::model::NodeSchema *sschema;
auto nom_modele = s.get_attribute_as_string("modele");
if(nom_modele.size() > 0)
{
sschema = root->get_schema(nom_modele);
if(sschema == nullptr)
return -1;
ss.child_str = nom_modele;
}
else
{
sschema = new utils::model::NodeSchema(s, root);
ss.child_str = s.get_attribute_as_string("name");
}
ss.ptr = sschema;
ss.min = ss.max = 1;
ss.name.set_value(Localized::LANG_ID, ss.child_str);
schema_vue->add_sub_node(ss);
}
schema_vue->update_size_info();
//schema->serialize()
modele = utils::model::Node::create_ram_node(schema_vue);
std::string s = modele.to_xml(true, true);
infos("Création schema :\n%s\n", s.c_str());
s = schema_vue->to_string();
infos("Schema :\n%s\n", s.c_str());
for(auto s: modele_mmi.children("mmi-gen-section"))
{
unsigned int col = s.get_attribute_as_int("colonne");
if(col >= ncolonnes)
{
erreur("Numéro de colonne invalide (%d / %d)", col, ncolonnes);
continue;
}
MMIGenSection *mgs = new MMIGenSection(modele.get_child(s.get_attribute_as_string("name")));
sections.push_back(mgs);
vboxes[col]->pack_start(mgs->frame, Gtk::PACK_EXPAND_WIDGET);
}
//vboxes[ncolonnes-1].pack_start(frame_infos, Gtk::PACK_SHRINK);
vboxes[ncolonnes-1]->pack_end(progress, Gtk::PACK_SHRINK);
/*frame_infos.set_label(utils::str::latin_to_utf8("Informations"));
frame_infos.add(text_scroll);*/
text_scroll.add(text_view);
text_scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);
text_buffer = Gtk::TextBuffer::create();
text_buffer->create_tag("bold")->property_weight() = Pango::WEIGHT_BOLD;
text_view.set_editable(false);
text_view.set_buffer(text_buffer);
show_all_children(true);
maj_vue();
return 0;
}
MMIGenSection *MMIGen::lookup(std::string nom)
{
for(auto &e: this->sections)
if(e->modele.schema()->name.get_id() == nom)
return e;
erreur("MMIGen::%s: non trouvé (%s).", __func__, nom.c_str());
return nullptr;
}
MMIGen::MMIGen(CmdeLine &cmdline,
utils::model::Node modele_mmi,
FileSchema *root)
{
init();
setup(cmdline, modele_mmi, root);
}
void MMIGen::on_b_save()
{
/* std::string fichier = utils::mmi::dialogs::save_dialog(
langue.get_item("dlg-sauve-titre"),
"*.xml",
"Fichier XML");
if(fichier.size() > 0)
configuration.save(fichier, true);*/
}
void MMIGen::on_b_open()
{
/* std::string fichier = utils::mmi::dialogs::open_dialog(
langue.get_item("dlg-ouvre-titre"),
"*.xml",
"Fichier XML");
if(fichier.size() > 0)
configuration.load(fichier);*/
}
void MMIGen::on_b_infos()
{
infos("on_b_infos gen");
Gtk::AboutDialog ad;
ad.set_copyright("(C) 2017 TSD CONSEIL");
//Glib::RefPtr<Gdk::Pixbuf> pix = Gdk::Pixbuf::create_from_file(utils::get_img_path() + "/todo.png");
//ad.set_logo(pix);
ad.set_name(langue.get_item("titre-principal") + "\n");
ad.set_program_name(langue.get_item("titre-principal"));
ad.set_version(modele_mmi.get_attribute_as_string("version"));
ad.set_position(Gtk::WIN_POS_CENTER);
ad.run();
}
void MMIGen::on_b_exit()
{
trace_majeure("Fin normale de l'application.");
//utils::files::delete_file(lockfile);
hide();
gere_fin_application();
exit(0);
}
void MMIGen::set_histo(std::string text)
{
text = utils::str::latin_to_utf8(text);
historique = text;
text_buffer->set_text(historique);
}
void MMIGen::put_histo(std::string text)
{
text = utils::str::latin_to_utf8(text);
historique += text;
text_buffer->set_text(historique);
Gtk::TextBuffer::iterator it = text_buffer->end();
text_view.scroll_to(it);
}
void MMIGen::put_histo_temp(std::string text)
{
text = utils::str::latin_to_utf8(text);
text_buffer->set_text(historique + text);
}
void MMIGen::maj_langue()
{
b_open.set_label(langue.get_item("open"));
b_open.set_tooltip_markup(langue.get_item("open-tt"));
b_save.set_label(langue.get_item("save"));
b_save.set_tooltip_markup(langue.get_item("save-tt"));
b_exit.set_label(langue.get_item("quitter"));
b_exit.set_tooltip_markup(langue.get_item("quitter-tt"));
b_infos.set_label(langue.get_item("apropos"));
b_infos.set_tooltip_markup(langue.get_item("apropos-tt"));
}
void MMIGen::maj_vue()
{
bool connected = false;
bool ope_ok = connected;
b_save.set_sensitive(ope_ok);
b_open.set_sensitive(ope_ok);
maj_langue();
}
}}
| 8,917
|
C++
|
.cc
| 284
| 27.848592
| 104
| 0.669897
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,975
|
theme.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/theme.cc
|
#include "cutil.hpp"
#include "mmi/theme.hpp"
#include "mmi/gtkutil.hpp"
#ifndef LINUX
#ifndef MSYS1
# define MSYS2
#endif
#endif
//#define DISABLE_THEME 1
// Ajouter settings.ini dans le dossier
// "C:\msys32\mingw32\share\gtk-3.0"
// Contenant :
// [Settings]
// gtk-theme-name=win32
namespace utils{ namespace mmi{
std::vector<Theme> themes;
static Theme *theme_en_cours = nullptr;
class ThemeCB
{
public:
#if 0
void on_parsing_error(const Glib::RefPtr<const Gtk::CssSection>& section, const Glib::Error& error)
{
infos("on_parsing_error(): %s",error.what().c_str());
/*
if (section)
{
const auto file = section->get_file();
if (file)
{
std::cerr << " URI = " << file->get_uri() << std::endl;
}
std::cerr << " start_line = " << section->get_start_line()+1
<< ", end_line = " << section->get_end_line()+1 << std::endl;
std::cerr << " start_position = " << section->get_start_position()
<< ", end_position = " << section->get_end_position() << std::endl;
}
*/
}
#endif
};
int charge_themes()
{
# ifndef MSYS2
return -1;
# else
// Chargement des CSS provider...
std::string chms[2] =
{
"/arc-theme-master/common/gtk-3.0/3.20/gtk-dark.css",
"/arc-theme-master/common/gtk-3.0/3.20/gtk-solid-dark.css"
};
std::string noms[2] = {"dark", "solid-dark"};
/*Gtk::Window *wnd_tmp = new Gtk::Window();
wnd_tmp->show();
wnd_tmp->present();*/
for(auto i = 0u; i < 2; i++)
{
Theme theme;
theme.id = noms[i];//th.get_attribute_as_string("name");
theme.chemin = "...";//th.get_attribute_as_string("chemin");
theme.provider = Gtk::CssProvider::create();
theme.desc = "...";//th.get_localized_name();
//ThemeCB cb;
//theme.provider->signal_parsing_error().connect(sigc::mem_fun(cb, &ThemeCB::on_parsing_error));
std::string fn = //utils::get_fixed_data_path() + "/themes/" + theme.chemin;
utils::get_fixed_data_path() + chms[i];
// darker : aucun effet
// dark : pb boutons et barre de titre
// + "/themes/arc-theme-master/common/gtk-3.0/3.20/gtk-dark.css";
//+ "/elem/elementaryDark/gtk-3.0/gtk.css";
if(!utils::files::file_exists(fn))
{
erreur("Fichier css non trouv� (%s).", fn.c_str());
return -1;
}
try
{
infos("Chargement du theme [%s]...", fn.c_str());
theme.provider->load_from_path(fn);
infos("Ok.");
//auto refStyleContext = wnd_tmp->get_style_context();
//refStyleContext->add_provider_for_screen(wnd_tmp->get_screen(), theme.provider,
// GTK_STYLE_PROVIDER_PRIORITY_USER+10);
}
catch(const Gtk::CssProviderError& ex)
{
erreur("CssProviderError, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
catch(const Glib::Error& ex)
{
erreur("Error, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
themes.push_back(theme);
}
# if 0
for(auto &th: mgc::app.modele_statique.children("theme"))
{
Theme theme;
theme.id = th.get_attribute_as_string("name");
theme.chemin = th.get_attribute_as_string("chemin");
theme.provider = Gtk::CssProvider::create();
theme.desc = th.get_localized_name();
ThemeCB cb;
theme.provider->signal_parsing_error().connect(sigc::mem_fun(cb, &ThemeCB::on_parsing_error));
std::string fn = utils::get_fixed_data_path() + "/themes/" + theme.chemin;
if(!utils::files::file_exists(fn))
{
erreur("Fichier css non trouv� (%s).", fn.c_str());
return -1;
}
try
{
infos("Chargement du theme [%s]...", fn.c_str());
theme.provider->load_from_path(fn);
infos("Ok.");
}
catch(const Gtk::CssProviderError& ex)
{
erreur("CssProviderError, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
catch(const Glib::Error& ex)
{
erreur("Error, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
themes.push_back(theme);
}
# endif
//wnd_tmp->hide();
return 0;
# endif
}
int installe_theme(std::string th, bool tactile)
{
infos("installe theme (%s)...", th.c_str());
# ifndef MSYS2
return -1;
//avertissement("Themage desactivé !");
//return 0;
# else
if((th == "aucun") || (th.size() == 0))
return 0;
for(auto &theme: themes)
{
if(theme.id == th)
{
infos("Theme [%s] trouve.", th.c_str());
//assert(ihm::Mmi::get_instance() != nullptr);
//auto wnd = ihm::Mmi::get_instance()->engine;
//assert(wnd != nullptr);
/*auto refStyleContext = wnd->get_style_context();
if(theme_en_cours != nullptr)
{
infos("Remove provider...");
//if(refStyleContext->get_p)
//refStyleContext->remove_provider_for_screen(wnd->get_screen(), theme_en_cours->provider);
refStyleContext->remove_provider(theme_en_cours->provider);
infos("Ok.");
}*/
// refStyleContext->add_provider(css_prov,
// GTK_STYLE_PROVIDER_PRIORITY_USER+10);
Gtk::Window wnd_tmp;// = new Gtk::Window();
wnd_tmp.show();
wnd_tmp.present();
auto refStyleContext = wnd_tmp.get_style_context();
//auto refStyleContext = Gtk::StyleContext::create();
infos("Add provider...");
refStyleContext->add_provider_for_screen(wnd_tmp.get_screen(), theme.provider,
GTK_STYLE_PROVIDER_PRIORITY_USER+10);
infos("ok.");
wnd_tmp.hide();
theme_en_cours = &theme;
return 0;
}
}
return -1;
# endif
}
#if 0
int installe_theme(int th, bool tactile)
{
// A FAIRE
// Supporter au moins :
// - THEME_STD_WINDOWS + !tactile
// - THEME_FOND_NOIR + tactile
infos("%s(%d,%s)...", __func__, (int) th, tactile ? "tactile" : "non tactile");
# if 0
auto css_prov = Gtk::CssProvider::create();
ThemeCB cb;
css_prov->signal_parsing_error().connect(sigc::mem_fun(cb, &ThemeCB::on_parsing_error));
std::string pts[NB_THEMES] =
{
"arc-theme-3.20/gtk.css",
"arc-theme-3.20/gtk-dark.css",
"arc-theme-3.20/gtk-darker.css",
"arc-theme-3.20/gtk-solid.css",
"arc-theme-3.20/gtk-solid-dark.css",
"arc-theme-3.20/gtk-solid-darker.css",
"gtk-theme-ubuntustudio-legacy-master/UbuntuStudio_Legacy/gtk-3.20/gtk.css",
//"essai/gtk.css"
};
if(((int) th) >= NB_THEMES)
{
erreur("Num�ro de theme invalide : %d.", (int) th);
return -1;
}
std::string chemin_theme = pts[(int) th];
try
{
infos("Chargement du theme [%s]...", fn.c_str());
css_prov->load_from_path(fn);
infos("Ok.");
}
catch(const Gtk::CssProviderError& ex)
{
erreur("CssProviderError, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
catch(const Glib::Error& ex)
{
erreur("Error, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
auto wnd = mgc::vue::MGCWnd::get_instance();
auto refStyleContext = wnd->get_style_context();
// refStyleContext->add_provider(css_prov,
// GTK_STYLE_PROVIDER_PRIORITY_USER+10);
refStyleContext->add_provider_for_screen(wnd->get_screen(), css_prov,
GTK_STYLE_PROVIDER_PRIORITY_USER+10);
for(auto &ctr: mgc::vue::MGCWnd::get_instance()->controles)
{
auto wnd2 = &(ctr->wnd);
refStyleContext = wnd2->get_style_context();
// refStyleContext->add_provider(css_prov,
// GTK_STYLE_PROVIDER_PRIORITY_USER+10);
refStyleContext->add_provider_for_screen(wnd2->get_screen(), css_prov,
GTK_STYLE_PROVIDER_PRIORITY_USER+10);
}
//wnd->show();
# endif
return 0;
}
#endif
}}
| 7,675
|
C++
|
.cc
| 248
| 26.322581
| 99
| 0.615772
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,976
|
docking.cc
|
tsdconseil_opencv-demonstrator/libcutil/src/mmi/docking.cc
|
/*#include <gtk/gtk.h>
#include <gtkmm.h>
#include "gdl/gdl.h"
extern "C"
{
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <string.h>
#include <stdlib.h>
#include <gtk/gtk.h>
}*/
#include <gtkmm.h>
#include "mmi/docking.hpp"
namespace utils { namespace mmi {
MyPaned::MyPaned(bool vertical)
{
force_realloc = false;
enfant_en_cours = nullptr;
a_eu_allocation = false;
total_natural_dim = total_minimum_dim = 0;
this->total_height = 0;
this->vertical = vertical;
derniere_allocation.set_x(0);
derniere_allocation.set_y(0);
derniere_allocation.set_width(1);
derniere_allocation.set_height(1);
set_has_window(false);
set_redraw_on_allocate(false);
maj_allocation();
}
MyPaned::~MyPaned()
{
/*
// These calls to Gtk::Widget::unparent() are necessary if MyPaned is
// deleted before its children. But if you use a version of gtkmm where bug
// https://bugzilla.gnome.org/show_bug.cgi?id=605728
// has not been fixed (gtkmm 3.7.10 or earlier) and the children are deleted
// before the container, these calls can make the program crash.
// That's because on_remove() is not called, when the children are deleted.
if (m_child_one)
m_child_one->unparent();
if (m_child_two)
m_child_two->unparent();
*/
}
int MyPaned::get_dim(Gtk::Widget *wid)
{
for(auto e: enfants)
if(e->widget == wid)
return e->dim;
erreur("%s: non trouvé.", __func__);
return -1;
}
int MyPaned::set_dim(Gtk::Widget *wid, int dim)
{
for(auto e: enfants)
{
if(e->widget == wid)
{
int mini, natu;
if(vertical)
wid->get_preferred_height(mini, natu);
else
wid->get_preferred_width(mini, natu);
if(dim >= mini)
e->dim = dim;
this->maj_allocation();
return 0;
}
}
erreur("%s: non trouvé.", __func__);
return -1;
}
void MyPaned::add_child(Gtk::Widget &w, int apres)
{
Enfant *e = new Enfant();
int mh, nh;
int mw, nw;
w.get_preferred_height(mh, nh);
w.get_preferred_width(mw, nw);
/*if(vertical)
e->dim = nh;
else
e->dim = nw;*/
e->dim = -1;
e->largeur = nw;
e->hauteur_pourcent = -1;
e->widget = &w;
if(vertical)
e->sep = &(e->hsep);
else
e->sep = &(e->vsep);
w.set_parent(*this);
e->event_box.set_parent(*this);
e->event_box.add(*(e->sep));
if(vertical)
e->event_box.set_hexpand(true);
else
e->event_box.set_vexpand(true);
e->sep->show();
e->event_box.show();
//e.vsep->set_margin_top(5);
e->event_box.set_events(Gdk::POINTER_MOTION_MASK
| Gdk::BUTTON_MOTION_MASK
| Gdk::ENTER_NOTIFY_MASK
| Gdk::LEAVE_NOTIFY_MASK
| Gdk::POINTER_MOTION_HINT_MASK
| Gdk::BUTTON_PRESS_MASK);
e->event_box.signal_motion_notify_event().connect(sigc::mem_fun(*this, &MyPaned::gere_motion));
e->event_box.signal_enter_notify_event().connect(
sigc::bind(sigc::mem_fun(*this, &MyPaned::gere_enter), e));
e->event_box.signal_leave_notify_event().connect(sigc::mem_fun(*this, &MyPaned::gere_leave));
e->event_box.signal_button_press_event().connect(
sigc::bind(sigc::mem_fun(*this, &MyPaned::gere_bpress), e));
e->event_box.signal_button_release_event().connect(
sigc::bind(sigc::mem_fun(*this, &MyPaned::gere_brelease), e));
if(apres == -1)
enfants.push_back(e);
else
enfants.insert(enfants.begin() + apres, e);
for(unsigned int i = 0u; i < enfants.size(); i++)
enfants[i]->num = i;
//allocation_initiale();
//reallocation_complete();
maj_allocation();
}
void MyPaned::maj_allocation()
{
unsigned int n = enfants.size();
est_taille_min(tl_min, th_min);
unsigned int total_dim = 0;
// On regarde si la taille affectée est :
// (1) >= à la taille totale naturelle
// (2) ou inférieure
int alloc_dim;
if(vertical)
alloc_dim = derniere_allocation.get_height();
else
alloc_dim = derniere_allocation.get_width();
//
for(auto i = 0u; i < n; i++)
{
auto e = enfants[i];
int mini, nat;
if(vertical)
e->widget->get_preferred_height(mini, nat);
else
e->widget->get_preferred_width(mini, nat);
e->dim_mini = mini;
e->dim_nat = nat;
//int h = e->hauteur;
// (1) APPEL SANS ALLOCATION, h[i] = -1
// (2) APPEL AVEC ALLOCATION, h[i] = -1
// (3) APPEL AVEC ALLOCATION, h[i] != -1
e->dim_temp = e->dim;
if(e->dim == -1)
{
e->dim_temp = nat; // Allocation taille naturelle
if(a_eu_allocation && (alloc_dim > 0) && (nat > 0))
{
// Si dernier, alloue tout ce qui reste
if((i == (unsigned int) (n - 1)) && (alloc_dim >= (nat + (int) total_dim)))
{
e->dim_temp = alloc_dim - total_dim;
infos("%d <- %d", e->dim, e->dim_temp);
e->dim = e->dim_temp;
}
else if(alloc_dim >= (int) (nat + total_dim))
{
infos("%d <- %d", e->dim, e->dim_temp);
e->dim = e->dim_temp;
}
}
}
// Si déjà une hauteur programmée, mais le dernier -> tout ce qui reste quand même
else if(i == n - 1)
{
if(a_eu_allocation)
{
if(alloc_dim > (int) total_dim)
e->dim_temp = alloc_dim - total_dim;
}
else
e->dim_temp = nat;
}
//if(!vertical)
infos("%s/%s: widget[%d] -> dim_temp = %d (nat = %d, min = %d, dim = %d, a_eu_allocation = %d).",
__func__, vertical ? "V" : "H", i, e->dim_temp, nat, mini, e->dim, a_eu_allocation);
total_dim += e->dim_temp;
//e->sep->get_preferred_height(mini, nat);
total_dim += 5;//mini;
}
total_natural_dim = total_dim;
if(vertical)
total_minimum_dim = th_min;
else
total_minimum_dim = tl_min;
total_dim = 0;
for(auto i = 0u; i < n; i++)
{
auto e = enfants[i];
//if(enfants[i]->widget->get_visible())
{
//int h;
int mini, nat;
if(vertical)
e->widget->get_preferred_height(mini, nat);
else
e->widget->get_preferred_width(mini, nat);
//h = enfants[i]->dim_temp;
if(vertical)
{
e->allocation[0].set_height(enfants[i]->dim_temp);
//Make it take up the full width available:
e->allocation[0].set_width(derniere_allocation.get_width());
e->allocation[0].set_x(derniere_allocation.get_x());
e->allocation[0].set_y(total_dim + derniere_allocation.get_y());
}
else
{
e->allocation[0].set_width(enfants[i]->dim_temp);
e->allocation[0].set_height(derniere_allocation.get_height());
e->allocation[0].set_x(total_dim + derniere_allocation.get_x());
e->allocation[0].set_y(derniere_allocation.get_y());
infos("placement[%d]: x = %d.", i, total_dim);
}
//enfants[i]->widget->size_allocate(ch_alloc);
total_dim += enfants[i]->dim_temp;
if(i + 1 < n)
{
//enfants[i]->sep->get_preferred_height(mini, nat);
mini = nat = 5;
//h = nat;
//infos("Separator alloc: mini = %d, nat = %d, POS = %d.", mini, nat,total_dim);
if(vertical)
{
e->allocation[1].set_height(nat);
e->allocation[1].set_width(derniere_allocation.get_width());
e->allocation[1].set_x(derniere_allocation.get_x());
e->allocation[1].set_y(total_dim + derniere_allocation.get_y());
}
else
{
e->allocation[1].set_width(nat);
e->allocation[1].set_height(derniere_allocation.get_height());
e->allocation[1].set_x(total_dim + derniere_allocation.get_x());
e->allocation[1].set_y(derniere_allocation.get_y());
}
//enfants[i]->event_box.size_allocate(ch_alloc);
total_dim += nat;
}
}
}
total_natural_dim = total_dim;
infos("total_dim = %d", total_dim);
}
Gtk::Widget *MyPaned::get_widget()
{
return this;
}
//This example container is a simplified VBox with at most two children.
Gtk::SizeRequestMode MyPaned::get_request_mode_vfunc() const
{
if(vertical)
return Gtk::SIZE_REQUEST_HEIGHT_FOR_WIDTH;
else
return Gtk::SIZE_REQUEST_WIDTH_FOR_HEIGHT;
}
void MyPaned::est_taille_min(int &largeur, int &hauteur)
{
largeur = 0;
hauteur = 0;
for(auto &ch: enfants)
{
int ml[2], pl[2], mh[2], ph[2];
ch->widget->get_preferred_width(ml[0], pl[0]);
ch->widget->get_preferred_height(mh[0], ph[0]);
ch->sep->get_preferred_width(ml[1], pl[1]);
ch->sep->get_preferred_height(mh[1], ph[1]);
if(vertical)
ch->valeur_min = mh[0];
else
ch->valeur_min = ml[0];
for(auto i = 0u; i < 2; i++)
{
if(vertical)
{
if(ml[i] > largeur)
largeur = ml[i];
hauteur += mh[i];
}
else
{
if(mh[i] > hauteur)
hauteur = mh[i];
largeur += ml[i];
}
}
}
infos("%s: %d, %d", __func__, largeur, hauteur);
}
//Discover the total amount of minimum space and natural space needed by
//this container and its children.
void MyPaned::get_preferred_width_vfunc(int& minimum_width, int& natural_width) const
{
if(enfants.size() == 0)
{
minimum_width = 0;
natural_width = 0;
return;
}
if(!vertical)
{
minimum_width = total_minimum_dim;
natural_width = total_natural_dim;
if(minimum_width > natural_width)
erreur("%s: min = %d, nat = %d.", __func__, minimum_width, natural_width);
return;
}
int min_width[2*enfants.size()];
int nat_width[2*enfants.size()];
unsigned int i = 0u;
for(auto &ch: enfants)
{
if(ch->widget->get_visible())
{
ch->widget->get_preferred_width(min_width[2*i], nat_width[2*i]);
ch->sep->get_preferred_width(min_width[2*i+1], nat_width[2*i+1]);
//infos("child reports %d, %d", min_width[2*i], nat_width[2*i]);
}
else
{
min_width[2*i] = nat_width[2*i] = 0;
min_width[2*i+1] = nat_width[2*i+1] = 0;
}
i++;
}
// Request a width equal to the width of the widest visible child.
minimum_width = *std::max_element(min_width, min_width + 2*enfants.size());
natural_width = *std::max_element(nat_width, nat_width + 2*enfants.size());
//infos("%s: %d, %d", __func__, minimum_width, natural_width);
if(minimum_width > natural_width)
erreur("%s: min = %d, nat = %d.", __func__, minimum_width, natural_width);
}
void MyPaned::get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const
{
get_preferred_height_vfunc(minimum_height, natural_height);
# if 0
if(enfants.size() == 0)
{
minimum_height = 0;
natural_height = 0;
return;
}
unsigned int n = enfants.size();
int child_minimum_height[n];
int child_natural_height[n];
int nvis_children = get_n_visible_children();
for(auto i = 0u; i < n; i++)
if(enfants[i]->widget->get_visible())
enfants[i]->widget->get_preferred_height_for_width(width, child_minimum_height[i], child_natural_height[i]);
//The allocated height will be divided equally among the visible children.
//Request a height equal to the number of visible children times the height
//of the highest child.
minimum_height = nvis_children *
*std::max_element(child_minimum_height, child_minimum_height + enfants.size());
natural_height = nvis_children *
*std::max_element(child_natural_height, child_natural_height + enfants.size());;
infos("%s: %d, %d", __func__, minimum_height, natural_height);
# endif
}
void MyPaned::get_preferred_height_vfunc(int& minimum_height, int& natural_height) const
{
if(enfants.size() == 0)
{
minimum_height = 0;
natural_height = 0;
return;
}
if(vertical)
{
minimum_height = total_minimum_dim;
natural_height = total_natural_dim;
//verbose("%s: min = %d, nat = %d", __func__, minimum_height, natural_height);
if(minimum_height > natural_height)
{
avertissement("%s: min = %d, nat = %d.", __func__, minimum_height, natural_height);
natural_height = minimum_height;
}
return;
}
int min_height[2*enfants.size()];
int nat_height[2*enfants.size()];
unsigned int i = 0u;
for(auto &ch: enfants)
{
if(ch->widget->get_visible())
{
ch->widget->get_preferred_height(min_height[2*i], nat_height[2*i]);
ch->sep->get_preferred_height(min_height[2*i+1], nat_height[2*i+1]);
//infos("child reports %d, %d", min_height[2*i], nat_height[2*i]);
}
else
{
min_height[2*i] = nat_height[2*i] = 0;
min_height[2*i+1] = nat_height[2*i+1] = 0;
}
i++;
}
// Request a width equal to the width of the widest visible child.
minimum_height = *std::max_element(min_height, min_height + 2*enfants.size());
natural_height = *std::max_element(nat_height, nat_height + 2*enfants.size());
//infos("%s: %d, %d", __func__, minimum_height, natural_height);
if(minimum_height > natural_height)
erreur("%s: min = %d, nat = %d.", __func__, minimum_height, natural_height);
# if 0
unsigned int n = enfants.size();
int child_minimum_height[n];
int child_natural_height[n];
int nvis_children = get_n_visible_children();
for(auto i = 0u; i < n; i++)
{
if(enfants[i]->widget->get_visible())
{
enfants[i]->widget->get_preferred_height(child_minimum_height[0], child_natural_height[0]);
}
}
//The allocated height will be divided equally among the visible children.
//Request a height equal to the number of visible children times the height
//of the highest child.
minimum_height = nvis_children *
*std::max_element(child_minimum_height, child_minimum_height + enfants.size());
natural_height = nvis_children *
*std::max_element(child_natural_height, child_natural_height + enfants.size());;
infos("%s: %d, %d", __func__, minimum_height, natural_height);
# endif
}
void MyPaned::get_preferred_width_for_height_vfunc(int height,
int& minimum_width, int& natural_width) const
{
get_preferred_width_vfunc(minimum_width, natural_width);
# if 0
if(enfants.size() == 0)
{
minimum_width = 0;
natural_width = 0;
return;
}
unsigned int n = enfants.size();
int child_minimum_width[n];
int child_natural_width[n];
int nvis_children = get_n_visible_children();
if(nvis_children > 0)
{
//Divide the height equally among the visible children.
const int height_per_child = height / nvis_children;
for(auto i = 0u; i < n; i++)
{
if(enfants[i]->widget->get_visible())
enfants[i]->widget->get_preferred_width_for_height(height_per_child,
child_minimum_width[i], child_natural_width[i]);
}
}
//Request a width equal to the width of the widest child.
minimum_width = *std::max_element(child_minimum_width, child_minimum_width + n);
natural_width = *std::max_element(child_natural_width, child_natural_width + n);
infos("%s: %d, %d", __func__, minimum_width, natural_width);
# endif
}
unsigned int MyPaned::get_n_visible_children() const
{
unsigned int res = 0;
for(auto &ch: enfants)
if(ch->widget->get_visible())
res++;
return res;
}
void MyPaned::on_size_allocate(Gtk::Allocation& allocation)
{
// Do something with the space that we have actually been given:
// (We will not be given heights or widths less than we have requested, though
// we might get more.)
if(!force_realloc)
{
if((allocation.get_x() == derniere_allocation.get_x())
&& (allocation.get_y() == derniere_allocation.get_y())
&& (allocation.get_width() == derniere_allocation.get_width())
&& (allocation.get_height() == derniere_allocation.get_height()))
{
for(auto e: enfants)
{
e->widget->size_allocate(e->allocation[0]);
if(e != enfants[enfants.size() - 1])
e->event_box.size_allocate(e->allocation[1]);
}
return;
}
}
else
force_realloc = false;
trace_verbeuse("(%d,%d,%d,%d)",
allocation.get_x(), allocation.get_y(),
allocation.get_width(), allocation.get_height());
// Use the offered allocation for this container:
set_allocation(allocation);
# if 1
if(a_eu_allocation && (derniere_allocation.get_width() > 0))
{
// Essaye de garder les mêmes proportions qu'avant
float tot = 0;
bool all_ok = true;
for(auto &e: enfants)
{
if(e->dim <= 0)
{
all_ok = false;
break;
}
tot += e->dim;
}
if(all_ok)
{
for(auto &e: enfants)
e->hauteur_pourcent = ((float) e->dim) / tot;
int dim_dispo;
if(vertical)
dim_dispo = allocation.get_height();
else
dim_dispo = allocation.get_width();
for(auto &e: enfants)
{
int essai = e->hauteur_pourcent * dim_dispo;
if(essai >= e->dim_mini)
e->dim = essai;
}
}
}
# endif
derniere_allocation = allocation;
a_eu_allocation = true;
maj_allocation();
for(auto e: enfants)
{
e->widget->size_allocate(e->allocation[0]);
if(e != enfants[enfants.size() - 1])
e->event_box.size_allocate(e->allocation[1]);
}
}
void MyPaned::forall_vfunc(gboolean, GtkCallback callback, gpointer callback_data)
{
for(auto ch: enfants)
{
callback(ch->widget->gobj(), callback_data);
if(ch != *(enfants.end()-1))
callback((GtkWidget *) ch->event_box.gobj(), callback_data);
}
}
void MyPaned::on_add(Gtk::Widget* child)
{
erreur("%s: TODO", __func__);
//children.push_back(child);
//child->set_parent(*this);
}
bool MyPaned::gere_motion(GdkEventMotion *mot)
{
if(deplacement)
{
trace_verbeuse("déplacement: %d, %d", (int) mot->x, (int) mot->y);
// Il faut se débrouiller pour que mot->y soit la coordonnée de départ du séparateur du bas
if(enfant_en_cours != nullptr)
{
int id = enfant_en_cours->num;
if(id >= (int) enfants.size() - 1)
{
avertissement("Déplacement dernier paneau -> impossible.");
return true;
}
int inc;
if(vertical)
inc = mot->y_root - deplacement_pos_initiale;
else
inc = mot->x_root - deplacement_pos_initiale;
int nvh[2];
nvh[0] = deplacement_taille_initiale[0] + inc;
nvh[1] = deplacement_taille_initiale[1] - inc;
if(inc > 0)
{
if(nvh[1] < enfants[id+1]->valeur_min)
{
nvh[1] = enfants[id+1]->valeur_min;
nvh[0] -= inc;
nvh[0] += deplacement_taille_initiale[1] - nvh[1];
trace_verbeuse("Blocage à cause du bas (min = %d)", enfants[id+1]->valeur_min);
}
}
else
{
if(nvh[0] < enfants[id]->valeur_min)
{
nvh[0] = enfants[id]->valeur_min;
nvh[1] += inc;
nvh[1] -= nvh[0] - deplacement_taille_initiale[0];
trace_verbeuse("Blocage à cause du haut");
}
}
enfants[id]->dim = nvh[0];
enfants[id+1]->dim = nvh[1];
# if 0
int w0 = enfants[id]->widget->get_allocated_width();
int h0 = enfants[id]->widget->get_allocated_height();
int w1 = enfants[id+1]->widget->get_allocated_width();
int h1 = enfants[id+1]->widget->get_allocated_height();
int inc = mot->y - last_dep;
//last_dep += inc;
last_dep = mot->y;
if(inc > 0)
{
// Si pas l'avant dernier
//if(id != enfants.size() - 1)
{
if(h1 - inc < enfants[id+1]->valeur_min)
{
inc = h1 - enfants[id+1]->valeur_min;
avertissement("Blocage à cause du bas (min = %d, h = %d)", enfants[id+1]->valeur_min, h1);
}
}
enfants[id]->dim = h0 + inc;
enfants[id+1]->dim = h1 - inc;
}
else
{
if(h0 + inc < enfants[id]->valeur_min)
{
inc = enfants[id]->valeur_min - h0;
avertissement("Blocage à cause du haut");
}
enfants[id]->dim = h0 + inc;
if(id != enfants.size() - 2)
enfants[id+1]->dim = h1 - inc;
}
# endif
//maj_allocation();
//enfants[id]->hauteur
force_realloc = true;
queue_resize();
//queue_draw();
//queue_resize_no_redraw();
}
}
return true;
}
bool MyPaned::gere_leave(GdkEventCrossing *mot)
{
auto ref_window = this->get_window();
ref_window->set_cursor(); // Curseur par défaut
return true;
}
bool MyPaned::gere_enter(GdkEventCrossing *mot, Enfant *e)
{
infos("enter notify: %d, %d", (int) mot->x, (int) mot->y);
auto ref_window = e->sep->get_window();
Glib::RefPtr<Gdk::Cursor> curseur;
if(vertical)
curseur = Gdk::Cursor::create(Gdk::DOUBLE_ARROW);
else
curseur = Gdk::Cursor::create(Gdk::SB_H_DOUBLE_ARROW);
ref_window->set_cursor(curseur);
return true;
}
bool MyPaned::gere_brelease(GdkEventButton *mot, Enfant *e)
{
infos("brelease: %d, %d", (int) mot->x, (int) mot->y);
enfant_en_cours = nullptr;
deplacement = false;
return true;
}
bool MyPaned::gere_bpress(GdkEventButton *mot, Enfant *e)
{
infos("bpress: paneau[%d], %d, %d", e->num, mot->x, mot->y);
enfant_en_cours = e;
if(vertical)
deplacement_pos_initiale = mot->y_root;
else
deplacement_pos_initiale = mot->x_root;
last_dep = deplacement_pos_initiale;
if(vertical)
{
deplacement_taille_initiale[0] = e->widget->get_allocated_height();
if(e->num != ((int) enfants.size() - 1))
deplacement_taille_initiale[1] = enfants[e->num+1]->widget->get_allocated_height();
}
else
{
deplacement_taille_initiale[0] = e->widget->get_allocated_width();
if(e->num != ((int) enfants.size() - 1))
deplacement_taille_initiale[1] = enfants[e->num+1]->widget->get_allocated_width();
}
deplacement = true;
return true;
}
/*void MyPaned::remove(Gtk::Widget &w)
{
}*/
void MyPaned::on_remove(Gtk::Widget* child)
{
Enfant *e = nullptr;
if(child)
{
const bool visible = child->get_visible();
for(auto i = 0u; i < enfants.size(); i++)
{
if(child == enfants[i]->widget)
{
e = enfants[i];
child->unparent();
e->event_box.unparent();
enfants.erase(enfants.begin() + i);
delete e;
if(visible)
queue_resize();
return;
}
}
}
}
GType MyPaned::child_type_vfunc() const
{
//If there is still space for one widget, then report the type of widget that
//may be added.
//if(!m_child_one || !m_child_two)
return Gtk::Widget::get_type();
//else
//{
//No more widgets may be added.
//return G_TYPE_NONE;
//}
}
void MainDock::maj_langue()
{
for(auto &ctrl: controles)
ctrl->maj_langue();
}
void MainDock::sauve()
{
int paned1, paned2;
paned1 = hpaned.enfants[0]->dim;
paned2 = hpaned.enfants[1]->dim;
/*mgc::app.modele_global.set_attribute("pos-fenetre-princ/paned1", paned1);
mgc::app.modele_global.set_attribute("pos-fenetre-princ/paned2", paned2);*/
modele.set_attribute("paned1", paned1);
modele.set_attribute("paned2", paned2);
//auto &lst = mgc::vue::MGCWnd::get_instance()->controles;
for(auto &vd: controles/*lst*/)
{
auto md = vd->controle->modele_dyn;
md.set_attribute("id", vd->controle->id);
md.set_attribute("visible", vd->visible);
md.set_attribute("docquee", vd->docquee);
md.set_attribute("dock-en-cours", vd->doc_en_cours);
if(!vd->docquee)
{
if(vd->visible)
{
auto win = vd->wnd.get_window();
if(win)
{
int x, y, l, h;
//win->get_position(x, y);
//l = win->get_width();
//h = win->get_height();
vd->wnd.get_position(x, y);
l = vd->wnd.get_width();
h = vd->wnd.get_height();
md.set_attribute("x", x);
md.set_attribute("y", x);
md.set_attribute("largeur", l);
md.set_attribute("hauteur", h);
}
}
}
else
{
// Recherche de l'endroit où est docké
int dim = vboxes[vd->doc_en_cours].get_dim(&(vd->drag_frame));
md.set_attribute("dim", dim);
}
}
}
void MainDock::charge()
{
/*int paned1 = mgc::app.modele_global.get_attribute_as_int("pos-fenetre-princ/paned1");
int paned2 = mgc::app.modele_global.get_attribute_as_int("pos-fenetre-princ/paned2");*/
int paned1 = modele.get_attribute_as_int("paned1");
int paned2 = modele.get_attribute_as_int("paned2");
hpaned.enfants[0]->dim = paned1;
hpaned.enfants[1]->dim = paned2;
Glib::RefPtr<Gdk::Screen> ecran = Gdk::Screen::get_default();
int ecran_largeur = ecran->get_width();
int ecran_hauteur = ecran->get_height();
//auto &lst = mgc::vue::MGCWnd::get_instance()->controles;
for(auto &vd: controles)
{
int x, y, l, h;
auto md = vd->controle->modele_dyn;
x = md.get_attribute_as_int("x");
y = md.get_attribute_as_int("y");
l = md.get_attribute_as_int("largeur");
h = md.get_attribute_as_int("hauteur");
vd->visible = md.get_attribute_as_boolean("visible");
vd->docquee = md.get_attribute_as_boolean("docquee");
vd->doc_en_cours = md.get_attribute_as_int("dock-en-cours");
if(vd->visible)
{
infos("Chargement ctrl [%s], docquee = %d.", vd->controle->id.c_str(), vd->docquee);
if(vd->docquee)
{
vboxes[vd->doc_en_cours].add_child(vd->drag_frame);
vd->drag_frame.show();
vd->drag_frame.b_dedocquer.show();
vboxes[vd->doc_en_cours].set_dim(&(vd->drag_frame), md.get_attribute_as_int("dim"));
}
else
{
if(!vd->docquable)
vd->wnd.add(*(vd->controle->widget));
else
vd->wnd.add(vd->drag_frame);
vd->wnd.show_all_children(true);
vd->wnd.show();
vd->drag_frame.b_dedocquer.hide();
vd->maj_vue();
auto win = vd->wnd.get_window();
if(win)
{
infos("move_resize(%d,%d,%d,%d)...", x, y, l, h);
if(x < 0)
{
avertissement("%s: x < 0 (%d)", __func__, x);
x = 0;
}
if(y < 0)
{
avertissement("%s: y < 0 (%d)", __func__, y);
y = 0;
}
if(x + l > ecran_largeur)
{
avertissement("%s: x + l (%d) > largeur ecran (%d)", __func__, x + l, ecran_largeur);
x -= (x + l) - ecran_largeur;
if(x < 0)
{
x = 0;
l = ecran_largeur;
}
}
if(y + h > ecran_hauteur)
{
avertissement("%s: y + h (%d) > hauteur ecran (%d)", __func__, y + h, ecran_hauteur);
y -= (y + h) - ecran_hauteur;
if(y < 0)
{
y = 0;
h = ecran_hauteur;
}
}
infos("move_resize reel(%d,%d,%d,%d)...", x, y, l, h);
vd->wnd.move(x, y);
vd->wnd.resize(l, h);
}
}
}
}
hpaned.queue_resize();
}
void VueDetachable::gere_dedocquage()
{
main_dock->vboxes[doc_en_cours].remove(drag_frame);
//drag_frame.remove();
docquee = false;
if(!docquable)
wnd.add(*(controle->widget));
else
wnd.add(drag_frame);
wnd.show_all_children(true);
wnd.show();
drag_frame.b_dedocquer.hide();
}
void VueDetachable::gere_fermeture()
{
if(docquee)
main_dock->vboxes[doc_en_cours].remove(drag_frame);
//drag_frame.remove();
visible = false;
}
void VueDetachable::affiche(bool visible)
{
this->controle->modele_dyn.set_attribute("visible", visible);
// Affichage
if(!this->visible && visible)
{
if(this->docquee)
{
//drag_frame.add(*(controle->widget));
//main_dock->vboxes[doc_en_cours].pack_start(drag_frame, Gtk::PACK_EXPAND_WIDGET);
main_dock->vboxes[doc_en_cours].add_child(drag_frame);
drag_frame.b_dedocquer.show();
drag_frame.show();
}
else
{
trace_verbeuse("Affichage fenetre [%s]", controle->id.c_str());
drag_frame.b_dedocquer.hide();
if(docquable)
wnd.add(drag_frame);
else
wnd.add(*(controle->widget));
wnd.show_all_children(true);
wnd.show();
}
this->visible = visible;
}
// Masquage
else if(!visible && this->visible)
{
if(docquee)
{
main_dock->vboxes[doc_en_cours].remove(drag_frame);
//drag_frame.remove();
}
else
{
wnd.remove();
wnd.hide();
}
this->visible = false;
}
//this->visible = visible;
//maj_vue();
}
void MainDock::gere_drag_data_received_gauche(
const Glib::RefPtr<Gdk::DragContext>& context, int b, int c,
const Gtk::SelectionData& selection_data, unsigned int a, unsigned int time)
{
gere_drag_data_received(context, b, c, selection_data, a, time, 0);
}
void MainDock::gere_drag_data_received_droit(
const Glib::RefPtr<Gdk::DragContext>& context, int b, int c,
const Gtk::SelectionData& selection_data, unsigned int a, unsigned int time)
{
gere_drag_data_received(context, b, c, selection_data, a, time, 1);
}
bool VueDetachable::gere_evt_delete(GdkEventAny *evt)
{
infos("Suppression manuelle fenêtre [%s].", controle->id.c_str());
if(visible && !docquee)
{
wnd.hide();
wnd.remove();
visible = false;
toggle->set_active(false);
}
return true;
}
void MainDock::gere_drag_data_received(
const Glib::RefPtr<Gdk::DragContext>& context, int b, int c,
const Gtk::SelectionData& selection_data, unsigned int a, unsigned int time, int num)
{
const int length = selection_data.get_length();
if((length >= 0) && (selection_data.get_format() == 8))
{
std::string s = selection_data.get_data_as_string();
infos("Reçu [%s] sur paned[%d]", s.c_str(), num);
VueDetachable *ctrl = recherche(s);
if(ctrl == nullptr)
return;
if(ctrl->visible && !ctrl->docquee && ctrl->docquable)
{
infos("Docquage en cours...");
ctrl->wnd.hide();
ctrl->wnd.remove();
//ctrl->drag_frame.add(*(ctrl->controle->widget));
//vboxes[num].pack_start(ctrl->drag_frame, Gtk::PACK_EXPAND_WIDGET);
vboxes[num].add_child(ctrl->drag_frame);
ctrl->drag_frame.show();
ctrl->docquee = true;
ctrl->doc_en_cours = num;
ctrl->drag_frame.b_dedocquer.show();
}
else if(ctrl->visible && ctrl->docquee && ctrl->docquable)
{
infos("Déplacement docquée %d -> %d...", ctrl->doc_en_cours, num);
vboxes[ctrl->doc_en_cours].remove(ctrl->drag_frame);
//vboxes[num].pack_start(ctrl->drag_frame, Gtk::PACK_EXPAND_WIDGET);
vboxes[num].add_child(ctrl->drag_frame);
ctrl->drag_frame.show();
ctrl->doc_en_cours = num;
ctrl->drag_frame.b_dedocquer.show();
}
//this->hpaned[1].show_all_children(true);
}
else
infos("Drag sans message ?");
context->drag_finish(false, false, time);
}
bool MainDock::gere_drag_motion(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, unsigned int prm)
{
infos("drag_motion : %d, %d.", x, y);
//const Glib::RefPtr< Gdk::Cursor > cursor = Gdk::Cursor::create(Gdk::HAND1);
//this->get_window()->set_cursor(cursor);
return true;
}
VueDetachable *MainDock::recherche(std::string id)
{
//auto lst = vue::MGCWnd::get_instance()->controles;
for(auto &vd: controles)
{
if(vd->controle->id == id)
return vd;
}
erreur("Controle non trouvé : [%s].", id.c_str());
return nullptr;
}
MyHPaned::MyHPaned(int largeur, int position)
{
set_contrainte(largeur, position);
//this->signal_check_resize()
}
MyHPaned::MyHPaned()
{
set_contrainte(-1, -1);
}
void MyHPaned::applique_contrainte()
{
infos("HPANED[%d] : Forcage position = %d (allocation = %d)", numero, position, get_allocated_width());
this->set_position(position);
}
void MyHPaned::set_contrainte(int largeur, int position)
{
forcer_position = true;
this->largeur = largeur;
this->position = position;
}
void MyHPaned::on_size_allocate(Gtk::Allocation &allocation)
{
//int w = this->get_allocated_width();
trace_majeure("MyHPaned[%d]::on_size_allocate(w = %d, h = %d)",
numero,
allocation.get_width(), allocation.get_height());
//if(forcer_position && (position != -1))
//this->set_position(position);
//this->set_position(100);
//this->set_position((position * w) / largeur);
HPaned::on_size_allocate(allocation);
//if(forcer_position && (position != -1))
//this->set_position(100);
//this->set_position(position);
//this->set_position((position * w) / largeur);
//set_position(3);
}
/*void set_position(int position)
{
}*/
MainDock::MainDock(utils::model::Node modele): hpaned(false)
{
infos("Creation du MainDock...");
this->modele = modele;
hpaned.add_child(*(vboxes[0].get_widget()));
hpaned.add_child(vbox);
hpaned.add_child(*(vboxes[1].get_widget()));
std::vector<Gtk::TargetEntry> cibles;
cibles.push_back( Gtk::TargetEntry("STRING") );
cibles.push_back( Gtk::TargetEntry("text/plain") );
vboxes[0].get_widget()->drag_dest_set(cibles);
vboxes[0].get_widget()->signal_drag_data_received().connect(sigc::mem_fun(*this,
&MainDock::gere_drag_data_received_gauche));
//gauche.signal_drag_begin()
vboxes[1].get_widget()->drag_dest_set(cibles);
vboxes[1].get_widget()->signal_drag_data_received().connect(sigc::mem_fun(*this,
&MainDock::gere_drag_data_received_droit));
//vbox.signal_drag_motion().connect(sigc::mem_fun(*this,
// &MGCWnd::gere_drag_motion));
infos("Ok.");
}
Gtk::Widget *MainDock::get_widget()
{
return &hpaned;//&hpaned[0];
}
void VueDetachable::gere_drag_data_get(
const Glib::RefPtr<Gdk::DragContext>& context,
Gtk::SelectionData& selection_data, unsigned int info, unsigned int time)
{
selection_data.set(selection_data.get_target(), 8 /* 8 bits format */,
(const unsigned char*) controle->id.c_str(),
controle->id.size());
//const Glib::RefPtr< Gdk::Cursor > cursor = Gdk::Cursor::create(Gdk::HAND1);
//this->wnd.get_window()->set_cursor(cursor);
//wnd.get_window()->set_cursor()
}
bool VueDetachable::gere_drag_motion(
const Glib::RefPtr<Gdk::DragContext>& context,
int x, int y, unsigned int time)
{
infos("Drag motion (%d, %d)", x, y);
return true;
}
bool VueDetachable::est_visible()
{
return visible;
}
bool VueDetachable::on_expose_event(const Cairo::RefPtr<Cairo::Context> &cr)
{
if(!expose)
{
expose = true;
if(!docquee)
{
auto md = controle->modele_dyn;
int x, y, l, h;
x = md.get_attribute_as_int("x");
y = md.get_attribute_as_int("y");
l = md.get_attribute_as_int("largeur");
h = md.get_attribute_as_int("hauteur");
visible = md.get_attribute_as_boolean("visible");
maj_vue();
auto win = wnd.get_window();
if(win)
{
wnd.move(x, y);
wnd.resize(l, h);
}
}
}
return true;
}
void VueDetachable::maj_vue()
{
if(docquee)
{
}
else
{
wnd.set_title(controle->modele.get_localized_name());
if(visible)
{
wnd.show();
wnd.present();
}
else
{
wnd.hide();
}
}
}
MyFrame::MyFrame()
// b_fermer(Gtk::Stock::CLOSE),
// b_dedocquer(Gtk::Stock::QUIT)
{
widget_en_cours = nullptr;
std::string pt = utils::get_fixed_data_path() + PATH_SEP + "img/fermer.png";
if(!utils::files::file_exists(pt))
{
erreur("Fichier non trouvé : %s", pt.c_str());
}
Gtk::Image *i1 = new Gtk::Image(utils::get_fixed_data_path() + PATH_SEP + "img/fermer.png");
b_fermer.set_image(*i1);
Gtk::Image *i2 = new Gtk::Image(utils::get_fixed_data_path() + PATH_SEP + "img/dedocquer.png");
b_dedocquer.set_image(*i2);
titre.show();
b_dedocquer.show();
b_fermer.show();
hbox.show();
hbox2.show();
//b_dedocquer = Gtk::ToolButton(Gtk::Stock::QUIT);
//b_fermer = Gtk::ToolButton(Gtk::Stock::CLOSE);
// 153, 180, 209
std::string css = "* { background: #99B4D1; background-color: #99B4D1; color: #ffffff; }";
auto p = Gtk::CssProvider::create();
try
{
p->load_from_data(css);
titre.get_style_context()->add_provider(p, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
b_fermer.get_style_context()->add_provider(p, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
b_dedocquer.get_style_context()->add_provider(p, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
hbox.get_style_context()->add_provider(p, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
evbox.get_style_context()->add_provider(p, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
}
catch(const Glib::Error& ex)
{
erreur("Error, Gtk::CssProvider::load_from_path() failed: %s",
ex.what().c_str());
}
catch(...)
{
erreur("Erreur add_provider.");
}
evbox.add(titre);
titre.set_hexpand(true);
hbox.pack_start(evbox, Gtk::PACK_EXPAND_WIDGET);
hbox.pack_start(b_dedocquer, Gtk::PACK_SHRINK);
hbox.pack_start(b_fermer, Gtk::PACK_SHRINK);
b_dedocquer.set_halign(Gtk::ALIGN_END);
b_fermer.set_halign(Gtk::ALIGN_END);
hbox.show();
hbox.set_hexpand(true);
hbox.show_all_children(true);
pack_start(hbox, Gtk::PACK_SHRINK);
hbox.set_hexpand(true);
}
void MyFrame::set_titre(std::string s)
{
titre.set_use_markup(true);
titre.set_label("<b>" + s + "</b>");
}
void MyFrame::add(Gtk::Widget &w)
{
pack_start(w, Gtk::PACK_EXPAND_WIDGET);
widget_en_cours = &w;
}
void MyFrame::remove()
{
if(widget_en_cours != nullptr)
Gtk::VBox::remove(*widget_en_cours);
}
void VueDetachable::maj_langue()
{
std::string ctrl_nom = controle->titre.get_localized();
wnd.set_title(ctrl_nom);
drag_frame.set_titre(ctrl_nom);
controle->maj_langue();
}
VueDetachable::VueDetachable(Controle *controle, MainDock *main_dock)
{
this->main_dock = main_dock;
doc_en_cours = 0;
docquee = false;
expose = false;
this->controle = controle;
controle->widget->show_all();
docquable = controle->modele.get_attribute_as_boolean("docable");
std::string ctrl_id = controle->titre.get_id();
std::string ctrl_nom = controle->titre.get_localized();
infos("Création vue détachable pour controle [%s] [%s]...", ctrl_id.c_str(), ctrl_nom.c_str());
visible = false;
wnd.set_title(ctrl_nom);
drag_frame.set_titre(ctrl_nom);
//if(docquable)
//wnd.set_decorated(false);
drag_frame.b_dedocquer.signal_clicked().connect(sigc::mem_fun(*this, &VueDetachable::gere_dedocquage));
drag_frame.b_fermer.signal_clicked().connect(sigc::mem_fun(*this, &VueDetachable::gere_fermeture));
if(docquable)
drag_frame.add(*(controle->widget));
std::vector<Gtk::TargetEntry> cibles;
cibles.push_back( Gtk::TargetEntry("STRING") );
cibles.push_back( Gtk::TargetEntry("text/plain") );
drag_frame.drag_source_set(cibles);
drag_frame.drag_source_add_text_targets();
drag_frame.signal_drag_data_get().connect(sigc::mem_fun(*this,
&VueDetachable::gere_drag_data_get));
controle->widget->drag_source_set(cibles);
controle->widget->drag_source_add_text_targets();
controle->widget->signal_drag_data_get().connect(sigc::mem_fun(*this,
&VueDetachable::gere_drag_data_get));
controle->widget->signal_drag_motion().connect(sigc::mem_fun(*this,
&VueDetachable::gere_drag_motion));
controle->widget->signal_draw().connect(sigc::mem_fun(*this, &VueDetachable::on_expose_event));
wnd.signal_delete_event().connect(sigc::mem_fun(*this, &VueDetachable::gere_evt_delete));
//controle->widget->drag_source_set_icon(Gtk::StockID("gtk-about"));
//controle->widget->drag_highlight()
}
}}
| 39,610
|
C++
|
.cc
| 1,270
| 26.06378
| 114
| 0.613346
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,977
|
images-selection.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/images-selection.cc
|
/** @file image-selecteur.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "images-selection.hpp"
#include <glibmm.h>
namespace ocvext {
void ImagesSelection::maj_langue()
{
//b_maj.set_label(utils::langue.get_item("b_maj"));
b_suppr_tout.set_label(utils::langue.get_item("b_del_tout"));
b_suppr.set_label(utils::langue.get_item("b_del"));
b_open.set_label(utils::langue.get_item("b_open"));
b_ajout.set_label(utils::langue.get_item("b_ajout"));
fenetre.set_title(utils::langue.get_item("titre-sel"));
}
void ImagesSelection::maj_actif()
{
bool ajout = true, retire = (csel != -1);
if((nmax >= 0) && (images.size() >= (unsigned int) nmax))
ajout = false;
if((nmin >= 0) && (images.size() <= (unsigned int) nmin))
retire = false;
b_ajout.set_sensitive(ajout);//images.size() < );
b_open.set_sensitive(csel != -1);
b_suppr.set_sensitive(retire);
b_suppr_tout.set_sensitive(nmin <= 0);//images.size() > 0);
b_maj.set_sensitive(images.size() > 0);
if((nmin == nmax) && toolbar_est_pleine)
{
toolbar.remove(b_suppr);
toolbar.remove(b_suppr_tout);
toolbar.remove(b_ajout);
toolbar_est_pleine = false;
}
if(!(nmin == nmax) && !toolbar_est_pleine)
{
toolbar.add(b_suppr);
toolbar.add(b_suppr_tout);
toolbar.add(b_ajout);
toolbar_est_pleine = true;
}
}
void ImagesSelection::maj_selection()
{
auto n = images.size();
for(auto i = 0u; i < n; i++)
{
Image &im = images[i];
cv::Scalar color(80,80,80);
if((csel == (int) i) && (n > 1)) // Seulement si plus d'une image
color = cv::Scalar(0,255,0);
cv::rectangle(bigmat,
cv::Rect(im.px - 3, im.py - 3, img_width + 3, img_height + 3),
color, 3);
}
vue.maj(bigmat);
/*pixbuf = Gdk::Pixbuf::create_from_data(bigmat.data,
Gdk::Colorspace::COLORSPACE_RGB,
false,
8,
bigmat.cols,
bigmat.rows,
3 * bigmat.cols);
gtk_image.set(pixbuf);
trace_verbeuse("reshow...");
//this->gtk_image.show();
gtk_image.queue_draw();*/
}
void ImagesSelection::maj_mosaique()
{
infos("maj_mosaique");
int largeur, hauteur;
largeur = vue.get_allocated_width();
hauteur = vue.get_allocated_height();
if((largeur <= 0) || (hauteur <= 0))
return;
infos("w = %d, h = %d", largeur, hauteur);
bigmat = cv::Mat::zeros(cv::Size(largeur,hauteur), CV_8UC3);
infos("bigmat ok.");
# if 0
if((largeur != bigmat.cols) || (height != bigmat.rows))
{
infos("if((width != bigmat.cols) || (hauteur != bigmat.rows))");
bigmat = cv::Mat::zeros(cv::Size(largeur,hauteur), CV_8UC3);
pixbuf = Gdk::Pixbuf::create_from_data(bigmat.data,
Gdk::Colorspace::COLORSPACE_RGB,
false,
8,
bigmat.cols,
bigmat.rows,
3 * bigmat.cols);
gtk_image.set(pixbuf);
}
else
bigmat = cv::Scalar(0);
# endif
auto n = images.size();
infos("n images = %d.", n);
if(n == 0)
{
infos("pas d'image.");
//gtk_image.queue_draw();
return;
}
if((n == 0) || (largeur <= 0) || (hauteur <= 0))
return;
nrows = (unsigned int) floor(sqrt(n));
ncols = (unsigned int) ceil(((float) n) / nrows);
col_width = largeur / ncols;
row_height = hauteur / nrows;
unsigned int txt_height = 0;//30;
img_width = col_width - 6;
img_height = row_height - 6 - txt_height;
trace_verbeuse("nrows=%d, ncols=%d.", nrows, ncols);
//trace_verbeuse("bigmat: %d * %d.")
unsigned int row = 0, col = 0;
for(auto i = 0u; i < n; i++)
{
Image &im = images[i];
im.ix = col;
im.iy = row;
im.px = im.ix * col_width + 3;
im.py = im.iy * row_height + 3;
trace_verbeuse("resize(%d,%d,%d,%d,%d,%d)",
im.px, im.py, col_width, row_height, col_width, row_height);
cv::Mat tmp = im.spec.img.clone();
float ratio_aspect_orig = ((float) tmp.cols) / tmp.rows;
float ratio_aspect_sortie = ((float) img_width) / img_height;
// Doit ajouter du padding vertical
if(ratio_aspect_orig > ratio_aspect_sortie)
{
int hauteur = img_height * ratio_aspect_sortie / ratio_aspect_orig;
int py = im.py + (img_height - hauteur) / 2;
cv::resize(tmp,
bigmat(cv::Rect(im.px, py, img_width, hauteur)),
cv::Size(img_width, hauteur));
}
// Doit ajouter du padding horizontal
else
{
int largeur = img_width * ratio_aspect_orig / ratio_aspect_sortie;
int px = im.px + (img_width - largeur) / 2;
cv::resize(tmp,
bigmat(cv::Rect(px, im.py, largeur, img_height)),
cv::Size(largeur, img_height));
}
col++;
if(col >= ncols)
{
col = 0;
row++;
}
}
maj_selection();
}
void ImagesSelection::on_size_change(Gtk::Allocation &alloc)
{
maj_mosaique();
}
ImagesSelection::ImagesSelection()
{
fs.from_file(utils::get_fixed_data_path() + "/ocvext-schema.xml");
//sets up the window that displays input image.
toolbar_est_pleine = true;
nmin = 0;
nmax = 100;
has_a_video = false;
fenetre.add(vbox);
vbox.pack_start(toolbar, Gtk::PACK_SHRINK);
evt_box.add(vue);
vbox.pack_start(evt_box, Gtk::PACK_EXPAND_WIDGET);
//set_size_request(300,200);
fenetre.set_default_size(450, 300);
csel = -1;
maj_mosaique();
toolbar.add(b_open);
toolbar.add(b_ajout);
toolbar.add(b_suppr);
toolbar.add(b_suppr_tout);
//toolbar.add(b_maj);
b_maj.set_stock_id(Gtk::Stock::REFRESH);
b_suppr_tout.set_stock_id(Gtk::Stock::REMOVE);
b_suppr.set_stock_id(Gtk::Stock::REMOVE);
b_open.set_stock_id(Gtk::Stock::OPEN);
b_ajout.set_stock_id(Gtk::Stock::ADD);
maj_langue();
maj_actif();
fenetre.show_all_children(true);
evt_box.set_can_focus(true);
evt_box.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
evt_box.signal_button_press_event().connect(
sigc::mem_fun(*this,
&ImagesSelection::on_b_pressed));
evt_box.signal_button_release_event().connect(
sigc::mem_fun(*this,
&ImagesSelection::on_b_released));
evt_box.signal_key_release_event().connect(
sigc::mem_fun(*this,
&ImagesSelection::on_k_released));
/*gtk_image.signal_size_allocate().connect(
sigc::mem_fun(*this,
&ImagesSelection::on_size_change));*/
b_open.signal_clicked().connect(sigc::mem_fun(*this,
&ImagesSelection::on_b_open));
b_ajout.signal_clicked().connect(sigc::mem_fun(*this,
&ImagesSelection::on_b_add));
b_suppr.signal_clicked().connect(sigc::mem_fun(*this,
&ImagesSelection::on_b_del));
b_suppr_tout.signal_clicked().connect(sigc::mem_fun(*this,
&ImagesSelection::on_b_del_tout));
b_maj.signal_clicked().connect(sigc::mem_fun(*this,
&ImagesSelection::on_b_maj));
std::vector<Gtk::TargetEntry> listTargets;
listTargets.push_back(Gtk::TargetEntry("text/uri-list"));
fenetre.drag_dest_set(listTargets, Gtk::DEST_DEFAULT_MOTION | Gtk::DEST_DEFAULT_DROP, Gdk::ACTION_COPY | Gdk::ACTION_MOVE);
fenetre.signal_drag_data_received().connect(sigc::mem_fun(*this, &ImagesSelection::on_dropped_file));
}
void ImagesSelection::on_dropped_file(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time)
{
if ((selection_data.get_length() >= 0) && (selection_data.get_format() == 8))
{
std::vector<Glib::ustring> file_list;
file_list = selection_data.get_uris();
for(auto i = 0u; i < file_list.size(); i++)
{
Glib::ustring path = Glib::filename_from_uri(file_list[i]);
std::string s = path;
infos("DnD: %s.", s.c_str());
if(this->images.size() == 0)
{
ajoute_fichier(s);
}
else
{
if(csel == -1)
set_fichier(0, s);
else
set_fichier(csel, s);
}
}
context->drag_finish(true, false, time);
return;
}
context->drag_finish(false, false, time);
}
bool ImagesSelection::has_video()
{
return has_a_video;
}
void ImagesSelection::get_entrees(std::vector<SpecEntree> &liste)
{
liste.clear();
for(auto i: images)
liste.push_back(i.spec);
}
void ImagesSelection::get_video_list(std::vector<std::string> &list)
{
list.clear();
for(auto i: images)
list.push_back(i.spec.chemin);
}
unsigned int ImagesSelection::get_nb_images() const
{
return images.size();
}
void ImagesSelection::get_list(std::vector<cv::Mat> &list)
{
list.clear();
for(auto i: images)
list.push_back(i.spec.img);
}
void ImagesSelection::maj_has_video()
{
has_a_video = false;
for(auto i: images)
if(i.spec.is_video())
has_a_video = true;
}
void ImagesSelection::set_fichier(int idx, std::string s)
{
if(s.size() == 0)
return;
trace_verbeuse("set [#%d <- %s]...", idx, s.c_str());
Image &img = images[idx];
img.spec.chemin = s;
std::string dummy;
utils::files::split_path_and_filename(s, dummy, img.nom);
std::string ext = utils::files::get_extension(img.nom);
img.nom = utils::files::remove_extension(img.nom);
if((ext == "mpg") || (ext == "avi") || (ext == "mp4") || (ext == "wmv"))
{
img.spec.type = SpecEntree::TYPE_VIDEO;
cv::VideoCapture vc(s);
if(!vc.isOpened())
{
utils::mmi::dialogs::affiche_erreur("Error",
"Error while loading video",
"Maybe the video format is not supported.");
return;
}
// Lis seulement la première image
vc >> img.spec.img;
vc.release();
}
else if((s.size() == 1) && (s[0] >= '0') && (s[0] <= '9'))
{
img.spec.type = SpecEntree::TYPE_WEBCAM;
int camnum = s[0] - '0';
img.spec.id_webcam = camnum;
img.spec.chemin = "Webcam " + utils::str::int2str(camnum);
cv::VideoCapture vc(camnum);
if(!vc.isOpened())
{
utils::mmi::dialogs::affiche_erreur("Error",
"Error while connecting to webcam",
"Maybe the webcam is not supported or is already used in another application.");
return;
}
// Lis seulement la première image
vc >> img.spec.img;
vc.release();
}
else
{
img.spec.type = SpecEntree::TYPE_IMG;
img.spec.img = cv::imread(s);
if(img.spec.img.data == nullptr)
{
utils::mmi::dialogs::affiche_erreur("Error",
"Error while loading image",
"Maybe the image format is not supported.");
return;
}
}
csel = idx;
maj_has_video();
maj_mosaique();
maj_actif();
if(nmax == 1)
on_b_maj();
}
void ImagesSelection::ajoute_photo(const cv::Mat &I)
{
images.resize(images.size() + 1);
utils::model::Node mod(fs.get_schema("media-schema"));
auto &img = images[images.size() - 1];
//mod.set_attribute("default-path", s);
img.modele = mod;
//set_fichier(images.size() - 1, s);
img.spec.type = SpecEntree::TYPE_IMG_RAM;
img.spec.img = I;
csel = images.size() - 1;
maj_has_video();
maj_mosaique();
maj_actif();
if(nmax == 1)
on_b_maj();
}
// Ajoute_fichier: accès externe = déf img par défaut
// accès interne = déf nv img
void ImagesSelection::ajoute_fichier(std::string s)
{
if(s.size() == 0)
return;
trace_verbeuse("Ajout [%s]...", s.c_str());
images.resize(images.size() + 1);
utils::model::Node mod(fs.get_schema("media-schema"));
mod.set_attribute("default-path", s);
images[images.size() - 1].modele = mod;
set_fichier(images.size() - 1, s);
}
std::string ImagesSelection::media_open_dialog(utils::model::Node mod)
{
//auto mod = create_default_model();
if(utils::mmi::NodeDialog::display_modal(mod))
return "";
int sel = mod.get_attribute_as_int("sel");
if(sel == 0)
{
// image par défaut
return mod.get_attribute_as_string("default-path");
}
else if(sel == 1)
{
// Fichier
return mod.get_attribute_as_string("file-schema/path");
}
else if(sel == 2)
{
// Caméra
char bf[2];
bf[0] = '0' + mod.get_attribute_as_int("cam-schema/idx");
bf[1] = 0;
return std::string(bf);
}
// URL
return mod.get_attribute_as_string("url-schema/url");
/*name = utils::langue.get_item("wiz0-name");
title = utils::langue.get_item("wiz0-title");
description = utils::langue.get_item("wiz0-desc");*/
}
void ImagesSelection::on_b_add()
{
trace_verbeuse("on b add...");
utils::model::Node mod(fs.get_schema("media-schema"));
ajoute_fichier(media_open_dialog(mod));
maj_actif();
}
void ImagesSelection::on_b_open()
{
trace_verbeuse("on b open...");
if(this->csel != -1)
{
set_fichier(this->csel, media_open_dialog(images[csel].modele));
maj_actif();
}
else
on_b_add();
}
void ImagesSelection::on_b_del()
{
trace_verbeuse("on b del().");
if(csel != -1)
{
trace_verbeuse("del %d...", csel);
images.erase(csel + images.begin(), 1 + csel + images.begin());
if(csel >= (int) images.size())
csel--;
maj_mosaique();
}
maj_actif();
}
void ImagesSelection::on_b_del_tout()
{
trace_verbeuse("on b del tout().");
images.clear();
maj_mosaique();
maj_actif();
}
void ImagesSelection::on_b_maj()
{
trace_verbeuse("on b maj.");
ImagesSelectionRefresh evt;
utils::CProvider<ImagesSelectionRefresh>::dispatch(evt);
}
void ImagesSelection::raz()
{
has_a_video = false;
images.clear();
csel = -1;
maj_mosaique();
}
bool ImagesSelection::on_b_pressed(GdkEventButton *event)
{
unsigned int x = event->x, y = event->y;
trace_verbeuse("bpress %d, %d", x, y);
csel = -1;
for(auto i = 0u; i < images.size(); i++)
{
auto &img = images[i];
if((x > img.px) && (y > img.py)
&& (x < img.px + this->img_width)
&& (y < img.py + this->img_height))
{
csel = i;
break;
}
}
maj_actif();
maj_selection();
return true;
}
bool ImagesSelection::on_b_released(GdkEventButton *event)
{
trace_verbeuse("brel");
evt_box.grab_focus();
return true;
}
bool ImagesSelection::on_k_released(GdkEventKey *event)
{
if(csel == -1)
return false;
if(event->keyval == GDK_KEY_Delete)
{
this->on_b_del();
return true;
}
else if(event->keyval == GDK_KEY_Down)
{
if(csel + ncols < images.size())
{
csel += ncols;
maj_selection();
}
return true;
}
else if(event->keyval == GDK_KEY_Up)
{
infos("Key up.");
if(csel >= (int) ncols)
{
csel -= ncols;
maj_selection();
}
else
infos("Refu: csel = %d, ncols = %d.", csel, ncols);
return true;
}
else if(event->keyval == GDK_KEY_Left)
{
//if(images[csel].ix > 0)
if(csel > 0)
{
csel--;
maj_selection();
}
return true;
}
else if(event->keyval == GDK_KEY_Right)
{
if(/*(images[csel].ix + 1 < ncols) &&*/ (csel + 1 < (int) images.size()))
{
csel++;
maj_selection();
}
return true;
}
return false;
}
}
| 15,883
|
C++
|
.cc
| 542
| 24.52583
| 164
| 0.615704
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,978
|
calib.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/calib.cc
|
#include "calib.hpp"
#include <opencv2/calib3d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>
#include <iostream>
namespace ocvext {
DialogueCalibration::DialogueCalibration()
{
infos("Init dialogue cal...");
prende_photo = false;
fs.from_file(utils::get_fixed_data_path() + "/ocvext-schema.xml");
prm = utils::model::Node(fs.get_schema("cal"));
vue_prm.init(prm);
paned.add1(vue_video);
paned.add2(*(vue_prm.get_gtk_widget()));
paned.set_position(200);
dialogue.add(vbox);
vbox.pack_start(paned, Gtk::PACK_EXPAND_WIDGET);
hbox.set_layout(Gtk::BUTTONBOX_END);
auto img = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL),
Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
b_fermer.set_image(*img);
b_fermer.set_border_width(4);
hbox.pack_end(b_fermer, Gtk::PACK_SHRINK);
b_fermer.signal_clicked().connect(sigc::mem_fun(this, &DialogueCalibration::gere_b_fermer));
//img = new Gtk::Image(Gtk::StockID(Gtk::Stock::EXECUTE),
// Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
//b_photo.set_image(*img);
b_photo.set_label(utils::langue.get_item("cap"));
b_photo.set_border_width(4);
hbox.pack_end(b_photo, Gtk::PACK_SHRINK);
b_photo.signal_clicked().connect(sigc::mem_fun(this, &DialogueCalibration::gere_b_photo));
b_cal.set_label(utils::langue.get_item("cal"));
b_cal.set_border_width(4);
hbox.pack_end(b_cal, Gtk::PACK_SHRINK);
b_cal.signal_clicked().connect(sigc::mem_fun(this, &DialogueCalibration::gere_b_cal));
vbox.pack_start(hbox, Gtk::PACK_SHRINK);
dialogue.set_size_request(800, 600);
dispatcheur.add_listener(this, &DialogueCalibration::gere_evt_gtk);
utils::hal::thread_start(this, &DialogueCalibration::thread_video);
infos("Init dialogue cal ok.");
}
void DialogueCalibration::gere_evt_gtk(const EvtGtk &eg)
{
infos("ev gtk.");
assert(photos.size() > 0);
img_list.ajoute_photo(photos[photos.size() - 1]);
}
void DialogueCalibration::gere_b_fermer()
{
dialogue.hide();
exit(0);
}
void DialogueCalibration::gere_b_photo()
{
infos("Photo...");
prende_photo = true;
}
void DialogueCalibration::gere_b_cal()
{
infos("Calibration...");
cv::Mat matrice_camera, prm_dist;
std::vector<cv::Mat> imgs;
img_list.get_list(imgs);
EtalonnageCameraConfig config;
config.ncolonnes = prm.get_attribute_as_int("nx");
config.nlignes = prm.get_attribute_as_int("ny");
config.largeur_case_cm = prm.get_attribute_as_int("dim");
config.type = (EtalonnageCameraConfig::Type) prm.get_attribute_as_int("sel");
if(etalonner_camera(imgs, config, matrice_camera, prm_dist))
{
avertissement("Echec etalonnage camera.");
utils::mmi::dialogs::affiche_erreur_localisee("echec-etalonnage");
return;
}
auto s = utils::mmi::dialogs::enregistrer_fichier_loc("enreg-cal", "*.yml", "fichier-cal");
if(s.size() == 0)
return;
infos("Svg cal vers [%s]...", s.c_str());
cv::FileStorage fs(s, cv::FileStorage::WRITE);
if(!fs.isOpened())
{
erreur("Echec ouverture fichier.");
return;
}
cv::write(fs, "camera_matrix", matrice_camera);
cv::write(fs, "distortion_coefficients", prm_dist);
infos("Ok.");
}
void DialogueCalibration::thread_video()
{
cv::VideoCapture camera(1);
cv::Mat I;
static unsigned int num_photo = 0;
for(;;)
{
camera >> I;
if(prende_photo)
{
prende_photo = false;
photos.push_back(I);
char buf[400];
sprintf(buf, "c:/dbi/photo-%d.png", num_photo);
cv::imwrite(buf, I);
num_photo++;
EvtGtk eg;
dispatcheur.on_event(eg);
}
vue_video.maj(I);
cv::waitKey(20);
}
}
void DialogueCalibration::affiche()
{
dialogue.set_title("Etalonage caméra");
dialogue.set_position(Gtk::WIN_POS_CENTER);
b_fermer.set_label(utils::langue.get_item("fermer"));
img_list.fenetre.show();
dialogue.show_all_children(true);
//vview.maj(I);
//dialogue.run();
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-0.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-1.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-2.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-3.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-4.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-5.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-6.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-7.png");
img_list.ajoute_fichier("c:/dbi/bic/etal-logitec-bis/photo-8.png");
Gtk::Main::run(dialogue);
}
int etalonner_camera(const std::vector<cv::Mat> &imgs,
const EtalonnageCameraConfig &config,
cv::Mat &matrice_camera, cv::Mat &prm_dist)
{
//int sel = input.model.get_attribute_as_int("sel");
int bw = config.ncolonnes, bh = config.nlignes;
infos("Etalonnage, ncolonnes = %d, nlignes = %d.");
cv::Size board_size(bw,bh);
std::vector<std::vector<cv::Point2f>> points_2d;
std::vector<std::vector<cv::Point3f>> points_3d;
std::vector<cv::Point2f> pointbuf;
unsigned int nb_imgs = imgs.size();
if(nb_imgs == 0)
return -1;
cv::Size resolution = imgs[0].size();
for(auto i = 0u; i < nb_imgs; i++)
{
infos("Analyse image de cal %d / %d...", i + 1, nb_imgs);
//cv::cvtColor(input.images[0], Ig, CV_BGR2GRAY);
//output.images[2] = cv::Mat(/*Ig.size()*/cv::Size(480,640), CV_8UC3);
auto Ig = imgs[i];
cv::Mat Ig2;
cv::cvtColor(Ig, Ig2, CV_BGR2GRAY);
infos("Resolution = %d * %d", Ig.cols, Ig.rows);
bool trouve;
if(config.type == EtalonnageCameraConfig::DAMIER)
{
infos("Recherche damier...");
trouve = cv::findChessboardCorners(Ig2, board_size, pointbuf,
cv::CALIB_CB_ADAPTIVE_THRESH
| cv::CALIB_CB_FAST_CHECK
| cv::CALIB_CB_NORMALIZE_IMAGE);
// improve the found corners' coordinate accuracy
if(trouve)
{
infos("Coins trouve, amelioration...");
cv::cornerSubPix(Ig2, pointbuf, cv::Size(11,11),
cv::Size(-1,-1), cv::TermCriteria(cv::TermCriteria::EPS+cv::TermCriteria::COUNT, 30, 0.1 ));
infos("ok.");
}
}
else
trouve = cv::findCirclesGrid(Ig, board_size, pointbuf );
//cvtColor(I, O[0], CV_GRAY2BGR);
//Mat Ior = input.images[0].clone();
//output.images[0] = Ior.clone();
//if(trouve)
//cv::drawChessboardCorners(output.images[0], board_size, Mat(pointbuf), trouve);
trace_majeure("Trouvé %d coins (found = %d).",
pointbuf.size(), (int) trouve);
if(trouve)
{
float square_size = 1;
std::vector<cv::Point3f> corners;
for(int i = 0; i < board_size.height; i++)
for( int j = 0; j < board_size.width; j++ )
corners.push_back(cv::Point3f(float(j*square_size),
float(i*square_size),
0));
points_3d.push_back(corners);
points_2d.push_back(pointbuf);
} // si trouve
} // for i
if(points_3d.size() == 0)
{
avertissement("Aucune mire trouvee.");
return -1;
}
matrice_camera = cv::Mat::eye(3, 3, CV_64F);
//if( flags & CALIB_FIX_ASPECT_RATIO )
// cameraMatrix.at<double>(0,0) = aspectRatio;
prm_dist = cv::Mat::zeros(8, 1, CV_64F);
std::vector<cv::Mat> rvecs, tvecs;
double rms = cv::calibrateCamera(points_3d,
points_2d, resolution,
matrice_camera, prm_dist, rvecs, tvecs,
cv::CALIB_FIX_K4 | cv::CALIB_FIX_K5);
infos("RMS error reported by calibrateCamera: %g\n", rms);
//cv::undistort(Ior, output.images[1], cameraMatrix, distCoeffs);
/*Size sz = Ior.size();
sz.height = sz.width = max(sz.width, sz.height);
sz.height = sz.width = max(sz.width, 500);
output.images[2] = cv::Mat::zeros(sz, CV_8UC3);*/
double fovx, fovy, focal, ar;
cv::Point2d ppoint;
cv::calibrationMatrixValues(matrice_camera, resolution, 1, 1, fovx, fovy, focal, ppoint, ar);
infos("Matrice camera: ");
std::cout << matrice_camera << "\n";
infos("Focal : %.2f, %.2f, %.2f\n", (float) fovx, (float) fovy, (float) focal);
infos("Point principal: %.2f, %.2f\n", (float) ppoint.x, (float) ppoint.y);
/*Mat tmp = output.images[2].clone();
cv::namedWindow("essai", CV_WINDOW_NORMAL);
cv::imshow("essai", tmp);
cv::waitKey();*/
//bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
//totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
// rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
return 0;
}
}
| 8,675
|
C++
|
.cc
| 232
| 32.366379
| 105
| 0.648377
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,979
|
hough.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/hough.cc
|
/** @file hough.cc
* @brief Hough transform / using gradient
* @author J.A. / 2015 / www.tsdconseil.fr
* @license LGPL V 3.0 */
#include "hough.hpp"
#include "gl.hpp"
#include <cmath>
#include <iostream>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
namespace ocvext
{
///** Hough transform using gradient matrix */
//template<typename Tin>
//void hough_gradient_template(const cv::Mat &g_abs,
// const cv::Mat &g_angle,
// cv::Mat &res,
// float rho_res, float theta_res)
//{
// int ntheta = (int) ceil(2 * CV_PI / theta_res);
// uint16_t sx = g_abs.cols, sy = g_abs.rows;
// int rmax = (int) std::ceil(std::sqrt(sx*sx+sy*sy) / rho_res);
// cv::Mat acc = cv::Mat::zeros(ntheta, rmax, CV_32F);
//
// for(int y = 0; y < sy; y++)
// {
// for(int x = 0; x < sx; x++)
// {
// float gnorm = (float) g_abs.at<Tin>(y,x);
// float theta = (float) g_angle.at<Tin>(y,x);
//
// int rho = (int) std::round((x * std::cos(theta) + y * std::sin(theta)) / rho_res);
// if(rho < 0)
// {
// rho = -rho;
// theta = theta + CV_PI;
// if(theta > 2 * CV_PI)
// theta -= 2 * CV_PI;
// }
// if(rho >= rmax)
// rho = rmax - 1;
//
// int ti = std::floor((ntheta * theta) / (2 * CV_PI));
// acc.at<float>(ti, rho) += (float) gnorm;
// } // i
// } //j
// cv::normalize(acc, res, 0, 255.0, cv::NORM_MINMAX);
//}
template<typename Tin>
void hough_gradient_template(const cv::Mat &g_abs,
const cv::Mat &g_angle,
cv::Mat &res,
float rho_res, float theta_res)
{
int ntheta = (int) ceil(CV_PI / theta_res);
uint16_t sx = g_abs.cols, sy = g_abs.rows;
int rmax = (int) std::ceil(std::sqrt(sx*sx+sy*sy) / rho_res);
cv::Mat acc = cv::Mat::zeros(ntheta, 2*rmax+1, CV_32F);
for(int y = 0; y < sy; y++)
{
for(int x = 0; x < sx; x++)
{
float gnorm = (float) g_abs.at<Tin>(y,x);
float theta = (float) g_angle.at<Tin>(y,x);
if(theta < 0)
theta += 2 * CV_PI;
if(theta >= CV_PI)
theta -= CV_PI;
assert(theta >= 0);
assert(theta < CV_PI);
int rho = (int) std::round((x * std::cos(theta) + y * std::sin(theta)) / rho_res);
assert(rho >= -rmax);
assert(rho <= rmax);
int ti = std::floor((ntheta * theta) / CV_PI);
acc.at<float>(ti, rho + rmax) += (float) gnorm;
} // i
} //j
cv::normalize(acc, res, 0, 255.0, cv::NORM_MINMAX);
}
/** Hough transform using gradient matrix */
template<typename Tin>
void hough_no_gradient_template(const cv::Mat &gradient_abs,
cv::Mat &res,
float rho_res, float theta_res)
{
unsigned int ntheta = (int) ceil(CV_PI / theta_res);
uint16_t sx = gradient_abs.cols, sy = gradient_abs.rows;
int i, j;
// CEIL
int cx = (sx >> 1) + (sx & 1);
int cy = (sy >> 1) + (sy & 1);
int rmax = (int) std::ceil(std::sqrt(sx*sx+sy*sy)/2);
signed short rho;
unsigned int nrho = 2*rmax/rho_res+1;
res = cv::Mat::zeros(cv::Size(ntheta, nrho), CV_32F);
for(j = 0; j < sy; j++)
{
int y = j - cy;
const float *gptr = gradient_abs.ptr<float>(j);
for(i = 0; i < sx; i++)
{
int x = i - cx;
float gnorm = *gptr++;//gradient_abs.at<Tin>(i,j);
for(auto k = 0u; k < (unsigned int) ntheta; k++)
{
float theta = (k * CV_PI) / ntheta;
rho = (int) std::round((x * std::cos(theta) + y * std::sin(theta)) / rho_res);
int ri = (rmax / rho_res) + rho;
if(ri >= (int) nrho)
ri = nrho -1;
if(ri < 0)
ri = 0;
res.at<float>(k,ri) += gnorm;
}
} // i
printf("j = %d.\n", j); fflush(0);
} //j
cv::normalize(res, res, 0, 255.0, cv::NORM_MINMAX);
}
void HoughWithGradientDir(const cv::Mat &g_abs,
const cv::Mat &g_angle,
cv::Mat &res,
float rho, float theta)
{
auto type = g_abs.depth();
switch(type)
{
case CV_32F:
hough_gradient_template<float>(g_abs, g_angle, res, rho, theta);
break;
case CV_16S:
hough_gradient_template<int16_t>(g_abs, g_angle, res, rho, theta);
break;
default:
std::cerr << "hough_gradient: type non supporté (" << type << ")." << std::endl;
CV_Assert(0);
}
}
void Hough_with_gradient_dir(const cv::Mat &img,
cv::Mat &res,
float rho_res,
float theta_res,
float gamma,
bool use_deriche)
{
cv::Mat gris = img, gx, gy, mag, angle;
if(img.channels() != 1)
cv::cvtColor(img, gris, CV_BGR2GRAY);
if(use_deriche)
{
Deriche_gradient(gris, gx, gy, gamma);
}
else
{
//cv::GaussianBlur(I, lissee, cv::Size(7,7), 2, 2);
cv::Sobel(gris, gx, CV_32F, 1, 0, 3);
cv::Sobel(gris, gy, CV_32F, 0, 1, 3);
}
cv::cartToPolar(gx, gy, mag, angle);
cv::normalize(mag, mag, 0, 1.0, cv::NORM_MINMAX);
HoughWithGradientDir(mag, angle, res, rho_res, theta_res);
}
void Hough_without_gradient_dir(const cv::Mat &img,
cv::Mat &res,
float rho_res,
float theta_res,
float gamma)
{
cv::Mat gris = img, gx, gy, mag, angle;
if(img.channels() != 1)
cv::cvtColor(img, gris, CV_BGR2GRAY);
printf("deriche...\n"); fflush(0);
Deriche_gradient(gris, gx, gy, gamma);
cv::cartToPolar(gx, gy, mag, angle);
cv::normalize(mag, mag, 0, 1.0, cv::NORM_MINMAX);
printf("template...\n"); fflush(0);
hough_no_gradient_template<float>(mag, res, rho_res, theta_res);
printf("ok.\n"); fflush(0);
}
/** Top hat filter (band-pass) approximation using Deriche
* exponential filter */
static void my_top_hat(const cv::Mat &I, cv::Mat &O,
float g1, float g2)
{
cv::Mat If1, If2;
Deriche_blur(I, If1, g1);
Deriche_blur(I, If2, g2);
O = cv::abs(If1 - If2); // Passe bas (haute fréq) - Passe bas (basse fréq)
}
#define dbgsave(XX,YY)
/*static void dbgsave(const std::string &name, const cv::Mat &I)
{
cv::Mat O;
cv::normalize(I, O, 0, 255.0, cv::NORM_MINMAX);
cv::imwrite(name, O);
}*/
void Hough_lines_with_gradient_dir(const cv::Mat &img,
std::vector<cv::Vec2f> &lines,
cv::Mat &debug,
float rho_res,
float theta_res,
float gamma,
float seuil)
{
cv::Mat prm, mask, mask2, mask3;
//dbgsave("build/0-entree.png", img);
Hough_with_gradient_dir(img, prm, rho_res, theta_res, gamma);
debug = prm.clone();
//dbgsave("build/1-hough.png", prm);
my_top_hat(prm, prm, 0.2, 0.6);
cv::normalize(prm, prm, 0, 1.0, cv::NORM_MINMAX);
//dbgsave("build/2-tophat.png", prm);
cv::threshold(prm, prm, seuil, 0, cv::THRESH_TOZERO);
dbgsave("build/3-seuil.png", prm);
cv::Mat K = cv::getStructuringElement(cv::MORPH_RECT,
cv::Size(7, 7)/*
cv::Point(1, 1)*/);
cv::Mat mask_max, mask_min;
cv::dilate(prm, mask_max, K);
cv::erode(prm, mask_min, K);
// On veut >= max dans le voisinage
// Mais aussi > au min dans le voisinage
cv::compare(prm, mask_max, mask2, cv::CMP_GE);
cv::compare(prm, mask_min, mask3, cv::CMP_GT);
mask2 &= mask3;
dbgsave("build/4-locmax.png", mask2);
cv::Mat locations; // output, locations of non-zero pixels
cv::findNonZero(mask2, locations);
unsigned int sx = img.cols, sy = img.rows;
int rmax = (int) std::ceil(std::sqrt(sx*sx+sy*sy) / rho_res);
for(auto i = 0u; i < locations.total(); i++)
{
int ri = locations.at<cv::Point>(i).x;
int ti = locations.at<cv::Point>(i).y;
float theta = ti * theta_res;
float rho = ri - rmax;
cv::Vec2f line(rho, theta);
lines.push_back(line);
}
debug.convertTo(debug, CV_8U);
cvtColor(debug, debug, CV_GRAY2BGR);
for(auto i = 0u; i < locations.total(); i++)
{
cv::Point p = locations.at<cv::Point>(i);
cv::circle(debug, p, 5, cv::Scalar(100,255,100), 1, CV_AA);
}
}
}
| 8,330
|
C++
|
.cc
| 248
| 27.596774
| 90
| 0.54161
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,980
|
fourier.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/fourier.cc
|
#include "fourier.hpp"
#include "cutil.hpp"
#include "opencv2/imgproc.hpp"
#include <assert.h>
#include "../include/ocvext.hpp"
namespace ocvext
{
void translation_rapide(const cv::Mat &I, cv::Mat &O,
int decx, int decy,
const cv::Size &dim_sortie,
const cv::Scalar &bg)
{
O.create(dim_sortie, I.type());
// decx > 0 => image décalée à droite
// Deux rectangle de même dimension
cv::Rect rdst, rsrc;
// A priori, on prend tout
rsrc.x = 0;
rsrc.y = 0;
rsrc.width = I.cols;
rsrc.height = I.rows;
rdst.x = decx;
rdst.y = decy;
rdst.width = O.cols - rdst.x;
rdst.height = O.rows - rdst.y;
if(rdst.x + rdst.width >= O.cols)
{
rdst.width = O.cols - 1 - rdst.x;
}
if(rdst.y + rdst.height >= O.rows)
{
rdst.height = O.rows - 1 - rdst.y;
}
// Maintenant on adapte les rectangles
if(rdst.x < 0)
{
rsrc.x -= rdst.x;
rsrc.width += rdst.x;
rdst.x = 0;
}
if(rdst.y < 0)
{
rsrc.y -= rdst.y;
rsrc.height += rdst.y;
rdst.y = 0;
}
if(rdst.x + rdst.width >= O.cols)
{
rdst.width = O.cols - 1 - rdst.x;
}
if(rdst.y + rdst.height >= O.rows)
{
rdst.height = O.rows - 1 - rdst.y;
}
if(rdst.width > rsrc.width)
{
rdst.width = rsrc.width;
}
if(rdst.width < rsrc.width)
{
rsrc.width = rdst.width;
}
if(rdst.height > rsrc.height)
{
rdst.height = rsrc.height;
}
if(rdst.height < rsrc.height)
{
rsrc.height = rdst.height;
}
O.setTo(bg);
//infos("src=%d,%d,%d,%d dst=%d,%d,%d,%d", rsrc.x,rsrc.y,rsrc.width,rsrc.height)
if(rsrc.width * rsrc.height > 0)
{
//infos("copyto: src = (%d,%d)[%d,%d,%d,%d], dst = (%d,%d)[%d,%d,%d,%d]...",
// I.cols, I.rows, rsrc.x,rsrc.y,rsrc.width,rsrc.height,
// O.cols, O.rows, rdst.x,rdst.y,rdst.width,rdst.height);
I(rsrc).copyTo(O(rdst));
//infos("ok.");
}
//O(rdst) = I(rsrc);
}
void translation(const cv::Mat &I, cv::Mat &O, int offsetx, int offsety,const cv::Scalar &bg)
{
cv::Mat H = (cv::Mat_<double>(2,3) << 1, 0, offsetx, 0, 1, offsety);
cv::warpAffine(I,O,H,I.size(),cv::INTER_CUBIC,cv::BORDER_CONSTANT, bg);
}
void dft_shift(cv::Point &p, const cv::Size &dim)
{
if(p.x < dim.width/2)
p.x = p.x + dim.width/2;
else
p.x = dim.width/2 - (dim.width - p.x);
if(p.y < dim.height/2)
p.y = p.y + dim.height/2;
else
p.y = dim.height/2 - (dim.height - p.y);
}
void dft_shift(cv::Mat &mag)
{
// crop the spectrum, if it has an odd number of rows or columns
mag = mag(cv::Rect(0, 0, mag.cols & -2, mag.rows & -2));
// rearrange the quadrants of Fourier image so that the origin is at the image center
int cx = mag.cols/2;
int cy = mag.rows/2;
cv::Mat q0(mag, cv::Rect(0, 0, cx, cy)); // Top-Left - Create a ROI per quadrant
cv::Mat q1(mag, cv::Rect(cx, 0, cx, cy)); // Top-Right
cv::Mat q2(mag, cv::Rect(0, cy, cx, cy)); // Bottom-Left
cv::Mat q3(mag, cv::Rect(cx, cy, cx, cy)); // Bottom-Right
cv::Mat tmp; // swap quadrants (Top-Left with Bottom-Right)
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);
q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
q2.copyTo(q1);
tmp.copyTo(q2);
}
void ift_shift(cv::Mat &mag)
{
// crop the spectrum, if it has an odd number of rows or columns
mag = mag(cv::Rect(0, 0, mag.cols & -2, mag.rows & -2));
// rearrange the quadrants of Fourier image so that the origin is at the image center
int cx = mag.cols/2;
int cy = mag.rows/2;
cv::Mat q0(mag, cv::Rect(0, 0, cx, cy)); // Top-Left - Create a ROI per quadrant
cv::Mat q1(mag, cv::Rect(cx, 0, cx, cy)); // Top-Right
cv::Mat q2(mag, cv::Rect(0, cy, cx, cy)); // Bottom-Left
cv::Mat q3(mag, cv::Rect(cx, cy, cx, cy)); // Bottom-Right
cv::Mat tmp; // swap quadrants (Top-Left with Bottom-Right)
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);
q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
q2.copyTo(q1);
tmp.copyTo(q2);
}
cv::Point detection_translation2(const cv::Mat &I0_, const cv::Mat &I1_)
{
cv::Mat I0 = I0_, I1 = I1_;
unsigned int nchn = I0.channels();
cv::Mat accu = cv::Mat::zeros(I0.size(), CV_32F);
dbg_image("I0", I0, true);
dbg_image("I1", I1, true);
cv::Mat F0, F1, M, C;
cv::dft(I0, F0, cv::DFT_COMPLEX_OUTPUT);
cv::dft(I1, F1, cv::DFT_COMPLEX_OUTPUT);
cv::mulSpectrums(F0, F1, M, 0, true);
cv::dft(M, C, cv::DFT_REAL_OUTPUT | cv::DFT_INVERSE);
C = cv::abs(C);
dbg_image("TC", C, true);
accu = C;
cv::Point max_loc;
cv::minMaxLoc(accu, nullptr, nullptr, nullptr, &max_loc, cv::Mat());
{
cv::Mat spectre = accu.clone();
cv::normalize(spectre, spectre, 0, 255, cv::NORM_MINMAX);
spectre.convertTo(spectre, CV_8U);
cv::cvtColor(spectre, spectre, CV_GRAY2BGR);
dft_shift(spectre);
cv::Point p = max_loc;
ocvext::dft_shift(p, spectre.size());
cv::line(spectre, cv::Point(spectre.cols/2-10, spectre.rows/2), cv::Point(spectre.cols/2+10, spectre.rows/2), cv::Scalar(0,255,0), 1, CV_AA);
cv::line(spectre, cv::Point(spectre.cols/2, spectre.rows/2-10), cv::Point(spectre.cols/2, spectre.rows/2+10), cv::Scalar(0,255,0), 1, CV_AA);
cv::circle(spectre, p, 10, cv::Scalar(0,0,255), 1, CV_AA);
dbg_image("accu", spectre);
}
if(max_loc.x > accu.cols / 2)
max_loc.x = -(accu.cols - max_loc.x);
if(max_loc.y > accu.rows / 2)
max_loc.y = -(accu.rows - max_loc.y);
max_loc = -max_loc;
infos("Translation detectee : %d, %d", max_loc.x, max_loc.y);
return max_loc;
}
#if 0
int transformee_log_polaire(const cv::Mat &I, cv::Mat &O,
unsigned int npas_angle, float rmin, unsigned int npas_rayon)
{
uint16_t sx = I.cols, sy = I.rows;
O.create(cv::Size(npas_rayon,npas_angle), CV_32F);
O.setTo(cv::Scalar(0));
cv::Mat src = I.clone();
float rmax = (std::min(I.cols,I.rows) * 0.5f);
float raison = std::pow(rmax / rmin, 1.0f / npas_rayon);
infos("npas rayon = %d, rmin = %f, rmax = %f, raison = %f", npas_rayon, rmin, rmax, raison);
cv::Mat X(sy,sx,CV_32F), Y(sy,sx,CV_32F);
for(auto y = 0u; y < sy; y++)
{
for(auto x = 0u; x < sx; x++)
{
X.at<float>(y,x) = ((float) x) - sx*0.5;
Y.at<float>(y,x) = ((float) y) - sy*0.5;
}
}
cv::Mat D, A;
cv::cartToPolar(X, Y, D, A);
float rayon = rmin;
for(auto i = 0u; i < npas_rayon; i++)
{
float r;
// On va remplir la colone "i" de la matrice (rayon)
// On cherche dans la matrice d'entrée tous les pixels
// situés à une distance du centre comprise entre rayon et rayon*raison
auto masque = (D >= rayon) && (D < rayon * raison);
// Il faut écrire un vecteur de taille "npas_angle" avec l'énergie suivant les différentes bandes angulaires
// Comment gérer le sous-échantillonnage pour les petits rayons ????
// ==> Idée : on accumule bêtement, et on filtre après
// Gain d'accu : I, position : A
/*for(auto j = 0u; j < npas_angle; j++)
{
}*/
rayon *= raison;
}
return 0;
}
#endif
int detection_rotation_echelle(const cv::Mat &I0, const cv::Mat &I1, float &angle, float &echelle)
{
cv::Mat I[2], maglp[2];
I[0] = I0;
I[1] = I1;
ocvext::dbg_image("I0", I0);
ocvext::dbg_image("I1", I1);
for(auto i = 0u; i < 2; i++)
{
cv::Mat F, plans[2], mag;
cv::dft(I[i], F, cv::DFT_COMPLEX_OUTPUT);
cv::split(F, plans);
cv::magnitude(plans[0], plans[1], mag);
ocvext::dft_shift(mag);
cv::Mat tmp;
cv::log(mag + 0.1, tmp);
ocvext::dbg_image("mag", tmp, true);
//cv::linearPolar(mag, maglp[i], cv::Point(mag.cols/2, mag.rows/2), mag.cols/2, cv::INTER_CUBIC);
// Log polar : le changement d'échelle devient une simple translation.
cv::logPolar(mag, maglp[i], cv::Point(mag.cols/2, mag.rows/2), mag.cols/2, cv::INTER_CUBIC);
cv::log(maglp[i] + 0.1, tmp);
ocvext::dbg_image("linpol", tmp, true);
}
//cv::Mat bmaglp[2];
//cv::waitKey()
//cv::copyMakeBorder(maglp[0], bmaglp[0], 128, 128, 128, 128, cv::BORDER_CONSTANT);
//cv::copyMakeBorder(maglp[1], bmaglp[1], 128, 128, 128, 128, cv::BORDER_CONSTANT);
ocvext::dbg_image("maglop0-avant-pond", maglp[0], true);
ocvext::dbg_image("maglop1-avant-pond", maglp[1], true);
//ocvext::dbg_image("maglop-apres-bord", bmaglp[0], true);
/*cv::log(bmaglp[0] + 0.01, bmaglp[0]);
cv::log(bmaglp[1] + 0.01, bmaglp[1]);*/
for(auto j = 0u; j < maglp[0].cols; j++)
{
cv::Rect r(j,0,1,maglp[0].rows);
float coef = std::pow(((float) j) / maglp[0].cols, 2);
maglp[0](r) *= coef;
maglp[1](r) *= coef;
}
ocvext::dbg_image("maglop0-pond", maglp[0], true);
ocvext::dbg_image("maglop1-pond", maglp[1], true);
cv::Point pt = ocvext::detection_translation2(maglp[0], maglp[1]);
infos("translation domaine polaire : %d, %d", pt.x, pt.y);
float ntheta = maglp[0].rows;
// pt.y == rows/2 => 180°
// pt.y
angle = - (CV_PI * ((float) pt.y) / (ntheta / 2));
if(angle > CV_PI/2)
angle -= CV_PI;
float M = maglp[0].cols/2;
echelle = std::exp(((float) - pt.x) / (M));
infos("Angle = %.1f degres, echelle = %.2f.", angle * 180 / 3.1415926, echelle);
return 0;
}
cv::Point detection_translation(const cv::Mat &I0_, const cv::Mat &I1_, bool normaliser_spectre, cv::Mat *spectre)
{
cv::Mat I0 = I0_, I1 = I1_;
assert(I0.size() == I1.size());
assert(I0.type() == I1.type());
infos("dim img = %d, %d", I0.cols, I0.rows);
if(I0.type() != CV_32F)
{
I0.convertTo(I0, CV_32F);
I1.convertTo(I1, CV_32F);
}
/*cv::normalize(I0, I0, 0, 1, cv::NORM_MINMAX);
cv::normalize(I1, I1, 0, 1, cv::NORM_MINMAX);*/
unsigned int nchn = I0.channels();
cv::Mat accu = cv::Mat::zeros(I0.size(), CV_32F);
cv::Mat I0s[3], I1s[3];
dbg_image("I0", I0, true);
dbg_image("I1", I1, true);
//if(nchn > 1)
{
cv::split(I0, I0s);
cv::split(I1, I1s);
}
for(auto i = 0u; i < nchn; i++)
{
/*dbg_image("I0s", I0s[i], true);
dbg_image("I1s", I1s[i], true);*/
/*cv::normalize(I0s[i], I0s[i], -1, 1, cv::NORM_MINMAX);
cv::normalize(I1s[i], I1s[i], -1, 1, cv::NORM_MINMAX);*/
cv::Mat F0, F1, M, C;
cv::dft(I0s[i], F0, cv::DFT_COMPLEX_OUTPUT);
cv::dft(I1s[i], F1, cv::DFT_COMPLEX_OUTPUT);
cv::mulSpectrums(F0, F1, M, 0, true);
// Est-ce vraiment nécessaire ?
if(normaliser_spectre)
{
for(auto y = 0u; y < (unsigned int) M.rows; y++)
{
for(auto x = 0u; x < (unsigned int) M.cols; x++)
{
cv::Vec2f &p = M.at<cv::Vec2f>(y,x);
float nrm = sqrt(p[0] * p[0] + p[1] * p[1]);
if(nrm > 0)
{
p[0] /= nrm;
p[1] /= nrm;
}
}
}
}
cv::dft(M, C, cv::DFT_REAL_OUTPUT | cv::DFT_INVERSE);
C = cv::abs(C);
dbg_image("TC", C, true);
accu += C;
}
/*cv::Mat tmp;
if(ocvext::est_debogage_actif())
{
cv::GaussianBlur(accu, tmp, cv::Size(9,9),0,0);
dbg_image("TCB", tmp, true);
}*/
cv::Point max_loc;
cv::minMaxLoc(accu, nullptr, nullptr, nullptr, &max_loc, cv::Mat());
if(spectre != nullptr)
{
*spectre = accu.clone();
cv::normalize(*spectre, *spectre, 0, 255, cv::NORM_MINMAX);
spectre->convertTo(*spectre, CV_8U);
cv::cvtColor(*spectre, *spectre, CV_GRAY2BGR);
dft_shift(*spectre);
cv::Point p = max_loc;
ocvext::dft_shift(p, spectre->size());
cv::circle(*spectre, p, 10, cv::Scalar(0,0,255), 1, CV_AA);
}
if(max_loc.x > accu.cols / 2)
max_loc.x = -(accu.cols - max_loc.x);
if(max_loc.y > accu.rows / 2)
max_loc.y = -(accu.rows - max_loc.y);
max_loc = -max_loc;
infos("Translation detectee : %d, %d", max_loc.x, max_loc.y);
return max_loc;
}
#define DEBOGUER_ESTIM 0
// Conversion coordonnees dans l'espace frequentiel en periode spatiale
static float uv_vers_p(float u, float v, uint16_t sx, uint16_t sy)
{
return 1.0 / sqrt((u/sx)*(u/sx)+(v/sy)*(v/sy));
}
static void p_vers_uv(float p, uint16_t sx, uint16_t sy, float &u, float &v)
{
u = sx / p;
v = sy / p;
}
static inline float sqr(float x)
{
return x * x;
}
int estime_periode(cv::Mat &I,
float &d, float &indice_confiance,
float dmin, float dmax,
cv::Mat *dbg)
{
# if DEBOGUER_ESTIM
infos("dmin = %.1f, dmax = %.1f.", dmin, dmax);
ocvext::dbg_image("patch", I, true);
# endif
I -= cv::mean(I)[0];
cv::Mat W, F, plans[2], mag;
cv::createHanningWindow(W, I.size(), CV_32F);
I = I.mul(W);
uint16_t sx = I.cols, sy = I.rows;
cv::dft(I, F, cv::DFT_COMPLEX_OUTPUT);
cv::split(F, plans);
cv::magnitude(plans[0], plans[1], mag);
mag = mag.mul(mag);
ocvext::dft_shift(mag);
if(dbg != nullptr)
{
dbg[0] = 1.0 + mag;
cv::log(dbg[0], dbg[0]);
cv::normalize(dbg[0], dbg[0], 0, 255, cv::NORM_MINMAX);
dbg[0].convertTo(dbg[0], CV_8U);
cv::cvtColor(dbg[0], dbg[0], CV_GRAY2BGR);
}
# if DEBOGUER_ESTIM
ocvext::dbg_image("mag", mag, true);
ocvext::dbg_image("log-mag", dbg);
# endif
unsigned int cx = sx/2, cy = sy/2;
# if DEBOGUER_ESTIM
//tmp.setTo(0.0);
//cv::Mat dessin_dmin_dmax(q0.size(), CV_8UC3, cv::Scalar(0,0,0));
# endif
// (1) Calcul du nuage de points
cv::Mat T, mg, itrp;
uint32_t n = 2 * (cx - 1) * (cy - 1);
uint32_t j, N = dmax + 1;
T = cv::Mat::zeros(n, 1, CV_32F);
mg = cv::Mat::zeros(n, 1, CV_32F);
itrp = cv::Mat::zeros(N, 1, CV_32F);
uint32_t i = 0;
//FILE *fo = fopen("./build/sci.sce", "wt");
for(auto fy = 1u; fy < cx; fy++)
{
for(auto fx = 1u; fx < cy; fx++)
{
// Utilise 2 quadrants
T.at<float>(i) = uv_vers_p(fx,fy,sx,sy);
mg.at<float>(i) = mag.at<float>(cy+fy,cx+fx);
i++;
T.at<float>(i) = uv_vers_p(fx,fy,sx,sy);
mg.at<float>(i) = mag.at<float>(cy-fy,cx+fx);
i++;
}
}
# if DEBOGUER_ESTIM
infos("Interpolation par noyaux (RBF: N = %d, n = %d)...", N, n);
# endif
// (2) Interpolation par noyaux (RBF)
for(i = dmin; i < N; i++)
{
float somme1 = 0;
float *Tptr = T.ptr<float>();
float *mgptr = mg.ptr<float>();
for(j = 0; j < n; j++)
{
//float k1 = std::exp(-(sqr(T.at<float>(j)-i))/(2*h1*h1));
float nm = sqr(*Tptr++ - i);
float k1 = 1.0 / (1.0 + nm);//std::exp(-nm/(2*h1*h1));
somme1 += k1 * (*mgptr++);
}
itrp.at<float>(i) = somme1;
}
# if DEBOGUER_ESTIM
infos("Fin itrp.");
cv::normalize(itrp, itrp, 0, 255, cv::NORM_MINMAX);
cv::Mat O = cv::Mat(255,itrp.rows,CV_8UC3,cv::Scalar(0));
plot_1d(O, itrp, cv::Scalar(0,255,0));
dbg_image("Itrp", O);
# endif
if(dbg != nullptr)
{
cv::Mat tmp;
cv::normalize(itrp, tmp, 0, N-1, cv::NORM_MINMAX);
dbg[1] = cv::Mat(N-1,itrp.rows,CV_8UC3,cv::Scalar(0));
plot_1d(dbg[1], tmp, cv::Scalar(0,255,0));
}
cv::Point max_loc;
cv::minMaxLoc(itrp, nullptr, nullptr, nullptr, &max_loc);
d = max_loc.y;
indice_confiance = 0;
# if DEBOGUER_ESTIM
infos("Meilleur: d = %f (f = %f)", d, (float) max_loc.y);
# endif
float rd = itrp.at<float>(max_loc.y);
// Verification si maximum local
if((d == dmin) || (d == dmax))
return -1;
/*if((rd <= accu.at<float>(max_loc.y-1))
|| (rd <= accu.at<float>(max_loc.y+1)))
return -1;*/
//int d2 = 0;
float rd2 = 0;//accu.at<float>(0);
// Recherche 2eme maxima local
for(int r = 0u; r + 1 < itrp.rows; r++)
{
float v = itrp.at<float>(r);
if((r != d) // diff�rent du max global
&& (v > rd2) // maxi
&& (v > itrp.at<float>(r-1)) // Maximum local
&& (v > itrp.at<float>(r+1)))
{
rd2 = v;
//d2 = r;
}
}
indice_confiance = rd - rd2;
/*indice_confiance = std::min(indice_confiance,
rd - accu.at<float>(max_loc.y-1));
indice_confiance = std::min(indice_confiance,
rd - accu.at<float>(max_loc.y+1));*/
float alpha = 1.0;
indice_confiance *= alpha / rd;
infos("Distance detectee : %.1f pixels, indice confiance = %f.", d, indice_confiance);
if(dbg != nullptr)
{
float u, v;
p_vers_uv(d, sx, sy, u, v);
cv::circle(dbg[0], cv::Point(cx, cy), u, cv::Scalar(0,0,255), 1, CV_AA);
}
return 0;
}
}
| 16,294
|
C++
|
.cc
| 503
| 28.198807
| 145
| 0.579715
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,981
|
reco.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/reco.cc
|
#include "reco.hpp"
#include "cutil.hpp"
namespace ocvext
{
AssociateurConfig::AssociateurConfig()
{
verifie_ratio = true;
verifie_symetrie = true;
seuil_ratio = 0.65;
}
Associateur::Associateur(const AssociateurConfig &config)
{
this->config = config;
}
void Associateur::calcule(const cv::Mat &desc0,
const cv::Mat &desc1,
std::vector<cv::DMatch> &res)
{
auto matcheur = cv::DescriptorMatcher::create("BruteForce-Hamming(2)");
//auto matcheur = new cv::FlannBasedMatcher();
infos("Calcule association...");
std::vector<std::vector<cv::DMatch>> matches;
infos("knn match (%d * %d, %d cols)...", desc0.rows, desc1.rows, desc0.cols);
matcheur->knnMatch(desc0, desc1, matches, 3);
infos("ok.");
for(auto &match: matches)
{
if(config.verifie_ratio)
{
if(match.size() < 3)
continue;
// On autorise 2 pts d'intérêts similaires
float ratio = match[0].distance / match[2].distance;
if(ratio > config.seuil_ratio)
continue;
}
res.push_back(match[0]);
}
infos("ok, nb assos = %d.", res.size());
if(config.verifie_symetrie)
{
std::vector<cv::DMatch> matches10, res2;
matcheur->match(desc1, desc0, matches10);
for(auto &m: res)
{
for(auto &m2: matches10)
{
if(m.queryIdx == m2.trainIdx)
{
if(m2.queryIdx == m.trainIdx)
{
res2.push_back(m);
}
break;
}
}
}
res = res2;
infos("Apres test symetrie : %d.", res.size());
}
}
}
| 1,602
|
C++
|
.cc
| 62
| 20.306452
| 79
| 0.59541
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,982
|
gl.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/gl.cc
|
/** @file gl.cc
* @brief Garcia-Lorca exponential filter and optimized Deriche gradient
* @author J.A. / 2015 / www.tsdconseil.fr
* @license LGPL V 3.0 */
#include "gl.hpp"
#include <stdio.h>
#include "opencv2/imgproc/imgproc.hpp" // for cv::Sobel function
namespace ocvext
{
template<typename T>
static void lexp_forward(T *x, uint16_t n, float gamma);
template<typename T>
static void lexp_reverse(T *x, uint16_t n, float gamma);
template<typename T>
static void lexp2_forward(T *x, uint16_t n, float gamma);
template<typename T>
static void lexp2_reverse(T *x, uint16_t n, float gamma);
/* lissage garcia - lorca (1d) */
template<typename T>
static void lgl_1d(T *x, uint16_t n, float gamma);
template<typename T>
static void lexp_forward(const T *x, T *y, uint16_t n, float gamma, uint16_t stride)
{
uint16_t i;
float accu = x[0];
float gam = gamma;
float ugam = 1.0 - gamma;
// Accu: représentation XXX.X
// Gamma: .X
for(i = 0; i < n; i++)
{
accu = ugam * x[i*stride] + gam * accu;
y[i*stride] = (T) accu;
}
}
template<typename T>
static void lexp_reverse(const T *x, T *y, uint16_t n, float gamma, uint16_t stride)
{
signed short i;
float accu = x[(n-1)*stride];
float gam = gamma;
float ugam = 1.0 - gamma;
// Accu: représentation XXX.X
// Gamma: .X
for(i = n-1; i >= 0; i--)
{
accu = ugam * x[i*stride] + gam * accu;
y[i*stride] = (T) accu;
}
}
template<typename T>
void lexp2_forward(const T *x, T *y, uint16_t n, float gamma, uint16_t stride)
{
lexp_forward<T>(x, y, n, gamma, stride);
lexp_forward<T>(x, y, n, gamma, stride);
}
template<typename T>
void lexp2_reverse(const T *x, T *y, uint16_t n, float gamma, uint16_t stride)
{
lexp_reverse<T>(x, y, n, gamma, stride);
lexp_reverse<T>(x, y, n, gamma, stride);
}
template<typename T>
void lgl_1d(const T *x, T *y, uint16_t n, float gamma, uint16_t stride)
{
lexp2_forward<T>(x, y, n, gamma, stride);
lexp2_reverse<T>(x, y, n, gamma, stride);
}
template<typename T>
void garciaLorcaBlur_template(const cv::Mat &I, cv::Mat &O, float gamma)
{
uint16_t sx = I.cols,
sy = I.rows,
nchn = I.channels();
cv::Mat t2 = I.t(); // transposition
// Filtrage vertical
for(auto c = 0; c < nchn; c++)
{
for(uint16_t x = 0u; x < sx; x++)
lgl_1d<T>(t2.ptr<T>(x)+c, t2.ptr<T>(x)+c, sy, gamma, nchn); // ligne x
}
O = t2.t();
// Filtrage horizontal
for(auto c = 0; c < nchn; c++)
{
for(uint16_t y = 0u; y < sy; y++)
lgl_1d<T>(O.ptr<T>(y)+c, O.ptr<T>(y)+c, sx, gamma, nchn);
}
}
int Deriche_blur(const cv::Mat &I, cv::Mat &O, float gamma)
{
switch(I.depth())
{
case CV_32F:
garciaLorcaBlur_template<float>(I, O, gamma);
break;
case CV_8U:
garciaLorcaBlur_template<uint8_t>(I, O, gamma);
break;
case CV_16S:
garciaLorcaBlur_template<int16_t>(I, O, gamma);
break;
default:
fprintf(stderr, "garciaLorcaBlur: type de données non supporté (%d).\n", I.depth());
return -1;
}
return 0;
}
int Deriche_gradient(const cv::Mat &I,
cv::Mat &gx,
cv::Mat &gy,
float gamma)
{
cv::Mat lissee;
if(Deriche_blur(I, lissee, gamma))
return -1;
//cv::GaussianBlur(I, lissee, cv::Size(7,7), 2, 2);
// Noyau simple, sans lissage : [-1 0 1]
cv::Sobel(lissee, gx, CV_32F, 1, 0, 1);
cv::Sobel(lissee, gy, CV_32F, 0, 1, 1);
return 0;
}
int Deriche_gradient(const cv::Mat &I,
cv::Mat &O,
float gamma)
{
cv::Mat gx, gy;
if(Deriche_gradient(I, gx, gy, gamma))
return -1;
cv::Mat agx, agy;
convertScaleAbs(gx,agx); // Conversion 8 bits non signé
convertScaleAbs(gy,agy); // Conversion 8 bits non signé
addWeighted(agx, .5, agy, .5, 0, O);
cv::normalize(O, O, 0, 255, cv::NORM_MINMAX);
return 0;
}
#if 0
#define trace(...) printf(__VA_ARGS__); fflush(0);
class GLRowFilter: public cv::BaseRowFilter
{
public:
GLRowFilter(float gamma, int type)
{
this->gamma = gamma;
this->type = type;
anchor = 0;
ksize = 2;
}
virtual void operator()(const uchar *src, uchar *dst, int width, int cn)
{
trace("row filter: width = %d, cn = %d, src = %x, dst = %x\n", width, cn, (uint32_t) src, (uint32_t) dst);
//trace("anchor = %d, ksize = %d.\n", anchor, ksize);
switch(type)
{
//case CV_8U:
//for(auto c = 0; c < cn; c++)
//lgl_1d<uint8_t>(&(src[c]),&(dst[c]),width,gamma,cn);
//break;
case CV_32F:
{
const float *fsrc = (const float *) src;
float *fdst = (float *) dst;
for(auto c = 0; c < cn; c++)
for(auto x = 0; x < width; x++)
fdst[x*cn+c] = fsrc[x*cn+c];
//lgl_1d<float>(&(fsrc[c]), &(fdst[c]), width, gamma, cn);
break;
}
default:
printf("Type non supporté : %d.\n", type); fflush(0);
abort();
return;
}
}
float gamma;
int type;
};
class GLColFilter: public cv::BaseColumnFilter
{
public:
GLColFilter(float gamma, int type)
{
this->gamma = gamma;
this->type = type;
anchor = 0;
ksize = 2;
}
virtual void operator()(const uchar **src, uchar *dst,
int dststep, int dstcount, int width)
{
trace("col filter: dstep = %d, dcount = %d, width = %d\n", dststep, dstcount, width);
trace("src = %x, src[0] = %x, src[1] = %x, dst = %x\n", (int) src, (int) src[0], (int) src[1], (int) dst);
/*int prev = (int) src[0];
for(auto i = 1; i < dstcount; i++)
{
int s = (int) src[i];
trace("ecart %d: %d.\n", i, s - prev);
prev = s;
}*/
switch(type)
{
//case CV_8U:
//for(auto c = 0; c < cn; c++)
// lgl_1d<uint8_t>(&(src[c]),&(dst[c]),width,gamma,cn);
//break;
case CV_32F:
{
const float **fsrc = (const float **) src;
float *fdst = (float *) dst;
//for(auto c = 0; c < cn; c++)
//lgl_1d<float>(&(fsrc[c]), &(fdst[c]), width, gamma, cn);*/
/*for(auto y = 0; y < dstcount; y++)
{
for(auto x = 0; x < width; x++)
fdst[y*dststep/4+x] = (fsrc[y])[x];
//fdst[y*dststep/4+x] = fsrc[y*dststep/4+x];
}*/
// PB 1 : les échantillons de sortie ne sont pas du tout alignés en mémoire
// PB 2 : on ne fait qu'une partie à chaque fois !
for(auto x = 0; x < width; x++)
{
lgl_1d<float>(&((fsrc[0])[x]), &(fdst[x]), dstcount, gamma, dststep/4);
}
break;
}
default:
printf("Type non supporté : %d.\n", type); fflush(0);
abort();
return;
}
}
float gamma;
int type;
};
cv::Ptr<cv::FilterEngine> createGarciaLorcaFilter(float gamma, int type)
{
cv::Ptr<cv::BaseRowFilter> row_filter(new GLRowFilter(gamma, type));
cv::Ptr<cv::BaseColumnFilter> col_filter(new GLColFilter(gamma, type));
trace("init filter engine...\n");
cv::FilterEngine *fe = new cv::FilterEngine(nullptr, row_filter, col_filter,
type, type, type);
trace("ok.\n");
return cv::Ptr<cv::FilterEngine>(fe);
}
void garciaLorcaBlur(const cv::Mat &I,
cv::Mat &O,
float gamma)
{
trace("creation filtre, type = %d...\n", I.type());
auto f = createGarciaLorcaFilter(gamma, I.type());
O = cv::Mat(I.rows,I.cols,I.type());
trace("apply...\n");
f->apply(I, O);//, cv::Rect(0,0,I.cols,I.rows));
}
#endif
}
| 7,516
|
C++
|
.cc
| 256
| 24.683594
| 110
| 0.576816
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,983
|
ocvext.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/ocvext.cc
|
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "cutil.hpp"
#include "../include/ocvext.hpp"
#ifdef WINDOWS
# include <windows.h>
#endif
namespace ocvext
{
GestionnaireEvenementGenerique *gestionnaire_evenement = nullptr;
static utils::model::Node noeud_en_cours;
static std::string chemin_tmp;
static unsigned int id_img = 0;
static bool log_en_cours = false;
static int niveau_indent = 0;
static std::string algo_en_cours;
void infos_demarre_log(utils::model::Node &res, const std::string &id)
{
noeud_en_cours = res;
chemin_tmp = utils::get_current_user_path() + PATH_SEP + "tmp";
utils::files::creation_dossier(chemin_tmp);
id_img = 0;
log_en_cours = true;
niveau_indent = 0;
}
void infos_arrete_log()
{
noeud_en_cours = utils::model::Node();
log_en_cours = false;
}
static std::string fais_indent()
{
std::string idt;
for(auto i = 0; i < niveau_indent; i++)
idt += " ";
return idt;
}
void infos_entre_algo(const std::string &nom_algo)
{
if(log_en_cours)
{
auto idt = fais_indent();
algo_en_cours = nom_algo;
trace_majeure("%sDebut algorithme [%s]", idt.c_str(), nom_algo.c_str());
noeud_en_cours = noeud_en_cours.add_child("img-collection");
noeud_en_cours.set_attribute("name", nom_algo);
niveau_indent++;
}
}
void infos_sors_algo()
{
if(log_en_cours)
{
auto idt = fais_indent();
infos("%sFin algorithme [%s]", idt.c_str(), algo_en_cours.c_str());
noeud_en_cours = noeud_en_cours.parent();
niveau_indent--;
if(niveau_indent < 0)
{
erreur("niveau indent = %d !", niveau_indent);
niveau_indent = 0;
}
}
}
void infos_progression(const std::string &infos, ...)
{
va_list ap;
va_start(ap, infos);
auto idt = fais_indent();
//infos("%s%s", idt.c_str(), infos.c_str());
char buf[2000];
vsnprintf(buf, 2000, infos.c_str(), ap);
//printf(idt.c_str());
//printf("%s\n", buf);
infos("%s%s", idt.c_str(), buf);
//utils::journal::gen_trace(utils::journal::AL_NORMAL, "",
// utils::journal::journal_principal, std::string(buf));
if(log_en_cours)
{
auto n = noeud_en_cours.add_child("log-item");
n.set_attribute("name", infos);
}
if(gestionnaire_evenement != nullptr)
gestionnaire_evenement->maj_infos(infos);
va_end(ap);
}
void infos_progression(const std::string &infos, const cv::Mat &img, bool normaliser)
{
if(img.cols == 0)
{
erreur("infos_progression (%s): image vide.", infos.c_str());
return;
}
if(log_en_cours)
{
cv::Mat m2;
if(normaliser)
{
cv::normalize(img, m2, 0, 255.0, cv::NORM_MINMAX);
}
else
m2 = img;
char bf[1000];
cv::Mat O;
ocvext::adapte_en_bgr(m2, O);
sprintf(bf, "%s/%d.png", chemin_tmp.c_str(), id_img);
cv::imwrite(bf, O);
id_img++;
auto n = noeud_en_cours.add_child("img-spec");
n.set_attribute("name", infos);
n.set_attribute("chemin", std::string(bf));
}
//ocvext::dbg_image(infos, img);
if(gestionnaire_evenement != nullptr)
gestionnaire_evenement->maj_infos(infos, img);
}
// Display intermediate image (debug mode only)
void dbg_image(const std::string &name,
const cv::Mat &m,
bool normalize,
const std::string &titre,
const std::string &description)
{
infos_progression(name, m, normalize);
# if 0
if(config.affiche_images_intermediaires)
{
cv::namedWindow(name.c_str(), CV_WINDOW_NORMAL);
cv::imshow(name.c_str(), m);
cv::waitKey(5);
}
//bool img_ess = config.enreg_images_essentielles && (titre.size() > 0) && (current_htsec != nullptr);
if(config.enreg_images_intermediaires)// || img_ess)
{
char path[200];
sprintf(path,
"%s/%d-%s.png",
config.dout.c_str(),
config.img_cnt++,
name.c_str());
cv::Mat m2;
if(normalize)
{
cv::normalize(m, m2, 0, 255.0, cv::NORM_MINMAX);
}
else
{
if(m.depth() == CV_32F)
m2 = m * 255;
else
m2 = m.clone();
}
if(m2.channels() == 1)
cv::cvtColor(m2, m2, CV_GRAY2BGR);
m2.convertTo(m2, CV_8U);
if(config.enreg_images_intermediaires)
cv::imwrite(path, m2);
}
# endif
}
Config config;
Config::Config()
{
img_cnt = 0;
affiche_images_intermediaires = false;
enreg_images_intermediaires = false;
/*enreg_images_importantes = false;
enreg_images_essentielles = false;
ess_cnt = 0;*/
//dout = "./build/img-out";
# ifdef WINDOWS
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&base_tick);
# endif
}
void init(bool affiche_img_interm,
bool stocke_img_interm,
const std::string &dossier_stockage)
{
defini_options_debogage(affiche_img_interm, stocke_img_interm);
if(dossier_stockage == "")
defini_dossier_stockage("./build/img-out");
else
defini_dossier_stockage(dossier_stockage);
}
void defini_dossier_stockage(const std::string &chemin)
{
config.dout = chemin;
config.img_cnt = 0;
if(config.enreg_images_intermediaires)
{
infos("set_output_folder(%s)", chemin.c_str());
utils::files::creation_dossier(chemin);
utils::proceed_syscmde("rm %s/*.png", chemin.c_str());
utils::proceed_syscmde("rm %s/*.jpg", chemin.c_str());
}
}
bool est_debogage_actif()
{
return config.affiche_images_intermediaires || config.enreg_images_intermediaires;
}
void defini_options_debogage(bool show_debug_view,
bool store_debug_view)
{
config.affiche_images_intermediaires = show_debug_view;
config.enreg_images_intermediaires = store_debug_view;
}
cv::Mat imread(const std::string &fn)
{
//infos("Lecture image @%s...", fn.c_str());
cv::Mat res = cv::imread(fn);
if(res.cols == 0)
{
const char *s1 = "le fichier n'existe pas";
const char *s2 = "le fichier existe";
const char *s = utils::files::file_exists(fn) ? s2 : s1;
erreur("erreur lors de l'image de [%s] (%s).", fn.c_str(), s);
}
return res;
}
void redim_preserve_aspect(const cv::Mat &I,
cv::Mat &O,
const cv::Size &dim, const cv::Scalar &bgcolor)
{
float h1 = dim.width * (I.rows / (float) I.cols);
float w2 = dim.height * (I.cols / (float) I.rows);
if(h1 <= dim.height)
cv::resize(I, O, cv::Size(dim.width, h1));
else
cv::resize(I, O, cv::Size(w2, dim.height));
}
void affiche_dans_cadre(const cv::Mat &I, cv::Mat &cadre, cv::Size taille_vue,
const cv::Scalar &arriere_plan,
cv::Point &p0, float &ratio)
{
auto taille_video = I.size();
cadre.create(taille_vue, CV_8UC4);
//trace_verbeuse("affiche_dans_cadre...");
// Redimensionnnement de la vidéo dans le cadre
// avec préservation du ratio d'aspect
float ratio_x = ((float) taille_vue.width) / taille_video.width;
float ratio_y = ((float) taille_vue.height) / taille_video.height;
//float mratio = (ratio_x < ratio_y) ? ratio_x : ratio_y;
cv::Rect rdi;
cadre.setTo(arriere_plan);
if(ratio_x < ratio_y) // bandes horizontales en haut et en bas
{
rdi.width = taille_vue.width;
rdi.x = 0;
rdi.height = taille_video.height * ratio_x;
rdi.y = (taille_vue.height - rdi.height) / 2;
ratio = ratio_x;
}
else // bandes verticales en haut et en bas
{
rdi.width = taille_video.width * ratio_y;
rdi.x = (taille_vue.width - rdi.width) / 2;
rdi.height = taille_vue.height;
rdi.y = 0;
// si ry > 0 : pb : rdi.width > taille_vue.width !!!
ratio = ratio_y;
}
p0 = cv::Point(rdi.x,rdi.y);
if(rdi.width * rdi.height == 0)
return;
/*trace_verbeuse("rx = %f, ry = %f,\nresize(%d,%d,%d,%d) -> %d,%d",
ratio_x, ratio_y, rdi.x, rdi.y, rdi.width, rdi.height,
taille_vue.width, taille_vue.height);*/
if(I.cols * I.rows == 0)
{
erreur("I.cols = %d, I.rows = %d.", I.cols, I.rows);
return;
}
cv::resize(I, cadre(rdi), rdi.size());
//trace_verbeuse("ok.");
}
void affiche_dans_cadre(const cv::Mat &I, cv::Mat &cadre, cv::Size taille_vue, const cv::Scalar &arriere_plan)
{
cv::Point p0;
float ratio;
affiche_dans_cadre(I, cadre, taille_vue, arriere_plan, p0, ratio);
}
void plot_1d(cv::Mat &image, const cv::Mat &x_, cv::Scalar color)
{
cv::Mat x = x_.clone();
if((x.rows == 1) && (x.cols > 1))
x = x_.t();
uint32_t n = x.rows;
float sx = image.cols, sy = image.rows;
float lxi = x.at<float>(0);
for(auto i = 1u; i < n; i++)
{
float xi = x.at<float>(i);
//printf("xi = %f\n", xi);
cv::line(image,
cv::Point((i-1)* sx / n,sy-lxi),
cv::Point(i * sx / n,sy-xi),
color, 1, CV_AA);
lxi = xi;
}
}
MultiPlot::MultiPlot()
{
nx = ny = sx = sy = cnt = 0;
}
MultiPlot::MultiPlot(uint16_t nx, uint16_t ny, uint16_t sx, uint16_t sy)
{
init(nx, ny, sx, sy);
}
void MultiPlot::init(uint16_t nx, uint16_t ny, uint16_t sx, uint16_t sy)
{
this->nx = nx;
this->ny = ny;
this->sx = sx;
this->sy = sy;
img.create(cv::Size(sx*nx,sy*ny), CV_8UC3);
cnt = 0;
}
void adapte_en_bgr(const cv::Mat &I, cv::Mat &O)
{
//infos("Adaptation en BGR: type entree = %d", I.type());
cv::Mat O1;
if(I.channels() == 1)
cv::cvtColor(I, O1, CV_GRAY2BGR);
else
O1 = I.clone();
if(O1.type() == CV_32FC3)
{
cv::normalize(O1, O1, 0, 255, cv::NORM_MINMAX);
O1.convertTo(O, CV_8UC3);
}
else
O = O1;
//infos("type sortie = %d", O.type());
}
void MultiPlot::ajoute(std::string nom, const cv::Mat &I, uint16_t ncols)
{
cv::Mat tmp;
adapte_en_bgr(I, tmp);
uint16_t col = cnt % nx;
uint16_t ligne = cnt / nx;
cv::resize(tmp, img(cv::Rect(col*sx,ligne*sy,sx*ncols,sy)), cv::Size(sx*ncols,sy));
int baseline = 0;
cv::Size sz = cv::getTextSize(nom.c_str(),
cv::FONT_HERSHEY_COMPLEX, 0.8, 1, &baseline);
baseline += 1;
img(cv::Rect(col*sx,ligne*sy + 2,std::min(sz.width,(int)sx*ncols),std::min(sz.height+baseline,(int)sy))) /= 3;
putText(img, nom.c_str(), cv::Point(col*sx,ligne*sy+sz.height + 2),
cv::FONT_HERSHEY_COMPLEX, 0.8,
cv::Scalar(0,255,255),1,CV_AA);
cnt += ncols;
}
void MultiPlot::creation_auto(const cv::Mat &I0, const cv::Mat &I1)
{
uint32_t ncols, nlignes;
if(I0.cols > I0.rows)
{
ncols = 1;
nlignes = 2;
}
else
{
ncols = 2;
nlignes = 1;
}
init(ncols,nlignes,std::max(I0.cols, I1.cols), std::max(I0.rows,I1.rows));
ajoute("", I0);
ajoute("", I1);
}
}
| 10,566
|
C++
|
.cc
| 371
| 24.493261
| 112
| 0.619901
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,984
|
vue-image.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/vue-image.cc
|
#include "vue-image.hpp"
#include "ocvext.hpp"
namespace ocvext {
#define DEBOGUE_VUE_IMAGE(AA)
//AA
std::vector<Cairo::RefPtr<Cairo::Context>> *VueImage::old_srf =
new std::vector<Cairo::RefPtr<Cairo::Context>>();
#if 0
void VueImage::get_preferred_width(int& minimum_width, int& natural_width) const
{
infos("**************** gpw : %d", csx);
minimum_width = natural_width = csx;
}
void VueImage::get_preferred_height(int& minimum_height, int& natural_height) const
{
infos("*************** gph : %d", csy);
minimum_height = natural_height = csy;
}
#endif
VueImage::VueImage(uint16_t dx, uint16_t dy, bool dim_from_parent)
: Gtk::DrawingArea(), dispatcher(16)
{
arriere_plan = cv::Scalar(0);
cr_alloue = false;
alloc_x = alloc_y = -1;
realise = false;
csx = 1;
csy = 1;
this->dim_from_parent = dim_from_parent;
//signal_size_allocate().
signal_realize().connect(sigc::mem_fun(*this, &VueImage::on_the_realisation));
dispatcher.add_listener(this, &VueImage::on_event);
change_dim_interne(dx,dy);
if(!dim_from_parent)
set_size_request(csx,csy);
//show();
}
void VueImage::get_dim(uint16_t &sx, uint16_t &sy)
{
sx = get_allocated_width();
sy = get_allocated_height();
//infos("get allocation : %d * %d", sx, sy);
/*if(alloc_x > 0)
{
sx = alloc_x;
sy = alloc_y;
}*/
}
void VueImage::change_dim_interne(uint16_t sx, uint16_t sy)
{
if((csx != sx) || (csy != sy))
{
DEBOGUE_VUE_IMAGE(infos("change dimension surface : (%d,%d) -> (%d,%d)", csx, csy, sx, sy));
csx = sx;
csy = sy;
//old = image_surface;
image_surface = Cairo::ImageSurface::create(Cairo::Format::FORMAT_RGB24, sx, sy);
/*if(en_attente.img.cols > 0)
{
DEBOGUE_VUE_IMAGE(infos("Envoi image en attente..."));
maj_surface(en_attente.img);
}
else
infos("pas d'image en attente");*/
}
}
void VueImage::change_dim(uint16_t sx, uint16_t sy)
{
if((csx != sx) || (csy != sy))
{
DEBOGUE_VUE_IMAGE(infos("change dimension surface : (%d,%d) -> (%d,%d)", csx, csy, sx, sy));
csx = sx;
csy = sy;
if(!dim_from_parent)
set_size_request(csx,csy);
//old = image_surface;
image_surface = Cairo::ImageSurface::create(Cairo::Format::FORMAT_RGB24, sx, sy);
/*if(en_attente.img.cols > 0)
{
DEBOGUE_VUE_IMAGE(infos("Envoi image en attente..."));
maj_surface(en_attente.img);
}
else
DEBOGUE_VUE_IMAGE(infos("pas d'image en attente"));*/
}
}
void VueImage::maj(const std::string &chemin_fichier)
{
auto img = ocvext::imread(chemin_fichier);
DEBOGUE_VUE_IMAGE(infos("lecture image debug [%s] => %d * %d", chemin_fichier.c_str(), img.cols, img.rows));
if(img.cols > 0)
maj(img);
}
void VueImage::coor_vue_vers_image(int xv, int yv, cv::Point &xi)
{
xv -= p0.x;
yv -= p0.y;
xv /= ratio;
yv /= ratio;
xi = cv::Point(xv, yv);
}
#define TEST00 1
void VueImage::maj(const cv::Mat &img)
{
cv::Mat img2, img3;
ocvext::adapte_en_bgr(img, img2);
if(img2.type() != CV_8UC3)
{
avertissement("devrait etre BGR 8 bits, mais type = %d.", img2.type());
return;
}
cv::cvtColor(img2, img3, CV_BGR2BGRA);
# if !TEST00
en_attente.img = img3;
# endif
//maj_surface(en_attente.img);
if(!realise)
{
avertissement("maj vue image : non realise.");
# if TEST00
en_attente.img = img3;
# endif
return;
}
if(dispatcher.is_full())
{
//avertissement("maj vue image: FIFO de sortie pleine, on va ignorer quelques trames...");
//return;
dispatcher.clear();
}
Trame t;
/*if((this->csx == img.cols) && (this->csy == img.rows))
{
t.img = cv::Mat();
memcpy(image_surface->get_data(), img3.ptr(), 4 * img.cols * img.rows);
}
else*/
{
t.img = img3.clone();
}
dispatcher.on_event(t);
}
void VueImage::maj_surface(const cv::Mat &I)
{
cv::Mat O;
uint16_t sx, sy;
get_dim(sx, sy);
//infos("resize (%d,%d) --> (%d,%d)", I.cols, I.rows, sx, sy);
// Un essai
// sx = I.cols; sy = I.rows;
affiche_dans_cadre(I, O, cv::Size(sx, sy), arriere_plan, p0, ratio);
///cv::resize(t.img, O, cv::Size(sx, sy));
//uint16_t sx = t.img.cols, sy = t.img.rows;
change_dim_interne(sx,sy);
DEBOGUE_VUE_IMAGE(infos("memcpy (sx = %d, sy = %d, type = %d)...", sx, sy, O.type());)
memcpy(this->image_surface->get_data(), O.ptr(), 4 * sx * sy);
DEBOGUE_VUE_IMAGE(infos("ok"));
}
void VueImage::on_event(const Trame &t)
{
/*if(t.img.cols != 0)
{
maj_surface(t.img);
}*/
# if TEST00
en_attente.img = t.img;
# endif
uint16_t sx, sy;
get_dim(sx, sy);
//infos("queue_draw (alloc = %d * %d)...", sx, sy);
queue_draw();
//draw_all();
//queue_draw_area(0, 0, csx, csy);
//do_update_view();
//show();
}
void VueImage::draw_all()
{
//void MyArea::force_redraw()
/*{
auto win = get_window();
if (win)
{
Gdk::Rectangle r(0, 0, get_allocation().get_width(), get_allocation().get_height());
win->invalidate_rect(r, false);
}
}*/
DEBOGUE_VUE_IMAGE(infos("draw all -> generation expose event..."));
GdkEventExpose evt;
evt.area.x = 0;
evt.area.y = 0;
evt.area.width = get_allocation().get_width();
evt.area.height = get_allocation().get_height();
gere_expose_event(&evt);
}
// Pas vraiment utilsé
bool VueImage::gere_expose_event(GdkEventExpose* event)
{
//int sx = get_allocated_width();
//int sy = get_allocated_height();
//DEBOGUE_VUE_IMAGE(infos("expose event : alloc = %d * %d", sx, sy));
do_update_view();
return true;
}
void VueImage::do_update_view()
{
DEBOGUE_VUE_IMAGE(trace_verbeuse("do update view..."));
if(!realise)
{
DEBOGUE_VUE_IMAGE(infos(" => non realise."));
return;
}
if(!cr)
{
auto wnd = get_window();
if(!wnd)
{
realise = false;
return;
}
cr = wnd->create_cairo_context();
}
DEBOGUE_VUE_IMAGE(trace_verbeuse("dessine(%d,%d)", csx, csy));
if(this->en_attente.img.cols > 0)
{
maj_surface(en_attente.img);
//image_surface = Cairo::ImageSurface::create(Cairo::Format::FORMAT_RGB24, csx, csy);
cr->set_source(image_surface, 0, 0);
cr->rectangle (0.0, 0.0, csx, csy);
cr->clip();
cr->paint();
}
}
// C'est ici qu'on dessine !
bool VueImage::on_draw(const Cairo::RefPtr<Cairo::Context> &cr)
{
uint16_t sx, sy;
get_dim(sx, sy);
DEBOGUE_VUE_IMAGE(infos("on draw (allocx = %d, allocy = %d, csx = %d, csy = %d)...", sx, sy, csx, csy));
if((sx != csx) || (sy != csy))
{
if(en_attente.img.cols > 0)
{
DEBOGUE_VUE_IMAGE(infos("image en attente : %d * %d, type = %d",
en_attente.img.cols, en_attente.img.rows, en_attente.img.type()));
//cv::Mat O, img2, img1;
//ocvext::adapte_en_bgr(en_attente.img, img1);
//cv::cvtColor(img1, img2, CV_BGR2BGRA);
//maj_surface(en_attente.img);
# if 0
//infos("resize (%d,%d) --> (%d,%d)", t.img.cols, t.img.rows, sx, sy);
cv::Mat O, img2, img1;
ocvext::adapte_en_bgr(en_attente.img, img1);
cv::cvtColor(img1, img2, CV_BGR2BGRA);
affiche_dans_cadre(img2, O, cv::Size(sx, sy), cv::Scalar(0));
//cv::resize(img2, O, cv::Size(sx, sy));
//uint16_t sx = t.img.cols, sy = t.img.rows;
change_dim(sx,sy);
infos("memcpy (sx = %d, sy = %d, type = %d)...", sx, sy, O.type());
memcpy(this->image_surface->get_data(), O.ptr(), 4 * sx * sy);
# endif
//maj(en_attente.img);
//return true;
//en_attente.img = cv::Mat();
}
}
//if(!cr_alloue)
if(!(cr == this->cr))
{
DEBOGUE_VUE_IMAGE(trace_majeure("CR different !"));
if(cr_alloue)
{
// Pour contourner bogue GTK sous Windows 10,
// il ne faut pas supprimer le CR
// sînon ("")
#ifdef WIN
old_srf->push_back(this->cr);
DEBOGUE_VUE_IMAGE(infos("destruction cr..."));
this->cr.clear();
#endif
}
DEBOGUE_VUE_IMAGE(infos("copie cr..."));
cr_alloue = true;
this->cr = cr;
DEBOGUE_VUE_IMAGE(infos("copie cr ok."));
}
do_update_view();
return true;
}
void VueImage::on_the_realisation()
{
uint16_t sx, sy;
get_dim(sx, sy);
DEBOGUE_VUE_IMAGE(infos("Vue image : realisation (alloc = %d * %d).", sx, sy));
realise = true;
if(sx <= 1)
// attends l'allocation
return;
if(en_attente.img.cols > 0)
{
DEBOGUE_VUE_IMAGE(infos("image en attente : %d * %d", en_attente.img.cols, en_attente.img.rows));
/*cv::Mat O, img2, img1;
ocvext::adapte_en_bgr(en_attente.img, img1);
cv::cvtColor(img1, img2, CV_BGR2BGRA);*/
on_event(en_attente);
//en_attente.img = cv::Mat(); // Sinon, on perd le fil...
}
else
do_update_view();
}
/*void VueImage::on_size_allocate(Gtk::Allocation &allocation)
{
alloc_x = allocation.get_width();
alloc_y = allocation.get_height();
//set_size_request(alloc_x, alloc_y);
//set_allocation(allocation);
infos("Vue image : allocation (%d * %d).", alloc_x, alloc_y);
if(en_attente.img.cols > 0)
{
infos("image en attente : %d * %d", en_attente.img.cols, en_attente.img.rows);
maj(en_attente.img);
//draw_all();
//en_attente.img = cv::Mat();
}
//queue_resize();
}*/
DialogueImage::DialogueImage()
{
dialogue.get_vbox()->pack_start(vview, Gtk::PACK_EXPAND_WIDGET);
auto img_cancel = new Gtk::Image(Gtk::StockID(Gtk::Stock::CANCEL),
Gtk::IconSize(Gtk::ICON_SIZE_BUTTON));
b_close.set_image(*img_cancel);
b_close.set_border_width(4);
hbox.pack_end(b_close, Gtk::PACK_SHRINK);
hbox.set_layout(Gtk::BUTTONBOX_END);
b_close.signal_clicked().connect(sigc::mem_fun(this, &DialogueImage::gere_b_fermer));
dialogue.get_vbox()->pack_start(hbox, Gtk::PACK_SHRINK);
dialogue.set_size_request(800, 600);
}
void DialogueImage::gere_b_fermer()
{
dialogue.hide();
}
void DialogueImage::affiche(cv::Mat &I, const std::string &titre, const std::string &infos)
{
dialogue.set_title(titre);
dialogue.set_position(Gtk::WIN_POS_CENTER);
b_close.set_label(utils::langue.get_item("fermer"));
dialogue.show_all_children(true);
vview.maj(I);
DEBOGUE_VUE_IMAGE(infos("dlg.run..."));
dialogue.run();
}
}
| 10,165
|
C++
|
.cc
| 354
| 25.042373
| 110
| 0.617172
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,985
|
vue-collection.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/vue-collection.cc
|
#include "vue-collection.hpp"
#ifdef WIN
# include <windows.h>
#endif
namespace ocvext{
void VueCollection::gere_b_ouvrir_image()
{
auto noeud = arbre.get_selection();
if(noeud.has_attribute("chemin"))
{
auto s = noeud.get_attribute_as_string("chemin");
infos("Ouverture [%s]...", s.c_str());
# ifdef WIN
::ShellExecute(NULL, "open", s.c_str(), NULL, NULL, SW_SHOW);
# endif
}
}
VueCollection::VueCollection(): vue(200,300,true)
{
//fenetre.set_title(titre);
vbox_princ.pack_start(barre_outil, Gtk::PACK_SHRINK);
vbox_princ.pack_start(hpaned, Gtk::PACK_EXPAND_WIDGET);
b_ouvrir_image.set_sensitive(false);
b_ouvrir_image.set_label("Ouvrir avec windows");
barre_outil.append(b_ouvrir_image, sigc::mem_fun(*this, &VueCollection::gere_b_ouvrir_image));
fenetre.add(vbox_princ);
hpaned.add1(arbre);
hpaned.add2(vbox);
//vbox.pack_start(vue);
vue_en_cours = nullptr;
fenetre.show_all_children(true);
arbre.add_listener(this, &VueCollection::gere_change_sel);
hpaned.set_position(300);
std::vector<std::string> ids;
ids.push_back("img-collection");
ids.push_back("img-spec");
arbre.set_liste_noeuds_affiches(ids);
}
void VueCollection::gere_change_sel(const utils::mmi::SelectionChangeEvent &sce)
{
//trace_verbeuse("changement selection.");
auto sel = sce.new_selection;
auto type = sel.schema()->name.get_id();
bool est_image = (type == "img-spec");
b_ouvrir_image.set_sensitive(est_image);
if(vue_en_cours != nullptr)
vbox.remove(*vue_en_cours);
vue_en_cours = nullptr;
if(type == "img-collection")
{
//cv::Mat m(1,1,CV_8UC3,cv::Scalar(0,0,0));
//vue.maj(m);
std::string s;
for(auto &l: sel.children("log-item"))
{
s += l.get_attribute_as_string("name");
s += "\n";
}
texte.get_buffer()->set_text(s);
vbox.pack_start(texte, Gtk::PACK_EXPAND_WIDGET);
vue_en_cours = &texte;
}
else if(type == "img-spec")
{
vbox.pack_start(vue, Gtk::PACK_EXPAND_WIDGET);
vue_en_cours = &vue;
vue.maj(sel.get_attribute_as_string("chemin"));
}
else
avertissement("VueCollection : type non gere (%s)", type.c_str());
fenetre.show_all_children(true);
}
void VueCollection::affiche(utils::model::Node &modele)
{
//auto s = modele.to_xml();
//infos("Affichage collection, modele :\n%s", s.c_str());
this->modele = modele;
arbre.set_model(modele);
// modele_arbre = utils::model::Node(modele.schema());
// modele_arbre.copy_from(modele);
// Construction modele arbre
fenetre.show_all_children(true);
fenetre.show();
}
void VueCollection::ferme()
{
fenetre.hide();
}
}
| 2,641
|
C++
|
.cc
| 89
| 26.404494
| 96
| 0.678685
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,987
|
test-fourier.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/test/test-fourier.cc
|
#include "fourier.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "cutil.hpp"
#include "../../include/ocvext.hpp"
void test_rotation(cv::Mat &I0, float angle, float echelle)
{
trace_majeure("Test rotation (%.1f, %.3f)...", angle, echelle);
cv::Mat I1;
cv::Size sz = I0.size();
cv::Point centre;
centre.x = sz.width / 2;
centre.y = sz.height / 2;
uint16_t sx = sz.width, sy = sz.height;
cv::Mat R = cv::getRotationMatrix2D(centre, angle, echelle);
cv::warpAffine(I0, I1, R, I0.size());
//Ig = Ig(Rect(sx/4,sy/4,sx/2,sy/2));
//output.images[idx++] = Ig;
float ad, ed;
ocvext::detection_rotation_echelle(I0, I1, ad, ed);
angle *= 3.1415926 / 180.0;
float ea = std::abs(ad - angle);
float ee = std::abs(ed - echelle);
infos("Erreur détection : angle -> %.1f degrés, echelle = %.3f", ea * 180.0 / 3.1415926, ee);
}
int main(int argc, const char **argv)
{
utils::init(argc, argv, "libocvext");
ocvext::init(false, true);
cv::Mat I0 = cv::imread("./data/img/5pts.png");
# if 0
cv::Mat I1 = cv::Mat::zeros(I0.size(), CV_8UC3);
cv::Point pt;
// Applique une translation
ocvext::translation(I0, I1, 130, -50, cv::Scalar(255,255,255));
pt = ocvext::detection_translation(I0, I1);
ocvext::translation(I0, I1, 130, 50, cv::Scalar(255,255,255));
pt = ocvext::detection_translation(I0, I1);
ocvext::translation(I0, I1, -130, 50, cv::Scalar(255,255,255));
pt = ocvext::detection_translation(I0, I1);
ocvext::translation(I0, I1, -130, -50, cv::Scalar(255,255,255));
pt = ocvext::detection_translation(I0, I1);
# endif
I0.convertTo(I0, CV_32F);
cv::cvtColor(I0, I0, CV_BGR2GRAY);
//test_rotation(I0, 0.0, 1.0);
//test_rotation(I0, 10.0, 1.0);
//test_rotation(I0, 25.0, 1.0);
//test_rotation(I0, 0.0, 1.2);
test_rotation(I0, 0.0, 1.5);
return 0;
}
| 1,852
|
C++
|
.cc
| 52
| 32.788462
| 95
| 0.649467
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,988
|
etalonnage-camera.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/outils/etalonnage-camera.cc
|
#include "calib.hpp"
#include "mmi/theme.hpp"
int main(int argc, const char **argv)
{
utils::init(argc, argv, "ocvext");
ocvext::init(false, false);
Gtk::Main kit(0, nullptr);
utils::langue.load(utils::get_fixed_data_path() + "/std-lang.xml");
utils::langue.load(utils::get_fixed_data_path() + "/ocvext-lang.xml");
utils::mmi::charge_themes();
utils::mmi::installe_theme("dark");
cv::setBreakOnError(true);
ocvext::DialogueCalibration dc;
dc.affiche();
return 0;
}
| 493
|
C++
|
.cc
| 16
| 28.0625
| 72
| 0.690021
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,989
|
scan.cc
|
tsdconseil_opencv-demonstrator/libocvext/src/outils/scan.cc
|
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "cutil.hpp"
#include <vector>
int main(int argc, const char **argv)
{
std::string dossier = argv[1];
std::vector<std::string> fichiers;
utils::files::explore_dossier(dossier, fichiers);
auto cnt = 0;
for(auto &f: fichiers)
{
auto ext = utils::files::get_extension(f);
if(ext != "jpg")
continue;
cv::Mat I = cv::imread(f.c_str());
if(I.cols == 0)
{
utils::erreur("Erreur ouverture fichier (%s)", f.c_str());
return -1;
}
utils::trace("Traitement [%s]: %d * %d", f.c_str(), I.cols, I.rows);
/*if(I.cols > I.rows)
{
I = I.t();
}*/
if(I.cols > 1000)
{
float ratio = 1000.0 / I.cols;
cv::resize(I, I, cv::Size(0,0), ratio, ratio);
utils::trace(" redim: %d * %d", I.cols, I.rows);
}
//cv::medianBlur(I, I, 3);
//cv::equalizeHist(I, I);
cv::cvtColor(I, I, CV_BGR2GRAY);
//cv::threshold(I, I, 0, 255, cv::THRESH_OTSU);
//cv::AdaptiveThresholdTypes
cv::adaptiveThreshold(I, I, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 21, 20);
f = utils::files::remove_extension(f);
cv::imwrite(f + ".png", I);
cnt++;
/*if(cnt > 10)
break;*/
//cv::imwrite(f + ".jp2", I);
}
return 0;
}
| 1,328
|
C++
|
.cc
| 47
| 23.382979
| 96
| 0.572677
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,990
|
gestion-souris.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/gestion-souris.cc
|
/** @file gestion-souris.cc
Copyright 2016 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "ocvdemo.hpp"
//void OCVDemo::mouse_callback(int image, int event, int x, int y, int flags)
void OCVDemo::on_event(const OCVMouseEvent &me)
{
mutex.lock();
//infos("ocvdemo mouse callback img = %d, x = %d, y = %d.",
// me.image, me.x, me.y);
switch (me.event)
{
case CV_EVENT_LBUTTONDOWN:
{
//trace_verbeuse("LB DOWN x = %d, y = %d.", me.x, me.y);
rdi0.x = me.x;
rdi0.y = me.y;
rdi1 = rdi0;
etat_souris = 1;
if((demo_en_cours != nullptr) && (demo_en_cours->props.requiert_masque))
{
masque_clic(me.x,me.y);
compute_Ia();
update_Ia();
}
break;
}
case CV_EVENT_MOUSEMOVE:
{
if(etat_souris == 1)
{
rdi1.x = me.x;
rdi1.y = me.y;
if((demo_en_cours != nullptr) && (demo_en_cours->props.requiert_masque))
masque_clic(me.x,me.y);
compute_Ia();
update_Ia();
infos("updated ia.");
}
break;
}
case CV_EVENT_LBUTTONUP:
{
//trace_verbeuse("LB UP x = %d, y = %d.", me.x, me.y);
if(etat_souris == 1)
{
rdi1.x = me.x;
rdi1.y = me.y;
compute_Ia();
etat_souris = 0;
if(demo_en_cours != nullptr)
{
if(demo_en_cours->props.requiert_roi)
{
int minx = min(rdi0.x, rdi1.x);
int miny = min(rdi0.y, rdi1.y);
int maxx = max(rdi0.x, rdi1.x);
int maxy = max(rdi0.y, rdi1.y);
Rect rdi(minx, miny, maxx - minx, maxy - miny);
trace_majeure("Set rdi(%d,%d,%d,%d).",
rdi.x, rdi.y, rdi.width, rdi.height);
demo_en_cours->set_roi(I0, rdi);
update();
}
else if(demo_en_cours->props.requiert_masque)
{
update();
}
else
demo_en_cours->on_mouse(me.x, me.y, me.event, me.image);
}
}
break;
}
}
mutex.unlock();
}
| 2,864
|
C++
|
.cc
| 89
| 24.606742
| 80
| 0.565217
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,991
|
ocvdemo.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/ocvdemo.cc
|
/** @file ocvdemo-main.cc
Copyright 2016 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "ocvdemo.hpp"
#include "mmi/theme.hpp"
int main(int argc, char **argv)
{
utils::CmdeLine cmdeline(argc, argv);
utils::init(cmdeline, "ocvdemo", "ocvdemo");
utils::journal::set_global_min_level(utils::journal::TRACE_TARGET_FILE, utils::journal::AL_VERBOSE);
//utils::TraceManager::set_global_min_level(TraceManager::TraceTarget::TRACE_TARGET_STD, TraceLevel::AL_NONE);
std::string dts = utils::get_current_date_time();
trace_majeure("\nFichier journal pour l'application OCVDEMO, version %d.%02d\nDate / heure lancement application : %s\n**************************************\n**************************************\n**************************************",
VMAJ, VMIN, dts.c_str());
langue.load("./data/odemo-lang.xml");
Gtk::Main kit(argc, argv);
utils::mmi::charge_themes();
utils::mmi::installe_theme("dark");
OCVDemo demo(cmdeline);
demo.demarre_interface();
return 0;
}
| 1,778
|
C++
|
.cc
| 34
| 48.441176
| 241
| 0.683603
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,992
|
demos-registration.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demos-registration.cc
|
/** @file demos-registration.cc
* Registration of the different demo items.
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "ocvdemo.hpp"
#include "demo-items/filtrage.hpp"
#include "demo-items/morpho-demo.hpp"
#include "demo-items/gradient-demo.hpp"
#include "demo-items/photographie.hpp"
#include "demo-items/reco-demo.hpp"
#include "demo-items/histo.hpp"
#include "demo-items/seuillage.hpp"
#include "demo-items/video-demo.hpp"
#include "demo-items/espaces-de-couleurs.hpp"
#include "demo-items/3d.hpp"
#include "demo-items/misc.hpp"
#include "demo-items/segmentation.hpp"
#include "demo-items/appauto.hpp"
#include "demo-items/demo-skeleton.hpp"
#include "demo-items/ocr.hpp"
#include "demo-items/fourier-demo.hpp"
//add a line to include your new demo header file patterned just as "demo-skeleton.hpp"
void OCVDemo::add_demos()
{
add_demo(new IFTDemo());
add_demo(new DemoDetectionPeriode());
add_demo(new DemoDetectionTranslation());
add_demo(new DemoDetectionRotation());
add_demo(new DetFlouDemo());
add_demo(new ScoreShiTomasi());
add_demo(new DemoRedim());
add_demo(new DemoOCR());
add_demo(new DemoSousSpectrale());
add_demo(new DemoSuperpixels());
add_demo(new DemoFaceRecognizer());
add_demo(new DemoAppAuto());
add_demo(new DemoHog());
add_demo(new DemoLocalisation3D());
add_demo(new DemoBalleTennis());
add_demo(new DemoSqueletisation());
add_demo(new DemoMahalanobis());
add_demo(new DemoFiltreGabor());
add_demo(new CameraDemo());
add_demo(new RectificationDemo());
add_demo(new StereoCalDemo());
add_demo(new StereoCalLiveDemo());
add_demo(new HDRDemo());
add_demo(new EpiDemo());
add_demo(new DispMapDemo());
add_demo(new MatchDemo());
add_demo(new ContourDemo());
add_demo(new CamCalDemo());
add_demo(new DFTDemo());
add_demo(new InpaintDemo());
add_demo(new PanoDemo());
add_demo(new WShedDemo());
add_demo(new SousArrierePlanDemo());
add_demo(new DemoFiltrage());
add_demo(new HSVDemo());
add_demo(new MorphoDemo());
add_demo(new CannyDemo());
add_demo(new HoughDemo());
add_demo(new HoughCDemo());
add_demo(new GradientDemo());
add_demo(new LaplaceDemo());
add_demo(new NetDemo());
add_demo(new CornerDemo());
add_demo(new HistoEgalisationDemo());
add_demo(new HistoCalc());
add_demo(new HistoBP());
add_demo(new Seuillage());
add_demo(new GrabCutDemo());
add_demo(new OptFlowDemo());
add_demo(new CamShiftDemo());
add_demo(new RectDemo());
add_demo(new DTransDemo());
add_demo(new CascGenDemo("casc-visage"));
add_demo(new CascGenDemo("casc-profile"));
add_demo(new CascGenDemo("casc-yeux"));
add_demo(new CascGenDemo("casc-plate"));
add_demo(new CascGenDemo("casc-sil"));
add_demo(new SkeletonDemo());
// Here is the spot to add a new demo. Copy/Paste and edit to match the name of your class.
}
| 3,638
|
C++
|
.cc
| 96
| 34.989583
| 92
| 0.735052
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,993
|
ocvdemo-export.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/ocvdemo-export.cc
|
/** @file export-doc.cc
Copyright 2016 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "ocvdemo.hpp"
std::string OCVDemo::export_demos(utils::model::Node &cat, Localized::Language lg)
{
std::string s;
auto nb_demos = cat.get_children_count("demo");
for(auto i = 0u; i < nb_demos; i++)
{
auto demo = cat.get_child_at("demo", i);
s += "<tr>";
if(i == 0)
{
s += "<td rowspan=\"" + utils::str::int2str(nb_demos) + "\"><b>";
s += cat.get_localized().get_value(lg);
s += "</b></td>";
}
s += "<td>" + demo.get_localized().get_value(lg) + "</td>";
//s += "<td>" + demo.get_localized().get_description(lg) + "</td>";
auto id = demo.name();
NodeSchema *ns = fs_racine->get_schema(id);
if(ns != nullptr)
{
std::string s2 = "<br/><img src=\"imgs/" + id + ".jpg\" alt=\"" + demo.get_localized().get_value(lg) + "\"/>";
s += "<td>" + ns->name.get_description(lg) + s2 + "</td>";
}
else
{
s += "<td></td>";
avertissement("Pas de schema / description pour %s.", id.c_str());
}
s += "</tr>";
}
return s;
}
std::string OCVDemo::export_html(Localized::Language lg)
{
std::string s = "<table class=\"formtable\">\n";
if(lg == Localized::Language::LANG_FR)
s += std::string(R"(<tr><td colspan="2"><b>Démonstration</b></td><td><b>Description</b></td></tr>)") + "\n";
else
s += std::string(R"(<tr><td colspan="2"><b>Demonstration</b></td><td><b>Description</b></td></tr>)") + "\n";
for(auto cat1: tdm.children("cat"))
{
for(auto cat2: cat1.children("cat"))
{
s += export_demos(cat2, lg);
}
s += export_demos(cat1, lg);
}
s += "</table>\n";
return s;
}
void OCVDemo::export_captures()
{
for(auto cat1: tdm.children("cat"))
{
for(auto cat2: cat1.children("cat"))
{
export_captures(cat2);
}
export_captures(cat1);
}
}
void OCVDemo::export_captures(utils::model::Node &cat)
{
auto nb_demos = cat.get_children_count("demo");
for(auto i = 0u; i < nb_demos; i++)
{
auto demo = cat.get_child_at("demo", i);
auto id = demo.get_attribute_as_string("name");
// Quelques démo requièrent une caméra pour fonctionner
if(!demo.get_attribute_as_boolean("export"))
continue;
trace_majeure("Export démo [%s]...", id.c_str());
// Arrête tout
setup_demo(tdm.get_child_at("cat", 0));
signal_une_trame_traitee.clear();
// Démarre nouvelle démo
setup_demo(demo);
infos("Attente fin traitement...");
// Il n'y a qu'un seul thread GTK => doit laisser la main
// aux autres tâches
//signal_une_trame_traitee.wait(); => non car bloquant pour GTK
while(!signal_une_trame_traitee.is_raised())
{
if(Gtk::Main::events_pending())
Gtk::Main::iteration();
}
infos("Fin traitement ok.");
std::string s = "../../site/data/log/opencv/demo/list/imgs/";
s += id + ".jpg";
Mat A = mosaique.get_global_img();
if(A.data == nullptr)
{
avertissement("A.data == nullptr");
continue;
}
cv::pyrDown(A, A);
cv::pyrDown(A, A);
trace_verbeuse("taille finale = %d * %d.", A.cols, A.rows);
imwrite(s, A);
if(!utils::files::file_exists(s))
avertissement("Echec lors de la sauvegarde du fichier.");
}
}
| 4,093
|
C++
|
.cc
| 119
| 29.613445
| 116
| 0.612567
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,994
|
ocvdemo-mmi.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/ocvdemo-mmi.cc
|
/** @file ocvdemo-mmi.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "ocvdemo.hpp"
#include <glibmm.h>
void OCVDemo::setup_menu()
{
infos("menu setup-ocvdemo-mmi");
agroup = Gtk::ActionGroup::create();
agroup->add( Gtk::Action::create("MenuMain", "_Menu") );
agroup->add( Gtk::Action::create("Input", langue.get_item("menu-entree")),
sigc::mem_fun(*this, &OCVDemo::on_menu_entree) );
agroup->add( Gtk::Action::create("Save", langue.get_item("save")),
sigc::mem_fun(*this, &OCVDemo::on_b_save ) );
agroup->add( Gtk::Action::create("Open", langue.get_item("Ouvrier")),
sigc::mem_fun(*this, &OCVDemo::on_b_open) );
agroup->add( Gtk::Action::create("Quit", langue.get_item("menu-quitter")),
sigc::mem_fun(*this, &OCVDemo::on_menu_quitter) );
Glib::RefPtr<Gtk::UIManager> m_refUIManager =
Gtk::UIManager::create();
m_refUIManager->insert_action_group(agroup);
wnd.add_accel_group(m_refUIManager->get_accel_group());
Glib::ustring ui_info =
"<ui>"
" <menubar name='MenuBar'>"
" <menu action='MenuMain'>"
" <menuitem action='Input'/>"
" <menuitem action='Save'/>"
" <menuitem action='Open'/>"
" <menuitem action='Quit'/>"
" </menu>"
" </menubar>"
"</ui>";
infos("add-ui ocvdemo-mmi");
m_refUIManager->add_ui_from_string(ui_info);
Gtk::Widget *pMenuBar = m_refUIManager->get_widget("/MenuBar");
vbox.pack_start(*pMenuBar, Gtk::PACK_SHRINK);
infos("After add-ui ocvdemo-mmi");
}
void OCVDemo::on_menu_entree()
{
infos("on menu entree. ocvdemo-mmi");
auto cp = utils::model::Node::create_ram_node(modele_global.schema());
cp.copy_from(modele_global);
if(utils::mmi::NodeDialog::display_modal(cp) == 0)
modele_global.copy_from(cp);
}
void OCVDemo::on_menu_quitter()
{
on_b_exit();
}
bool OCVDemo::on_delete_event(GdkEventAny *event)
{
on_b_exit();
return true;
}
void OCVDemo::on_b_infos()
{
infos("on_b_infos ocvdemo-mmi");
Gtk::AboutDialog ad;
ad.set_copyright("(C) 2015 - 2017 TSD Conseil / J.A.");
Glib::RefPtr<Gdk::Pixbuf> pix = Gdk::Pixbuf::create_from_file(utils::get_img_path() + "/logo.png");
ad.set_logo(pix);
//ad.set_logo_icon_name("OpenCV demonstrator");
ad.set_name(langue.get_item("main-title") + "\n");
ad.set_program_name(langue.get_item("main-title"));
if(modele_global.get_attribute_as_boolean("mode-appli-ext"))
{
ad.set_copyright("(C) 2015 - 2017 TSD Conseil");
}
else
{
char buf[500];
std::string s = langue.get_item("rev");
sprintf(buf, s.c_str(), VMAJ, VMIN, VPATCH, OCV_VMAJ, OCV_VMIN, OCV_VPATCH);
ad.set_version(buf);
ad.set_copyright("(C) 2015 - 2016 TSD Conseil / J.A. and contributors");
ad.set_license("LGPL");
ad.set_license_type(Gtk::LICENSE_LGPL_3_0);
ad.set_website("http://www.tsdconseil.fr/log/opencv/demo/index-en.html");
ad.set_website_label("http://www.tsdconseil.fr/index-en.html");
std::vector<Glib::ustring> v;
v.push_back("J.A. / TSD Conseil");
ad.set_authors(v);
std::string cmts;
cmts += langue.get_item("credit-image") + "\n";
cmts += langue.get_item("credit-image-opencv") + "\n";
cmts += langue.get_item("credit-image-carte") + "\n";
cmts += langue.get_item("credit-image-autre");
ad.set_comments(cmts);
}
ad.set_wrap_license(true);
ad.set_position(Gtk::WIN_POS_CENTER);
ad.run();
}
void OCVDemo::maj_bts()
{
int ho = has_output();
b_save.set_sensitive(ho);
}
void OCVDemo::on_b_open()
{
img_selecteur.on_b_open();
}
void OCVDemo::on_b_save()
{
infos("Save.");
if(!has_output())
{
avertissement("Pas de sortie dispo.");
return;
}
//auto s = utils::mmi::dialogs::save_dialog(langue.get_item("title-save"),
//"*.jpg,*.jp2,*.png,*.bmp", "Image");
std::string s, title = langue.get_item("title-save");
Gtk::FileChooserDialog dialog(title, Gtk::FILE_CHOOSER_ACTION_SAVE);
dialog.set_position(Gtk::WIN_POS_CENTER_ALWAYS);
if(utils::mmi::mainWindow != nullptr)
dialog.set_transient_for(*utils::mmi::mainWindow);
dialog.set_modal(true);
//Add response buttons the the dialog:
dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
//Add filters, so that only certain file types can be selected:
Glib::RefPtr<Gtk::FileFilter> filter;
filter = Gtk::FileFilter::create();
filter->set_name("Image JPEG");
filter->add_mime_type("*.jpg");
dialog.add_filter(filter);
filter = Gtk::FileFilter::create();
filter->set_name("Image PNG");
filter->add_mime_type("*.png");
dialog.add_filter(filter);
filter = Gtk::FileFilter::create();
filter->set_name("Image JPEG 2000");
filter->add_mime_type("*.j2");
dialog.add_filter(filter);
filter = Gtk::FileFilter::create();
filter->set_name("Image BMP");
filter->add_mime_type("*.bmp");
dialog.add_filter(filter);
//Show the dialog and wait for a user response:
int result = dialog.run();
//Handle the response:
if(result == Gtk::RESPONSE_OK)
{
std::string filename = dialog.get_filename();
std::string ext = utils::files::get_extension(filename);
if(ext.size() == 0)
{
auto s = dialog.get_filter()->get_name();
if(s == "Image JPEG")
ext = ".jpg";
else if(s == "Image JPEG 2000")
ext = ".jp2";
else if(s == "Image BMP")
ext = ".bmp";
else if(s == "Image PNG")
ext = ".png";
filename += ext;
}
dialog.hide();
if(demo_en_cours->output.nout == 1)
imwrite(filename, get_current_output());
else
{
auto fnaked = utils::files::remove_extension(filename);
auto ext = utils::files::get_extension(filename);
for(auto i = 0; i < demo_en_cours->output.nout; i++)
imwrite(fnaked + utils::str::int2str(i) + "." + ext, demo_en_cours->output.images[i]);
}
}
}
void OCVDemo::on_dropped_file(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time)
{
if ((selection_data.get_length() >= 0) && (selection_data.get_format() == 8))
{
img_selecteur.on_dropped_file(context, x, y, selection_data, info, time);
# if 0
std::vector<Glib::ustring> file_list;
file_list = selection_data.get_uris();
if(file_list.size() > 0)
{
Glib::ustring path = Glib::filename_from_uri(file_list[0]);
//do something here with the 'filename'. eg open the file for reading
std::string s = path;//file_list[0];//path;
infos("DnD: %s.", s.c_str());
utils::model::Node new_model = utils::model::Node::create_ram_node(modele_global.schema());
new_model.copy_from(modele_global);
new_model.set_attribute("sel", 1);
new_model.set_attribute("file-schema/path", s);
modele_global.copy_from(new_model);
context->drag_finish(true, false, time);
return;
}
# endif
}
else
context->drag_finish(false, false, time);
}
void OCVDemo::on_b_exit()
{
trace_majeure("Fin normale de l'application ocvdemo-mmi.");
ODEvent evt;
evt.type = ODEvent::FIN;
event_fifo.push(evt);
utils::files::delete_file(lockfile);
wnd.hide();
OCVDemoFinAppli odfa;
dispatch(odfa);
exit(0);
}
void OCVDemo::maj_langue_systeme()
{
trace_majeure("maj_langue_systeme() ocvdemo-mmi.");
int sel = modele_global.get_attribute_as_int("langue");
utils::model::Localized::current_language = (Localized::LanguageEnum) (sel + Localized::LANG_FR);
}
void OCVDemo::maj_langue()
{
trace_majeure("maj_langue() ocvdemo-mmi.");
auto prev_lg = utils::model::Localized::current_language;
maj_langue_systeme();
b_save.set_label(langue.get_item("save"));
b_save.set_tooltip_markup(langue.get_item("save-tt"));
b_exit.set_label(langue.get_item("quitter"));
b_exit.set_tooltip_markup(langue.get_item("quitter-tt"));
b_infos.set_label(langue.get_item("apropos"));
b_infos.set_tooltip_markup(langue.get_item("apropos-tt"));
b_entree.set_label(langue.get_item("entree"));
b_open.set_label(langue.get_item("b-ouvrir"));
b_entree.set_tooltip_markup(langue.get_item("entree-tt"));
b_open.set_tooltip_markup(langue.get_item("entree-tt"));
// Apparently OpenCV windows support only ISO-8859-1
// Seems OpenCV does the right thing now.
// Correction. olnly works with OpenCV on Linux.
// Still broke on windows.
#ifdef WIN
titre_principal = utils::str::utf8_to_latin(langue.get_item("resultats"));
#else
titre_principal = langue.get_item("resultats");
#endif
//char bf[500];
//sprintf(bf, " [version %d.%d.%d]", VMAJ, VMIN, VPATCH);
wnd.set_title(langue.get_item("main-title"));// + std::string(bf));
if(utils::model::Localized::current_language != prev_lg)
{
lock = true;
vue_arbre.maj_langue();
lock = false;
utils::mmi::SelectionChangeEvent sce;
sce.new_selection = vue_arbre.get_selection();
this->on_event(sce);
}
barre_outil_dessin.maj_lang();
img_selecteur.maj_langue();
}
| 9,812
|
C++
|
.cc
| 269
| 32.527881
| 156
| 0.66568
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,995
|
test-webcam.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/test-webcam.cc
|
/** @file test-webcam.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include <opencv2/opencv.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/features2d/features2d.hpp>
#include "mmi/gtkutil.hpp"
#include "cutil.hpp"
using namespace cv;
int main(int argc, char **argv)
{
utils::CmdeLine cmdeline(argc, argv);
utils::init(cmdeline, "ocvdemo", "test-webcam");
utils::journal::set_global_min_level(utils::journal::TraceTarget::TRACE_TARGET_FILE, utils::journal::AL_VERBOSE);
VideoCapture cam(0);
utils::langue.load("./data/lang.xml");
Gtk::Main kit(argc, argv);
if(!cam.isOpened())
{
utils::mmi::dialogs::affiche_erreur(utils::langue.get_item("cam-err-1"), utils::langue.get_item("cam-err-2"), utils::langue.get_item("cam-err-3"));
return -1;
}
Mat I;
do
{
cam >> I;
if(I.data == nullptr)
break;
// A FAIRE : diviser la résolution par 2 et passer en niveaux de gris
// [...]
cv::pyrDown(I, I);
imshow("Camera #0", I);
} while (waitKey(30) == -1); // Sortie dès que appui sur une touche
return 0;
}
| 1,877
|
C++
|
.cc
| 47
| 35.914894
| 151
| 0.706696
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,996
|
ocvdemo-misc.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/ocvdemo-misc.cc
|
/** @file ocvdemo.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "ocvdemo.hpp"
// Conversion latin -> utf8:
// iconv -f latin1 -t utf-8 data/lang8859.xml > data/lang.xml
using utils::model::Localized;
static OCVDemo *instance = nullptr;
OCVDemoItem::OCVDemoItem()
{
output.nout = 1;
props.requiert_roi = false;
props.requiert_masque = false;
props.preserve_ratio_aspet = false;
// Default demo item requires only 1 input image / video
props.input_min = 1;
props.input_max = 1;
}
static void prepare_image(cv::Mat &I)
{
if(I.channels() == 1)
cv::cvtColor(I, I, CV_GRAY2BGR);
if(I.depth() == CV_32F)
I.convertTo(I, CV_8UC3);
}
void OCVDemo::thread_calcul()
{
for(;;)
{
auto evt = event_fifo.pop();
switch(evt.type)
{
////////////////////////////
// Fin de l'application
////////////////////////////
case ODEvent::FIN:
trace_majeure("Fin du thread de calcul.");
signal_thread_calcul_fin.raise();
return;
////////////////////////////
// Calcul sur une image
////////////////////////////
case ODEvent::CALCUL:
try
{
calcul_status = evt.demo->proceed(evt.demo->input, evt.demo->output);
}
catch(...)
{
// TODO -> transmettre msg erreur
//utils::mmi::dialogs::show_error(langue.get_item("err-opencv-title"),
// langue.get_item("err-opencv-msg"), langue.get_item("err-opencv-msg2"));
break;
}
signal_calcul_termine.raise();
break;
default:
erreur("%s: invalid event.", __func__);
return;
}
}
}
bool OCVDemo::are_all_video_ok()
{
bool res = true;
for(auto &vc: video_captures)
if(!vc.isOpened())
res = false;
return res;
}
void OCVDemo::thread_video()
{
std::vector<cv::Mat> tmp;
for(;;)
{
debut:
if(video_stop)
{
video_stop = false;
video_en_cours = false;
signal_video_suspendue.raise();
signal_video_demarre.wait();
}
while(!entree_video || !are_all_video_ok() || (video_captures.size() == 0))
{
video_en_cours = false;
signal_video_suspendue.raise();
signal_video_demarre.wait();
}
video_en_cours = true;
tmp.resize(video_captures.size());
mutex_video.lock();
for(auto i = 0u; i < video_captures.size(); i++)
{
//trace_verbeuse("[tvideo] lecture trame video[%d]...", i);
video_captures[i] >> tmp[i];
//trace_verbeuse("[tvideo] ok.");
utils::hal::sleep(10);
if(tmp[i].empty())
{
trace_majeure("[tvideo] Fin de vidéo : redémarrage.");
if(video_fp.size() > 0)
{
// TODO: redémarrage de toutes les vidéos en même temps
video_captures[i].release();
video_captures[i].open(video_fp);
}
mutex_video.unlock();
goto debut; // Hack to fix
}
}
mutex_video.unlock();
// Prévention deadlock
if(video_stop)
{
video_stop = false;
video_en_cours = false;
signal_video_suspendue.raise();
signal_video_demarre.wait();
continue;
}
//trace_verbeuse("gtk dispatcher...");
gtk_dispatcher.on_event(tmp);
// Pour éviter le deadlock, attends soit que :
// - fin de traitement
// - ou demande d'arrêt de la vidéo
for(;;)
{
if(signal_image_video_traitee.wait(10) == 0)
break;
if(video_stop)
break;
}
}
}
void OCVDemo::on_video_image(const std::vector<cv::Mat> &tmp)
{
// Récupération d'une trame vidéo (mais ici on est dans le thread GTK)
// (Recovery of a video frame (but here we are in the GTK thread))
//trace_verbeuse("on_video_image...");
if(demo_en_cours != nullptr)
{
I0 = tmp[0];
auto &v = demo_en_cours->input.images;
for(auto i = 0u; i < tmp.size(); i++)
{
if(v.size() <= i)
v.push_back(tmp[i]);
else
v[i] = tmp[i];
}
update();
}
signal_image_video_traitee.raise();
}
void OCVDemo::on_b_masque_raz()
{
masque_raz();
update_Ia();
update();
}
void OCVDemo::masque_clic(int x0, int y0)
{
if(this->outil_dessin_en_cours == 0)
{
for(auto i = -2; i <= 2; i++)
{
for(auto j = -2; j <= 2; j++)
{
int x = x0 + i;
int y = y0 + j;
Ia.at<Vec3b>(y,x).val[0] = 255;
Ia.at<Vec3b>(y,x).val[1] = 255;
Ia.at<Vec3b>(y,x).val[2] = 255;
demo_en_cours->input.mask.at<unsigned char>(y,x) = 255;
}
}
}
else
{
// Floodfill
cv::Mat mymask = Mat::zeros(Ia.rows+2,Ia.cols+2,CV_8U);
cv::floodFill(Ia, mymask, Point(x0,y0), Scalar(255,255,255));
Mat roi(mymask, Rect(1,1,Ia.cols,Ia.rows));
this->demo_en_cours->input.mask |= roi;
update();
}
}
// Calcul d'une sortie à partir de l'image I0
// avec mise à jour de la mosaique de sortie.
// (Calculating an output from the image I0 with updating the output mosaic)
void OCVDemo::update()
{
if(demo_en_cours == nullptr)
return;
// Première fois que la démo est appelée avec des entrées (I0) valides ?
// (First time the demo is called with the inputs (I0) valid?)
if(first_processing)
{
first_processing = false;
if(demo_en_cours->props.requiert_masque)
demo_en_cours->input.mask = cv::Mat::zeros(I0.size(), CV_8U);
}
//trace_verbeuse("Acquisition mutex_update...");
mutex_update.lock();
//trace_verbeuse("mutex_update ok.");
sortie_en_cours = false;
if(modele_demo.is_nullptr())
{
mutex_update.unlock();
return;
}
I1 = I0.clone();
auto s = modele.to_xml();
infos("Calcul [%s], img: %d*%d, %d chn, model =\n%s",
demo_en_cours->props.id.c_str(),
I0.cols, I0.rows, I0.channels(),
s.c_str());
// RAZ des images de sorties
for(auto i = 0u; i < DEMO_MAX_IMG_OUT; i++)
demo_en_cours->output.images[i] = cv::Mat();
// Appel au thread de calcul
ODEvent evt;
evt.type = ODEvent::CALCUL;
evt.demo = demo_en_cours;
evt.modele = modele;
event_fifo.push(evt);
// Attente fin de calcul
signal_calcul_termine.wait();
if(calcul_status)
{
avertissement("ocvdemo: Echec calcul.");
auto s = demo_en_cours->output.errmsg;
if(langue.has_item(s))
s = langue.get_item(s);
utils::mmi::dialogs::affiche_avertissement("Erreur de traitement",
langue.get_item("echec-calcul"), s);
mutex_update.unlock();
return;
}
else
{
infos("Calcul [%s] ok.", demo_en_cours->props.id.c_str());
if(demo_en_cours->output.nout > 0)
sortie_en_cours = true;
else
sortie_en_cours = false;
}
std::vector<cv::Mat> lst;
compute_Ia();
prepare_image(Ia);
lst.push_back(Ia);
unsigned int img_count = demo_en_cours->output.nout;
if(img_count && (demo_en_cours->output.images[img_count - 1 ].data == nullptr))
{
avertissement("Img count = %d, et image de sortie non initialisée.", img_count);
img_count = 1;
}
else if(img_count == 0)
{
if(Ia.data != nullptr)
img_count = 1;
else
lst.clear();
}
std::vector<std::string> titres;
for(auto j = 0u; j < img_count; j++)
{
if(j > 0)
{
prepare_image(demo_en_cours->output.images[j]);
lst.push_back(demo_en_cours->output.images[j]);
}
char buf[50];
sprintf(buf, "o[id=%d]", j);
std::string s = "";
if(modele_demo.has_child(std::string(buf)))
{
auto n = modele_demo.get_child(std::string(buf));
s = n.get_localized().get_localized();
}
if((j < 4) && (demo_en_cours->output.names[j].size() > 0))
{
s = demo_en_cours->output.names[j];
if(langue.has_item(s))
s = langue.get_item(s);
}
// titres.push_back(utils::str::utf8_to_latin(s)); // à passer en utf-8 dès que fenêtre GTK fait
titres.push_back(s);
}
mosaique.preserve_ratio_aspet = demo_en_cours->props.preserve_ratio_aspet;
mosaique.show_multiple_images(titre_principal, lst, titres);
maj_bts();
//trace_verbeuse("Liberation mutex_update...");
mutex_update.unlock();
signal_une_trame_traitee.raise();
cv::waitKey(10); // Encore nécessaire à cause de la fenêtre OpenCV
}
///////////////////////////////////////////////////////////////
// Détection d'un changement sur le modèle
// - global
// ==> maj_entree
// - ou de la démo en cours
// ==> update_demo, update
///////////////////////////////////////////////////////////////
void OCVDemo::on_event(const ChangeEvent &ce)
{
trace_verbeuse("change-event: %d / %s",
(int) ce.type, ce.path[0].name.c_str());
if(ce.type != ChangeEvent::GROUP_CHANGE)
return;
if(lock)
return;
lock = true;
if(ce.path[0].name == "global-schema")
{
trace_verbeuse("Changement sur configuration globale");
lock = false;
maj_langue();
maj_entree();
modele_global.save(chemin_fichier_config);
maj_bts();
return;
}
trace_verbeuse("Change event detected.");
update();
lock = false;
maj_bts();
}
void OCVDemo::add_demo(OCVDemoItem *demo)
{
items.push_back(demo);
auto schema = fs_racine->get_schema(demo->props.id);
demo->modele = utils::model::Node::create_ram_node(schema);
demo->modele.add_listener(this);
demo->add_listener(this);
}
void OCVDemo::on_event(const ImageSelecteurRefresh &e)
{
if(!ignore_refresh)
maj_entree();
}
void OCVDemo::on_event(const OCVDemoItemRefresh &e)
{
update();
}
void OCVDemo::release_all_videos()
{
for(auto &vc: video_captures)
if(vc.isOpened())
vc.release();
video_captures.clear();
}
///////////////////////////////////
// Mise à jour du flux / image d'entrée (update flux / input image)
// Requiert : demo_en_cours bien défini (requires: demo_en_cours clear)
///////////////////////////////////
void OCVDemo::maj_entree()
{
if(demo_en_cours == nullptr)
return;
first_processing = true;
entree_video = false;
trace_verbeuse("lock...");
mutex_video.lock();
trace_verbeuse("lock ok.");
release_all_videos();
// Idée :
// - transformer video_capture en un tableau
// - mais on peut avoir un fichier vidéo et une image en même temps !
//
// si mode vidéo.
std::vector<ImageSelecteur::SpecEntree> entrees;
img_selecteur.get_entrees(entrees);
unsigned int vid = 0; // Index in video list
demo_en_cours->input.images.resize(entrees.size());
for(auto i = 0u; i < entrees.size(); i++)
{
auto &se = entrees[i];
if(se.is_video())
{
infos("Ouverture fichier video [%s]...", se.chemin.c_str());
int res;
video_captures.push_back(cv::VideoCapture());
if(se.type == ImageSelecteur::SpecEntree::TYPE_WEBCAM)
res = video_captures[vid].open(se.id_webcam);
else
res = video_captures[vid].open(se.chemin);
trace_verbeuse("Effectué.");
if(!res)
{
utils::mmi::dialogs::affiche_erreur(langue.get_item("ech-vid-tit"),
langue.get_item("ech-vid-sd"),
langue.get_item("ech-vid-d") + "\n" + se.chemin);
mutex_video.unlock();
return;
}
video_fp = se.chemin; // TODO : vecteur
entree_video = true;
video_captures[vid] >> I0; // TODO: à supprimer
vid++;
}
else
{
demo_en_cours->input.images[i] = se.img;
I0 = se.img.clone();
if(I0.data == nullptr)
{
utils::mmi::dialogs::affiche_erreur("Erreur",
"Impossible de charger l'image", "");
destroyWindow(titre_principal);
mosaique.callback_init_ok = false;
}
}
}
mutex_video.unlock();
if(video_captures.size() > 0)
signal_video_demarre.raise();
else
update();
maj_bts();
}
OCVDemoItem *OCVDemo::recherche_demo(const std::string &nom)
{
for(auto demo: items)
if(demo->props.id == nom)
return demo;
erreur("Demo non trouve (%s).", nom.c_str());
return nullptr;
}
void OCVDemo::setup_demo(const utils::model::Node &sel)
{
auto id = sel.get_attribute_as_string("name");
auto s = sel.get_localized_name();
trace_majeure("Selection changed: %s (%s).", id.c_str(), s.c_str());
while(video_en_cours)
{
signal_video_demarre.clear();
signal_video_suspendue.clear();
video_stop = true;
infos("interruption flux video...");
signal_video_suspendue.wait();
infos("Flux video interrompu.");
}
mutex_update.lock();
trace_verbeuse("Debut setup...");
cadre_proprietes.remove();
if (rp != nullptr)
{
delete rp;
rp = nullptr;
}
modele_demo = sel;
if((sel.schema()->name.get_id() != "demo")
|| (fs_racine->get_schema(id) == nullptr))
{
img_selecteur.hide();
destroyWindow(titre_principal);
mosaique.callback_init_ok = false;
mutex_update.unlock();
maj_bts();
return;
}
//auto schema = fs_racine->get_schema(id);
//modele = utils::model::Node::create_ram_node(schema);
//modele = demo.
//modele.add_listener(this);
/*{
utils::mmi::NodeViewConfiguration vconfig;
vconfig.show_desc = true;
vconfig.show_main_desc = true;
rp = new utils::mmi::NodeView(&wnd, modele, vconfig);
cadre_proprietes.set_label(s);
cadre_proprietes.add(*(rp->get_widget()));
cadre_proprietes.show();
cadre_proprietes.show_all_children(true);
}*/
trace_verbeuse("setup demo...");
///////////////////////////////////////////
// - Localise la demo parmi les démos enregistrées
// - Initialise les zones d'intérêt
// - Appel maj_entree()
// - Affiche la barre d'outil si nécessaire
///////////////////////////////////////////
//en:
// - Locates the demo from the demos recorded
// - Initializes areas of interest
// - Call maj_entree() eg. major_entry()
// - Displays the toolbar if necessary
//////////////////////////////////////////
trace_verbeuse("update_demo()...");
namedWindow(titre_principal, CV_WINDOW_NORMAL);
//en: current demo
demo_en_cours = nullptr;
for(auto demo: items)
{
if(demo->props.id == id)
{
demo_en_cours = demo;
rdi0.x = demo->input.roi.x;
rdi0.y = demo->input.roi.y;
rdi1.x = demo->input.roi.x + demo->input.roi.width;
rdi1.y = demo->input.roi.y + demo->input.roi.height;
modele = demo->modele;
{
utils::mmi::NodeViewConfiguration vconfig;
vconfig.show_desc = true;
vconfig.show_main_desc = true;
rp = new utils::mmi::NodeView(&wnd, modele, vconfig);
cadre_proprietes.set_label(s);
cadre_proprietes.add(*(rp->get_widget()));
cadre_proprietes.show();
cadre_proprietes.show_all_children(true);
}
demo->input.model = modele;
/* code mort
* dead code
demo->setup_model(modele);
*/
// Réinitialisation des images de sorties (au cas où elles pointaient vers les images d'entrées)
// Resetting outputs images ( in case they pointed to the pictures of inputs )
//for(auto i = 0u; i < DEMO_MAX_IMG_OUT; i++)
// demo->
/* code mort
* dead code
if(demo->configure_ui())
break;
*/
if(demo_en_cours->props.requiert_masque)
barre_outil_dessin.montre();
else
barre_outil_dessin.cache();
if(this->modele_global.get_attribute_as_boolean("afficher-sources"))
img_selecteur.show();
//img_selecteur.present();
ignore_refresh = true;
img_selecteur.raz();
img_selecteur.nmin = demo->props.input_min;
img_selecteur.nmax = demo->props.input_max;
for(const auto &img: modele_demo.children("img"))
img_selecteur.ajoute_fichier(img.get_attribute_as_string("path"));
int nmissing = demo->props.input_min - img_selecteur.get_nb_images();
trace_verbeuse("nmissing is %d ", nmissing );
if(nmissing > 0)
{
for(auto i = 0; i < nmissing; i++)
img_selecteur.ajoute_fichier(utils::get_fixed_data_path() + "/img/lena.jpg");
}
ignore_refresh = false;
}
}
if(demo_en_cours == nullptr)
{
avertissement("Demo non trouvee : %s", id.c_str());
std::string s = "";
for(auto demo: items)
s += demo->props.id + " ";
infos("Liste des demos disponibles :\n%s", s.c_str());
}
this->wnd.present();
//if((demo_en_cours != nullptr) )//&& demo_en_cours->props.requiert_mosaique)
//img_selecteur.present();
if(demo_en_cours && (demo_en_cours->props.requiert_masque))
barre_outil_dessin.montre();
maj_bts();
mutex_update.unlock();
trace_verbeuse("** SETUP SCHEMA TERMINE, MAJ ENTREE...");
maj_entree();
}
void OCVDemo::on_event(const utils::mmi::SelectionChangeEvent &e)
{
if(lock)
return;
sortie_en_cours = false;
if(e.new_selection.is_nullptr())
{
maj_bts();
return;
}
setup_demo(e.new_selection);
}
void OCVDemo::on_b_masque_gomme()
{
barre_outil_dessin.b_remplissage.set_active(false);
barre_outil_dessin.b_gomme.set_active(true);
outil_dessin_en_cours = 0;
}
void OCVDemo::on_b_masque_remplissage()
{
barre_outil_dessin.b_gomme.set_active(false);
barre_outil_dessin.b_remplissage.set_active(true);
outil_dessin_en_cours = 1;
}
void OCVDemo::compute_Ia()
{
if((demo_en_cours != nullptr) && (demo_en_cours->props.requiert_roi))
{
Ia = I0.clone();
cv::rectangle(Ia, rdi0, rdi1, Scalar(0,255,0), 3);
}
else if((demo_en_cours != nullptr) && (demo_en_cours->props.requiert_masque))
{
if((Ia.data == nullptr) || (Ia.size() != I1.size()))
Ia = demo_en_cours->output.images[0];
}
else if(demo_en_cours != nullptr)
Ia = demo_en_cours->output.images[0];
else
Ia = I0;
}
void OCVDemo::masque_raz()
{
Ia = I0.clone();
demo_en_cours->input.mask = cv::Mat::zeros(I0.size(), CV_8U);
}
void OCVDemo::update_Ia()
{
mosaique.update_image(0, Ia);
}
OCVDemo *OCVDemo::get_instance()
{
return instance;
}
OCVDemo::OCVDemo(utils::CmdeLine &cmdeline, const std::string &prefixe_modele_)
{
std::string prefixe_modele = prefixe_modele_;
if(prefixe_modele.size() == 0)
prefixe_modele = "odemo";
infos("OCVDemo::OCVDemo() (constructeur).");
utils::model::Localized::current_language = Localized::LANG_EN;
video_en_cours = false;
video_stop = false;
outil_dessin_en_cours = 0;
entree_video = false;
ignore_refresh = false;
demo_en_cours = nullptr;
etat_souris = 0;
instance = this;
lock = false;
rp = nullptr;
fs_racine = new utils::model::FileSchema(utils::get_fixed_data_path()
+ PATH_SEP + prefixe_modele + "-schema.xml");
utils::mmi::NodeViewConfiguration vconfig;
chemin_fichier_config = utils::get_current_user_path() + PATH_SEP + "cfg.xml";
if(!files::file_exists(chemin_fichier_config))
{
modele_global = utils::model::Node::create_ram_node(fs_racine->get_schema("global-schema"));
modele_global.save(chemin_fichier_config);
this->on_menu_entree();
}
else
{
modele_global = utils::model::Node::create_ram_node(fs_racine->get_schema("global-schema"), chemin_fichier_config);
if(modele_global.is_nullptr())
{
modele_global = utils::model::Node::create_ram_node(fs_racine->get_schema("global-schema"));
modele_global.save(chemin_fichier_config);
}
}
infos("Application configuration:\n%s\n", modele_global.to_xml().c_str());
maj_langue_systeme();
lockfile = utils::get_current_user_path() + PATH_SEP + "lock.dat";
if(utils::files::file_exists(lockfile))
{
if(utils::mmi::dialogs::check_dialog(
langue.get_item("check-lock-1"),
langue.get_item("check-lock-2"),
langue.get_item("check-lock-3")))
{
auto s = utils::mmi::dialogs::enregistrer_fichier(langue.get_item("save-log-title"),
".txt", "Log file");
if(s.size() > 0)
{
if(utils::files::get_extension(s).size() == 0)
s += ".txt";
utils::files::copy_file(s,
utils::get_current_user_path() + PATH_SEP + "ocvdemo-log.txt.old");
}
}
}
else
utils::files::save_txt_file(lockfile, "OCV demo est en cours.");
modele_global.add_listener(this);
wnd.add(vbox);
vbox.pack_start(frame_menu, Gtk::PACK_SHRINK);
barre_outils.set_icon_size(Gtk::ICON_SIZE_SMALL_TOOLBAR);
barre_outils.set_has_tooltip(false);
vbox.pack_start(barre_outils, Gtk::PACK_SHRINK);
barre_outils.add(b_entree);
barre_outils.add(b_save);
if(!modele_global.get_attribute_as_boolean("afficher-sources"))
barre_outils.add(b_open);
barre_outils.add(b_infos);
barre_outils.add(b_exit);
mosaique.add_listener(this);
b_save.set_stock_id(Gtk::Stock::SAVE);
b_open.set_stock_id(Gtk::Stock::OPEN);
b_exit.set_stock_id(Gtk::Stock::QUIT);
b_infos.set_stock_id(Gtk::Stock::ABOUT);
b_entree.set_stock_id(Gtk::Stock::PREFERENCES);
b_save.signal_clicked().connect(sigc::mem_fun(*this, &OCVDemo::on_b_save));
b_open.signal_clicked().connect(sigc::mem_fun(*this, &OCVDemo::on_b_open));
b_exit.signal_clicked().connect(sigc::mem_fun(*this, &OCVDemo::on_b_exit));
b_infos.signal_clicked().connect(sigc::mem_fun(*this, &OCVDemo::on_b_infos));
b_entree.signal_clicked().connect(sigc::mem_fun(*this, &OCVDemo::on_menu_entree));
vbox.pack_start(hpaned, Gtk::PACK_EXPAND_WIDGET);
auto schema = fs_racine->get_schema("ocv-demo");
tdm = utils::model::Node::create_ram_node(schema,
utils::get_fixed_data_path() + PATH_SEP + prefixe_modele + "-model.xml");
//"./data/odemo-model.xml");
auto s = tdm.to_xml();
infos("TOC = \n%s\n", s.c_str());
auto sc2 = tdm.schema();
s = sc2->to_string();
infos("TOC SCHEMA = \n%s\n", s.c_str());
add_demos();
std::vector<std::string> ids;
ids.push_back("cat");
ids.push_back("demo");
vue_arbre.set_liste_noeuds_affiches(ids);
vue_arbre.set_model(tdm);
vue_arbre.utils::CProvider<utils::mmi::SelectionChangeEvent>::add_listener(this);
hpaned.pack1(vue_arbre, true, true);
hpaned.pack2(cadre_proprietes, true, true);
vue_arbre.set_size_request(300, 300);
hpaned.set_border_width(5);
hpaned.set_position(300);
wnd.show_all_children(true);
wnd.set_size_request(730,500);
if(cmdeline.has_option("-s"))
{
trace_majeure("Export tableau des fonctions supportees...");
//these are used to generate the web site
auto s = this->export_html(Localized::Language::LANG_FR);
utils::files::save_txt_file("../../../site/contenu/opencv/ocvdemo/table.html", s);
s = this->export_html(Localized::Language::LANG_EN);
utils::files::save_txt_file("../../../site/contenu/opencv/ocvdemo/table-en.html", s);
s = this->export_html(Localized::Language::LANG_DE);
utils::files::save_txt_file("../../../site/contenu/opencv/ocvdemo/table-de.html", s);
s = this->export_html(Localized::Language::LANG_RU);
utils::files::save_txt_file("../../../site/contenu/opencv/ocvdemo/table-ru.html", s);
}
barre_outil_dessin.b_raz.signal_clicked().connect(sigc::mem_fun(*this,
&OCVDemo::on_b_masque_raz));
barre_outil_dessin.b_gomme.signal_clicked().connect(sigc::mem_fun(*this,
&OCVDemo::on_b_masque_gomme));
barre_outil_dessin.b_remplissage.signal_clicked().connect(sigc::mem_fun(*this,
&OCVDemo::on_b_masque_remplissage));
maj_langue();
std::vector<Gtk::TargetEntry> listTargets;
listTargets.push_back(Gtk::TargetEntry("text/uri-list"));
wnd.drag_dest_set(listTargets, Gtk::DEST_DEFAULT_MOTION | Gtk::DEST_DEFAULT_DROP, Gdk::ACTION_COPY | Gdk::ACTION_MOVE);
wnd.signal_drag_data_received().connect(sigc::mem_fun(*this, &OCVDemo::on_dropped_file));
maj_bts();
this->img_selecteur.CProvider<ImageSelecteurRefresh>::add_listener(this);
wnd.signal_delete_event().connect(sigc::mem_fun(*this,&OCVDemo::on_delete_event));
utils::hal::thread_start(this, &OCVDemo::thread_calcul);
utils::hal::thread_start(this, &OCVDemo::thread_video);
gtk_dispatcher.add_listener(this, &OCVDemo::on_video_image);
// Moved "-c" from above to here so it runs after thread_calcul has been started.
if(cmdeline.has_option("-c"))
{
trace_majeure("Export des captures d'écran...");
export_captures();
trace_majeure("Toutes les captures ont été exportées.");
on_b_exit();
}
}
void OCVDemo::demarre_interface()
{
Gtk::Main::run(wnd);
}
bool OCVDemo::has_output()
{
return sortie_en_cours;
}
Mat OCVDemo::get_current_output()
{
return demo_en_cours->output.images[0];
}
| 25,156
|
C++
|
.cc
| 792
| 27.112374
| 121
| 0.629518
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,997
|
image-selecteur.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/tools/image-selecteur.cc
|
/** @file image-selecteur.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "tools/image-selecteur.hpp"
#include "ocvdemo.hpp"
#include <glibmm.h>
void ImageSelecteur::maj_langue()
{
b_maj.set_label(utils::langue.get_item("b_maj"));
b_suppr_tout.set_label(utils::langue.get_item("b_del_tout"));
b_suppr.set_label(utils::langue.get_item("b_del"));
b_open.set_label(utils::langue.get_item("b_open"));
b_ajout.set_label(utils::langue.get_item("b_ajout"));
set_title(utils::langue.get_item("titre-sel"));
}
void ImageSelecteur::maj_actif()
{
bool ajout = true, retire = (csel != -1);
if((nmax >= 0) && (images.size() >= (unsigned int) nmax))
ajout = false;
if((nmin >= 0) && (images.size() <= (unsigned int) nmin))
retire = false;
b_ajout.set_sensitive(ajout);//images.size() < );
b_open.set_sensitive(csel != -1);
b_suppr.set_sensitive(retire);
b_suppr_tout.set_sensitive(nmin <= 0);//images.size() > 0);
b_maj.set_sensitive(images.size() > 0);
if((nmin == nmax) && toolbar_est_pleine)
{
toolbar.remove(b_suppr);
toolbar.remove(b_suppr_tout);
toolbar.remove(b_ajout);
toolbar_est_pleine = false;
}
if(!(nmin == nmax) && !toolbar_est_pleine)
{
toolbar.add(b_suppr);
toolbar.add(b_suppr_tout);
toolbar.add(b_ajout);
toolbar_est_pleine = true;
}
}
void ImageSelecteur::maj_selection()
{
auto n = images.size();
for(auto i = 0u; i < n; i++)
{
Image &im = images[i];
cv::Scalar color(80,80,80);
if((csel == (int) i) && (n > 1)) // Seulement si plus d'une image
color = cv::Scalar(0,255,0);
cv::rectangle(bigmat,
cv::Rect(im.px - 3, im.py - 3, img_width + 3, img_height + 3),
color, 3);
}
pixbuf = Gdk::Pixbuf::create_from_data(bigmat.data,
Gdk::Colorspace::COLORSPACE_RGB,
false,
8,
bigmat.cols,
bigmat.rows,
3 * bigmat.cols);
gtk_image.set(pixbuf);
trace_verbeuse("reshow...");
//this->gtk_image.show();
gtk_image.queue_draw();
}
void ImageSelecteur::maj_mosaique()
{
if(OCVDemo::get_instance() == nullptr)
return;
if(!OCVDemo::get_instance()->get_modele_global().get_attribute_as_boolean("afficher-sources"))
return;
infos("maj_mosaique");
int width, height;
width = gtk_image.get_allocated_width();
height = gtk_image.get_allocated_height();
if((width <= 0) || (height <= 0))
return;
if((width != bigmat.cols) || (height != bigmat.rows))
{
infos("if((width != bigmat.cols) || (height != bigmat.rows))");
bigmat = cv::Mat::zeros(cv::Size(width,height), CV_8UC3);
pixbuf = Gdk::Pixbuf::create_from_data(bigmat.data,
Gdk::Colorspace::COLORSPACE_RGB,
false,
8,
bigmat.cols,
bigmat.rows,
3 * bigmat.cols);
gtk_image.set(pixbuf);
}
else
bigmat = cv::Scalar(0);
auto n = images.size();
if(n == 0)
{
gtk_image.queue_draw();
return;
}
if((n == 0) || (width <= 0) || (height <= 0))
return;
nrows = (unsigned int) floor(sqrt(n));
ncols = (unsigned int) ceil(((float) n) / nrows);
col_width = width / ncols;
row_height = height / nrows;
unsigned int txt_height = 0;//30;
img_width = col_width - 6;
img_height = row_height - 6 - txt_height;
trace_verbeuse("nrows=%d, ncols=%d.", nrows, ncols);
//trace_verbeuse("bigmat: %d * %d.")
unsigned int row = 0, col = 0;
for(auto i = 0u; i < n; i++)
{
Image &im = images[i];
im.ix = col;
im.iy = row;
im.px = im.ix * col_width + 3;
im.py = im.iy * row_height + 3;
trace_verbeuse("resize(%d,%d,%d,%d,%d,%d)",
im.px, im.py, col_width, row_height, col_width, row_height);
cv::Mat tmp;
cv::cvtColor(im.spec.img, tmp, CV_BGR2RGB);
float ratio_aspect_orig = ((float) tmp.cols) / tmp.rows;
float ratio_aspect_sortie = ((float) img_width) / img_height;
// Doit ajouter du padding vertical
if(ratio_aspect_orig > ratio_aspect_sortie)
{
int hauteur = img_height * ratio_aspect_sortie / ratio_aspect_orig;
int py = im.py + (img_height - hauteur) / 2;
cv::resize(tmp,
bigmat(cv::Rect(im.px, py, img_width, hauteur)),
cv::Size(img_width, hauteur));
}
// Doit ajouter du padding horizontal
else
{
int largeur = img_width * ratio_aspect_orig / ratio_aspect_sortie;
int px = im.px + (img_width - largeur) / 2;
cv::resize(tmp,
bigmat(cv::Rect(px, im.py, largeur, img_height)),
cv::Size(largeur, img_height));
}
col++;
if(col >= ncols)
{
col = 0;
row++;
}
}
maj_selection();
}
void ImageSelecteur::on_size_change(Gtk::Allocation &alloc)
{
maj_mosaique();
}
ImageSelecteur::ImageSelecteur()
{
//sets up the window that displays input image.
toolbar_est_pleine = true;
nmin = 0;
nmax = 100;
has_a_video = false;
this->add(vbox);
vbox.pack_start(toolbar, Gtk::PACK_SHRINK);
evt_box.add(gtk_image);
vbox.pack_start(evt_box, Gtk::PACK_EXPAND_WIDGET);
//set_size_request(300,200);
set_default_size(450, 300);
csel = -1;
maj_mosaique();
toolbar.add(b_open);
toolbar.add(b_ajout);
toolbar.add(b_suppr);
toolbar.add(b_suppr_tout);
toolbar.add(b_maj);
b_maj.set_stock_id(Gtk::Stock::REFRESH);
b_suppr_tout.set_stock_id(Gtk::Stock::REMOVE);
b_suppr.set_stock_id(Gtk::Stock::REMOVE);
b_open.set_stock_id(Gtk::Stock::OPEN);
b_ajout.set_stock_id(Gtk::Stock::ADD);
maj_langue();
maj_actif();
//if(OCVDemo::get_instance()->get_modele_global().get_attribute_as_boolean("afficher-sources"))
show_all_children(true);
evt_box.set_can_focus(true);
evt_box.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
evt_box.signal_button_press_event().connect(
sigc::mem_fun(*this,
&ImageSelecteur::on_b_pressed));
evt_box.signal_button_release_event().connect(
sigc::mem_fun(*this,
&ImageSelecteur::on_b_released));
evt_box.signal_key_release_event().connect(
sigc::mem_fun(*this,
&ImageSelecteur::on_k_released));
gtk_image.signal_size_allocate().connect(
sigc::mem_fun(*this,
&ImageSelecteur::on_size_change));
b_open.signal_clicked().connect(sigc::mem_fun(*this,
&ImageSelecteur::on_b_open));
b_ajout.signal_clicked().connect(sigc::mem_fun(*this,
&ImageSelecteur::on_b_add));
b_suppr.signal_clicked().connect(sigc::mem_fun(*this,
&ImageSelecteur::on_b_del));
b_suppr_tout.signal_clicked().connect(sigc::mem_fun(*this,
&ImageSelecteur::on_b_del_tout));
b_maj.signal_clicked().connect(sigc::mem_fun(*this,
&ImageSelecteur::on_b_maj));
std::vector<Gtk::TargetEntry> listTargets;
listTargets.push_back(Gtk::TargetEntry("text/uri-list"));
drag_dest_set(listTargets, Gtk::DEST_DEFAULT_MOTION | Gtk::DEST_DEFAULT_DROP, Gdk::ACTION_COPY | Gdk::ACTION_MOVE);
signal_drag_data_received().connect(sigc::mem_fun(*this, &ImageSelecteur::on_dropped_file));
}
void ImageSelecteur::on_dropped_file(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time)
{
if ((selection_data.get_length() >= 0) && (selection_data.get_format() == 8))
{
std::vector<Glib::ustring> file_list;
file_list = selection_data.get_uris();
for(auto i = 0u; i < file_list.size(); i++)
{
Glib::ustring path = Glib::filename_from_uri(file_list[i]);
std::string s = path;
infos("DnD: %s.", s.c_str());
if(this->images.size() == 0)
{
ajoute_fichier(s);
}
else
{
if(csel == -1)
set_fichier(0, s);
else
set_fichier(csel, s);
}
}
context->drag_finish(true, false, time);
return;
}
context->drag_finish(false, false, time);
}
bool ImageSelecteur::has_video()
{
return has_a_video;
}
void ImageSelecteur::get_entrees(std::vector<SpecEntree> &liste)
{
liste.clear();
for(auto i: images)
liste.push_back(i.spec);
}
void ImageSelecteur::get_video_list(std::vector<std::string> &list)
{
list.clear();
for(auto i: images)
list.push_back(i.spec.chemin);
}
unsigned int ImageSelecteur::get_nb_images() const
{
return images.size();
}
void ImageSelecteur::get_list(std::vector<cv::Mat> &list)
{
list.clear();
for(auto i: images)
list.push_back(i.spec.img);
}
void ImageSelecteur::maj_has_video()
{
has_a_video = false;
for(auto i: images)
if(i.spec.is_video())
has_a_video = true;
}
void ImageSelecteur::set_fichier(int idx, std::string s)
{
if(s.size() == 0)
return;
trace_verbeuse("set [#%d <- %s]...", idx, s.c_str());
Image &img = images[idx];
img.spec.chemin = s;
std::string dummy;
utils::files::split_path_and_filename(s, dummy, img.nom);
std::string ext = utils::files::get_extension(img.nom);
img.nom = utils::files::remove_extension(img.nom);
if((ext == "mpg") || (ext == "avi") || (ext == "mp4") || (ext == "wmv"))
{
img.spec.type = SpecEntree::TYPE_VIDEO;
cv::VideoCapture vc(s);
if(!vc.isOpened())
{
utils::mmi::dialogs::affiche_erreur("Error",
"Error while loading video",
"Maybe the video format is not supported.");
return;
}
// Lis seulement la première image
vc >> img.spec.img;
vc.release();
}
else if((s.size() == 1) && (s[0] >= '0') && (s[0] <= '9'))
{
img.spec.type = SpecEntree::TYPE_WEBCAM;
int camnum = s[0] - '0';
img.spec.id_webcam = camnum;
img.spec.chemin = "Webcam " + utils::str::int2str(camnum);
cv::VideoCapture vc(camnum);
if(!vc.isOpened())
{
utils::mmi::dialogs::affiche_erreur("Error",
"Error while connecting to webcam",
"Maybe the webcam is not supported or is already used in another application.");
return;
}
// Lis seulement la première image
vc >> img.spec.img;
vc.release();
}
else
{
img.spec.type = SpecEntree::TYPE_IMG;
img.spec.img = cv::imread(s);
if(img.spec.img.data == nullptr)
{
utils::mmi::dialogs::affiche_erreur("Error",
"Error while loading image",
"Maybe the image format is not supported.");
return;
}
}
csel = idx;
maj_has_video();
maj_mosaique();
maj_actif();
if(nmax == 1)
on_b_maj();
}
static utils::model::Node create_default_model()
{
auto fs = OCVDemo::get_instance()->get_fileschema();
auto schema = fs->get_schema("media-schema");
return utils::model::Node::create_ram_node(schema);
}
// Ajoute_fichier: accès externe = déf img par défaut
// accès interne = déf nv img
void ImageSelecteur::ajoute_fichier(std::string s)
{
if(s.size() == 0)
return;
trace_verbeuse("Ajout [%s]...", s.c_str());
images.resize(images.size() + 1);
auto mod = create_default_model();
mod.set_attribute("default-path", s);
images[images.size() - 1].modele = mod;
set_fichier(images.size() - 1, s);
}
std::string ImageSelecteur::media_open_dialog(utils::model::Node mod)
{
//auto mod = create_default_model();
if(utils::mmi::NodeDialog::display_modal(mod))
return "";
int sel = mod.get_attribute_as_int("sel");
if(sel == 0)
{
// image par défaut
return mod.get_attribute_as_string("default-path");
}
else if(sel == 1)
{
// Fichier
return mod.get_attribute_as_string("file-schema/path");
}
else if(sel == 2)
{
// Caméra
char bf[2];
bf[0] = '0' + mod.get_attribute_as_int("cam-schema/idx");
bf[1] = 0;
return std::string(bf);
}
// URL
return mod.get_attribute_as_string("url-schema/url");
/*name = utils::langue.get_item("wiz0-name");
title = utils::langue.get_item("wiz0-title");
description = utils::langue.get_item("wiz0-desc");*/
}
void ImageSelecteur::on_b_add()
{
trace_verbeuse("on b add...");
auto mod = create_default_model();
ajoute_fichier(media_open_dialog(mod));
maj_actif();
}
void ImageSelecteur::on_b_open()
{
trace_verbeuse("on b open...");
if(this->csel != -1)
{
set_fichier(this->csel, media_open_dialog(images[csel].modele));
maj_actif();
}
else
on_b_add();
}
void ImageSelecteur::on_b_del()
{
trace_verbeuse("on b del().");
if(csel != -1)
{
trace_verbeuse("del %d...", csel);
images.erase(csel + images.begin(), 1 + csel + images.begin());
if(csel >= (int) images.size())
csel--;
maj_mosaique();
}
maj_actif();
}
void ImageSelecteur::on_b_del_tout()
{
trace_verbeuse("on b del tout().");
images.clear();
maj_mosaique();
maj_actif();
}
void ImageSelecteur::on_b_maj()
{
trace_verbeuse("on b maj.");
ImageSelecteurRefresh evt;
utils::CProvider<ImageSelecteurRefresh>::dispatch(evt);
}
void ImageSelecteur::raz()
{
has_a_video = false;
images.clear();
csel = -1;
maj_mosaique();
}
bool ImageSelecteur::on_b_pressed(GdkEventButton *event)
{
unsigned int x = event->x, y = event->y;
trace_verbeuse("bpress %d, %d", x, y);
csel = -1;
for(auto i = 0u; i < images.size(); i++)
{
auto &img = images[i];
if((x > img.px) && (y > img.py)
&& (x < img.px + this->img_width)
&& (y < img.py + this->img_height))
{
csel = i;
break;
}
}
maj_actif();
maj_selection();
return true;
}
bool ImageSelecteur::on_b_released(GdkEventButton *event)
{
trace_verbeuse("brel");
evt_box.grab_focus();
return true;
}
bool ImageSelecteur::on_k_released(GdkEventKey *event)
{
if(csel == -1)
return false;
if(event->keyval == GDK_KEY_Delete)
{
this->on_b_del();
return true;
}
else if(event->keyval == GDK_KEY_Down)
{
if(csel + ncols < images.size())
{
csel += ncols;
maj_selection();
}
return true;
}
else if(event->keyval == GDK_KEY_Up)
{
infos("Key up.");
if(csel >= (int) ncols)
{
csel -= ncols;
maj_selection();
}
else
infos("Refu: csel = %d, ncols = %d.", csel, ncols);
return true;
}
else if(event->keyval == GDK_KEY_Left)
{
//if(images[csel].ix > 0)
if(csel > 0)
{
csel--;
maj_selection();
}
return true;
}
else if(event->keyval == GDK_KEY_Right)
{
if(/*(images[csel].ix + 1 < ncols) &&*/ (csel + 1 < (int) images.size()))
{
csel++;
maj_selection();
}
return true;
}
return false;
}
| 15,486
|
C++
|
.cc
| 527
| 24.548387
| 163
| 0.616564
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,998
|
boutils-image.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/tools/boutils-image.cc
|
/** @file boutils-image.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "tools/boutils-image.hpp"
#include "cutil.hpp"
MasqueBOutils::MasqueBOutils()
{
tools.set_icon_size(Gtk::ICON_SIZE_SMALL_TOOLBAR);
tools.set_has_tooltip(false);
tools.add(b_raz);
tools.add(b_gomme);
//tools.add(b_remplissage);
b_gomme.set_active(true);
b_raz.set_stock_id(Gtk::Stock::REDO);
Gtk::Image *buttonImage = new Gtk::Image(utils::get_fixed_data_path() + "/img/gomme.png");
b_gomme.set_icon_widget(*buttonImage);
//b_gomme.set_image(*buttonImage);
//b_gomme.set_icon_widget(*buttonImage);
buttonImage = new Gtk::Image(utils::get_fixed_data_path() + "/img/remp.png");
b_remplissage.set_icon_widget(*buttonImage);
//b_exit.signal_clicked().connect(sigc::mem_fun(*this, &OCVDemo::on_b_exit));
wnd.add(vbox);
vbox.pack_start(tools, Gtk::PACK_SHRINK);
wnd.show_all_children(true);
maj_lang();
wnd.set_size_request(370,50);
}
void MasqueBOutils::montre()
{
wnd.show_all_children(true);
wnd.show_now();
}
void MasqueBOutils::cache()
{
wnd.hide();
}
void MasqueBOutils::maj_lang()
{
b_raz.set_label(utils::langue.get_item("b_raz"));
b_gomme.set_label(utils::langue.get_item("b_gomme"));
b_remplissage.set_label(utils::langue.get_item("b_remplissage"));
wnd.set_title(utils::langue.get_item("wnd-tools"));
}
| 2,135
|
C++
|
.cc
| 55
| 35.6
| 92
| 0.723703
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
753,999
|
image-mosaic.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/tools/image-mosaic.cc
|
/** @file image-mosaic.cc
* @brief Affichage de plusieurs images sur une même fenêtre
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "tools/image-mosaique.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "ocvdemo.hpp"
using namespace cv;
// Adapté d'après http://code.opencv.org/projects/opencv/wiki/DisplayManyImages
ImageMosaique::ImageMosaique()
{
preserve_ratio_aspet = false;
callback_init_ok = false;
}
void mouse_callback(int event, int x, int y, int flags, void *param)
{
((ImageMosaique *) param)->mouse_callback(event, x, y, flags);
}
void ImageMosaique::mouse_callback(int event, int x, int y, int flags)
{
//infos("imosaic mouse callback x = %d, y = %d.", x, y);
// Conversion vers coordoonnées image i
for(auto j = 0u; j < img_pos.size(); j++)
{
cv::Rect r = img_pos[j];
if((x >= r.x) && (y >= r.y) && (x < r.x + r.width) && (y < r.y + r.height))
{
int x2 = ((x - r.x) * img_sizes[j].width) / r.width;
int y2 = ((y - r.y) * img_sizes[j].height) / r.height;
OCVMouseEvent me;
me.image = j;
me.event = event;
me.x = x2;
me.y = y2;
me.flags = flags;
dispatch(me);
}
}
}
void ImageMosaique::update_image(int index, const cv::Mat &img)
{
trace_verbeuse("ImageMosaique::update_image");
mutex.lock();
cv::Rect rect(img_pos[index].x, img_pos[index].y,
img_pos[index].width, img_pos[index].height);
cv::Mat roi(disp_img, rect);
Mat im = img.clone();
while((im.cols >= 2 * roi.size().width) || (im.rows >= 2 * roi.size().height))
pyrDown(im, im);
while((im.cols < roi.size().width / 2) && (im.rows < roi.size().height / 2))
pyrUp(im, im);
cv::resize(im, roi, roi.size());
cv::imshow(title.c_str(), disp_img);
mutex.unlock();
}
int ImageMosaique::show_multiple_images(std::string title,
std::vector<cv::Mat> lst,
std::vector<std::string> titles)
{
mutex.lock();
this->title = title;
cv::Mat img;
unsigned int nimages = lst.size();
int sizex, sizey;
int i;
int m, n;
int x, y;
// w - Maximum number of images in a row
// h - Maximum number of images in a column
int w, h;
// scale - How much we have to resize the image
float scale;
//int max;
bool show_deco = true;
img_pos.clear();
img_sizes.clear();
/*if(nimages < 0)
{
erreur("%s: Number of arguments too small.", __func__);
mutex.unlock();
return -1;
}*/
if((nimages > 0) && (lst[0].cols <= 0))
{
erreur("%s: First image empty.", __func__);
mutex.unlock();
return -1;
}
if(nimages == 0)
{
w = h = 1;
sizex = sizey = 1;
}
else if (nimages == 1)
{
w = h = 1;
sizex = lst[0].cols;
sizey = lst[0].rows;
show_deco = false;
}
else if (nimages == 2)
{
w = 2; h = 1;
sizex = 500;
sizey = 500;
}
else if (nimages == 3)
{
w = 3; h = 1;
sizex = 640;//350;
sizey = 480;//350;
}
else if (nimages == 4)
{
w = 2; h = 2;
sizex = sizey = 350;
}
else if (nimages == 5 || nimages == 6)
{
w = 3; h = 2;
sizex = sizey = 250;
}
else if (nimages == 7 || nimages == 8)
{
w = 4; h = 2;
sizex = sizey = 250;
}
else
{
w = (int) ceil(sqrt(nimages));
h = (int) ceil(((float) nimages) / w);
//w = 4; h = 3;
sizex = sizey = 100;
}
if(nimages > 1)
sizey = (sizex * lst[0].rows) / lst[0].cols;
uint16_t W = /*100*/20 + (20+sizex)*w;
uint16_t H = 20 + (sizey+30)*h;
if(nimages <= 1)
{
W = sizex;
H = sizey;
}
infos("show_multiple_images (sizex = %d, sizey = %d, w = %d, h = %d, W = %d, H = %d)",
sizex, sizey, w, h, W, H);
// Create a new 3 channel image
disp_img.create(cv::Size(W, H), CV_8UC3);
disp_img.setTo(Scalar(0));
// Loop for nArgs number of arguments
for (i = 0, m = 20, n = 20; i < (int) nimages; i++, m += (20 + sizex))
{
// Get the Pointer to the IplImage
img = lst[i];
auto sz = img.size();
x = sz.width;
y = sz.height;
float scalex = ((float) x) / sizex;
float scaley = ((float) y) / sizey;
scale = std::max(scalex,scaley);
// Used to Align the images
if(((i % w) == 0) && (m != 20))
{
m = 20;
n += 30 + sizey;
}
if(nimages == 1)
{
m = 0; n = 0;
scale = 1;
disp_img = img;
}
// Set the image ROI to display the current image
cv::Rect rect(m, n, (int)(x/scale), (int)(y/scale));
//trace_verbeuse("di: %d*%d, r:%d,%d,%d,%d.", disp_img.cols, disp_img.rows, rect.x, rect.y, rect.width, rect.height);
cv::Mat roi(disp_img, rect);
if(nimages > 1)
// Resize the input image and copy the it to the Single Big Image
{
Mat im = img.clone();
while((im.cols >= 2 * roi.size().width) || (im.rows >= 2 * roi.size().height))
pyrDown(im, im);
while((im.cols <= roi.size().width / 2) && (im.rows <= roi.size().height / 2))
pyrUp(im, im);
cv::resize(im, roi, roi.size());
}
img_pos.push_back(rect);
img_sizes.push_back(Size(img.cols, img.rows));
if(show_deco && (titles[i].size() > 0))
{
std::string texte = titles[i];
int baseLine;
double tscale = 1.0;
auto font = FONT_HERSHEY_COMPLEX_SMALL;
Size si = getTextSize(texte, font, tscale, 1.2, &baseLine);
///int dx = (x/scale);
int xc = m + (x/(2*scale));
putText(disp_img, texte,
Point(xc - si.width / 2, n + y / scale + 1.5 * si.height),
font,
tscale,
Scalar(255,255,255),
1.2,
CV_AA);
}
}
// Create a new window, and show the Single Big Image
trace_verbeuse("namedWindow...");
auto model = OCVDemo::get_instance()->get_modele_global();
if(model.get_attribute_as_boolean("force-taille-sortie"))
{
trace_verbeuse("Forçage taille...");
cv::namedWindow(title.c_str(), CV_WINDOW_KEEPRATIO | CV_WINDOW_NORMAL);
cv::resizeWindow(title.c_str(),
model.get_attribute_as_int("sortie-sx"),
model.get_attribute_as_int("sortie-sy"));
}
else
{
trace_verbeuse("Taille auto...");
if(nimages == 1)
{
trace_majeure("KEEP RATIO");
cv::namedWindow(title.c_str(), CV_WINDOW_KEEPRATIO | CV_WINDOW_NORMAL);
cv::resizeWindow(title.c_str(), lst[0].cols, lst[0].rows);
}
else
cv::namedWindow(title.c_str(), 1);
//cv::moveWindow(title.c_str(), 0,0);
}
trace_verbeuse("imwrite");
//cv::imwrite("./essai.jpg", disp_img); // OK
trace_verbeuse("imshow: [%s], %d * %d", title.c_str(), disp_img.cols, disp_img.rows);
cv::imshow(title.c_str(), disp_img);
//cv::moveWindow(title.c_str(), 0, 0);
if(!callback_init_ok)
{
trace_verbeuse("cbinit");
setMouseCallback(title, ::mouse_callback, this);
callback_init_ok = true;
}
infos("done.");
mutex.unlock();
return 0;
}
| 7,683
|
C++
|
.cc
| 256
| 25.328125
| 121
| 0.590168
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,000
|
ocr.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/ocr.cc
|
#include "demo-items/ocr.hpp"
#ifdef USE_CONTRIB
#include "opencv2/text.hpp"
#endif
#include <cmath>
#include <iostream>
DemoOCR::DemoOCR()
{
props.id = "ocr";
}
int DemoOCR::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
#ifdef USE_CONTRIB
cv::Mat I = input.images[0];
cv::Ptr<cv::text::BaseOCR> algo;
Ptr<cv::text::OCRHMMDecoder::ClassifierCallback> cls
= cv::text::loadOCRHMMClassifierNM("OCRHMM_knn_model_data.xml");
cv::Mat trans_prob = cv::Mat::ones(6,6,CV_32F),
em_prob = cv::Mat::eye(6,6,CV_32F);
trans_prob /= 6.0;
std::string voc = "OpenCV";
//algo = cv::text::OCRHMMDecoder::create(cls, voc, trans_prob, em_prob);
//algo = cv::text::OCRTesseract::create();
std::string res;
std::vector<Rect> component_rects;
std::vector<std::string> component_texts;
algo->run(I, res, &component_rects, &component_texts);
cv::Mat O = I.clone();
cv::putText(O, res, Point(0,0), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0,255,0), 1);
infos("Nb rect : %d.", component_rects.size());
infos("Texte detecte : [%s]", res.c_str());
output.images[0] = O;
//auto algo = cv::text::OCRHMMDecoder::create()
# else
output.images[0] = input.images[0];
# endif
return 0;
}
| 1,237
|
C++
|
.cc
| 38
| 29.605263
| 81
| 0.675997
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,001
|
photographie.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/photographie.cc
|
/** @file photography.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/photographie.hpp"
#include <opencv2/photo.hpp>
HDRDemo::HDRDemo()
{
props.id = "hdr";
props.input_max = -1;
output.nout = 1;
}
int HDRDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Ptr<MergeMertens> merge_mertens = createMergeMertens();
Mat tmp, tmp2;
merge_mertens->process(input.images, tmp);
tmp.convertTo(tmp2, CV_8UC3, 255, 0);
output.images[0] = tmp2;
return 0;
}
| 1,288
|
C++
|
.cc
| 32
| 36.71875
| 79
| 0.741573
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,002
|
appauto.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/appauto.cc
|
/** @file appauto.cc
Copyright 2016 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/appauto.hpp"
#include <iostream>
#include <vector>
#include <assert.h>
#include <stdio.h>
#include <cmath>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace cv::ml;
Ptr<StatModel> creation_classifieur_svm(utils::model::Node &model)
{
float gamma = model.get_attribute_as_float("svm/svm-rbf/gamma");
if(gamma == 0)
gamma = 1.0e-10;
float C = model.get_attribute_as_float("svm/C");
if (C <= 0)
C = 1.0e-10;
int kernel = model.get_attribute_as_int("svm/kernel");
int degre = model.get_attribute_as_int("svm/svm-poly/degre");
//trace_verbeuse("Gamma = %f, C = %f, kernel = %d.", gamma, C, kernel);
// A FAIRE : créer un classifieur SVM avec noyau RBF
Ptr<SVM> svm = SVM::create();
svm->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 1000, 1e-3));
svm->setGamma(gamma);
svm->setKernel((SVM::KernelTypes) kernel);//SVM::RBF);
svm->setNu(0.5);
svm->setP(0.1);
svm->setC(C);
svm->setType(SVM::C_SVC); // ou NU_SVC
svm->setDegree(degre);
return svm;
}
Ptr<StatModel> creation_classifieur_knn(utils::model::Node &model)
{
Ptr<KNearest> knearest = KNearest::create();
knearest->setDefaultK(model.get_attribute_as_int("kppv/K"));
knearest->setIsClassifier(true);
//knearest->setAlgorithmType(KNearest::COMPRESSED_INPUT);//KDTREE);//:BRUTE_FORCE);
knearest->setAlgorithmType(KNearest::BRUTE_FORCE);
//knearest->setMaxCategories(model.get_attribute_as_int("nclasses"));
return knearest;
}
Ptr<StatModel> creation_classifieur_adaboost(utils::model::Node &model)
{
// A FAIRE : créer un classifieur Adaboost
Ptr<Boost> res = Boost::create();
res->setMaxCategories(model.get_attribute_as_int("nclasses"));
res->setMaxDepth(1);
return res;
}
DemoAppAuto::DemoAppAuto()
{
props.id = "2d-2classes";
props.input_min = 0;
props.input_max = 0;
}
int DemoAppAuto::proceed(OCVDemoItemInput &entree, OCVDemoItemOutput &sortie)
{
// (1) Génération d'un jeu de données
uint16_t nclasses = entree.model.get_attribute_as_int("nclasses");
uint32_t n = entree.model.get_attribute_as_int("napp"),
ntraits = 2u;
float bruit = entree.model.get_attribute_as_float("bruit");
Mat mat_entrainement(Size(ntraits,n), CV_32F);
uint32_t sx = 512, sy = 512;
uint32_t sx2 = 32, sy2 = 32;
Mat O(Size(sx, sy), CV_8UC3, Scalar(255,255,255));
Mat O2(Size(sx2, sy2), CV_8UC3);
RNG rng;
Mat labels(Size(1,n), CV_32S);
auto ptr = labels.ptr<int>();
auto *optr = mat_entrainement.ptr<float>();
uint16_t dl = (5 * 512) / sx;
infos("Generation jeu de donnees (n = %d, nclasses = %d)...", n, nclasses);
int n1 = std::floor(std::sqrt(nclasses));
int n2 = std::ceil(nclasses / n1);
trace_verbeuse("Partition du plan : %d * %d.", n1, n2);
# define MAX_CLASSES 4
Scalar couleurs[MAX_CLASSES];
couleurs[0] = Scalar(255,0,0);
couleurs[1] = Scalar(0,255,0);
couleurs[2] = Scalar(0,0,255);
couleurs[3] = Scalar(255,0,255);
for(auto i = 0u; i < n; i++)
{
uint8_t classe = 0;
//float x = rng.uniform(0.0f, 2 * 3.1415926f);
float x = rng.uniform(-1.0f, 1.0f);
float y = rng.uniform(-1.0f, 1.0f);
if(nclasses == 2)
{
if(y >= std::sin(3.1415926 * x))
classe = 1;
}
else
{
// Entre 0 et 1
float x2 = (x + 1) / 2;
float y2 = (y + 1) / 2;
if((x2 < 0) || (x2 >= 1) || (y2 < 0) || (y2 >= 1))
{
i--;
continue;
}
classe = std::floor(x2 * n1) + std::floor(y2 * n2) * n1;
}
x = x + rng.gaussian(bruit);
y = y + rng.gaussian(bruit);
assert(classe < MAX_CLASSES);
int xi = sx/2 + x * sx / 2;
int yi = sy/2 + y * sy / 2;
cv::line(O, Point(xi-dl,yi), Point(xi+dl,yi), couleurs[classe], 1, CV_AA);
cv::line(O, Point(xi,yi-dl), Point(xi,yi+dl), couleurs[classe], 1, CV_AA);
*optr++ = x;
*optr++ = y;
//mat_entrainement.at<float>(i,0) = x;
//mat_entrainement.at<float>(i,1) = y;
*ptr++ = classe;
}
trace_verbeuse("ok.");
// (2) Entrainement SVM
/*float gamma = input.model.get_attribute_as_float("svm/svm-rbf/gamma");
if(gamma == 0)
gamma = 1.0e-10;
float C = input.model.get_attribute_as_float("svm/C");
if(C <= 0)
C = 1.0e-10;
int kernel = input.model.get_attribute_as_int("svm/kernel");
int degre = input.model.get_attribute_as_int("svm/svm-poly/degre");
trace_verbeuse("Gamma = %f, C = %f, kernel = %d.", gamma, C, kernel);
Ptr<SVM> svm = SVM::create();
svm->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 1000, 1e-3));
svm->setGamma(gamma);
svm->setKernel((SVM::KernelTypes) kernel); //SVM::RBF);
svm->setNu(0.5);
svm->setP(0.1);
svm->setC(C);//0.01);
svm->setType(SVM::C_SVC);
svm->setDegree(degre);*/
Ptr<StatModel> smodel;
auto sel = input.model.get_attribute_as_int("sel");
if(sel == 0)
smodel = creation_classifieur_svm(input.model);
else if(sel == 1)
smodel = creation_classifieur_knn(input.model);
else
smodel = creation_classifieur_adaboost(input.model);
trace_verbeuse("Entrainement...");
smodel->train(mat_entrainement, ROW_SAMPLE, labels);
trace_verbeuse("Ok.");
trace_verbeuse("Echantillonnage du plan...");
Vec3b *o2ptr = O2.ptr<Vec3b>();
Vec3b c[MAX_CLASSES];
for(auto i = 0u; i < MAX_CLASSES; i++)
for(auto j = 0u; j < 3; j++)
c[i][j] = couleurs[i][j];
Mat traits(Size(2,1),CV_32F);
float *tptr = traits.ptr<float>();
for(auto y = 0u; y < sy2; y++)
{
for(auto x = 0u; x < sx2; x++)
{
tptr[0] = (((float) x) - sx2/2) / (sx2 / 2);
tptr[1] = (((float) y) - sy2/2) / (sy2 / 2);
int res = smodel->predict(traits);
assert((res < MAX_CLASSES) && (res >= 0));
*o2ptr++ = c[res];
}
}
trace_verbeuse("Ok.");
sortie.nout = 2;
sortie.images[0] = O;
sortie.names[0] = "Entrainement";
sortie.images[1] = O2;
sortie.names[1] = "Classication";
return 0;
}
| 6,804
|
C++
|
.cc
| 192
| 31.510417
| 85
| 0.64494
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,003
|
demo-fourier.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/demo-fourier.cc
|
#include "demo-items/fourier-demo.hpp"
#include "fourier.hpp"
#include "ocvext.hpp"
IFTDemo::IFTDemo()
{
props.id = "ift";
props.requiert_masque = true;
}
int IFTDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
cv::Mat I, O, mag;
input.mask.convertTo(I, CV_32F);
//cv::cvtColor(I, I, CV_BGR2GRAY);
ocvext::dft_shift(I);
cv::dft(I, O, cv::DFT_COMPLEX_OUTPUT);
//cv::putText()
cv::Mat plans[2];
cv::split(O, plans);
infos("plan0 = %d,%d, plan1 = %d,%d", plans[0].cols, plans[0].rows, plans[1].cols, plans[1].rows);
cv::magnitude(plans[0], plans[1], mag);
ocvext::dft_shift(mag);
cv::normalize(mag, mag, 0, 255, cv::NORM_MINMAX);
//cv::normalize(plans[0], mag, 0, 255, cv::NORM_MINMAX);
ocvext::dft_shift(mag);
output.images[0] = I.clone();
output.images[1] = mag;
output.nout = 2;
output.names[0] = "Espace de Fourier";
output.names[1] = "Trf. inverse";
return 0;
}
DFTDemo::DFTDemo()
{
props.id = "dft";
output.nout = 2;
output.names[0] = "Entree";
output.names[1] = "DFT";
}
int DFTDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat Ig, padded; //expand input image to optimal size
float angle = input.model.get_attribute_as_float("angle");
bool fenetrage = input.model.get_attribute_as_boolean("fenetrage");
bool vue_log = input.model.get_attribute_as_boolean("log");
bool decalage_dc = input.model.get_attribute_as_boolean("decalage-dc");
int source = input.model.get_attribute_as_int("source");
int periode = input.model.get_attribute_as_int("dft-sin/periode");
cvtColor(input.images[0], Ig, CV_BGR2GRAY);
if(source == 1)
{
Ig = cv::Mat::zeros(512, 512, CV_32F);
for(auto y = 0u; y < 512; y++)
{
float *ptr = Ig.ptr<float>(y);
for(auto x = 0u; x < 512; x++)
{
float xf = x;
//*ptr++ = 128.0 + 128 * std::sin(2 * CV_PI * xf / (512 * (periode / 512.0)));
*ptr++ = 128 * std::sin(2 * CV_PI * xf / (512 * (periode / 512.0)));
}
}
}
Ig.convertTo(Ig, CV_32F);
if(fenetrage)
{
cv::Mat W;
cv::createHanningWindow(W, Ig.size(), CV_32F);
Ig = Ig.mul(W);
/*cv::imshow("W", W);
cv::imshow("F", Ig/255.0);
cv::waitKey(0);*/
}
//uint16_t idx = 1;
if(angle != 0)
{
cv::Size sz = Ig.size() / 2;
cv::Point centre;
centre.x = sz.width;
centre.y = sz.height;
uint16_t sx = sz.width, sy = sz.height;
cv::Mat R = cv::getRotationMatrix2D(centre, angle, 1.0);
cv::warpAffine(Ig, Ig, R, Ig.size());
Ig = Ig(Rect(sx/4,sy/4,sx/2,sy/2));
//output.images[idx++] = Ig;
}
output.images[0] = Ig;
/*int m = getOptimalDFTSize( Ig.rows );
int n = getOptimalDFTSize( Ig.cols ); // on the border add zero values
copyMakeBorder(Ig, padded, 0, m - Ig.rows, 0, n - Ig.cols, BORDER_CONSTANT, Scalar::all(0));
Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
merge(planes, 2, complexI); // Add to the expanded another plane with zeros
*/
Mat plans[2], complexI, mag;
cv::dft(Ig, complexI, cv::DFT_COMPLEX_OUTPUT);
cv::split(complexI, plans);
magnitude(plans[0], plans[1], mag);
if(vue_log)
cv::log(mag + 1.0, mag);
if(decalage_dc)
ocvext::dft_shift(mag);
cv::normalize(mag, mag, 0, 255, NORM_MINMAX);
output.images[1] = mag;
//output.nout = idx;
return 0;
}
DemoDetectionRotation::DemoDetectionRotation()
{
props.id = "detection-rotation";
}
DemoDetectionTranslation::DemoDetectionTranslation()
{
props.id = "detection-translation";
}
int DemoDetectionTranslation::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
cv::Mat I, O;
uint16_t idx = 0;
//cv::cvtColor(input.images[0], I, CV_BGR2GRAY);
I = input.images[0].clone();
output.names[idx] = "Image";
output.images[idx++] = I.clone();
I.convertTo(I, CV_32F);
cv::Mat T, S;
int dx = input.model.get_attribute_as_int("tx");
int dy = input.model.get_attribute_as_int("ty");
bool norm_spectre = input.model.get_attribute_as_boolean("norm-spectre");
T = I.clone();
ocvext::translation_rapide(I, T, dx, dy, I.size(), cv::Scalar(0));
cv::Mat tmp;
T.convertTo(tmp, CV_8U);
output.names[idx] = "Translation";
output.images[idx++] = tmp;
ocvext::detection_translation(I, T, norm_spectre, &S);
cv::normalize(S, S, 0, 255, cv::NORM_MINMAX);
//S.convertTo(S, CV_8U);
output.names[idx] = "Correlation";
output.images[idx++] = S;
output.nout = idx;
return 0;
}
int DemoDetectionRotation::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
cv::Mat I, mag, O;
cv::cvtColor(input.images[0], I, CV_BGR2GRAY);
I.convertTo(I, CV_32F);
float echelle = input.model.get_attribute_as_float("echelle");
float angle = input.model.get_attribute_as_float("angle");
int dx = input.model.get_attribute_as_int("tx");
int dy = input.model.get_attribute_as_int("ty");
bool mode_log = input.model.get_attribute_as_boolean("mode-log");
uint16_t idx = 0;
//if(angle != 0)
{
cv::Size sz = I.size() / 2;
cv::Point centre;
centre.x = sz.width;
centre.y = sz.height;
cv::Mat R = cv::getRotationMatrix2D(centre, angle, echelle);
// R = Matrice 2x3
R.at<double>(0,2) = dx;
R.at<double>(1,2) = dy;
cv::warpAffine(I, I, R, I.size());
//I = I(Rect(sx/4,sy/4,sx/2,sy/2));
output.names[idx] = "Rotation";
output.images[idx++] = I;
}
cv::Mat F, plans[2];
cv::dft(I, F, DFT_COMPLEX_OUTPUT, I.rows);
cv::split(F, plans);
cv::magnitude(plans[0], plans[1], mag);
mag += Scalar::all(1); // switch to logarithmic scale
cv::log(mag, mag);
ocvext::dft_shift(mag);
if(mode_log)
cv::logPolar(mag, O, cv::Point(mag.cols/2, mag.rows/2), mag.cols/2, cv::INTER_CUBIC);
else
cv::linearPolar(mag, O, cv::Point(mag.cols/2, mag.rows/2), mag.cols/2, cv::INTER_CUBIC);
cv::normalize(mag, mag, 0, 255, cv::NORM_MINMAX);
cv::normalize(O, O, 0, 255, cv::NORM_MINMAX);
output.names[idx] = "Mag TFR";
output.images[idx++] = mag;
output.names[idx] = "Trf pol.";
output.images[idx++] = O;
output.nout = idx;
return 0;
}
DemoSousSpectrale::DemoSousSpectrale()
{
props.id = "sous-spect";
}
static void sousstraction_spectrale_gs(cv::Mat &I, cv::Mat &O, cv::Mat &mag, cv::Mat &masque, float seuil)
{
cv::Mat F, plans[2];
cv::dft(I, F, DFT_COMPLEX_OUTPUT, I.rows);
//infos("F: cols=%d, rows=%d, type=%d, nchn=%d", F.cols, F.rows, F.type(), F.channels());
cv::split(F, plans);
cv::magnitude(plans[0], plans[1], mag);
float moy = cv::mean(mag)[0];
masque = mag > (seuil * moy);
F.setTo(0.0, masque);
cv::dft(F, O, cv::DFT_INVERSE + cv::DFT_SCALE + DFT_REAL_OUTPUT, I.rows);// + K_spatial[i].rows / 2);
cv::normalize(O,O,0,255,cv::NORM_MINMAX);
}
static void sousstraction_spectrale(cv::Mat &I, cv::Mat &O, cv::Mat &mag, float seuil)
{
cv::Mat compos[3], compos_sortie[3];
cv::split(I, compos);
cv::Mat masque;
for(auto i = 0u; i < 3; i++)
{
sousstraction_spectrale_gs(compos[i], compos_sortie[i], mag, masque, seuil);
}
cv::merge(compos_sortie, 3, O);
}
int DemoSousSpectrale::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
cv::Mat mag, O, I = input.images[0], If;
I.convertTo(If, CV_32F);
sousstraction_spectrale(If, O, mag, input.model.get_attribute_as_float("seuil"));
O.convertTo(O, CV_8U);
output.nout = 3;
output.images[0] = If;
output.names[0] = "Entree";
cv::log(mag + 0.1, mag);
cv::normalize(mag, mag, 0, 255, cv::NORM_MINMAX);
ocvext::dft_shift(mag);
output.images[1] = mag;
output.names[1] = "Magnitude DFT";
output.images[2] = O;
output.names[2] = "Soustraction spectrale";
return 0;
}
DemoDetectionPeriode::DemoDetectionPeriode()
{
props.id = "detection-periode";
}
int DemoDetectionPeriode::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
float zoom = input.model.get_attribute_as_int("zoom") / 100.0;
cv::Mat Ig;
cvtColor(input.images[0], Ig, CV_BGR2GRAY);
Ig.convertTo(Ig, CV_32F);
unsigned int sx = Ig.cols, sy = Ig.rows;
cv::resize(Ig, Ig, cv::Size(0,0), zoom, zoom);
cv::Rect r(Ig.cols/2-sx/2,Ig.rows/2-sy/2,sx,sy);
infos("Ig: %d,%d, r: %d,%d,%d,%d", Ig.cols, Ig.rows, r.x, r.y, r.width, r.height);
cv::Mat I = Ig(r).clone();
/*auto px = Ig.cols * (zoom - 1);
auto py = Ig.rows * (zoom - 1);
cv::Mat I = Ig(cv::Rect())*/
output.images[0] = I.clone();
output.names[0] = "Entree";
float d, indice_confiance;
float dmin = 1, dmax = 50;
// ocvext::defini_options_debogage(false, true);
// ocvext::defini_dossier_stockage("./build/ocvext");
cv::Mat dbg[2];
ocvext::estime_periode(I, d, indice_confiance, dmin, dmax, dbg);
output.nout = 3;
output.images[1] = dbg[0];
output.names[1] = "TFD";
output.images[2] = dbg[1];
output.names[2] = "Energie radiale max.";
# if 0
Ig -= cv::mean(Ig)[0];
cv::resize(Ig, Ig, cv::Size(256, 256));
// Fenêtrage
cv::Mat W;
cv::createHanningWindow(W, Ig.size(), CV_32F);
Ig = Ig.mul(W);
//cv::copyMakeBorder(Ig, Ig, 128, 128, 128, 128, cv::BORDER_CONSTANT, cv::Scalar(0));
dft(Ig, F, cv::DFT_COMPLEX_OUTPUT);
cv::split(F, plans);
magnitude(plans[0], plans[1], mag);
mag += Scalar::all(0.00001);
cv::log(mag, mag);
ocvext::dft_shift(mag);
cv::normalize(mag, mag, 0, 255, NORM_MINMAX);
output.images[0] = mag;
// TODO: accumuler suivant le rayon
# if 0
// TODO: accumuler suivant le rayon
cv::Mat pol, red;
cv::linearPolar(mag, pol, cv::Point(mag.size())/2, mag.cols, cv::INTER_LINEAR);
cv::normalize(pol, pol, 0, 255, cv::NORM_MINMAX);
output.images[1] = pol;
cv::reduce(pol, red, 0, REDUCE_SUM);
// TODO : plot
{
cv::Mat tmp(255, 640, CV_8UC3, cv::Scalar(0));
cv::Mat pc2;
cv::normalize(red, pc2, 0, 255, cv::NORM_MINMAX);
//for(auto i = 0; i < ntheta; i++)
//printf("pc[%d] = %f\n", i, pc2.at<float>(i));
ocvext::plot_1d(tmp, pc2, cv::Scalar(0,255,0));
output.images[2] = tmp;
}
output.nout = 3;
# endif
# endif
return 0;
}
| 10,120
|
C++
|
.cc
| 302
| 30.043046
| 106
| 0.636317
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,004
|
demo-skeleton.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/demo-skeleton.cc
|
/** @file demo-skeleton.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/demo-skeleton.hpp" // REPLACE WITH THE NAME OF YOUR INCLUDE FILE
// Replace "SkeletonDemo" by the name of your class
int SkeletonDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
// - The input image(s) are in the vector input.images (of type: vector<cv::Mat>).
// You can assume that input images are in BGR format, 8 bits.
// - The output image(s) should be stored in output.images[0], output.images[1], ... (of type: array of cv::Mat)
// Output images can be in BGR or grayscale format, 8 bits or floating point (in this case from 0 to 1.0).
// In this simple case we do the minimum.
// set number of images out to one.
output.nout = 1;
//clone the input to the output.
output.images[0]=input.images[0].clone();
//set a name.
output.names[0] = "The same";
// Return code: 0 if computing is successful (return any other value to indicate a failure)
return 0;
}
| 1,799
|
C++
|
.cc
| 33
| 50.606061
| 114
| 0.728571
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,005
|
histo.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/histo.cc
|
/** @file histo.cc
* @brief Traitements basés sur les histogrammes
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/histo.hpp"
static void calcul_histogramme_1d(const Mat &I,
MatND &hist,
int canal,
int maxval,
int nbins)
{
float hranges[] = {0, (float) maxval};
const float *ranges[] = {hranges};
calcHist(&I, 1, &canal, Mat(), // (pas de masque)
hist, 1, &nbins, ranges,
true, // Histogram uniforme
false);
normalize(hist, hist, 0, 255, NORM_MINMAX);
}
static void calcul_histogramme_2d(const Mat &I,
MatND &hist,
int canaux[],
int maxval[],
int nbins[])
{
float hranges0[] = {0, (float) maxval[0]};
float hranges1[] = {0, (float) maxval[1]};
const float *ranges[] = {hranges0, hranges1};
calcHist(&I, 1, canaux, Mat(), // (pas de masque)
hist, 2, nbins, ranges,
true, // Histogram uniforme
false); // Pas d'accumulation
normalize(hist, hist, 0, 255, NORM_MINMAX);
}
HistoBP::HistoBP()
{
props.id = "hist-bp";
props.requiert_roi = true;
input.roi = Rect(116,77,134-116,96-77);//Rect(225,289,50,50);
}
int calc_hist(const cv::Mat &I, cv::Rect &roi, cv::MatND &hist)
{
Mat hsv, hue, mask;
if(roi.width * roi.height == 0)
return -1;
Mat tmp = I(roi);
cvtColor(tmp, hsv, CV_BGR2HSV);
inRange(hsv, Scalar(0, 30, 30), Scalar(180, 256, 256), mask);
hue.create( hsv.size(), hsv.depth());
int ch[] = { 0, 0 };
mixChannels(&hsv, 1, &hue, 1, ch, 1 );
int bins = 25;
int histSize = MAX( bins, 2 );
float hue_range[] = { 0, 180 };
const float* ranges = { hue_range };
/// Get the histogram and normalize it
calcHist( &hue, 1, 0, mask, hist, 1, &histSize, &ranges, true, false );
normalize(hist, hist, 0, 255, NORM_MINMAX, -1, Mat());
return 0;
}
int calc_bp(const cv::Mat &I, const cv::MatND &hist, cv::MatND &backproj)
{
Mat Ihsv, Ihue, mask;
cvtColor(I, Ihsv, CV_BGR2HSV);
inRange(Ihsv, Scalar(0, 30, 30), Scalar(180, 256, 256), mask);
Ihue.create(Ihsv.size(), Ihsv.depth());
int ch[] = { 0, 0 };
mixChannels(&Ihsv, 1, &Ihue, 1, ch, 1 );
float hue_range[] = { 0, 180 };
const float* ranges = { hue_range };
/// Get backprojection
calcBackProject(&Ihue, 1, 0, hist, backproj, &ranges, 1, true);
backproj &= mask;
return 0;
}
int calc_bp(const cv::Mat &I, cv::Rect &roi, cv::MatND &backproj)
{
MatND hist;
calc_hist(I, roi, hist);
return calc_bp(I, hist, backproj);
}
int HistoBP::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
output.nout = 2;
output.images[0] = input.images[0].clone();
if(input.roi.width * input.roi.height > 0)
calc_bp(input.images[0], input.roi, output.images[1]);
output.names[0] = utils::langue.get_item("ROI selection");
output.names[1] = utils::langue.get_item("Backprojection");
return 0;
}
HistoCalc::HistoCalc()
{
props.id = "hist-calc";
}
static void dessine_courbe(const MatND &x, Mat &image, Scalar color, float yscale)
{
uint32_t n = x.rows;
float sx = image.cols, sy = image.rows;
float lxi = x.at<float>(0) * yscale;
for(auto i = 1u; i < n; i++)
{
float xi = x.at<float>(i) * yscale;
line(image,
Point((i-1)* sx / n,sy-lxi),
Point(i* sx / n,sy-xi),
color, 2, CV_AA);
lxi = xi;
}
}
int HistoCalc::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
// 0 : histogrammes séparés RGB
// 1 : histogramme niveaux de gris
// 2 : histogrammes séparés HSV
// 3 : histogramme 2D HS
int sel = input.model.get_attribute_as_int("sel");
int nbins = input.model.get_attribute_as_int("nbins");
if(nbins < 1)
nbins = 1;
MatND hist;
Mat I = input.images[0];
if(sel == 0)
{
output.nout = 1;
MatND hist[3];
output.images[0] = Mat(Size(512,512), CV_8UC3, cv::Scalar(255,255,255));
for(auto i = 0u; i < 3; i++)
calcul_histogramme_1d(I, hist[i], i, 255, nbins);
dessine_courbe(hist[0], output.images[0], Scalar(255,0,0), 512.0 / 255);
dessine_courbe(hist[1], output.images[0], Scalar(0,255,0), 512.0 / 255);
dessine_courbe(hist[2], output.images[0], Scalar(0,0,255), 512.0 / 255);
output.names[0] = utils::langue.get_item("histo-bvr");
}
else if(sel == 1)
{
cv::Mat Ig;
cv::cvtColor(I, Ig, CV_BGR2GRAY);
calcul_histogramme_1d(Ig, hist, 0, 255, nbins);
output.images[0] = Mat(Size(512,512), CV_8UC3, cv::Scalar(255,255,255));
dessine_courbe(hist, output.images[0], Scalar(0,0,0), 512.0 / 255);
output.names[0] = "Histogramme luminance";
}
else if(sel == 2)
{
Mat I2;
cvtColor(I, I2, CV_BGR2HSV);
int vmax[3] = {179,255,255};
for(auto i = 0u; i < 3; i++)
{
calcul_histogramme_1d(I2, hist, 0, vmax[i], nbins);
output.images[i] = Mat(Size(512,512), CV_8UC3, cv::Scalar(255,255,255));
dessine_courbe(hist, output.images[i], Scalar(0,0,0), 512.0 / 255.0);
}
output.nout = 3;
output.names[0] = "Teinte / Hue";
output.names[1] = "Saturation";
output.names[2] = "Valeur";
}
else if(sel == 3)
{
output.nout = 1;
Mat I2;
cvtColor(I, I2, CV_BGR2HSV);
int canaux[2] = {0, 1}; // Teinte & Saturation
int vmax[2] = {180, 255};
int vnbins[2] = {nbins, nbins};
calcul_histogramme_2d(I2, hist, canaux, vmax, vnbins);
while(hist.cols < 400)
cv::pyrUp(hist, hist);
output.images[0] = hist;
}
return 0;
}
HistoEgalisationDemo::HistoEgalisationDemo()
{
props.id = "histeq";
}
int HistoEgalisationDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int sel = input.model.get_attribute_as_int("sel");
int esp = input.model.get_attribute_as_int("espace");
int code[2] = {0};
int index_L = 0;
if(esp == 0)
{
code[0] = CV_BGR2YUV;
code[1] = CV_YUV2BGR;
}
else if(esp == 1)
{
code[0] = CV_BGR2Lab;
code[1] = CV_Lab2BGR;
}
else if(esp == 2)
{
code[0] = CV_BGR2HSV;
code[1] = CV_HSV2BGR;
index_L = 2;
}
else if(esp == 3)
{
code[0] = CV_BGR2HLS;
code[1] = CV_HLS2BGR;
index_L = 1;
}
Mat tmp;
if(esp == 4)
tmp = input.images[0].clone();
else
cvtColor(input.images[0], tmp, code[0]);
Mat chns[3];
split(tmp, chns);
// Egalisation luminance
if(sel == 0)
{
cv::equalizeHist(chns[index_L], chns[index_L]);
}
// Egalisation 3 canaux RGB (pour voir les artefacts couleurs)
else if(sel == 1)
{
for(auto i = 0u; i < 3; i++)
equalizeHist(chns[i], chns[i]);
}
merge(chns, 3, tmp);
if(esp == 4)
output.images[0] = tmp;
else
cvtColor(tmp, output.images[0], code[1]);
return 0;
}
| 7,689
|
C++
|
.cc
| 243
| 26.674897
| 85
| 0.61157
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,006
|
gradient-demo.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/gradient-demo.cc
|
/** @file gradient-demo.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/gradient-demo.hpp"
#include "gl.hpp"
#include "hough.hpp"
#include "opencv2/core/core.hpp"
ContourDemo::ContourDemo()
{
props.id = "contours";
}
int calcule_canny(const cv::Mat &I, cv::Mat &masque_canny,
const utils::model::Node &modele)
{
Mat tmp;
cvtColor(I, tmp, CV_BGR2GRAY);
int seuil_methode = modele.get_attribute_as_int("seuil-methode");
int seuil_bas = modele.get_attribute_as_int("seuil-bas");
int seuil_haut = modele.get_attribute_as_int("seuil-haut");
int norme = modele.get_attribute_as_int("norme");
int taille_noyau = modele.get_attribute_as_int("taille-noyau");
bool prefiltrage = modele.get_attribute_as_boolean("prefiltrage");
int taille_prefilt = modele.get_attribute_as_int("taille-noyau-prefiltrage");
if(prefiltrage)
blur(tmp, tmp, Size(taille_prefilt,taille_prefilt));
if(seuil_methode == 1)
{
cv::Scalar moyenne, sigma;
cv::meanStdDev(tmp, moyenne, sigma);
seuil_bas = moyenne[0] - sigma[0];
seuil_haut = moyenne[0] + sigma[0];
}
//infos("Canny: seuils = %d, %d.", seuil_bas, seuil_haut);
if(taille_noyau < 3)
taille_noyau = 3;
if((taille_noyau & 1) == 0)
taille_noyau++;
Canny(tmp, masque_canny, seuil_bas, seuil_haut, taille_noyau, norme == 1);
return 0;
}
int ContourDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat masque_canny;
calcule_canny(input.images[0], masque_canny, input.model);
output.names[0] = "Canny";
output.names[1] = "Contours";
output.nout = 2;
/*int kernel_width = 5;
int kernel_type = MORPH_RECT;
Mat K = getStructuringElement(kernel_type,
Size(2*kernel_width + 1, 2*kernel_width+1),
Point(kernel_width, kernel_width));
morphologyEx(detected_edges, detected_edges, MORPH_CLOSE, K);*/
output.images[0] = masque_canny;
int type_contour = input.model.get_attribute_as_int("typcont");
int mode = RETR_EXTERNAL;
if(type_contour == 1)
mode = RETR_TREE;
std::vector<std::vector<cv::Point> > contours;
std::vector<Vec4i> hierarchie;
findContours(masque_canny, contours,
hierarchie,
mode,
CHAIN_APPROX_SIMPLE,
Point(0,0));
RNG rng(12345);
// Dessine les contours
Mat dessin = Mat::zeros(masque_canny.size(), CV_8UC3 );
for(auto i = 0u; i < contours.size(); i++ )
{
Scalar couleur = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));
drawContours(dessin, contours, i, couleur, 2, 8, hierarchie, 0, Point());
}
output.images[1] = dessin;
return 0;
}
NetDemo::NetDemo()
{
props.id = "net";
}
int NetDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat I32, lap;
auto I = input.images[0].clone();
float c = input.model.get_attribute_as_float("coef");
I.convertTo(I32, CV_32F);
Laplacian(I, lap, CV_32F, 3);
Mat sharp_image_32bit = I32 - c * lap;
sharp_image_32bit.convertTo(output.images[0], CV_8U);
return 0;
}
GradientDemo::GradientDemo()
{
props.id = "gradient";
}
int GradientDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat gx, gy, agx, agy,tmp,grad;
auto model = input.model;
auto I = input.images[0];
float sigma = model.get_attribute_as_float("gaussian-sigma/sigma");
float gamma = model.get_attribute_as_float("deriche-gamma/gamma");
int sel = model.get_attribute_as_int("sel");
int sel2 = model.get_attribute_as_int("sel2");
int sel3 = model.get_attribute_as_int("sel3");
int tnoyau = model.get_attribute_as_int("taille-noyau");
//bool mode_hsv = model.get_attribute_as_boolean("mode-hsv");
cv::Mat masque_saturation_luminance;
/*if(mode_hsv)
{
cv::Mat hsv;
cv::Mat hsv_composantes[3];
cv::cvtColor(I, hsv, CV_BGR2HSV);
cv::split(hsv, hsv_composantes);
I = hsv_composantes[0]; // Teinte
masque_saturation_luminance =
(hsv_composantes[1] > 50)
& (hsv_composantes[2] > 50);
}*/
if((tnoyau & 1) == 0)
tnoyau++;
//GaussianBlur(I,tmp, Size(3,3),0);
if(sigma > 0)
{
if(sel3 == 0)
GaussianBlur(I,tmp, Size(0,0),sigma);
else if(sel3 == 1)
ocvext::Deriche_blur(I, tmp, gamma);
else
tmp = I.clone();
}
else
tmp = I.clone();
bool preconv = input.model.get_attribute_as_boolean("preconv");
bool gradient_couleur = input.model.get_attribute_as_boolean("couleur");
if(preconv)
cvtColor(tmp,tmp,CV_BGR2GRAY);
if(sel2 == 0)
{
Sobel(tmp,gx,CV_32F,1,0,tnoyau,1,0);
Sobel(tmp,gy,CV_32F,0,1,tnoyau,1,0);
}
else
{
Scharr(tmp,gx,CV_32F,1,0);
Scharr(tmp,gy,CV_32F,0,1);
}
if(!preconv && (!gradient_couleur || (sel == 2)))
{
infos("Gradient couleur -> abs...");
gx = cv::abs(gx);
gy = cv::abs(gy);
gx = gx / 255;
gy = gy / 255;
cvtColor(gx,gx,CV_BGR2GRAY);
cvtColor(gy,gy,CV_BGR2GRAY);
}
if(sel == 0)
{
output.nout = 1;
cv::Mat mag, angle;
cv::cartToPolar(gx, gy, mag, angle);
/*if(mode_hsv)
{
infos("mag : %d, %d, masque : %d, %d", mag.cols, mag.rows, masque_saturation_luminance.cols, masque_saturation_luminance.rows);
mag.setTo(0.0f, 255 - masque_saturation_luminance);
}*/
//addWeighted(agx, .5, agy, .5, 0, output.images[0]);
cv::normalize(mag, output.images[0], 0, 255, cv::NORM_MINMAX);
output.names[0] = utils::langue.get_item("gabs");
}
else if(sel == 2)
{
cv::Mat mag, angle;
cv::cartToPolar(gx, gy, mag, angle, true);
cv::normalize(mag, mag, 0, 255, cv::NORM_MINMAX);
cv::Mat hsv[3], hsv2;
hsv[0] = angle;
hsv[1] = cv::Mat::ones(angle.size(), CV_32F);
hsv[2] = mag;
cv::merge(hsv, 3, hsv2);
cv::cvtColor(hsv2, output.images[0], CV_HSV2BGR);
output.names[0] = "Gradient";
}
else
{
convertScaleAbs(gx,agx);
convertScaleAbs(gy,agy);
output.nout = 2;
output.images[0] = agx;
output.images[1] = agy;
output.names[0] = "GX";
output.names[1] = "GY";
}
return 0;
}
DetFlouDemo::DetFlouDemo()
{
props.id = "det-flou";
}
int DetFlouDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int taille_noyau = input.model.get_attribute_as_int("taille-noyau");
int BS = input.model.get_attribute_as_int("taille-bloc");
if((taille_noyau & 1) == 0)
taille_noyau++;
Mat tmp, lap;
cv::cvtColor(input.images[0], tmp, CV_BGR2GRAY);
cv::Laplacian(tmp, lap, CV_32F, taille_noyau, 1, 0);
//lap = cv::abs(lap);
cv::Scalar m, d;
cv::meanStdDev(lap, m, d);
//float score_global = d[0];
cv::Mat res = cv::Mat::zeros(lap.rows / BS, lap.cols / BS, CV_32F);
unsigned int yo = 0;
for(auto y = 0u; y + BS < (unsigned int) lap.rows; y += BS)
{
unsigned int xo = 0;
for(auto x = 0u; x + BS < (unsigned int) lap.cols; x += BS)
{
cv::meanStdDev(lap(cv::Rect(x,y,BS,BS)), m, d);
res.at<float>(yo,xo) = d[0];
xo++;
}
yo++;
}
cv::normalize(res, res, 0, 255, cv::NORM_MINMAX);
/*while()
{
cv::pyrUp(res, res);
}*/
cv::resize(res, res, cv::Size(lap.cols, lap.rows));
output.images[0] = res;
//cv::normalize(lap, output.images[0], 0, 255, NORM_MINMAX);
//convertScaleAbs(lap, output.images[0]); // Conversion vers CV_8U
output.names[0] = "Laplacien";
return 0;
}
LaplaceDemo::LaplaceDemo()
{
props.id = "laplace";
}
int LaplaceDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
bool pref = input.model.get_attribute_as_boolean("prefiltrer");
float sigma = input.model.get_attribute_as_float("sigma");
int aff = input.model.get_attribute_as_int("aff");
int taille_noyau = input.model.get_attribute_as_int("taille-noyau");
float echelle = input.model.get_attribute_as_float("echelle");
if((taille_noyau & 1) == 0)
taille_noyau++;
Mat tmp, lap;
cv::cvtColor(input.images[0], tmp, CV_BGR2GRAY);
if(pref && (sigma > 0))
GaussianBlur(tmp, tmp, Size(0,0), sigma);
if(echelle < 0.01)
echelle = 0.01;
infos("Resize echelle = %f", echelle);
cv::resize(tmp, tmp, cv::Size(0,0), echelle, echelle);
cv::Laplacian(tmp, lap, CV_32F, taille_noyau, 1, 0);
cv::resize(lap, lap, cv::Size(0,0), 1.0 / echelle, 1.0 / echelle);
if(aff == 0)
lap = cv::abs(lap);
cv::normalize(lap, output.images[0], 0, 255, NORM_MINMAX);
//convertScaleAbs(lap, output.images[0]); // Conversion vers CV_8U
output.names[0] = "Laplacien";
return 0;
}
CannyDemo::CannyDemo()
{
props.id = "canny";
}
int CannyDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
calcule_canny(input.images[0], output.images[0], input.model);
output.names[0] = "Contours";
return 0;
}
HoughDemo::HoughDemo()
{
props.id = "hough";
}
static void dessine_ligne(cv::Mat &I, float rho, float theta)
{
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(I, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
}
int HoughDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
float reso_rho = input.model.get_attribute_as_float("reso-rho");
float reso_theta = input.model.get_attribute_as_float("reso-theta") * CV_PI / 180.0;
float seuil = input.model.get_attribute_as_float("seuil");
float seuilg = input.model.get_attribute_as_float("seuilg");
float seuil_canny = input.model.get_attribute_as_float("seuil-canny");
float angle = input.model.get_attribute_as_float("angle");
Mat dst, bw;
int ratio = 3;
auto I = input.images[0].clone();
cv::cvtColor(I, bw, CV_BGR2GRAY);
if(angle != 0)
{
infos("Rotation %f degres...", angle);
cv::Size sz = bw.size() / 2;
cv::Point centre;
centre.x = sz.width;
centre.y = sz.height;
//uint16_t sx = sz.width, sy = sz.height;
cv::Mat R = cv::getRotationMatrix2D(centre, angle, 1.0);
cv::warpAffine(bw, bw, R, bw.size());
cv::warpAffine(I, I, R, bw.size());
//bw = bw(Rect(sx/4,sy/4,sx/2,sy/2));
}
if((reso_theta <= 0) || (reso_rho <= 0))
{
output.nout = 0;
output.errmsg = "Les resolutions en rho et theta doivent etre positives.";
return -1;
}
cv::blur(bw, bw, cv::Size(3, 3));
Canny(bw, bw, seuil_canny, seuil_canny * ratio, 3);
cvtColor(bw, output.images[0], CV_GRAY2BGR);
int sel = input.model.get_attribute_as_int("sel");
if(sel == 0)
{
output.images[1] = I.clone();
output.nout = 2;
std::vector<Vec2f> lignes;
HoughLines(bw, lignes, reso_rho, reso_theta, seuil, 0, 0);
infos("Détecté %d lignes.\n", (int) lignes.size());
for(const auto &l: lignes)
dessine_ligne(output.images[1], l[0], l[1]);
}
else if(sel == 1)
{
output.images[1] = I.clone();
output.nout = 2;
std::vector<cv::Vec4i> lines;
cv::HoughLinesP(bw, lines, reso_rho, reso_theta, seuil,
30, // min line length
10); // max line gap
for(size_t i = 0; i < lines.size(); i++ )
{
//float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
pt1.x = lines[i].val[0];
pt1.y = lines[i].val[1];
pt2.x = lines[i].val[2];
pt2.y = lines[i].val[3];
line(output.images[1], pt1, pt2, Scalar(0,0,255), 3, CV_AA);
}
}
else if(sel == 2)
{
output.nout = 3;
output.images[0] = I.clone();
std::vector<Vec2f> lignes;
cv::Mat deb;
ocvext::Hough_lines_with_gradient_dir(I, lignes, deb, reso_rho, reso_theta, 0.6, seuilg);
cv::pyrUp(deb, deb);
output.images[1] = deb.t();
output.names[1] = "Espace parametrique";
infos("Détecté %d lignes.\n", (int) lignes.size());
output.images[2] = I.clone();
for(const auto &l: lignes)
dessine_ligne(output.images[2], l[0], l[1]);
}
return 0;
}
HoughCDemo::HoughCDemo()
{
props.id = "houghc";
}
int HoughCDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat gris;
double seuil_canny = input.model.get_attribute_as_int("seuil-canny");
auto I = input.images[0];
cvtColor(I, gris, CV_BGR2GRAY);
output.images[0] = I.clone();
std::vector<Vec3f> cercles;
double seuil = input.model.get_attribute_as_int("seuil");
int rmin = input.model.get_attribute_as_int("rmin");
int rmax = input.model.get_attribute_as_int("rmax");
HoughCircles(gris, cercles, CV_HOUGH_GRADIENT, 2 /* dp = 2 */,
20 /* min dist */,
seuil_canny,
seuil,
rmin,
rmax);
infos("Détecté %d cercles.\n", (int) cercles.size());
for(size_t i = 0; i < cercles.size(); i++ )
{
float xc = cercles[i][0], yc = cercles[i][1], r = cercles[i][2];
cv::circle(output.images[0], Point(xc,yc), r, Scalar(0,255,0), 2);
}
return 0;
}
RectDemo::RectDemo()
{
props.id = "hough-rec";
}
Point2f computeIntersect(cv::Vec4i a,
cv::Vec4i b)
{
int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3], x3 = b[0], y3 = b[1], x4 = b[2], y4 = b[3];
//float denom;
if (float d = ((float)(x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)))
{
cv::Point2f pt;
pt.x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
pt.y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;
return pt;
}
else
return cv::Point2f(-1, -1);
}
void sortCorners(std::vector<cv::Point2f>& corners,
cv::Point2f center)
{
std::vector<cv::Point2f> top, bot;
for(auto i = 0u; i < corners.size(); i++)
{
if (corners[i].y < center.y)
top.push_back(corners[i]);
else
bot.push_back(corners[i]);
}
corners.clear();
if (top.size() == 2 && bot.size() == 2){
cv::Point2f tl = top[0].x > top[1].x ? top[1] : top[0];
cv::Point2f tr = top[0].x > top[1].x ? top[0] : top[1];
cv::Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0];
cv::Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1];
corners.push_back(tl);
corners.push_back(tr);
corners.push_back(br);
corners.push_back(bl);
}
}
// D'après http://opencv-code.com/tutorials/automatic-perspective-correction-for-quadrilateral-objects/
int RectDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
cv::Mat bw;
auto I = input.images[0];
cv::cvtColor(I, bw, CV_BGR2GRAY);
cv::blur(bw, bw, cv::Size(3, 3));
cv::Canny(bw, bw, 100, 100, 3);
Mat I0 = I.clone();
std::vector<cv::Vec4i> lines;
cv::HoughLinesP(bw, lines, 1, CV_PI/180, 70, 30, 10);
output.nout = 2;
output.names[0] = "Localisation quadrilatere";
output.names[1] = "Correction de perspective";
// Expand the lines
for(auto i = 0u; i < lines.size(); i++)
{
cv::Vec4i v = lines[i];
lines[i][0] = 0;
lines[i][1] = ((float)v[1] - v[3]) / (v[0] - v[2]) * -v[0] + v[1];
lines[i][2] = I.cols;
lines[i][3] = ((float)v[1] - v[3]) / (v[0] - v[2]) * (I.cols - v[2]) + v[3];
}
std::vector<cv::Point2f> corners;
for(auto i = 0u; i < lines.size(); i++)
{
for (unsigned int j = i+1; j < lines.size(); j++)
{
cv::Point2f pt = computeIntersect(lines[i], lines[j]);
if (pt.x >= 0 && pt.y >= 0)
corners.push_back(pt);
}
}
std::vector<cv::Point2f> approx;
cv::approxPolyDP(cv::Mat(corners), approx, cv::arcLength(cv::Mat(corners), true) * 0.02, true);
if (approx.size() != 4)
{
//errmsg = "obj-pas-quadri";
//return -1;
output.images[0] = Mat::zeros(I.size(), CV_8UC3);
return 0;
}
cv::Point2f center(0,0);
// Get mass center
for (auto i = 0u; i < corners.size(); i++)
center += corners[i];
center *= (1. / corners.size());
output.images[0] = input.images[0].clone();
output.images[1] = Mat::zeros(I.size(), CV_8UC3);
sortCorners(corners, center);
if (corners.size() == 0)
{
//errmsg = "coins-non-tries-correctement";
//return -1;
return 0;
}
// Draw lines
for(auto i = 0u; i < lines.size(); i++)
{
cv::Vec4i v = lines[i];
cv::line(output.images[0], cv::Point(v[0], v[1]), cv::Point(v[2], v[3]), CV_RGB(0,255,0));
}
// Draw corner points
cv::circle(output.images[0], corners[0], 3, CV_RGB(255,0,0), 2);
cv::circle(output.images[0], corners[1], 3, CV_RGB(0,255,0), 2);
cv::circle(output.images[0], corners[2], 3, CV_RGB(0,0,255), 2);
cv::circle(output.images[0], corners[3], 3, CV_RGB(255,255,255), 2);
// Draw mass center
cv::circle(output.images[0], center, 3, CV_RGB(255,255,0), 2);
cv::Mat quad = cv::Mat::zeros(300, 220, CV_8UC3);
std::vector<cv::Point2f> quad_pts;
quad_pts.push_back(cv::Point2f(0, 0));
quad_pts.push_back(cv::Point2f(quad.cols, 0));
quad_pts.push_back(cv::Point2f(quad.cols, quad.rows));
quad_pts.push_back(cv::Point2f(0, quad.rows));
cv::Mat transmtx = cv::getPerspectiveTransform(corners, quad_pts);
cv::warpPerspective(I0, output.images[1], transmtx, quad.size());
return 0;
}
| 17,821
|
C++
|
.cc
| 536
| 29.076493
| 133
| 0.625627
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,007
|
video-demo.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/video-demo.cc
|
/** @file video-demo.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/video-demo.hpp"
#include "demo-items/histo.hpp"
#include "opencv2/video.hpp"
#include "opencv2/videostab.hpp"
DemoVideoStab::DemoVideoStab()
{
props.id = "videostab";
}
int DemoVideoStab::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
return 0;
}
CamShiftDemo::CamShiftDemo()
{
props.id = "camshift";
props.requiert_roi = true;
bp_init_ok = false;
}
void CamShiftDemo::set_roi(const cv::Mat &I, const cv::Rect &new_roi)
{
bp_init_ok = false;
input.roi = new_roi;
this->trackwindow = input.roi;
if(input.roi.width * input.roi.height < 4)
{
avertissement("set_roi: aire trop petite.");
return;
}
/* Calcul de l'histogramme et backprojection */
trace_majeure("set roi(%d,%d,%d,%d): calc bp...",
input.roi.x, input.roi.y, input.roi.width, input.roi.height);
trace_verbeuse("img dim = %d * %d.", I.cols, I.rows);
calc_hist(I, input.roi, hist);
trace_verbeuse("fait.");
bp_init_ok = true;
}
int CamShiftDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
auto I = input.images[0];
output.names[1] = "back-projection histo.";
if(!bp_init_ok)
{
auto sx = I.cols, sy = I.rows;
trace_verbeuse("SX %d SY %d.", sx, sy);
set_roi(I, Rect(sx/2-50,sy/3,20,20));//Rect(100,300,50,50));
}
if(bp_init_ok)
{
cv::MatND backproj;
calc_bp(I, hist, backproj);
bool suivi_taille = input.model.get_attribute_as_boolean("suivi-taille");
bool affiche_pa = input.model.get_attribute_as_boolean("affiche-pa");
if(affiche_pa)
{
output.nout = 2;
output.images[0] = backproj;
output.images[1] = I.clone();
}
else
{
output.nout = 1;
output.images[0] = I;
}
cvtColor(backproj, output.images[1], CV_GRAY2BGR);
trace_verbeuse("camshift, %d...", trackwindow.width);
cv::Rect tw3;
tw3.width = trackwindow.width;
tw3.height = trackwindow.height;
RotatedRect trackbox = CamShift(backproj, trackwindow,
TermCriteria(TermCriteria::EPS | TermCriteria::COUNT, 10, 1 ));
trace_verbeuse("camshift ok, %d.", trackwindow.width);
auto tw2 = trackbox.boundingRect();
// Meme centre que tw2, mais meme largeur que tw1
if(!suivi_taille)
{
tw3.x = tw2.x + tw2.width / 2 - tw3.width / 2;
tw3.y = tw2.y + tw2.height / 2 - tw3.height / 2;
trackwindow = tw3;
}
if(trackwindow.width * trackwindow.height > 0)
{
cv::rectangle(I, trackwindow, Scalar(255,255,0), 3);
trace_verbeuse("trackwindow: %d, %d, %d, %d.",
trackwindow.x, trackwindow.y,
trackwindow.width, trackwindow.height);
}
else
avertissement("tracwindow: aire nulle.");
}
return 0;
}
SousArrierePlanDemo::SousArrierePlanDemo()
{
props.id = "sous-arriere-plan";
nframes = 0;
output.nout = 3;
output.names[0] = "masque";
output.names[2] = "arriere-plan";
osel = -1;
//this->mog2 = createBackgroundSubtractorMOG2();
}
void SousArrierePlanDemo::update_sel(int nsel)
{
if(nsel != osel)
{
if(nsel == 0)
algo = createBackgroundSubtractorMOG2();
else if(nsel == 1)
algo = createBackgroundSubtractorKNN();
osel = nsel;
}
}
int SousArrierePlanDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int sel = input.model.get_attribute_as_int("sel");
update_sel(sel);
Mat tmp, mask;
auto I = input.images[0];
output.images[0] = I;
resize(I,tmp,Size(0,0),0.25,0.25);
algo->apply(tmp, mask);
algo->getBackgroundImage(output.images[2]);
//resize(mask,output.images[1],Size(0,0),4,4);
//mask = mask > 128;
/*cv::Mat masque2;
mask.convertTo(masque2, CV_32F);
cv::Mat O = I.clone();
cvtColor(I, O, CV_BGR2GRAY);
O.convertTo(O, CV_32F);
cv::pyrUp(masque2, masque2);
cv::pyrUp(masque2, masque2);*/
output.images[1] = mask;
//I.copyTo(output.images[1], masque2);
//output.images[1] = Mat::zeros(O.size(), CV_32F);
//output.images[1] += O.mul(masque2 / 255);
//output.images[1].convertTo(output.images[1], CV_8U);
nframes++;
if(nframes < 5)
{
output.images[1] = I.clone();
output.images[2] = I.clone();
return 0;
}
# ifdef OCV240
if(mhi.data == nullptr)
mhi = Mat::zeros(mask.size(), CV_32F);
int maxhist = model.get_attribute_as_int("max-hist");
infos("updateMotionHistory...");
updateMotionHistory(mask, mhi, nframes - 5, maxhist);
Mat segmask = Mat::zeros(mask.size(), CV_32F);
int seuil = model.get_attribute_as_int("seuil");
std::vector<Rect> brects;
infos("segmentMotion...");
segmentMotion(mhi, segmask, brects, nframes - 5, seuil);
infos("rects...");
images[1] = tmp.clone();
for(auto r: brects)
cv::rectangle(images[1], r, Scalar(0,255,0));
resize(images[1], images[1], Size(0,0), 4, 4);
this->names[1] = langue.get_item("mask-arr");
this->names[2] = "Segmentation";
# endif
infos("fin.");
return 0;
}
OptFlowDemo::OptFlowDemo()
{
props.id = "flux-optique";
reset = true;
algo = createOptFlow_DualTVL1();
output.names[0] = "Flux optique";
}
int OptFlowDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
// computed flow image that has the same size as prev and type CV_32FC2
Mat flow;
Mat I1;
Mat _hsv[3], hsv;
Mat xy[2], mag, nmag, angle;
auto I = input.images[0];
output.nout = 2;
output.images[0] = I;
if(Iprec.size() != I.size())
reset = true;
if(reset)
{
reset = false;
cv::cvtColor(I, Iprec, CV_BGR2GRAY);
output.images[1] = I;
//out.images[0] = Mat::zeros(I.size(), CV_8UC3);
return 0;
}
cv::cvtColor(I, I1, CV_BGR2GRAY);
calcOpticalFlowFarneback(Iprec, I1, flow, 0.5, 3, 15, 3, 5, 1.2, 0);
Iprec = I1.clone();
split(flow, xy);
cartToPolar(xy[0],xy[1], mag, angle);
double maxVal;
minMaxLoc(mag, 0, &maxVal);
normalize(mag,nmag,0,1.0,NORM_MINMAX);
_hsv[0] = angle * ((360.0 / (2 * 3.141592))); // Teinte (couleur) = angle
_hsv[1] = 1.0 * Mat::ones(angle.size(), CV_32F); // Chromaticité = 1
_hsv[2] = nmag; // Luminance
merge(_hsv, 3, hsv);
output.images[1] = Mat(hsv.size(), CV_8UC3);
cvtColor(hsv, output.images[1], cv::COLOR_HSV2BGR);
output.images[1].convertTo(output.images[1], CV_8UC3, 255);
trace_verbeuse("fait: %d * %d, depth = %d.", output.images[0].cols, output.images[0].rows, output.images[0].depth());
return 0;
}
| 7,239
|
C++
|
.cc
| 225
| 28.422222
| 119
| 0.661782
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,008
|
segmentation.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/segmentation.cc
|
#include "demo-items/segmentation.hpp"
#include <iostream>
#ifdef USE_CONTRIB
#include "opencv2/ximgproc.hpp"
#endif
DemoSuperpixels::DemoSuperpixels()
{
props.id = "superpixels";
}
int DemoSuperpixels::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
#ifdef USE_CONTRIB
auto slic = cv::ximgproc::createSuperpixelSLIC(
input.images[0], cv::ximgproc::SLICO,
input.model.get_attribute_as_int("taille"),
input.model.get_attribute_as_float("reglage"));
slic->iterate();
Mat masque;
slic->getLabelContourMask(masque);//);
Mat O = input.images[0].clone();
O /= 2;
O.setTo(Scalar(0,0,0), masque);
output.images[0] = O;
# else
output.images[0] = input.images[0];
# endif
return 0;
}
DemoMahalanobis::DemoMahalanobis()
{
props.id = "mahalanobis";
props.requiert_roi = true;
input.roi = Rect(116,77,134-116,96-77);
}
int DemoMahalanobis::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat I = input.images[0];
output.nout = 2;
output.images[0] = I.clone();
if(input.roi.area() == 0)
{
output.images[1] = I.clone();
infos("RDI invalide.");
return 0;
}
cv::Mat ILab;
cvtColor(I, ILab, CV_BGR2Lab);
infos("Compute covar samples...");
auto M = ILab(input.roi);
# if 0
Mat samples(M.rows*M.cols,2,CV_32F);
for(auto y = 0u; y < (unsigned int) M.rows; y++)
{
for(auto x = 0u; x < (unsigned int) M.cols; x++)
{
const Vec3b &bgr = M.at<Vec3b>(y,x);
float sum = bgr[0] + bgr[1] + bgr[2];
// R / (B + G +R)
samples.at<float>(x+y*M.cols, 0) = bgr[2] / sum;
// B / (B + G +R)
samples.at<float>(x+y*M.cols, 1) = bgr[0] / sum;
}
}
# endif
Mat samples(M.rows*M.cols,3,CV_32F);
for(auto y = 0u; y < (unsigned int) M.rows; y++)
{
for(auto x = 0u; x < (unsigned int) M.cols; x++)
{
const Vec3b &Lab = M.at<Vec3b>(y,x);
samples.at<float>(x+y*M.cols, 0) = Lab[0];
samples.at<float>(x+y*M.cols, 1) = Lab[1];
samples.at<float>(x+y*M.cols, 2) = Lab[2];
}
}
infos("Compute covar matrix...");
Mat covar, covari, mean;
cv::calcCovarMatrix(samples, covar, mean,
CV_COVAR_NORMAL | CV_COVAR_SCALE | CV_COVAR_ROWS);
cv::invert(covar, covari, cv::DECOMP_SVD);
std::cout << "mean: " << mean << std::endl;
std::cout << "covar: " << covar << std::endl;
std::cout << "covari: " << covari << std::endl;
mean.convertTo(mean, CV_32F);
covari.convertTo(covari, CV_32F);
infos(" Mahalanobis...");
const Vec3b *iptr = ILab.ptr<Vec3b>();
Mat v(1,3,CV_32F);
Mat fmask(I.size(), CV_32F);
float *optr = fmask.ptr<float>();
float *pv = v.ptr<float>(0);
for(auto i = 0u; i < input.images[0].total(); i++)
{
const Vec3b &Lab = *iptr++;
/*float sum = bgr[0] + bgr[1] + bgr[2];
float cr = bgr[2] / sum;
float cb = bgr[0] / sum;
pv[0] = cr;
pv[1] = cb;*/
pv[0] = Lab[0];
pv[1] = Lab[1];
pv[2] = Lab[2];
float dst = cv::Mahalanobis(mean, v, covari);
*optr++ = dst;
}
infos(" normalize...");
cv::normalize(fmask, fmask, 0, 255, cv::NORM_MINMAX);
//fmask = 255.0 - fmask;
fmask.convertTo(fmask, CV_8UC1);
output.images[1] = fmask;
return 0;
}
WShedDemo::WShedDemo()
{
props.id = "watershed";
output.nout = 3;
}
int WShedDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat gray, nb, ret;
cvtColor(input.images[0], gray, CV_BGR2GRAY);
threshold(gray,nb,0,255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
//Execute morphological-open
morphologyEx(nb,ret,MORPH_OPEN,Mat::ones(9,9,CV_8SC1),Point(4,4),2);
Mat distTransformed(ret.rows,ret.cols,CV_32F);
distanceTransform(ret,distTransformed,CV_DIST_L2,3);
//normalize the transformed image in order to display
normalize(distTransformed, distTransformed, 0.0, 255.0, NORM_MINMAX);
output.nout = 4;
output.images[0] = input.images[0];
output.images[1] = distTransformed.clone();
output.names[1] = "Distance Transformation";
//threshold the transformed image to obtain markers for watershed
threshold(distTransformed,distTransformed,input.model.get_attribute_as_float("seuil-dist") * 255,255,CV_THRESH_BINARY);
distTransformed.convertTo(distTransformed,CV_8UC1);
output.images[2] = distTransformed.clone();
output.names[2] = "Thresholded dist. trans.";
//imshow("Thresholded Distance Transformation",distTransformed);
std::vector<std::vector<Point> > contours;
std::vector<Vec4i> hierarchy;
findContours(distTransformed, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
if(contours.empty())
return -1;
Mat markers(distTransformed.size(), CV_32S);
markers = Scalar::all(0);
int idx, compCount = 0;
//draw contours
for(idx = 0; idx >= 0; idx = hierarchy[idx][0], compCount++)
drawContours(markers, contours, idx, Scalar::all(compCount+1), -1, 8, hierarchy, INT_MAX);
std::vector<Vec3b> colorTab;
for(auto i = 0; i < compCount; i++ )
{
int b = theRNG().uniform(0, 255);
int g = theRNG().uniform(0, 255);
int r = theRNG().uniform(0, 255);
colorTab.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
}
//apply watershed with the markers as seeds
watershed(input.images[0], markers);
output.images[3] = Mat(markers.size(), CV_8UC3);
infos("paint the watershed image...");
for(auto i = 0; i < markers.rows; i++)
{
for(auto j = 0; j < markers.cols; j++)
{
int index = markers.at<int>(i,j);
if(index == -1)
output.images[3].at<Vec3b>(i,j) = Vec3b(255,255,255);
else if((index <= 0) || (index > compCount))
output.images[3].at<Vec3b>(i,j) = Vec3b(0,0,0);
else
output.images[3].at<Vec3b>(i,j) = colorTab[index - 1];
}
}
output.images[3] = output.images[3] * 0.5 + input.images[0] * 0.5;
return 0;
}
GrabCutDemo::GrabCutDemo()
{
props.id = "grabcut";
props.requiert_roi = true;
input.roi.x = 137;
input.roi.y = 5;
input.roi.width = 251 - 137;
input.roi.height = 130 - 5;
}
int GrabCutDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat mask, bgmodel, fgmodel;
Mat I = input.images[0];
mask = Mat::zeros(I.size(), CV_8UC1);
trace_verbeuse("grabcut...");
Mat Id;
cv::pyrDown(I, Id);
cv::Rect roi2;
roi2.x = input.roi.x / 2;
roi2.y = input.roi.y / 2;
roi2.width = input.roi.width / 2;
roi2.height = input.roi.height / 2;
cv::grabCut(Id, mask, roi2, bgmodel, fgmodel, 1, GC_INIT_WITH_RECT);
//cv::pyrUp(mask, mask);
trace_verbeuse("masque...");
output.nout = 2;
output.images[0] = I.clone();
output.images[1] = I.clone();
//Point3_<uchar> *p = O.ptr<Point3_<uchar>>(0,0);
for(auto y = 0; y < I.rows; y++)
{
for(auto x = 0; x < I.cols; x++)
{
uint8_t msk = mask.at<uint8_t>(Point(x/2,y/2));
if((msk == GC_BGD) || (msk == GC_PR_BGD))
{
Vec3b &pix = output.images[1].at<Vec3b>(Point(x,y));
pix[0] = 0;
pix[1] = 0;
pix[2] = 0;
}
}
}
trace_verbeuse("terminé.");
return 0;
}
| 7,024
|
C++
|
.cc
| 223
| 27.713004
| 121
| 0.634439
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
754,009
|
misc.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/misc.cc
|
/** @file misc.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/misc.hpp"
CameraDemo::CameraDemo()
{
props.id = "camera";
props.input_min = 1;
props.input_max = -1;
}
int CameraDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
output.nout = input.images.size();
for(auto i = 0u; i < input.images.size(); i++)
output.images[i] = input.images[i].clone();
// Return code: 0 if computing is successful (return any other value to indicate a failure)
return 0;
}
| 1,310
|
C++
|
.cc
| 30
| 39.666667
| 93
| 0.732752
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,010
|
morpho-demo.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/morpho-demo.cc
|
/** @file morpho-demo.cc
* @brief Démonstrations autour des opérateurs morphologiques
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/morpho-demo.hpp"
#include "thinning.hpp"
MorphoDemo::MorphoDemo()
{
props.id = "morpho";
}
int MorphoDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int sel = input.model.get_attribute_as_int("type");
int kersel = input.model.get_attribute_as_int("kernel");
int niter = input.model.get_attribute_as_int("niter");
int kernel_type = MORPH_RECT;
if(kersel == 0)
kernel_type = MORPH_RECT;
else if(kersel == 1 )
kernel_type = MORPH_CROSS;
else if(kersel == 2)
kernel_type = MORPH_ELLIPSE;
else
assert(0);
int kernel_width = input.model.get_attribute_as_int("kernel-width");
printf("Proceed k = %d, kw = %d, sel = %d.\n", kersel, kernel_width, sel);
fflush(0);
Mat K = getStructuringElement(kernel_type,
Size(2*kernel_width + 1, 2*kernel_width+1 ),
Point(kernel_width, kernel_width));
auto I = input.images[0];
if(sel == 0)
dilate(I,output.images[0],K,cv::Point(-1,-1),niter);
else if(sel == 1)
erode(I,output.images[0],K,cv::Point(-1,-1),niter);
else
morphologyEx(I, output.images[0], sel, K, cv::Point(-1,-1), niter);
return 0;
}
DemoSqueletisation::DemoSqueletisation()
{
props.id = "squeletisation";
}
int DemoSqueletisation::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat A, squelette;
cv::cvtColor(input.images[0], A, CV_BGR2GRAY);
if(input.model.get_attribute_as_boolean("binariser"))
cv::threshold(A, A, 128, 255, cv::THRESH_OTSU);
if(input.model.get_attribute_as_boolean("inverser"))
A = 255 - A;
int sel = input.model.get_attribute_as_int("sel");
// Gradient morphologique
// Algorithme d'après page web
// http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/
if(sel == 0)
{
ocvext::thinning_morpho(A, squelette);
}
// Zhang-Suen
// D'après https://web.archive.org/web/20160322113207/http://opencv-code.com/quick-tips/implementation-of-thinning-algorithm-in-opencv/
else if(sel == 1)
{
ocvext::thinning_Zhang_Suen(A, squelette);
}
// Guo-Hall
// D'après https://web.archive.org/web/20160314104646/http://opencv-code.com/quick-tips/implementation-of-guo-hall-thinning-algorithm/
else if(sel == 2)
{
ocvext::thinning_Guo_Hall(A, squelette);
}
int aff = input.model.get_attribute_as_int("aff");
if(aff == 0)
{
output.nout = 1;
output.names[0] = "Squelitisation";
output.images[0] = squelette;
}
else if(aff == 1)
{
output.nout = 2;
output.names[0] = "Binarisation";
output.names[1] = "Squelitisation";
output.images[0] = A;
output.images[1] = squelette;
}
else if(aff == 2)
{
output.nout = 1;
output.names[0] = "Squelitisation";
output.images[0] = input.images[0].clone();
output.images[0].setTo(Scalar(0,0,255), squelette);
}
return 0;
}
| 3,833
|
C++
|
.cc
| 107
| 31.420561
| 137
| 0.684282
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,011
|
espaces-de-couleurs.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/espaces-de-couleurs.cc
|
/** @file color-demo.cc
* @brief Gestion des espaces de couleurs
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/espaces-de-couleurs.hpp"
HSVDemo::HSVDemo()
{
props.id = "hsv";
output.names[0] = "Couleur";
}
int HSVDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int T = input.model.get_attribute_as_int("T");
int S = input.model.get_attribute_as_int("S");
int V = input.model.get_attribute_as_int("V");
auto I = input.images[0];
int sx = I.cols;
int sy = I.rows;
//I.setTo(Scalar(0,0,0));
I = Mat::zeros(Size(sx,sy),CV_8UC3);
Mat tsv = Mat::zeros(Size(sx,sy),CV_8UC3);
tsv.setTo(Scalar(T,S,V));
cvtColor(tsv, output.images[0], CV_HSV2BGR);
return 0;
}
DemoBalleTennis::DemoBalleTennis()
{
props.id = "tennis";
}
int DemoBalleTennis::proceed(OCVDemoItemInput &input,
OCVDemoItemOutput &output)
{
Mat &I = input.images[0];
// Solutions :
// (1) Mahalanobis distance, puis seuillage
// (2) Projection arrière d'histogramme
// (3) Seuillage simple sur teinte / saturation
Mat tsv, masque;
cvtColor(I, tsv, CV_BGR2HSV);
inRange(tsv, Scalar(input.model.get_attribute_as_int("T0"),
input.model.get_attribute_as_int("S0"),
input.model.get_attribute_as_int("V0")),
Scalar(input.model.get_attribute_as_int("T1"),
input.model.get_attribute_as_int("S1"),
input.model.get_attribute_as_int("V1")),
masque);
Mat dst;
Point balle_loc;
cv::distanceTransform(masque, dst, CV_DIST_L2, 3);
cv::minMaxLoc(dst, nullptr, nullptr, nullptr, &balle_loc);
Mat O = input.images[0].clone();
// Position de la balle détectée
cv::line(O, balle_loc - Point(5,0), balle_loc + Point(5,0),
Scalar(0,0,255), 1);
cv::line(O, balle_loc - Point(0,5), balle_loc + Point(0,5),
Scalar(0,0,255), 1);
output.images[0] = O;
return 0;
}
| 2,703
|
C++
|
.cc
| 71
| 33.591549
| 79
| 0.684716
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,012
|
3d.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/3d.cc
|
/** @file 3d.cc
@brief Démonstratation relatives à la 3D
Démonstrations inspirées du livre :
G. Bradski, Learning OpenCV: Computer vision with the OpenCV library, 2008
Et aussi d'après l'exemple fourni avec opencv: opencv/sources/samples/cpp/stereo_calib.cpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/3d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include <cmath>
#include <iostream>
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
StereoCalDemo *StereoCalDemo::instance;
StereoCalResultats stereo_cal;
class MatText
{
public:
MatText(Mat I)
{
this->I = I;
x = 0; y = 25;
last_dy = 20;
}
inline void print(std::string s, ...)
{
va_list ap;
va_start(ap, s);
printv(s, ap);
va_end(ap);
}
private:
inline void printv(std::string s, va_list ap)
{
char tmp_buffer[1000];
if(vsnprintf(tmp_buffer, 1000, s.c_str(), ap) > 0)
printi1(std::string(tmp_buffer));
}
void printi1(const std::string &s)
{
std::string tamp;
for(auto i = 0u; i < s.length(); i++)
{
if(s[i] == '\n')
{
printi(tamp);
tamp = "";
x = 0;
y += last_dy;
}
else
{
char c[2];
c[0] = s[i];
c[1] = 0;
tamp += std::string(c);
}
}
printi(tamp);
}
void printi(const std::string &s)
{
if(s.size() == 0)
return;
int baseLine;
double tscale = 2.0;
auto font = FONT_HERSHEY_COMPLEX_SMALL;
Size si = getTextSize(s, font, tscale, 1.2, &baseLine);
putText(I, s,
Point(x, y),
font,
tscale,
Scalar(255,255,255),
1.2,
CV_AA);
last_dy = (last_dy > (si.height + 2)) ? last_dy : (si.height + 2);
x += si.width;
if(x >= (unsigned int) I.cols)
{
x = 0;
y += si.height + 2;
}
}
Mat I;
uint32_t x, y;
int last_dy;
};
StereoFMatDemo::StereoFMatDemo()
{
props.id = "stereo-fmat";
}
int StereoFMatDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
return 0;
}
StereoCalDemo *StereoCalDemo::get_instance()
{
return instance;
}
int StereoCalDemo::lookup_corners(cv::Mat &I,
cv::Mat &O,
utils::model::Node &model,
std::vector<cv::Point2f> &coins)
{
unsigned int bw = input.model.get_attribute_as_int("bw"),
bh = input.model.get_attribute_as_int("bh");
cv::Size dim_damier(bw,bh);
O = I.clone();
bool found = cv::findChessboardCorners(I, dim_damier, coins,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
//trace_verbeuse("Image %d: trouvé %d coins.", k, coins.size());
# if 0
// Résolution d'ambiguité si damier carré
if((coins.size() == bh * bw) && (bh == bw))
{
// Si les coins sont alignés verticalement, fait une rotation de 90° (pour lever l'ambiguité)
auto d = coins[1] - coins[0];
auto angle = std::fmod(atan2(d.y, d.x) + 2 * M_PI, 2 * M_PI);
if(angle > M_PI)
angle -= 2 * M_PI;
if((std::fabs(angle) > M_PI / 4) && (std::fabs(angle) < 3 * M_PI / 4))
{
infos("Image: coins verticaux (%.2f radians) -> transposition.", angle);
std::vector<cv::Point2f> coins2 = coins;
for(auto i = 0u; i < bw; i++)
for(auto j = 0u; j < bw; j++)
coins[i+j*bw] = coins2[i*bw+j];
}
auto signe = coins[0].y - coins[2*bw].y;
if(signe < 0)
{
infos("Image: miroir vertical.");
std::reverse(coins.begin(), coins.end());
}
signe = coins[0].x - coins[2].x;
if(signe < 0)
{
infos("Image: miroir horizontal.");
for(auto i = 0u; i < bw; i++)
std::reverse(coins.begin()+i*bw, coins.begin()+(i+1)*bw);
}
}
# endif
if(!found || (coins.size() < 5))
{
output.errmsg = utils::langue.get_item("coins-non-trouves");
avertissement("%s", output.errmsg.c_str());
avertissement("Coins.size = %d.", coins.size());
return -1;
}
cv::Mat gris;
cv::cvtColor(I, gris, CV_BGR2GRAY);
cv::cornerSubPix(gris, coins, Size(11,11), Size(-1,-1),
TermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 30, 0.01));
// Dessin des coins
cv::drawChessboardCorners(O, dim_damier, Mat(coins), found);
return 0;
}
// Stereo cal demo :
// - (1) une démo à partir de vidéo (cu1), une autre démo à partir d'un jeu d'images (cu2) ?
// - (2) Une démo qui gère les deux
//
// cu1 : nécessite boutons suivants :
// b1: détection des coins (ou automatique ?)
// b2: calibration à partir des paires déjà trouvées
//
StereoCalLiveDemo::StereoCalLiveDemo()
{
props.id = "stereo-cal-live";
props.input_min = 2;
props.input_max = 2;
}
int StereoCalLiveDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
unsigned int bw = input.model.get_attribute_as_int("bw"),
bh = input.model.get_attribute_as_int("bh");
output.nout = 2;
std::vector<cv::Point2f> coins[2];
auto scal = StereoCalDemo::get_instance();
for(auto i = 0u; i < 2; i++)
scal->lookup_corners(input.images[i],
output.images[i],
input.model,
coins[i]);
if((coins[0].size() == bw * bh) && (coins[1].size() == bw * bh))
{
pairs.push_back(coins[0]);
pairs.push_back(coins[1]);
infos("Nouvelle paires ajoutée (%d au total).", pairs.size() / 2);
}
return 0;
}
//////////////////////////////////////////////////////////
/// STEREO CALIBRATION DEMO ////////
//////////////////////////////////////////////////////////
StereoCalDemo::StereoCalDemo()
{
instance = this;
props.id = "stereo-cal";
props.input_min = 2;
props.input_max = -1; // indefinite number of pairs
stereo_cal.valide = false;
}
int StereoCalDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
stereo_cal.valide = false;
output.images[0] = input.images[0];
cv::Size dim_img = input.images[0].size();
if(dim_img != input.images[1].size())
{
avertissement("%s: images de dim différentes.");
output.errmsg = "Les 2 images / vidéo doivent être de même résolution.";
return -1;
}
// Nombre de coins (x,y)
unsigned int bw = input.model.get_attribute_as_int("bw"),
bh = input.model.get_attribute_as_int("bh");
cv::Size dim_damier(bw,bh);
// Coordonnées 3D des coins du damier, dans le repère lié au damier (e.g. Z = 0)
std::vector<std::vector<cv::Point3f>> points_obj;
// Coordonnées 2D des coins du damier, dans les deux images
std::vector<std::vector<cv::Point2f>> points_img[2];
// Pour l'instant, on ne gère qu'une seule paire d'image
unsigned int npaires = input.images.size() / 2;
// Largeur d'un carré du damier (unité physique arbitraire)
// Ici, 2 cm
float largeur_carre = input.model.get_attribute_as_float("taille");
infos("Calibration stéréo...");
points_obj.resize(npaires);
points_img[0].resize(npaires);
points_img[1].resize(npaires);
output.nout = 2 * npaires;
for(auto i = 0u; i < 2 * npaires; i++)
output.names[i] = "Image " + utils::str::int2str(i);
trace_verbeuse(" 1. Recherche des coins...");
for(auto p = 0u; p < npaires; p++)
{
for(auto k = 0; k < 2; k++)
{
if(lookup_corners(input.images[2*p+k], output.images[2*p+k], input.model, points_img[k][p]))
{
avertissement("Paire %d, image %d: coins non trouvés.", p, k);
return -1;
}
}
}
trace_verbeuse(" 2. Calibration...");
// Calcul des coordonnées 3D
for(auto j = 0; j < dim_damier.height; j++ )
for(auto k = 0; k < dim_damier.width; k++ )
points_obj[0].push_back(cv::Point3f(k * largeur_carre, j * largeur_carre, 0));
for(auto j = 1u; j < npaires; j++)
points_obj[j] = points_obj[0];
// Initialisation des matrices de caméra (identité)
for(auto i = 0u; i < 2; i++)
stereo_cal.matrices_cameras[i] = Mat::eye(3, 3, CV_64F);
float rms = cv::stereoCalibrate(points_obj, points_img[0], points_img[1],
stereo_cal.matrices_cameras[0], stereo_cal.dcoefs[0],
stereo_cal.matrices_cameras[1], stereo_cal.dcoefs[1],
dim_img,
stereo_cal.R, stereo_cal.T, stereo_cal.E, stereo_cal.F,
CV_CALIB_FIX_ASPECT_RATIO |
CV_CALIB_ZERO_TANGENT_DIST |
//CV_CALIB_FIX_FOCAL_LENGTH |
CV_CALIB_SAME_FOCAL_LENGTH |
CV_CALIB_RATIONAL_MODEL |
CV_CALIB_FIX_K3 | CV_CALIB_FIX_K4 | CV_CALIB_FIX_K5);
trace_verbeuse("Erreur RMS calibration: %.3f.", (float) rms);
cv::stereoRectify(stereo_cal.matrices_cameras[0], stereo_cal.dcoefs[0],
stereo_cal.matrices_cameras[1], stereo_cal.dcoefs[1],
dim_img, stereo_cal.R, stereo_cal.T,
stereo_cal.rectif_R[0], stereo_cal.rectif_R[1],
stereo_cal.rectif_P[0], stereo_cal.rectif_P[1],
stereo_cal.Q,
CALIB_ZERO_DISPARITY,
1 // 0 : Seulement les pixels valides sont visibles,
// 1 : tous les pixels (y compris noirs) sont visibles
);
// Calcul des LUT pour la rectification de caméra
for(auto k = 0u; k < 2; k++)
cv::initUndistortRectifyMap(
stereo_cal.matrices_cameras[k], stereo_cal.dcoefs[k],
stereo_cal.rectif_R[k], stereo_cal.rectif_P[k],
dim_img, CV_32FC1, //CV_16SC2,
stereo_cal.rmap[k][0], stereo_cal.rmap[k][1]);
// A FAIRE:
// - Vérifier qualité de la calibration
stereo_cal.valide = true;
return 0;
}
RectificationDemo::RectificationDemo()
{
props.id = "rectif";
props.input_min = 2;
props.input_max = 2;
}
static void rectification(const cv::Mat &I0, const cv::Mat &I1,
cv::Mat &O0, cv::Mat &O1)
{
cv::remap(I0, O0,
stereo_cal.rmap[0][0],
stereo_cal.rmap[0][1],
CV_INTER_LINEAR);
cv::remap(I1, O1,
stereo_cal.rmap[1][0],
stereo_cal.rmap[1][1],
CV_INTER_LINEAR);
}
int RectificationDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
output.nout = 2;
output.names[0] = "Image 1";
output.names[1] = "Image 2";
if(!stereo_cal.valide)
{
output.errmsg = utils::langue.get_item("pas-de-cal-stereo");
return -1;
}
for(auto i = 0u; i < 2; i++)
rectification(input.images[0], input.images[1],
output.images[0], output.images[1]);
return 0;
}
//////////////////////////////////////////////////////////
/// DEMO LIGNES EPIPOLAIRES ////////
//////////////////////////////////////////////////////////
EpiDemo::EpiDemo()
{
props.id = "epi";
props.input_min = 2;
props.input_max = 2;
}
void EpiDemo::raz()
{
points[0].clear();
points[1].clear();
}
void EpiDemo::on_mouse(int x, int y, int evt, int wnd)
{
trace_verbeuse("epi demo souris %d, %d.", x, y);
Point2f pt(x,y);
points[wnd].push_back(pt);
OCVDemoItemRefresh e;
CProvider<OCVDemoItemRefresh>::dispatch(e);
}
int EpiDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
// L'utilisateur choisi des points sur l'image 1
// On calcule les épilignes correspondantes sur l'image 2
if(!stereo_cal.valide)
{
output.errmsg = utils::langue.get_item("pas-de-cal-stereo");
return -1;
}
output.nout = 2;
output.images[0] = input.images[0].clone();
output.images[1] = input.images[1].clone();
for(auto k = 0u; k < 2; k++)
{
auto npts = points[k].size();
if(npts == 0)
continue;
//Mat F = stereo_cal.F;
std::vector<cv::Vec3f> epilignes;
cv::computeCorrespondEpilines(cv::Mat(points[k]), 1 + k, stereo_cal.F, epilignes);
int sx = input.images[k].cols;
cv::RNG rng(0);
for(auto i = 0u; i < npts; i++)
{
cv::Scalar color(rng(256),rng(256),rng(256));
cv::line(output.images[1-k],
cv::Point(0, -epilignes[i][2]/epilignes[i][1]),
cv::Point(sx,-(epilignes[i][2]+epilignes[i][0]*sx)/epilignes[i][1]),
color);
cv::circle(output.images[k], points[k][i], 3, color, -1, CV_AA);
}
}
return 0;
}
//////////////////////////////////////////////////////////
/// DISPARITY MAP DEMO ////////
//////////////////////////////////////////////////////////
DispMapDemo::DispMapDemo()
{
props.id = "disp-map";
props.input_min = 2;
props.input_max = 2;
}
int DispMapDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
if(input.images.size() != 2)
{
output.errmsg = "Disparity map demo: needs 2 input images.";
return -1;
}
cv::Mat I[2];
I[0] = input.images[0].clone();
I[1] = input.images[1].clone();
if(input.model.get_attribute_as_boolean("rectifie"))
{
if(!stereo_cal.valide)
{
output.errmsg = utils::langue.get_item("pas-de-cal-stereo");
return -1;
}
for(auto i = 0u; i < 2; i++)
rectification(I[0], I[1], I[0], I[1]);
}
Ptr<StereoMatcher> matcher;
int sel = input.model.get_attribute_as_int("sel");
if(sel == 0)
{
auto sb = StereoBM::create();
// Parameters below from Opencv/samples/stereo_match.cpp
sb->setPreFilterCap(31);
int bsize = input.model.get_attribute_as_int("bm/taille-bloc");
if((bsize & 1) == 0)
bsize++;
sb->setBlockSize(bsize);
sb->setMinDisparity(0);
sb->setNumDisparities(((I[0].cols/8) + 15) & -16);
sb->setTextureThreshold(input.model.get_attribute_as_int("bm/seuil-texture"));
sb->setUniquenessRatio(input.model.get_attribute_as_int("bm/ratio-unicite"));
sb->setSpeckleWindowSize(input.model.get_attribute_as_int("bm/speckles-fen"));
sb->setSpeckleRange(input.model.get_attribute_as_int("bm/speckles-intervalle"));
sb->setDisp12MaxDiff(input.model.get_attribute_as_int("bm/disp-max-diff"));
matcher = sb;
// StereoBM ne supporte que des images en niveaux de gris
cvtColor(I[0], I[0], CV_BGR2GRAY);
cvtColor(I[1], I[1], CV_BGR2GRAY);
}
else if(sel == 1)
{
// int minDisparity, int numDisparities, int blockSize,
matcher = StereoSGBM::create(0, 16 * 100, 7);
}
Mat disp, disp8, dispf;
matcher->compute(I[0], I[1], disp);
// ==> 3 = CV_16S
trace_verbeuse("disp orig depth = %d, nchn = %d, size = %d * %d.", disp.depth(), disp.channels(), disp.rows, disp.cols);
// !!!! disp.convertTo(dispf, CV_32F, 1. / 16);
disp.convertTo(dispf, CV_32F, 1.);
trace_verbeuse("dispf depth = %d, nchn = %d, size = %d * %d.", dispf.depth(), dispf.channels(), dispf.rows, dispf.cols);
dispf = dispf * (1.0 / 16);
/*{
double minv, maxv;
cv::minMaxLoc(dispf, &minv, &maxv);
infos("Min dispf(z) = %lf, max dispf(z) = %lf.", minv, maxv);
cv::minMaxLoc(disp, &minv, &maxv);
infos("Min disp(z) = %lf, max disp(z) = %lf.", minv, maxv);
for(auto ii = 0u; ii < 100; ii++)
{
std::cout << "disp: " << disp.at<short>(ii,ii) << std::endl;
std::cout << "dispf:" << dispf.at<float>(ii,ii) << std::endl;
}
}*/
normalize(disp, disp8, 0, 255, CV_MINMAX, CV_8U);
output.images[0] = disp8;
output.names[0] = utils::langue.get_item("disp-map");
if(input.model.get_attribute_as_boolean("calc-prof"))
{
cv::Mat im3d(disp.size(), CV_32FC3);
cv::reprojectImageTo3D(dispf, im3d, stereo_cal.Q, true);
int pairs[2] = {2, 0}; // 2 -> 0
cv::Mat z(im3d.size(), CV_32F);
printf("im3d: %d * %d: im3d[..] = ", im3d.cols, im3d.rows);//%f, %f, %f.",
//);//, im3d.at<Vec3f>(50,50)[0],
// , im3d.at<Vec3f>(50,50)[0], , im3d.at<Vec3f>(50,50)[0]);
std::cout << im3d.at<Vec3f>(50,50) << std::endl;
std::cout << im3d.at<Vec3f>(51,50) << std::endl;
std::cout << im3d.at<Vec3f>(100,50) << std::endl;
cv::mixChannels(&im3d, 1, &z, 1, pairs, 1);
/*double minv, maxv;
cv::minMaxLoc(z, &minv, &maxv);
infos("Min(z) = %lf, max(z) = %lf.", minv, maxv);*/
float zmax = input.model.get_attribute_as_float("zmax");
auto mask = z > zmax;
z.setTo(Scalar(zmax), mask);
z = zmax - z;
cv::Mat z8;
normalize(z, z8, 0, 255, CV_MINMAX, CV_8U);
output.images[0] = z;
output.names[0] = utils::langue.get_item("prof");
}
return 0;
}
//////////////////////////////////////////////////////////
/// CAMERA CALIBRATION DEMO ////////
//////////////////////////////////////////////////////////
CamCalDemo::CamCalDemo()
{
props.id = "cam-cal";
output.nout = 3;
output.names[0] = "Detection des coins";
output.names[1] = "Distortion corrigee";
}
int CamCalDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat Ig;
int sel = input.model.get_attribute_as_int("sel");
int bw = input.model.get_attribute_as_int("bw");
int bh = input.model.get_attribute_as_int("bh");
Size board_size(bw,bh);
std::vector<std::vector<Point2f>> imagePoints;
std::vector<Point2f> pointbuf;
cvtColor(input.images[0], Ig, CV_BGR2GRAY);
output.images[2] = cv::Mat(/*Ig.size()*/cv::Size(480,640), CV_8UC3);
output.images[1] = output.images[2];
bool trouve;
if(sel == 0)
{
trouve = cv::findChessboardCorners(Ig, board_size, pointbuf,
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE);
// improve the found corners' coordinate accuracy
if(trouve)
cv::cornerSubPix(Ig, pointbuf, Size(11,11),
Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.1 ));
}
else if(sel == 1)
trouve = cv::findCirclesGrid(Ig, board_size, pointbuf );
else
trouve = cv::findCirclesGrid(Ig, board_size, pointbuf, CALIB_CB_ASYMMETRIC_GRID );
//cvtColor(I, O[0], CV_GRAY2BGR);
Mat Ior = input.images[0].clone();
output.images[0] = Ior.clone();
if(trouve)
cv::drawChessboardCorners(output.images[0], board_size, Mat(pointbuf), trouve);
trace_majeure("Trouvé %d coins (found = %d).",
pointbuf.size(), (int) trouve);
if(trouve)
{
Mat distCoeffs;
Mat cameraMatrix;
cameraMatrix = Mat::eye(3, 3, CV_64F);
//if( flags & CALIB_FIX_ASPECT_RATIO )
// cameraMatrix.at<double>(0,0) = aspectRatio;
distCoeffs = Mat::zeros(8, 1, CV_64F);
float square_size = 1;
std::vector<std::vector<Point3f> > objectPoints(1);
std::vector<Point3f> &corners = objectPoints[0];
if(sel <= 1)
{
for( int i = 0; i < board_size.height; i++ )
for( int j = 0; j < board_size.width; j++ )
corners.push_back(Point3f(float(j*square_size),
float(i*square_size), 0));
}
else
{
for( int i = 0; i < board_size.height; i++ )
for( int j = 0; j < board_size.width; j++ )
corners.push_back(Point3f(float((2*j + i % 2)*square_size),
float(i*square_size), 0));
}
imagePoints.push_back(pointbuf);
objectPoints.resize(imagePoints.size(),objectPoints[0]);
std::vector<Mat> rvecs, tvecs;
// Fonction obsoléte ?
double rms = cv::calibrateCamera(objectPoints,
imagePoints, Ior.size(),
cameraMatrix, distCoeffs, rvecs, tvecs,
CALIB_FIX_K4 | CALIB_FIX_K5);
infos("RMS error reported by calibrateCamera: %g\n", rms);
cv::undistort(Ior, output.images[1], cameraMatrix, distCoeffs);
Size sz = Ior.size();
sz.height = sz.width = max(sz.width, sz.height);
sz.height = sz.width = max(sz.width, 500);
output.images[2] = cv::Mat::zeros(sz, CV_8UC3);
double fovx, fovy, focal, ar;
Point2d ppoint;
cv::calibrationMatrixValues(cameraMatrix, Ior.size(), 1, 1, fovx, fovy, focal, ppoint, ar);
MatText mt(output.images[2]);
std::stringstream str;
mt.print("Camera matrix:\n");
str << cameraMatrix << "\n";
mt.print("Focal : %.2f, %.2f, %.2f\n", (float) fovx, (float) fovy, (float) focal);
mt.print("Point principal: %.2f, %.2f\n", (float) ppoint.x, (float) ppoint.y);
mt.print(str.str());
/*Mat tmp = output.images[2].clone();
cv::namedWindow("essai", CV_WINDOW_NORMAL);
cv::imshow("essai", tmp);
cv::waitKey();*/
//bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
//totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
// rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
}
return 0;
}
DemoLocalisation3D::DemoLocalisation3D()
{
props.id = "suivi-balle-3d";
props.input_min = 2;
props.input_max = 2;
}
int DemoLocalisation3D::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
if(!stereo_cal.valide)
{
output.errmsg = utils::langue.get_item("pas-de-cal-stereo");
return -1;
}
Point balle_loc[2];
output.nout = 3;
for(auto k = 0u; k < 2; k++)
{
Mat &I = input.images[k];
Mat tsv, masque;
cvtColor(I, tsv, CV_BGR2HSV);
inRange(tsv, Scalar(18, 100, 128),
Scalar(30, 255, 255), masque);
Mat dst;
cv::distanceTransform(masque, dst, CV_DIST_L2, 3);
cv::minMaxLoc(dst, nullptr, nullptr, nullptr, &balle_loc[k]);
infos("Balle loc[%d]: %d, %d.", balle_loc[k].x, balle_loc[k].y);
Mat O = input.images[k].clone();
// Position de la balle détectée
cv::line(O, balle_loc[0] - Point(5,0), balle_loc[0] + Point(5,0),
Scalar(0,0,255), 1);
cv::line(O, balle_loc[0] - Point(0,5), balle_loc[0] + Point(0,5),
Scalar(0,0,255), 1);
output.images[k] = O;
}
//Mat O = input.images[0].clone();
//p1(1) = Point2f(balle_loc[1].x,balle_loc[1].y);
// Calcul de la position en 3D
cv::Point2f loc_rectifiee[2];
for(auto k = 0u; k < 2; k++)
{
Mat_<Point2f> p1(1,1), p2(1,1);
p1(0) = Point2f(balle_loc[0].x,balle_loc[0].y);
cv::undistortPoints(p1,
p2,
stereo_cal.matrices_cameras[k],
stereo_cal.dcoefs[k],
stereo_cal.rectif_R[k],
stereo_cal.rectif_P[k]);
loc_rectifiee[k] = p2(0);
}
// 2D vers 3D
float y_dist = loc_rectifiee[0].y - loc_rectifiee[1].y;
float x_dist = loc_rectifiee[0].x - loc_rectifiee[1].x;
infos("X dist = %.2f, Y dist = %.2f.", x_dist, y_dist);
cv::Point3f p0, p1;
p0.x = loc_rectifiee[0].x;
p0.y = loc_rectifiee[0].y;
p0.z = x_dist;
//p0[3] = 0;
Mat_<Point3f> mp0(1,1), mp1(1,1);
mp0(0) = p0;
cv::perspectiveTransform(mp0, mp1, stereo_cal.Q); // ????
p1 = mp1(0);
infos("Coordonnées 3D = %.2f, %.2f, %.2f.", p1.x, p1.y, p1.z);
/*Mat O;
cv::remap(input.images[0], O,
stereo_cal.rmap[0][0],
stereo_cal.rmap[0][1],
CV_INTER_LINEAR);*/
Mat O = input.images[0];
// Juste un test : reprojection du point 3d vers l'image 0
// ==> On devrait avoir à peu près les coordonnées du point détecté.
Mat_<Point2f> mp2; // Coordonnées dans l'image 0
cv::projectPoints(mp1,
stereo_cal.R, stereo_cal.T,
stereo_cal.matrices_cameras[0],
stereo_cal.dcoefs[0],
mp2);
infos("Balle reprojetee sur img0 : %.2f, %.2f.", mp2(0).x, mp2(0).y);
output.images[2] = O;
return 0;
}
| 23,897
|
C++
|
.cc
| 683
| 29.718887
| 122
| 0.599199
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,013
|
filtrage.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/filtrage.cc
|
/** @file filtrage.cc
* @brief Filtrage
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/filtrage.hpp"
#include <random>
DemoFiltreGabor::DemoFiltreGabor()
{
props.id = "gabor";
}
int DemoFiltreGabor::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int taille_noyau = input.model.get_attribute_as_int("taille-noyau");
float sigma = input.model.get_attribute_as_float("sigma");
float theta = input.model.get_attribute_as_float("theta");
float lambda = input.model.get_attribute_as_float("lambda");
float gamma = input.model.get_attribute_as_float("gamma");
float psi = input.model.get_attribute_as_float("psi");
if((taille_noyau & 1) == 0)
taille_noyau++;
cv::Mat K = cv::getGaborKernel(cv::Size(taille_noyau, taille_noyau), sigma, theta, lambda, gamma, psi);
cv::Mat tmp;
cv::cvtColor(input.images[0], tmp, CV_BGR2GRAY);
cv::filter2D(tmp, output.images[0], -1, K);
return 0;
}
DemoRedim::DemoRedim()
{
props.id = "redim";
}
int DemoRedim::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
auto tp = input.model.get_attribute_as_int("type");
auto qt = input.model.get_attribute_as_int("qt");
auto algo = input.model.get_attribute_as_int("algo");
cv::Mat I = input.images[0];
cv::Mat O = I.clone();
cv::Size osize = I.size();
if(tp == 0)
{
for(auto i = 0; i < qt; i++)
osize *= 2;
}
else
{
for(auto i = 0; i < qt; i++)
osize /= 2;
}
if(algo == 0) // pyrdown
{
for(auto i = 0; i < qt; i++)
{
if(tp == 0) // Agrandissement
cv::pyrUp(O, O);
else
cv::pyrDown(O, O);
}
}
else
{
cv::resize(O, O, osize);
}
output.images[0] = O;
return 0;
}
DemoFiltrage::DemoFiltrage()
{
props.id = "filtrage";
}
int DemoFiltrage::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
DemoFiltrageConfig config;
auto model = input.model;
config.type_filtre = (DemoFiltrageConfig::filtre_t) model.get_attribute_as_int("sel");
config.bruit_blanc_actif = model.get_attribute_as_boolean("gaussian");
config.poivre_et_sel_actif = model.get_attribute_as_boolean("sp");
config.sigma_bb = model.get_attribute_as_float("sigma");
config.sigma_ps = model.get_attribute_as_float("sigma2");
config.p_ps = model.get_attribute_as_float("p");
config.ma.taille_noyau = model.get_attribute_as_int("ma/taille-noyau");
config.gaussien.taille_noyau = model.get_attribute_as_int("gaussian/taille-noyau");
if((config.gaussien.taille_noyau % 2) == 0)
{
config.gaussien.taille_noyau++;
model.set_attribute("gaussian/taille-noyau", config.gaussien.taille_noyau);
}
config.gaussien.sigma = model.get_attribute_as_float("gaussian/sigma");
config.median.taille_noyau = model.get_attribute_as_int("median/taille-noyau");
if((config.median.taille_noyau % 2) == 0)
{
config.median.taille_noyau++;
model.set_attribute("median/taille-noyau", config.median.taille_noyau);
}
config.bilateral.taille_noyau = model.get_attribute_as_int("bilateral/taille-noyau");
config.bilateral.sigma_couleur = model.get_attribute_as_float("bilateral/sigma-color");
config.bilateral.sigma_espace = model.get_attribute_as_float("bilateral/sigma-space");
return proceed(config, input.images[0], output);
}
int DemoFiltrage::proceed(const DemoFiltrageConfig &conf, cv::Mat &I, OCVDemoItemOutput &output)
{
cv::Mat Ib, If;
I.convertTo(I, CV_32F, 1.0); // intervalle de sortie = 0..255
Ib = I.clone();
uint32_t n = I.cols * I.rows;
float *ptr = Ib.ptr<float>();
std::default_random_engine generator;
std::normal_distribution<float> distri1(0, conf.sigma_bb);
std::normal_distribution<float> distri2(0, conf.sigma_ps);
// bruit blanc gaussien
if(conf.bruit_blanc_actif)
{
for(uint32_t i = 0; i < n * 3; i++)
ptr[i] += distri1(generator);
}
if(conf.poivre_et_sel_actif)
{
std::uniform_real_distribution<float> distri3(0,1.0);
for(uint32_t i = 0; i < n * 3; i++)
{
// bruit poivre et sel
float f = distri3(generator);
if(f < conf.p_ps)
ptr[i] += distri2(generator);
}
}
I.convertTo(I, CV_8UC3, 1.0); // intervalle de sortie = 0..255
Ib.convertTo(Ib, CV_8UC3, 1.0); // intervalle de sortie = 0..255
If.convertTo(If, CV_8UC3, 1.0); // intervalle de sortie = 0..255
if(conf.type_filtre == DemoFiltrageConfig::FILTRE_MA)
cv::blur(Ib, If, cv::Size(conf.ma.taille_noyau,conf.ma.taille_noyau));
else if(conf.type_filtre == DemoFiltrageConfig::FILTRE_GAUSSIEN)
cv::GaussianBlur(Ib, If, cv::Size(conf.gaussien.taille_noyau,conf.gaussien.taille_noyau), conf.gaussien.sigma);
else if(conf.type_filtre == DemoFiltrageConfig::FILTRE_MEDIAN)
cv::medianBlur(Ib, If, conf.median.taille_noyau);
else if(conf.type_filtre == DemoFiltrageConfig::FILTRE_BILATERAL)
cv::bilateralFilter(Ib, If, conf.bilateral.taille_noyau, conf.bilateral.sigma_couleur, conf.bilateral.sigma_espace);
output.nout = 2;
output.images[0] = Ib;
output.images[1] = If;
output.names[0] = "Noisy image";
output.names[1] = "Filtered image";
return 0;
}
| 5,919
|
C++
|
.cc
| 155
| 34.470968
| 120
| 0.696276
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,014
|
seuillage.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/seuillage.cc
|
/** @file seuillage.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/seuillage.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/photo/photo.hpp"
InpaintDemo::InpaintDemo()
{
props.id = "inpaint";
props.requiert_masque = true;
}
int InpaintDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
output.nout = 2;
auto I = input.images[0];
output.images[0] = I.clone();
if(input.mask.data != nullptr)
cv::inpaint(I, input.mask, output.images[1], 3, CV_INPAINT_TELEA);
else
{
infos("Le masque n'est pas défini.");
output.images[1] = I.clone();
}
return 0;
}
Seuillage::Seuillage()
{
props.id = "seuillage";
}
int Seuillage::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int sel = input.model.get_attribute_as_int("sel");
auto I = input.images[0];
Mat Ig;
cvtColor(I, Ig, CV_BGR2GRAY);
// Fixe
if(sel == 0)
{
int seuil = input.model.get_attribute_as_int("seuillage-fixe/seuil");
threshold(Ig, output.images[0], seuil, 255, THRESH_BINARY_INV);
}
// Otsu
else if(sel == 1)
{
threshold(Ig, output.images[0], 0 /* non utilisé */,
255, THRESH_BINARY_INV | THRESH_OTSU);
}
// Adaptatif
else if(sel == 2)
{
int taille_bloc = input.model.get_attribute_as_int("seuillage-adaptatif/taille-bloc");
int seuil = input.model.get_attribute_as_int("seuillage-adaptatif/seuil");
if((taille_bloc & 1) == 0)
taille_bloc++;
cv::adaptiveThreshold(Ig, output.images[0], 255,
ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV,
taille_bloc, seuil);
// ou ADAPTIVE_THRESH_MEAN_C
}
return 0;
}
DTransDemo::DTransDemo()
{
props.id = "dtrans";
}
int DTransDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
Mat Ig, tmp;
cvtColor(input.images[0], Ig, CV_BGR2GRAY);
threshold(Ig, output.images[0], 0 /* non utilisé */,
255, THRESH_BINARY_INV | THRESH_OTSU);
infos("dtrans...");
cv::distanceTransform(output.images[0], tmp, CV_DIST_L2, 3);
infos("ok.");
normalize(tmp, output.images[0], 0, 255, NORM_MINMAX, CV_8UC1);
return 0;
}
| 2,979
|
C++
|
.cc
| 90
| 29.366667
| 90
| 0.697139
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,015
|
reco-demo.cc
|
tsdconseil_opencv-demonstrator/ocvdemo/src/demo-items/reco-demo.cc
|
/** @file reco-demo.cc
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#include "demo-items/reco-demo.hpp"
#ifdef USE_CONTRIB
#include "opencv2/face.hpp"
#endif
#include "opencv2/stitching.hpp"
#include "opencv2/calib3d/calib3d.hpp"
MatchDemo::MatchDemo()
{
props.id = "corner-match";
props.input_min = 2;
props.input_max = 2;
lock = false;
}
int MatchDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
//if(!lock)
{
lock = true;
imgs = input.images;
/*if(imgs[0].size() != imgs[1].size())
{
avertissement("imgs[0].size() != imgs[1].size(): %d*%d, %d*%d",
imgs[0].cols, imgs[0].rows,
imgs[1].cols, imgs[1].rows);
output.nout = 0;
return 0;
}*/
output.nout = 1;
Ptr<cv::Feature2D> detecteur;
int sel = input.model.get_attribute_as_int("sel");
if(sel == 0)
detecteur = cv::ORB::create(input.model.get_attribute_as_int("npts")); // OCV 3.0
else
detecteur = cv::BRISK::create();
std::vector<cv::KeyPoint> kpts[2];
Mat desc[2];
// OCV 3.0
detecteur->detectAndCompute(imgs[0], Mat(), kpts[0], desc[0]);
detecteur->detectAndCompute(imgs[1], Mat(), kpts[1], desc[1]);
if((kpts[0].size() == 0) || (kpts[1].size() == 0))
{
output.nout = 1;
output.images[0] = input.images[0].clone();
return 0;
}
bool cross_check = input.model.get_attribute_as_boolean("cross-check");
cv::BFMatcher matcher(NORM_HAMMING, cross_check);
std::vector<std::vector<DMatch>> matches;
matcher.knnMatch(desc[0], desc[1], matches, 2);
std::vector<DMatch> good_matches;
auto SEUIL_RATIO = input.model.get_attribute_as_float("seuil-ratio");
//# define SEUIL_RATIO .5f
//0.65f
for(auto &match: matches)
{
// Si moins de 2 voisins, on ignore
if(match.size() >= 2)
{
float ratio = match[0].distance / match[1].distance;
if(ratio < SEUIL_RATIO)
good_matches.push_back(match[0]);
}
}
# if 0
double max_dist = 0; double min_dist = 100;
//-- Quick calculation of max and min distances between keypoints
for( int i = 0; i < matches.size(); i++ )
{
double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
printf("-- Max dist : %f \n", max_dist );
printf("-- Min dist : %f \n", min_dist );
//-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
std::vector<DMatch> good_matches;
int seuil = model.get_attribute_as_float("seuil");
for(int i = 0; i < matches.size(); i++)
{
if(matches[i].distance < seuil/**min_dist*/)
good_matches.push_back(matches[i]);
}
# endif
output.images[0] = Mat::zeros(Size(640*2,480*2), CV_8UC3);
if(good_matches.size() > 0)
cv::drawMatches(imgs[0], kpts[0], imgs[1], kpts[1], good_matches, output.images[0]);
infos("draw match ok: %d assoc, %d ok.",
matches.size(), good_matches.size());
# if 0
if(good_matches.size() > 8)
{
//-- Localize the object
std::vector<Point2f> obj;
std::vector<Point2f> scene;
for(unsigned int i = 0u; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( kpts[0][ good_matches[i].queryIdx ].pt );
scene.push_back( kpts[1][ good_matches[i].trainIdx ].pt );
}
Mat H = findHomography(obj, scene, CV_RANSAC);
//-- Get the corners from the image_1 ( the object to be "detected" )
std::vector<Point2f> obj_corners(4);
obj_corners[0] = cvPoint(0,0);
obj_corners[1] = cvPoint(imgs[0].cols, 0 );
obj_corners[2] = cvPoint(imgs[0].cols, imgs[0].rows );
obj_corners[3] = cvPoint( 0, imgs[0].rows );
std::vector<Point2f> scene_corners(4);
cv::perspectiveTransform(obj_corners, scene_corners, H);
Point2f dec(imgs[0].cols, 0);
#if 0
//-- Draw lines between the corners (the mapped object in the scene - image_2 )
line(I, scene_corners[0] + dec,
scene_corners[1] + dec,
Scalar(0, 255, 0), 4 );
line(I, scene_corners[1] + dec,
scene_corners[2] + dec,
Scalar( 0, 255, 0), 4 );
line(I, scene_corners[2] + dec,
scene_corners[3] + dec,
Scalar( 0, 255, 0), 4 );
line(I, scene_corners[3] + dec,
scene_corners[0] + dec,
Scalar( 0, 255, 0), 4 );
# endif
}
# endif
output.names[0] = "Correspondances";
lock = false;
}
return 0;
}
// Panorama:
// http://study.marearts.com/2013/11/opencv-stitching-example-stitcher-class.html
// http://ramsrigoutham.com/2012/11/22/panorama-image-stitching-in-opencv/
//
PanoDemo::PanoDemo()
{
props.id = "pano";
lock = false;
props.input_max = -1;
}
int PanoDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
if(!lock)
{
lock = true;
Stitcher stitcher = Stitcher::createDefault();
Mat pano;
auto t0 = getTickCount();
auto status = stitcher.stitch(input.images, pano);
t0 = getTickCount() - t0;
output.images[0] = pano;
// output.vrai_sortie = pano; // to deprecate
output.names[0] = "Panorama";
trace_verbeuse("%.2lf sec\n", t0 / getTickFrequency());
if (status != Stitcher::OK)
{
avertissement("échec pano.");
return -1;
}
lock = false;
}
return 0;
}
ScoreShiTomasi::ScoreShiTomasi()
{
props.id = "score-harris";
}
int ScoreShiTomasi::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
cv::Mat I, O;
cv::cvtColor(input.images[0], I, CV_BGR2GRAY);
I.convertTo(I, CV_32F);
int sel = input.model.get_attribute_as_int("sel");
int tbloc = input.model.get_attribute_as_int("tbloc");
int ksize = input.model.get_attribute_as_int("ksize");
float k = input.model.get_attribute_as_float("k");
if((ksize & 1) == 0)
ksize++;
O = Mat::zeros(I.size(), CV_32F);
if(sel == 0)
cv::cornerHarris(I, O, tbloc, ksize, k);
else
cv::cornerMinEigenVal(I, O, tbloc, ksize);
cv::normalize(O, O, 0, 255, cv::NORM_MINMAX);
O.convertTo(O, CV_8U);
output.images[0] = O;
return 0;
}
CornerDemo::CornerDemo()
{
props.id = "corner-det";
}
int CornerDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
int sel = input.model.get_attribute_as_int("sel");
int max_pts = input.model.get_attribute_as_int("max-pts");
Ptr<FeatureDetector> detector;
// Shi-Tomasi
if(sel == 0)
{
detector = GFTTDetector::create(max_pts, 0.01, 10, 3, false);
}
// Harris
else if(sel == 1)
{
detector = GFTTDetector::create(max_pts, 0.01, 10, 3, true);
}
// FAST
else if(sel == 2)
{
detector = FastFeatureDetector::create();
}
// SURF
else if(sel == 3)
{
detector = ORB::create(max_pts);
}
Mat gris;
//GoodFeaturesToTrackDetector harris_detector(1000, 0.01, 10, 3, true );
std::vector<KeyPoint> keypoints;
cvtColor(input.images[0], gris, CV_BGR2GRAY);
infos("detection...");
detector->detect(gris, keypoints);
//if(keypoints.size() > max_pts)
//keypoints.resize(max_pts);
output.images[0] = input.images[0].clone();
infos("drawK");
drawKeypoints(input.images[0], keypoints, output.images[0], Scalar(0, 0, 255));
infos("ok");
return 0;
}
VisageDemo::VisageDemo(): rng(12345)
{
String face_cascade_name = "./data/cascades/haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "./data/cascades/haarcascade_eye_tree_eyeglasses.xml";
props.id = "casc-visage";
//-- 1. Load the cascades
if(!face_cascade.load(face_cascade_name))
{
erreur("--(!)Error loading\n");
return;
}
if(!eyes_cascade.load(eyes_cascade_name))
{
erreur("--(!)Error loading\n");
return;
}
output.names[0] = " ";
}
int VisageDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
std::vector<Rect> faces;
Mat frame_gray;
auto I = input.images[0];
cvtColor(I, frame_gray, CV_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
output.images[0] = I.clone();
int minsizex = input.model.get_attribute_as_int("minsizex");
int minsizey = input.model.get_attribute_as_int("minsizey");
//int maxsizex = model.get_attribute_as_int("maxsizex");
//int maxsizey = model.get_attribute_as_int("maxsizey");
//-- Detect faces
trace_verbeuse("Détection visages...");
face_cascade.detectMultiScale(frame_gray, faces,
1.1, // scale factor
2, // min neighbors
0 | CV_HAAR_SCALE_IMAGE,
Size(minsizex,minsizey), // Minimum size
Size()); // Maximum size
infos("Détecté %d visages.", faces.size());
for(size_t i = 0; i < faces.size(); i++ )
{
Point center( faces[i].x + faces[i].width * 0.5, faces[i].y + faces[i].height * 0.5 );
cv::rectangle(output.images[0], Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height), Scalar(0,255,0), 3);
Mat faceROI = frame_gray(faces[i]);
std::vector<Rect> eyes;
//-- In each face, detect eyes
trace_verbeuse("Détection yeux...");
eyes_cascade.detectMultiScale(faceROI, eyes, 1.05, 2,
CV_HAAR_SCALE_IMAGE);//, Size(5, 5) );
trace_verbeuse("%d trouvés.\n", eyes.size());
for(size_t j = 0; j < eyes.size(); j++)
{
Point center( faces[i].x + eyes[j].x + eyes[j].width * 0.5, faces[i].y + eyes[j].y + eyes[j].height * 0.5 );
int radius = cvRound( (eyes[j].width + eyes[j].height) * 0.25 );
circle(output.images[0], center, radius, Scalar( 255, 0, 0 ), 4, CV_AA, 0);
}
}
return 0;
}
CascGenDemo::CascGenDemo(std::string id): rng(12345)
{
output.names[0] = " ";
cascade_ok = false;
props.id = id;
if(id == "casc-yeux")
cnames.push_back("./data/cascades/haarcascade_eye_tree_eyeglasses.xml");
else if(id == "casc-sil")
{
cnames.push_back("./data/cascades/haarcascade_fullbody.xml");
// Cascade HOG plus supportée à partir d'OpenCV 3.0
//cnames.push_back("./data/cascades/hogcascade_pedestrians.xml");
}
else if(id == "casc-profile")
{
cnames.push_back("./data/cascades/haarcascade_profileface.xml");
cnames.push_back("./data/cascades/lbpcascade_profileface.xml");
}
else if(id == "casc-visage")
{
cnames.push_back("./data/cascades/haarcascade_frontalface_alt.xml");
cnames.push_back("./data/cascades/lbpcascade_frontalface.xml");
}
else if(id == "casc-plate")
cnames.push_back("./data/cascades/haarcascade_russian_plate_number.xml");
else
{
avertissement("Cascade inconnue: %s.", id.c_str());
return;
}
// I do not know if this is correct but setting nout to 1 seems to do the right thing.
//output.nout = 0;
output.nout = 1;
unsigned int i = 0;
for(auto cname: cnames)
{
try
{
if(!cascade[i++].load(cname))
{
avertissement("Erreur chargement cascade: %s.", cname.c_str());
return;
}
}
catch(...)
{
avertissement("Exception loading cascade");
return;
}
}
cascade_ok = true;
}
int CascGenDemo::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
if(!cascade_ok)
return -1;
auto I = input.images[0];
std::vector<Rect> rdi;
Mat frame_gray;
cvtColor(I, frame_gray, CV_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
int sel = 0;
if(input.model.has_attribute("sel"))
sel = input.model.get_attribute_as_int("sel");
if(sel >= (int) cnames.size())
sel = 0;
int minsizex = input.model.get_attribute_as_int("minsizex");
int minsizey = input.model.get_attribute_as_int("minsizey");
//-- Detect faces
cascade[sel].detectMultiScale(frame_gray, rdi,
1.1, /* facteur d'échelle */
2, /* min voisins ? */
CV_HAAR_SCALE_IMAGE, /* ? */
Size(minsizex,minsizey),
Size(/*maxsizex,maxsizey*/));
output.images[0] = I.clone();
infos("Détecté %d objets.", rdi.size());
for(size_t i = 0; i < rdi.size(); i++ )
{
Point center( rdi[i].x + rdi[i].width * 0.5, rdi[i].y + rdi[i].height * 0.5 );
cv::rectangle(output.images[0], rdi[i],
Scalar(0,255,0), 3);
}
return 0;
}
DemoHog::DemoHog()
{
props.id = "hog";
}
int DemoHog::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
//HOGDescriptor::getDefaultPeopleDetector();
HOGDescriptor hog;
std::vector<float> ders;
std::vector<Point>locs;
cv::Mat img;
cvtColor(input.images[0], img, CV_BGR2GRAY);
infos("img.size = %d * %d.", img.cols, img.rows);
hog.nbins = input.model.get_attribute_as_int("nbins");
hog.nlevels = 64;
hog.signedGradient = true;
hog.derivAperture = 0;
hog.winSigma = -1;
hog.histogramNormType = 0;
hog.L2HysThreshold = 0.2;
hog.gammaCorrection = false;
uint16_t dim_cellule = input.model.get_attribute_as_int("dim-cellule");
uint16_t dim_bloc = input.model.get_attribute_as_int("dim-bloc");
hog.cellSize = Size(dim_cellule,dim_cellule);
hog.winSize = Size(dim_bloc*dim_cellule,dim_bloc*dim_cellule);
hog.blockStride = Size(dim_bloc*dim_cellule,dim_bloc*dim_cellule);
hog.blockSize = Size(dim_bloc*dim_cellule,dim_bloc*dim_cellule);
hog.compute(img, ders);
// Théoriquement, 512 * 512 / (16 * 16) = 1024 cellules
// Chaque cellule = 16 bins => 16 k elements
infos("ders.size = %d.", ders.size());
// Dessin HOG
uint16_t sx = img.cols, sy = img.rows;
uint16_t ncellsx = sx / dim_cellule, ncellsy = sy / dim_cellule;
uint16_t res = 16;
Mat O = Mat::zeros(Size(ncellsx * res, ncellsy * res), CV_32F);
Mat tmp = Mat::zeros(Size(res,res), CV_32F);
for(auto b = 0; b < hog.nbins; b++)
{
Mat masque2 = Mat::zeros(Size(res, res), CV_32F);
Point p1(res/2,res/2), p2;
float angle = (b * 2 * 3.1415926) / hog.nbins;
p2.x = res/2 + 2 * res * cos(angle);
p2.y = res/2 + 2 * res * sin(angle);
cv::line(masque2, p1, p2, Scalar(1), 1, CV_AA);
p2.x = res/2 - 2 * res * cos(angle);
p2.y = res/2 - 2 * res * sin(angle);
cv::line(masque2, p1, p2, Scalar(1), 1, CV_AA);
tmp = tmp + masque2;
}
for(auto y = 0; y < ncellsy; y++)
{
for(auto x = 0; x < ncellsx; x++)
{
Mat masque = Mat::zeros(Size(res, res), CV_32F);
for(auto b = 0; b < hog.nbins; b++)
{
float val = ders.at(y * ncellsx * hog.nbins + x * hog.nbins + b);
Mat masque2 = Mat::zeros(Size(res, res), CV_32F);
Point p1(res/2,res/2), p2;
float angle = (b * 2 * 3.1415926) / hog.nbins;
p2.x = res/2 + 2 * res * cos(angle);
p2.y = res/2 + 2 * res * sin(angle);
cv::line(masque2, p1, p2, Scalar(val), 1, CV_AA);
p2.x = res/2 - 2 * res * cos(angle);
p2.y = res/2 - 2 * res * sin(angle);
cv::line(masque2, p1, p2, Scalar(val), 1, CV_AA);
masque = masque + masque2;
}
masque = masque / tmp;
Mat rdi(O, Rect(x * res, y * res, res, res));
masque.copyTo(rdi);
}
}
cv::normalize(O, O, 0, 255, NORM_MINMAX);
O.convertTo(O, CV_8U);
cvtColor(O, O, CV_GRAY2BGR);
output.images[0] = O;
output.nout = 1;
if(input.model.get_attribute_as_boolean("detecte-personnes"))
{
auto img = O.clone();
auto coefs = HOGDescriptor::getDefaultPeopleDetector();
hog.setSVMDetector(coefs);
std::vector<cv::Rect> locs;
hog.detectMultiScale(img, locs);//, double hit_thres, Size winStride,
// Size padding, double scale, double fthreshold, false);
for(auto &r: locs)
cv::rectangle(img, r, Scalar(0,0,255), 1, CV_AA);
output.nout = 2;
output.images[1] = img;
}
return 0;
}
DemoFaceRecognizer::DemoFaceRecognizer()
{
props.id = "face-recognizer";
props.input_min = 0;
props.input_max = 0;
}
int DemoFaceRecognizer::proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output)
{
# ifdef USE_CONTRIB
uint16_t sx = 0, sy = 0;
unsigned int nclasses = 40;
unsigned int nex = 10;
output.nout = 0;
std::vector<cv::Mat> images[2];
std::vector<int> labels[2];
for(auto i = 0u; i < nclasses; i++)
{
for(auto j = 0u; j < nex; j++)
{
char buf[50];
sprintf(buf, "/img/att_faces/s%d/%d.pgm", i + 1, j + 1);
auto chemin = utils::get_fixed_data_path() + buf;
auto img = cv::imread(chemin, CV_LOAD_IMAGE_GRAYSCALE);
if(img.data == nullptr)
{
output.errmsg = "Image non trouvée : " + chemin;
return -1;
}
images[j / (nex / 2)].push_back(img);
labels[j / (nex / 2)].push_back(i);
sx = img.cols;
sy = img.rows;
}
}
trace_verbeuse("Sx = %d, sy = %d.", sx, sy);
int algo = input.model.get_attribute_as_int("algo");
if(algo <= 2)
{
unsigned int ncompos = 0;
Ptr<cv::face::FaceRecognizer> model;
if(algo == 0)
{
ncompos = input.model.get_attribute_as_int("eigenface/numcompo");
model = cv::face::createEigenFaceRecognizer(ncompos);
}
else if(algo == 1)
{
ncompos = input.model.get_attribute_as_int("fisherface/numcompo");
model = cv::face::createFisherFaceRecognizer(ncompos);
}
else if(algo == 2)
{
model = cv::face::createLBPHFaceRecognizer();//radius, neighbors, gx, gy);
}
model->train(images[0], labels[0]);
uint32_t ntests = images[1].size();
int nfaux = 0;
for(auto i = 0u; i < ntests; i++)
{
int label;
double confiance;
model->predict(images[1][i], label, confiance);
if(label != labels[1][i])
nfaux++;
}
float taux = ((float) (ntests - nfaux)) / ntests;
infos("Ntests = %d, nfaux = %d, taux de réussite = %.2f %%.", ntests, nfaux, taux * 100);
output.nout = 0;
if(algo <= 1)
{
cv::face::BasicFaceRecognizer *model2 = (cv::face::BasicFaceRecognizer *) model.get();
Mat ev = model2->getEigenVectors();
infos("Eigen vectors = %d * %d.", ev.cols, ev.rows);
// 80 * 10304 = numcompos * (nbdims total)
output.nout = ev.cols;//ncompos;
if(ncompos > DEMO_MAX_IMG_OUT)
output.nout = DEMO_MAX_IMG_OUT;
for(auto i = 0; i < output.nout; i++)
{
cv::Mat mat = ev.col(i).t();
mat = mat.reshape(1, sy);
//trace_verbeuse("nv taille = %d * %d.", mat.cols, mat.rows);
mat.convertTo(mat, CV_32F);
cv::normalize(mat, mat, 0, 1.0, NORM_MINMAX);
mat.convertTo(mat, CV_8U, 255);
output.images[i] = mat;
}
}
}
else
{
output.errmsg = "Algorithme non supporté.";
return -1;
}
# else
output.nout = 0;
# endif
return 0;
}
| 19,775
|
C++
|
.cc
| 585
| 28.437607
| 153
| 0.608483
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,016
|
modele.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/modele.hpp
|
/** @file modele.hpp
* @brief Gestion d'un mod�le de donn�es arborescent
* avec repr�sentation RAM, XML, ou ROM compress�.
*
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J.A. **/
#ifndef MODELE_HPP
#define MODELE_HPP
#include "mxml.hpp"
#include "slots.hpp"
#include "bytearray.hpp"
#include "cutil.hpp"
#include <vector>
#include <string>
#include <map>
#include <stdint.h>
#include "journal.hpp"
namespace utils
{
/** @brief Generic data representation */
namespace model
{
class FileSchema;
class NodeSchema;
class Attribute;
class Node;
class NodePatron;
class RamNode;
/** @brief Item of a path */
class XPathItem
{
public:
XPathItem();
XPathItem(const std::string &name, int instance = -1);
XPathItem(const std::string &name,
const std::string &att_name,
const std::string &att_value);
virtual ~XPathItem();
/** Node type */
std::string name;
/** Optionnal instance number (-1 if unspecified) */
int instance;
/** Optionnal attribute value ("" if unspecified) */
std::string att_name, att_value;
};
/** @brief An XPath defines a path from a root Node to a sub node or attribute
* XPath can be built from a std::string with the following format:
* - xpath to an attribute: "subname/subname/attname"
* - xpath to a sub-node: "subname"
*
* Supported tokens:
* ".." -> parent node
* "." -> current node
* "" -> root node
*
* */
class XPath
{
public:
XPath();
XPath(const XPathItem &xpi);
XPath(const std::string &s);
XPath(const char *s);
XPath(const XPath &xp);
XPath(const XPath &root, const std::string &leaf, int instance = 0);
virtual ~XPath();
void clear();
int from_string(const std::string &s);
void operator =(const XPath &xp);
bool operator ==(const XPath &xp) const;
XPath operator+(const XPath &xp) const;
std::string to_string() const;
const char *c_str() const;
bool is_valid() const;
XPathItem root() const;
bool has_child() const;
int length() const;
XPath child() const;
XPath add_parent(XPathItem item) const;
XPathItem &operator[](const unsigned int i);
const XPathItem &operator[](const unsigned int i) const;
XPath remove_last() const;
void add(const XPathItem &xpi);
std::string get_last() const;
XPath get_first() const;
static XPath null;
operator std::string const () const {return to_string();}
private:
std::string full_string;
bool valid;
std::vector<XPathItem> items;
};
/** @brief A change occurred in the source node.
* May be:
* - An attribute change
* - A node added or removed */
class ChangeEvent
{
public:
typedef enum
{
/** @brief Individual attribute change */
ATTRIBUTE_CHANGED = 0,
/** @brief New child added */
CHILD_ADDED = 1,
/** @brief Child removed */
CHILD_REMOVED = 2,
/** @brief Command executed --> deprecated, to remove */
COMMAND_EXECUTED = 3,
/** @brief A group of changes (one change or more) has occurred simultaneously
* inside the node. */
GROUP_CHANGE = 4
} type_t;
type_t type;
/** Path to the element at the origin of the event */
XPath path;
std::string to_string() const;
ChangeEvent();
// DEPRECATED : to remove
static ChangeEvent create_att_changed(Attribute *source);
// DEPRECATED : to remove
static ChangeEvent create_child_removed(std::string type, uint32_t instance);
// DEPRECATED : to remove
static ChangeEvent create_child_added(std::string type, uint32_t instance);
// DEPRECATED : to remove
static ChangeEvent create_command_exec(Node *source, std::string name);
};
/** @brief List of the different attribute types */
typedef enum attribute_type_enum
{
/** @brief Integer */
TYPE_INT = 0,
/** @brief String of characters */
TYPE_STRING = 1,
/** @brief Boolean */
TYPE_BOOLEAN = 2,
/** @brief Floating point (single or double precision) */
TYPE_FLOAT = 3,
/** @brief 24 bits RGB color */
TYPE_COLOR = 4,
/** @brief Date / time */
TYPE_DATE = 5,
/** @brief Folder path */
TYPE_FOLDER = 6,
/** @brief File path */
TYPE_FILE = 7,
/** @brief Serial port selection */
TYPE_SERIAL = 8,
/** @brief Large array of unformatted data */
TYPE_BLOB = 9
} attribute_type_t;
/** @brief Item of an enumeration */
class Enumeration
{
public:
Enumeration();
Enumeration(const Enumeration &e);
void operator =(const Enumeration &e);
~Enumeration();
/** Name to display for this value */
Localized name;
/** Value */
std::string value;
/** Optionnal schema (can be nullptr) */
NodeSchema *schema;
/** Optionnal schema name */
std::string schema_str;
};
/** @brief Schema of an attribute */
class AttributeSchema
{
public:
friend class NodeSchema;
AttributeSchema();
AttributeSchema(const Node &e);
AttributeSchema(const MXml &mx);
AttributeSchema(const AttributeSchema &c);
~AttributeSchema();
void operator =(const AttributeSchema &c);
std::string type2string() const;
std::string to_string() const;
std::string get_default_value() const;
std::string get_ihm_value(std::string val) const;
void serialize(ByteArray &ba) const;
int unserialize(ByteArray &ba);
bool is_valid(std::string s);
bool is_valid(const ByteArray &ba) const;
void get_valid_chars(std::vector<std::string> &cars);
void make_default_default_value(ByteArray &res) const;
/** Name, translations and descriptions of this attribute */
Localized name;
/** Attribute type */
attribute_type_t type;
/** Size, in bytes, for int and float (TYPE_INT or TYPE_FLOAT) */
int size;
/** For integers only */
bool is_signed;
/** For integers only */
bool is_bytes;
/** For integers only */
bool is_hexa;
/** Is it an IP address (for strings only) */
bool is_ip;
/** Is it some formatted long text (for strings only) */
bool formatted_text;
bool is_error;
/** Optionnal unit specification, e.g. Hz, second, etc. */
std::string unit;
/** Possible extensions, for TYPE_FILE only */
std::string extension;
/** This specify the condition of validity of the attribute */
std::string requirement;
///////////////////////////////////////////////
/// DEFAULT MMI BEHAVIOUR
///////////////////////////////////////////////
/** Is the attribute hidden? */
bool is_hidden;
/** Is this attribute writable? */
bool is_read_only;
/** Is this attribute a measure? */
bool is_instrument;
/** Must this attribute be saved? */
bool is_volatile;
/** Nombre de digits à afficher */
int digits;
bool has_unit() const {return (unit.size() > 0);}
long int min;
long int max;
bool has_min, has_max;
long int get_min();
long int get_max();
bool has_constraints() const;
std::string regular_exp;
std::vector<std::string> constraints;
std::vector<Enumeration> enumerations;
ByteArray default_value;
/** ? */
bool is_unique;
unsigned short id;
bool has_description() const {return (name.has_description());}
bool has_description_fr() const {return (name.has_description());}
bool fixed_size() const;
int get_int (const ByteArray &ba) const;
bool get_boolean(const ByteArray &ba) const;
float get_float (const ByteArray &ba) const;
std::string get_string (const ByteArray &ba) const;
int serialize(ByteArray &ba, int value) const;
int serialize(ByteArray &ba, bool value) const;
int serialize(ByteArray &ba, float value) const;
int serialize(ByteArray &ba, const std::string &value) const;
private:
static journal::Logable log;
};
/** @brief Schema for a container of a list of nodes */
class SubSchema
{
public:
SubSchema();
void operator =(const SubSchema &ss);
std::string to_string() const;
/** Minimum and maximum number of nodes (-1 = unspecified) */
int min, max;
/** Name, translations and descriptions */
Localized name;
/** Pointer to the schema of the children nodes. */
NodeSchema *ptr;
/** Name of the schema of the children node */
std::string child_str;
int default_count;
/** Default key for indexing */
std::string default_key;
///////////////////////////////////////////////
/// DEFAULT MMI BEHAVIOUR
///////////////////////////////////////////////
/** Display as tabular ? */
bool display_tab;
/** Display as tree */
bool display_tree;
/** Unfold by default in tree view ? */
bool display_unfold;
bool is_hidden;
/** Is managed by a choice */
bool is_exclusive;
/** The user cannot add / remove items from this table */
bool readonly;
bool show_header;
/** List of attributes to display into the table (if display_tab) */
std::vector<std::string> resume;
inline bool has_max() const {return (max > 0);}
inline bool has_min() const {return (min > 0);}
};
/** @brief Schema of the reference to another node */
class RefSchema
{
public:
RefSchema();
Localized name;
NodeSchema *ptr;
std::string path;
std::string child_str;
bool is_hidden;
};
/** @brief Schema describing a command */
class CommandSchema
{
public:
CommandSchema(const MXml &mx);
CommandSchema(const Node &model);
CommandSchema(const CommandSchema &cs);
void operator =(const CommandSchema &cs);
Localized name;
/** @brief Input parameters */
refptr<NodeSchema> input;
/** @brief Output parameters */
refptr<NodeSchema> output;
private:
};
/** @brief Schema describing a node */
class NodeSchema
{
public:
friend class RamNode;
friend class FileSchema;
NodeSchema(){}
NodeSchema(const Node &elmt, FileSchema *root = nullptr, const std::string &name = "");
NodeSchema(const MXml &mx);
NodeSchema(const NodeSchema &c);
~NodeSchema();
void operator =(const NodeSchema &c);
std::string to_string();
bool has_description() const {return name.has_description();}
#ifndef TESTCLI
bool has_key_attribute() const;
AttributeSchema *get_key_attribute();
#endif
void do_inherits();
bool has_editable_props();
bool has_reference(std::string name) const;
RefSchema *get_reference(std::string name);
bool has_icon() const {return (icon_path.size() > 0);}
void update_size_info();
bool has_attribute(std::string name) const;
refptr<AttributeSchema> get_attribute(std::string name);
bool has_child(std::string name) const;
std::string get_localized() const;
NodeSchema *get_sub(std::string name);
void serialize(ByteArray &ba);
int unserialize(ByteArray &ba);
CommandSchema *get_command(std::string name);
/** @brief Import specifications from a XML node */
void from_xml(const MXml &mx);
SubSchema *get_child(std::string name);
/** Return the index of the child */
int get_sub_index(const std::string &name) const;
void add_attribute(refptr<AttributeSchema> schema);
void add_sub_node(const SubSchema &schema);
void ajoute_enfant(NodeSchema *enfant, unsigned int min = 1, unsigned int max = 1);
/* @returns true if nothing is configurable in this schema */
bool is_empty() const;
bool fixed_size;
bool attributes_fixed_size;
bool children_fixed_size;
/** Sub-node specifications */
std::deque<SubSchema> children;
/** Attributes list */
std::deque<refptr<AttributeSchema> > attributes;
std::deque<CommandSchema> commands;
std::deque<RefSchema> references;
NodeSchema *inheritance;
std::string icon_path;
/** Name, translations and descriptions */
Localized name;
/** A mapper from the sub id to the sub index */
std::map<std::string, int> mapper;
/** A mapper from the att id to the att index */
std::map<std::string, int> att_mapper;
static journal::Logable log;
private:
// ??
std::string inheritance_name;
};
/** @brief Model schema loaded from a file */
class FileSchema
{
public:
FileSchema();
~FileSchema();
/** @brief Construit un sch�ma � partir d'un fichier xml */
FileSchema(std::string filename);
int from_file(std::string filename);
int from_string(const std::string &s);
int from_xml(const MXml &mx);
void from_element(const Node &e);
/** @param name name of the schema if not specified in the node */
void add_schema(const Node &e, const std::string &name = "");
FileSchema(const FileSchema &c);
void operator =(const FileSchema &c);
NodeSchema *get_schema(std::string name);
NodeSchema *root;
std::string to_string();
/** Check if the schema is complete: returns -1 if not the case, 0 if ok. */
int check_complete();
private:
void from_xml2(const MXml &root);
void from_element2(const Node &e);
void build_references();
std::vector<refptr<NodeSchema> > schemas;
};
/** @brief Attribute value for a node
* TODO: should be private! */
class Attribute: public CProvider<ChangeEvent>
{
public:
friend class Node;
friend class RamNode;
friend class ChangeEvent;
Attribute();
Attribute(refptr<AttributeSchema> schema);
virtual ~Attribute(){}
/** @returns Non-zero value if failed to set the new value */
virtual int set_value(const std::string &s);
void set_value(int i);
void set_value(float f);
void set_value(bool b);
int set_value(const ByteArray &ba);
bool get_boolean() const;
int get_int() const;
float get_float() const;
std::string get_string() const;
void serialize(ByteArray &ba) const;
void unserialize(ByteArray &ba);
void forward_change_event();
refptr<AttributeSchema> schema;
private:
/** Storage place */
ByteArray value;
bool up2date;
bool inhibit_event_dispatch;
Node *node;
NodePatron *parent;
static journal::Logable log;
protected:
virtual void value_changed(){}
};
/** @cond not-documented */
class NodeIterator
{
public:
NodeIterator(NodePatron *parent, int type, int index)
{this->parent = parent; this->type = type; this->index = index;}
bool operator!=(const NodeIterator& x) const
{
return index != x.index;
}
const Node operator*() const;
Node operator++();
private:
int index;
NodePatron *parent;
int type;
};
class ConstNodeIterator
{
public:
ConstNodeIterator(const NodePatron *parent, int type, int index) {this->parent = parent; this->type = type; this->index = index;}
bool operator!=(const ConstNodeIterator& x) const
{
return index != x.index;
}
const Node operator*() const;
const Node operator++();
private:
int index;
const NodePatron *parent;
int type;
};
class NodeList
{
public:
NodeList(NodePatron *parent, int type){this->parent = parent; this->type = type;}
NodeIterator begin() const
{
return NodeIterator(parent, type, 0);
}
NodeIterator end() const;
private:
NodePatron *parent;
int type;
};
class ConstNodeList
{
public:
ConstNodeList(const NodePatron *parent, int type){this->parent = parent; this->type = type;}
ConstNodeIterator begin() const
{
return ConstNodeIterator(parent, type, 0);
}
ConstNodeIterator end() const;
private:
const NodePatron *parent;
int type;
};
/** @endcond */
/** @brief A tree node */
class Node
{
public:
friend class Attribute;
friend class NodeIterator;
friend class ConstNodeIterator;
friend class NodeList;
friend class ConstNodeList;
friend class ChangeEvent;
Node(NodeSchema *schema, const std::string &fichier_source = "");
Node(const Node &e);
Node(Node &e);
/** Copy only the reference */
void operator =(const Node &e);
/** True if points to the same reference */
bool operator ==(const Node &e) const;
/** True if different references */
bool operator !=(const Node &e) const;
bool est_egal(const Node &e) const;
/** Uninitialized or invalid tree node ? */
bool is_nullptr() const;
/** Get parent node */
Node parent() const;
/** Change the order of a child */
Node down(Node child);
/** Change the order of a child */
Node up(Node child);
// GET CHILDREN, TYPE PRECISE
NodeList children(const std::string &type);
ConstNodeList children(const std::string &type) const;
unsigned long get_children_count(const std::string &type) const;
Node get_child_at(const std::string &type, unsigned int i);
const Node get_child_at(const std::string &type, unsigned int i) const;
void copy_from(const Node e);
Node clone() const;
void add_listener(CListener<ChangeEvent> *lst);
void remove_listener(CListener<ChangeEvent> *lst);
/// (1) Gestion des attributs
bool has_attribute(const XPath &path) const;
bool get_attribute_as_boolean(const std::string &name) const;
int get_attribute_as_int(const std::string &name) const;
float get_attribute_as_float(const std::string &name) const;
std::string get_attribute_as_string(const std::string &name) const;
ByteArray get_attribute_as_raw(const std::string &name) const;
int set_attribute(const XPath &path, const std::string &value);
int set_attribute(const XPath &path, int value);
int set_attribute(const XPath &path, bool value);
int set_attribute(const XPath &path, float value);
int set_attribute(const XPath &path, const char *value);
int set_attribute(const XPath &path, const ByteArray &value);
Node add_child(Node nv);
Node add_child(NodeSchema *schema);
Node add_child(const std::string &sub_name);
Node get_child(const XPath &path);
const Node get_child(const XPath &path) const;
void remove_child(Node child);
/** Returns the path to a given child */
int get_path_to(const Node &child, XPath &res);
/// (2) Gestion des enfants
bool has_child(const XPath &path) const;
/** @param root_path If not empty, a path from which all file paths will be stored
* as relative paths.
* If not specified, all file paths are stored as absolute paths. */
std::string to_xml(unsigned int indent = 0,
bool display_default_values = false,
bool display_spaces = true,
bool charset_latin = false,
const std::string root_path = "") const;
std::string to_html(unsigned int level = 0) const;
void serialize(ByteArray &res) const;
void unserialize(ByteArray &source);
static Node create_ram_node();
static Node create_ram_node(NodeSchema *schema);
static Node create_ram_node_from_string(NodeSchema *schema, const std::string &content);
static Node create_ram_node(NodeSchema *schema, std::string filename);
int save(const std::string &filename, bool store_default_values = false);
int load(const std::string &schema_file, const std::string &data_file);
// ????? to deprecate
void load(const std::string &filename);
/** @returns the schema describing the structure of this node */
//virtual
NodeSchema *schema() const;
bool contains(const Node &elt);
void get_children_recursive(const std::string &type, std::deque<Node> &res);
///////////////////////////////////////////////////////////////////
// BELOW ARE DEPRECATED METHODS TO BE REMOVED
///////////////////////////////////////////////////////////////////
/** Prevent any modification of this node and its children
* to be notified to the change listeners.
* The notifications are defered until unlock() is called.
* This enable to group multiple change events into a single one. */
// @deprecated
void lock();
/** Enable notifications to be called */
// @deprecated
void unlock();
// GET CHILDREN, TYPE NON PRECISE
/** @deprecated */
unsigned long get_children_count() const;
Node get_child_at(unsigned int index);
const Node get_child_at(unsigned int index) const;
// REFERENCES
// @deprecated
unsigned int get_reference_count() const;
// @deprecated
void set_reference(const std::string &name, Node e);
// @deprecated
void set_reference(const std::string &name, const XPath &path);
// @deprecated
XPath get_reference_path(const std::string &name);
// @deprecated
const Node get_reference_at(unsigned int i, std::string &name) const;
/* to deprecate ? (ideally mask the Attribute class) */
Attribute *get_attribute(const XPath &path);
/* to deprecate ? (ideally mask the Attribute class) */
const Attribute *get_attribute(const XPath &path) const;
/* to deprecate! */
std::string name() const {return get_attribute_as_string("name");}
/* to deprecate! */
std::string description() const;
/* to deprecate! */
std::string get_identifier(bool disp_type = true, bool bold = false) const;
/* to deprecate! */
std::string get_localized_name() const;
// @deprecated
bool has_reference(const std::string &name) const;
// @deprecated
const Node get_reference(const std::string &name) const;
// @deprecated
std::string text_resume(int indent = 0) const;
// @deprecated
virtual std::string class_name() const;
// @deprecated
virtual std::string type() const;
// ?
bool is_attribute_valid(const std::string &name);
virtual ~Node();
Node();
Localized get_localized() const;
/* To move another place */
std::string format_c_comment(int indent);
void dispatch_event(const ChangeEvent &ce);
/** @returns Full path to this node */
std::string get_fullpath() const;
protected:
void setup_refs();
NodePatron *data;
Node(NodePatron *data);
friend class RamNode;
friend class RomNode;
private:
// Should be private!
void fromXml(const MXml &e, const std::string &root_path = "");
std::string to_xml_atts(unsigned int indent = 0,
bool display_default_values = false,
bool charset_latin = false,
std::string root_path = "") const;
void check_min();
void setup_schema();
void setup_default_subs();
};
/** Drawing graphics from schemas */
class DotTools
{
public:
DotTools();
int export_html_att_table(std::string &res, const Node &schema);
/** @brief Build a graphic representation of the schema using dots */
void build_graphic(Node &schema, const std::string &output_filename);
private:
std::string complete_dot_graph(Node section, int level);
std::string get_name(const Node &e);
std::string get_attribute_type_description(const Node &e);
std::string get_attribute_long_description(const Node &e);
};
class LatexWrapper
{
public:
int export_att_table(std::string &res, const Node &schema);
private:
std::string get_name(const Node &e);
std::string get_attribute_type_description(const Node &e);
std::string get_attribute_long_description(const Node &e);
};
/** Generate a c++ class from a node schema */
class NodeCppWrapper
{
public:
NodeCppWrapper();
int gen_ccp_wrapper(NodeSchema *schema, const std::string &path_c, const std::string &path_h);
/** @brief Generate a class definition. */
std::string gen_class(NodeSchema *schema, int indent = 0);
std::string gen_class_impl(NodeSchema *schema);
private:
std::string gen_attribute_comment(const AttributeSchema &as, int indent);
std::string format_comment(int indent, const Localized &l);
std::string gen_attribute_type(const AttributeSchema &as);
std::string gen_indent(size_t indent);
std::string gen_get_attribute_as(const AttributeSchema &as);
};
}
}
#endif
| 24,341
|
C++
|
.h
| 721
| 30.560333
| 131
| 0.677549
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,017
|
erreurs.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/erreurs.hpp
|
#ifndef ERREURS_H
#define ERREURS_H
#include "modele.hpp"
namespace utils {
struct Erreur
{
unsigned int id;
utils::model::Localized locale;
};
extern int erreurs_charge();
extern int erreur_affiche(unsigned int id);
extern Erreur &erreur_get(unsigned int);
extern void signale_erreur(unsigned int id, ...);
extern void affiche_pile_erreurs();
}
#endif
| 374
|
C++
|
.h
| 16
| 21.0625
| 49
| 0.780059
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,018
|
slots.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/slots.hpp
|
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef SLOTS_H
#define SLOTS_H
#include "hal.hpp"
#include <vector>
#include <deque>
namespace utils
{
template <class Type> class Provider;
template <class Type> class Listener;
template <class Type> class CProvider;
template <class Type> class CListener;
/** @cond not-documented */
template <class B>
class EventFunctor
{
public:
virtual void call( B &b) = 0;
};
#if 0
class VoidEventFunctor
{
public:
virtual void call() = 0;
};
#endif
template <class A, class B>
class SpecificEventFunctor: public EventFunctor<B>
{
public:
SpecificEventFunctor(A *object, void(A::*m_function)( B &b))
{
this->object = object;
this->m_function = m_function;
}
virtual int call( B &b)
{
return (*object.*m_function)(b);
}
private:
int (A::*m_function)( B &);
A *object;
};
#if 0
template <class A>
class SpecificVoidEventFunctor: public VoidEventFunctor
{
public:
SpecificVoidEventFunctor(A *object, void (A::*m_function)())
{
this->object = object;
this->m_function = m_function;
}
virtual void call()
{
(*object.*m_function)();
}
private:
void (A::*m_function)();
A *object;
};
/** @endcond */
#endif
/** Event provider mother class. */
template <class Type>
class Provider
{
friend class Listener<Type>;
public:
void add_listener(Listener<Type> *lst);
void remove_listener(Listener<Type> *lst);
void remove_all_listeners();
void dispatch( Type &evt);
/** Block until all dispatch is done. */
//void wait_dispatch_done();
template<class A>
int add_listener(A *target,
void (A:: *fun)( Type &));
template<class A>
int remove_listener(A *target,
void (A:: *fun)( Type &));
virtual ~Provider<Type>(){remove_all_listeners();}
private:
std::deque<void *> listeners;
std::deque<EventFunctor<Type> *> functors;
};
#if 0
class VoidEventProvider
{
public:
void remove_all_listeners();
void dispatch();
template<class A>
int add_listener(A *target,
void (A:: *fun)());
template<class A>
int remove_listener(A *target,
void (A:: *fun)());
virtual ~VoidEventProvider(){remove_all_listeners();}
private:
std::deque<VoidEventFunctor *> functors;
};
#endif
/** Event listener mother class. */
template <class Type>
class Listener
{
friend class Provider<Type>;
public:
virtual ~Listener() {}
std::string listener_name;
//private:
virtual void on_event( Type &evt) = 0;
};
template <class Type>
void Provider<Type>::add_listener(Listener<Type> *lst)
{
listeners.push_back(lst);
}
template <class Type>
void Provider<Type>::remove_listener(Listener<Type> *lst)
{
std::deque<void *>::iterator it;
for(it = listeners.begin(); it != listeners.end(); it++)
{
void *cur = *it;
if(cur == (void *) lst)
{
listeners.erase(it);
return;
}
}
}
template <class Type>
void Provider<Type>::remove_all_listeners()
{
listeners.clear();
functors.clear();
}
template <class Type>
void Provider<Type>::dispatch( Type &evt)
{
//mutex.lock();
std::vector<void *> copy;
for(unsigned int i = 0; i < listeners.size(); i++)
copy.push_back(listeners[i]);
for(unsigned int i = 0; i < copy.size(); i++)
{
void *cur = copy[i];
Listener<Type> *pt = (Listener<Type> *) cur;
pt->on_event(evt);
}
std::vector<EventFunctor<Type> *> copy2;
for(unsigned int i = 0; i < functors.size(); i++)
copy2.push_back(functors[i]);
for(unsigned int i = 0; i < copy2.size(); i++)
{
EventFunctor<Type> *ef = copy2[i];
ef->call(evt);
}
//mutex.unlock();
}
#if 0
template<class A>
int VoidEventProvider::add_listener(A *target,
void (A:: *fun)())
{
/* TODO: check if not already registered */
VoidEventFunctor *f = new SpecificVoidEventFunctor<A>(target, fun);
functors.push_back(f);
return 0;
}
#endif
template<class Type>
template<class A>
int Provider<Type>::add_listener(A *target,
void (A:: *fun)( Type &))
{
/* TODO: check if not already registered */
SpecificEventFunctor<A,Type> *f = new SpecificEventFunctor<A,Type>(target, fun);
functors.push_back(f);
return 0;
}
#if 0
template<class A>
int VoidEventProvider::remove_listener(A *target,
void (A:: *fun)())
{
return 0;
}
#endif
template<class Type>
template<class A>
int Provider<Type>::remove_listener(A *target,
void (A:: *fun)( Type &))
{
//std::deque<SpecificEventFunctor<A,Type> *>::iterator it;
/*for(it = functors.begin(); it != functors.end(); it++)
{
EventFunctor<Type> *cur = *it;
SpecificEventFunctor<A,Type> *cst = (SpecificEventFunctor<A,Type>) cur;
if((cst->object == target)
&& (cst->m_function == fun))
{
functors.erase(it);
return;
}
}*/
return 0;
}
// ###############################################################################
/** @cond not-documented */
template <class B>
class CEventFunctor
{
public:
virtual void call(const B &b) = 0;
};
template <class A, class B>
class SpecificCEventFunctor: public CEventFunctor<B>
{
public:
SpecificCEventFunctor(A *object, void(A::*m_function)(const B &b))
{
this->object = object;
this->m_function = m_function;
}
virtual void call(const B &b)
{
(*object.*m_function)(b);
}
private:
void (A::*m_function)(const B &);
A *object;
};
/** @endcond */
/** Event provider mother class. */
template <class Type>
class CProvider
{
friend class CListener<Type>;
public:
void add_listener(CListener<Type> *lst);
void remove_listener(CListener<Type> *lst);
void remove_all_listeners();
void dispatch(const Type &evt);
/** Block until all dispatch is done. */
//void wait_dispatch_done();
template<class A>
int add_listener(A *target,
void (A:: *fun)(const Type &));
template<class A>
int remove_listener(A *target,
void (A:: *fun)(const Type &));
virtual ~CProvider<Type>(){remove_all_listeners();}
private:
std::deque<void *> listeners;
std::deque<CEventFunctor<Type> *> functors;
//OSMutex mutex;
};
/** Event listener mother class. */
template <class Type>
class CListener
{
friend class CProvider<Type>;
public:
virtual ~CListener() {}
std::string listener_name;
//private:
virtual void on_event(const Type &evt) = 0;
};
template <class Type>
void CProvider<Type>::add_listener(CListener<Type> *lst)
{
listeners.push_back(lst);
}
template <class Type>
void CProvider<Type>::remove_listener(CListener<Type> *lst)
{
std::deque<void *>::iterator it;
for(it = listeners.begin(); it != listeners.end(); it++)
{
void *cur = *it;
if(cur == (void *) lst)
{
listeners.erase(it);
return;
}
}
}
template <class Type>
void CProvider<Type>::remove_all_listeners()
{
//mutex.lock();
listeners.clear();
functors.clear();
//mutex.unlock();
}
/*template <class Type>
void Provider<Type>::wait_dispatch_done()
{
mutex.lock();
listeners.clear();
functors.clear();
mutex.unlock();
}*/
template <class Type>
void CProvider<Type>::dispatch(const Type &evt)
{
//mutex.lock();
std::vector<void *> copy;
for(unsigned int i = 0; i < listeners.size(); i++)
copy.push_back(listeners[i]);
for(unsigned int i = 0; i < copy.size(); i++)
{
void *cur = copy[i];
CListener<Type> *pt = (CListener<Type> *) cur;
pt->on_event(evt);
}
std::vector<CEventFunctor<Type> *> copy2;
for(unsigned int i = 0; i < functors.size(); i++)
copy2.push_back(functors[i]);
for(unsigned int i = 0; i < copy2.size(); i++)
{
CEventFunctor<Type> *ef = copy2[i];
ef->call(evt);
}
//mutex.unlock();
}
template<class Type>
template<class A>
int CProvider<Type>::add_listener(A *target,
void (A:: *fun)(const Type &))
{
/* TODO: check if not already registered */
SpecificCEventFunctor<A,Type> *f = new SpecificCEventFunctor<A,Type>(target, fun);
functors.push_back(f);
return 0;
}
template<class Type>
template<class A>
int CProvider<Type>::remove_listener(A *target,
void (A:: *fun)(const Type &))
{
//std::deque<SpecificEventFunctor<A,Type> *>::iterator it;
/*for(it = functors.begin(); it != functors.end(); it++)
{
EventFunctor<Type> *cur = *it;
SpecificEventFunctor<A,Type> *cst = (SpecificEventFunctor<A,Type>) cur;
if((cst->object == target)
&& (cst->m_function == fun))
{
functors.erase(it);
return;
}
}*/
return 0;
}
}
#endif
| 9,499
|
C++
|
.h
| 377
| 21.411141
| 84
| 0.640252
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.