Articles for developing a GUI library - c++

Basically, I'm unable to find any good articles for developing your own GUI, that deal with good practices, the basic structure, event bubbling, tips and avoiding all the usual pitfalls. I'm specifically not interested on how to build some proof-of-concept GUI in 5 minutes that just barely works... nor am I interested in building the next future GUI.
The purpose is to build a reasonably capable GUI to be used for tools for a game, however they will exist within the game itself so I don't want to use existing large scale GUIs, and I find most game GUIs to be rather bloated for what I need. And I enjoy the experience of doing it myself.
I have done a GUI in the past which worked very well to a point, however, due to some bad design decisions and inexperience it could only do so much (and was built in Flash so it got a lot of stuff for free). So I would like to really understand the basics this time.

A few tips -
1) Pick your style the UI will work - will it be stateless? If yes, how are you going to handle the events appropriately? In case it'll be stateless, you'll maybe have to re-evaluate your UI user code twice in order to get up to date event changes from user side. If your UIs store state, then you won't have to care about handling events, but it'll limit your UIs when it comes to rapid mutations and rebuilds.
2) Do not rely on the OO too much, virtual methods are not the fastest thing in the world so use them with care; having some sort of inheritance based structure might help though. Beware of dynamic_cast and RTTI if you use objects; they will slow you down. Instead, set up an enum, get_type() method for every widget class, and do manual checks for castability.
3) Try to separate the looks and the UI logic/layout.
4) If you want dynamic windows, layouts etc. then you'll have to handle aligning, clamping, positions etc. and their updates. If you want just statically positioned widgets, it'll make it much easier.
5) Do not overdesign, you won't benefit from that.
There is not really anything too specific I tell you; having some concrete question would help, maybe?

Take a look at the docs for existing GUI libraries. That should give you details on proven designs to handle the issues you've run into.
You might want to start with one you're familiar with, but one that I think is designed quite well is AppKit. Its API is Obj-C so it would require some adjustment if you wanted to copy it, but the docs give all kinds of details about how objects interact to, e.g. handle events, and how layout constraints work, which should be directly applicable to designing an OO GUI in most any language.

Related

How to select the right architectural/design patterns

I am doing my own research project, and I am quite struggling regarding the right choice of architectural/design patterns.
In this project, after the "system" start, I need to do something in background (tasks, processing, display data and so on) and at the same be able to interact with the system using, for example, keyboard and send some commands, like "give me status of this particular object" or "what is the data in this object".
So my question is - what software architectural/design patterns can be applied to this particular project? How the interraction between classes/objects should be organized? How should the objects be created?
Can, for example, "event-driven architecture" or "Microkernel" be applied here? Some references to useful resources will be very much appreciated!
Thank you very much in advance!
Careful with design patterns. If you sprinkle them throughout your code hoping that everything will work great, you'll soon have an unreadable, boilerplate full mess. They are recipes, not solutions.
My advice to you is pick a piece of paper and a pencil and start drawing all the entities of your domain, with all their requisites, and see how they relate. If you want to get somewhat serious about it, you can do something like this.
When defining your entities, strive for high cohesion and loose coupling.
High cohesion means that you should keep similar functionalities together. In a very simple example, if you have a class that reads stuff from a file and processes it, the class has low cohesion, since reading and processing are two very distinct functionalities. In this case, you would want a class for each functionality.
As for loose coupling, it means that your entities should be independent of each other. Using the example above, supposed that you are now the proud owner of two highly cohesive classes - one that reads stuff from a file (Reader), and one that processes that stuff (Processor). Now, suppose that the Processor class has an instance of the Reader class, and calls it in order to get its input. In this case, we can say that both classes are tightly coupled, since Processor won't work without Reader. In the OOP world, the solution for this is typically the use of interfaces. You can find a neat example here.
After defining an initial model of your domain and gathering as much knowledge about it as you can, you can now start to think about the implementation's architecture. This is were you can start thinking about the architectural patterns. Event driven architecture, clean architecture, MVP, MVVM... It will all depend on your domain. It is your job to know which pattern will fit best. Spoiler alert: this can be extremely hard to do correctly even for experienced engineers, so don't be afraid to fail.
Finally, leave the design patterns for the implementation stage. Their use completely depends on your implementation problems and decisions. Also, DON'T FORCE THEM. Ideally, you will solve a problem and, IF APPLICABLE, you'll see a pattern emerging. Trust me, the last thing you want is to have a case of design patternitis. Anyway, if you need literature on patterns, I totally recommend this book. It's great no matter your level as an engineer.
Further reading:
SOLID principles
Onion Architecture
Clean architecture
Good luck!
You have a background task, and it can be used for a message pump/event queue indeed. Then your foreground task would send requests to this background thread and asynchronously wait for the result.
Have a look at the book "Patterns for Parallel Programming".
It is much better if you check a book for Design Patterns. I really like this one.
For example, if you need to get some data from a particular object, you may need the Observer Pattern to work for you and as soon as the object has the data, you (or another object) get to know this data and can work with it, with another pattern (strategy might work, it really depends on what you have to do).
If you have to do some things at the same time, check also the Singleton pattern (well, check the most important ones!).

