109ea23a4aa90661ee8ae0d41fcb5f1820b9612d
[claws.git] / src / gtkspell.c
1 /* gtkpspell - a spell-checking addon for GtkText
2  * Copyright (c) 2000 Evan Martin.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
17  */
18 /*
19     Stuphead: (C) 2000,2001 Grigroy Bakunov, Sergey Pinaev
20  */
21
22 /*
23  * Adapted for Sylpheed (Claws) (c) 2001 by Hiroyuki Yamamoto & 
24  * The Sylpheed Claws Team.
25  */
26
27 /*
28  *  Adapted for pspell (c) 2001 Melvin Hadasht
29  *
30  */
31 #if defined(HAVE_CONFIG_H)
32 #include "config.h"
33 #endif
34
35 #if USE_PSPELL
36 #include "intl.h"
37
38 #include <gtk/gtk.h>
39 #include <sys/types.h>
40 #include <sys/wait.h>
41 #include <unistd.h>
42 #include <stdio.h>
43 #include <signal.h>
44 #include <ctype.h>
45 #include <string.h>
46 #include <stdlib.h>
47 #include <errno.h>
48 #include <stdio.h>
49 #include <sys/time.h>
50 #include <fcntl.h>
51 #include <time.h>
52 #include <prefs_common.h>
53 #include <utils.h>
54
55 #include <dirent.h>
56
57 #include <gtk/gtkoptionmenu.h>
58 #include <gtk/gtkmenu.h>
59 #include <gtk/gtkmenuitem.h>
60
61 #include "gtkxtext.h"
62
63 #include "gtkspell.h"
64
65 #include <pspell/pspell.h>
66
67 /* size of the text buffer used in various word-processing routines. */
68 #define BUFSIZE 1024
69
70 /* number of suggestions to display on each menu. */
71 #define MENUCOUNT 15
72
73
74 /* Only one config per session */
75
76 GtkPspellConfig * gtkpspellconfig;
77
78 /* Function called from menus */
79
80 static void add_word_to_session(GtkWidget *w, GtkPspell * d);
81 static void add_word_to_personal(GtkWidget *w, GtkPspell * d);
82 static void set_sug_mode(GtkWidget *w, GtkPspell * gtkpspell);
83 static void check_all(GtkWidget *w, GtkPspell * gtkpspell);
84 static void menu_change_dict(GtkWidget *w, GtkPspell * gtkpspell);
85
86 static GdkColor highlight = { 0, 255 * 256, 0, 0 };
87
88 static void entry_insert_cb(GtkXText *gtktext,
89                             gchar *newtext, guint len, guint *ppos, 
90                             GtkPspell *gtkpspell);
91
92 /*  Run the first pspell_config from which every new config is */
93 /*    cloned  */
94
95 GtkPspellConfig * gtkpspell_init(){
96   return new_pspell_config();
97 }
98
99 /* Finish all. No more spelling. Called when the program ends */
100
101 void gtkpspell_finished(GtkPspellConfig * gtkpspellconfig){
102   if(gtkpspellconfig){
103     delete_pspell_config( gtkpspellconfig );
104     gtkpspellconfig = NULL;
105   }
106 }
107
108
109 /* Test if there is a manager running */
110
111 int gtkpspell_running(GtkPspell * gtkpspell) 
112 {
113         return (gtkpspell->config!=NULL);
114 }
115
116 /* Creates a new session if a gtkpspellconfig exists */
117 /* The settings are defaults.  If no path/dict is set afterwards, the default one is used  */
118
119 GtkPspell * gtkpspell_new(GtkPspellConfig *gtkpspellconfig){
120   GtkPspell *gtkpspell;
121
122   if( gtkpspellconfig == NULL ){
123     gtkpspellconfig=gtkpspell_init();
124     if(gtkpspellconfig==NULL){
125       debug_print(_("Pspell could not be started."));
126       prefs_common.enable_pspell=FALSE;
127       return NULL;
128     }
129   }
130
131   gtkpspell               = g_new( GtkPspell ,1);
132   gtkpspell->config       = gtkpspellconfig;
133   gtkpspell->possible_err = new_pspell_manager( gtkpspell->config );
134   gtkpspell->checker      = NULL;
135
136   if( pspell_error_number( gtkpspell->possible_err ) != 0){
137     debug_print(_("Pspell error : %s\n"), pspell_error_message( gtkpspell->possible_err ));
138     delete_pspell_can_have_error( gtkpspell->possible_err );
139   }
140   else{
141     gtkpspell->checker = to_pspell_manager( gtkpspell->possible_err );
142   }
143  
144   gtkpspell->dictionary_list = NULL;
145   gtkpspell->path            = NULL;
146   gtkpspell->dict            = NULL;
147   gtkpspell->mode            = PSPELL_FASTMODE;
148   gtkpspell->gtktext         = NULL;
149   return gtkpspell;
150 }
151
152 /* Creates a new session and set path/dic */
153
154 GtkPspell *gtkpspell_new_with_config(GtkPspellConfig *gtkpspellconfig, 
155                                      guchar *path, 
156                                      guchar *dict, 
157                                      guint mode, 
158                                      guchar *encoding){
159   GtkPspell *gtkpspell;
160
161   if( gtkpspellconfig == NULL) {
162     gtkpspellconfig=gtkpspell_init();
163     if(gtkpspellconfig==NULL){
164       debug_print(_("Pspell could not be started."));
165       prefs_common.enable_pspell=FALSE;
166       return NULL;
167     }
168   }
169
170   gtkpspell                  = g_new( GtkPspell ,1);
171   gtkpspell->path            = NULL;
172   gtkpspell->dict            = NULL;
173   gtkpspell->dictionary_list = NULL;
174   gtkpspell->gtktext         = NULL;
175   
176   gtkpspell->config       = pspell_config_clone(gtkpspellconfig);
177   gtkpspell->mode = PSPELL_FASTMODE;
178   if(!set_path_and_dict(gtkpspell, gtkpspell->config, path, dict)){
179     debug_print(_("Pspell could not be configured."));
180     gtkpspell=gtkpspell_delete(gtkpspell);
181     return gtkpspell;
182   }
183   if(encoding)
184     pspell_config_replace(gtkpspell->config,"encoding",encoding);
185
186   gtkpspell->possible_err = new_pspell_manager( gtkpspell->config );
187   gtkpspell->checker      = NULL;
188
189   if( pspell_error_number( gtkpspell->possible_err ) != 0){
190     debug_print(_("Pspell error : %s\n"), pspell_error_message( gtkpspell->possible_err ));
191     delete_pspell_can_have_error( gtkpspell->possible_err );
192     gtkpspell=gtkpspell_delete(gtkpspell);
193   }
194   else{
195     gtkpspell->checker = to_pspell_manager( gtkpspell->possible_err );
196   }
197   return gtkpspell;
198 }
199
200
201 /* Finishes a session */
202
203 GtkPspell *  gtkpspell_delete( GtkPspell *gtkpspell ){
204
205   if( gtkpspell->checker ){
206     delete_pspell_manager( gtkpspell->checker );
207     gtkpspell->checker      = NULL;
208     gtkpspell->possible_err = NULL; /* checker is a cast from
209                                        possible_err */
210   }
211
212   if( gtkpspell->dictionary_list )
213     gtkpspell_free_dictionary_list( gtkpspell->dictionary_list );
214
215   g_free( gtkpspell->path );
216   g_free( gtkpspell->dict );
217   gtkpspell->path = NULL;
218   gtkpspell->dict = NULL;
219
220   g_free( gtkpspell );
221   return NULL;
222 }
223   
224   
225 int set_path_and_dict( GtkPspell *gtkpspell, 
226                        PspellConfig *config,
227                        guchar *path, 
228                        guchar * dict )
229 {
230   guchar *module   = NULL;
231   guchar *language = NULL;
232   guchar *spelling = NULL;
233   guchar *jargon   = NULL;
234
235   guchar buf[BUFSIZE];
236   guchar *end;
237   guchar *temppath;
238   guchar *tempdict;
239
240   /* Change nothing if any of path/dict/config is NULL */
241   if( path==NULL || dict==NULL || config==NULL)
242     return 0;
243
244   /* This is done, so we can free gtkpspell->path, even if it was
245      given as an argument of the function */
246   temppath = g_strdup( path );
247   g_free( gtkpspell->path );
248   
249   /* pspell dict name format :                         */
250   /*   <lang>[[-<spelling>[-<jargon>]]-<module>.pwli   */
251   /* Strip off path                                    */
252
253   if(!strrchr(dict,G_DIR_SEPARATOR)){ /* plain dict name */
254     strncpy(buf,dict,BUFSIZE-1);
255   }
256   else{ /* strip path */
257     strncpy(buf,strrchr(dict,G_DIR_SEPARATOR)+1,BUFSIZE-1);
258   }
259   g_free(gtkpspell->dict);
260
261   /* Ensure no buffers overflows if the dict is to long */
262   buf[BUFSIZE-1] = 0x00;
263   
264   language = buf;
265   if(( module=strrchr(buf,'-'))!=NULL){
266     module++;
267     if(( end=strrchr(module,'.'))!=NULL)
268       end[0]=0x00;
269     }
270
271   /* In tempdict, we have only the dict name, without path nor
272      extension. Useful in the popup menus */
273
274   tempdict=g_strdup(buf);
275
276   /* Probably I am too paranoied... */
277   if(!( language[0]!=0x00 && language[1]!=0x00))
278     language = NULL;
279   else{
280      spelling = strchr(language,'-');
281      if( spelling!=NULL ){
282        spelling[0] = 0x00;
283        spelling++;
284      }
285     if( spelling!=module ){
286       if( ( end=strchr( spelling,'-' ) )!=NULL ){
287         end[0] = 0x00;
288         jargon = end+1;
289         if( jargon!=module )
290           if( ( end=strchr(jargon,'-') )!=NULL )
291             end[0] = 0x00;
292           else
293             jargon = NULL;
294         else
295         jargon = NULL;
296       }
297       else
298       spelling = NULL;
299     }
300     else 
301       spelling = NULL;
302   }
303
304   debug_print( _("Language : %s\nSpelling: %s\nJargon: %s\nModule: %s\n"),language,spelling,jargon,module);
305
306   if(language) 
307     pspell_config_replace(config,"language-tag",language);
308   if(spelling) 
309     pspell_config_replace(config,"spelling",spelling);
310   if(jargon)
311     pspell_config_replace(config,"jargon",jargon);
312   if(module)
313     pspell_config_replace(config,"module",module);
314   if(temppath)
315     pspell_config_replace(config,"word-list-path",temppath);
316
317   switch(gtkpspell->mode){
318   case PSPELL_FASTMODE: pspell_config_replace(config,"sug_mode","fast");
319     break;
320   case PSPELL_NORMALMODE: pspell_config_replace(config,"sug_mode","normal");
321     break;
322   case PSPELL_BADSPELLERMODE: pspell_config_replace(config,"sug_mode","bad-spellers");
323     break;
324   }
325   
326   gtkpspell->path = g_strdup(temppath);
327   gtkpspell->dict = g_strdup(tempdict);
328   g_free(temppath);
329   g_free(tempdict);
330
331   return -1;
332 }
333
334 /* Set path and dict. The session is resetted. */
335 /* 0 on error, -1 on success */
336 int gtkpspell_set_path_and_dict(GtkPspell * gtkpspell, guchar * path, guchar * dict){
337
338   PspellConfig * config2;
339
340   /* It seems changing an already running config is not the way to go
341      */
342
343   config2 = pspell_config_clone( gtkpspell->config );
344
345   if(gtkpspell->checker){
346     delete_pspell_manager(gtkpspell->checker);
347   }
348   gtkpspell->checker      = NULL;
349   gtkpspell->possible_err = NULL;
350
351   if(set_path_and_dict(gtkpspell,config2,path,dict)==0){
352     debug_print("Pspell set_path_and_dict error.");
353     return 0;
354   }
355   
356   gtkpspell->possible_err = new_pspell_manager( config2 );
357
358   delete_pspell_config(config2);
359   config2 = NULL;
360
361   if(pspell_error_number(gtkpspell->possible_err)!=0){
362     debug_print("Pspell set path&dict error %s\n",
363                 pspell_error_message(gtkpspell->possible_err));
364     delete_pspell_can_have_error(gtkpspell->possible_err);
365     gtkpspell->possible_err = NULL;
366     return 0;
367   }
368
369   gtkpspell->checker=to_pspell_manager(gtkpspell->possible_err);
370
371   return -1;
372 }
373   
374 /* What dict are we using ? language-spelling-jargon-module format */
375 /* Actually, this function is not used and hence not tested. */
376 /* Returns an allocated string */  
377 guchar * gtkpspell_get_dict( GtkPspell *gtkpspell ){
378
379   guchar * dict;
380   guchar * language;
381   guchar * spelling;
382   guchar * jargon;
383   guint len;
384
385   if(gtkpspell->config==NULL)
386     return NULL;
387   
388   language = g_strdup(pspell_config_retrieve(gtkpspell->config,"language"));
389   spelling = g_strdup(pspell_config_retrieve(gtkpspell->config,"spelling"));
390   jargon   = g_strdup(pspell_config_retrieve(gtkpspell->config,"jargon"  ));
391   len      = strlen(language) + strlen(spelling) + strlen(jargon);
392
393   if( len<BUFSIZE ){
394     dict = g_new(char,len+4);
395     strcpy(dict,language);
396     if(spelling){
397       strcat(dict,"-");
398       strcat(dict,spelling);
399       if(jargon){
400         strcat(dict,"-");
401         strcat(dict,jargon);
402       }
403     }
404   }
405   g_free(language);
406   g_free(spelling);
407   g_free(jargon);
408   
409   return dict;
410 }
411   
412 /* Return the dict path as an allocated string */
413 /* Not used = not tested */
414
415 guchar * gtkpspell_get_path(GtkPspell * gtkpspell){
416
417   guchar * path;
418
419   if( gtkpspell->config=NULL )
420     return NULL;
421
422   path = g_strdup(pspell_config_retrieve(gtkpspell->config,"word-list-path"));
423
424   return path;
425 }
426
427 /* Menu callback : change dict */
428   
429 static void menu_change_dict(GtkWidget *w, GtkPspell * gtkpspell){
430
431   guchar *thedict,*thelabel;
432   
433   /* Dict is simply the menu label */
434
435   gtk_label_get( GTK_LABEL(GTK_BIN(w)->child),(gchar **) &thelabel );
436   thedict=g_strdup(thelabel);
437
438   /* Set path, dict, (and sug_mode ?) */
439   gtkpspell_set_path_and_dict(gtkpspell,gtkpspell->path,thedict);
440   g_free(thedict);
441 }
442
443   
444 /* Menu callback : Set the suggestion mode */
445
446 static void set_sug_mode(GtkWidget *w, GtkPspell * gtkpspell){
447
448   unsigned char * themode;
449
450   gtk_label_get(GTK_LABEL(GTK_BIN(w)->child),(gchar **) &themode);
451
452   if( !strcmp(themode,_("Fast Mode")) ){
453       gtkpspell_set_sug_mode( gtkpspell,"fast" );
454       gtkpspell->mode = PSPELL_FASTMODE;
455   }
456   if( !strcmp(themode,_("Normal Mode")) ){
457       gtkpspell_set_sug_mode( gtkpspell,"normal" );
458       gtkpspell->mode = PSPELL_NORMALMODE;
459   }
460   if(!strcmp( themode,_("Bad Spellers Mode")) ){
461       gtkpspell_set_sug_mode( gtkpspell,"bad-spellers" );
462       gtkpspell->mode = PSPELL_BADSPELLERMODE;
463   }
464 }
465   
466 /* Set the suggestion mode */
467 /* Actually, the session is resetted and everything is reset. */
468 /* We take the used path/dict pair and create a new config with them
469    */
470
471 int gtkpspell_set_sug_mode( GtkPspell * gtkpspell, gchar * themode ){
472   PspellConfig *config2;
473   guchar       *path;
474   guchar       *dict;
475
476   delete_pspell_manager( gtkpspell->checker );
477   gtkpspell->checker = NULL;
478
479   config2 = pspell_config_clone(gtkpspell->config);
480
481   if(!set_path_and_dict( gtkpspell, config2, gtkpspell->path, gtkpspell->dict )){
482     debug_print(_("Pspell set_sug_mod could not reset path & dict\n"));
483     return 0;
484   }
485
486   pspell_config_replace( config2, "sug-mode", themode );
487
488   gtkpspell->possible_err = new_pspell_manager( config2 );
489   delete_pspell_config( config2 );
490   config2 = NULL;
491
492   if( pspell_error_number( gtkpspell->possible_err )!=0 ){
493     debug_print( _("Pspell set sug-mode error %s\n"),
494         pspell_error_message( gtkpspell->possible_err ) );
495     delete_pspell_can_have_error( gtkpspell->possible_err );
496     gtkpspell->possible_err = NULL;
497     return 0;
498   }
499   gtkpspell->checker = to_pspell_manager( gtkpspell->possible_err );
500   return -1;
501 }
502   
503   
504 /* Create a suggestion list for  word  */
505
506 static GList* misspelled_suggest( GtkPspell * gtkpspell, guchar *word ) 
507 {
508   const guchar          *newword;
509   GList                 *l = NULL;
510   int                    count;
511   const PspellWordList  *suggestions ;
512   PspellStringEmulation *elements ;
513
514   if( word==NULL ) return NULL;
515
516   if( !pspell_manager_check( gtkpspell->checker,word,-1 ) ){
517        suggestions =  pspell_manager_suggest( gtkpspell->checker,(const char *) word,-1 );
518        elements    = pspell_word_list_elements( suggestions );
519        /* First one must be the misspelled (why this ?) */
520        l           = g_list_append( l,g_strdup(word) ); 
521        while( ( newword=pspell_string_emulation_next( elements ) )!=NULL )
522          l = g_list_append( l, g_strdup( newword ) );
523        return l;
524   }
525   return NULL;
526 }
527
528
529 /* Just test if word is correctly spelled */  
530
531 static int misspelled_test(GtkPspell * gtkpspell, unsigned char *word) 
532 {
533     if( pspell_manager_check( gtkpspell->checker, word, -1) ) 
534       return 0;
535     return 1;
536 }
537
538
539 static gboolean iswordsep(unsigned char c) 
540 {
541     return !isalpha(c) && c != '\'';
542 }
543
544 static guchar get_text_index_whar(GtkPspell * gtkpspell, int pos) 
545 {
546     guchar a;
547     gchar *text;
548     text = gtk_editable_get_chars(GTK_EDITABLE(gtkpspell->gtktext), pos, pos + 1);
549     if (text == NULL) return 0;
550     a = (guchar) * text;
551     g_free(text);
552     return a;
553 }
554
555 static gboolean get_word_from_pos(GtkPspell * gtkpspell, int pos, 
556                                   unsigned char* buf,
557                                   int *pstart, int *pend) 
558 {
559     gint start, end;
560     GtkXText * gtktext;
561     gtktext=gtkpspell->gtktext;
562     if (iswordsep(get_text_index_whar(gtkpspell, pos))) return FALSE;
563
564     for (start = pos; start >= 0; --start) {
565         if (iswordsep(get_text_index_whar(gtkpspell, start))) break;
566     }
567     start++;
568
569     for (end = pos; end < gtk_xtext_get_length(gtktext); end++) {
570         if (iswordsep(get_text_index_whar(gtkpspell, end))) break;
571     }
572
573     if (buf) {
574         for (pos = start; pos < end; pos++) buf[pos - start] = get_text_index_whar(gtkpspell, pos);
575         buf[pos - start] = 0;
576     }
577
578     if (pstart) *pstart = start;
579     if (pend) *pend = end;
580
581     return TRUE;
582 }
583
584 static gboolean get_curword(GtkPspell * gtkpspell, unsigned char* buf,
585                             int *pstart, int *pend) 
586 {
587     int pos = gtk_editable_get_position(GTK_EDITABLE(gtkpspell->gtktext));
588     return get_word_from_pos(gtkpspell, pos, buf, pstart, pend);
589 }
590
591 static void change_color(GtkPspell * gtkpspell, int start, int end, 
592                          GdkColor *color) 
593 {
594     char *newtext;
595     GtkXText *gtktext;
596     gtktext=gtkpspell->gtktext;
597     if (start >= end) {
598         return ;
599     };
600     gtk_xtext_freeze(gtktext);
601     newtext = gtk_editable_get_chars(GTK_EDITABLE(gtktext), start, end);
602     if(newtext){
603         gtk_signal_handler_block_by_func(GTK_OBJECT(gtktext),
604                                          GTK_SIGNAL_FUNC(entry_insert_cb), gtkpspell);
605         gtk_xtext_set_point(gtktext, start);
606         gtk_xtext_forward_delete(gtktext, end - start);
607
608         gtk_xtext_insert(gtktext, NULL, color, NULL, newtext, end - start);
609         gtk_signal_handler_unblock_by_func(GTK_OBJECT(gtktext),
610                                            GTK_SIGNAL_FUNC(entry_insert_cb), gtkpspell);
611    }
612    gtk_xtext_thaw(gtktext);
613 }
614
615 static gboolean check_at(GtkPspell * gtkpspell, int from_pos) 
616 {
617     int start, end;
618     unsigned char buf[BUFSIZE];
619     GtkXText * gtktext;
620     gtktext=gtkpspell->gtktext;
621     if (from_pos < 0) return FALSE;
622     if (!get_word_from_pos(gtkpspell, from_pos, buf, &start, &end)) {
623         return FALSE;
624     };
625     strncpy(gtkpspell->theword,buf,BUFSIZE-1);
626     gtkpspell->theword[BUFSIZE-1]=0x00;
627
628     if (misspelled_test(gtkpspell, buf)) {
629         if (highlight.pixel == 0) {
630             /* add an entry for the highlight in the color map. */
631             GdkColormap *gc = gtk_widget_get_colormap(GTK_WIDGET(gtktext));
632             gdk_colormap_alloc_color(gc, &highlight, FALSE, TRUE);
633             ;
634         }
635         change_color(gtkpspell, start, end, &highlight);
636         return TRUE;
637     } else {
638         change_color(gtkpspell, start, end,
639                      &(GTK_WIDGET(gtktext)->style->fg[0]));
640         return FALSE;
641     }
642 }
643
644
645 static void check_all(GtkWidget *w, GtkPspell * gtkpspell){
646   gtkpspell_check_all(gtkpspell);
647 }
648
649
650 void gtkpspell_check_all(GtkPspell * gtkpspell) 
651 {
652     guint origpos;
653     guint pos = 0;
654     guint len;
655     float adj_value;
656     GtkXText * gtktext;
657     gtktext=gtkpspell->gtktext;
658
659     if (!gtkpspell_running(gtkpspell)) return ;
660
661     len = gtk_xtext_get_length(gtktext);
662
663     adj_value = gtktext->vadj->value;
664     gtk_xtext_freeze(gtktext);
665     origpos = gtk_editable_get_position(GTK_EDITABLE(gtktext));
666     gtk_editable_set_position(GTK_EDITABLE(gtktext),0);
667     while (pos < len) {
668         while (pos < len && iswordsep(get_text_index_whar(gtkpspell, pos)))
669             pos++;
670         while (pos < len && !iswordsep(get_text_index_whar(gtkpspell, pos)))
671             pos++;
672         if (pos > 0)
673             check_at(gtkpspell, pos - 1);
674     }
675     gtk_xtext_thaw(gtktext);
676     gtk_editable_set_position(GTK_EDITABLE(gtktext), origpos);
677     gtk_editable_select_region(GTK_EDITABLE(gtktext), origpos, origpos);
678
679 }
680
681 static void entry_insert_cb(GtkXText *gtktext, 
682                             gchar *newtext, guint len, guint *ppos, 
683                             GtkPspell * gtkpspell) 
684 {
685     if (!gtkpspell_running(gtkpspell)) return ;
686
687     if (iswordsep(newtext[0])) {
688         /* did we just end a word? */
689         if (*ppos >= 2) check_at(gtkpspell, *ppos - 2);
690
691         /* did we just split a word? */
692         if (*ppos < gtk_xtext_get_length(gtktext))
693             check_at(gtkpspell, *ppos + 1);
694     } else {
695         /* check as they type, *except* if they're typing at the end (the most
696          * common case.
697          */
698         if (*ppos < gtk_xtext_get_length(gtktext) &&
699                 !iswordsep(get_text_index_whar(gtkpspell, *ppos)))
700             check_at(gtkpspell, *ppos - 1);
701     }
702
703 }
704
705 static void entry_delete_cb(GtkXText *gtktext,
706                             gint start, gint end, GtkPspell *gtkpspell) 
707 {
708     int origpos;
709     if (!gtkpspell_running(gtkpspell)) return ;
710
711     origpos = gtk_editable_get_position(GTK_EDITABLE(gtktext));
712     check_at(gtkpspell, start - 1);
713     gtk_editable_set_position(GTK_EDITABLE(gtktext), origpos);
714     gtk_editable_select_region(GTK_EDITABLE(gtktext), origpos, origpos);
715     /* this is to *UNDO* the selection, in case they were holding shift
716      * while hitting backspace. */
717 }
718
719 static void replace_word(GtkWidget *w, GtkPspell * gtkpspell) 
720 {
721     int start, end,oldlen, newlen;
722     guint origpos;
723     unsigned char *newword;
724     unsigned char buf[BUFSIZE];
725     guint pos;
726     GtkXText * gtktext;
727     gtktext=gtkpspell->gtktext;
728
729     gtk_xtext_freeze(GTK_XTEXT(gtktext));
730     origpos = gtkpspell->orig_pos;
731     pos     = origpos;
732
733     gtk_label_get(GTK_LABEL(GTK_BIN(w)->child), (gchar**) &newword);
734     newlen = strlen(newword);
735
736     get_curword(gtkpspell, buf, &start, &end);
737     oldlen=end-start;
738
739     gtk_xtext_set_point(GTK_XTEXT(gtktext), end);
740     gtk_xtext_backward_delete(GTK_XTEXT(gtktext), end - start);
741     gtk_xtext_insert(GTK_XTEXT(gtktext), NULL, NULL, NULL, newword, strlen(newword));
742     
743 #if 0
744     if(end-start>0 /*&& gtkpspell->learn*/){ 
745       buf[end-start]=0x00; /* Just be sure the buffer is correct... */
746       /* Learn from common misspellings */
747       pspell_manager_store_replacement(gtkpspell->checker,buf,end-start,
748                                        newword,strlen(newword));
749     }
750 #endif
751     /* Put the point and the position where we clicked with the mouse */
752     /* It seems to be a hack, as I must thaw,freeze,thaw the widget   */
753     /* to let it update correctly the word insertion and then the     */
754     /* point & position position. If not, SEGV after the first replacement */
755     /* If the new word ends before point, put the point at its end*/
756     
757     if(origpos-start<=oldlen && origpos-start>=0) {
758       /* Original point was in the word. */
759       /* Put the insertion point in the same location */
760       /* with respect to the new length */
761       /* If the original position is still within the word, */
762       /* then keep the original position. If not, move to the */
763       /* end of the word */
764       if(origpos-start>newlen)
765         pos=start+newlen;
766     }
767     else
768       if (origpos>end) {
769         /* move the position according to the change of length */
770       pos=origpos+newlen-oldlen;
771       }
772     gtk_xtext_thaw(GTK_XTEXT(gtktext));
773     gtk_xtext_freeze(GTK_XTEXT(gtktext));
774     if(GTK_XTEXT(gtktext)->text_len<pos)
775       pos=gtk_xtext_get_length(GTK_XTEXT(gtktext));
776     gtkpspell->orig_pos=pos;
777     gtk_editable_set_position(GTK_EDITABLE(gtktext),gtkpspell->orig_pos);
778     gtk_xtext_set_point(GTK_XTEXT(gtktext), 
779                         gtk_editable_get_position(GTK_EDITABLE(gtktext)));
780     gtk_xtext_thaw(GTK_XTEXT(gtktext));
781 }
782
783 /* Accept this word for this session */
784
785 static void add_word_to_session(GtkWidget *w, GtkPspell * gtkpspell){
786     guint pos;
787     GtkXText * gtkxtext;
788     gtkxtext=gtkpspell->gtktext;
789
790     gtk_xtext_freeze(GTK_XTEXT(gtkxtext));
791     pos = gtk_editable_get_position(GTK_EDITABLE(gtkxtext));
792     
793     pspell_manager_add_to_session(gtkpspell->checker,gtkpspell->theword,strlen(gtkpspell->theword));
794
795     check_at(gtkpspell,gtk_editable_get_position(GTK_EDITABLE(gtkxtext)));
796
797     gtk_xtext_thaw(GTK_XTEXT(gtkxtext));
798     gtk_xtext_freeze(GTK_XTEXT(gtkxtext));
799     gtk_editable_set_position(GTK_EDITABLE(gtkxtext),pos);
800     gtk_xtext_set_point(GTK_XTEXT(gtkxtext), gtk_editable_get_position(GTK_EDITABLE(gtkxtext)));
801     gtk_xtext_thaw(GTK_XTEXT(gtkxtext));
802 }
803
804 /* Add word to personal dict. Save the list at every addition (may be
805    not efficient...) */
806
807 static void add_word_to_personal(GtkWidget *w, GtkPspell * gtkpspell){
808     guint pos;
809     GtkXText * gtkxtext;
810     gtkxtext=gtkpspell->gtktext;
811
812     gtk_xtext_freeze(GTK_XTEXT(gtkxtext));
813     pos = gtk_editable_get_position(GTK_EDITABLE(gtkxtext));
814     
815     pspell_manager_add_to_personal(gtkpspell->checker,gtkpspell->theword,strlen(gtkpspell->theword));
816     pspell_manager_save_all_word_lists(gtkpspell->checker);
817     
818     check_at(gtkpspell,gtk_editable_get_position(GTK_EDITABLE(gtkxtext)));
819     gtk_xtext_thaw(GTK_XTEXT(gtkxtext));
820     gtk_xtext_freeze(GTK_XTEXT(gtkxtext));
821     gtk_editable_set_position(GTK_EDITABLE(gtkxtext),pos);
822     gtk_xtext_set_point(GTK_XTEXT(gtkxtext), gtk_editable_get_position(GTK_EDITABLE(gtkxtext)));
823         gtk_xtext_thaw(GTK_XTEXT(gtkxtext));
824 }
825
826        
827 static GtkMenu *make_menu_config(GtkPspell *gtkpspell){
828   GtkWidget *menu, *item, *submenu;
829
830   
831   menu = gtk_menu_new();
832
833         item = gtk_menu_item_new_with_label(_("Spell check all"));
834                 gtk_widget_show(item);
835                 gtk_menu_append(GTK_MENU(menu), item);
836         gtk_signal_connect(GTK_OBJECT(item),"activate",
837                 GTK_SIGNAL_FUNC(check_all),gtkpspell);
838
839
840         item = gtk_menu_item_new();
841                 gtk_widget_show(item);
842                 gtk_menu_append(GTK_MENU(menu),item);
843
844         submenu = gtk_menu_new();
845                 item = gtk_menu_item_new_with_label(_("Change dictionary"));
846                 gtk_widget_show(item);
847                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item),submenu);
848                 gtk_menu_append(GTK_MENU(menu), item);
849                 /* Dict list */
850                 if(gtkpspell->dictionary_list==NULL)
851                   gtkpspell->dictionary_list=gtkpspell_get_dictionary_list(gtkpspell->path);
852        
853                 
854         {
855           GtkWidget * curmenu=submenu;
856           int count = 0;
857           Dictionary *dict;
858           GSList *tmp;
859           tmp = gtkpspell->dictionary_list;
860           for (tmp =  gtkpspell->dictionary_list;tmp!=NULL;tmp=g_slist_next(tmp)){
861             dict= (Dictionary *) tmp->data;
862             item = gtk_check_menu_item_new_with_label(dict->name);
863             if(strcmp2(dict->name,gtkpspell->dict))
864               gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),FALSE);
865             else{
866               gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),TRUE);
867               gtk_widget_set_sensitive(GTK_WIDGET(item),FALSE);
868             }
869             gtk_menu_append(GTK_MENU(curmenu),item);
870             gtk_signal_connect(GTK_OBJECT(item),"activate",
871                 GTK_SIGNAL_FUNC(menu_change_dict),gtkpspell);
872             gtk_widget_show(item);
873             count++;
874             if(count==MENUCOUNT){
875               GtkWidget *newmenu;
876               newmenu=gtk_menu_new();
877               item=gtk_menu_item_new_with_label(_("More..."));
878               gtk_menu_item_set_submenu(GTK_MENU_ITEM(item),newmenu);
879               gtk_menu_append(GTK_MENU(curmenu),item);
880               gtk_widget_show(item);
881               curmenu=newmenu;
882               count=0;
883             }
884           }
885         }  
886
887         item = gtk_menu_item_new();
888                 gtk_widget_show(item);
889                 gtk_menu_append(GTK_MENU(menu),item);
890
891         item = gtk_check_menu_item_new_with_label(_("Fast Mode"));
892                 gtk_widget_show(item);
893                 gtk_menu_append(GTK_MENU(menu),item);
894                 if(gtkpspell->mode==PSPELL_FASTMODE){
895                   gtk_widget_set_sensitive(GTK_WIDGET(item),FALSE);
896                   gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),TRUE);
897                 }
898                 else
899                   gtk_signal_connect(GTK_OBJECT(item),"activate",
900                         GTK_SIGNAL_FUNC(set_sug_mode),gtkpspell);
901
902
903
904         item = gtk_check_menu_item_new_with_label(_("Normal Mode"));
905                 gtk_widget_show(item);
906                 gtk_menu_append(GTK_MENU(menu),item);
907                 if(gtkpspell->mode==PSPELL_NORMALMODE){
908                   gtk_widget_set_sensitive(GTK_WIDGET(item),FALSE);
909                   gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),TRUE);
910                 }
911                 else
912                   gtk_signal_connect(GTK_OBJECT(item),"activate",
913                         GTK_SIGNAL_FUNC(set_sug_mode),gtkpspell);
914         
915         item = gtk_check_menu_item_new_with_label(_("Bad Spellers Mode"));
916                 gtk_widget_show(item);
917                 gtk_menu_append(GTK_MENU(menu),item);
918                 if(gtkpspell->mode==PSPELL_BADSPELLERMODE){
919                   gtk_widget_set_sensitive(GTK_WIDGET(item),FALSE);
920                   gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),TRUE);
921                 }
922                 else
923                   gtk_signal_connect(GTK_OBJECT(item),"activate",
924                         GTK_SIGNAL_FUNC(set_sug_mode),gtkpspell);
925
926
927
928         return GTK_MENU(menu);
929 }
930   
931 /* Add menus to accept this word for this session and to add it to personal
932    dictionary */
933 static GtkMenu *make_menu(GList *l, GtkPspell * gtkpspell) 
934 {
935     GtkWidget *menu, *item;
936     unsigned char *caption;
937     GtkXText * gtktext;
938     gtktext=gtkpspell->gtktext;
939
940     menu = gtk_menu_new(); 
941         caption = g_strdup_printf(_("Accept `%s' for this session"), (unsigned char*)l->data);
942                 item = gtk_menu_item_new_with_label(caption);
943                 g_free(caption);
944                 gtk_widget_show(item);
945                 gtk_menu_append(GTK_MENU(menu), item);
946
947         gtk_signal_connect(GTK_OBJECT(item), "activate",
948                 GTK_SIGNAL_FUNC(add_word_to_session), gtkpspell);
949
950         caption = g_strdup_printf(_("Add `%s' to personal dictionary"), (char*)l->data);
951                 item = gtk_menu_item_new_with_label(caption);
952                 g_free(caption);
953                 gtk_widget_show(item);
954                 gtk_menu_append(GTK_MENU(menu), item);
955
956         gtk_signal_connect(GTK_OBJECT(item), "activate",
957                 GTK_SIGNAL_FUNC(add_word_to_personal), gtkpspell);
958          
959
960         item = gtk_menu_item_new();
961         gtk_widget_show(item);
962         gtk_menu_append(GTK_MENU(menu), item);
963
964         l = l->next;
965         if (l == NULL) {
966             item = gtk_menu_item_new_with_label(_("(no suggestions)"));
967             gtk_widget_show(item);
968             gtk_menu_append(GTK_MENU(menu), item);
969         } else {
970             GtkWidget *curmenu = menu;
971             int count = 0;
972             do {
973                 if (l->data == NULL && l->next != NULL) {
974                     count = 0;
975                     curmenu = gtk_menu_new();
976                     item = gtk_menu_item_new_with_label(_("Others..."));
977                     gtk_widget_show(item);
978                     gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), curmenu);
979                     gtk_menu_append(GTK_MENU(curmenu), item);
980                     l = l->next;
981                 } else if (count > MENUCOUNT) {
982                     count -= MENUCOUNT;
983                     item = gtk_menu_item_new_with_label(_("More..."));
984                     gtk_widget_show(item);
985                     gtk_menu_append(GTK_MENU(curmenu), item);
986                     curmenu = gtk_menu_new();
987                     gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), curmenu);
988                 }
989                 item = gtk_menu_item_new_with_label((unsigned char*)l->data);
990                 gtk_signal_connect(GTK_OBJECT(item), "activate",
991                                    GTK_SIGNAL_FUNC(replace_word), gtkpspell);
992                 gtk_widget_show(item);
993                 gtk_menu_append(GTK_MENU(curmenu), item);
994                 count++;
995             } while ((l = l->next) != NULL);
996         }
997     return GTK_MENU(menu);
998 }
999
1000 static void popup_menu(GtkPspell * gtkpspell, GdkEventButton *eb) 
1001 {
1002     unsigned char buf[BUFSIZE];
1003     GList *list, *l;
1004     GtkXText * gtktext;
1005     gtktext=gtkpspell->gtktext;
1006     gtkpspell->orig_pos=gtk_editable_get_position(GTK_EDITABLE(gtktext));
1007
1008     if( !(eb->state & GDK_SHIFT_MASK) )
1009       if (get_curword(gtkpspell, buf, NULL, NULL)){
1010         if (buf != NULL) {
1011           strncpy(gtkpspell->theword,buf,BUFSIZE-1);
1012           gtkpspell->theword[BUFSIZE-1]=0x00;
1013           list = misspelled_suggest(gtkpspell, buf);
1014           if (list != NULL) {
1015             gtk_menu_popup(make_menu(list, gtkpspell), NULL, NULL, NULL, NULL,
1016                            eb->button, eb->time);
1017             for (l = list; l != NULL; l = l->next)
1018               g_free(l->data);
1019             g_list_free(list);
1020             return;
1021           }
1022         }
1023       }
1024     gtk_menu_popup(make_menu_config(gtkpspell),NULL,NULL,NULL,NULL,
1025           eb->button,eb->time);
1026
1027 }
1028
1029 /* ok, this is pretty wacky:
1030  * we need to let the right-mouse-click go through, so it moves the cursor,
1031  * but we *can't* let it go through, because GtkText interprets rightclicks as
1032  * weird selection modifiers.
1033  *
1034  * so what do we do?  forge rightclicks as leftclicks, then popup the menu.
1035  * HACK HACK HACK.
1036  */
1037 static gint button_press_intercept_cb(GtkXText *gtktext, GdkEvent *e, GtkPspell * gtkpspell) 
1038
1039 {
1040     GdkEventButton *eb;
1041     gboolean retval;
1042
1043     if (!gtkpspell_running(gtkpspell)) return FALSE;
1044
1045     if (e->type != GDK_BUTTON_PRESS) return FALSE;
1046     eb = (GdkEventButton*) e;
1047
1048     if (eb->button != 3) return FALSE;
1049
1050     /* forge the leftclick */
1051     eb->button = 1;
1052
1053         gtk_signal_handler_block_by_func(GTK_OBJECT(gtktext),
1054                                      GTK_SIGNAL_FUNC(button_press_intercept_cb), gtkpspell);
1055     gtk_signal_emit_by_name(GTK_OBJECT(gtktext), "button-press-event",
1056                             e, &retval);
1057     gtk_signal_handler_unblock_by_func(GTK_OBJECT(gtktext),
1058                                        GTK_SIGNAL_FUNC(button_press_intercept_cb), gtkpspell);
1059     gtk_signal_emit_stop_by_name(GTK_OBJECT(gtktext), "button-press-event");
1060     
1061     /* now do the menu wackiness */
1062     popup_menu(gtkpspell, eb);
1063     gtk_grab_remove(GTK_WIDGET(gtktext));
1064     return TRUE;
1065 }
1066
1067 void gtkpspell_uncheck_all(GtkPspell * gtkpspell) 
1068 {
1069     int origpos;
1070     unsigned char *text;
1071     float adj_value;
1072     GtkXText * gtktext;
1073     gtktext=gtkpspell->gtktext;
1074
1075     adj_value = gtktext->vadj->value;
1076     gtk_xtext_freeze(gtktext);
1077     origpos = gtk_editable_get_position(GTK_EDITABLE(gtktext));
1078     text = gtk_editable_get_chars(GTK_EDITABLE(gtktext), 0, -1);
1079     gtk_xtext_set_point(gtktext, 0);
1080     gtk_xtext_forward_delete(gtktext, gtk_xtext_get_length(gtktext));
1081     gtk_xtext_insert(gtktext, NULL, NULL, NULL, text, strlen(text));
1082     gtk_xtext_thaw(gtktext);
1083
1084     gtk_editable_set_position(GTK_EDITABLE(gtktext), origpos);
1085     gtk_adjustment_set_value(gtktext->vadj, adj_value);
1086 }
1087
1088 void gtkpspell_attach(GtkPspell * gtkpspell, GtkXText *gtktext) 
1089 {
1090     gtkpspell->gtktext=gtktext;
1091 //    if (prefs_common.auto_makepspell) {
1092         gtk_signal_connect(GTK_OBJECT(gtktext), "insert-text",
1093                            GTK_SIGNAL_FUNC(entry_insert_cb), gtkpspell);
1094         gtk_signal_connect_after(GTK_OBJECT(gtktext), "delete-text",
1095                                  GTK_SIGNAL_FUNC(entry_delete_cb), gtkpspell);
1096 //    };
1097     gtk_signal_connect(GTK_OBJECT(gtktext), "button-press-event",
1098                        GTK_SIGNAL_FUNC(button_press_intercept_cb), gtkpspell);
1099
1100 }
1101
1102 void gtkpspell_detach(GtkPspell * gtkpspell) 
1103 {
1104     GtkXText * gtktext;
1105     gtktext=gtkpspell->gtktext;
1106 //    if (prefs_common.auto_makepspell) {
1107         gtk_signal_disconnect_by_func(GTK_OBJECT(gtktext),
1108                                       GTK_SIGNAL_FUNC(entry_insert_cb), gtkpspell);
1109         gtk_signal_disconnect_by_func(GTK_OBJECT(gtktext),
1110                                       GTK_SIGNAL_FUNC(entry_delete_cb), gtkpspell);
1111 //    };
1112     gtk_signal_disconnect_by_func(GTK_OBJECT(gtktext),
1113                                   GTK_SIGNAL_FUNC(button_press_intercept_cb), gtkpspell);
1114
1115     gtkpspell_uncheck_all(gtkpspell);
1116 }
1117
1118 /*** Sylpheed (Claws) ***/
1119
1120 static GSList *create_empty_dictionary_list(void)
1121 {
1122         GSList *list = NULL;
1123         Dictionary *dict;
1124         
1125         dict = g_new0(Dictionary, 1);
1126         dict->name = g_strdup(_("None"));
1127         return g_slist_append(list, dict);
1128 }
1129
1130 /* gtkpspell_get_dictionary_list() - returns list of dictionary names */
1131 GSList *gtkpspell_get_dictionary_list(const gchar *pspell_path)
1132 {
1133         GSList *list;
1134         gchar *dict_path, *tmp, *prevdir;
1135         GSList *walk;
1136         Dictionary *dict;
1137         DIR *dir;
1138         struct dirent *ent;
1139
1140         list = NULL;
1141
1142 #ifdef USE_THREADS
1143 #warning TODO: no directory change
1144 #endif
1145         dict_path=g_strdup(pspell_path);
1146         prevdir = g_get_current_dir();
1147         if (chdir(dict_path) <0) {
1148                 FILE_OP_ERROR(dict_path, "chdir");
1149                 g_free(prevdir);
1150                 g_free(dict_path);
1151                 return create_empty_dictionary_list();
1152         }
1153
1154         debug_print(_("Checking for dictionaries in %s\n"), dict_path);
1155
1156         if (NULL != (dir = opendir("."))) {
1157                 while (NULL != (ent = readdir(dir))) {
1158                         /* search for pwli */
1159                         if (NULL != (tmp = strstr(ent->d_name, ".pwli"))) {
1160                                 dict = g_new0(Dictionary, 1);
1161                                 dict->name = g_strndup(ent->d_name, tmp - ent->d_name);
1162                                 debug_print(_("Found dictionary %s\n"), dict->name);
1163                                 list = g_slist_append(list, dict);
1164                         }
1165                 }                       
1166                 closedir(dir);
1167         }
1168         else {
1169                 FILE_OP_ERROR(dict_path, "opendir");
1170                 debug_print(_("No dictionary found\n"));
1171                 list = create_empty_dictionary_list();
1172         }
1173         if(list==NULL){
1174           debug_print(_("No dictionary found"));
1175           list = create_empty_dictionary_list();
1176         }
1177         chdir(prevdir);
1178         g_free(dict_path);
1179         g_free(prevdir);
1180         return list;
1181 }
1182
1183 void gtkpspell_free_dictionary_list(GSList *list)
1184 {
1185         Dictionary *dict;
1186         GSList *walk;
1187         for (walk = list; walk != NULL; walk = g_slist_next(walk))
1188                 if (walk->data) {
1189                         dict = (Dictionary *) walk->data;
1190                         if (dict->name)
1191                                 g_free(dict->name);
1192                         g_free(dict);
1193                 }                               
1194         g_slist_free(list);
1195 }
1196
1197 static void dictionary_option_menu_item_data_destroy(gpointer data)
1198 {
1199         gchar *str = (gchar *) data;
1200
1201         if (str)
1202                 g_free(str);
1203 }
1204
1205 GtkWidget *gtkpspell_dictionary_option_menu_new(const gchar *pspell_path)
1206 {
1207         GSList *dict_list, *tmp;
1208         GtkWidget *item;
1209         GtkWidget *menu;
1210         Dictionary *dict;
1211
1212         dict_list = gtkpspell_get_dictionary_list(pspell_path);
1213         g_return_val_if_fail(dict_list, NULL);
1214
1215         menu = gtk_menu_new();
1216         
1217         for (tmp = dict_list; tmp != NULL; tmp = g_slist_next(tmp)) {
1218                 dict = (Dictionary *) tmp->data;
1219                 item = gtk_menu_item_new_with_label(dict->name);
1220                 if (dict->name)
1221                         gtk_object_set_data_full(GTK_OBJECT(item), "dict_name",
1222                                          g_strdup(dict->name), 
1223                                          dictionary_option_menu_item_data_destroy);
1224                 gtk_menu_append(GTK_MENU(menu), item);                                   
1225                 gtk_widget_show(item);
1226         }
1227
1228         gtk_widget_show(menu);
1229
1230         gtkpspell_free_dictionary_list(dict_list);
1231
1232         return menu;
1233 }
1234
1235
1236
1237 gchar *gtkpspell_get_dictionary_menu_active_item(GtkWidget *menu)
1238 {
1239         GtkWidget *menuitem;
1240         gchar *result;
1241
1242         g_return_val_if_fail(GTK_IS_MENU(menu), NULL);
1243         menuitem = gtk_menu_get_active(GTK_MENU(menu));
1244         result = gtk_object_get_data(GTK_OBJECT(menuitem), "dict_name");
1245         g_return_val_if_fail(result, NULL);
1246         return g_strdup(result);
1247   
1248 }
1249 #endif