What Dispatcher should I use for UI operations in a Visual Studio 2010+ extension - dispatcher

Currently I'm aware of the following Dispatcher objects.
If you have a text view, you can use IWpfTextView.VisualElement.Dispatcher.
If your class is constructed by MEF (marked with [Export] and not directly constructed from your own code), then you can use the fact that the MEF part resolution algorithm and construction occurs on the UI thread, allowing the use of Dispatcher.CurrentDispatcher. For example:
[Export(typeof(ISomeInterface))]
public class MyClass : ISomeInterface {
private readonly Dispatcher _dispatcher;
public MyClass() {
_dispatcher = Dispatcher.CurrentDispatcher.
}
}
You can use Application.Current.Dispatcher from any code.
What, if any, is the recommended practice for obtaining a Dispatcher?

Do not take a dependency on MEF composing on UI thread. If it works for you right now, you're just getting lucky. Also MEF is delayed in nature and full of Lazy, so if you happen to realize it on a background thread, the entire subgraph will get realized on background.
I would use #1 or #3 (doesn't matter which, there is only one UI thread dispatcher, doesn't matter how you get to it).

Related

Can I swap QObject child keeping signals and slots connected

Suppose I have class:
class Foo : public QObject{
Q_OBJECT
public:
...
private:
Bar* m_bar;
}
And for whatever reason, I'd like to replace m_bar with a pointer to an object of DerivedBar. The use case I most often find is when I want to replace it with an object of MockBar (using the google mock framework) for unit testing.
Now I know in most cases, I could just extend the constructor to be something like:
Foo(Bar* bar, QObject* parent)
and just set m_bar accordingly.
But the problem I have is when the classes are QWidgets and I'm assembling them via Qt Designer. Imagine Foo and Bar are widgets, and Bar is placed inside of Foo from designer; their connections are also set via designer (ie, stored in the qml file). I've tried something like:
Bar* bar = foo.findChild<Bar*>();
bar = new MockBar(&foo);
(neglecting any memory leaks here, just trying to get functionality) But when I go to set expectations, it does not seem to be connected like the existing one was. Slots aren't called in response to signals. I don't think this is entirely unexpected due to the way connections are made, but I'm wondering if there's a way to get the effect I'm looking for.
(nb: for now, using qt 4.8 and gcc 4.6, which does limit some options for c++
Here's a better answer I've found: The issue for me is ultimately to do with the QWidgets generated from ui files. But since the Ui::FooWidget class is functionally just a pimpl pattern, I can create a pointer to a local copy of one, and modify Foo's constructor to allow me to optionally inject the ui implementation. If Foo is making a direct function call to BarWidget, I can replace that ui's 'barWidget' object with my MockBarWidget, and set expectations and such and perform testing. The previous answer will still satisfy to some degree when the interaction between the two widgets is one of signal/slot connections.
Previous Answer:
Here's one answer I've found so far, but I don't much like it:
Bar* bar = foo.findChild<Bar*>();
bool connectTest = QObject::connect(&foo, SIGNAL(setValue(int)), bar, SLOT(setValue(int)), Qt::UniqueConnection);
ASSERT_FALSE(connectTest);
bar = new MockBar(&foo);
connectTest = QObject::connect(&foo, SIGNAL(setValue(int)), bar, SLOT(setValue(int)), Qt::UniqueConnection);
ASSERT_TRUE(connectTest);
//... rest of test
I could probably wrap the whole thing up in some kind of helper function, and that function may be better with c++11/Qt5 where signals and slots can be method pointers. But I wonder if I'm missing an easier way to do it.
Edit: It turns out this pattern was giving me a false positive, only the first 'connectTest' part of the test was giving a valid test of behaviour. This flaw is more obvious when Foo doesn't emit a signal to bar , but merely calls a method on bar. The mock is not injected through this pattern.

Organization of the QT Code

I am writing an application of middle size. I will have many gui components and many classes. However, it is difficult for me to organize the code, to separate the logic, ... For example, let say that I press one button that creates an object of a class and perform a computation on that object. After exiting the slot function of the button, this local object is destroyed. What if I need it in another function later? Defining everything as a global variable in the header file is not a good thing for me. So I was thinking of a static class that contains somehow pointers to all the objects I will need later. Does anybody has a better idea?
How to manage objects inside an application is always a tricky
question. Qt goes down a very object-oriented route and uses reference
semantics implemented through pointer for nearly everything. To
prevent tedious manual memory management Qt organizes everything into
Object Trees. This
is augmented by Qt own
object model that adds
some dynamic capabilities.
If you want to go down that route, stick to everything Qt provides. It
is much more similar to Java than the usual C++ approach and might be
more comforting for beginners and maybe suits your application
domain. It tightly ties your code to Qt and will make it hard to
separate from it.
One other approach means to simply forgo all Qt stuff and work out the
core logic of your application. Develop it in pure C++ and than have a
thin layer that ties this logic into your Qt application through
signals and slots. In such an approach you would opt to use more
value-semantics.
For your concrete example of creating an algorithm and keeping it
around. The Qt approach:
class MyAlgo : public QObject {
Q_OBJECT
public:
MyAlgo(QObject* o) : QObject(o) { }
virtual compute();
};
// use it in a mainwindow slot
void MainWindow::executeAlgorithm(const QString& name) {
MyAlgo* algo = this->findChild<MyAlgo*>(name);
if(!algo) {
// not found, create
algo = new MyAlgo(this); // make mainwindow the parent of this algo
algo->setName(name); // QObject name property
}
algo->compute();
}

How to execute a method in another thread?

I'm looking for a solution for this problem in C or C++.
edit: To clarify. This is on a linux system. Linux-specific solutions are absolutely fine. Cross-plaform is not a concern.
I have a service that runs in its own thread. This service is a class with several methods, some of which need to run in the own service's thread rather than in the caller's thread.
Currently I'm using wrapper methods that create a structure with input and output parameters, insert the structure on a queue and either return (if a "command" is asynchronous) or wait for its execution (if a "command" is synchronous).
On the thread side, the service wakes, pops a structure from the queue, figures out what to execute and calls the appropriate method.
This implementation works but adding new methods is quite cumbersome: define wrapper, structure with parameters, and handler. I was wondering if there is a more straightforward means of coding this kind of model: a class method that executes on the class's own thread, instead of in the caller's thread.
edit - kind of conclusion:
It seems that there's no de facto way to implement what I asked that doesn't involve extra coding effort.
I'll stick with what I came up with, it ensures type safeness, minimizes locking, allows sync and async calls and the overhead it fairly modest.
On the other hand it requires a bit of extra coding and the dispatch mechanism may become bloated as the number of methods increases. Registering the dispatch methods on construction, or having the wrappers do that work seem to solve the issue, remove a bit of overhead and also remove some code.
My standard reference for this problem is here.
Implementing a Thread-Safe Queue using Condition Variables
As #John noted, this uses Boost.Thread.
I'd be careful about the synchronous case you described here. It's easy to get perf problems if the producer (the sending thread) waits for a result from the consumer (the service thread). What happens if you get 1000 async calls, filling up the queue with a backlog, followed by a sync call from each of your producer threads? Your system will 'play dead' until the queue backlog clears, freeing up those sync callers. Try to decouple them using async only, if you can.
There are several ways to achieve this, depending upon the complexity you want to accept. Complexity of the code is directly proportional to the flexibility desired. Here's a simple one (and quite well used):
Define a classes corresponding to each functionality your server exposes.
Each of these classes implements a function called execute and take a basic structure called input args and output args.
Inside the service register these methods classes at the time of initialization.
Once a request comes to the thread, it will have only two args, Input and Ouput, Which are the base classes for more specialized arguments, required by different method classes.
Then you write you service class as mere delegation which takes the incoming request and passes on to the respective method class based on ID or the name of the method (used during initial registration).
I hope it make sense, a very good example of this approach is in the XmlRpc++ (a c++ implementation of XmlRpc, you can get the source code from sourceforge).
To recap:
struct Input {
virtual ~Input () = 0;
};
struct Ouput {
virtual ~Output () = 0;
};
struct MethodInterface {
virtual int32_t execute (Input* __input, Output* __output) = 0;
};
// Write specialized method classes and taking specialized input, output classes
class MyService {
void registerMethod (std::string __method_name, MethodInterface* __method);
//external i/f
int32_t execute (std::string __method, Input* __input, Output* __output);
};
You will still be using the queue mechanism, but you won't need any wrappers.
IMHO, If you want to decouple method execution and thread context, you should use Active Object Pattern (AOP)
However, you need to use ACE Framework, which supports many OSes, e.g. Windows, Linux, VxWorks
You can find detailed information here
Also, AOP is a combination of Command, Proxy and Observer Patterns, if you know the details of them, you may implement your own AOP. Hope it helps
In addition to using Boost.Thread, I would look at boost::function and boost::bind. That said, it seems fair to have untyped (void) arguments passed to the target methods, and let those methods cast to the correct type (a typical idiom for languages like C#).
Hey now Rajivji, I think you have it upside-down. Complexity of code is inversely proportional to flexibility. The more complex your data structures and algorithms are, the more restrictions you are placing on acceptable inputs and behaviour.
To the OP: your description seems perfectly general and the only solution, although there are different encodings of it. The simplest may be to derive a class from:
struct Xqt { virtual void xqt(){} virtual ~Xqt(){} };
and then have a thread-safe queue of pointers to Xqt. The service thread then just pops the queue to px and calls px->xqt(), and then delete px. The most important derived class is this one:
struct Dxqt : Xqt {
xqt *delegate;
Dxqt(xqt *d) : delegate(d) {}
void xqt() { delegate->xqt(); }
};
because "all problems in Computer Science can be solved by one more level of indirection" and in particular this class doesn't delete the delegate. This is much better than using a flag, for example, to determine if the closure object should be deleted by the server thread.

Is creating a base class for all applications of a particular type good design?

I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a little background.
The application has three major states:
1. Display rasterized scene
2. Display a ray traced version of the same scene
3. Display a hybrid version of the scene
Clearly, I can divide my application into four major parts:
1. A state management system to switch between the above modes.
2. An input system that can receive both keyboard and mouse input.
3. The raster engine used for display.
4. The ray tracing system.
Any application encompassing the above needs to be able to:
1. Create a window.
2. Do all the steps needed to allow rendering in that window.
3. Initialize the input system.
4. Initialize the state manager.
5. Start looping (and rendering!).
I want to be able to change the rendering engine/state manager/input system/ ray tracing system at any time, so long as certain minimum requirements are met. Imho, this requires separating the interface from the implementation. With that in mind, I created the interfaces for the above systems.
At that point, I noticed that the application has a common 'interface' as well. So I thought to abstract it out into an ApplicationBase class with virtual methods. A specific application, such as one which uses OGRE for window creation, rendering etc would derive from this class and implement it.
My first question is - is it a good idea to design like this?
Here is the code for the base class:
#ifndef APPLICATION_H
#define APPLICATION_H
namespace Hybrid
{
//Forward declarations
class StateManager;
class InputSystem;
//Base Class for all my apps using hybrid rendering.
class Application
{
private:
StateManager* state_manager;
InputSystem* input_system;
public:
Application()
{
try
{
//Create the state manager
initialise_state_manager();
//Create the input system
initialise_input_system();
}
catch(...) //Change this later
{
//Throw another exception
}
}
~Application()
{
delete state_manager;
delete input_system;
}
//If one of these fails, it throws an
//exception.
virtual void initialise_state_manager() = 0;
virtual void initialise_input_system() = 0;
virtual void create_window() = 0;
//Other methods.
};
#endif
When I use OGRE, I rely on OGRE to create the window. This requires OGRE to be initialised before the createWindow() function is called in my derived class. Of course, as it is, createWindow is going to be called first! That leaves me with the following options:
1. Leave the base class constructor empty.
2. In the derived class implementation, make initialising OGRE part of the createWindow function.
3. Add an initialize render system pure virtual function to my base class. This runs the risk of forcing a dummy implementation in derived classes which have no use for such a method.
My second question is- what are your recommendations on the choice of one of these strategies for initialising OGRE?
You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additionally, write something like OgreManager self-contained class with initialization (looping etc) methods and event callbacks. Since applications could create and initialize this object at any moment, your second question is solved automatically.
Your design may save a few lines of code for creating new application objects, but the price is maintaining soup-like master object with potentially long inheritance line.
Use interfaces and callbacks.
P.S.: not to mention that calling virtual functions in constructor doesn't mean what you probably expect.
Yes, that is a good design, and it is one that I use myself.
For your second question, I would remove anything from the base constructor that has any possibility of not being applicable to a derived class. If OGRE wants to create the window itself then you need to allow it to do that, and I don't think that it makes sense to initialize OGRE in createWindow (it's misleading).
You could add an initialize render system virtual method, but I think you should just leave that task to the derived class's constructor. Application initialization is always a tricky task, and really, really difficult to abstract. From my experience, it's best not to make any assumptions about what the derived class might want to do, and just let it do the work itself in any way that it wants.
That said, if you can think of something that will absolutely apply to any conceivable derived class then feel free to add that to the base constructor.

Overriding / modifying C++ classes using DLLs

I have a project with a large codebase (>200,000 lines of code) I maintain ("The core").
Currently, this core has a scripting engine that consists of hooks and a script manager class that calls all hooked functions (that registered via DLL) as they occur. To be quite honest I don't know how exactly it works, since the core is mostly undocumented and spans several years and a magnitude of developers (who are, of course, absent). An example of the current scripting engine is:
void OnMapLoad(uint32 MapID)
{
if (MapID == 1234)
{
printf("Map 1234 has been loaded");
}
}
void SetupOnMapLoad(ScriptMgr *mgr)
{
mgr->register_hook(HOOK_ON_MAP_LOAD, (void*)&OnMapLoad);
}
A supplemental file named setup.cpp calls SetupOnMapLoad with the core's ScriptMgr.
This method is not what I'm looking for. To me, the perfect scripting engine would be one that will allow me to override core class methods. I want to be able to create classes that inherit from core classes and extend on them, like so:
// In the core:
class Map
{
uint32 m_mapid;
void Load();
//...
}
// In the script:
class ExtendedMap : Map
{
void Load()
{
if (m_mapid == 1234)
printf("Map 1234 has been loaded");
Map::Load();
}
}
And then I want every instance of Map in both the core and scripts to actually be an instance of ExtendedMap.
Is that possible? How?
The inheritance is possible. I don't see a solution for replacing the instances of Map with instances of ExtendedMap.
Normally, you could do that if you had a factory class or function, that is always used to create a Map object, but this is a matter of existing (or inexistent) design.
The only solution I see is to search in the code for instantiations and try to replace them by hand. This is a risky one, because you might miss some of them, and it might be that some of the instantiations are not in the source code available to you (e.g. in that old DLL).
Later edit
This method overriding also has a side effect in case of using it in a polymorphic way.
Example:
Map* pMyMap = new ExtendedMap;
pMyMap->Load(); // This will call Map::Load, and not ExtendedMap::Load.
This sounds like a textbook case for the "Decorator" design pattern.
Although it's possible, it's quite dangerous: the system should be open for extension (i.e. hooks), but closed for change (i.e. overriding/redefining). When inheriting like that, you can't anticipate the behaviour your client code is going to show. As you see in your example, client code must remember to call the superclass' method, which it won't :)
An option would be to create a non-virtual interface: an abstract base class that has some template methods that call pure virtual functions. These must be defined by subclasses.
If you want no core Map's to be created, the script should give the core a factory to create Map descendants.
If my experience with similar systems is applicable to your situation, there are several hooks registered. So basing a solution on the pattern abstract factory will not really work. Your system is near of the pattern observer, and that's what I'd use. You create one base class with all the possible hooks as virtual members (or several one with related hooks if the hooks are numerous). Instead of registering hooks one by one, you register one object, of a type descendant of the class with the needed override. The object can have state, and replace advantageously the void* user data fields that such callbacks system have commonly.