Porting C++ w/ MFC to a Touch Screen

Looking for a GUI framework to use with C++ to "modernize" an existing interface for touchscreen.
I'm a novice programmer with a background in C++/Java that was just assigned a project that involves taking an existing C++ program using MFC (3 data views, multiple text/radio controlled dialog boxes, etc.) and redesigning the interface to be "touch-screen friendly" such as larger button controls, sliders and whatnot.
I've been given pretty free-reign with instructions to make a "more modern looking interface" as opposed to the typical bare-bones MFC I've been given. I know I have quite a bit to learn either way, so any suggestions are helpful.
So far the options I've come up with are:
MFC just tweak existing controls to accommodate touch input, keep crappy looking interface.
Managed C++ or C++/CLI figure out how to keep the underlying C++ structure while being able to design a new interface with WPF or Windows Forms.
Qt completely new to me, but seems a promising alternative.
Really I just need to find a way to make this program look like it wasn't written over 10 years ago, and so far in teaching myself MFC, it doesn't seem that flexible in terms of incorporating any sort of graphic-design/themes.
Are there other alternatives I should be looking into? Is there more to MFC than meets the eye and I just need to learn more about it? As I said, any suggestions of things to look into are helpful.
What you've listed as #1 could really be either of two approaches. One (call it 1a) is to continue using the same version of VC++ and MFC as the original, and do only the bare minimum of editing to increase the sizes of the controls where needed. Short of encountering some fairly bad luck in how the existing code is written, this might not involve any real programming at all, and would be relatively quick and easy.
The second (call it 1b) would be to do the update using the current version of VC++, MFC, etc. This would probably involve some code updates, but probably not anything terrible (though if it's much more than 10 years old, significant code updates could be needed as well). With some care, you may be able to update the UI quite a bit (e.g., change from menus to ribbons, include color theme support), still with fairly minimal investment.
Your #2 could easily end up as nearly a complete rewrite. Despite superficial similarities, C++/CLI is a completely different language from C++. The only way this really makes sense is if you have quite a bit of non-UI code you can leave alone completely, and use C++/CLI exclusively as a "bridge" between existing C++ and a .NET UI (and the UI is fairly minimal, so the rather mediocre tool support for C++/CLI doesn't cause a big problem). If your UI is any more than fairly trivial, C# has enough better tool support that it may easily be a better choice than C++/CLI.
Your #3 will probably require only marginally less rewriting than 2, at least of the code that's related to the UI. While the code would remain C++, Qt is quite a lot different from MFC. The big advantage would be if you (might soon) want to support something other than Windows (e.g., iOS or Android). For portability, Qt has a huge advantage over any of the alternatives you've named.
A lot comes back to a question of how much C++ code you can retain intact. If you have a lot of code in an "engine" that's cleanly separated from the UI, and a fairly simple UI, then retaining that existing code make a lot of sense, and rewriting the UI from the ground up isn't all that terrible of a problem. On the other hand, if the UI and business logic code are heavily intertwined (fairly common) then any more than really minor tweaks to the UI is likely to me significant rewriting of the rest of the code as well.
Conclusion: if the UI is heavily intertwined with other code, your only real choice is between 1a and 1b. If the UI is easily detached from other code, the choice between 2 and 3 is (at least to me) primarily one of whether portability is at all likely to matter (now or any time soon).

Better framework than MFC?

My clients have used MFC applications in years. Main reason was because their applications were real-time app interacting with various sensors, and their performance was key to their success.
I used MFC about 10 years ago and moved to .NET. But I am willing to go back to MFC if neccessary. But question is if it is worth and if there is anything better than MFC right now.
I understand that C++ is necessary to optimize our applications and that MFC is OOP wrapper for Win32 API and might be fastest OOP UI API on Windows.
But I am mainly worried about its testability and its complex API. So MFC might slow us down in long term.
What do you think? Is there any framework that you can achieve better performance than with MFC?
UPDATE: As for needed performance, I don't have exact numbers but I saw one app in its operations. It was almost getting various types of signals from each of moving objects. My guess at the time was less than 1/2 second to get & display all the signals from each one. But I could be wrong.
You probably want to look at Qt.
The internet is full of comparisons of MFC and Qt; here is a particularly recent one: https://softwareengineering.stackexchange.com/questions/17490/comparing-qt-vs-mfc
Assuming (although it wasn't specified in the question) that your application is another sensor-control system, it doesn't matter as much as you think it does.
Basically, your architecture should keep the sensor communications in their own thread, which asynchronously communicate with the rest of the app. So you're mostly checking to see if your potential replacement libraries do something pathological with their multi-threading implementation.
To give particulars, we would need particulars: required response times, interrupt frequencies, these sorts of things. But even in that case, we'd mostly just be guessing (or campaigning for our favorite API).
My real recommendation is that you look into the performance numbers you get with .NET in a "prototype control". Your recent familiarity with the API should enable you to do this relatively quickly.
If the performance seems unacceptable, do a similar prototype in Qt or WTL or whatever else looks reasonable. I would consider MFC a last resort simply due to age UNLESS you can leverage significant amounts of existing control code from the client.
There are some best alternatives for MFC.
QT is the first choice to go with. But for commercial release, it becomes little costlier.
wxWidgets, is also a good choice for a cross platform opensource library.
Ultralight - This is totally different as it is a HTML based UI engine to create nice applications with the help of HTML, css, and javascript.

Removing dependencies from statechart framework

I've got lots of problems with project i am currently working on. The project is more than 10 years old and it was based on one of those commercial C++ frameworks which were very populary in the 90's. The problem is with statecharts. The framework provides quite common implementation of state pattern. Each state is a separate class, with action on entry, action in state etc. There is a switch which sets current state according to received events.
Devil is hidden in details. That project is enormous. It's something about 2000 KLOC. There is definitely too much statecharts (i've seen "for" loops implemented using statecharts). What's more ... framework allows to embed statechart in another statechart so there are many statecherts with seven or even more levels of nesting. Because statecharts run in different threads, and it's possible to send events between statecharts we have lots of synchronization problems (and big mess in interfaces).
I must admit that scale of this problem is overwhelming and I don't know how to touch it. My first idea was to remove as much code as I can from statecharts and put it into separate classes. Then delegate these classes from statechart to do a job. But in result we will have many separate functions, which logically don't have any specific functionality and any change in statechart architecture will need also a change of that classes and functions.
So I asking for help:
Do you know any books/articles/magic artefacts which can help me to fix this ? I would like to at least separate as much code as I can from statechart without introducing any hidden dependencies and keep separated code maintainable, testable and reusable.
If you have any suggestion how to handle this, please let me know.
The statechart pattern is intended to be used specifically to remove switch statements, so this sounds like a horrid abuse. Additionally, states should only change on asynchronous events. If you are processing an event and you change through multiple states (or for loop, etc.), then this is also a horrid abuse of the pattern.
I would start from these two points, as they will solve much of your concurrency issues just fixing them up. What you need to determine is:
What are your external, asynchronous events to the system? These are the only things that should be determining state transitions, not things that happen during event processing. An event may cause 0 or 1 state transitions. Once you have a list of these state transitions, you can reconstruct the actual states of your system. If you are aware of UML State diagrams, this would be a perfect time to sketch one up in a charting program, not just for yourself (though it will help you immensely), but also for everyone in the future that has to return to the project. As you have learned, this happens.
Now that you know what are really states, list what are states in the code that shouldn't be. This usually indicates that something can be "functionally decomposed". Instead of a state object for each of these, likely all that is needed is a separate function. This will cut down on a lot of the overhead of state objects and should clean up the code immensely.
Now it's time to tackle those horrendous switch statements you mentioned. If they were truly based on state, you shouldn't need one at all. Instead, you should be able to call the state machine directly.
Something like:
myStateMachine->myEvent();
and it should work without any switch. But notice, this may be the case even for some of those objects that don't work across asynchronous events. This is also an indication of where you may just use inheritance to get the same effect. If you have:
switch (someTypeIdentifier)
{
case type1:
doSomething();
break;
case type2:
doSomethingElse();
break;
}
usually the correct OOP method to do is to create two actual types Type1, Type2, both derived from an abstract base TypeBase, with a virtual method doSomething() that does what you need. The reason this is useful is because it means you can "close" the handling (in the meaning of the Open/Closed Principle), and still extend the functionality by adding new derived types as needed (leaving it open to extension). This saves bugs like crazy because it gets developers hands out of those switch statements, which can get quite ugly and convoluted, instead encapsulating each separate behavior in separate classes.
4 - Now look to fix up your thread issues. Identify all objects used from multiple threads. Make a list. Now, how are these used? Are some of them always used together? Start making groups. The goal here is to find the level of encapsulation that best works for these objects, separate the objects into individual classes that control their own synchronisation, figure out the atomic level of actual "transactions" for the objects, and make methods of the classes that expose those meaningful transactions, wrapped behind the scenes with the appropriate mutexes, condition variables, etc.
You might be saying "that sounds like a lot of work! Why do all that instead of just writing it all over myself?" Good question! :) The reason is actually straightforward: if you are going to do it all by yourself, those are the steps you should be doing anyway. You should be identifying your states, your dynamic polymorphism, and getting a handle on the multithreaded transactions. But, if you start with the existing code, you also have all of those unspoken business rules that were never documented and may cause all sorts of unexpected bugs down the line. You don't have to bring everything over - if you suspect it's a bug, discuss the logic with the people who have worked with the system in the past (if available), QA, or whoever might identify bugs, and see if it really should be carried over. But you need to actually evaluate what the bugs are either way, or you may not code something that actually needed coding.
In the end, this is a manual process that is a part of software engineering. There are CASE tools that can help draw up the state diagrams and even publish them to code, there are refactoring tools, like those found in many IDEs, that can help move code between functions and classes, and similar tools which can help identify threading needs. However, those things shouldn't be picked up for a single project. They need to be learned throughout your career, picking them up and learning them more deeply over years of work, as they are a part of being a software engineer. They don't do it for you. You still need to know the whys and hows, and they just help get it done more efficiently.
Statecharts (including nested Statecharts) are a powerful way to specify, understand and even simulate/validate complex control flow. But to gain the benefit, you need the statechart model in a suitable tool (I used Statemate way back in the day, not sure if it's still available), plus a reliable mapping from the chart to the code (Statemate used to generate the code) - then you can forget about the state management code (mostly)! In your situation, if you don't have the model, I would try to reverse one from the code - as Ira says, chances are high that the original developers had a model in some form, and you may find the code making a lot of sense as the model emerges. If this works out, you will have a really good spec/model of the code which should make future code edits much easier (even if you don't want to go to automatic code generation, and maintain the code/model mapping manually (but you'll need to be meticulous!!))
Sounds to me like your best bet is (gulp!) likely to start from scratch if it's as horrifically broken as you make out. Is there any documentation? Could you begin to build some saner software based on the docs?
If a complete re-write isn't an option (and they never are in my experience) I'd try some of the following:
If you don't already have it, draw an architectural picture of the whole system. Sketch out how all the bits are supposed to work together and that will help you break the system down into potentially manageable / testable parts.
Do you have any kind of requirements or testing plan in place? If not, can you write one and start to put unit tests in place for the various chunks of code / functionality which exist already? If you can do that, you can start to refactor things without breaking as much of whatever does currently work.
Once you've broken things down a bit, start building your unit tests into integration tests which pull together more of the functionality.
I've not read them myself, but I've heard good things about these books which may have some advice you can use:
Refactoring: Improving the Design of Existing Code (Object Technology Series).
Working Effectively with Legacy Code (Robert C. Martin)
Good luck! :-)

