Showing posts with label new. Show all posts
Showing posts with label new. Show all posts

Monday, June 13, 2016

How to Keep a Secret

If your program needs to ask the user for a password, e.g. to connect to a web site or a database, chances are that it proposes a way to remember this password and not have to enter it the next time. This is convenient for the users, but is quite difficult to implement in any more or less secure way and a lot of programs end up storing the passwords in plain text, or something almost indistinguishable from it, e.g. base64-encoded string, in wxConfig.

But now wxWidgets provides a better way to do it with the new wxSecretStore class. It is still as simple to use as wxConfig but uses the OS-provided password storage facility such as Microsoft Windows credentials vault or OS X keychain, for storing the secrets you confide to it. Here is how you would normally use it:

Currently there is not much more that can be done with this class, the only functionality not illustrated by this example is deleting a previously stored secret, but in the future we could extend it, notably to provide a way to also ask the user to enter the password using the OS-provided dialog. Let us know if you use wxSecretStore and if you see possible improvements, please don't keep them secret!

Friday, April 01, 2016

Improving Inherently Important Internationalisation Issues

One of the lesser-known advantages of wxWidgets compared to many other libraries is that, using its API, you can centre a window on the screen and set its colour to grey without having to Americanise your programme. But, as natural as this behaviour is, and in spite of agreeing to wxWidgets licence (the very spelling of which should have been a sufficient hint), some users still expressed their surprise in their dialogue with us and refused our advice to accept using this flavour of the API. And so, to accommodate them, wxWidgets has traditionally provided alternatives such as Center() method, wxColor class and wxGRAY constant.

