Qt's state machine as a node graph? - c++

I am trying to figure out how to use a node graph for processing a set of data.
It is for an application that manipulates sound data, much like if you had a bunch of pedals for your guitar.
You have some nodes with predefined procedures connected to each other in a directed graph.
Each takes a turn to process the data, and when one is finished it gives a signal to the next node to do it's thing. The idea is you piece these nodes together using the ui.
I am using Qt for creating the UI, and as such I was looking through it's documentation to see if there was something I could use for the above mentioned problem. And I found the Qt state machine, from what I can read it seems to do what I need, a state is entered, you do some processing, when it is done a finished signal is given, and the next state in the graph is started. Also the fact that you could nest states, giving me the ability to create new nodes by combining existing ones, seems like an attractive idea.
However the state machine was created for changing the attributes of widgets (changing their state) and not for wrapping procedures. For example, a button is pressed and the state machine changes the state of another widget, and e.g. if the button is released the state is swapped back.
So, anyone with more experience, with Qt, the state machine, or processing by node graphs, who could give me a hint whether or not tweaking the state machine to wrap my procedures will work. Or, if there is something else in the Qt library I could use?

I used QStateMachine for online message processing (online in the sense of online algorithm) and it worked fine, there weren't restrictions just because the original idea was to modify widgets.
However, personally I would not use it for your project because a state machine is not exactly what you describe. It might be possible to bend it to your needs but it would certainly be weird. A better solution would be to make a nice polymorphic OO model with your "effects" having a base class and a decoupled graph implementation to connect them. You can use Qt signals to signal finishing the the graph to take the next step. It is also easier to build your custom graph from data than create the states and transitions for the state machine dynamically.

Related

Synchronous single file download - is it the right approach in a GUI Qt application?

I'm developing an updater for my application in Qt, primarily to get to know the framework (I realize there are multiple ready-made solutions available, that's not relevant here). It is a basic GUI application using a QMainWindow subclass for its main window and an MyAppUpdater class to perform the actual program logic.
The update information (version, changelog, files to be downloaded) is stored on my server as an XML file. The first thing the updater should do after it sets up the UI is query that server, get the XML file, parse it and display info to the user. Here's where I have a problem though; coming from a procedural/C background, I'd initiate a synchronous download, set a timeout of maybe 3 seconds, then see what happens - if I manage to download the file correctly, I'll parse it and carry on, otherwise display an error.
However, seeing how inconvenient something like that is to implement in Qt, I've come to believe that its network classes are designed in a different way, with a different approach in mind.
I was thinking about initiating an asynchronous download in, say, InitVersionInfoDownload, and then connecting QNetworkReply's finished signal to a slot called VersionInfoDownloadComplete, or something along these lines. I'd also need a timer somewhere to implement timeout checks - if the slot is not invoked after say 3 seconds, the update should be aborted. However, this approach seems overly complicated and in general inadequate to the situation; I cannot proceed without retrieving this file from the server, or indeed do anything while waiting for it to be downloaded, so an asynchronous approach seems inappropriate in general.
Am I mistaken about that, or is there a better way?
TL;DR: It's the wrong approach in any GUI application.
how inconvenient something like that is to implement in Qt
It's not meant to be convenient, since whenever I see a shipping product that behaves that way, I have an urge to have a stern talk with the developers. Blocking the GUI is a usability nightmare. You never want to code that way.
coming from a procedural/C background, I'd initiate a synchronous download, set a timeout of maybe 3 seconds, then see what happens
If you write any sort of machine or interface control code in C, you probably don't want it to be synchronous either. You'd set up a state machine and process everything asynchronously. When coding embedded C applications, state machines make hard things downright trivial. There are several solutions out there, QP/C would be a first class example.
was thinking about initiating an asynchronous download in, say, InitVersionInfoDownload, and then connecting QNetworkReply's finished signal to a slot called VersionInfoDownloadComplete, or something along these lines. I'd also need a timer somewhere to implement timeout checks - if the slot is not invoked after say 3 seconds, the update should be aborted. However, this approach seems overly complicated
It is trivial. You can't discuss such things without showing your code: perhaps you've implemented it in some horribly verbose manner. When done correctly, it's supposed to look lean and sweet. For some inspiration, see this answer.
I cannot proceed without retrieving this file from the server, or indeed do anything while waiting for it to be downloaded
That's patently false. Your user might wish to cancel the update and exit your application, or resize its window, or minimize/maximize it, or check the existing version, or the OS might require a window repaint, or ...
Remember: Your user and the environment are in control. An application unresponsive by design is not only horrible user experience, but also makes your code harder to comprehend and test. Pseudo-synchronous spaghetti gets out of hand real quick. With async design, it's trivial to use signal spy or other products to introspect what the application is doing, where it's stuck, etc.

User Interface doesn't update output with position data

