How to override default signal handler of TextBuffer - gtkmm

I am trying to override the default on_erase signal handler of Gtk::TextView. I derive TextBuffer and override the default handler; but the override is not working. When using cast_static, the RefPtr is valid, but when using cast_dynamic the RefPtr is null.
#include <gtkmm.h>
#include "CTextBuffer.h"
class CMain : public Gtk::Window
{
public:
CMain();
virtual ~CMain();
private:
Gtk::TextView m_textView;
Glib::RefPtr<CTextBuffer> m_refTextBuffer;
};
#include "CMain.h"
CMain::CMain()
{
Glib::RefPtr<Gtk::TextBuffer> refTextBuffer = Gtk::TextBuffer::create();
m_refTextBuffer = Glib::RefPtr<CTextBuffer>::cast_dynamic(refTextBuffer);
m_textView.set_buffer(m_refTextBuffer);
add(m_textView);
show_all();
}
CMain::~CMain()
{}
#include <gtkmm.h>
class CTextBuffer : public Gtk::TextBuffer
{
public:
CTextBuffer();
virtual ~CTextBuffer();
protected:
virtual void on_erase(const TextBuffer::iterator& range_start, const TextBuffer::iterator& range_end);
};
#include "CTextBuffer.h"
CTextBuffer::CTextBuffer() {}
CTextBuffer::~CTextBuffer() {}
void CTextBuffer::on_erase (const TextBuffer::iterator& range_start, const TextBuffer::iterator& range_end)
{
Gtk::TextBuffer::on_erase(range_start, range_end);
}

Simply use a ref to your own type:
CMain::CMain()
{
Glib::RefPtr<CTextBuffer> refTextBuffer{ new CTextBuffer };
m_textView.set_buffer(refTextBuffer);
add(m_textView);
show_all();
}
void CTextBuffer::on_erase (const TextBuffer::iterator& range_start, const TextBuffer::iterator& range_end)
{
std::cout << "Own override was called" << std::endl;
Gtk::TextBuffer::on_erase(range_start, range_end);
}
You find some more information on how to usw own derived widgets here:
https://developer.gnome.org/gtkmm-tutorial/stable/sec-builder-using-derived-widgets.html.en

Related

ANTLR4 C++ listener not calling overriden enterRule methods

I need some help with walking a tree with a listener (using C++). After initiating the tree walk with my listener and using gdb to attach to the process (I built the C++ runtime library with the Debug flag to be able to have the debug info in gdb), I can see it enters ParseTreeWalker::walk(), and if I execute getText() on the ParseTree* parameter I can see it has all the tokens from my input, so far so good. But when walk() calls enterRule():
void ParseTreeWalker::enterRule(ParseTreeListener *listener, ParseTree *r) const {
auto *ctx = downCast<ParserRuleContext*>(r);
listener->enterEveryRule(ctx);
ctx->enterRule(listener);
}
When I try to step in ctx->enterRule(listener) it just goes back to walk(). I've added breakpoints to my listener methods I want to debug but it appears they're not being called. I even added some std::cout statements in them but I don't see them being executed. I also added some std::cout statements to my overriden version of visitTerminal and those are getting printed...
If I inspect the ctx variable inside this method, it does seem to have the right type
_vptr.ParseTree = 0x6e6048 <vtable for MyParser::DocumentContext+16>...
So, I'm very confused, am I missing something obvious that's causing my enter* methods not get executed?
The generated BaseListener looks like this:
#include "antlr4-runtime.h"
#include "MyDCXParserListener.h"
class MyDCXParserBaseListener : public MyDCXParserListener {
public:
virtual void enterDocument(MyDCXParser::DocumentContext * /*ctx*/) override { }
virtual void exitDocument(MyDCXParser::DocumentContext * /*ctx*/) override { }
virtual void enterLine(MyDCXParser::LineContext * /*ctx*/) override { }
virtual void exitLine(MyDCXParser::LineContext * /*ctx*/) override { }
virtual void enterEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }
virtual void exitEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }
virtual void visitTerminal(antlr4::tree::TerminalNode * /*node*/) override { }
virtual void visitErrorNode(antlr4::tree::ErrorNode * /*node*/) override { }
};
The derived class I created looks like this:
.h
#include "antlr4-runtime.h"
#include "MyDCXParser.h"
#include "MyDCXParserBaseListener.h"
#include <iostream>
using namespace std;
class MyDCXListener : public MyDCXParserBaseListener
{
private:
public:
//
MyDCXListener();
//
~MyDCXListener();
// Don't allow copy constructor nor assignment operator
MyDCXListener(const MyDCXListener&) = delete;
MyDCXListener& operator=(const MyDCXListener&) = delete;
//
void enterDocument(MyDCXParser::DocumentContext * /*ctx*/) override;
void exitDocument(MyDCXParser::DocumentContext * /*ctx*/) override {}
void enterLine(MyDCXParser::LineContext * /*ctx*/) override;
void exitLine(MyDCXParser::LineContext * /*ctx*/) override {}
void visitTerminal(antlr4::tree::TerminalNode *node) override { std::cout << "visitTerminal(): '" << node->getText().c_str() << std::endl; }
};
.cpp
#include "MyDCXListener.h"
//
MyDCXListener::MyDCXListener()
{
}
MyDCXListener::~MyDCXListener()
{
}
void MyDCXListener::enterDocument(MyDCXParser::DocumentContext * ctx)
{
std::cout << "MyDCXListener::enterDocument()" << std::endl;
}
void MyDCXListener::enterLine(MyDCXParser::LineContext * ctx)
{
std::cout << "MyDCXListener::enterLine()" << std::endl;
}
I see the "visitTerminal" message but not the ones for enterDocument() nor enterLine()

