summaryrefslogtreecommitdiff
path: root/components/text/nautilus-text-view.c
blob: b00b6a2c7841be4f4271729c85e5e0edf03c089c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */

/*
 *  Copyright (C) 2000 Eazel, Inc.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2 of the
 *  License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this library; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Author: Andy Hertzfeld <andy@eazel.com>
 *
 */

/* text view - display a text file */

#include <config.h>
#include "nautilus-text-view.h"

#include <gnome-xml/parser.h>
#include <gnome-xml/xmlmemory.h>

#include <bonobo/bonobo-zoomable.h>
#include <bonobo/bonobo-control.h>

#include <libnautilus/libnautilus.h>
#include <libnautilus/nautilus-clipboard.h>
#include <libnautilus-extensions/nautilus-background.h>
#include <libnautilus-extensions/nautilus-bonobo-extensions.h>
#include <libnautilus-extensions/nautilus-file-utilities.h>
#include <libnautilus-extensions/nautilus-file.h>
#include <libnautilus-extensions/nautilus-gdk-extensions.h>
#include <libnautilus-extensions/nautilus-gdk-pixbuf-extensions.h>
#include <libnautilus-extensions/nautilus-glib-extensions.h>
#include <libnautilus-extensions/nautilus-gtk-extensions.h>
#include <libnautilus-extensions/nautilus-gtk-macros.h>
#include <libnautilus-extensions/nautilus-string.h>
#include <libnautilus-extensions/nautilus-font-factory.h>
#include <libnautilus-extensions/nautilus-stock-dialogs.h>
#include <libnautilus-extensions/nautilus-xml-extensions.h>
#include <libnautilus-extensions/nautilus-global-preferences.h>

#include <gnome.h>
#include <gtk/gtkeventbox.h>
#include <libgnome/gnome-i18n.h>
#include <libgnomevfs/gnome-vfs.h>
#include <ghttp.h>

#include <limits.h>

#define MAX_SERVICE_ITEMS 32
#define TEXT_VIEW_CHUNK_SIZE 65536
#define MAX_FILE_SIZE	1024*1024
#define MAX_SELECTION_SIZE 256

#define ADDITIONAL_SERVICES_MENU_PATH	"/menu/Services Placeholder/Services/Service Items"

#define NAUTILUS_PREFERENCES_TEXT_VIEW_FONT                     "components/text_view/font"
#define NAUTILUS_PREFERENCES_TEXT_VIEW_STANDARD_FONT_SIZE       "components/text_view/standard_font_size"

struct NautilusTextViewDetails {
	NautilusFile *file;
        GtkWidget *event_box;
	GnomeVFSAsyncHandle *file_handle;	
	char *buffer;
	
	BonoboZoomable *zoomable;
	int zoom_index;
	
	GtkWidget *container;
	GtkWidget *text_display;
	
	int service_item_count;
	GnomeVFSFileSize file_size;
	gboolean service_item_uses_selection[MAX_SERVICE_ITEMS];
};

/* structure for handling service menu item execution */
typedef struct {
	NautilusTextView *text_view;
	char *service_template;
	char *source_mode;
} ServiceMenuItemParameters;

static void nautilus_text_view_initialize_class (NautilusTextViewClass *klass);
static void nautilus_text_view_initialize       (NautilusTextView      *view);
static void nautilus_text_view_destroy          (GtkObject             *object);
static void nautilus_text_view_update           (NautilusTextView      *text_view);
static void text_view_load_location_callback    (NautilusView          *view,
						 const char            *location,
						 NautilusTextView      *text_view);
static void merge_bonobo_menu_items             (BonoboControl         *control,
						 gboolean               state,
						 gpointer               user_data);
static void nautilus_text_view_update_font      (NautilusTextView      *text_view);
static int  update_service_menu_items           (GtkWidget             *widget,
						 GdkEventButton        *event,
						 gpointer              *user_data);
static void zoomable_set_zoom_level_callback    (BonoboZoomable        *zoomable,
						 float                  level,
						 NautilusTextView      *view);