I am creating a user interface using (Qt) and I am attaching it to my C/C++ motion application using shared memory as my form of Inter Process Communication.
I currently have a class which I created in my motion application that has many members. Most of these members are used to update data on the UI and some of them get updated about 20 to 50 times a second, so it is pretty fast (the reason being because it is tracking motion). My problem is that the data is not getting updated on the UI frequently. It gets updated every few seconds. I was able to get it work using other variables made in structures from my application by using "volatile" however it does not seem to be working for members of my class. I know that the problem is not on the UI (Qt) side, because I saw that the actual member data was not being updated in my application, even though I have commands every cycle to update the data.
I was pretty sure the problem is that some optimization is occurring since I do not have my members declared as volatile as in my structures, but when I made them volatile it still did not work. I found that when I through a comment to print out in the function that updates my motion data within my motion application, the UI updates much more frequently as if the command to print out the comment deters the compiler form optimizing out some stuff.
Has anyone experienced this problem or have a possible solution?
Your help is greatly appreciated. Thanks ahead of time!
EDIT:
The interface does not freeze completely. I just updates every few seconds instead of continuously as I intended for it to do. Using various tests I know that the problem is not on the GUI or shared memory side. The problem lies strictly on the motion application side. The function that I am calling is below: int
`motionUpdate(MOTION_STAT * stat)
{
positionUpdate(&stat->traj);
}
`
where
positionUpdate(){stat->Position = motStatus.pos_fb;}
Position is a class member that contains x, y, and z. The function does not seem to update the position values unless I put a printed out comment before positionUpdate(). I don't track the change in shared memory to update the UI, but instead just update the UI every cycle.
Especially Given you are using Qt, I would strongly advise not using "native" shared memory, but to use signals instead. Concurrency using message-passing (signals/slots is one such way) is much, much easier to reason about and debug than trying to share memory.
I would expect your problem with updating is that the UI isn't being called enough of the time, so there is a backlog of updating to do.
Try putting in some code that throws away updates if they happen less than 0.3 seconds apart and see if that helps. You may wish to tune that number but start at the larger end.
Secondly, make sure there aren't any "notspots" in your app, in which the GUI thread is not being given the chance to run. If there are, consider putting code into another thread or, alternatively, calling processEvents() within that part of the code.
If the above really isn't what's happening, I would suggest adding more info about the architecture of your program.

Switching between various screens of the same state type?

