Search code examples
cgtkglibc

gtk+ text editor, open python script aborts complaining about invalid utf-8 text


I'm in the debugging phase of writing my text editor using gtk+ 2.0 & gtksourceview 2.0. When I open certain files (previously edited in geany, and usually python files) the editor crashes with the following output:

(ledit:23515): Gtk-CRITICAL **: IA__gtk_text_buffer_set_text: assertion `GTK_IS_TEXT_BUFFER (buffer)' failed
**
GLib:ERROR:gutf8.c:1915:_g_utf8_make_valid: assertion failed: (g_utf8_validate (string->str, -1, NULL))
Aborted

I've tried to trap this error as follows:

char *path,*string;
GtkTextBuffer *tbuffer;
gsize length = -1;


path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
g_file_get_contents(path,&string,&length,NULL); 
if (g_utf8_validate(string,length,NULL))
{
  ...
  gtk_text_buffer_set_text(tbuffer,string,-1);
  ...
}
else
{
  printf("invalid utf-8 data\n");
} 

but this fails to work. I have two questions:

  1. why did this fail to trap the error?
  2. what else can I do to make the string valid utf-8 on the fly?

Solution

  • It turns out I was trying to trap the error on the wrong function. The function that was throwing the error was g_file_get_contents. I modified the code block as shown below, and the problem files are now opening fine, which I am kind of puzzled by, since it is still perfoming the same function that was throwing the error, but now it is in the condition of the if statement, and it works fine???

    char *path,*string;
    GtkTextBuffer *tbuffer;
    gsize length = -1;
    
    
    path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
    
    if ( g_file_get_contents(path,&string,&length,NULL) )
    {
      ...
      gtk_text_buffer_set_text(tbuffer,string,-1);
      ...
    }
    else
    {
      printf("file did not open\n");
    }