static void zoomable_zoom_in_callback           (BonoboZoomable        *zoomable,
						 NautilusTextView      *directory_view);
static void zoomable_zoom_out_callback          (BonoboZoomable        *zoomable,
						 NautilusTextView      *directory_view);
static void zoomable_zoom_to_fit_callback       (BonoboZoomable        *zoomable,
						 NautilusTextView      *directory_view);
static void nautilus_text_view_load_uri         (NautilusTextView      *view,
						 const char            *uri);
static void font_changed_callback               (gpointer               callback_data);

NAUTILUS_DEFINE_CLASS_BOILERPLATE (NautilusTextView,
                                   nautilus_text_view,
                                   NAUTILUS_TYPE_VIEW)

static float text_view_preferred_zoom_levels[] = { .25, .50, .75, 1.0, 1.5, 2.0, 4.0 };
static int   text_view_font_size_deltas[] = { -6, -4, -2, 0, +4, +10, +22 };
static const int max_preferred_zoom_levels = (sizeof (text_view_preferred_zoom_levels) /
                                              sizeof (float)) - 1;

static void
nautilus_text_view_initialize_class (NautilusTextViewClass *klass)
{
	GtkObjectClass *object_class;
	
	object_class = GTK_OBJECT_CLASS (klass);
	
	object_class->destroy = nautilus_text_view_destroy;

	/* Text view component fonts */
	nautilus_preferences_default_set_string (NAUTILUS_PREFERENCES_TEXT_VIEW_FONT,
						 NAUTILUS_USER_LEVEL_INTERMEDIATE,
						 "fixed");
	nautilus_preferences_default_set_integer (NAUTILUS_PREFERENCES_TEXT_VIEW_STANDARD_FONT_SIZE,
						  NAUTILUS_USER_LEVEL_INTERMEDIATE,
						  14);
}

/* initialize ourselves by connecting to the location change signal and allocating our subviews */