I've been having an issue with the basic structure of a program that I'm working on. I'm a very inexperienced programmer trying to teach myself the basics of programs that use multiple states.
Right now, I have a very simple game-ish program with a game loop that redirects event, logic, and rendering to my StateManager class, which pushes and pops states onto a . The StateManager class then redirects the events, logic, and rendering to whatever state is on the back() of the vector. The idea is to have an assortment of different states for each phase of the program (in this case a simple game with splash screens, menus, gameplay, death screens, etc)...
However, I'm a VERY novice coder (trying my best to learn), and I've run into a fundamental issue with my program right from the very first state class...
The first class that I made is the SplashScreenState. And the basic concept was to have a state that essentially just shows a series of 'splash screen images' (lets say 3, for the sake of example), and each time the user presses a key, it switches to the next image, and finally (when it is out of splash screen images to cycle through) switches to the next state (menustate).
My problem is that I'm having a hard time figuring out how to structure this. Originally, I made the mistake of treating each different splash screen image as an instance of the SplashScreenState. However, I figured that do so was incorrect, as all 3 splash screens would technically be part of the same 'state'.
So now I have two main issues:
The first issue is that I'm not sure how/where to store all the splashscreen images. If I want to cycle between 3 different screen images when the program starts up, should I make them all members of the SplashScreenState class? Or is it smarter to simply have one class member for the 'currentImage', and each time the user hits a key it runs a load() function to load the next image into the currentImage pointer? Is it better to make an array or vector of images and cycle through them? I'm just not sure...
My second issue is with the eventhandling() of the SplashScreenState.. I know that I want the image on the screen to change like; *image1 -> image 2 -> image 3 -> changeState(menuState).. So that each time the user hits a key on their keyboard, it switches to the next splash screen, until the last splash screen, where it will then change state to the main menu. I'm not sure what the best way of doing this is either.. Should I create an enum for each splash screen and increment through them (until the final screen where it changes states)? I also think that, if I did store all my various screens in an array, then I could easily increment through them, but then would that be unoptimized because all the screens would have to be stored in memory at all times?
Anyway, I'm know this question might be very basic and noobish, but that's where I am right now unfortunately! I haven't had any formal education in programming and I've been teaching myself, so I really really appreciate all the help and expertise that's present on this site! ^^
Thanks!
You seem to be torn between an object-oriented vs a procedural paradigm for handling state transitions. The other answer suggesting a switch statement to handle enumerated state changes is a good procedural way to go about it. The drawbacks to that are that you might end up with a monolithic game class that contains all the code and all the superfluous state-specific data for handling your event/logic/rendering for all possible states. The object-oriented way to handle this is much cleaner, and encapsulates these into their own separate state objects where they can be used polymorphically through a shared interface. Then, instead of holding all the details for handling all the states in your game class, your game class needs only to store a state pointer and not worry about the implementation details of the concrete state object. This moves the responsibility of handling state transitions out of the game class and into the state class where it belongs. You should read up on the state/strategy pattern from a design patterns book. Handling the changing of a state should be the responsibility of the state object itself. Here is some reading:
http://www.codeproject.com/Articles/14325/Understanding-State-Pattern-in-C
http://sourcemaking.com/design_patterns/state
http://sourcemaking.com/design_patterns/state/cpp/1
http://codewrangler.home.comcast.net/~codewrangler/tech_info/patterns_code.html#State
http://en.wikipedia.org/wiki/State_pattern
http://www.codeproject.com/Articles/38962/State-Design-Pattern
Quoting from the Design Patterns and Pattern-Oriented Software Architecture books:
The pattern-based approach uses code instead of data structures to specify state transitions, but does a good job of accommodating state transition actions. The state pattern doesn't specify where the state transitions must be defined. It can be done in the context object, or in each individual derived state class. It is generally more flexible and appropriate to let the state subclasses specify their successor state and when to make the transition.
You have the option of creating state objects ahead of time and never destroying them, which can be good when state changes occur rapidly and you want to avoid destroying states that might be needed again shortly. On the other hand, it can be inconvenient because the context must keep references to all states that might be entered.
When the states that will be entered are not known at run-time and contexts change state infrequently, it is preferable to create state objects as needed and destroy them thereafter. In determining which to use, you need to consider cost as well as transition frequency.
Excellent explanation of your problem, first of all.
The portion of your game managing the splash screen can work in two ways. You've examined the problem and it's really that simple:
Receive input; set next state.
So, examples:
STATE_SPLASH1
STATE_SPLASH2
STATE_SPLASH3
STATE_TITLE
STATE_GAME_INIT
STATE_GAME
STATE_EXIT
pseudocode:
state = STATE_SPLASH1
while (state != STATE_EXIT)
... receive input ...
... process events to responders ...
... update ...
... yadda yadda ...
switch (state) {
case STATE_SPLASH1:
show_splash1()
case STATE_SPLASH2:
show_splash2()
case ..:
case STATE_TITLE:
show_title()
case STATE_GAME_INIT:
show_loading()
setup_level()
setup_characters()
case STATE_GAME:
game_update()
case STATE_EXIT:
cleanup_and_quit()
Another way is to manage splash a 'game state' and then the state of the splash as an internal state. and when splash has no more logic to run, set the game state to the next one. When I was learning, I found the DOOM source to be a valuable resource and man, is it nothing but hundreds of state machines. :)

How to de-GUI a complex tanglewad C++/Qt4 app?

We have a large messy app written in C++ and Qt4, many library dependencies, hundreds of classes and no coherent structure. It normally runs as a GUI app manipulated interactively, but sometimes it's launched in a hands-off way from another program that feeds it command line options and communicates with it by dbus. The GUI still shows, but no human or trained monkey is there to click anything. "Relaxen und watch das blinkenlights" Whether interactively or automatically, when run the app writes image files.
My job the next few weeks is to add an "no gui" feature, such that the app can run in the hands-off way and write its image files, without ever showing its GUI. Internally, the images to be written are made using QImage and other non-GUI Qt objects, but these are possessed by other objects that do involve the GUI classes of Qt. After several attempts to understand the mess, I cannot find a way to disentangle things such as to have the app create images w/o the whole full-blown GUI running. At one time, I was hoping I could just set xxx.visible= false; for all xxx that are GUI objects, but this is not practical or possible (AFIK).
Are there any general strategies to follow to add this no-gui feature to this app? Some technique that won't require deep redesign of the class hierarchy?
The long and hard way is finding out what and how the logic is executed, extract the logic to some QObject based classes (with signals and slots) and make it a QtCore app. I know this doesn't help, but that's the correct way.
If setting all GUI elements to hidden (or perhaps only the QMainWindow?) is not an option, this is the only thing you can do.
Qt allows you to do this, but if the original coder did not plan this in, you've got a lot of refactoring/recoding to do.
This really depends on how the program is written. If the logic is somewhat seperated from the interface, then it could be as simple as finding out what class inherits from the QMainWindow class and making sure that is never initialised.
In the case where the logic is all over the place, I'd strongly suggest trying to get all the logic into a form of signal or slot (which has probably already happened considering that it's a GUI app), then just not initialising the QMainWindow instance and calling these manually.
Try to subclass interface classes (QMainWindow, QDialog, etc), and implement your logic there.

