DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

GtkEditable Insert Handler Which Filters Certain Characters

02.27.2006
| 3347 views |
  • submit to reddit
        This is an example of a signal handler for GtkEditable::insert-text which filters out certain characters as the user types.

static void
insert_filtered (GtkEditable *entry, gchar *new_text, gint new_text_length, gint *position, gpointer data)
{
        gchar *clean_text;
        gint   i, j;

        clean_text = g_strndup (new_text, new_text_length);
        for (i = 0, j = 0; i < new_text_length; i++) {
                gchar c = new_text[i];
                if (c == '\t' || c == '\n' || c == '\r' || c == '(' ||
                    c == ')'  || c == '['  || c == ']'  || c == '<' ||
                    c == '>'  || c == '+'  || c == '\'' || c == '"')
                        continue;
                clean_text[j] = c;
                j++;
        }
        clean_text[j] = '\0';

        /* Call the default handler directly and stop the emission */
        g_signal_stop_emission_by_name (G_OBJECT (entry), "insert-text");
        if (clean_text[0] != '\0') {
                GtkEditableClass *klass;
                klass = GTK_EDITABLE_GET_CLASS (entry);
                klass->insert_text (entry, clean_text, j, position);
        }

        g_free (clean_text);
}

Example usage:
...
        GtkWidget *entry;

        entry = gtk_entry_new ();
        g_signal_connect (G_OBJECT (entry), "insert-text", G_CALLBACK (insert_filtered), NULL);
...