static void
nautilus_text_view_initialize (NautilusTextView *text_view)
{
	GtkWidget *scrolled_window;
	
	text_view->details = g_new0 (NautilusTextViewDetails, 1);

        text_view->details->event_box = gtk_event_box_new ();

        nautilus_view_construct (NAUTILUS_VIEW (text_view), text_view->details->event_box);

	/* set up the zoomable interface */
	text_view->details->zoomable = bonobo_zoomable_new ();
	text_view->details->zoom_index = 3;
	
	gtk_signal_connect (GTK_OBJECT (text_view->details->zoomable), "set_zoom_level",
			    GTK_SIGNAL_FUNC (zoomable_set_zoom_level_callback), text_view);
	gtk_signal_connect (GTK_OBJECT (text_view->details->zoomable), "zoom_in",
			    GTK_SIGNAL_FUNC (zoomable_zoom_in_callback), text_view);
	gtk_signal_connect (GTK_OBJECT (text_view->details->zoomable), "zoom_out",
			    GTK_SIGNAL_FUNC (zoomable_zoom_out_callback), text_view);
	gtk_signal_connect (GTK_OBJECT (text_view->details->zoomable), "zoom_to_fit",
			    GTK_SIGNAL_FUNC (zoomable_zoom_to_fit_callback), text_view);
	
	bonobo_zoomable_set_parameters_full (text_view->details->zoomable,
					     1.0, .25, 4.0, TRUE, TRUE, FALSE,
					     text_view_preferred_zoom_levels, NULL,
					     NAUTILUS_N_ELEMENTS (text_view_preferred_zoom_levels));
	
	bonobo_object_add_interface (BONOBO_OBJECT (text_view),
				     BONOBO_OBJECT (text_view->details->zoomable));
 
    	
	gtk_signal_connect (GTK_OBJECT (text_view), 
			    "load_location",
			    text_view_load_location_callback, 
			    text_view);
			    	
	/* allocate a vbox to contain the text widget */
	text_view->details->container = gtk_vbox_new (FALSE, 0);
	gtk_container_set_border_width (GTK_CONTAINER (text_view->details->container), 0);
	gtk_container_add (GTK_CONTAINER (text_view->details->event_box), GTK_WIDGET (text_view->details->container));
	
	/* allocate the text object */
	text_view->details->text_display = gtk_text_new (NULL, NULL);
        gtk_widget_ref (text_view->details->text_display);
	gtk_text_set_editable (GTK_TEXT (text_view->details->text_display), FALSE);

	/* add signal handlers to the text field to enable/disable the service menu items */
	gtk_signal_connect_after (GTK_OBJECT (text_view->details->text_display),
                                  "button_release_event",
                                  GTK_SIGNAL_FUNC (update_service_menu_items), 
                                  text_view);
	gtk_signal_connect_after (GTK_OBJECT (text_view->details->text_display),
                                  "key_press_event",
                                  GTK_SIGNAL_FUNC (update_service_menu_items), 
                                  text_view);

	/* set the font of the text object */
	nautilus_text_view_update_font (text_view);

	/* Keep track of font changes */
	nautilus_preferences_add_callback_while_alive (NAUTILUS_PREFERENCES_TEXT_VIEW_FONT,
                                                       font_changed_callback,
                                                       text_view,
                                                       GTK_OBJECT (text_view));
	nautilus_preferences_add_callback_while_alive (NAUTILUS_PREFERENCES_TEXT_VIEW_STANDARD_FONT_SIZE,
                                                       font_changed_callback,
                                                       text_view,
                                                       GTK_OBJECT (text_view));
	
	scrolled_window = gtk_scrolled_window_new (NULL, NULL);
	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
					GTK_POLICY_AUTOMATIC,
					GTK_POLICY_AUTOMATIC);
	gtk_container_add (GTK_CONTAINER (scrolled_window), text_view->details->text_display);
	gtk_container_add (GTK_CONTAINER (text_view->details->container), scrolled_window);

	/* get notified when we are activated so we can merge in our menu items */
        gtk_signal_connect (GTK_OBJECT (nautilus_view_get_bonobo_control
					(NAUTILUS_VIEW (text_view))),
                            "activate",
                            merge_bonobo_menu_items,
                            text_view);
		 	
	/* finally, we can show everything */	
	gtk_widget_show_all (GTK_WIDGET (text_view->details->event_box));
}

static void
detach_file (NautilusTextView *text_view)
{
        nautilus_file_unref (text_view->details->file);
        text_view->details->file = NULL;
}

static void
nautilus_text_view_destroy (GtkObject *object)
{
	NautilusTextView *text_view;
	
        text_view = NAUTILUS_TEXT_VIEW (object);

        detach_file (text_view);

	if (text_view->details->file_handle) {
		gnome_vfs_async_cancel (text_view->details->file_handle);
	}
	
        gtk_widget_unref (text_view->details->text_display);
	g_free (text_view->details->buffer);

	g_free (text_view->details);

	NAUTILUS_CALL_PARENT (GTK_OBJECT_CLASS, destroy, (object));
}

/* here's a callback for the async close, which does nothing */
static void
file_close_callback (GnomeVFSAsyncHandle *handle,
			  GnomeVFSResult result,
			  gpointer callback_data)
{
}

/* this routine is called when we're finished reading to deallocate the buffer and
 * put up an error message if necessary
 */
static void
done_file_read (NautilusTextView *text_view, gboolean succeeded)
{
	if (text_view->details->buffer != NULL) {
		g_free (text_view->details->buffer);
		text_view->details->buffer = NULL;		
	}
	
	if (text_view->details->file_handle != NULL) {
		gnome_vfs_async_close (text_view->details->file_handle,
				       file_close_callback,
				       NULL);
	}
}
 
/* this callback handles the next chunk of data from the file by copying it into the
 * text field and reading more if necessary */
