GTK/C sharing data and variables between functions - c

The problem is: what's the best way to share data between functions, but specifically in GTK/C application? The best means the most 'proper', the fastest in run and/or absorbing as low CPU power as possible.
I'm asking because I have to code some app with GUI under linux, but I'm rather a microcontroller programmer (and maybe it's hard to me to think like big computer). In small 8-bit MCU's world, where code is in plain C, globals are the fastest and commonly used way to share data between functions.
But I guess that in much more complicated app running under operating system there must be other 'special' way to do that. To this point I noticed that GTK (GDK, Glib etc.) offer many special functions and build-in mechanisms to makes programmer's life easiest, so I suppose it should be something elegant for sharing variables between functions.
Searching through the net I've seen different solutions:
- classes with private variables and methods to get/set them - but my app is coded in C, not C++, I'd like to avoid using object programming,
- global structs or even one big global struct with many members,
- good plain globals,
- GtkClipboard, but I think it's for different purposes.
What I want to do is simply to set some variable 'A' in one callback function, set that variable once again in second callback, and then in another callback do something depending upon value of variable 'A', like this:
callback_func1{
//...
A = some_func();
//...
}
callback_func2{
//...
A = another_func();
//...
}
callback_func3{
//...
if(A>threshold) do_something();
else do_nothing();
//...
}

You're right to be wary of globals, especially if you only want to allow certain functions to be modifying them.
Assuming you're retaining more data than just A (which for simplicity I've defined as int), you can set up your structure in the familiar way
typedef struct t_MYCBSD
{
int A;
// other members
} MYCBSD; // callback struct data
including other data members as necessary. (I've included the t_MYCBSD in case there is some self-referencing).
You can then implement your callback functions as follows:
void callback_func1( GtkWidget *widget, gpointer user_data )
{
MYCBSD *data = user_data;
data->A = some_func();
}
void callback_func2( GtkWidget *widget, gpointer user_data )
{
MYCBSD *data = user_data;
data->A = another_func();
}
void callback_func3( GtkWidget *widget, gpointer user_data )
{
MYCBSD *data = user_data;
if( data->A > threshold ) do_something();
else do_nothing();
}
Obviously, some_func(), another_func(), threshold, do_something() and do_nothing() are valid in this context.
NOTE: the data pointer to your struct makes the syntax a little more clear. You can also use:
((MYCBSD *) user_data)->A = some_func();
In any case, you usually set up your callbacks when creating your widgets. In the following (heavily culled, non-GtkBuilder) code, MYCBSD mydata will be locally scoped. I'm assuming the callbacks will be set for some buttons with the "clicked" event.
int main( int argc, char* argv[] )
{
MYCBSD mydata;
// Below-referenced widgets
GtkWidget *mywidget1, *mywidget2, *mywidget3;
// ... other widgets and variables
mydata.A = 0; // Optionally set an initial value to A
// Standard init via gtk_init( &argc, &argv );
// ... Create the toplevel and a container of some kind
// Create mywidget1,2,3 (as buttons, for example)
mywidget1 = gtk_button_new_with_label ("widget1");
mywidget2 = gtk_button_new_with_label ("widget2");
mywidget1 = gtk_button_new_with_label ("widget3");
g_signal_connect( mywidget1, "clicked", G_CALLBACK(callback_func1), &mydata );
g_signal_connect( mywidget2, "clicked", G_CALLBACK(callback_func2), &mydata );
g_signal_connect( mywidget3, "clicked", G_CALLBACK(callback_func3), &mydata );
// ... Attach those widgets to container
// ... and show all
// Run the app in a standard way via gtk_main();
return 0;
}
The important lines here are:
g_signal_connect( mywidget1, "clicked", G_CALLBACK(callback_func1), &mydata );
g_signal_connect( mywidget2, "clicked", G_CALLBACK(callback_func2), &mydata );
g_signal_connect( mywidget3, "clicked", G_CALLBACK(callback_func3), &mydata );
where the last parameter passes your data to the callback functions.
If you're only looking to share a single value, A, you can pass that in a similar way without the need of a struct.

If you want to use globals, just use globals. And, regardless of what the world says, nobody died because used globals.
Globals are avoided because make maintenance hard on big programs and, from your description, this just does not seem to be the case.
On the sharing side, GTK+ programs are usually not parallel, so you can freely access globals in RW without problems. And also when tasks are used, it is best practice to put all the GTK+ calls on the same task: you are still allowed to access globals in RW from the same task.

Related

How do i organize a GTK program?

I have a function called create_interface. In that function is a signal handler for the Open menu button (the menu is created in create_interface). I want to pass the window widget and also pass along the tree view widget, because when you open a file an entry in the tree view is supposed to show up. I tried passing them as a struct, but, although its works, GTK generates some error messages.
// This is global.
struct everything
{
GtkWidget *window;
GtkWidget *tree_view;
}
GtkWidget *create_interface (void)
{
struct everything instance;
struct everything *widgets;
widgets = &instance;
...code here...
g_signal_connect(file_mi_open_file_dialog, "clicked", G_CALLBACK(open_file_dialog), widgets);
The function open_file_dialog looks like this:
void open_file_dialog (GtkWidget *wid, gpointer data)
{
struct everything *sample_name = data;
...rest of code here...
I was wondering if there was another way of organizing a program so you do not have to have global variables.
I tried passing them as a struct, but, although its works, GTK generates some error messages.
The problem is that you're trying to use a stack-allocated struct, which becomes invalid after the create_interface() function is done, while you would normally expect these values to still be valid at a later moment in time (for example, when open_file_dialog() is called.
I was wondering if there was another way of organizing a program so you do not have to have global variables.
One possible solution is indeed to use a global variable: this will be valid throughout the lifetime of the program, but it has major drawbacks: it doesn't scale if you have to do that for each callback, and it's architecturally not really clean.
Another solution is to allocate your "closure" (i.e. the variables you want to capture at the moment you create your callback) on the heap, and to free it when you're done with it. GLib even helps you with this by a call g_signal_connect_data() (or g_signal_connect_object() if you save your fields in a GObject)
// Technically you don't need the typedef
typedef struct _ClickedClosure {
GtkWidget *window;
GtkWidget *treeview;
} ClickedClosure;
GtkWidget *create_interface (void)
{
// Note that the g_new0 allocates on the heap instead of using the stack
ClickedClosure *closure = g_new0 (ClickedClosure, 1);
// code here to initialize your window/treeview ...
// put the widgets in the closure
closure->window = my_window;
closure->treeview = treeview;
// Connect to the signal
g_signal_connect_data(file_mi_open_file_dialog, "clicked",
G_CALLBACK(open_file_dialog), closure, g_free, 0);
}
void open_file_dialog (GtkWidget *wid, gpointer data)
{
// Since this was allocated on the heap, this is still valid
ClickedClosure *sample_name = data;
// code handling here ...
}
Very often, what developers using GTK do, is that they're using their own GObject classes/objects already, which they can then use with g_signal_connect_object(), or by manually freeing it with g_object_unref() later. Using GObject then also allows you to to a runtime-typecheck cast, which makes sure your closure has the right type.

Validating entry for GtkCellRendererText, g_signal_connect gpointer to struct contains garbage

I'm trying to come up with a general purpose library to remove a lot of the set up work for GTK, so that the GTK code can be hidden away neatly. Mostly it works okay. The problem I have is with providing a validator for an edited Cell. If I put the validation code into my tree_cell_edited function then it works fine - but I don't want to do that because that messes with my nicely reusable libraries (they won't be reusable anymore!)
What I tried to do is implement tree_cell_edited as follows:
void tree_cell_edited (GtkCellRendererText *cell, const gchar *path_string, const gchar *new_text, gpointer model_definition_ptr) {
struct model_definition *model_def = (struct model_definition*)model_definition_ptr;
GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(model_def->tableview));
if (model_def->validator_ptr == NULL) {
g_print("Validator is null\n");
}
GtkTreePath *path = gtk_tree_path_new_from_string (path_string);
GtkTreeIter iter;
gint column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (cell), "column_number"));
gtk_tree_model_get_iter (model, &iter, path);
char *upd_text=(char *)malloc( strlen(new_text) * 2 ); // need to malloc twice the size of the text to allow modification - need a better solution later
strcpy(upd_text, new_text);
if ( ( ((struct model_definition*)model_definition_ptr)->validator_ptr == NULL ) || (*model_def->validator_ptr)(cell, path_string, (char **) &upd_text, model) ) {
gtk_tree_store_set(GTK_TREE_STORE (model), &iter, column, upd_text, -1);
}
free(upd_text);
gtk_tree_path_free (path);
}
Which is set up as follows:
g_signal_connect (cell, "edited", G_CALLBACK (tree_cell_edited), &model_def);
The model_def struct is set up as:
typedef struct model_definition {
bool (*validator_ptr)();
GtkWidget *tableview;
} model_definition;
and
model_definition model_def;
model_def.validator_ptr = &valid_edit;
model_def.tableview = tableview;
where valid_edit is my validation function. When I try this with valid_edit set to NULL then Validator is NULL never gets printed. When I use this style of code I get invalid cast from 'GtkWindow' to 'GtkTreeView' errors some of the time but not all of the time - whereas if I do the more traditional passing of the GtkTreeModel in to tree_cell_edited it all works fine.
Whats the issue here? Do I not have complete freedom over what I pass into whatever function I call with g_signal_connect for an edited cell? Is there something embarrassing and obviously wrong with my code? Is there a better way of calling my validation routine, bearing in mind that I don't want it in my Gtk code (for reasons of reusability).
If it helps, this code needs to be usable on Linux, Windows and macOS - so if it's a clever but platform specific trick then it isn't going to work.

GtkSpinner with long-lasting function with C

I'm making a GTK+3 application in C and I want a spinner to show when the program is processing the data. Here's what I generally have:
main()
{
//Some statements
g_signal_connect(G_OBJECT(btnGenerate), "clicked", G_CALLBACK(Generate), &mainform);
}
void Generate(GtkWidget *btnGenerate, form_widgets *p_main_form)
{
gtk_spinner_start(GTK_SPINNER(p_main_form->spnProcessing));
Begin_Lengthy_Processing(Parameters, Galore, ...);
//gtk_spinner_stop(GTK_SPINNER(p_main_form->spnProcessing));
}
I have the stop function commented out so I can see the spinner spin even after the function has finished, but the spinner starts after the function is finished, and I suspect it turns on in the main loop.
I also found out that the entire interface freezes during the execution of the long going function.
Is there a way to get it to start and display inside the callback function? I found the same question, but it uses Python and threads. This is C, not Python, so I would assume things are different.
You need to run your lengthy computation in a separate thread, or break it up into chunks and run each of them separately as idle callbacks in the main thread.
If your lengthy computation takes a single set of inputs and doesn’t need any more inputs until it’s finished, then you should construct it as a GTask and use g_task_run_in_thread() to start the task. Its result will be delivered back to the main thread via the GTask’s GAsyncReadyCallback. There’s an example here.
If it takes more input as it progresses, you probably want to use a GAsyncQueue to feed it more inputs, and a GThreadPool to provide the threads (amortising the cost of creating threads over multiple calls to the lengthy function, and protecting against denial of service).
The GNOME developer docs give an overview of how to do threading.
This is what I got:
int main()
{
// Statements...
g_signal_connect(G_OBJECT(btnGenerate), "clicked", G_CALLBACK(Process), &mainform);
// More statements...
}
void Process(GtkWidget *btnGenerate, form_widgets *p_main_form)
{
GError *processing_error;
GThread *start_processing;
gtk_spinner_start(GTK_SPINNER(p_main_form->spnProcessing));
active = true;
if((start_processing = g_thread_try_new(NULL, (GThreadFunc)Generate, p_main_form, &processing_error)) == NULL)
{
printf("%s\n", processing_error->message);
printf("Error, cannot create thread!?!?\n\n");
exit(processing_error->code);
}
}
void Generate(form_widgets *p_main_form)
{
// Long process
active = false;
}
My program, once cleaned up and finished, as there are many other bugs in the program, will be put on GitHub.
Thank you all for your help. This answer comes from looking at all of your answers and comments as well as reading some more documentation, but mostly your comments and answers.
I did something similar in my gtk3 program. It's not that difficult. Here's how I would go about it.
/**
g_idle_add_full() expects a pointer to a function with the signature below:
(*GSourceFunc) (gpointer user_data).
So your function signature must adhere to that in order to be called.
But you might want to pass variables to the function.
If you don't want to have the variables in the global scope
then you can do this:
typedef struct myDataType {
char* name;
int age;
} myDataType;
myDataType person = {"Max", 25};
then when calling g_idle_add_full() you do it this way:
g_idle_add_full(G_PRIORITY_HIGH_IDLE, myFunction, person, NULL);
*/
int main()
{
// Assumming there exist a pointer called data
g_idle_add_full(G_PRIORITY_HIGH_IDLE, lengthyProcessCallBack, data, NULL);
// GTK & GDK event loop continues and window should be responsive while function runs in background
}
gboolean lengthyProcessCallBack(gpointer data)
{
myDataType person = (myDataType) *data;
// Doing lenghthy stuff
while(;;) {
sleep(3600); // hypothetical long process :D
}
return FALSE; // removed from event sources and won't be called again.
}

passing multiple values using GTK_SIGNAL_FUNC

I'm trying to pass multiple values to a function when gtk_button click event invoke. The value are type of struct, int and gtk_image. I have a set of gtk images which attached to a table. The code fraction is as below,
`
GtkWidget *coin[6][7];
....
for(i=0;i<6;i++){
for(j=0;j<7;j++){
coin[i][j] = gtk_image_new_from_file("CoinC.png");
gtk_table_attach_defaults (GTK_TABLE(boardTable), coin[i][j], j, j+1, t, t+1);
}
t-=1;
}
`
I have created buttons to do some function and in the function involve some widgets set properties. One of it is I would like to change my image display as per code below
gtk_image_set_from_file(coin[slot][b->heights[0]],"CoinB.png");
The event fire code for button is as per below
gtk_signal_connect (GTK_OBJECT(button[0]), "clicked", GTK_SIGNAL_FUNC(dropCoin(b,0,coin)),NULL);
And the dropCoin function is as per below
gint dropCoin(board_type *b, gint slot, GtkWidget *coin[6][7]){
if(cp(b)==PLAYER_ONE){
makeMove(b,slot);
gtk_image_set_from_file(coin[slot][b->heights[0]-1],"CoinB.png");
}else{
makeMove(b, getReasonedMove(b));
gtk_image_set_from_file(coin[slot][b->heights[0]-1],"CoinA.png");
}
return 0;
}
Everytime I compile and run the program, the event straightway fired up without any clicking action being done. And when I tried to click back the same button, the event is not fired. I also received below error g_cclosure_new: assertion callback_func != NULL failed and
g_signal_connect_closure_by_id:assertion `closure != NULL' failed
Is there any other way to pass multiple values with widget to the event function.
What you're doing is using the return value from a call to dropCoin() as the function pointer.
You are not in any way telling GTK+ that it should call dropCoin() with the indicated parameters at a later time: the call happens right there before gtk_signal_connect() runs.
Signal callbacks only have a single user-settable parameter: the gpointer user_data. You need to find a way to associate all your desired data with that single pointer, typically by allocating some memory to hold the data and passing a pointer to that memory. In C, this is of course typically done by declaring a struct, and then allocating an instance of it.
Btw, your code is using an old version of GTK+, you should consider upgrading to 3.x.
You must give a function pointer to GTK_SIGNAL_FUNC. What you do is calling dropCoin and passing the resulting int to GTK_SIGNAL_FUNC.
Your call should look more like
gtk_signal_connect (GTK_OBJECT(button[0]), "clicked", GTK_SIGNAL_FUNC(dropCoin),NULL);
You can pass only one parameter, but you can wrap more than one value into a struct and pass that instead.
Update:
The function will be called with the argument you passed to gtk_signal_connect
struct send_Data {
board_type *b;
gint slot;
GtkWidget *coin;
};
struct send_Data arg;
gtk_signal_connect (GTK_OBJECT(button[0]), "clicked", GTK_SIGNAL_FUNC(dropCoin), &arg);
and dropCoin is defined as
void dropCoin(struct send_Data *arg){
...
// do something with arg
makeMove(arg->b, arg->slot);
foo(arg->b);
bar(arg->coin);
...
}

GTK+: issues passing data to call_back functions

I am building a GTK program that does the following: A button gets clicked by the user, it retrieves information from the server, then creates new buttons that the user can click on. I technically have a signal in main, and in that call_back I have multiple signals (for each of the created buttons).
I would like to pass data to this new button, but here it becomes icky. If I create a struct inside my first button I will later crash in the buttons that are generated because the struct is locally defined on the stack, and so it gets deleted.
I cannot create a global variable as each of the created button need different values. I basically would like to pass a struct with multiple fields when my initial button (callback method) gets called, but each of this struct is different.
The only way I can think of is to allocate it on the heap, but it becomes a bit of overhead to know when to free it.
Is there a good way around this please, or am I following wrong design choices for GTK by having a signal handler create a new signal handler please?
Thank you very much.
EDIT:
I am still crashing, and I am very confused why.
This is the code for the main button:
struct buttonData* data = (struct buttonData*) malloc(sizeof(struct buttonData));
data->IP = strdup(newDevice.IP.c_str()); // Added strdup
data->port = atoi(newDevice.port.c_str());
g_signal_connect(G_OBJECT(deviceButton), "button_press_event", G_CALLBACK(showDeviceAndConnect), (gpointer) data);
Code for the button that is generated:
static void showDeviceAndConnect(GtkWidget * deviceButton, gpointer data) {
struct buttonData* toConnect = (struct buttonData *) data;
fprintf(stderr, "IP: %s, PORT: %d\n", toConnect->IP, toConnect->port); //SIGSEGV
}
I am not sure why. Any help would be very appreciated.
The reason for the crash is the signature of your callback. "button-press-event" expects the callback with the signature gboolean foo(GtkWidget* , GdkEvent*, gpointer). As you callback has signature of void foo (GtkWidget * , gpointer ) the second parameter which you are getting in the callback function is not gpointer data which used when registering callback but GdkEvent pointer. Thus when you are dereferencing GdkEvent pointer (thinking it as the data you had passed) you are seeing the crash. So to fix this issue change static void showDeviceAndConnect(GtkWidget * deviceButton, gpointer data) to static void showDeviceAndConnect(GtkWidget * deviceButton, GdkEvent *ev, gpointer data).
Alternatively, as you are using only data in showDeviceAndConnect function you can using g_signal_connect_swapped which will pass the data as the first parameter; so if you use g_signal_connect_swapped your function static void showDeviceAndConnect(GtkWidget * deviceButton, gpointer data) can be static void showDeviceAndConnect(gpointer data).
Hope this helps!
The only way I can think of is to allocate it on the heap, but it becomes a bit of overhead to know when to free it.
That is the way to do it. Allocate the structure on the heap and pass a pointer to it as the callback data. Note that even while it does not apply to you since you are dynamically generating those buttons, using global variables is a poor choice as a solution.

Resources