In C++/CLI what is the easiest way to pass internal variables to delegate?

I am trying to set a delegate that takes a local variable as a parameter. The declaration looks like this:
ref class Main
{
private:
Func<String^>^ _expensiveMethodDelegate;
public:
property Func<String^>^ ExpensiveMethodDelegate
{
Func<String^>^ get() { return this->_expensiveMethodDelegate; }
void set(Func<String^>^ value) { this->_expensiveMethodDelegate = value; }
};
void DoWork()
{
String^ result = this->_expensiveMethodDelegate();
Debug::WriteLine(result);
}
};
In C# the code will look like this:
string parameter = "value";
Main main = new Main();
main.ExpensiveMethodDelegate = () =>
{
Thread.Sleep(1000); // do expensive work
return parameter + "1";
};
main.DoWork();
What is the easiest way of achieving this goal using managed C++ (VS 2015)? Note: I read articles Workaround for not having lambdas that can capture managed variables and Lambda expressions as CLR (.NET) delegates / event handlers in Visual C++ 2010 and still cannot figure out what is the solution.
I tried code like this (using make_delegate from the second article), but it fails to compile:
String^ parameter = L"value";
Main^ main = gcnew Main();
main->ExpensiveMethodDelegate = make_delegate(
[](String^ parameter) -> String^
{
Threading::Thread::Sleep(1000); // do work
return parameter + L"1";
});
main->DoWork();
This is what I came up with:
#pragma once
#include <new>
using namespace std::tr1;
using namespace System;
namespace helper
{
private struct return_type_helper
{
private:
template<class D>
struct dependent_false { enum { value = false }; };
template <class D>
struct illegal_delegate_type
{
static_assert(dependent_false<D>::value, "Delegates with more than 2 parameters, or with parameters of tracking reference types (T%), are not supported.");
};
struct anything
{
template<class T>
operator T() const;
};
public:
template<class D>
static decltype(static_cast<D^>(nullptr)(anything())) dummy(int(*)[2]);
template<class D>
static decltype(static_cast<D^>(nullptr)(anything(), anything())) dummy(int(*)[3]);
};
template<class Func, class Aligner = char, bool Match = (alignment_of<Func>::value == alignment_of<Aligner>::value)>
struct aligner
{
static_assert(Match, "Function object has unsupported alignment");
};
template<class Func, class Aligner>
private struct aligner<Func, Aligner, true>
{
typedef Aligner type;
};
template<class F>
private ref class lambda_wrapper
{
public:
lambda_wrapper(const F& f)
{
pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
new(pf) F(f);
}
~lambda_wrapper()
{
pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
pf->~F();
}
template <class D>
operator D ^ ()
{
D^ d = nullptr;
return gcnew D(this, &lambda_wrapper<F>::invoke<decltype(return_type_helper::dummy<D>(0))>);
}
private:
template<class T>
[System::Runtime::InteropServices::StructLayout(System::Runtime::InteropServices::LayoutKind::Sequential, Size = sizeof(T))]
value struct embedded_storage
{
private:
typename aligner<T>::type dummy;
};
embedded_storage<F> f_storage;
template<class R, class A1>
R invoke(A1 a1)
{
pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
return (*pf)(a1);
}
template<class R, class A1, class A2>
R invoke(A1 a1, A2 a2)
{
pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
return (*pf)(a1, a2);
}
};
template <typename...>
ref class DelegateHelper;
template<class TParam1, class TResult>
ref class DelegateHelper<TParam1, TResult>
{
private:
Func<TParam1, TResult>^ _lambda;
TParam1 _param1;
TResult Execute()
{
return this->_lambda(this->_param1);
}
public:
template<class TLambda>
DelegateHelper(TLambda lambda, TParam1 param1)
{
this->_lambda = gcnew helper::lambda_wrapper<TLambda>(lambda);
this->_param1 = param1;
}
static operator Func<TResult> ^ (DelegateHelper<TParam1, TResult>^ value)
{
return gcnew Func<TResult>(value, &DelegateHelper<TParam1, TResult>::Execute);
}
};
template<class TParam1, class TParam2, class TResult>
ref class DelegateHelper<TParam1, TParam2, TResult>
{
private:
Func<TParam1, TParam2, TResult>^ _lambda;
TParam1 _param1;
TParam2 _param2;
TResult Execute()
{
return this->_lambda(this->_param1, this->_param2);
}
public:
template<class TLambda>
DelegateHelper(TLambda lambda, TParam1 param1, TParam2 param2)
{
this->_lambda = gcnew helper::lambda_wrapper<TLambda>(lambda);
this->_param1 = param1;
this->_param2 = param2;
}
static operator Func<TResult> ^ (DelegateHelper<TParam1, TParam2, TResult>^ value)
{
return gcnew Func<TResult>(value, &DelegateHelper<TParam1, TParam2, TResult>::Execute);
}
};
}
This is how to use it:
String^ parameter1 = L"value1";
String^ parameter2 = L"value2";
Main^ main = gcnew Main();
auto lambda1 = [](String^ parameter) -> String^
{
Threading::Thread::Sleep(1000);
return parameter;
};
main->ExpensiveMethodDelegate = gcnew helper::DelegateHelper<String^, String^>(lambda1, parameter1);
main->DoWork();
auto lambda2 = [](String^ parameter1, String^ parameter2) -> String^
{
Threading::Thread::Sleep(1000);
return parameter1 + parameter2;
};
main->ExpensiveMethodDelegate = gcnew helper::DelegateHelper<String^, String^, String^>(lambda2, parameter1, parameter2);
main->DoWork();
Not sure if it is the most elegant way, but it does the work I was looking for.