static void
file_read_callback (GnomeVFSAsyncHandle *vfs_handle,
		    GnomeVFSResult result,
		    gpointer buffer,
		    GnomeVFSFileSize bytes_requested,
		    GnomeVFSFileSize bytes_read,
		    gpointer callback_data)
{
	NautilusTextView *text_view;
        GtkText *display;
        char *name, *message;

	text_view = NAUTILUS_TEXT_VIEW (callback_data);

	text_view->details->file_size += bytes_read;
	
	if (result == GNOME_VFS_OK) {
		/* write the buffer into the text field */
                display = GTK_TEXT (text_view->details->text_display);
		if (!GTK_OBJECT_DESTROYED (display)) {
                        gtk_text_freeze (display);
                        gtk_text_set_point (display,
                                            gtk_text_get_length (display));
                        gtk_text_insert (display,
                                         NULL, NULL, NULL,
                                         buffer, bytes_read);
                        gtk_text_thaw (display);
                }
                
		/* read more if necessary */		
		if (text_view->details->file_size < MAX_FILE_SIZE) {
                        gnome_vfs_async_read (text_view->details->file_handle,
                                              text_view->details->buffer,
                                              TEXT_VIEW_CHUNK_SIZE,
                                              file_read_callback,
                                              callback_data);
                        return;
		} else {
                        name = nautilus_file_get_name (text_view->details->file);
                        message = g_strdup_printf (_("Sorry, but %s is too large for Nautilus to load all of it."),
                                                   name);
                        
			nautilus_show_error_dialog (message, _("File too large"), NULL);
                        
			g_free (name);
			g_free (message);
		}
	}

	done_file_read (text_view, result == GNOME_VFS_OK || result == GNOME_VFS_ERROR_EOF);
}


/* this callback gets invoked when the open call has completed */
static void
file_opened_callback (GnomeVFSAsyncHandle *vfs_handle,
		      GnomeVFSResult result,
		      gpointer callback_data)
{
	NautilusTextView *text_view;
	text_view = NAUTILUS_TEXT_VIEW (callback_data);
	
	if (result != GNOME_VFS_OK) {
		text_view->details->file_handle = NULL;
		done_file_read (text_view, FALSE);
		return;
	}

	text_view->details->file_size = 0;
	
	/* read the next chunck of the file */
	gnome_vfs_async_read (text_view->details->file_handle,
			      text_view->details->buffer,
			      TEXT_VIEW_CHUNK_SIZE,
			      file_read_callback,
			      callback_data);
}

/* callback to handle reading a chunk of the file
 * here's where we do the real work of inserting the text from the file into the view
 * Since the file may be large, and possibly remote, we load the text asynchronously and
 * progressively, one chunk at a time.
 */
static void
nautilus_text_view_update (NautilusTextView *text_view) 
{
	char *uri;
	
	uri = nautilus_file_get_uri (text_view->details->file);
	gtk_editable_delete_text (GTK_EDITABLE (text_view->details->text_display), 0, -1);   

	if (text_view->details->file_handle) {
		gnome_vfs_async_cancel (text_view->details->file_handle);
	}
	
	/* if necessary, allocate the buffer */
	if (text_view->details->buffer == NULL) {
		text_view->details->buffer = g_malloc (TEXT_VIEW_CHUNK_SIZE);
	}
	
	/* kick things off by opening the file asynchronously */
	gnome_vfs_async_open (&text_view->details->file_handle,
			      uri,
			      GNOME_VFS_OPEN_READ,
			      file_opened_callback,
			      text_view);
        g_free (uri);
}


static void
nautilus_text_view_load_uri (NautilusTextView *text_view, 
                             const char *uri)
{
 
	detach_file (text_view);
	text_view->details->file = nautilus_file_get (uri);
	
	nautilus_text_view_update (text_view);
}

static void
text_view_load_location_callback (NautilusView *view, 
                                   const char *location,
                                   NautilusTextView *text_view)
{
	nautilus_view_report_load_underway (NAUTILUS_VIEW (text_view));
	nautilus_text_view_load_uri (text_view, location);
	nautilus_view_report_load_complete (NAUTILUS_VIEW (text_view));
}