Keeping the GUI separate

I have a program that (amongst other things) has a command line interface that lets the user enter strings, which will then be sent over the network. The problem is that I'm not sure how to connect the events, which are generated deep inside the GUI, to the network interface. Suppose for instance that my GUI class hierarchy looks like this:
GUI -> MainWindow -> CommandLineInterface -> EntryField
Each GUI object holds some other GUI objects and everything is private. Now the entryField object generates an event/signal that a message has been entered. At the moment I'm passing the signal up the class hierarchy so the CLI class would look something like this:
public:
sig::csignal<void, string> msgEntered;
And in the c'tor:
entryField.msgEntered.connect(sigc::mem_fun(this, &CLI::passUp));
The passUp function just emits the signal again for the owning class (MainWindow) to connect to until I can finally do this in the main loop:
gui.msgEntered.connect(sigc::mem_fun(networkInterface, &NetworkInterface::sendMSG));
Now this seems like a real bad solution. Every time I add something to the GUI I have to wire it up all through the class hierarchy. I do see several ways around this. I could make all objects public, which would allow me to just do this in the main loop:
gui.mainWindow.cli.entryField.msgEntered.connect(sigc::mem_fun(networkInterface, &NetworkInterface::sendMSG));
But that would go against the idea of encapsulation. I could also pass a reference to the network interface all over the GUI, but I would like to keep the GUI code as seperate as possible.
It feels like I'm missing something essential here. Is there a clean way to do this?
Note: I'm using GTK+/gtkmm/LibSigC++, but I'm not tagging it as such because I've had pretty much the same problem with Qt. It's really a general question.
The root problem is that you're treating the GUI like its a monolithic application, only the gui is connected to the rest of the logic via a bigger wire than usual.
You need to re-think the way the GUI interacts with the back-end server. Generally this means your GUI becomes a stand-alone application that does almost nothing and talks to the server without any direct coupling between the internals of the GUI (ie your signals and events) and the server's processing logic. ie, when you click a button you may want it to perform some action, in which case you need to call the server, but nearly all the other events need to only change the state inside the GUI and do nothing to the server - not until you're ready, or the user wants some response, or you have enough idle time to make the calls in the background.
The trick is to define an interface for the server totally independently of the GUI. You should be able to change GUIs later without modifying the server at all.
This means you will not be able to have the events sent automatically, you'll need to wire them up manually.
Try the Observer design pattern. Link includes sample code as of now.
The essential thing you are missing is that you can pass a reference without violating encapsulation if that reference is cast as an interface (abstract class) which your object implements.
Short of having some global pub/sub hub, you aren't going to get away from passing something up or down the hierarchy. Even if you abstract the listener to a generic interface or a controller, you still have to attach the controller to the UI event somehow.
With a pub/sub hub you add another layer of indirection, but there's still a duplication - the entryField still says 'publish message ready event' and the listener/controller/network interface says 'listen for message ready event', so there's a common event ID that both sides need to know about, and if you're not going to hard-code that in two places then it needs to be passed into both files (though as global it's not passed as an argument; which in itself isn't any great advantage).
I've used all four approaches - direct coupling, controller, listener and pub-sub - and in each successor you loosen the coupling a bit, but you don't ever get away from having some duplication, even if it's only the id of the published event.
It really comes down to variance. If you find you need to switch to a different implementation of the interface, then abstracting the concrete interface as a controller is worthwhile. If you find you need to have other logic observing the state, change it to an observer. If you need to decouple it between processes, or want to plug into a more general architecture, pub/sub can work, but it introduces a form of global state, and isn't as amenable to compile-time checking.
But if you don't need to vary the parts of the system independently it's probably not worth worrying about.
As this is a general question I’ll try to answer it even though I’m “only” a Java programmer. :)
I prefer to use interfaces (abstract classes or whatever the corresponding mechanism is in C++) on both sides of my programs. On one side there is the program core that contains the business logic. It can generate events that e.g. GUI classes can receive, e.g. (for your example) “stringReceived.” The core on the other hand implements a “UI listener” interface which contains methods like “stringEntered”.
This way the UI is completely decoupled from the business logic. By implementing the appropriate interfaces you can even introduce a network layer between your core and your UI.
[Edit] In the starter class for my applications there is almost always this kind of code:
Core core = new Core(); /* Core implements GUIListener */
GUI gui = new GUI(); /* GUI implements CoreListener */
core.addCoreListener(gui);
gui.addGUIListener(core);
[/Edit]
You can decouple ANY GUI and communicate easily with messages using templatious virtual packs. Check out this project also.
In my opinion, the CLI should be independant from GUI. In a MVC architecture, it should play the role of model.
I would put a controller which manages both EntryField and CLI: each time EntryField changes, CLI gets invoqued, all of this is managed by the controller.