Admittedly, in practice this has been sufficient to avoid any problems for a long time while still remaining true to wxWidgets historically British roots. However, in addition to being British, wxWidgets was always mostly a European effort and, besides, knowing that it was actually born in Edinburgh, it might well end being exclusively European and not British at all in the near future (but don't worry, even if the worst happens, we plan to continue supporting British spelling for at least two more release cycles, in accordance with the general backwards compatibility policy). Considering this, it seems especially strange to have alternative American versions of the spelling, but no attention being paid to the other European languages.

And now, after releasing 3.1.0, it's finally time to do something about it as, clearly, there are few unresolved issues of comparable importance left. To begin with, I obviously had to add wxCouleur class which should undoubtedly help with wxWidgets adoption in francophone countries. But adding just the French variant would certainly be undiplomatic, so another pull request adds, in the grand European tradition of Franco-German alliance, wxFarbe, and both of them will be merged together to avoid any questions of precedence. Further, France and Germany notwithstanding, I certainly don't plan to discriminate against other countries but, in the usual spirit of Open Source, additions of wxColore, wxFarve, wxKleur etc will have to wait until the appropriate patches are submitted (luckily for them, Spanish users can, in the meanwhile, already reuse the American variant, just as they already do with many other words, e.g. burrito, for the classic American food).

Of course, nothing is ever as simple as planned and, while working on this, I quickly realized that Greek might present some practical difficulties as UTF-8 support is still, even in 2016, not perfect on some of the legacy platforms supported by wxWidgets, but it would be difficult to use wxΧρώμα without it. A compromise solution that we're currently discussing would be to introduce a wxChroma class right now and deprecate it by the time 3.2 is released as Unicode support should really be widely available everywhere by then (3.2 release is currently planned for the early 2030-ies).

I do hope you will enjoy these changes, but, let's be honest, this is just the beginning and we clearly still have a lot of work to do in this area. Fully supporting colour internationalization is important, but it's just the first step and we plan to go much further. Just imagine to be able to open a wxFenêtre and choose a wxStylo for drawing on it and then, perhaps if you live in Switzerland, create a wxKnopf as its child. The possibilities are endless! Unfortunately, the same can't be said about our resources, so we count on your help to make wxWidgets the best internationalized library of all time -- and we're looking forward to your contributions!

Thursday, September 11, 2014

GSoC 2014 summary: Windows task bar API project

This is the first in a series of posts about wxWidgets GSoC 2014 projects and it is about Chaobin Zhang's work on wrapping Windows taskbar API for the use in wxWidgets. The project was a success and I'd like to congratulate Chaobin and thank him and Bryan Petty, who was the mentor on this project, for their work!

The new API additions and things they allow to do are described in more details in Chaobin's own post here, please read it for more information, but, in short, almost all taskbar features are now accessible via wxWidgets API.

Of course, they still remain unportable and Windows-only and while it's better to provide access to them than not do it at all, the main goal of wxWidgets is to facilitate writing portable applications and so the next target is to build a higher level API which would be available elsewhere. We have made a start with wxAppProgressIndicator and wxGA_PROGRESS style for wxGauge using it, but this is still not implemented for any other platform yet. Any contributions implementing this (simple) class in terms of NSProgress under OS X or ideas about how it could be implemented under Linux would be very welcome.

Thursday, July 24, 2014

Easier way to avoid dependencies on the system installed libraries

When you build wxWidgets under Unix, configure script will by default try using the system versions of the third party libraries, such as libpng, libjpeg, libtiff and so on. Usually this is the right thing to do, as you avoid compiling (potentially a lot of) code which already exists in the ready to use binary form on your system and, more importantly, use exactly the same version of these libraries as other libraries wxWidgets links with, notably GTK+ ones.

However, sometimes you may want to avoid using the system libraries, e.g. because you want to build a statically linked version of your program with as few dependencies as possible. This was always possible by explicitly disabling the use of each and every library with -with-libfoo=builtin, but this was relatively tiresome and it was easy to forget a library or two.

To remedy this, I've just added a new --disable-sys-libs configure option which does exactly what it says: when it is specified on configure command line, only the built-in versions of the third party libraries will be used. This can be useful in the above mentioned static linking scenario under Linux but is probably most valuable under OS X where you never want to have dependencies on any locally installed (e.g. via Homebrew or MacPorts) libraries as this would make the resulting binary impossible to run on other OS X machines.

To summarize, it's a tiny feature, but one which would probably go unnoticed in the 3.1 release change log while I think it could be something useful to quite a few people.

Wednesday, May 01, 2013

Simpler way to create fonts

Just a quick note about the new and simpler way to create fonts in wxWidgets 2.9: in addition to a multitude of wxFont constructors taking various font attributes, such as size, style, weight, face name and so on, there is now another constructor, taking a single wxFontInfo object that combines all of them together and allows to use the named parameter idiom for the font creation.

It may seem non-obvious how can adding another constructor help with the problem of having too many constructors, so here is a quick example to show how it does: suppose you want to create an underlined, 12 point version of "Courier" font. Here is how you'd do it currently:

wxFont f(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, true, "Courier");
And here is how you'd do it with the new constructor:
wxFont f(wxFontInfo(12).Underlined().FaceName("Courier"));

Hopefully the advantages from the point of view of the library user are clear:

  • You don't need to specify the default parameters such as wxFONTFAMILY_DEFAULT, that you don't care about.
  • Each font attribute is clearly written out, while the meaning of true (which meant that the font should be underlined, by the way) was hardly obvious in the first form.
  • You can specify the parameters in any order instead of having to check the documentation every time.
  • Last and really least but still: you can create strike-through fonts (notice that they are only supported under MSW and GTK currently) using the new constructor using the natural Strikethrough() syntax, while this wasn't supported at all with the old constructor.
From our, i.e. developers, point of view, there is one extra important advantage, related to the last point: if support for a new wxFont attribute is added later, this way of creating fonts will be easy to extend to support it.

So my advice is to use wxFontInfo in all the new code using wxWidgets 2.9. The old constructors are not going anywhere and can still be used (except for the one taking int flags which was added for 2.9.4 and now removed to avoid ambiguities with the other existing constructors), but there is no reason to prefer them to the new one.

Sunday, January 20, 2013

About the benefits of procrastination

And no, I'm not going to speak about why postponing 2.9.5 release for so long after its initially scheduled October 2012 release date is a good thing. Instead, I'd like to explain how can the recently added CallAfter() function make your life simpler.

CallAfter() is a method of wxEvtHandler, which means that it's available in the code of any classes deriving from it, including wxWindow but also wxApp and several others. And it basically allows to call another method of the class in which it is used asynchronously later. Notice that no threads are involved, the call to that other method still happens on the same main GUI thread but at a slightly later time. To be precise, the control first must return to the event loop and only then (i.e. "after") the specified method will be called.

Using it is quite simple: if you want to call some method Foo() taking 0, 1 or 2 arguments (this is the current maximum but it could be extended in the future if really needed), you can just write

void SomeWindow::OnSomeEvent(wxEvent& event) { // If the method doesn't take any arguments: CallAfter(&SomeWindow::Foo); // If the method takes an argument: CallAfter(&SomeWindow::Foo, arg1); // Or if it takes two: CallAfter(&SomeWindow::Foo, arg1, arg2); }
Notice that Foo() must be a method of the same class. But other than that, this is pretty straightforward.

The above explains how to use CallAfter() but doesn't answer the really interesting question which is, of course, why would you ever want to do this instead of just calling Foo() directly? The answer is that some things often just can't be done immediately in a GUI program, either because doing them would interfere with its normal flow of control and generate extra events, potentially resulting in unexpectedly re-entering the same event handler and infinite recursion. Or because the current state of the program simply doesn't allow them. An example of the first case is showing a message box from a window activation event handler: doing this would immediately deactivate the window back again which is probably unexpected. An example of the second case is showing a message box from event handlers for all events generated by mouse click, e.g. button press event: as the mouse is captured by the button when the click happens, its mouse grab is released unexpectedly and the standard control itself can get confused by it, e.g. the button could appear to be stuck in pressed state.

The message box example is actually a poor one because wxWidgets already provides an easy way to prevent such problems from happening by using wxLogMessage() function which already postpones showing the message box until the next event loop iteration. What CallAfter() does is to provide you with a generic way to do the same thing very simply.

As a more realistic example, let's consider a common GUI layout with a tree control on the left and some window displaying the items in the tree on the right. Suppose you'd like to update the display when a tree item is double-clicked. There is a wxEVT_COMMAND_TREE_ITEM_ACTIVATED event corresponding to this action so typically you'd do something like this:

TreeViewFrame::TreeViewFrame() { wxTreeCtrl* tree = new wxTreeCtrl(this, ...); tree->Bind(wxEVT_COMMAND_TREE_ITEM_ACTIVATED, &TreeViewFrame::OnActivated, this); // This is the window showing the current item. m_view = new ViewWindow(this); DisplayItem(initial); } void TreeViewFrame::OnActivated(wxTreeEvent& event) { ... retrieve the item to show from the event (typically using client data) ... DisplayItem(item); } void TreeViewFrame::DisplayItem(ItemType item) { m_view->ShowItem(item); // Give the focus to the view to allow the user to easily use the keyboard. m_view->SetFocus(); }
And this works perfectly well except that the view doesn't get the focus after double clicking an item in the tree under Windows. The reason for this is that the native tree control there sends the activation event first and then processes the (second) mouse click which resulted in it itself, and as part of this processing it sets the focus to the control itself (as it's normal for the control to become focused when clicked). So while the view does get focus during the activation event handler execution, it loses it almost immediately afterwards.

In a perfect world, wxWidgets would somehow isolate you from this peculiarity of Windows tree control implementation. But doing this is rather not trivial and, remember, this is just one of several examples. So in the imperfect world we live in, you need to deal with this problem at your application level. CallAfter() reduces the imperfectness of having to do it to acceptably low level as all you need to change in the snippet above to make it work is to replace the last line of the event handler with the call to it:

void TreeViewFrame::OnActivated(wxTreeEvent& event) { ... retrieve the item to show from the event (typically using client data) ... CallAfter(&TreeViewFrame::DisplayItem, item); }
All we did was to delay the item display until the next event loop iteration after the one which dispatched the activated event itself and this is enough to get rid of the focus problem.

So if you have any capture, focus or other global state problems (and notice that they can stem from your own code as well, and not just behaviour of the native controls or wxWidgets itself), you can often use CallAfter() to easily solve them by just postponing whatever you need to do until slightly later. Remember that laziness is a cardinal virtue for a programmer -- and now wxWidgets helps you to cultivate it!


P.S. But we'll still try to release 2.9.5 soon...

Monday, April 18, 2011

Using dynamic auto-completion in text controls

wxTextEntry supports auto-completion of a fixed of strings in wxWidgets 2.9 since quite some time however so far you had to specify the full of set of strings to complete and, incidentally, this didn't work under OS X meaning that one of three major platforms didn't support auto-completion at all.

Lack of support of OS X aside, this is a useful feature which helps the users a lot with the data entry. For example, it is typically used to keep the history of previous entries in a text control and auto-complete the entries used in the past automatically. And for this the existing AutoComplete() worked fine. Sometimes, however, using a fixed set of strings is impractical. A typical example is trying to complete the results of some database queries: there can be a lot of them and it can be wasteful to get all the results from the database. It would be much better to be able to dynamically retrieve just the completions for the prefix already entered by user.

And this is exactly what the newly added wxTextCompleter class and wxTextEntry::AutoComplete() overload taking it allows to do. A text completer object can dynamically generate the completions using the prefix already by the user, either by overriding Start() and GetNext() methods of wxTextCompleter itself or by overriding the single GetCompletions() method of wxTextCompleterSimple class. The widgets sample was updated to show how to do it and the documentation of wxTextCompleterSimple also contains a simple example and hopefully the new API should be clear enough to be used without problems.

As usual, things could be improved further: for one, even though the new dynamic auto-completion is implemented under MSW and OS X, it is not implemented under GTK yet. It shouldn't be difficult to do it by defining a GtkTreeModel forwarding to wxTextCompleter and using it with GtkEntryCompletion but this still remains to be done. Also, under OS X the completion currently needs to be triggered manually by pressing F5 and doesn't appear automatically. This is the native behaviour but it doesn't seem to be particularly useful so we'd need to make it appear automatically. As usual, any contributions implementing either of those improvements would be gratefully received by wxWidgets project so don't hesitate to help if you'd like to use the missing features in your programs.

But even in the current state, you can easily define custom dynamic text completers and also use fixed lists of completion strings under all of the major platforms now.

Tuesday, February 22, 2011

Markup in control labels

As I'm hopelessly out of date with my planned updates anyhow, I've decided to write a brief post about a nice new feature that was recently added to wx instead:

This feature is the possibility to use Pango-like markup in some wxWidgets controls, notably wxButton and wxStaticText. This means that it is now possible to write
wxButton *b = new wxButton(parent, wxID_ANY, "");
b->SetLabelMarkup("<span size='x-large' color='blue'>Big</span> <b>bold</b> button");
and it will indeed behave as expected:
MSW button with markup OS X button with markup GTK+ button with markup

Currently this works for wxButton in all major ports and for the wxGTK and the generic versions of wxStaticText (that can be used under all platforms if this feature is important). The plan is to extend this to more controls later, e.g. wxCheckBox, wxRadioButton or wxStaticBox and maybe even allow using markup for the items of controls with multiple items such as wxListBox or wxComboBox. There is however no definite schedule for this so if anybody is interested in using markup with these controls, please consider helping with implementing it, it should be pretty simple to do by simply copying wxButton behaviour.

Monday, July 13, 2009

Blogging about logging

I've just finished a series of changes which were meant to make wxLog less embarrassing and more useful. Of course, wxLog was always meant to be a simple logging framework adapted for typical logging patterns of GUI applications but there is such thing as being too simple and it became apparent since quite some time that wxLog was insufficient for any kind of application using multiple threads or even simply separated in multiple components whose logging should be controlled simultaneously. And as most applications nowadays do use multiple threads, this is a serious limitation indeed.

As an aside, when I realized that the deficiencies of wxLog really prevented it from being useful in the application I was working on, my first idea was not to enhance it but to switch to another, dedicated logging library. But incredibly enough I couldn't find any good candidate: there are tons of libraries based on log4j but translating Java API in C++ is really not a good idea and I hoped to find something more idiomatically C++-ish. So I naturally turned towards Boost and found not one but two libraries named "Boost.Log", with one even confusingly called "Boost.Log v2" despite being older than the other one. Unfortunately, while both of them are undoubtedly great libraries, I was completely overwhelmed by their complexity. They are certainly great and allow some things I wouldn't even think of if I were creating a new logging library from scratch, e.g. a possibility to associate a decrementing counter starting from 100 with step of -5 with every log record which is extremely impressive but also doesn't seem to be especially useful in practice and I'd prefer to just simply use a logging library instead of admiring its marvellous elegance. So I passed them too -- and decided that while wxLog might be too simple, keeping it simple enough was still very important.

With this in mind, I decided to simply fix the few most glaring omissions in wxLog:
  1. Lack of support for logging from threads other than main.
  2. Impossibility to treat logs from different parts of application differently.
  3. Absence of __FILE__, __LINE__ and __FUNCTION__ information.
The first one was already solved for some logging targets, e.g. wxLogWindow was already thread-safe as it collected the messages coming from other threads and really displayed it in its text control only during the idle time from the main thread. All I did was to extend this approach to all log targets by moving its implementation in wxLog itself.

This does introduce a new problem however: as the messages are buffered instead of being output immediately, they could be lost if the program crashes before the main thread has a chance to output them. So I also added a concept of per-thread log targets which can be associated with a single thread only and don't need to do any buffering. Of course, such target can't show messages to the user -- as this can only be done from the main GUI thread -- but it can log them to a file and so a thread can always set up wxLogStderr or a wxLogStream to ensure that its messages are saved in a file as soon as they are output.

On a related note, using wxLogNull (and wxLog::EnableLogging() which it uses internally) now only disables logging for the current thread and not the application as a whole. This makes sense as if you just want to suppress an error message from a wxWidgets function you're going to call, you shouldn't disable all the logs from the other threads of your application which can be doing something completely unrelated while this function is executing. The initial plan was to also add a new way of disabling the logging globally but after thinking about it for quite some time I couldn't find any realistic use case when doing this would be really useful so for now logging can only be enabled thread-wise -- but we can always make it possible to disable it either globally or, which probably makes more sense, on log target basis, if really needed.



The second problem was solved by introducing the notion of "log components". These are simply arbitrary strings which identify the component which logged a message. By default, messages logged by wxWidgets come from the log component "wx" and its subcomponents, that is strings starting with "wx/" like, for example, "wx/net/ftp", while messages generated outside of wxWidgets have empty log component as it's not defined by default. This is already useful as sometimes you may want to treat wxWidgets and your own messages differently, e.g. you could disable all non-error messages from wxWidgets by setting the log level of the "wx" component to wxLOG_Error while keeping all messages, including the debugging ones, from your code enabled. But this feature becomes really useful mostly when you do define your own custom log components. This is done simply by #define-ing wxLOG_COMPONENT before using wxLogXXX() functions. It can be done on the compiler command line (to ensure that the same value is uniformly used everywhere) or inside the source files. In either case you will probably want to use different values for different parts of your application, e.g. "myapp/ui" and "myapp/db" and "myapp/network" and so on. And then you can independently configure the log level for each module and, also importantly, you can distinguish between the messages logged by different components and send them to different final destinations (e.g. database-related messages to one log file and network ones to another) from your overridden wxLog::DoLogRecord().

Finally, to solve the last problem in the list, all wxLogXXX() functions have been replaced by macros with the same names, which allows to record the information about the log message location. It can be retrieved from DoLogRecord() from the wxLogRecordInfo struct passed to it. By default, this information is not used in any of the predefined loggers (yet?) but it's available in case you nee it.

Moreover, in process of doing this, I actually created a relatively generic mechanism for passing arbitrary extra information to the log functions -- but, still remembering my experience of reading Boost.Log documentation, I decided to not make it public for now and to keep things simple.

After all, with the additions mentioned above wxLog is already much more useful and hopefully it's good enough for even complex wxWidgets applications now. And if not, we'd be interested to hear about still missing features, of course, so do have a look at the improved wxLog version in svn trunk and let us know what do you think!