/* update the font and redraw */
static void
nautilus_text_view_update_font (NautilusTextView *text_view)
{
	char *font_name;
	GdkFont *font;
	int font_size;

	font_size = nautilus_preferences_get_integer (NAUTILUS_PREFERENCES_TEXT_VIEW_STANDARD_FONT_SIZE);

	font_size += text_view_font_size_deltas[text_view->details->zoom_index];

	font_name = nautilus_preferences_get (NAUTILUS_PREFERENCES_TEXT_VIEW_FONT);
	g_return_if_fail (font_name != NULL);

	font = nautilus_font_factory_get_font_by_family (font_name, font_size);
	g_free (font_name);

	g_return_if_fail (font != NULL);
	
	nautilus_gtk_widget_set_font (text_view->details->text_display, font);
	gdk_font_unref (font);

	gtk_editable_changed (GTK_EDITABLE (text_view->details->text_display));
}

/* handle merging in the menu items */
static void
handle_ui_event (BonoboUIComponent *ui,
		 const char *id,
		 Bonobo_UIComponent_EventType type,
		 const char *state,
		 NautilusTextView *view)
{
	if (type == Bonobo_UIComponent_STATE_CHANGED
            && nautilus_str_is_equal (state, "1")) {
                nautilus_preferences_set (NAUTILUS_PREFERENCES_TEXT_VIEW_FONT, id);
	}
}

static char *
get_selected_text (GtkEditable *text_widget)
{
	if (!text_widget->has_selection || text_widget->selection_start_pos == text_widget->selection_end_pos) {
		return NULL;
	}

	return gtk_editable_get_chars (text_widget, text_widget->selection_start_pos, text_widget->selection_end_pos);
}

/* here's the callback to handle the actual work for service menu items */
static void
handle_service_menu_item (BonoboUIComponent *ui, gpointer user_data, const char *verb)
{
	char *selected_text, *mapped_text, *uri;
	ServiceMenuItemParameters *parameters;
	int text_size;
	char *text_ptr;
	
	parameters = (ServiceMenuItemParameters *) user_data;
	
	/* determine if we should operate on the whole document or just the selection */
	if (nautilus_strcmp (parameters->source_mode, "document") == 0) {
		selected_text = gtk_editable_get_chars (GTK_EDITABLE (parameters->text_view->details->text_display), 0, -1);
		if (selected_text && strlen (selected_text) > 0) {
			/* formulate the url */
			mapped_text = gnome_vfs_escape_string (selected_text);
			uri = g_strdup_printf (parameters->service_template, mapped_text);
			g_free (mapped_text);
			
			/* load the resultant page through gnome-vfs */
                        /* FIXME: This uses sync. I/O. */
			if (nautilus_read_entire_file (uri, &text_size, &text_ptr) == GNOME_VFS_OK) {
 				gtk_editable_delete_text (GTK_EDITABLE (parameters->text_view->details->text_display), 0, -1);   
				gtk_text_insert (GTK_TEXT (parameters->text_view->details->text_display),
                                                 NULL, NULL, NULL,
                                                 text_ptr, text_size);
				g_free (text_ptr);
			}
			
			g_free (uri);
		}
		g_free (selected_text);
	} else {
		selected_text = get_selected_text (GTK_EDITABLE (parameters->text_view->details->text_display));
		if (selected_text != NULL) {
			/* truncate the selection to a reasonable size */
			if (strlen (selected_text) > MAX_SELECTION_SIZE) {
				selected_text [MAX_SELECTION_SIZE] = '\0';
			}
			
			/* formulate the url */
			mapped_text = gnome_vfs_escape_string (selected_text);
			uri = g_strdup_printf (parameters->service_template, mapped_text);
			
			/* goto the url */	
			nautilus_view_open_location_in_this_window (NAUTILUS_VIEW (parameters->text_view), uri);

			g_free (uri);
			g_free (selected_text);
			g_free (mapped_text);
		}
		
	}
}

