Are Singletons EVIL in GUI Programming with Qt? - qt

I'm just starting my first fairly large Qt project which will be mostly a bunch of screens with buttons, tab widgets, and Qwt Plots. The panel stack pattern described in Qt Quarterly 27 seems pretty nice for my application. Each of my screens is a QWidget encapsulated in a Panel which is shown/hidden by a QStackedWidget. However it uses a singleton pattern for each Panel so that they aren't all created immediately as the app starts and so that more than one of each screen isn't ever created.
So I started coding. Got the panel stack working. Added some code so that dynamically updating widgets aren't dynamically updating all the time. Got my history stack/back button working for the panels. Everything seems just fine, but I've got one nagging worry:
My code smells.
I am in no place to argue with any of the hate posted here and on blogs about the singleton pattern. I think I get it and the code I've written does make me feel a bit dirty with all the boilerplate lines and global objects. But I do like not having to worry about whether or not I already instantiated a screen before switching to it and adding it to my history stack. I just say switch to that screen, it's added to my history stack, and the magic works.
From what I've read there are also some cases where singletons can be worthwhile. Is this one of those special cases? The magic screen switching / history stack makes me think 'yes' but the sheer number of different singleton classes I'm going to have to create makes me think 'NO no NO NO NO'.
I want to just man up and figure out how to get the singleton pattern out of my code now so that I don't have to do it later. But I don't want to get rid of all my singleton classes just to get rid of my singleton classes because they're EVIL [citation needed].
Any input is much appreciated!

I don't really hate singletons, but this sounds like a case with no use for them. I don't understand why there are so many singletons in that article.
First, the PanelStack is a singleton by itself. Why? If that's your main widget, then just create it on the stack in the main(), which is both cleaner and faster. If it is a part of a more complicated UI, then put it there as a member of that UI. A regular class is just fine here, making it singleton only limits its possible uses.
Then, each panel is also a singleton? At this point even singleton lovers should begin to feel that there are too many of them already. Which is probably why you are asking this question in the first place. Let's see what real advantages singletons give here. Well, about the only advantage I can figure out from that article is the ability of lazily creating panels on the fly as they are needed. This is actually a good thing, but in fact, lazy creation and singletons are different patterns, although one often uses the other.
Why not just put all those panels in some common container instead? In this case, the PanelStack looks like a perfect candidate for it. It is the very place where panels are stored after all. Instead of a bunch of singletons, let's create a bunch of methods in the PanelStack:
class PanelStack : public QWidget
{
Q_OBJECT
public:
int addPanel(AbstractPanel *);
void showPanel(int);
RecordingsPanel *getRecordingsPanel();
ReecrdingDetailsPanel *getRecordingDetailsPanel();
private:
...
};
And so on. These get*Panel() methods can still create panels lazily as needed. Now, it's essentially the same thing as having a bunch of singletons, with some advantages added:
If we make panels children of the stack, they are automatically deleted when the stack is deleted. No need to worry about memory management which is always a pain with singletons.
You could even implement some sort of "garbage collector" in the PanelStack that deletes panels that haven't been used for some time. Or when some sort of "max active panels" limit is reached.
Now, the only disadvantage I can think of is that we have a dependency between the stack and the panels now. But what's worse, to store instances in one class, introducing a dependency, or to store them globally? If you think that the stack should be independent from panels, which does sound reasonable, then we probably just need another class to put all those things in. It could be a subclass of QApplication, or just some random "UI manager" class, but it is still better to store everything in one place than to store everything globally.
Using singletons here only breaks encapsulation and limits the possible uses of the whole UI. What if we want to have two windows with those panels? Or multiple tabs (think web browser)? Singletons will bite hard. And they are only really useful when the instance is accessed widely across many unrelated classes (think DB connections, loggers, pools and other typical singleton uses). They are mostly useless in an UI because with UI it is almost always obvious that "this thing belongs there, and probably nowhere else".

Related

