/*
Example running a command into a GtkTextView by Micah Carrick
Written for www.gtkforums.com
Compile using:
gcc -Wall -g main.c -o example `pkg-config --cflags --libs gtk+-2.0 libglade-2.0`
*/
#include <gtk/gtk.h>
/* structure to hold references to our widgets */
typedef struct
{
GtkWidget *entry;
GtkWidget *textview;
} MyWidgets;
/* call back function for when the button is pressed */
static void
on_execute_button_clicked (GtkWidget* widget,
gpointer user_data)
{
MyWidgets *widgets;
gchar *output;
const gchar *command;
GError *error =
NULL;
GtkTextBuffer *buffer;
widgets = (MyWidgets *)user_data;
command = gtk_entry_get_text (GTK_ENTRY (widgets->entry));
/* execute command */
g_spawn_command_line_sync (command, &output,
NULL,
NULL, &error);
if (error !=
NULL)
{
GtkWidget *dialog;
/* create an error dialog containing the error message */
dialog = gtk_message_dialog_new (
NULL, GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
error->message);
gtk_window_set_title (GTK_WINDOW (dialog),
"Error");
/* run the dialog */
gtk_dialog_run (GTK_DIALOG (dialog));
/* clean up memory used by dialog and error */
gtk_widget_destroy (dialog);
g_error_free(error);
return;
}
/* get the text buffer */
buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (widgets->textview));
/* set the text in the buffer to the output */
gtk_text_buffer_set_text (buffer, output, -
1);
/* free the output string */
g_free (output);
}
int
main (
int argc,
char *argv[])
{
GtkWidget *window;
GtkBuilder *gxml;
MyWidgets *widgets;
PangoFontDescription *font_desc;
widgets = g_slice_new (MyWidgets);
/* initialize the GTK+ library */
gtk_init (&argc, &argv);
/* build GladeXML object from the glade XML file */
gxml = gtk_builder_new ();
gtk_builder_add_from_file (gxml,
"example.xml",
NULL);
/* get widgets from GladeXML object */
window = GTK_WIDGET (gtk_builder_get_object (gxml,
"window"));
widgets->entry = GTK_WIDGET (gtk_builder_get_object (gxml,
"execute_entry"));
widgets->textview = GTK_WIDGET (gtk_builder_get_object (gxml,
"output_textview"));
/* call gtk_main_quit() when the window's "x" is clicked */
g_signal_connect (G_OBJECT (window),
"delete-event", gtk_main_quit,
NULL);
/*
Call on_button_clicked() when execute_button is clicked, passing the
MyWidget struct to the function as the user_data
*/
g_signal_connect (gtk_builder_get_object (gxml,
"execute_button"),
"clicked", G_CALLBACK (on_execute_button_clicked),
widgets);
/* free GladeXML object */
g_object_unref (G_OBJECT (gxml));
/* use a fixed width font on the text view so the output looks proper */
font_desc = pango_font_description_from_string (
"monospace 10");
gtk_widget_modify_font (widgets->textview, font_desc);
pango_font_description_free (font_desc);
/* show the main window */
gtk_widget_show (window);
gtk_main ();
return 0;
}