/* utility routines to add service items to the services menu by iterating the services/text directory */

static ServiceMenuItemParameters *
service_menu_item_parameters_new (NautilusTextView *text_view, const char *service_template, const char *source_mode)
{
	ServiceMenuItemParameters *result;

	result = g_new0 (ServiceMenuItemParameters, 1);
	result->text_view = text_view;
	result->service_template = g_strdup (service_template);
	if (source_mode != NULL) {
		result->source_mode = g_strdup (source_mode);
	} else {
		result->source_mode = NULL;
	}
	
	return result;
}

static void
service_menu_item_parameters_free (ServiceMenuItemParameters *parameters)
{
	g_free (parameters->service_template);
	g_free (parameters->source_mode);
	g_free (parameters);
}			      

/* add a service menu entry from the passed in xml file */
static void
add_one_service (NautilusTextView *text_view, BonoboControl *control, const char *xml_path, int* index)
{
	xmlDocPtr service_definition;
	xmlNodePtr service_node;
	char *label, *escaped_label;
	char *tooltip, *template;
	char *verb_name, *item_path, *verb_path, *source_mode;
	ServiceMenuItemParameters *parameters;
	BonoboUIComponent *ui;
	
	/* load and parse the xml file */
	service_definition = xmlParseFile(xml_path);
	ui = bonobo_control_get_ui_component (control);
	 	
	if (service_definition != NULL) {
		service_node = xmlDocGetRootElement (service_definition);
	
		/* extract the label and template */
		label = nautilus_xml_get_property_translated (service_node, "label");	
		tooltip = nautilus_xml_get_property_translated (service_node, "tooltip");	
		template = xmlGetProp (service_node, "template");
		source_mode = xmlGetProp (service_node, "source");
		
		if (label != NULL && template != NULL) {
			/* allocate a structure containing the text_view and template to pass in as the user data */
			escaped_label = nautilus_str_double_underscores (label);
			parameters = service_menu_item_parameters_new (text_view, template, source_mode);
		
			text_view->details->service_item_uses_selection[*index] = 
				nautilus_strcmp (source_mode, "document") != 0;
			
			/* use bonobo to add the menu item */
			nautilus_bonobo_add_numbered_menu_item 
				(ui, 
		 		ADDITIONAL_SERVICES_MENU_PATH,
		 		*index,
		 		escaped_label, 
		 		NULL);
			g_free (escaped_label);

			/* set the tooltip if one was present */
			if (tooltip) {
				item_path = nautilus_bonobo_get_numbered_menu_item_path
						(ui, ADDITIONAL_SERVICES_MENU_PATH, *index);	
				nautilus_bonobo_set_tip (ui, item_path, tooltip);
				g_free (item_path);
			}
			
			verb_name = nautilus_bonobo_get_numbered_menu_item_command 
				(ui, ADDITIONAL_SERVICES_MENU_PATH, *index);	
			bonobo_ui_component_add_verb_full (ui, verb_name,
							   handle_service_menu_item,
							   parameters,
							  (GDestroyNotify) service_menu_item_parameters_free);	   
			
			/* initially disable the item unless it's document-based; it will be enabled if there's a selection */
			verb_path = g_strdup_printf ("/commands/%s", verb_name);
			if (nautilus_strcmp (source_mode, "document") != 0) {
				nautilus_bonobo_set_sensitive (ui, verb_path, FALSE);
			}
			g_free (verb_name);	
			g_free (verb_path);
			
			*index += 1;
		}

		xmlFree (label);
		xmlFree (template);
		xmlFree (tooltip);
		
		/* release the xml file */
		xmlFreeDoc (service_definition);	
	}
}

/* iterate through the passed in services directory to add services to the menu.
 * Don't add a service with the same name as one that has already been added.
 */