Is it possible to re-paint/update content in a Qt GUI application although the main thread is blocked?

There is a lot of discussion (e.g. here) going on about spinning or moving busy indicators in a GUI but I could not find a single one that clearly states that it is impossible to re-paint/update any content in a GUI application while the main thread is blocked.
This question is actually a general one and is not necessarily directly related to Qt GUI applications.
When the main thread of a GUI is performing a blocking operation no events are processed and no content can be re-painted. There are two "recommended" approaches:
Using worker threads
Splitting the work in chunks and updating the UI "just not that often"
The problem is that there are operations that simply cannot be moved to worker threads or any other asynchronous mechanism. The best example is the serialization and de-serialization of the UI itself. In both scenarios the user must not click happily in the UI and change settings while the settings, properties, etc. are taken from the widgets (during the saving) or applied to the widgets (during the loading). This is true for the threading approach as well as the splitting into chunks.
Edit: Another example is the application of stylesheets to a complete GUI. Imagine that a user wants so select a "dark" scheme. All of the widgets need to be updated and the currently visible ones needs to be re-painted. During this step the event loop cannot run. A similar discussion can be found here.
In my case I'm working on an embedded device so there is another approach:
Directly overwriting a specific region of the framebuffer
This approach feels very ugly and comes with a lot of problematic scenarios and surly involves lots of debugging.
The last but sad approach:
Do not use any moving/updating content at all and just show something static such as "...in progress..."
Well, this is just sad...
Do you agree on these observations? Does anyone know of a different approach or concept in general un-related to Qt?
The problem is that there are operations that simply cannot be moved to worker threads or any other asynchronous mechanism.
I can't agree. These operations should be split into blocking and non-blocking operations. Everything that blocks should be handled asynchronously, or, if no non-blocking APIs are available, handed off to a worker thread.
The best example is the serialization and de-serialization of the UI itself.
I find it a particularly poor example mainly because I've yet to run into a need for blocking the GUI, and serialization doesn't call for it.
In both scenarios the user must not click happily in the UI and change settings while the settings, properties, etc. are saved or loaded.
Construction and destruction of the widgets should be very quick, if that's what you mean by "deserializing" the UI. Recall that the blocking I/O and long parsing has been done in another thread. Almost all Qt widgets certainly are quick to set up, and those that are not are a necessary evil that you have no choice but to live with. If you have your own widgets that do blocking operations like disk or registry access in their constructors or event handlers (plenty of such "code" exists), fix them.
If you're merely talking about setting widget values, this again is super-quick and can be done all in one batch. You will probably need a viewmodel to asynchronously interface between the view (widgets, QML view, or a QAbstractItemView) and the data source.
Disk I/O and parsing/output of the on-disk representation belongs in a separate worker. Once you create an internal representation, it can be passed to the gui thread to build the widget tree or populate the interface.
You should implement thread-safe models using QAbstractItemModel or a similar interface, and populate them in a worker thread, and let the GUI thread react to the updates in real time.
If you wish to indicate to the user that a part of the interface is not usable yet, e.g. while a model gets populated, you could do so via an overlay, making sure that you temporarily disable the focus on the widgets that are under the overlay. This is not hard and I'd find it amusing if your entire question could be reduced to "how do I make a part of the UI inaccessible while it's being modified".
The key thing missing is that the UI should handle asynchronously reacting to a model changing its state. For all I care, it could take an hour to load the data needed to fully populate the model. It doesn't mean that your application should be unresponsive. Simply make the parts of the UI that can't be interacted with inaccessible for interaction. Ensure that other parts of the application that need the configuration data are similarly either inaccessible or in a partially usable state that will asynchronously revert to full state once the configuration becomes available.

QML Component loader vs separate file for reusing items