How to serialize std::chrono::duration with Boost?

Is it possible to serialize std::chrono::duration or especially std::chrono::milliseconds with boost::serialization?
The following error occurred:
"struct std::chrono::duration >’ has no member named ‘serialize"
I need this for my template-class:
#include <iostream>
#include <chrono>
#include <boost/serialization/serialization.hpp>
template<typename T>
class Field {
public:
// Default Constructor
Field() {}
Field(std::string name, T value) :
mName(name), mValue(value) {}
~Field() {}
const std::string& getName() const {
return mName;
}
T getValue() const {
return mValue;
}
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive& archive, const unsigned int) {
archive & boost::serialization::make_nvp("Name", mName);
archive & boost::serialization::make_nvp("Value", mValue);
}
std::string mName;
T mValue;
};
BOOST_CLASS_IMPLEMENTATION( Field<int>, boost::serialization::object_serializable )
BOOST_CLASS_IMPLEMENTATION( Field<std::chrono::milliseconds>, boost::serialization::object_serializable )
I'm creating the following object:
Field<std::chrono::milliseconds> mSimTime;
Let's say you have:
auto earlier = std::chrono::system_clock::now();
auto now = std::chrono::system_clock::now();
auto aLotOfMilliseconds= std::chrono::duration_cast<std::chrono::milliseconds>(
now - earlier);
// Serialize here int64_t.
then after deserialization, you have:
std::chrono::duration<int64_t, std::milli> duration(aLotOfMilliseconds);