static GList *
add_services_to_menu (NautilusTextView *text_view,
			BonoboControl *control,
			const char *services_directory,
			GList *added_services,
			int* index)
{
	GnomeVFSResult result;
	GList *file_list, *element;	
	GnomeVFSFileInfo *current_file_info;
	char *services_uri, *service_xml_path;
	
	services_uri = gnome_vfs_get_uri_from_local_path (services_directory);
	result = gnome_vfs_directory_list_load (&file_list, services_uri, GNOME_VFS_FILE_INFO_DEFAULT, NULL);
	
	if (result != GNOME_VFS_OK) {
		g_free (services_uri);
		return added_services;
	}

	/* iterate through the directory */
	for (element = file_list; element != NULL; element = element->next) {
		current_file_info = element->data;

		if (*index >= MAX_SERVICE_ITEMS) {
			break;
		}
		
		if (nautilus_istr_has_suffix (current_file_info->name, ".xml")) {		
			if (g_list_find_custom (added_services, current_file_info->name,
						(GCompareFunc) strcmp) == NULL) {
				service_xml_path = nautilus_make_path (services_directory, current_file_info->name);
				add_one_service (text_view, control, service_xml_path, index);
				added_services = g_list_prepend (added_services, g_strdup (current_file_info->name));
				g_free (service_xml_path);
			}
		}
	}
	
	g_free (services_uri);
	gnome_vfs_file_info_list_free (file_list);	
	return added_services;
}

/* build the services menu from the shared and private services/text directories */
static void
nautilus_text_view_build_service_menu (NautilusTextView *text_view, BonoboControl *control)
{
	char *services_directory, *user_directory, *nautilus_datadir;
	GList *added_services;
	int index;

	index = 0;
	
	/* first, add the services from the global directory */
	nautilus_datadir = nautilus_make_path (DATADIR, "nautilus");
	services_directory = nautilus_make_path (nautilus_datadir, "services/text");
	added_services = add_services_to_menu (text_view, control, services_directory, NULL, &index);
	g_free (nautilus_datadir);
	g_free (services_directory);
	
	/* now add services from the user-specific directory, if any */	
	user_directory = nautilus_get_user_directory ();
	services_directory = nautilus_make_path (user_directory, "services/text");
	added_services = add_services_to_menu (text_view, control, services_directory, added_services, &index);
	g_free (services_directory);
	g_free (user_directory);

	/* add any services that are present in the updates folder */
	user_directory = nautilus_get_user_directory ();
	services_directory = nautilus_make_path (user_directory, "updates/services/text");
	added_services = add_services_to_menu (text_view, control, services_directory, added_services, &index);
	g_free (services_directory);
	g_free (user_directory);
	
	text_view->details->service_item_count = index;	
	nautilus_g_list_free_deep (added_services);
}

/* handle updating the service menu items according to the selection state of the text display */
static int
update_service_menu_items (GtkWidget *widget, GdkEventButton *event, gpointer *user_data)
{
	NautilusTextView *text_view;
	BonoboUIComponent *ui;
	BonoboControl *control;
	GtkEditable *text_widget;
	gboolean has_selection;
	char *verb_name, *verb_path;
	int index;
	
	text_view = NAUTILUS_TEXT_VIEW (user_data);
	control = nautilus_view_get_bonobo_control (NAUTILUS_VIEW (text_view));	
	ui = bonobo_control_get_ui_component (control);
	
	/* determine if there is a selection */
	text_widget = GTK_EDITABLE (text_view->details->text_display);
	has_selection = text_widget->has_selection && text_widget->selection_start_pos != text_widget->selection_end_pos;
	
	/* iterate through the menu items, handling the selection state */
	
	for (index = 0; index < text_view->details->service_item_count; index++) {
		verb_name = nautilus_bonobo_get_numbered_menu_item_command 
				(ui, ADDITIONAL_SERVICES_MENU_PATH, index);	
		
		verb_path = g_strdup_printf ("/commands/%s", verb_name);
		if (text_view->details->service_item_uses_selection[index]) {
			nautilus_bonobo_set_sensitive (ui, 
                                                       verb_path,
                                                       has_selection);
		}
		g_free (verb_name);
		g_free (verb_path);
	}
	
	return FALSE;
}