In my application ( QML, QtQuck 1.1, C++ ) I want to reuse some items in my screen.
Generally there are two options ( please let me know if there are more)
1.Use a separate .qml file and put the basic block inside and import in new screen
2.Create a component and use loader to load it.
But I cannot understand which option to use.
Whats the difference between these two options.
Or
which will consume less CPU load?
Thanks!!
Use the first approach unless:
You need to conditionally load QML based on some runtime condition. Note that file selectors are more efficient than Loaders for this purpose, but it might not be possible to use them, depending on your requirements.
You want to avoid loading expensive QML until absolutely necessary (lazy loading).
You should especially be wary of using Loader to load components that are created in large numbers (such as those used as delegates in views), as it doesn't come for free.
To clarify on a part of the answer provided by Mitch:
You should especially be wary of using Loader to load components that
are created in large numbers (such as those used as delegates in
views), as it doesn't come for free.
Using a Loaderas a delegate just to create some other object doesn't make sense except for a very narrow case. You can directly and most definitely should use YourItem {} as a delegate instead. Delaying instantiation in a view delegate in particular is not a very good idea, since that will mess up the view layout, absent the actual item's dimensions which can't be determined without loading it. Even in the case where the Loader is not the top element but nested, it won't be problematic, as QML views only instantiate delegate objects for objects that are in view, if your model has 10k objects it is not like you will have 10k loaders unless they are all in view, which ... won't me much of a view.
Also, if you really need dynamic instantiation, then you will need at least an Item to use as a parent anyway, so the overhead of the Loader becomes negligible and a very good trade-off for the extra flexibility and functionality such as use bindings for the item or to set a dynamic source component. You could do that with an Item but you will have to implement it yourself, and in the end it will end up with larger overhead than Loader.
The CPU time for either of the approaches will not make a difference. Now if you are dynamically creating lots of objects manually, you definitely neither need nor should be using loaders. And not because of the CPU time, but because of memory usage - QML objects are memory hogs, a few thousand objects of medium complexity will likely run you into serious trouble on a 32bit build, especially on a mobile device. Even an empty, non visible QtObject is like 160 bytes. On top of that JS garbage collection is pretty much a joke when it comes to releasing resources, it will do fine on reusing. If you for example create 1 GB of visual items, then delete them and force garbage collection, you will only get a tiny fraction of that memory back, but if you create the objects again, memory usage will be pretty much the same +/- a few megabytes.
In short, in separate .qml file put global component wich you will include and use in different files.
Create component in same file if you will use it only in one file.
Also it depends on the size and complexity of the component. Big and complex component preferably place to separate file.
Compiling faster when all code in one file, but development faster when everything in their place.

final methods in JavaFX source

Problem
I need to overwrite the method
#Override protected final void layoutChartChildren(double top, double left, double width, double height)
of the XYChart class. Obviously I'm not allowed to.
Question
Why do people declare methods as "final"? Is there any benefit in that?
This answer is just a verbatim quote of text by Richard Bair, one of the JavaFX API designers, which was posted on a mailing list in response to the question: "Why is almost everything in the [JavaFX] API final?"
Subclassing breaks encapsulation. That's the fundamental reason why
you must design with care to allow for subclassing, or prohibit it.
Making all the fields of a class public would give developers
increased power -- but of course this breaks encapsulation, so we
avoid it.
We broke people all the time in Swing. It was very difficult to make
even modest bug fixes in Swing without breaking somebody. Changing the
order of calls in a method, broke people. When your framework or API
is being used by millions of programs and the program authors have no
way of knowing which version of your framework they might be running
on (the curse of a shared install of the JRE!), then you find an awful
lot of wisdom in making everything final you possibly can. It isn't
just to protect your own freedom, it actually creates a better product
for everybody. You think you want to subclass and override, but this
comes with a significant downside. The framework author isn't going to
be able to make things better for you in the future.
There's more to it though. When you design an API, you have to think
about the combinations of all things allowed by a developer. When you
allow subclassing, you open up a tremendous number of additional
possible failure modes, so you need to do so with care. Allowing a
subclass but limiting what a superclass allows for redefinition
reduces failure modes. One of my ideals in API design is to create an
API with as much power as possible while reducing the number of
failure modes. It is challenging to do so while also providing enough
flexibility for developers to do what they need to do, and if I have
to choose, I will always err on the side of giving less API in a
release, because you can always add more API later, but once you've
released an API you're stuck with it, or you will break people. And in
this case, API doesn't just mean the method signature, it means the
behavior when certain methods are invoked (as Josh points out in
Effective Java).
The getter / setter method problem Jonathan described is a perfect
example. If we make those methods non-final, then indeed it allows a
subclass to override and log calls. But that's about all it is good
for. If the subclass were to never call super, then we will be broken
(and their app as well!). They think they're disallowing a certain
input value, but they're not. Or the getter returns a value other than
what the property object holds. Or listener notification doesn't
happen right or at the right time. Or the wrong instance of the
property object is returned.
Two things I really like: final, and immutability. GUI's however tend
to favor big class hierarchies and mutable state :-). But we use final
and immutability as much as we can.
Some information:
Best practice since JavaFX setters/getters are final?