Call c++ code in c# by a cli wrapper

I have a c++ code that needs to be called in c# by a cli wrapper. I am stuck at the operator overloading part.
//this is my code
//Cppclass.h
#ifdef CPP_EXP_EXPORTS
#define CPP_EXP __declspec(dllexport)
#else
#define CPP_EXP __declspec(dllimport)
#endif
class CPP_EXP Cppclass;
CPP_EXP Cppclass operator-(Cppclass const &, Cppclass const &);
class CPP_EXP Cppclass
{
public:
friend CPP_EXP Cppclass operator-(Cppclass const &, Cppclass const &);
};
//this is my managed c++ code.
#include "Cppclass.h"
namespace Wrapper
{
public ref class cppwrapclass
{
public:
static cppwrapclass ^ operator-(cppwrapclass%A,cppwrapclass%B)
{
operator-(A.obj,B.obj);
return gcnew cppwrapclass();
}
private:
Cppclass *obj;
};
}
Its showing an intellisense error and not getting compiled.
You write a wrapper like this:
public ref class cppwrapclass
{
public:
cppwrapclass(Cppclass *obj)
: obj(obj)
{
}
~cppwrapclass()
{
this->!cppwrapclass();
}
!cppwrapclass()
{
if (obj)
{
delete obj;
obj = nullptr;
}
}
static cppwrapclass^ operator-(cppwrapclass% A, cppwrapclass% B)
{
return gcnew cppwrapclass(new Cppclass(*A.obj - *B.obj));
}
private:
Cppclass* obj;
};
A.obj is of type Cppclass*, therefore *A.obj is of type Cppclass, and *A.obj - *B.obj is a temporary Cppclass which needs to be moved to the heap in order to be referenced by the wrapper, hence the copy constructor call: new Cppclass(*A.obj - *B.obj).
The rest is the Dispose pattern and finalizer plumbing code.

how to access variable from one class in another in QT mobility?