/* this routine is invoked when the view is activated to merge in our menu items */
static void
merge_bonobo_menu_items (BonoboControl *control, gboolean state, gpointer user_data)
{
 	NautilusTextView *text_view;

	g_assert (BONOBO_IS_CONTROL (control));
	
	text_view = NAUTILUS_TEXT_VIEW (user_data);

	if (state) {
                /* FIXME bugzilla.eazel.com 1274:
                 * See nautilus-text-view-ui.xml.  Need to query system for
                 * available fonts instead of hard coding the font list
                 */

                /* FIXME bugzilla.eazel.com 7907: 
                 * The "GTK System Font" string is hard coded in many places.
                 * Please see nautilus-text-view-ui.xml.
                 */
		nautilus_view_set_up_ui (NAUTILUS_VIEW (text_view),
				         DATADIR,
					 "nautilus-text-view-ui.xml",
					 "nautilus-text-view");

		nautilus_text_view_build_service_menu (text_view, control);

                gtk_signal_connect (GTK_OBJECT (bonobo_control_get_ui_component (control)),
                                    "ui_event", handle_ui_event, text_view);
                
		nautilus_clipboard_set_up_editable_in_control (GTK_EDITABLE (text_view->details->text_display),
						       		control,
						       		FALSE);

	}

        /* Note that we do nothing if state is FALSE. Nautilus content
         * views are never explicitly deactivated
	 */
}

/* handle the zoomable signals */
static void
nautilus_text_view_zoom_to_level (NautilusTextView *text_view, int zoom_index)
{
	int pinned_zoom_index;
	pinned_zoom_index = zoom_index;

	if (pinned_zoom_index < 0) {
		pinned_zoom_index = 0;
	} else if (pinned_zoom_index > max_preferred_zoom_levels) {
		pinned_zoom_index = max_preferred_zoom_levels;
	}
	
	if (pinned_zoom_index != text_view->details->zoom_index) {
		text_view->details->zoom_index = pinned_zoom_index;
		bonobo_zoomable_report_zoom_level_changed (text_view->details->zoomable,
                                                           text_view_preferred_zoom_levels[pinned_zoom_index]);		
		nautilus_text_view_update_font (text_view);
	}
 }

static void
nautilus_text_view_bump_zoom_level (NautilusTextView *text_view, int increment)
{
	nautilus_text_view_zoom_to_level (text_view, text_view->details->zoom_index + increment);
}

static void
zoomable_zoom_in_callback (BonoboZoomable *zoomable, NautilusTextView *text_view)
{
	nautilus_text_view_bump_zoom_level (text_view, 1);
}

static void
zoomable_zoom_out_callback (BonoboZoomable *zoomable, NautilusTextView *text_view)
{
	nautilus_text_view_bump_zoom_level (text_view, -1);
}

static int
zoom_index_from_float (float zoom_level)
{
	int i;

	for (i = 0; i < max_preferred_zoom_levels; i++) {
		float this, epsilon;

		/* if we're close to a zoom level */
		this = text_view_preferred_zoom_levels [i];
		epsilon = this * 0.01;

		if (zoom_level < this + epsilon)
			return i;
	}

	return max_preferred_zoom_levels;
}

static void
zoomable_set_zoom_level_callback (BonoboZoomable *zoomable, float level, NautilusTextView *view)
{
	nautilus_text_view_zoom_to_level (view, zoom_index_from_float (level));
}

static void
zoomable_zoom_to_fit_callback (BonoboZoomable *zoomable, NautilusTextView *view)
{
	nautilus_text_view_zoom_to_level (view, zoom_index_from_float (1.0));
}

static void
font_changed_callback (gpointer callback_data)
{
	g_return_if_fail (NAUTILUS_IS_TEXT_VIEW (callback_data));

	nautilus_text_view_update_font (NAUTILUS_TEXT_VIEW (callback_data));
}