When to define a GTK class, when to use signals? - c

I'm fairly new to GTK, and am messing around with my first "serious" GTK (gtk+-3) app. I'd like to draw on the wisdom of others' experience about when it's suitable to define a new GTK class, or just use a "vanilla" GTK classes, and implement behaviour via signal handlers.
I've come across two examples so far:
Custom Widgets
I'm creating a new widget: basically a GtkDrawingArea, which I use to display some data. I had originally assumed that the best way to implement this would be to subclass GtkDrawingArea, using G_DEFINE_TYPE, and provide my own draw callback:
static void mywidget_class_init(MyWidgetClass *klass)
{
GTK_WIDGET_CLASS(klass)->draw = mywidget_draw;
}
However, it looks like I could implement exactly the same functionality without defining a new type, by just creating a vanilla GtkDrawingArea, and hooking up the appropriate signals during initialisation.
[My custom widget will eventually provide more than just the draw callback, as it needs to be interactive, but that comes later...]
Application Windows
My application consists of a few different windows, which currently are vanilla GtkWindows:
struct myapp_somewindow {
struct myapp *app;
GtkWindow *window;
GtkWidget *some_label_that_is_updated;
/*... other window-specific fields */
}
When the myapp_somewindow struct is initialised, I create the GtkWindow with gtk_window_new(), and initialise the widgets/layouts/etc, and connect the signals. [I'll probably be using .ui files for the more complex cases eventually, but the windows are simple enough for now.]
This could be done my defining a new subclass of GtkWindow, but I'm not certain when the code overhead of defining the new class becomes worthwhile.
I'm aware that there's probably no strict rules for which approach to take, but are there any general guidelines to use when making these design decisions? Are there any major pitfalls of either approach?

I've worked on a fair few projects using GTK+ and Clutter and i've always promoted heavy use of subclassing of generic widgets / actors to more specific ones.
By convention with GObject you create a new file for each class and thus if you pull in the behaviour and state mechanics associated with your widget into a subclass you will pull that code into a separate file. This helps make it easier to structure your code and helps when someone else wants to come along and read it.
The subclassing strategy also helps you enforce encapsulation as a good practice on your code base. If your widgets and their associated state and logic are well encapsulated then that can help with reuse.
A good example of a project where this subclassing strategy has been used is tasks, and in particular it's internal helper library: http://git.gnome.org/browse/tasks/tree/libkoto This meant that when we wanted to port the application to a new platform or provide a different view on the data it was quite easy to just glue the existing widgets and tree models together in a different way.
If you want to use C and you find subclassing a bit tedious then you can try this tool: http://git.gnome.org/browse/turbine/ to help automate the creation of your subclasses.

I would use the guideline of defining a new class when you need to save some state for the widget. Otherwise, you'll end up creating custom structures holding that state to pass as user data to the signal handlers, making your code more complicated and creating more opportunities for memory leaks.
That would suggest that for your second use case, application windows, you should always define a new class.
One reason to do it this way is that your widget might start out simple, with behavior that you can implement purely with signal handlers, but later might become more complicated. For example, suppose you want to add a backing store to your drawing area. The "perceived cost" of refactoring your simple widget into a class is high, whereas it'll make your code much cleaner than working around it.
Another advantage is that classes can have properties. You can bind these properties to other classes' properties or to GSettings keys, which is a really powerful mechanism and can make your code really simple.
If you don't like all the class boilerplate, consider programming in Vala.

Related

How does XML document work with GTK to create user interface?

I am working on a C/GTK+3 project right now. I have a little experience with front end but mostly only with Android. Even then that was VERY LITTLE experience.
I notice that in the C code I place objects and set properties (like if a textview is editable etc). I also have been able to connect a .ui XML file to my program with the builder functions.
I am wondering how the XML file gets linked to the C code defining the interface. Does it match by structure, by the name or ID properties? Why are properties like "visible" and "editable" present in both the C code and the XML? Do you need the XML file? Do you need to specify the properties in both the XML file and the C code or just one? Will I ever completely understand front end development?
There's two ways of constructing a user interface:
You write the code for it.
You write a file that describes the user interface, and have the user interface built for you at runtime.
If you write the code yourself, everytime you want to move widgets around, you have to modify your code, that you'll need to compile. That is doable for a small UI, and is what is done in most tutorials.
If you use ui files, then you use the Glade application to design your UI graphically, and it will write the UI files for you. This helps in splitting responsabilities too: you may have design people taking care of the UI, and let developpers focus on the behavior. Even without that, you'll be able to design a UI faster with an editor like Glade than by coding it by hand. Think you skip all the compile/debug cycles.
In your ui file, if you name a wigdet "bob", you'll be able to get it in your code by passing its name to gtk_builder_get_object. GtkBuilder takes care of the construction and the memory, so don't destroy the widgets it creates if you need to display them again, and hide them instead.
You have examples of use of UI files in the GTK documentation:
https://developer.gnome.org/gtk3/stable/ch01s04.html#id-1.2.3.12.5

Replacing 3rd party Windows Forms UI controls in a large codebase

Me and my colleagues are investigating how to replace 3rd party WinForms controlls by our new UI controls in our large legacy codebase. Practically we would like to replace the 3rd party controlls in the inheritance chain. The 3rd party controlls are used dozens of places by subclassing the 3rd party UI controlls. We d like to perform this change as safety as possible, with minimal code change all over the solution. Do you have any experience how to start? Obviously the inheritance means strong coupling here, so i d like to find the less painful solution here.
Is the "branch by abstraction" concept applicable here?
This is a pretty subjective decision based on your team's understanding of the code base as well as workflow. The bright side is that you've already subclassed all the controls, so you've already done the tedious work of being able to provide whatever properties the code is looking for to compile.
Given that this is WinForms, this should be much more straightforward, since the control sizes and locations are set on the Control level. You need to worry about mapping properties/methods that exist in the old vendor's controls to your new controls and not as much about form layout. This might be straightforward for some controls and more complex for others (i.e. grids).
The biggest roadblock IMO is going to be handling the current design-time serialized logic in InitializeComponent. If you've created a property to map from old -> new, you're going to have to be careful that when the designer re-serializes everything after you open the form and modify something, you might not want to serialize both the old property and the new. As an example:
Old Vendor
this.myOldComponent.Data = this.dataSource;
New Vendor
this.myNewComponent.DataSource = this.dataSource;
In this case, you may consider creating a new property called Data on your subclassed new component so that the old code works without changing anything. Let's say you open the form in the designed and move the grid a few pixels, causing the designer to serialize the data. You might now have:
this.myNewComponent.Data = this.dataSource;
this.myNewComponent.DataSource = this.dataSource;
You can prevent serialization with attributes (good discussion on it in this SO question, but this is just an example of something you might hit.
I don't think there's really a pattern here to follow, unless you mean on the source control level, in which case I would say to absolutely create a new branch apart from your regular development one; who knows what kinds of roadblocks you may hit and you'd want to shelve your work for a bit.
Ultimately, you may decide that it's just best to suck it up and rip out the old components and put in the new, but as mentioned this is very subjective. It's situations like this that make me really love WPF and the MVVM model, since you could entirely rip out the UI and keep the business logic intact.

How to reuse array of items collection in Ext Js widgets?

I'm using Ext Js 4.1.1.
In many of the Ext JS widgets I am using, I am required to reuse data. For example, the items collection for buttongroup in top toolbar may be repeated in menu bar on the left side. For manageability, I should be able to have the array for items collection defined in a separate file (which could potentially follow the class naming convention for auto loading).
The approach I tried is that I am creating a class that has statics. Each static function returns an array that can be assigned to items collection of the widget. This works but I believe that using a class is an overkill if I can just use an array. Any suggestions?
Not sure if it will be useful to create separate objects for storing configuration for toolbars, buttons groups and etc. In the context of the extjs in almost all cases you need not only manage configuration but also behavior of a component.
The best way for me here - creation of generic/basic predefined classes, where you can state not only configuration but work around the behavior, add you'r custom events and process any unexpected results. After it you can easily reuse and extend it easily.
For instance you have a menu or a toolbar with 3 items A, B, C. For sure you need to know wherever you use it what was clicked (for instance) A, B or C. Creating a class and manages required events you can fire you own events which will tell you what was clicked and it is much easier to use in any context where this component will be used. Add post and pre processing, template methods and etc...
Creating a big file just with configuration is not readable and not extendable, will be a case whre you will need to add functionality and behavior to all such generic components and it will be not easier to do with just arrays or simple configs. Separating even just simple general components having just simple configuration (in the beginning) will bring more expressive in the code structure and readability and in the later time gives you the power to manage it.
Pure configurations can just keep the code accurateness and re-usability but what about behavior for in almost cases you need to control..
The design, maintainability and extensibility are very important points in every big web-applications and in context of extjs 4.

How would you work with "MDI-ness" in an application that wants to use the MVP pattern?

The situation: MainForm (assigned to the MainPresenter) is up and running. The user click a ShowFoo button - an event is passed to the MainPresenter which in turn creates new FooPresenter and the FooView. How should I proceed now ? Where should the presenter be created and where should the view be created and most importantly, where should the MDIParent property be set ? (so fat I kind of think that should be done in the main view.
Notes: I am using a dependency framework, though that is quite irrelevant to the problem. Ideally I would like the IView to independent of the Form class.
The way I would handle it have a function off of the MainPresenter interface that allows me to create a FooPresenter (as well as a Foo2Presenter, etc). THe MainPresenter has all the information inside of it to properly setup a child form of the MDI parent. Hence why it makes sense to have it there.
An alternative is to have a AppPresenters class that has the MainPresenter and the FooPresenter as properties or functions. Here the AppPresenters hold the presenter classes as well takes on the responsibility for tying the forms together to have a proper MDI application. The implication of this approach is the fact the application is a master/parent form with a bunch of child forms is not reflected in the design of your interfaces.
The differences between the two approaches is minimal in my opinion. Both could be adapted to a different style of UI readily. So go which on makes better sense for you and your application.

Best place to bring up new window in Model View ViewModel

I have an MVVM application. In one of the ViewModels is the 'FindFilesCommand' which populates an ObservableCollection. I then implement a 'RemoveFilesCommand' in the same ViewModel. This command then brings up a window to get some more user input.
Where/what is the best way to do this whilst keeping with the MVVM paradigm? Somehow
doing:
new WhateverWindow( ).Show( )
in the ViewModel seems wrong.
Cheers,
Steve
I personally look at this scenario as one where the main window view model wants to surface a task for the end user to complete.
It should be responsible for creating the task, and initializing it. The view should be responsible for creating and showing the child window, and using the task as the newly instantiated window's view model.
The task can be canceled or committed. It raises a notification when it is completed.
The window uses the notification to close itself. The parent view model uses the notification to do additional work once the task has committed if there is followup work.
I believe this is as close to the natural/intuitive thing people do with their code-behind approach, but refactored to split the UI-independent concerns into a view model, without introducing additional conceptual overhead such as services etc.
I have an implementation of this for Silverlight. See http://www.nikhilk.net/ViewModel-Dialogs-Task-Pattern.aspx for more details... I'd love to hear comments/further suggestions on this.
In the Southridge realty example of Jaime Rodriguez and Karl Shifflet, they are creating the window in the viewmodel, more specifically in the execute part of a bound command:
protected void OnShowDetails ( object param )
{
// DetailsWindow window = new DetailsWindow();
ListingDetailsWindow window = new ListingDetailsWindow();
window.DataContext = new ListingDetailsViewModel ( param as Listing, this.CurrentProfile ) ;
ViewManager.Current.ShowWindow(window, true);
}
Here is the link:
http://blogs.msdn.com/jaimer/archive/2009/02/10/m-v-vm-training-day-sample-application-and-decks.aspx
I guess thats not of a big problem. After all, the Viewmodel acts as the 'glue' between the view and the business layer/data layer, so imho it's normal to be coupled to the View (UI)...
Onyx (http://www.codeplex.com/wpfonyx) will provide a fairly nice solution for this. As an example, look at the ICommonDialogProvider service, which can be used from a ViewModel like this:
ICommonFileDialogProvider provider = this.View.GetService<ICommonDialogProvider>();
IOpenFileDialog openDialog = provider.CreateOpenFileDialog();
// configure the IOpenFileDialog here... removed for brevity
openDialog.ShowDialog();
This is very similar to using the concrete OpenFileDialog, but is fully testable. The amount of decoupling you really need would be an implementation detail for you. For instance, in your case you may want a service that entirely hides the fact that you are using a dialog. Something along the lines of:
public interface IRemoveFiles
{
string[] GetFilesToRemove();
}
IRemoveFiles removeFiles = this.View.GetService<IRemoveFiles>();
string[] files = removeFiles.GetFilesToRemove();
You then have to ensure the View has an implementation for the IRemoveFiles service, for which there's several options available to you.
Onyx isn't ready for release yet, but the code is fully working and usable at the very least as a reference point. I hope to release stabilize the V1 interface very shortly, and will release as soon as we have decent documentation and samples.
I have run into this issue with MVVM as well. My first thought is to try to find a way to not use the dialog. Using WPF it is a lot easier to come up with a slicker way to do things than with a dialog.
When that is not possible, the best option seems to be to have the ViewModel call a Shared class to get the info from the user. The ViewModel should be completely unaware that a dialog is being shown.
So, as a simple example, if you needed the user to confirm a deletion, the ViewModel could call DialogHelper.ConfirmDeletion(), which would return a boolean of whether the user said yes or no. The actual showing of the dialog would be done in the Helper class.
For more advanced dialogs, returning lots of data, the helper method should return an object with all the info from the dialog in it.
I agree it is not the smoothest fit with the rest of MVVM, but I haven't found any better examples yet.
I'd have to say, Services are the way to go here.
The service interface provides a way of returning the data. Then the actual implementation of that service can show a dialog or whatever to get the information needed in the interface.
That way to test this you can mock the service interface in your tests, and the ViewModel is none the wiser. As far as the ViewModel is concerned, it asked a service for some information and it received what it needed.
What we are doing is somethng like that, what is described here:
http://www.codeproject.com/KB/WPF/DialogBehavior.aspx?msg=3439968#xx3439968xx
The ViewModel has a property that is called ConfirmDeletionViewModel. As soon as I set the Property the Behavior opens the dialog (modal or not) and uses the ConfirmDeletionViewModel. In addition I am passing a delegate that is executed when the user wants to close the dialog. This is basically a delegate that sets the ConfirmDeletionViewModel property to null.
For Dialogs of this sort. I define it as a nested class of the FindFilesCommand. If the basic dialog used among many commands I define it in a module accessible to those commands and have the command configure the dialog accordingly.
The command objects are enough to show how the dialog is interacting with the rest of the software. In my own software the Command objects reside in their own libraries so dialog are hidden from the rest of the system.
To do anything fancier is overkill in my opinion. In addition trying to keep it at the highest level often involving creating a lot of extra interfaces and registration methods. It is a lot of coding for little gain.
Like with any framework slavish devotion will lead you down some strange alleyways. You need to use judgment to see if there are other techniques to use when you get a bad code smell. Again in my opinion dialogs should be tightly bound and defined next to the command that use them. That way five years later I can come back to that section of the code and see everything that command is dealing with.
Again in the few instances that a dialog is useful to multiple commands I define it in a module common to all of them. However in my software maybe 1 out of 20 dialogs is like this. The main exception being the file open/save dialog. If a dialog is used by dozens of commands then I would go the full route of defining a interface, creating a form to implement that interface and registering that form.
If Localization for international use is important to your application you will need to make sure you account for that with this scheme as all the forms are not in one module.

Resources