I have two classes: first generate position data (latitude and longitude), how I can access this data (variables latitude and longitute) in second class? becouse in second class I get crazy number(
Here are headers and classes:
first header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGeoPositionInfoSource>
#include <QGeoPositionInfo>
#include <QtCore/QPointer>
#include <QGeoSatelliteInfo>
#include <QGeoSatelliteInfoSource>
#include "gpsform.h"
QTM_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
double latitude;
double longitude;
double altitude;
double speed;
public slots:
void positionUpdated(QGeoPositionInfo geoPositionInfo);
private:
Ui::MainWindow *ui;
QPointer<QGeoPositionInfoSource> locationDataSource;
private slots:
void on_pushButton_2_clicked();
void on_pushButton_4_clicked();
void startGPS();
void on_pushButton_clicked();
signals:
void updated();
};
#endif // MAINWINDOW_H
first class
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "quitdiallog.h"
#include <QGeoCoordinate>
#include <QDebug>
#include <QtGui/QMessageBox>
#include <QList>
#include "gpsform.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
setWindowTitle("Мой кОмпаС");
ui->setupUi(this);
startGPS();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::startGPS()
{
// Obtain the location data source if it is not obtained already
if (!locationDataSource)
{
locationDataSource =
QGeoPositionInfoSource::createDefaultSource(this);
if (locationDataSource)
{
// Whenever the location data source signals that the current
// position is updated, the positionUpdated function is called.
QObject::connect(locationDataSource,
SIGNAL(positionUpdated(QGeoPositionInfo)),
this,
SLOT(positionUpdated(QGeoPositionInfo)));
// Start listening for position updates
locationDataSource->setUpdateInterval(100);
locationDataSource->setPreferredPositioningMethods(QGeoPositionInfoSource::SatellitePositioningMethods);
locationDataSource->startUpdates();
} else {
// Not able to obtain the location data source
// TODO: Error handling
}
} else {
// Start listening for position updates
locationDataSource->setUpdateInterval(5000);
locationDataSource->startUpdates();
}
}
void MainWindow::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
//gpsform *gpf=new gpsform;
if (geoPositionInfo.isValid())
{
//locationDataSource->stopUpdates();
QGeoCoordinate geoCoordinate = geoPositionInfo.coordinate();
latitude = geoCoordinate.latitude();
longitude = geoCoordinate.longitude();
altitude=geoCoordinate.altitude();
ui->label->setNum(latitude);
ui->label_2->setNum(longitude);
/*if(QGeoPositionInfo::GroundSpeed)
{
speed=QGeoPositionInfo::GroundSpeed;
ui->label_4->setNum(speed);
}*/
emit updated();
//gpf->latitude=this->latitude;
//gpsform *gpf=new gpsform;
//gpf->show();
//gpf->latitude=latitude;
}
}
void MainWindow::on_pushButton_clicked()
{
/*ui->label_3->setNum(latitude);
qDebug()<<latitude<<" "<<longitude<<" "<<altitude;*/
gpsform *gps=new gpsform;
this->hide();
gps->show();
}
void MainWindow::on_pushButton_4_clicked()
{
QuitDiallog *qi=new QuitDiallog;
this->hide();
qi->show();
}
void MainWindow::on_pushButton_2_clicked()
{
ui->label_3->setNum(latitude);
}
second header
#ifndef GPSFORM_H
#define GPSFORM_H
#include <QWidget>
#include "mainwindow.h"
QTM_USE_NAMESPACE
namespace Ui {
class gpsform;
}
class gpsform : public QWidget
{
Q_OBJECT
public:
explicit gpsform(QWidget *parent = 0);
~gpsform();
double latitude;
private:
Ui::gpsform *ui;
private slots:
void on_pushButton_clicked();
void updatedata();
};
#endif // GPSFORM_H
second class:
#include "gpsform.h"
#include "ui_gpsform.h"
#include "mainwindow.h"
#include <QTimer>
#include <QDebug>
gpsform::gpsform(QWidget *parent) :
QWidget(parent),
ui(new Ui::gpsform)
{
ui->setupUi(this);
/*ui->label->setNum(mw->latitude);*/
/* QTimer * timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(update()));
timer->start(50);*/
/* MainWindow *mw = new MainWindow;
QObject::connect(mw,SIGNAL(updated()),this,SLOT(updatedata()));*/
}
gpsform::~gpsform()
{
delete ui;
}
void gpsform::updatedata()
{
/* MainWindow *mw = new MainWindow;
this->latitude=mw->latitude;
ui->label->setNum(mw->latitude);*/
}
void gpsform::on_pushButton_clicked()
{
MainWindow *mw = new MainWindow;
//latitude=mw->latitude;
qDebug()<<mw->latitude;
ui->label->setNum(latitude);
}
For example I want to see latitude in second class, by pressing button. In future I'll do this by Signal/slot to generate label text every time, the position is updated. But now I'll get crazy number. Help me please
MainWindow *mw = new MainWindow;
//latitude=mw->latitude;
qDebug()<<mw->latitude;
You create a new instance of MainWindow and directly access its latitude member. But was it initialized? I see the only place writing into this member in MainWindow is positionUpdated. Are you sure this method gets invoked before you access mw->latitude? You could easily verify that with another qDebug printout from positionUpdated, or by using the debugger.
To comment on the code style in general - it's not good practice to directly access members of other classes like this. One of the problems (as you've just encountered!) with this approach is that the class has no way to actually control the validity of its member. Even the most basic solution - having an accessor method instead of raw member access could do wonders for you here, because the accessor method could potentially check if the value has been computed (or even compute it lazily).