我试图用 GTK3 和 GtkSourceView 编写一个基本的文本编辑器,但是在将文件加载到我的缓冲区时遇到了一些问题。我对 Gtk 和 GtkSourceView 都是新手,如果我遗漏了一些明显的东西,我深表歉意。
这是有问题的功能:
void open_file(GtkSourceBuffer *buffer,kideWindow *self,const char *filename)
{
GtkSourceLanguageManager *lm;
GtkSourceLanguage *language = NULL;
GError *err = NULL;
gboolean reading;
GtkTextIter iter;
GIOChannel *io;
gchar *gbuffer;
g_return_val_if_fail (buffer != NULL, FALSE);
g_return_val_if_fail (filename != NULL, FALSE);
g_return_val_if_fail (GTK_SOURCE_BUFFER (buffer), FALSE);
/* get the Language for C source mimetype */
lm = g_object_get_data (G_OBJECT (buffer), "languages-manager");
language = gtk_source_language_manager_get_language (lm,"c");
g_print("Language: [%s]\n", gtk_source_language_get_name(language));
if (language == NULL)
{
g_print ("No language found for mime type `%s'\n", "text/x-c");
g_object_set (G_OBJECT (buffer), "highlight", FALSE, NULL);
}
else
{
gtk_source_buffer_set_language (buffer, language);
g_object_set (G_OBJECT (buffer), "highlight", TRUE, NULL);
}
/* Now load the file from Disk */
io = g_io_channel_new_file (filename, "r", &err);
if (!io)
{
g_print("error: %s %s\n", (err)->message, filename);
return FALSE;
}
if (g_io_channel_set_encoding (io, "utf-8", &err) != G_IO_STATUS_NORMAL)
{
g_print("err: Failed to set encoding:\n%s\n%s", filename, (err)->message);
return FALSE;
}
gtk_source_buffer_begin_not_undoable_action (buffer);
gtk_text_buffer_set_text (GTK_TEXT_BUFFER (buffer), "", 0);
gbuffer = g_malloc (4096);
reading = TRUE;
while (reading)
{
gsize bytes_read;
GIOStatus status;
status = g_io_channel_read_chars (io, gbuffer, 4096, &bytes_read, &err);
switch (status)
{
case G_IO_STATUS_EOF: reading = FALSE;
case G_IO_STATUS_NORMAL:
if (bytes_read == 0) continue;
gtk_text_buffer_get_end_iter ( GTK_TEXT_BUFFER (buffer), &iter);
gtk_text_buffer_insert (GTK_TEXT_BUFFER(buffer),&iter,gbuffer,bytes_read);
break;
case G_IO_STATUS_AGAIN: continue;
case G_IO_STATUS_ERROR:
default:
g_print("err (%s): %s", filename, (err)->message);
/* because of error in input we clear already loaded text */
gtk_text_buffer_set_text (GTK_TEXT_BUFFER (buffer), "", 0);
reading = FALSE;
break;
}
}
g_free (gbuffer);
gtk_source_buffer_end_not_undoable_action (buffer);
g_io_channel_unref (io);
if (err)
{
g_error_free (err);
return FALSE;
}
gtk_text_buffer_set_modified (GTK_TEXT_BUFFER (buffer), FALSE);
/* move cursor to the beginning */
gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);
gtk_text_buffer_place_cursor (GTK_TEXT_BUFFER (buffer), &iter);
g_object_set_data_full (G_OBJECT (buffer),"filename", g_strdup (filename),
(GDestroyNotify) g_free);
return TRUE;
}
返回的错误是:
** (kide:5813): CRITICAL **: open_file: assertion 'buffer != NULL' failed
任何帮助将不胜感激,在此先感谢:)