Displaying Flex Object References

I have a bit of a memory leak issue in my Flex application, and the short version of my question is: is there any way (in AcitonScript 3) to find all live references to a given object?
What I have is a number of views with presentation models behind each of them (using Swiz). The views of interest are children of a TabNavigator, so when I close the tab, the view is removed from the stage. When the view is removed from the stage, Swiz sets the model reference in the view to null, as it should. I also removeAllChildren() from the view.
However when profiling the application, when I do this and run a GC, neither the view nor the presentation model are freed (though both set their references to each other to null). One model object used by the view (not a presenter, though) IS freed, so it's not completely broken.
I've only just started profiling today (firmly believing in not optimising too early), so I imagine there's some kind of reference floating around somewhere, but I can't see where, and what would be super helpful would be the ability to debug and see a list of objects that reference the target object. Is this at all possible, and if not natively, is there some light-weight way to code this into future apps for debugging purposes?
Cheers.
Assuming you are using Flex Builder, you could try the Profiler. In my experience, it's not so good for profiling performance, but it's been of great help for finding memory leaks.
It's not the most intuitive tool and it takes a while to get used to it (I mean, to the point where it actually becomes helpful). But, in my opinion, investing some time to at least learn the basics pays off. There's an enormous difference between just seeing how much memory the player is using globally (what System.totalMemory gives you, a very rough, imprecise and often misleading indicator) and actually track how many instances of each object have been created, how many are still alive and where were they allocated (so you can find the potential leak in the code and actually fix it instead of relying in black magic).
I don't know of any good tutorials for the FB profiler, but maybe this'll help to get you started.
First, launch the profiler. Uncheck performance profiling and check everything else (Enable memory profiling, watch live memory data and generate object allocation stack traces).
When the profiler starts, you'll see stats about the app objects, grouped by class. At this point, you might want to tweak filters. You'll see a lot of data and it's very easy to be overwhelmed. For now, ignore everything native to flash and flex stuff, if possible, and concentrate on some object that you think it should be collected.
The most important figures are "cumulative instances" and "instances". The first is the total number of instances created so far; the second, the number of said instances that are still alive. So, a good starting point is get your app to the state where the view you suspect that leaks gets created. You should see 1 for "cumulative instances" and "instances".
Now, do whatever you need to do to get to the point where this view should be cleaned up (navigate to other part of the app, etc) and run a GC (there's a button for that in the profiler UI). A crucial point is that you will be checking the app behaviour against your expectations -if that makes sense-. Finding leaks automatically in a garbarge collected environment is close to impossible by definition; otherwise, there would be no leaks. So, keep that in mind: you test against your expectations; you are the one who knows the life cycle of your objects and can say, "at this point this object should have been collected; if it's not, there's something wrong".
Now, if the "instances" count for you view goes down to 0, there's no leak there. If you think the app leaks, try to find other objects that might not have been disposed properly. If the count remains at 1, it means your view is leaked. Now, you'll have to find why and where.
At this point, you should take a "memory snapshot" (the button next to the Force GC button). Open the snapshot, find the object in the grid and double click on it. This will give you a list of all the objects that have a reference to this object. It's actually a tree, and probably each item will contain in turn a number of backreferences and so on. These are the objects that are preventing your view from being collected. In the right panel, also, you will an allocation trace. This will show how the selected object was created (pretty much like a stack trace).
You'll probably see a hugh number of objects there. But your best bet is to concentrate in those that have a longer life cycle than the object you're examining (your view). What I mean is, look for stage, a parent view, etc; objects on which your view depends on rather than objets that depend on your view, if that makes sense. If your view has a button and you added a listener to it, your button will have a ref to your view. In most cases, this is not a problem, since the button depends on the view and once the view is collect, so is the button. So, the idea is that since there are a lot of objects, you should try to stay focused or you will get nowhere. This method is rather heuristic, but in my experience, it works.
Once you find the source of a leak, go back to the source, change the code accordingly (maybe this requires not just changing code but refactoring a bit). Then repeat the process and check whether your change has caused the desired effect. It might take a while, depending on how big or complex is your app and how much you know about it. But if you go step by step, finding and fixing one problem at the time, you'll eventually get rid of the leaks. Or at least the worst and more evident ones. So, while a bit tedious, it pays off (and as a nice aside, you'll eventually understand what a waste of time is in most cases to use weak refs for every single event handler on the face of this earth, nulling out every single variable, etc, etc; it's an enlightening experience ;).
Hope this helps.
Flash GC uses a mix of ref counting and mark and sweep, so it does detect circular references. It seems rather you're having another reference in you object graph. The most common reason is, that the objects you want disposed still are having event handlers registered on objects that are not disposed. You could try to ensure that handlers are always registered with weak reference. You could also override addEventListener and removeEventListener in all (base) classes, if possible, to look which listeners are registered and whether there are chances for some not to be removed.
Also, you can write destructors for your objects, that for ui components clear graphics and remove all children, and for all objects, removes references to all properties. That way, only your object is kept in RAM, which shouldn't require much memory (a small footprint of 20 B or so, plus 4 B per variable (8 for a Number)).
greetz
back2dos
also a useful heuristics for finding memory leaks: http://www.tikalk.com/flex/solving-memory-leaks-using-flash-builder-4-profiler

What is the best approach to moving a preexisting project from Flash 7/AS2 to Flex/AS3?

I have a large codebase that targetted Flash 7, with a lot of AS2 classes. I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.
The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3. I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.
Has anyone tried porting a large codebase of AS2 code to AS3? How difficult is it? What kinds of pitfalls did you run into? Any recommendations for approaches to doing this kind of project?
Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3:
Package naming
class your.package.YourClass
{
}
becomes
package your.package
{
class YourClass
{
}
}
Imports are required
You must explicitly import any outside classes used -- referring to them by their fully qualified name is no longer enough.
Interface methods can't be labelled 'public'
This makes total sense, but AS2 will let you do it so if you have any they'll need to be removed.
Explicit 'override' keyword
Any functions that override a parent class function must be declared with the override keyword, much like C#. Along the same lines, if you have interfaces that extend other interfaces and redeclare functions, those overrides must be removed (again, as with public, this notation didn't make sense anyway but AS2 let you do it).
All the Flash builtin stuff changed
You alluded to this above, but it's now flash.display.MovieClip instead of just MovieClip, for example. There are a lot of specifics in this category, and I didn't get far enough to find them all, but there's going to be a lot of annoyance here.
Conclusion
I didn't get to work on this conversion to the point of success, but I was able in a matter of hours to write a quick C# tool that handled every aspect of this except the override keyword. Automating the imports can be tricky -- in my case the packages we use all start with a few root-level packages so they're easy to detect.
First off, I hope you're not using eval() in your projects, since there is no equivalent in AS3.
One of the things I would do is go through Adobe's migration guide (which is basically just an itemized list of what has changed) item by item and try to figure out if each item can be changed via a simple search and replace operation (possibly using a regex) or whether it's easier to just manually edit the occurrences to correspond to AS3. Probably in a lot of cases (especially if, as you said, the amount of code to be migrated is quite high) you'll be best off scripting the changes (i.e. using regex search & replace) and manually fixing any border cases where the automated changes have failed.
Be prepared to set some time aside for a bit of debugging and running through some test cases as well.
Also, as others have already mentioned, trying to combine AS2 SWFs with AS3 SWFs is not a good idea and doesn't really even work, so you'll definitely have to migrate all of the code in one project at once.
Here are some additional references for moving from AS2 to AS3:
Grant Skinners Introductory AS3 Workshop slidedeck
http://gskinner.com/talks/as3workshop/
Lee Brimelow : 6 Reasons to learn ActionScript 3
http://www.adobe.com/devnet/actionscript/articles/six_reasons_as3.html
Colin Moock : Essential ActionScript 3 (considered the "bible" for ActionScript developers):
http://www.amazon.com/Essential-ActionScript-3-0/dp/0596526946
mike chambers
mesh#adobe.com
My experience has been that the best way to migrate to AS3 is in two phases - first structurally, and second syntactically.
First, do rounds of refactoring where you stay in AS2, but get as close to AS3 architecture as you can. Naturally this includes moving all your frame scripts and #include scripts into packages and classes, but you can do more subtle things like changing all your event listeners and dispatchers to follow the AS3 flow (using static class properties for event types, and registering by method rather than by object). You'll also want to get rid of all your "built-in" events (such as onEnterFrame), and you'll want to take a close look at nontrivial mouse interaction (such as dragging) and keyboard interaction (such as detecting whether a key is pressed). This phase can be done incrementally.
The second phase is to convert from AS2 to AS3 - changing "_x" to "x", and all the APIs, and so on. This can't be done incrementally, you have to just do as much as you can in one fell swoop and then start fixing all the compile errors. For this reason, the more you can do in the first phase, the more pain you avoid in the second phase.
This process has worked for me on a reasonably large project, but I should note that the first phase requires a solid understanding of how AS3 is structured. If you're new to AS3, then you'll probably need to try building some of the functionality you'll need to be porting. For example, if your legacy code uses dragging and drop targets, you'll want to try implementing that in AS3 to understand how your code will have to change structurally. If you then refactor your AS2 with that in mind, the final syntax changes should go smoothly.
The biggest pitfalls for me were the parts that involved a lot of attaching, duplicating and moving MovieClips, changing their depths, and so on. All that stuff can't really be rearchitected to look like AS3; you have to just mash it all into the newer way of thinking and then start fixing the bugs.
One final note - I really wouldn't worry about stuff like import and override statements, at least not to the point of automating it. If you miss any, it will be caught by the compiler. But if you miss structural problems, you'll have a lot more pain.
Migrating a bigger project like this from as2 will be more than a simple search and replace. The new syntax is fairly similar and simple to adapt (as lilserf mentioned) but if nothing else the fact that as3 is more strict and the new event model will mostly likely cause a lot of problems. You'll probably be better off by more or less rewriting almost everything from scratch, possibly using the old code as a guide.
Migrating from as2 -> as3 in terms of knowledge is fairly simple though. If you know object oriented as2, moving on to as3 won't be a problem at all.
You still don't have to use mxml for your UI unless you specifically want to. Mxml just provides a quick way to build the UI (etc) but if you want to do it yourself with actionscript there's nothing stopping you (this would also probably be easier if you already have that UI in as2 code). Flex (Builder) is just a quick way to do stuff you may not want to do yourself, such as building the UI and binding data but essentially it's just creating a part of the .swf for you -- there's no magic to it ;)

Resources