Presenting MVC to Old C++ Spaghetti Coders?

I wish to present the idea of MVC to a bunch of old C++ spaghetti coders (at my local computer club).
One of them that has alot of influence on the rest of the group seems to finally be getting the idea of encapsulation (largely due in part to this website).
I was hoping that I could also point him in the right direction by showing him Model View Controller, but I need to do it in a way that makes sense to him, as well as it probably needs to be written in C/C++!
I realize that MVC is a very old architectural pattern so it would seem to me that there should be something out there that would do the job.
I'm more of a web developer, so I was wondering if anybody out there who is a good C/C++ coder could tell me what it is that made the MVC light switch turn on in your head.
Don't start off with MVC. Start off with Publish / Subscribe (AKA the "listener" pattern).
Without the listener pattern fully understood, the advantages of MVC will never be understood. Everyone can understand the need to update something else when something changes, but few think about how to do it in a maintainable manner.
Present one option after another, showing each option's weaknesses and strengths: making the variable a global, merging the other portion of code into the variable holder, modifying the holder to directly inform the others, and eventually creating a standard means of registering the intent to listen.
Then show how the full blown listener can really shine. Write a small "model" class and add half a dozen "listeners" and show how you never had to compromise the structure of the original class to add "remote" updates.
Once you get this down, move the idea into to the "model view" paradigm. Throw two or three different views on the same model, and have everyone amazed on how comparatively easy it is to add different views of the same information.
Finally discuss the need to manage views and update data. Note that the input is partially dependent on items which are not in the view or the model (like the keyboard and mouse). Introduce the idea of centralizing the processing where a "controller" needs to coordinate which models to create and maintain in memory, and which views to present to the user.
Once you do that, you'll have a pretty good introduction to MVC.
You might find it easier to sell them on the Document/View or Document/Presenter patterns. MVC was invented on Smalltalk where everything about the different UI elements had to be coded by the developer (as I understand, never used the thing). Thus the controller element was necessary because didn't have things like TextElement::OnChange. Now days, more modern GUI API's use Document/View but Document/Presenter is something I've seen proposed.
You might also consider reading Robert Martin's article on the TaskMaster framework.
You might also consider that any C++ developer who is not familiar with these patterns and already understands their purpose and necessity is either a complete newb or a basket-case best avoided. People like that cause more harm than good and are generally too arrogant to learn anything new or they already would have.
Get some spaghetti C++ code (theirs?), refactor it to use MVC, and show them what advantages it has, like easier unit testing, re-use of models, making localized changes to the view with less worry, etc.