2005-01-07 [colin] 0.9.13cvs28.3
[claws.git] / src / gtk / gtkaspell.c
1 /* gtkaspell - a spell-checking addon for GtkText
2  * Copyright (c) 2000 Evan Martin (original code for ispell).
3  * Copyright (c) 2002 Melvin Hadasht.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; If not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
18  */
19 /*
20  * Stuphead: (C) 2000,2001 Grigroy Bakunov, Sergey Pinaev
21  * Adapted for Sylpheed (Claws) (c) 2001-2002 by Hiroyuki Yamamoto & 
22  * The Sylpheed Claws Team.
23  * Adapted for pspell (c) 2001-2002 Melvin Hadasht
24  * Adapted for GNU/aspell (c) 2002 Melvin Hadasht
25  */
26  
27 #ifdef HAVE_CONFIG_H
28 #  include "config.h"
29 #endif
30
31 #ifdef USE_ASPELL
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <signal.h>
39 #include <ctype.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <sys/time.h>
43 #include <fcntl.h>
44 #include <time.h>
45 #include <dirent.h>
46
47 #include <glib.h>
48
49 #include <gtk/gtk.h>
50 #include <gdk/gdk.h>
51 #include <gtk/gtkoptionmenu.h>
52 #include <gtk/gtkmenu.h>
53 #include <gtk/gtkmenuitem.h>
54 #include <gdk/gdkkeysyms.h>
55
56 #include <aspell.h>
57
58 #include "intl.h"
59 #include "gtk/gtktext.h"
60 #include "utils.h"
61 #include "codeconv.h"
62
63 #include "gtkaspell.h"
64 #define ASPELL_FASTMODE       1
65 #define ASPELL_NORMALMODE     2
66 #define ASPELL_BADSPELLERMODE 3
67
68 #define GTKASPELLWORDSIZE 1024
69
70 /* size of the text buffer used in various word-processing routines. */
71 #define BUFSIZE 1024
72
73 /* number of suggestions to display on each menu. */
74 #define MENUCOUNT 15
75
76 /* 'config' must be defined as a 'AspellConfig *' */
77 #define RETURN_FALSE_IF_CONFIG_ERROR() \
78 { \
79         if (aspell_config_error_number(config) != 0) { \
80                 gtkaspellcheckers->error_message = g_strdup(aspell_config_error_message(config)); \
81                 return FALSE; \
82         } \
83 }
84
85 #define CONFIG_REPLACE_RETURN_FALSE_IF_FAIL(option, value) { \
86         aspell_config_replace(config, option, value);        \
87         RETURN_FALSE_IF_CONFIG_ERROR();                      \
88         }
89
90 typedef struct _GtkAspellCheckers {
91         GSList          *checkers;
92         GSList          *dictionary_list;
93         gchar           *error_message;
94 } GtkAspellCheckers;
95
96 typedef struct _Dictionary {
97         gchar *fullname;
98         gchar *dictname;
99         gchar *encoding;
100 } Dictionary;
101
102 typedef struct _GtkAspeller {
103         Dictionary      *dictionary;
104         gint             sug_mode;
105         AspellConfig    *config;
106         AspellSpeller   *checker;
107 } GtkAspeller;
108
109 typedef void (*ContCheckFunc) (gpointer *gtkaspell);
110
111 struct _GtkAspell
112 {
113         GtkAspeller     *gtkaspeller;
114         GtkAspeller     *alternate_speller;
115         gchar           *dictionary_path;
116         gchar            theword[GTKASPELLWORDSIZE];
117         gint             start_pos;
118         gint             end_pos;
119         gint             orig_pos;
120         gint             end_check_pos;
121         gboolean         misspelled;
122         gboolean         check_while_typing;
123         gboolean         use_alternate;
124
125         ContCheckFunc    continue_check; 
126
127         GtkWidget       *config_menu;
128         GtkWidget       *popup_config_menu;
129         GtkWidget       *sug_menu;
130         GtkWidget       *replace_entry;
131         GtkWidget       *parent_window;
132
133         gint             default_sug_mode;
134         gint             max_sug;
135         GList           *suggestions_list;
136
137         GtkTextView     *gtktext;
138         GdkColor         highlight;
139 };
140
141 typedef AspellConfig GtkAspellConfig;
142
143 /******************************************************************************/
144
145 static GtkAspellCheckers *gtkaspellcheckers;
146
147 /* Error message storage */
148 static void gtkaspell_checkers_error_message    (gchar          *message);
149
150 /* Callbacks */
151 static void entry_insert_cb                     (GtkTextBuffer  *textbuf,
152                                                  GtkTextIter    *iter,
153                                                  gchar          *newtext, 
154                                                  gint           len,
155                                                  GtkAspell      *gtkaspell);
156 static void entry_delete_cb                     (GtkTextBuffer  *textbuf,
157                                                  GtkTextIter    *startiter,
158                                                  GtkTextIter    *enditer,
159                                                  GtkAspell      *gtkaspell);
160 static gint button_press_intercept_cb           (GtkTextView    *gtktext,
161                                                  GdkEvent       *e, 
162                                                  GtkAspell      *gtkaspell);
163
164 /* Checker creation */
165 static GtkAspeller* gtkaspeller_new             (Dictionary     *dict);
166 static GtkAspeller* gtkaspeller_real_new        (Dictionary     *dict);
167 static GtkAspeller* gtkaspeller_delete          (GtkAspeller    *gtkaspeller);
168 static GtkAspeller* gtkaspeller_real_delete     (GtkAspeller    *gtkaspeller);
169
170 /* Checker configuration */
171 static gint             set_dictionary                  (AspellConfig *config, 
172                                                          Dictionary *dict);
173 static void             set_sug_mode_cb                 (GtkMenuItem *w, 
174                                                          GtkAspell *gtkaspell);
175 static void             set_real_sug_mode               (GtkAspell *gtkaspell, 
176                                                          const char *themode);
177
178 /* Checker actions */
179 static gboolean check_at                        (GtkAspell      *gtkaspell, 
180                                                  int             from_pos);
181 static gboolean check_next_prev                 (GtkAspell      *gtkaspell, 
182                                                  gboolean        forward);
183 static GList* misspelled_suggest                (GtkAspell      *gtkaspell, 
184                                                  guchar         *word);
185 static void add_word_to_session_cb              (GtkWidget      *w, 
186                                                  gpointer        data);
187 static void add_word_to_personal_cb             (GtkWidget      *w, 
188                                                  gpointer        data);
189 static void replace_with_create_dialog_cb       (GtkWidget      *w,
190                                                  gpointer        data);
191 static void replace_with_supplied_word_cb       (GtkWidget      *w, 
192                                                  GtkAspell      *gtkaspell);
193 static void replace_word_cb                     (GtkWidget      *w, 
194                                                  gpointer       data); 
195 static void replace_real_word                   (GtkAspell      *gtkaspell, 
196                                                  gchar          *newword);
197 static void check_with_alternate_cb             (GtkWidget      *w,
198                                                  gpointer        data);
199 static void use_alternate_dict                  (GtkAspell      *gtkaspell);
200 static void toggle_check_while_typing_cb        (GtkWidget      *w, 
201                                                  gpointer        data);
202
203 /* Menu creation */
204 static void popup_menu                          (GtkAspell      *gtkaspell, 
205                                                  GdkEventButton *eb);
206 static GtkMenu* make_sug_menu                   (GtkAspell      *gtkaspell);
207 static void populate_submenu                    (GtkAspell      *gtkaspell, 
208                                                  GtkWidget      *menu);
209 static GtkMenu* make_config_menu                (GtkAspell      *gtkaspell);
210 static void set_menu_pos                        (GtkMenu        *menu, 
211                                                  gint           *x, 
212                                                  gint           *y, 
213                                                  gboolean       *push_in,
214                                                  gpointer        data);
215 /* Other menu callbacks */
216 static gboolean cancel_menu_cb                  (GtkMenuShell   *w,
217                                                  gpointer        data);
218 static void change_dict_cb                      (GtkWidget      *w, 
219                                                  GtkAspell      *gtkaspell);
220 static void switch_to_alternate_cb              (GtkWidget      *w, 
221                                                  gpointer        data);
222
223 /* Misc. helper functions */
224 static void             set_point_continue              (GtkAspell *gtkaspell);
225 static void             continue_check                  (gpointer *gtkaspell);
226 static gboolean         iswordsep                       (unsigned char c);
227 static guchar           get_text_index_whar             (GtkAspell *gtkaspell, 
228                                                          int pos);
229 static gboolean         get_word_from_pos               (GtkAspell *gtkaspell, 
230                                                          gint pos, 
231                                                          unsigned char* buf,
232                                                          gint buflen,
233                                                          gint *pstart, 
234                                                          gint *pend);
235 static void             allocate_color                  (GtkAspell *gtkaspell,
236                                                          gint rgbvalue);
237 static void             change_color                    (GtkAspell *gtkaspell, 
238                                                          gint start, 
239                                                          gint end, 
240                                                          gchar *newtext,
241                                                          GdkColor *color);
242 static guchar*          convert_to_aspell_encoding      (const guchar *encoding);
243 static gint             compare_dict                    (Dictionary *a, 
244                                                          Dictionary *b);
245 static void             dictionary_delete               (Dictionary *dict);
246 static Dictionary *     dictionary_dup                  (const Dictionary *dict);
247 static void             free_suggestions_list           (GtkAspell *gtkaspell);
248 static void             reset_theword_data              (GtkAspell *gtkaspell);
249 static void             free_checkers                   (gpointer elt, 
250                                                          gpointer data);
251 static gint             find_gtkaspeller                (gconstpointer aa, 
252                                                          gconstpointer bb);
253 static void             gtkaspell_alert_dialog          (gchar *message);
254 /* gtkspellconfig - only one config per session */
255 GtkAspellConfig * gtkaspellconfig;
256
257 /******************************************************************************/
258 static gint get_textview_buffer_charcount(GtkTextView *view);
259 static gint get_textview_buffer_position(GtkTextView *view);
260
261 static gint get_textview_buffer_charcount(GtkTextView *view)
262 {
263         GtkTextBuffer *buffer;
264
265         g_return_val_if_fail(view, 0);
266
267         buffer = gtk_text_view_get_buffer(view);
268         g_return_val_if_fail(buffer, 0);
269
270         return gtk_text_buffer_get_char_count(buffer);
271 }
272 static gint get_textview_buffer_offset(GtkTextView *view)
273 {
274         GtkTextBuffer * buffer;
275         GtkTextMark * mark;
276         GtkTextIter iter;
277
278         g_return_val_if_fail(view, 0);
279
280         buffer = gtk_text_view_get_buffer(view);
281         g_return_val_if_fail(buffer, 0);
282
283         mark = gtk_text_buffer_get_insert(buffer);
284         g_return_val_if_fail(mark, 0);
285
286         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
287
288         return gtk_text_iter_get_offset(&iter);
289 }
290 static void set_textview_buffer_offset(GtkTextView *view, gint offset)
291 {
292         GtkTextBuffer *buffer;
293         GtkTextIter iter;
294
295         g_return_if_fail(view);
296
297         buffer = gtk_text_view_get_buffer(view);
298         g_return_if_fail(buffer);
299
300         gtk_text_buffer_get_iter_at_offset(buffer, &iter, offset);
301         gtk_text_buffer_place_cursor(buffer, &iter);
302 }
303 /******************************************************************************/
304
305 void gtkaspell_checkers_init(void)
306 {
307         gtkaspellcheckers                  = g_new(GtkAspellCheckers, 1);
308         gtkaspellcheckers->checkers        = NULL;
309         gtkaspellcheckers->dictionary_list = NULL;
310         gtkaspellcheckers->error_message   = NULL;
311 }
312         
313 void gtkaspell_checkers_quit(void)
314 {
315         GSList *checkers;
316         GSList *dict_list;
317
318         if (gtkaspellcheckers == NULL) 
319                 return;
320
321         if ((checkers  = gtkaspellcheckers->checkers)) {
322                 debug_print("Aspell: number of running checkers to delete %d\n",
323                                 g_slist_length(checkers));
324
325                 g_slist_foreach(checkers, free_checkers, NULL);
326                 g_slist_free(checkers);
327         }
328
329         if ((dict_list = gtkaspellcheckers->dictionary_list)) {
330                 debug_print("Aspell: number of dictionaries to delete %d\n",
331                                 g_slist_length(dict_list));
332
333                 gtkaspell_free_dictionary_list(dict_list);
334                 gtkaspellcheckers->dictionary_list = NULL;
335         }
336
337         g_free(gtkaspellcheckers->error_message);
338
339         return;
340 }
341
342 static void gtkaspell_checkers_error_message (gchar *message)
343 {
344         gchar *tmp;
345         if (gtkaspellcheckers->error_message) {
346                 tmp = g_strdup_printf("%s\n%s", 
347                                       gtkaspellcheckers->error_message,
348                                       message);
349                 g_free(message);
350                 g_free(gtkaspellcheckers->error_message);
351                 gtkaspellcheckers->error_message = tmp;
352         } else 
353                 gtkaspellcheckers->error_message = message;
354 }
355
356 const char *gtkaspell_checkers_strerror(void)
357 {
358         g_return_val_if_fail(gtkaspellcheckers, "");
359         return gtkaspellcheckers->error_message;
360 }
361
362 void gtkaspell_checkers_reset_error(void)
363 {
364         g_return_if_fail(gtkaspellcheckers);
365         
366         g_free(gtkaspellcheckers->error_message);
367         
368         gtkaspellcheckers->error_message = NULL;
369 }
370
371 GtkAspell *gtkaspell_new(const gchar *dictionary_path,
372                          const gchar *dictionary, 
373                          const gchar *encoding,
374                          gint  misspelled_color,
375                          gboolean check_while_typing,
376                          gboolean use_alternate,
377                          GtkTextView *gtktext,
378                          GtkWindow *parent_win)
379 {
380         Dictionary      *dict;
381         GtkAspell       *gtkaspell;
382         GtkAspeller     *gtkaspeller;
383         GtkTextBuffer *buffer;
384
385         g_return_val_if_fail(gtktext, NULL);
386         buffer = gtk_text_view_get_buffer(gtktext);
387         
388         dict           = g_new0(Dictionary, 1);
389         dict->fullname = g_strdup(dictionary);
390         dict->encoding = g_strdup(encoding);
391
392         gtkaspeller    = gtkaspeller_new(dict); 
393         dictionary_delete(dict);
394
395         if (!gtkaspeller)
396                 return NULL;
397         
398         gtkaspell = g_new0(GtkAspell, 1);
399
400         gtkaspell->dictionary_path    = g_strdup(dictionary_path);
401
402         gtkaspell->gtkaspeller        = gtkaspeller;
403         gtkaspell->alternate_speller  = NULL;
404         gtkaspell->theword[0]         = 0x00;
405         gtkaspell->start_pos          = 0;
406         gtkaspell->end_pos            = 0;
407         gtkaspell->orig_pos           = -1;
408         gtkaspell->end_check_pos      = -1;
409         gtkaspell->misspelled         = -1;
410         gtkaspell->check_while_typing = check_while_typing;
411         gtkaspell->continue_check     = NULL;
412         gtkaspell->config_menu        = NULL;
413         gtkaspell->popup_config_menu  = NULL;
414         gtkaspell->sug_menu           = NULL;
415         gtkaspell->replace_entry      = NULL;
416         gtkaspell->gtktext            = gtktext;
417         gtkaspell->default_sug_mode   = ASPELL_FASTMODE;
418         gtkaspell->max_sug            = -1;
419         gtkaspell->suggestions_list   = NULL;
420         gtkaspell->use_alternate      = use_alternate;
421         gtkaspell->parent_window      = GTK_WIDGET(parent_win);
422         
423         allocate_color(gtkaspell, misspelled_color);
424
425         g_signal_connect_after(G_OBJECT(buffer), "insert-text",
426                                G_CALLBACK(entry_insert_cb), gtkaspell);
427         g_signal_connect_after(G_OBJECT(buffer), "delete-range",
428                                G_CALLBACK(entry_delete_cb), gtkaspell);
429         g_signal_connect(G_OBJECT(gtktext), "button-press-event",
430                          G_CALLBACK(button_press_intercept_cb),
431                          gtkaspell);
432         
433         debug_print("Aspell: created gtkaspell %0x\n", (guint) gtkaspell);
434
435         return gtkaspell;
436 }
437
438 void gtkaspell_delete(GtkAspell * gtkaspell) 
439 {
440         GtkTextView *gtktext = gtkaspell->gtktext;
441         
442         g_signal_handlers_disconnect_by_func(G_OBJECT(gtktext),
443                                              G_CALLBACK(entry_insert_cb),
444                                       gtkaspell);
445         g_signal_handlers_disconnect_by_func(G_OBJECT(gtktext),
446                                              G_CALLBACK(entry_delete_cb),
447                                              gtkaspell);
448         g_signal_handlers_disconnect_by_func(G_OBJECT(gtktext),
449                                              G_CALLBACK(button_press_intercept_cb),
450                                              gtkaspell);
451
452         gtkaspell_uncheck_all(gtkaspell);
453         
454         gtkaspeller_delete(gtkaspell->gtkaspeller);
455
456         if (gtkaspell->use_alternate && gtkaspell->alternate_speller)
457                 gtkaspeller_delete(gtkaspell->alternate_speller);
458
459         if (gtkaspell->sug_menu)
460                 gtk_widget_destroy(gtkaspell->sug_menu);
461
462         if (gtkaspell->popup_config_menu)
463                 gtk_widget_destroy(gtkaspell->popup_config_menu);
464
465         if (gtkaspell->config_menu)
466                 gtk_widget_destroy(gtkaspell->config_menu);
467
468         if (gtkaspell->suggestions_list)
469                 free_suggestions_list(gtkaspell);
470
471         g_free((gchar *)gtkaspell->dictionary_path);
472
473         debug_print("Aspell: deleting gtkaspell %0x\n", (guint) gtkaspell);
474
475         g_free(gtkaspell);
476
477         gtkaspell = NULL;
478 }
479
480 static void entry_insert_cb(GtkTextBuffer *textbuf,
481                             GtkTextIter *iter,
482                             gchar *newtext,
483                             gint len,
484                             GtkAspell *gtkaspell)
485 {
486         size_t wlen;
487         guint pos;
488
489         g_return_if_fail(gtkaspell->gtkaspeller->checker);
490
491         if (!gtkaspell->check_while_typing)
492                 return;
493
494         pos = gtk_text_iter_get_offset(iter);
495         
496         if (iswordsep(newtext[0])) {
497                 /* did we just end a word? */
498                 if (pos >= 2)
499                         check_at(gtkaspell, pos - 2);
500
501                 /* did we just split a word? */
502                 if (pos < gtk_text_buffer_get_char_count(textbuf))
503                         check_at(gtkaspell, pos + 1);
504         } else {
505                 /* check as they type, *except* if they're typing at the end (the most
506                  * common case).
507                  */
508                 if (pos < gtk_text_buffer_get_char_count(textbuf) &&
509                     !iswordsep(get_text_index_whar(gtkaspell, pos))) {
510                         check_at(gtkaspell, pos - 1);
511                 }
512         }
513 }
514
515 static void entry_delete_cb(GtkTextBuffer *textbuf,
516                             GtkTextIter *startiter,
517                             GtkTextIter *enditer,
518                             GtkAspell *gtkaspell)
519 {
520         int origpos;
521         gint start, end;
522     
523         g_return_if_fail(gtkaspell->gtkaspeller->checker);
524
525         if (!gtkaspell->check_while_typing)
526                 return;
527
528         start = gtk_text_iter_get_offset(startiter);
529         end = gtk_text_iter_get_offset(enditer);
530         origpos = get_textview_buffer_offset(gtkaspell->gtktext);
531         if (start) {
532                 check_at(gtkaspell, start - 1);
533                 check_at(gtkaspell, start);
534         }
535
536         set_textview_buffer_offset(gtkaspell->gtktext, origpos);
537         /* this is to *UNDO* the selection, in case they were holding shift
538          * while hitting backspace. */
539         /* needed with textview ??? */
540         /* gtk_editable_select_region(GTK_EDITABLE(gtktext), origpos, origpos); */
541 }
542
543 /* ok, this is pretty wacky:
544  * we need to let the right-mouse-click go through, so it moves the cursor,
545  * but we *can't* let it go through, because GtkText interprets rightclicks as
546  * weird selection modifiers.
547  *
548  * so what do we do?  forge rightclicks as leftclicks, then popup the menu.
549  * HACK HACK HACK.
550  */
551 static gint button_press_intercept_cb(GtkTextView *gtktext,
552                                       GdkEvent *e, 
553                                       GtkAspell *gtkaspell)
554 {
555         GdkEventButton *eb;
556         gboolean retval;
557
558         g_return_val_if_fail(gtkaspell->gtkaspeller->checker, FALSE);
559
560         if (e->type != GDK_BUTTON_PRESS) 
561                 return FALSE;
562         eb = (GdkEventButton*) e;
563
564         if (eb->button != 3) 
565                 return FALSE;
566
567         /* forge the leftclick */
568         eb->button = 1;
569
570         g_signal_handlers_block_by_func(G_OBJECT(gtktext),
571                                         G_CALLBACK(button_press_intercept_cb), 
572                                         gtkaspell);
573         g_signal_emit_by_name(G_OBJECT(gtktext), "button-press-event",
574                               e, &retval);
575         g_signal_emit_by_name(G_OBJECT(gtktext), "button-release-event",
576                               e, &retval);
577         g_signal_handlers_unblock_by_func(G_OBJECT(gtktext),
578                                           G_CALLBACK(button_press_intercept_cb), 
579                                            gtkaspell);
580         g_signal_stop_emission_by_name(G_OBJECT(gtktext), "button-press-event");
581     
582         /* now do the menu wackiness */
583         popup_menu(gtkaspell, eb);
584         gtk_grab_remove(GTK_WIDGET(gtktext));
585         return FALSE;
586 }
587
588 /* Checker creation */
589 static GtkAspeller *gtkaspeller_new(Dictionary *dictionary)
590 {
591         GSList          *exist;
592         GtkAspeller     *gtkaspeller = NULL;
593         GtkAspeller     *tmp;
594         Dictionary      *dict;
595
596         g_return_val_if_fail(gtkaspellcheckers, NULL);
597
598         g_return_val_if_fail(dictionary, NULL);
599
600         if (dictionary->fullname == NULL)
601                 gtkaspell_checkers_error_message(
602                                 g_strdup(_("No dictionary selected.")));
603         
604         g_return_val_if_fail(dictionary->fullname, NULL);
605         
606         if (dictionary->dictname == NULL) {
607                 gchar *tmp;
608
609                 tmp = strrchr(dictionary->fullname, G_DIR_SEPARATOR);
610
611                 if (tmp == NULL)
612                         dictionary->dictname = dictionary->fullname;
613                 else
614                         dictionary->dictname = tmp + 1;
615         }
616
617         dict = dictionary_dup(dictionary);
618
619         tmp = g_new0(GtkAspeller, 1);
620         tmp->dictionary = dict;
621
622         exist = g_slist_find_custom(gtkaspellcheckers->checkers, tmp, 
623                                     find_gtkaspeller);
624         
625         g_free(tmp);
626
627         if ((gtkaspeller = gtkaspeller_real_new(dict)) != NULL) {
628                 gtkaspellcheckers->checkers = g_slist_append(
629                                 gtkaspellcheckers->checkers,
630                                 gtkaspeller);
631
632                 debug_print("Aspell: Created a new gtkaspeller %0x\n",
633                                 (gint) gtkaspeller);
634         } else {
635                 dictionary_delete(dict);
636
637                 debug_print("Aspell: Could not create spell checker.\n");
638         }
639
640         debug_print("Aspell: number of existing checkers %d\n", 
641                         g_slist_length(gtkaspellcheckers->checkers));
642
643         return gtkaspeller;
644 }
645
646 static GtkAspeller *gtkaspeller_real_new(Dictionary *dict)
647 {
648         GtkAspeller             *gtkaspeller;
649         AspellConfig            *config;
650         AspellCanHaveError      *ret;
651         
652         g_return_val_if_fail(gtkaspellcheckers, NULL);
653         g_return_val_if_fail(dict, NULL);
654
655         gtkaspeller = g_new(GtkAspeller, 1);
656         
657         gtkaspeller->dictionary = dict;
658         gtkaspeller->sug_mode   = ASPELL_FASTMODE;
659
660         config = new_aspell_config();
661
662         if (!set_dictionary(config, dict))
663                 return NULL;
664         
665         ret = new_aspell_speller(config);
666         delete_aspell_config(config);
667
668         if (aspell_error_number(ret) != 0) {
669                 gtkaspellcheckers->error_message
670                         = g_strdup(aspell_error_message(ret));
671                 
672                 delete_aspell_can_have_error(ret);
673                 
674                 return NULL;
675         }
676
677         gtkaspeller->checker = to_aspell_speller(ret);
678         gtkaspeller->config  = aspell_speller_config(gtkaspeller->checker);
679
680         return gtkaspeller;
681 }
682
683 static GtkAspeller *gtkaspeller_delete(GtkAspeller *gtkaspeller)
684 {
685         g_return_val_if_fail(gtkaspellcheckers, NULL);
686         
687         gtkaspellcheckers->checkers = 
688                 g_slist_remove(gtkaspellcheckers->checkers, 
689                                 gtkaspeller);
690
691         debug_print("Aspell: Deleting gtkaspeller %0x.\n", 
692                         (gint) gtkaspeller);
693
694         gtkaspeller_real_delete(gtkaspeller);
695
696         debug_print("Aspell: number of existing checkers %d\n", 
697                         g_slist_length(gtkaspellcheckers->checkers));
698
699         return gtkaspeller;
700 }
701
702 static GtkAspeller *gtkaspeller_real_delete(GtkAspeller *gtkaspeller)
703 {
704         g_return_val_if_fail(gtkaspeller,          NULL);
705         g_return_val_if_fail(gtkaspeller->checker, NULL);
706
707         aspell_speller_save_all_word_lists(gtkaspeller->checker);
708
709         delete_aspell_speller(gtkaspeller->checker);
710
711         dictionary_delete(gtkaspeller->dictionary);
712
713         debug_print("Aspell: gtkaspeller %0x deleted.\n", 
714                     (gint) gtkaspeller);
715
716         g_free(gtkaspeller);
717
718         return NULL;
719 }
720
721 /*****************************************************************************/
722 /* Checker configuration */
723
724 static gboolean set_dictionary(AspellConfig *config, Dictionary *dict)
725 {
726         gchar *language = NULL;
727         gchar *jargon = NULL;
728         gchar *size   = NULL;
729         gchar  buf[BUFSIZE];
730         
731         g_return_val_if_fail(config, FALSE);
732         g_return_val_if_fail(dict,   FALSE);
733
734         strncpy(buf, dict->fullname, BUFSIZE-1);
735         buf[BUFSIZE-1] = 0x00;
736
737         buf[dict->dictname - dict->fullname] = 0x00;
738
739         CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("dict-dir", buf);
740         debug_print("Aspell: looking for dictionaries in path %s.\n", buf);
741
742         strncpy(buf, dict->dictname, BUFSIZE-1);
743         language = buf;
744         
745         if ((size = strrchr(buf, '-')) && isdigit((int) size[1]))
746                 *size++ = 0x00;
747         else
748                 size = NULL;
749                                 
750         if ((jargon = strchr(language, '-')) != NULL) 
751                 *jargon++ = 0x00;
752         
753         if (size != NULL && jargon == size)
754                 jargon = NULL;
755
756         debug_print("Aspell: language: %s, jargon: %s, size: %s\n",
757                     language, jargon, size);
758         
759         if (language)
760                 CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("lang", language);
761         if (jargon)
762                 CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("jargon", jargon);
763         if (size)
764                 CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("size", size);
765         if (dict->encoding) {
766                 gchar *aspell_enc;
767         
768                 aspell_enc = convert_to_aspell_encoding (dict->encoding);
769                 aspell_config_replace(config, "encoding",
770                                       (const char *) aspell_enc);
771                 g_free(aspell_enc);
772
773                 RETURN_FALSE_IF_CONFIG_ERROR();
774         }
775         
776         return TRUE;
777 }
778
779 guchar *gtkaspell_get_dict(GtkAspell *gtkaspell)
780 {
781
782         g_return_val_if_fail(gtkaspell->gtkaspeller->config,     NULL);
783         g_return_val_if_fail(gtkaspell->gtkaspeller->dictionary, NULL);
784         
785         return g_strdup(gtkaspell->gtkaspeller->dictionary->dictname);
786 }
787   
788 guchar *gtkaspell_get_path(GtkAspell *gtkaspell)
789 {
790         guchar *path;
791         Dictionary *dict;
792
793         g_return_val_if_fail(gtkaspell->gtkaspeller->config, NULL);
794         g_return_val_if_fail(gtkaspell->gtkaspeller->dictionary, NULL);
795
796         dict = gtkaspell->gtkaspeller->dictionary;
797         path = g_strndup(dict->fullname, dict->dictname - dict->fullname);
798
799         return path;
800 }
801
802 /* set_sug_mode_cb() - Menu callback: Set the suggestion mode */
803 static void set_sug_mode_cb(GtkMenuItem *w, GtkAspell *gtkaspell)
804 {
805         char *themode;
806         
807         gtk_label_get(GTK_LABEL(GTK_BIN(w)->child), (gchar **) &themode);
808         
809         set_real_sug_mode(gtkaspell, themode);
810
811         if (gtkaspell->config_menu)
812                 populate_submenu(gtkaspell, gtkaspell->config_menu);
813 }
814
815 static void set_real_sug_mode(GtkAspell *gtkaspell, const char *themode)
816 {
817         gint result;
818         gint mode = ASPELL_FASTMODE;
819         g_return_if_fail(gtkaspell);
820         g_return_if_fail(gtkaspell->gtkaspeller);
821         g_return_if_fail(themode);
822
823         if (!strcmp(themode,_("Normal Mode")))
824                 mode = ASPELL_NORMALMODE;
825         else if (!strcmp( themode,_("Bad Spellers Mode")))
826                 mode = ASPELL_BADSPELLERMODE;
827
828         result = gtkaspell_set_sug_mode(gtkaspell, mode);
829
830         if(!result) {
831                 debug_print("Aspell: error while changing suggestion mode:%s\n",
832                             gtkaspellcheckers->error_message);
833                 gtkaspell_checkers_reset_error();
834         }
835 }
836   
837 /* gtkaspell_set_sug_mode() - Set the suggestion mode */
838 gboolean gtkaspell_set_sug_mode(GtkAspell *gtkaspell, gint themode)
839 {
840         AspellConfig *config;
841
842         g_return_val_if_fail(gtkaspell, FALSE);
843         g_return_val_if_fail(gtkaspell->gtkaspeller, FALSE);
844         g_return_val_if_fail(gtkaspell->gtkaspeller->config, FALSE);
845
846         debug_print("Aspell: setting sug mode of gtkaspeller %0x to %d\n",
847                         (guint) gtkaspell->gtkaspeller, themode);
848
849         config = gtkaspell->gtkaspeller->config;
850
851         switch (themode) {
852                 case ASPELL_FASTMODE: 
853                         CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("sug-mode", "fast");
854                         break;
855                 case ASPELL_NORMALMODE: 
856                         CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("sug-mode", "normal");
857                         break;
858                 case ASPELL_BADSPELLERMODE: 
859                         CONFIG_REPLACE_RETURN_FALSE_IF_FAIL("sug-mode", 
860                                                             "bad-spellers");
861                         break;
862                 default: 
863                         gtkaspellcheckers->error_message = 
864                                 g_strdup(_("Unknown suggestion mode."));
865                         return FALSE;
866                 }
867
868         gtkaspell->gtkaspeller->sug_mode = themode;
869         gtkaspell->default_sug_mode      = themode;
870
871         return TRUE;
872 }
873
874 /* misspelled_suggest() - Create a suggestion list for  word  */
875 static GList *misspelled_suggest(GtkAspell *gtkaspell, guchar *word) 
876 {
877         const guchar          *newword;
878         GList                 *list = NULL;
879         const AspellWordList  *suggestions;
880         AspellStringEnumeration *elements;
881
882         g_return_val_if_fail(word, NULL);
883
884         if (!aspell_speller_check(gtkaspell->gtkaspeller->checker, word, -1)) {
885                 free_suggestions_list(gtkaspell);
886
887                 suggestions = aspell_speller_suggest(
888                                 gtkaspell->gtkaspeller->checker,
889                                                      (const char *)word, -1);
890                 elements    = aspell_word_list_elements(suggestions);
891                 list        = g_list_append(list, g_strdup(word)); 
892                 
893                 while (newword = aspell_string_enumeration_next(elements))
894                         list = g_list_append(list, g_strdup(newword));
895
896                 gtkaspell->max_sug          = g_list_length(list) - 1;
897                 gtkaspell->suggestions_list = list;
898
899                 return list;
900         }
901
902         free_suggestions_list(gtkaspell);
903
904         return NULL;
905 }
906
907 /* misspelled_test() - Just test if word is correctly spelled */  
908 static int misspelled_test(GtkAspell *gtkaspell, unsigned char *word) 
909 {
910         return aspell_speller_check(gtkaspell->gtkaspeller->checker, word, -1)
911                                     ? 0 : 1;
912 }
913
914
915 static gboolean iswordsep(unsigned char c) 
916 {
917         return !isalpha(c) && c != '\'';
918 }
919
920 static guchar get_text_index_whar(GtkAspell *gtkaspell, int pos) 
921 {
922         GtkTextView *view = gtkaspell->gtktext;
923         GtkTextBuffer *buffer = gtk_text_view_get_buffer(view);
924         GtkTextIter start, end;
925         const gchar *utf8chars;
926         guchar a = '\0';
927
928         gtk_text_buffer_get_iter_at_offset(buffer, &start, pos);
929         gtk_text_buffer_get_iter_at_offset(buffer, &end, pos+1);
930
931         utf8chars = gtk_text_iter_get_text(&start, &end);
932         if (is_ascii_str(utf8chars)) {
933                 a = utf8chars ? utf8chars[0] : '\0' ;
934         } else {
935                 gchar *tr = conv_iconv_strdup(utf8chars, CS_UTF_8, 
936                                 gtkaspell->gtkaspeller->dictionary->encoding);
937                 if (tr) {
938                         a = tr[0];
939                         g_free(tr);
940                 }
941         }
942
943         return a;
944 }
945
946 /* get_word_from_pos () - return the word pointed to. */
947 /* Handles correctly the quotes. */
948 static gboolean get_word_from_pos(GtkAspell *gtkaspell, gint pos, 
949                                   unsigned char* buf, gint buflen,
950                                   gint *pstart, gint *pend) 
951 {
952
953         /* TODO : when correcting a word into quotes, change the color of */
954         /* the quotes too, as may be they were highlighted before. To do  */
955         /* this, we can use two others pointers that points to the whole    */
956         /* word including quotes. */
957
958         gint start;
959         gint end;
960                   
961         guchar c;
962         GtkTextView *gtktext;
963         
964         gtktext = gtkaspell->gtktext;
965         if (iswordsep(get_text_index_whar(gtkaspell, pos))) 
966                 return FALSE;
967         
968         /* The apostrophe character is somtimes used for quotes 
969          * So include it in the word only if it is not surrounded 
970          * by other characters. 
971          */
972          
973         for (start = pos; start >= 0; --start) {
974                 c = get_text_index_whar(gtkaspell, start);
975                 if (c == '\'') {
976                         if (start > 0) {
977                                 if (!isalpha(get_text_index_whar(gtkaspell,
978                                                                  start - 1))) {
979                                         /* start_quote = TRUE; */
980                                         break;
981                                 }
982                         }
983                         else {
984                                 /* start_quote = TRUE; */
985                                 break;
986                         }
987                 }
988                 else if (!isalpha(c))
989                                 break;
990         }
991
992         start++;
993
994         for (end = pos; end < get_textview_buffer_charcount(gtktext); end++) {
995                 c = get_text_index_whar(gtkaspell, end); 
996                 if (c == '\'') {
997                         if (end < get_textview_buffer_charcount(gtktext)) {
998                                 if (!isalpha(get_text_index_whar(gtkaspell,
999                                                                  end + 1))) {
1000                                         /* end_quote = TRUE; */
1001                                         break;
1002                                 }
1003                         }
1004                         else {
1005                                 /* end_quote = TRUE; */
1006                                 break;
1007                         }
1008                 }
1009                 else if(!isalpha(c))
1010                                 break;
1011         }
1012                                                 
1013         if (pstart) 
1014                 *pstart = start;
1015         if (pend) 
1016                 *pend = end;
1017
1018         if (buf) {
1019                 if (end - start < buflen) {
1020                         for (pos = start; pos < end; pos++) {
1021                                 buf[pos - start] =
1022                                         get_text_index_whar(gtkaspell, pos);
1023                         }
1024                         buf[pos - start] = 0;
1025                 } else
1026                         return FALSE;
1027         }
1028
1029         return TRUE;
1030 }
1031
1032 static gboolean check_at(GtkAspell *gtkaspell, gint from_pos) 
1033 {
1034         gint          start, end;
1035         unsigned char buf[GTKASPELLWORDSIZE];
1036         GtkTextView     *gtktext;
1037
1038         g_return_val_if_fail(from_pos >= 0, FALSE);
1039     
1040         gtktext = gtkaspell->gtktext;
1041
1042         if (!get_word_from_pos(gtkaspell, from_pos, buf, sizeof(buf), 
1043                                &start, &end))
1044                 return FALSE;
1045
1046         if (misspelled_test(gtkaspell, buf)) {
1047                 strncpy(gtkaspell->theword, buf, GTKASPELLWORDSIZE - 1);
1048                 gtkaspell->theword[GTKASPELLWORDSIZE - 1] = 0;
1049                 gtkaspell->start_pos  = start;
1050                 gtkaspell->end_pos    = end;
1051                 free_suggestions_list(gtkaspell);
1052
1053                 change_color(gtkaspell, start, end, buf, &(gtkaspell->highlight));
1054                 return TRUE;
1055         } else {
1056                 change_color(gtkaspell, start, end, buf, NULL);
1057                 return FALSE;
1058         }
1059 }
1060
1061 static gboolean check_next_prev(GtkAspell *gtkaspell, gboolean forward)
1062 {
1063         gint pos;
1064         gint minpos;
1065         gint maxpos;
1066         gint direc = -1;
1067         gboolean misspelled;
1068         
1069         minpos = 0;
1070         maxpos = gtkaspell->end_check_pos;
1071
1072         if (forward) {
1073                 minpos = -1;
1074                 direc = 1;
1075                 maxpos--;
1076         } 
1077
1078         pos = get_textview_buffer_offset(gtkaspell->gtktext);
1079         gtkaspell->orig_pos = pos;
1080         while (iswordsep(get_text_index_whar(gtkaspell, pos)) &&
1081                pos > minpos && pos <= maxpos)
1082                 pos += direc;
1083         while (!(misspelled = check_at(gtkaspell, pos)) &&
1084                pos > minpos && pos <= maxpos) {
1085
1086                 while (!iswordsep(get_text_index_whar(gtkaspell, pos)) &&
1087                        pos > minpos && pos <= maxpos)
1088                         pos += direc;
1089
1090                 while (iswordsep(get_text_index_whar(gtkaspell, pos)) &&
1091                        pos > minpos && pos <= maxpos)
1092                         pos += direc;
1093         }
1094         if (misspelled) {
1095                 misspelled_suggest(gtkaspell, gtkaspell->theword);
1096
1097                 if (forward)
1098                         gtkaspell->orig_pos = gtkaspell->end_pos;
1099
1100                 set_textview_buffer_offset(gtkaspell->gtktext,
1101                                 gtkaspell->end_pos);
1102                 /* scroll line to window center */
1103                 gtk_text_view_scroll_to_mark(gtkaspell->gtktext,
1104                         gtk_text_buffer_get_insert(
1105                                 gtk_text_view_get_buffer(gtkaspell->gtktext)),
1106                         0.0, TRUE, 0.0, 0.5);
1107                 /* let textview recalculate coordinates (set_menu_pos) */
1108                 while (gtk_events_pending ())
1109                         gtk_main_iteration ();
1110
1111                 gtk_menu_popup(make_sug_menu(gtkaspell), NULL, NULL,
1112                                 set_menu_pos, gtkaspell, 0, GDK_CURRENT_TIME);
1113
1114         } else {
1115                 reset_theword_data(gtkaspell);
1116
1117                 gtkaspell_alert_dialog(_("No misspelled word found."));
1118                 set_textview_buffer_offset(gtkaspell->gtktext,
1119                                           gtkaspell->orig_pos);
1120         }
1121
1122         return misspelled;
1123 }
1124
1125 void gtkaspell_check_backwards(GtkAspell *gtkaspell)
1126 {
1127         gtkaspell->continue_check = NULL;
1128         gtkaspell->end_check_pos =
1129                 get_textview_buffer_charcount(gtkaspell->gtktext);
1130         check_next_prev(gtkaspell, FALSE);
1131 }
1132
1133 void gtkaspell_check_forwards_go(GtkAspell *gtkaspell)
1134 {
1135
1136         gtkaspell->continue_check = NULL;
1137         gtkaspell->end_check_pos =
1138                 get_textview_buffer_charcount(gtkaspell->gtktext);
1139         check_next_prev(gtkaspell, TRUE);
1140 }
1141
1142 void gtkaspell_check_all(GtkAspell *gtkaspell)
1143 {       
1144         GtkTextView *gtktext;
1145         gint start, end;
1146         GtkTextBuffer *buffer;
1147         GtkTextIter startiter, enditer;
1148
1149         g_return_if_fail(gtkaspell);
1150         g_return_if_fail(gtkaspell->gtktext);
1151
1152         gtktext = gtkaspell->gtktext;
1153         buffer = gtk_text_view_get_buffer(gtktext);
1154         gtk_text_buffer_get_selection_bounds(buffer, &startiter, &enditer);
1155         start = gtk_text_iter_get_offset(&startiter);
1156         end = gtk_text_iter_get_offset(&enditer);
1157
1158         if (start == end) {
1159                 start = 0;
1160                 end = gtk_text_buffer_get_char_count(buffer);
1161         } else if (start > end) {
1162                 gint tmp;
1163
1164                 tmp   = start;
1165                 start = end;
1166                 end   = tmp;
1167         }
1168
1169         set_textview_buffer_offset(gtktext, start);
1170
1171         gtkaspell->continue_check = continue_check;
1172         gtkaspell->end_check_pos  = end;
1173
1174         gtkaspell->misspelled = check_next_prev(gtkaspell, TRUE);
1175 }       
1176
1177 static void continue_check(gpointer *data)
1178 {
1179         GtkAspell *gtkaspell = (GtkAspell *) data;
1180         gint pos = get_textview_buffer_offset(gtkaspell->gtktext);
1181         if (pos < gtkaspell->end_check_pos && gtkaspell->misspelled)
1182                 gtkaspell->misspelled = check_next_prev(gtkaspell, TRUE);
1183         else
1184                 gtkaspell->continue_check = NULL;
1185 }
1186
1187 void gtkaspell_highlight_all(GtkAspell *gtkaspell) 
1188 {
1189         guint     origpos;
1190         guint     pos = 0;
1191         guint     len;
1192         GtkTextView *gtktext;
1193
1194         g_return_if_fail(gtkaspell->gtkaspeller->checker);      
1195
1196         gtktext = gtkaspell->gtktext;
1197
1198         len = get_textview_buffer_charcount(gtktext);
1199
1200         origpos = get_textview_buffer_offset(gtktext);
1201
1202         while (pos < len) {
1203                 while (pos < len &&
1204                        iswordsep(get_text_index_whar(gtkaspell, pos)))
1205                         pos++;
1206                 while (pos < len &&
1207                        !iswordsep(get_text_index_whar(gtkaspell, pos)))
1208                         pos++;
1209                 if (pos > 0)
1210                         check_at(gtkaspell, pos - 1);
1211         }
1212         set_textview_buffer_offset(gtktext, origpos);
1213 }
1214
1215 static void replace_with_supplied_word_cb(GtkWidget *w, GtkAspell *gtkaspell) 
1216 {
1217         unsigned char *newword;
1218         GdkEvent *e= (GdkEvent *) gtk_get_current_event();
1219         
1220         newword = gtk_editable_get_chars(GTK_EDITABLE(gtkaspell->replace_entry),
1221                                          0, -1);
1222
1223         if (strcmp(newword, gtkaspell->theword)) {
1224                 replace_real_word(gtkaspell, newword);
1225
1226                 if ((e->type == GDK_KEY_PRESS &&
1227                     ((GdkEventKey *) e)->state & GDK_CONTROL_MASK)) {
1228                         aspell_speller_store_replacement(
1229                                         gtkaspell->gtkaspeller->checker,
1230                                          gtkaspell->theword, -1,
1231                                          newword, -1);
1232                 }
1233                 gtkaspell->replace_entry = NULL;
1234         }
1235
1236         g_free(newword);
1237
1238         set_point_continue(gtkaspell);
1239 }
1240
1241
1242 static void replace_word_cb(GtkWidget *w, gpointer data)
1243 {
1244         unsigned char *newword;
1245         GtkAspell *gtkaspell = (GtkAspell *) data;
1246         GdkEvent *e= (GdkEvent *) gtk_get_current_event();
1247
1248         gtk_label_get(GTK_LABEL(GTK_BIN(w)->child), (gchar**) &newword);
1249
1250         replace_real_word(gtkaspell, newword);
1251
1252         if ((e->type == GDK_KEY_PRESS && 
1253             ((GdkEventKey *) e)->state & GDK_CONTROL_MASK) ||
1254             (e->type == GDK_BUTTON_RELEASE && 
1255              ((GdkEventButton *) e)->state & GDK_CONTROL_MASK)) {
1256                 aspell_speller_store_replacement(
1257                                 gtkaspell->gtkaspeller->checker,
1258                                                  gtkaspell->theword, -1, 
1259                                                  newword, -1);
1260         }
1261
1262         gtk_menu_shell_deactivate(GTK_MENU_SHELL(w->parent));
1263
1264         set_point_continue(gtkaspell);
1265 }
1266
1267 static void replace_real_word(GtkAspell *gtkaspell, gchar *newword)
1268 {
1269         int             oldlen, newlen, wordlen;
1270         gint            origpos;
1271         gint            pos;
1272         gint            start = gtkaspell->start_pos;
1273         GtkTextView     *gtktext;
1274         GtkTextBuffer   *textbuf;
1275         GtkTextIter     startiter, enditer;
1276     
1277         if (!newword) return;
1278
1279         gtktext = gtkaspell->gtktext;
1280         textbuf = gtk_text_view_get_buffer(gtktext);
1281
1282         origpos = gtkaspell->orig_pos;
1283         pos     = origpos;
1284         oldlen  = gtkaspell->end_pos - gtkaspell->start_pos;
1285         wordlen = strlen(gtkaspell->theword);
1286
1287         newlen = strlen(newword); /* FIXME: multybyte characters? */
1288
1289         g_signal_handlers_block_by_func(G_OBJECT(gtktext),
1290                                          G_CALLBACK(entry_insert_cb),
1291                                          gtkaspell);
1292         g_signal_handlers_block_by_func(G_OBJECT(gtktext),
1293                                          G_CALLBACK(entry_delete_cb),
1294                                          gtkaspell);
1295
1296         gtk_text_buffer_get_iter_at_offset(textbuf, &startiter,
1297                                            gtkaspell->start_pos);
1298         gtk_text_buffer_get_iter_at_offset(textbuf, &enditer,
1299                                            gtkaspell->end_pos);
1300         g_signal_emit_by_name(G_OBJECT(textbuf), "delete-range",
1301                               &startiter, &enditer, gtkaspell);
1302         g_signal_emit_by_name(G_OBJECT(textbuf), "insert-text",
1303                               &startiter, newword, newlen, gtkaspell);
1304
1305         g_signal_handlers_unblock_by_func(G_OBJECT(gtktext),
1306                                            G_CALLBACK(entry_insert_cb),
1307                                            gtkaspell);
1308         g_signal_handlers_unblock_by_func(G_OBJECT(gtktext),
1309                                            G_CALLBACK(entry_delete_cb),
1310                                            gtkaspell);
1311
1312         /* Put the point and the position where we clicked with the mouse
1313          * It seems to be a hack, as I must thaw,freeze,thaw the widget
1314          * to let it update correctly the word insertion and then the
1315          * point & position position. If not, SEGV after the first replacement
1316          * If the new word ends before point, put the point at its end.
1317          */
1318
1319         if (origpos - gtkaspell->start_pos < oldlen &&
1320             origpos - gtkaspell->start_pos >= 0) {
1321                 /* Original point was in the word.
1322                  * Let it there unless point is going to be outside of the word
1323                  */
1324                 if (origpos - gtkaspell->start_pos >= newlen) {
1325                         pos = gtkaspell->start_pos + newlen;
1326                 }
1327         }
1328         else if (origpos >= gtkaspell->end_pos) {
1329                 /* move the position according to the change of length */
1330                 pos = origpos + newlen - oldlen;
1331         }
1332
1333         gtkaspell->end_pos = gtkaspell->start_pos + strlen(newword); /* FIXME: multibyte characters? */
1334
1335         if (get_textview_buffer_charcount(gtktext) < pos)
1336                 pos = get_textview_buffer_charcount(gtktext);
1337         gtkaspell->orig_pos = pos;
1338
1339         set_textview_buffer_offset(gtktext, gtkaspell->orig_pos);
1340 }
1341
1342 /* Accept this word for this session */
1343 static void add_word_to_session_cb(GtkWidget *w, gpointer data)
1344 {
1345         guint     pos;
1346         GtkTextView *gtktext;
1347         GtkAspell *gtkaspell = (GtkAspell *) data; 
1348         gtktext = gtkaspell->gtktext;
1349
1350         pos = get_textview_buffer_offset(gtktext);
1351
1352         aspell_speller_add_to_session(gtkaspell->gtkaspeller->checker,
1353                                       gtkaspell->theword,
1354                                       strlen(gtkaspell->theword));
1355
1356         check_at(gtkaspell, gtkaspell->start_pos);
1357
1358         gtk_menu_shell_deactivate(GTK_MENU_SHELL(GTK_WIDGET(w)->parent));
1359
1360         set_point_continue(gtkaspell);
1361 }
1362
1363 /* add_word_to_personal_cb() - add word to personal dict. */
1364 static void add_word_to_personal_cb(GtkWidget *w, gpointer data)
1365 {
1366         GtkAspell *gtkaspell = (GtkAspell *) data; 
1367         GtkTextView *gtktext    = gtkaspell->gtktext;
1368
1369         aspell_speller_add_to_personal(gtkaspell->gtkaspeller->checker,
1370                                        gtkaspell->theword,
1371                                        strlen(gtkaspell->theword));
1372
1373         check_at(gtkaspell, gtkaspell->start_pos);
1374
1375         gtk_menu_shell_deactivate(GTK_MENU_SHELL(GTK_WIDGET(w)->parent));
1376         set_point_continue(gtkaspell);
1377 }
1378
1379 static void check_with_alternate_cb(GtkWidget *w, gpointer data)
1380 {
1381         GtkAspell *gtkaspell = (GtkAspell *) data;
1382         gint misspelled;
1383
1384         gtk_menu_shell_deactivate(GTK_MENU_SHELL(GTK_WIDGET(w)->parent));
1385
1386         use_alternate_dict(gtkaspell);
1387         misspelled = check_at(gtkaspell, gtkaspell->start_pos);
1388
1389         if (!gtkaspell->continue_check) {
1390
1391                 gtkaspell->misspelled = misspelled;
1392
1393                 if (gtkaspell->misspelled) {
1394
1395                         misspelled_suggest(gtkaspell, gtkaspell->theword);
1396
1397                         set_textview_buffer_offset(gtkaspell->gtktext,
1398                                             gtkaspell->end_pos);
1399
1400                         gtk_menu_popup(make_sug_menu(gtkaspell), NULL, NULL,
1401                                        set_menu_pos, gtkaspell, 0,
1402                                        GDK_CURRENT_TIME);
1403                         return;
1404                 }
1405         } else
1406                 gtkaspell->orig_pos = gtkaspell->start_pos;
1407
1408         set_point_continue(gtkaspell);
1409 }
1410         
1411 static void replace_with_create_dialog_cb(GtkWidget *w, gpointer data)
1412 {
1413         GtkWidget *dialog;
1414         GtkWidget *label;
1415         GtkWidget *hbox;
1416         GtkWidget *entry;
1417         GtkWidget *ok_button;
1418         GtkWidget *cancel_button;
1419         gchar *thelabel;
1420         gint xx, yy;
1421         GtkAspell *gtkaspell = (GtkAspell *) data;
1422
1423         gdk_window_get_origin((GTK_WIDGET(w)->parent)->window, &xx, &yy);
1424
1425         gtk_menu_shell_deactivate(GTK_MENU_SHELL(GTK_WIDGET(w)->parent));
1426
1427         dialog = gtk_dialog_new();
1428
1429         gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
1430         gtk_window_set_title(GTK_WINDOW(dialog),_("Replace unknown word"));
1431         gtk_widget_set_uposition(dialog, xx, yy);
1432
1433         g_signal_connect_swapped(G_OBJECT(dialog), "destroy",
1434                                  G_CALLBACK(gtk_widget_destroy), 
1435                                  G_OBJECT(dialog));
1436
1437         hbox = gtk_hbox_new(FALSE, 0);
1438         gtk_container_set_border_width(GTK_CONTAINER(hbox), 8);
1439
1440         thelabel = g_strdup_printf(_("Replace \"%s\" with: "), 
1441                                    gtkaspell->theword);
1442         label = gtk_label_new(thelabel);
1443         g_free(thelabel);
1444         gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
1445
1446         entry = gtk_entry_new();
1447         gtkaspell->replace_entry = entry;
1448         gtk_entry_set_text(GTK_ENTRY(entry), gtkaspell->theword);
1449         gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1);
1450         g_signal_connect(G_OBJECT(entry), "activate",
1451                          G_CALLBACK(replace_with_supplied_word_cb), 
1452                          gtkaspell);
1453         g_signal_connect_swapped(G_OBJECT(entry), "activate",
1454                                  G_CALLBACK(gtk_widget_destroy), 
1455                                  G_OBJECT(dialog));
1456         gtk_box_pack_start(GTK_BOX(hbox), entry, TRUE, TRUE, 0);
1457
1458         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), hbox, TRUE, 
1459                            TRUE, 0);
1460         label = gtk_label_new(_("Holding down Control key while pressing "
1461                                 "Enter\nwill learn from mistake.\n"));
1462         gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT);
1463         gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1464         gtk_misc_set_padding(GTK_MISC(label), 8, 0);
1465         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, 
1466                         TRUE, TRUE, 0);
1467
1468         hbox = gtk_hbox_new(TRUE, 0);
1469
1470         ok_button = gtk_button_new_with_label(_("OK"));
1471         gtk_box_pack_start(GTK_BOX(hbox), ok_button, TRUE, TRUE, 8);
1472         g_signal_connect(G_OBJECT(ok_button), "clicked",
1473                          G_CALLBACK(replace_with_supplied_word_cb), 
1474                          gtkaspell);
1475         g_signal_connect_swapped(G_OBJECT(ok_button), "clicked",
1476                                    G_CALLBACK(gtk_widget_destroy), 
1477                                    G_OBJECT(dialog));
1478
1479         cancel_button = gtk_button_new_with_label(_("Cancel"));
1480         gtk_box_pack_start(GTK_BOX(hbox), cancel_button, TRUE, TRUE, 8);
1481         g_signal_connect_swapped(G_OBJECT(cancel_button), "clicked",
1482                                  G_CALLBACK(gtk_widget_destroy), 
1483                                  G_OBJECT(dialog));
1484
1485         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1486
1487         gtk_widget_grab_focus(entry);
1488
1489         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1490
1491         gtk_widget_show_all(dialog);
1492 }
1493
1494 void gtkaspell_uncheck_all(GtkAspell * gtkaspell) 
1495 {
1496         gint      origpos;
1497         gchar    *text;
1498         gfloat    adj_value;
1499         GtkTextView *gtktext;
1500         GtkTextBuffer *buffer;
1501         GtkTextIter startiter, enditer;
1502         
1503         gtktext = gtkaspell->gtktext;
1504
1505         buffer = gtk_text_view_get_buffer(gtktext);
1506         gtk_text_buffer_get_iter_at_offset(buffer, &startiter, 0);
1507         gtk_text_buffer_get_iter_at_offset(buffer, &enditer,
1508                                    get_textview_buffer_charcount(gtktext)-1);
1509         gtk_text_buffer_remove_tag_by_name(buffer, "misspelled",
1510                                            &startiter, &enditer);
1511 }
1512
1513 static void toggle_check_while_typing_cb(GtkWidget *w, gpointer data)
1514 {
1515         GtkAspell *gtkaspell = (GtkAspell *) data;
1516
1517         gtkaspell->check_while_typing = gtkaspell->check_while_typing == FALSE;
1518
1519         if (!gtkaspell->check_while_typing)
1520                 gtkaspell_uncheck_all(gtkaspell);
1521
1522         if (gtkaspell->config_menu)
1523                 populate_submenu(gtkaspell, gtkaspell->config_menu);
1524 }
1525
1526 static GSList *create_empty_dictionary_list(void)
1527 {
1528         GSList *list = NULL;
1529         Dictionary *dict;
1530
1531         dict = g_new0(Dictionary, 1);
1532         dict->fullname = g_strdup(_("None"));
1533         dict->dictname = dict->fullname;
1534         dict->encoding = NULL;
1535
1536         return g_slist_append(list, dict);
1537 }
1538
1539 /* gtkaspell_get_dictionary_list() - returns list of dictionary names */
1540 GSList *gtkaspell_get_dictionary_list(const gchar *aspell_path, gint refresh)
1541 {
1542         GSList *list;
1543         Dictionary *dict;
1544         AspellConfig *config;
1545         AspellDictInfoList *dlist;
1546         AspellDictInfoEnumeration *dels;
1547         const AspellDictInfo *entry;
1548
1549         if (!gtkaspellcheckers)
1550                 gtkaspell_checkers_init();
1551
1552         if (gtkaspellcheckers->dictionary_list && !refresh)
1553                 return gtkaspellcheckers->dictionary_list;
1554         else
1555                 gtkaspell_free_dictionary_list(
1556                                 gtkaspellcheckers->dictionary_list);
1557         list = NULL;
1558
1559         config = new_aspell_config();
1560 #if 0 
1561         aspell_config_replace(config, "rem-all-word-list-path", "");
1562         if (aspell_config_error_number(config) != 0) {
1563                 gtkaspellcheckers->error_message = g_strdup(
1564                                 aspell_config_error_message(config));
1565                 gtkaspellcheckers->dictionary_list =
1566                         create_empty_dictionary_list();
1567
1568                 return gtkaspellcheckers->dictionary_list; 
1569         }
1570 #endif
1571         aspell_config_replace(config, "dict-dir", aspell_path);
1572         if (aspell_config_error_number(config) != 0) {
1573                 gtkaspellcheckers->error_message = g_strdup(
1574                                 aspell_config_error_message(config));
1575                 gtkaspellcheckers->dictionary_list =
1576                         create_empty_dictionary_list();
1577
1578                 return gtkaspellcheckers->dictionary_list; 
1579         }
1580
1581         dlist = get_aspell_dict_info_list(config);
1582         delete_aspell_config(config);
1583
1584         debug_print("Aspell: checking for dictionaries in %s\n", aspell_path);
1585         dels = aspell_dict_info_list_elements(dlist);
1586         while ( (entry = aspell_dict_info_enumeration_next(dels)) != 0) 
1587         {
1588                 dict = g_new0(Dictionary, 1);
1589                 dict->fullname = g_strdup_printf("%s%s", aspell_path, 
1590                                 entry->name);
1591                 dict->dictname = dict->fullname + strlen(aspell_path);
1592                 dict->encoding = g_strdup(entry->code);
1593                 debug_print("Aspell: found dictionary %s %s\n", dict->fullname,
1594                                 dict->dictname);
1595                 list = g_slist_insert_sorted(list, dict,
1596                                 (GCompareFunc) compare_dict);
1597         }
1598
1599         delete_aspell_dict_info_enumeration(dels);
1600         
1601         if(list==NULL){
1602                 
1603                 debug_print("Aspell: error when searching for dictionaries: "
1604                               "No dictionary found.\n");
1605                 list = create_empty_dictionary_list();
1606         }
1607
1608         gtkaspellcheckers->dictionary_list = list;
1609
1610         return list;
1611 }
1612
1613 void gtkaspell_free_dictionary_list(GSList *list)
1614 {
1615         Dictionary *dict;
1616         GSList *walk;
1617         for (walk = list; walk != NULL; walk = g_slist_next(walk))
1618                 if (walk->data) {
1619                         dict = (Dictionary *) walk->data;
1620                         dictionary_delete(dict);
1621                 }                               
1622         g_slist_free(list);
1623 }
1624
1625 GtkWidget *gtkaspell_dictionary_option_menu_new(const gchar *aspell_path)
1626 {
1627         GSList *dict_list, *tmp;
1628         GtkWidget *item;
1629         GtkWidget *menu;
1630         Dictionary *dict;
1631
1632         dict_list = gtkaspell_get_dictionary_list(aspell_path, TRUE);
1633         g_return_val_if_fail(dict_list, NULL);
1634
1635         menu = gtk_menu_new();
1636         
1637         for (tmp = dict_list; tmp != NULL; tmp = g_slist_next(tmp)) {
1638                 dict = (Dictionary *) tmp->data;
1639                 item = gtk_menu_item_new_with_label(dict->dictname);
1640                 g_object_set_data(G_OBJECT(item), "dict_name",
1641                                   dict->fullname); 
1642                                          
1643                 gtk_menu_append(GTK_MENU(menu), item);                                   
1644                 gtk_widget_show(item);
1645         }
1646
1647         gtk_widget_show(menu);
1648
1649         return menu;
1650 }
1651
1652 gchar *gtkaspell_get_dictionary_menu_active_item(GtkWidget *menu)
1653 {
1654         GtkWidget *menuitem;
1655         gchar *dict_fullname;
1656         gchar *label;
1657
1658         g_return_val_if_fail(GTK_IS_MENU(menu), NULL);
1659
1660         menuitem = gtk_menu_get_active(GTK_MENU(menu));
1661         dict_fullname = (gchar *) g_object_get_data(G_OBJECT(menuitem), 
1662                                                     "dict_name");
1663         g_return_val_if_fail(dict_fullname, NULL);
1664
1665         label = g_strdup(dict_fullname);
1666
1667         return label;
1668   
1669 }
1670
1671 gint gtkaspell_set_dictionary_menu_active_item(GtkWidget *menu,
1672                                                const gchar *dictionary)
1673 {
1674         GList *cur;
1675         gint n;
1676
1677         g_return_val_if_fail(menu != NULL, 0);
1678         g_return_val_if_fail(dictionary != NULL, 0);
1679         g_return_val_if_fail(GTK_IS_OPTION_MENU(menu), 0);
1680
1681         n = 0;
1682         for (cur = GTK_MENU_SHELL(gtk_option_menu_get_menu(
1683                                         GTK_OPTION_MENU(menu)))->children;
1684              cur != NULL; cur = cur->next) {
1685                 GtkWidget *menuitem;
1686                 gchar *dict_name;
1687
1688                 menuitem = GTK_WIDGET(cur->data);
1689                 dict_name = g_object_get_data(G_OBJECT(menuitem), 
1690                                               "dict_name");
1691                 if ((dict_name != NULL) && !strcmp2(dict_name, dictionary)) {
1692                         gtk_option_menu_set_history(GTK_OPTION_MENU(menu), n);
1693
1694                         return 1;
1695                 }
1696                 n++;
1697         }
1698
1699         return 0;
1700 }
1701
1702 GtkWidget *gtkaspell_sugmode_option_menu_new(gint sugmode)
1703 {
1704         GtkWidget *menu;
1705         GtkWidget *item;
1706
1707         menu = gtk_menu_new();
1708         gtk_widget_show(menu);
1709
1710         item = gtk_menu_item_new_with_label(_("Fast Mode"));
1711         gtk_widget_show(item);
1712         gtk_menu_append(GTK_MENU(menu), item);
1713         g_object_set_data(G_OBJECT(item), "sugmode",
1714                           GINT_TO_POINTER(ASPELL_FASTMODE));
1715
1716         item = gtk_menu_item_new_with_label(_("Normal Mode"));
1717         gtk_widget_show(item);
1718         gtk_menu_append(GTK_MENU(menu), item);
1719         g_object_set_data(G_OBJECT(item), "sugmode",
1720                           GINT_TO_POINTER(ASPELL_NORMALMODE));
1721         
1722         item = gtk_menu_item_new_with_label(_("Bad Spellers Mode"));
1723         gtk_widget_show(item);
1724         gtk_menu_append(GTK_MENU(menu), item);
1725         g_object_set_data(G_OBJECT(item), "sugmode",
1726                           GINT_TO_POINTER(ASPELL_BADSPELLERMODE));
1727
1728         return menu;
1729 }
1730         
1731 void gtkaspell_sugmode_option_menu_set(GtkOptionMenu *optmenu, gint sugmode)
1732 {
1733         g_return_if_fail(GTK_IS_OPTION_MENU(optmenu));
1734
1735         g_return_if_fail(sugmode == ASPELL_FASTMODE ||
1736                          sugmode == ASPELL_NORMALMODE ||
1737                          sugmode == ASPELL_BADSPELLERMODE);
1738
1739         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), sugmode - 1);
1740 }
1741
1742 gint gtkaspell_get_sugmode_from_option_menu(GtkOptionMenu *optmenu)
1743 {
1744         gint sugmode;
1745         GtkWidget *item;
1746         
1747         g_return_val_if_fail(GTK_IS_OPTION_MENU(optmenu), -1);
1748
1749         item = gtk_menu_get_active(GTK_MENU(gtk_option_menu_get_menu(optmenu)));
1750         
1751         sugmode = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item),
1752                                                     "sugmode"));
1753
1754         return sugmode;
1755 }
1756
1757 static void use_alternate_dict(GtkAspell *gtkaspell)
1758 {
1759         GtkAspeller *tmp;
1760
1761         tmp = gtkaspell->gtkaspeller;
1762         gtkaspell->gtkaspeller = gtkaspell->alternate_speller;
1763         gtkaspell->alternate_speller = tmp;
1764
1765         if (gtkaspell->config_menu)
1766                 populate_submenu(gtkaspell, gtkaspell->config_menu);
1767 }
1768
1769 static void popup_menu(GtkAspell *gtkaspell, GdkEventButton *eb) 
1770 {
1771         GtkTextView * gtktext;
1772         
1773         gtktext = gtkaspell->gtktext;
1774
1775         gtkaspell->orig_pos = get_textview_buffer_offset(gtktext);
1776
1777         if (!(eb->state & GDK_SHIFT_MASK)) {
1778                 if (check_at(gtkaspell, gtkaspell->orig_pos)) {
1779
1780                         set_textview_buffer_offset(gtktext, gtkaspell->orig_pos);
1781
1782                         if (misspelled_suggest(gtkaspell, gtkaspell->theword)) {
1783                                 gtk_menu_popup(make_sug_menu(gtkaspell),
1784                                                NULL, NULL, NULL, NULL,
1785                                                eb->button, GDK_CURRENT_TIME);
1786
1787                                 return;
1788                         }
1789                 } else
1790                         set_textview_buffer_offset(gtktext, gtkaspell->orig_pos);
1791         }
1792
1793         gtk_menu_popup(make_config_menu(gtkaspell), NULL, NULL, NULL, NULL,
1794                        eb->button, GDK_CURRENT_TIME);
1795 }
1796
1797 static gboolean aspell_key_pressed(GtkWidget *widget,
1798                                    GdkEventKey *event,
1799                                    GtkAspell *gtkaspell)
1800 {
1801         if (event && isascii(event->keyval)) {
1802                 gtk_accel_groups_activate(gtkaspell->parent_window, 
1803                                 event->keyval, event->state);
1804         }
1805         return FALSE;
1806 }
1807
1808 /* make_sug_menu() - Add menus to accept this word for this session 
1809  * and to add it to personal dictionary 
1810  */
1811 static GtkMenu *make_sug_menu(GtkAspell *gtkaspell) 
1812 {
1813         GtkWidget       *menu, *item;
1814         unsigned char   *caption;
1815         GtkTextView     *gtktext;
1816         GtkAccelGroup   *accel;
1817         GList           *l = gtkaspell->suggestions_list;
1818         gchar           *utf8buf;
1819
1820         gtktext = gtkaspell->gtktext;
1821
1822         accel = gtk_accel_group_new();
1823         menu = gtk_menu_new(); 
1824
1825         if (gtkaspell->sug_menu)
1826                 gtk_widget_destroy(gtkaspell->sug_menu);
1827
1828         gtkaspell->sug_menu = menu;     
1829
1830         g_signal_connect(G_OBJECT(menu), "cancel",
1831                          G_CALLBACK(cancel_menu_cb), gtkaspell);
1832
1833         caption = g_strdup_printf(_("\"%s\" unknown in %s"), 
1834                                   (unsigned char*) l->data, 
1835                                   gtkaspell->gtkaspeller->dictionary->dictname);
1836         item = gtk_menu_item_new_with_label(caption);
1837         gtk_widget_show(item);
1838         gtk_menu_append(GTK_MENU(menu), item);
1839         gtk_misc_set_alignment(GTK_MISC(GTK_BIN(item)->child), 0.5, 0.5);
1840         g_free(caption);
1841
1842         item = gtk_menu_item_new();
1843         gtk_widget_show(item);
1844         gtk_menu_append(GTK_MENU(menu), item);
1845
1846         item = gtk_menu_item_new_with_label(_("Accept in this session"));
1847         gtk_widget_show(item);
1848         gtk_menu_append(GTK_MENU(menu), item);
1849         g_signal_connect(G_OBJECT(item), "activate",
1850                          G_CALLBACK(add_word_to_session_cb), 
1851                          gtkaspell);
1852         gtk_widget_add_accelerator(item, "activate", accel, GDK_space,
1853                                    GDK_CONTROL_MASK,
1854                                    GTK_ACCEL_LOCKED | GTK_ACCEL_VISIBLE);
1855
1856         item = gtk_menu_item_new_with_label(_("Add to personal dictionary"));
1857         gtk_widget_show(item);
1858         gtk_menu_append(GTK_MENU(menu), item);
1859         g_signal_connect(G_OBJECT(item), "activate",
1860                          G_CALLBACK(add_word_to_personal_cb), 
1861                          gtkaspell);
1862         gtk_widget_add_accelerator(item, "activate", accel, GDK_Return,
1863                                    GDK_CONTROL_MASK,
1864                                    GTK_ACCEL_LOCKED | GTK_ACCEL_VISIBLE);
1865
1866         item = gtk_menu_item_new_with_label(_("Replace with..."));
1867         gtk_widget_show(item);
1868         gtk_menu_append(GTK_MENU(menu), item);
1869         g_signal_connect(G_OBJECT(item), "activate",
1870                          G_CALLBACK(replace_with_create_dialog_cb), 
1871                          gtkaspell);
1872         gtk_widget_add_accelerator(item, "activate", accel, GDK_R, 0,
1873                                    GTK_ACCEL_LOCKED | GTK_ACCEL_VISIBLE);
1874
1875         if (gtkaspell->use_alternate && gtkaspell->alternate_speller) {
1876                 caption = g_strdup_printf(_("Check with %s"), 
1877                         gtkaspell->alternate_speller->dictionary->dictname);
1878                 item = gtk_menu_item_new_with_label(caption);
1879                 g_free(caption);
1880                 gtk_widget_show(item);
1881                 gtk_menu_append(GTK_MENU(menu), item);
1882                 g_signal_connect(G_OBJECT(item), "activate",
1883                                  G_CALLBACK(check_with_alternate_cb),
1884                                  gtkaspell);
1885                 gtk_widget_add_accelerator(item, "activate", accel, GDK_X, 0,
1886                                            GTK_ACCEL_LOCKED | GTK_ACCEL_VISIBLE);
1887         }
1888
1889         item = gtk_menu_item_new();
1890         gtk_widget_show(item);
1891         gtk_menu_append(GTK_MENU(menu), item);
1892
1893         l = l->next;
1894         if (l == NULL) {
1895                 item = gtk_menu_item_new_with_label(_("(no suggestions)"));
1896                 gtk_widget_show(item);
1897                 gtk_menu_append(GTK_MENU(menu), item);
1898         } else {
1899                 GtkWidget *curmenu = menu;
1900                 gint count = 0;
1901                 
1902                 do {
1903                         if (count == MENUCOUNT) {
1904                                 count -= MENUCOUNT;
1905
1906                                 item = gtk_menu_item_new_with_label(_("More..."));
1907                                 gtk_widget_show(item);
1908                                 gtk_menu_append(GTK_MENU(curmenu), item);
1909
1910                                 curmenu = gtk_menu_new();
1911                                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item),
1912                                                           curmenu);
1913                         }
1914
1915                         utf8buf  = conv_codeset_strdup((unsigned char*)l->data,
1916                                                         conv_get_current_charset_str(),
1917                                                         CS_UTF_8);
1918                         item = gtk_menu_item_new_with_label(utf8buf);
1919                         gtk_widget_show(item);
1920                         gtk_menu_append(GTK_MENU(curmenu), item);
1921                         g_signal_connect(G_OBJECT(item), "activate",
1922                                          G_CALLBACK(replace_word_cb),
1923                                          gtkaspell);
1924
1925                         if (curmenu == menu && count < MENUCOUNT) {
1926                                 gtk_widget_add_accelerator(item, "activate",
1927                                                            accel,
1928                                                            GDK_A + count, 0,
1929                                                            GTK_ACCEL_LOCKED | 
1930                                                            GTK_ACCEL_VISIBLE);
1931                                 gtk_widget_add_accelerator(item, "activate", 
1932                                                            accel,
1933                                                            GDK_A + count, 
1934                                                            GDK_CONTROL_MASK,
1935                                                            GTK_ACCEL_LOCKED);
1936                                 }
1937
1938                         count++;
1939
1940                 } while ((l = l->next) != NULL);
1941         }
1942
1943         gtk_window_add_accel_group
1944                 (GTK_WINDOW(gtkaspell->parent_window),
1945                  accel);
1946         g_signal_connect(G_OBJECT(menu),
1947                         "key_press_event",
1948                         G_CALLBACK(aspell_key_pressed), gtkaspell);
1949         
1950         return GTK_MENU(menu);
1951 }
1952
1953 static void populate_submenu(GtkAspell *gtkaspell, GtkWidget *menu)
1954 {
1955         GtkWidget *item, *submenu;
1956         gchar *dictname;
1957         GtkAspeller *gtkaspeller = gtkaspell->gtkaspeller;
1958
1959         if (GTK_MENU_SHELL(menu)->children) {
1960                 GList *amenu, *alist;
1961                 for (amenu = (GTK_MENU_SHELL(menu)->children); amenu; ) {
1962                         alist = amenu->next;
1963                         gtk_widget_destroy(GTK_WIDGET(amenu->data));
1964                         amenu = alist;
1965                 }
1966         }
1967         
1968         dictname = g_strdup_printf(_("Dictionary: %s"),
1969                                    gtkaspeller->dictionary->dictname);
1970         item = gtk_menu_item_new_with_label(dictname);
1971         gtk_misc_set_alignment(GTK_MISC(GTK_BIN(item)->child), 0.5, 0.5);
1972         g_free(dictname);
1973         gtk_widget_show(item);
1974         gtk_menu_append(GTK_MENU(menu), item);
1975
1976         item = gtk_menu_item_new();
1977         gtk_widget_show(item);
1978         gtk_menu_append(GTK_MENU(menu), item);
1979                 
1980         if (gtkaspell->use_alternate && gtkaspell->alternate_speller) {
1981                 dictname = g_strdup_printf(_("Use alternate (%s)"), 
1982                                 gtkaspell->alternate_speller->dictionary->dictname);
1983                 item = gtk_menu_item_new_with_label(dictname);
1984                 g_free(dictname);
1985                 g_signal_connect(G_OBJECT(item), "activate",
1986                                  G_CALLBACK(switch_to_alternate_cb),
1987                                  gtkaspell);
1988                 gtk_widget_show(item);
1989                 gtk_menu_append(GTK_MENU(menu), item);
1990         }
1991
1992         item = gtk_check_menu_item_new_with_label(_("Fast Mode"));
1993         if (gtkaspell->gtkaspeller->sug_mode == ASPELL_FASTMODE) {
1994                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),TRUE);
1995                 gtk_widget_set_sensitive(GTK_WIDGET(item),FALSE);
1996         } else
1997                 g_signal_connect(G_OBJECT(item), "activate",
1998                                  G_CALLBACK(set_sug_mode_cb),
1999                                  gtkaspell);
2000         gtk_widget_show(item);
2001         gtk_menu_append(GTK_MENU(menu), item);
2002
2003         item = gtk_check_menu_item_new_with_label(_("Normal Mode"));
2004         if (gtkaspell->gtkaspeller->sug_mode == ASPELL_NORMALMODE) {
2005                 gtk_widget_set_sensitive(GTK_WIDGET(item), FALSE);
2006                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE);
2007         } else
2008                 g_signal_connect(G_OBJECT(item), "activate",
2009                                  G_CALLBACK(set_sug_mode_cb),
2010                                  gtkaspell);
2011         gtk_widget_show(item);
2012         gtk_menu_append(GTK_MENU(menu),item);
2013
2014         item = gtk_check_menu_item_new_with_label(_("Bad Spellers Mode"));
2015         if (gtkaspell->gtkaspeller->sug_mode == ASPELL_BADSPELLERMODE) {
2016                 gtk_widget_set_sensitive(GTK_WIDGET(item), FALSE);
2017                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE);
2018         } else
2019                 g_signal_connect(G_OBJECT(item), "activate",
2020                                  G_CALLBACK(set_sug_mode_cb),
2021                                  gtkaspell);
2022         gtk_widget_show(item);
2023         gtk_menu_append(GTK_MENU(menu), item);
2024         
2025         item = gtk_menu_item_new();
2026         gtk_widget_show(item);
2027         gtk_menu_append(GTK_MENU(menu), item);
2028         
2029         item = gtk_check_menu_item_new_with_label(_("Check while typing"));
2030         if (gtkaspell->check_while_typing)
2031                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE);
2032         else    
2033                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), FALSE);
2034         g_signal_connect(G_OBJECT(item), "activate",
2035                          G_CALLBACK(toggle_check_while_typing_cb),
2036                          gtkaspell);
2037         gtk_widget_show(item);
2038         gtk_menu_append(GTK_MENU(menu), item);
2039
2040         item = gtk_menu_item_new();
2041         gtk_widget_show(item);
2042         gtk_menu_append(GTK_MENU(menu), item);
2043
2044         submenu = gtk_menu_new();
2045         item = gtk_menu_item_new_with_label(_("Change dictionary"));
2046         gtk_menu_item_set_submenu(GTK_MENU_ITEM(item),submenu);
2047         gtk_widget_show(item);
2048         gtk_menu_append(GTK_MENU(menu), item);
2049
2050         /* Dict list */
2051         if (gtkaspellcheckers->dictionary_list == NULL)
2052                 gtkaspell_get_dictionary_list(gtkaspell->dictionary_path, FALSE);
2053         {
2054                 GtkWidget * curmenu = submenu;
2055                 int count = 0;
2056                 Dictionary *dict;
2057                 GSList *tmp;
2058                 tmp = gtkaspellcheckers->dictionary_list;
2059                 
2060                 for (tmp = gtkaspellcheckers->dictionary_list; tmp != NULL; 
2061                                 tmp = g_slist_next(tmp)) {
2062                         if (count == MENUCOUNT) {
2063                                 GtkWidget *newmenu;
2064                                 
2065                                 newmenu = gtk_menu_new();
2066                                 item = gtk_menu_item_new_with_label(_("More..."));
2067                                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), 
2068                                                           newmenu);
2069                                 
2070                                 gtk_menu_append(GTK_MENU(curmenu), item);
2071                                 gtk_widget_show(item);
2072                                 curmenu = newmenu;
2073                                 count = 0;
2074                         }
2075                         dict = (Dictionary *) tmp->data;
2076                         item = gtk_check_menu_item_new_with_label(dict->dictname);
2077                         g_object_set_data(G_OBJECT(item), "dict_name",
2078                                           dict->fullname); 
2079                         if (strcmp2(dict->fullname,
2080                             gtkaspell->gtkaspeller->dictionary->fullname))
2081                                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), FALSE);
2082                         else {
2083                                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE);
2084                                 gtk_widget_set_sensitive(GTK_WIDGET(item),
2085                                                          FALSE);
2086                         }
2087                         g_signal_connect(G_OBJECT(item), "activate",
2088                                          G_CALLBACK(change_dict_cb),
2089                                          gtkaspell);
2090                         gtk_widget_show(item);
2091                         gtk_menu_append(GTK_MENU(curmenu), item);
2092                         
2093                         count++;
2094                 }
2095         }  
2096 }
2097
2098 static GtkMenu *make_config_menu(GtkAspell *gtkaspell)
2099 {
2100         if (!gtkaspell->popup_config_menu)
2101                 gtkaspell->popup_config_menu = gtk_menu_new();
2102
2103         debug_print("Aspell: creating/using popup_config_menu %0x\n", 
2104                         (guint) gtkaspell->popup_config_menu);
2105         populate_submenu(gtkaspell, gtkaspell->popup_config_menu);
2106
2107         return GTK_MENU(gtkaspell->popup_config_menu);
2108 }
2109
2110 void gtkaspell_populate_submenu(GtkAspell *gtkaspell, GtkWidget *menuitem)
2111 {
2112         GtkWidget *menu;
2113
2114         menu = GTK_WIDGET(GTK_MENU_ITEM(menuitem)->submenu);
2115         
2116         debug_print("Aspell: using config menu %0x\n", 
2117                         (guint) gtkaspell->popup_config_menu);
2118         populate_submenu(gtkaspell, menu);
2119         
2120         gtkaspell->config_menu = menu;
2121         
2122 }
2123
2124 static void set_menu_pos(GtkMenu *menu, gint *x, gint *y, 
2125                          gboolean *push_in, gpointer data)
2126 {
2127         GtkAspell       *gtkaspell = (GtkAspell *) data;
2128         gint             xx = 0, yy = 0;
2129         gint             sx,     sy;
2130         gint             wx,     wy;
2131         GtkTextView     *text = GTK_TEXT_VIEW(gtkaspell->gtktext);
2132         GtkTextBuffer   *textbuf;
2133         GtkTextIter      iter;
2134         GdkRectangle     rect;
2135         GtkRequisition   r;
2136
2137         textbuf = gtk_text_view_get_buffer(gtkaspell->gtktext);
2138         gtk_text_buffer_get_iter_at_mark(textbuf, &iter,
2139                                          gtk_text_buffer_get_insert(textbuf));
2140         gtk_text_view_get_iter_location(gtkaspell->gtktext, &iter, &rect);
2141         gtk_text_view_buffer_to_window_coords(text, GTK_TEXT_WINDOW_TEXT,
2142                                               rect.x, rect.y, 
2143                                               &rect.x, &rect.y);
2144
2145         gdk_window_get_origin(GTK_WIDGET(gtkaspell->gtktext)->window, &xx, &yy);
2146
2147         sx = gdk_screen_width();
2148         sy = gdk_screen_height();
2149
2150         gtk_widget_get_child_requisition(GTK_WIDGET(menu), &r);
2151
2152         wx =  r.width;
2153         wy =  r.height;
2154
2155         *x = rect.x + xx +
2156              gdk_char_width(gtk_style_get_font(GTK_WIDGET(text)->style), ' ');
2157
2158         *y = rect.y + rect.height + yy;
2159
2160         if (*x + wx > sx)
2161                 *x = sx - wx;
2162         if (*y + wy > sy)
2163                 *y = *y - wy -
2164                      gdk_string_height(gtk_style_get_font(
2165                                                 GTK_WIDGET(text)->style),
2166                                        gtkaspell->theword);
2167 }
2168
2169 /* Menu call backs */
2170
2171 static gboolean cancel_menu_cb(GtkMenuShell *w, gpointer data)
2172 {
2173         GtkAspell *gtkaspell = (GtkAspell *) data;
2174
2175         gtkaspell->continue_check = NULL;
2176         set_point_continue(gtkaspell);
2177
2178         return FALSE;
2179 }
2180
2181 gboolean gtkaspell_change_dict(GtkAspell *gtkaspell, const gchar *dictionary)
2182 {
2183         Dictionary      *dict;       
2184         GtkAspeller     *gtkaspeller;
2185         gint             sug_mode;
2186
2187         g_return_val_if_fail(gtkaspell, FALSE);
2188         g_return_val_if_fail(dictionary, FALSE);
2189   
2190         sug_mode  = gtkaspell->default_sug_mode;
2191
2192         dict = g_new0(Dictionary, 1);
2193         dict->fullname = g_strdup(dictionary);
2194         dict->encoding = g_strdup(gtkaspell->gtkaspeller->dictionary->encoding);
2195
2196         if (gtkaspell->use_alternate && gtkaspell->alternate_speller &&
2197             dict == gtkaspell->alternate_speller->dictionary) {
2198                 use_alternate_dict(gtkaspell);
2199                 dictionary_delete(dict);
2200                 return TRUE;
2201         }
2202         
2203         gtkaspeller = gtkaspeller_new(dict);
2204
2205         if (!gtkaspeller) {
2206                 gchar *message;
2207                 message = g_strdup_printf(_("The spell checker could not change dictionary.\n%s"), 
2208                                           gtkaspellcheckers->error_message);
2209
2210                 gtkaspell_alert_dialog(message); 
2211                 g_free(message);
2212         } else {
2213                 if (gtkaspell->use_alternate) {
2214                         if (gtkaspell->alternate_speller)
2215                                 gtkaspeller_delete(gtkaspell->alternate_speller);
2216                         gtkaspell->alternate_speller = gtkaspell->gtkaspeller;
2217                 } else
2218                         gtkaspeller_delete(gtkaspell->gtkaspeller);
2219
2220                 gtkaspell->gtkaspeller = gtkaspeller;
2221                 gtkaspell_set_sug_mode(gtkaspell, sug_mode);
2222         }
2223         
2224         dictionary_delete(dict);
2225
2226         if (gtkaspell->config_menu)
2227                 populate_submenu(gtkaspell, gtkaspell->config_menu);
2228
2229         return TRUE;    
2230 }
2231
2232 /* change_dict_cb() - Menu callback : change dict */
2233 static void change_dict_cb(GtkWidget *w, GtkAspell *gtkaspell)
2234 {
2235         gchar           *fullname;
2236   
2237         fullname = (gchar *) g_object_get_data(G_OBJECT(w), "dict_name");
2238         
2239         if (!strcmp2(fullname, _("None")))
2240                 return;
2241
2242         gtkaspell_change_dict(gtkaspell, fullname);
2243 }
2244
2245 static void switch_to_alternate_cb(GtkWidget *w,
2246                                    gpointer data)
2247 {
2248         GtkAspell *gtkaspell = (GtkAspell *) data;
2249         use_alternate_dict(gtkaspell);
2250 }
2251
2252 /* Misc. helper functions */
2253
2254 static void set_point_continue(GtkAspell *gtkaspell)
2255 {
2256         GtkTextView  *gtktext;
2257
2258         gtktext = gtkaspell->gtktext;
2259
2260         set_textview_buffer_offset(gtktext, gtkaspell->orig_pos);
2261
2262         if (gtkaspell->continue_check)
2263                 gtkaspell->continue_check((gpointer *) gtkaspell);
2264 }
2265
2266 static void allocate_color(GtkAspell *gtkaspell, gint rgbvalue)
2267 {
2268         GtkTextBuffer *buffer = gtk_text_view_get_buffer(gtkaspell->gtktext);
2269         GdkColor *color = &(gtkaspell->highlight);
2270
2271         /* Shameless copy from Sylpheed's gtkutils.c */
2272         color->pixel = 0L;
2273         color->red   = (int) (((gdouble)((rgbvalue & 0xff0000) >> 16) / 255.0)
2274                         * 65535.0);
2275         color->green = (int) (((gdouble)((rgbvalue & 0x00ff00) >>  8) / 255.0)
2276                         * 65535.0);
2277         color->blue  = (int) (((gdouble) (rgbvalue & 0x0000ff)        / 255.0)
2278                         * 65535.0);
2279
2280         gtk_text_buffer_create_tag(buffer, "misspelled",
2281                                    "foreground-gdk", color, NULL);
2282 }
2283
2284 static void change_color(GtkAspell * gtkaspell, 
2285                          gint start, gint end,
2286                          gchar *newtext,
2287                          GdkColor *color) 
2288 {
2289         GtkTextView *gtktext;
2290         GtkTextBuffer *buffer;
2291         GtkTextIter startiter, enditer;
2292
2293         g_return_if_fail(start < end);
2294     
2295         gtktext = gtkaspell->gtktext;
2296     
2297         buffer = gtk_text_view_get_buffer(gtktext);
2298         gtk_text_buffer_get_iter_at_offset(buffer, &startiter, start);
2299         gtk_text_buffer_get_iter_at_offset(buffer, &enditer, end);
2300         if (color)
2301                 gtk_text_buffer_apply_tag_by_name(buffer, "misspelled",
2302                                                   &startiter, &enditer);
2303         else
2304                 gtk_text_buffer_remove_tag_by_name(buffer, "misspelled",
2305                                                    &startiter, &enditer);
2306 }
2307
2308 /* convert_to_aspell_encoding () - converts ISO-8859-* strings to iso8859-* 
2309  * as needed by aspell. Returns an allocated string.
2310  */
2311
2312 static guchar *convert_to_aspell_encoding (const guchar *encoding)
2313 {
2314         guchar * aspell_encoding;
2315
2316         if (strstr2(encoding, "ISO-8859-")) {
2317                 aspell_encoding = g_strdup_printf("iso8859%s", encoding+8);
2318         }
2319         else {
2320                 if (!strcmp2(encoding, "US-ASCII"))
2321                         aspell_encoding = g_strdup("iso8859-1");
2322                 else
2323                         aspell_encoding = g_strdup(encoding);
2324         }
2325
2326         return aspell_encoding;
2327 }
2328
2329 /* compare_dict () - compare 2 dict names */
2330 static gint compare_dict(Dictionary *a, Dictionary *b)
2331 {
2332         guint   aparts = 0,  bparts = 0;
2333         guint   i;
2334
2335         for (i=0; i < strlen(a->dictname); i++)
2336                 if (a->dictname[i] == '-')
2337                         aparts++;
2338         for (i=0; i < strlen(b->dictname); i++)
2339                 if (b->dictname[i] == '-')
2340                         bparts++;
2341
2342         if (aparts != bparts) 
2343                 return (aparts < bparts) ? -1 : +1;
2344         else {
2345                 gint compare;
2346                 compare = strcmp2(a->dictname, b->dictname);
2347                 if (!compare)
2348                         compare = strcmp2(a->fullname, b->fullname);
2349                 return compare;
2350         }
2351 }
2352
2353 static void dictionary_delete(Dictionary *dict)
2354 {
2355         g_free(dict->fullname);
2356         g_free(dict->encoding);
2357         g_free(dict);
2358 }
2359
2360 static Dictionary *dictionary_dup(const Dictionary *dict)
2361 {
2362         Dictionary *dict2;
2363
2364         dict2 = g_new(Dictionary, 1); 
2365
2366         dict2->fullname = g_strdup(dict->fullname);
2367         dict2->dictname = dict->dictname - dict->fullname + dict2->fullname;
2368         dict2->encoding = g_strdup(dict->encoding);
2369
2370         return dict2;
2371 }
2372
2373 static void free_suggestions_list(GtkAspell *gtkaspell)
2374 {
2375         GList *list;
2376
2377         for (list = gtkaspell->suggestions_list; list != NULL;
2378              list = list->next)
2379                 g_free(list->data);
2380
2381         g_list_free(list);
2382         
2383         gtkaspell->max_sug          = -1;
2384         gtkaspell->suggestions_list = NULL;
2385 }
2386
2387 static void reset_theword_data(GtkAspell *gtkaspell)
2388 {
2389         gtkaspell->start_pos     =  0;
2390         gtkaspell->end_pos       =  0;
2391         gtkaspell->theword[0]    =  0;
2392         gtkaspell->max_sug       = -1;
2393
2394         free_suggestions_list(gtkaspell);
2395 }
2396
2397 static void free_checkers(gpointer elt, gpointer data)
2398 {
2399         GtkAspeller *gtkaspeller = elt;
2400
2401         g_return_if_fail(gtkaspeller);
2402
2403         gtkaspeller_real_delete(gtkaspeller);
2404 }
2405
2406 static gint find_gtkaspeller(gconstpointer aa, gconstpointer bb)
2407 {
2408         Dictionary *a = ((GtkAspeller *) aa)->dictionary;
2409         Dictionary *b = ((GtkAspeller *) bb)->dictionary;
2410
2411         if (a && b && a->fullname && b->fullname  &&
2412             strcmp(a->fullname, b->fullname) == 0 &&
2413             a->encoding && b->encoding)
2414                 return strcmp(a->encoding, b->encoding);
2415
2416         return 1;
2417 }
2418
2419 static void gtkaspell_alert_dialog(gchar *message)
2420 {
2421         GtkWidget *dialog;
2422         GtkWidget *hbox;
2423         GtkWidget *label;
2424         GtkWidget *ok_button;
2425
2426         dialog = gtk_dialog_new();
2427         gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
2428         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_MOUSE);
2429         g_signal_connect_swapped(G_OBJECT(dialog), "destroy",
2430                                  G_CALLBACK(gtk_widget_destroy), 
2431                                  G_OBJECT(dialog));
2432
2433         label  = gtk_label_new(message);
2434         gtk_misc_set_padding(GTK_MISC(label), 8, 8);
2435
2436         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), label);
2437         
2438         hbox = gtk_hbox_new(FALSE, 0);
2439
2440         ok_button = gtk_button_new_with_label(_("OK"));
2441         GTK_WIDGET_SET_FLAGS(ok_button, GTK_CAN_DEFAULT);
2442         gtk_box_pack_start(GTK_BOX(hbox), ok_button, TRUE, TRUE, 8);    
2443
2444         g_signal_connect_swapped(G_OBJECT(ok_button), "clicked",
2445                                  G_CALLBACK(gtk_widget_destroy), 
2446                                  G_OBJECT(dialog));
2447         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
2448                         
2449         gtk_widget_grab_default(ok_button);
2450         gtk_widget_grab_focus(ok_button);
2451         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
2452
2453         gtk_widget_show_all(dialog);
2454 }
2455 #endif