File: ContentHandler.cpp

package info (click to toggle)
galeon 2.0.6-2.1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 19,156 kB
  • ctags: 9,680
  • sloc: ansic: 77,798; cpp: 13,928; sh: 9,000; xml: 5,761; makefile: 901
file content (919 lines) | stat: -rw-r--r-- 27,618 bytes parent folder | download | duplicates (2)
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
/*
 *  Copyright (C) 2001 Philip Langdale
 *
 *  This program 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, or (at your option)
 *  any later version.
 *
 *  This program 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 program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/*
 * The functioning of the download architecture, as described by Philip
 * on 28 May 2001 and updated on 28 June 2001, and again on 05 Jan 2005:
 * 
 * When mozilla runs into a file it cannot render internally or that it
 * does not have a plugin for, it calls the
 * nsIExternalHelperAppService. This service will then either attempt to
 * save the file or run it with a helper app depending on what the
 * mozilla mime database returns.
 * 
 * nsIExternalHelperAppService then calls out to the nsIHelperAppDialog
 * interface which handles the UI for the service. This is the interface
 * which we have reimplemented. Therefore, with a major caveat, we have
 * put a GNOME/GTK frontend on an unmodified mozilla backend.
 * 
 * Now for the caveat. With respect to saving files to disk, the mozilla
 * backend works exactly the same as it does in
 * mozilla-the-browser. However, for dealing with helper apps, we do not
 * use the mozilla backend at all. This is because we want to use the
 * gnome-vfs database to retrieve helper-app info, rather than the
 * mozilla helper app database. Note that mozilla now uses gnome-vfs for
 * it's backend, so in theory, we don't need this step. In reality, I 
 * remain suspicious of gnome-vfs's mime database and frankly don't trust
 * any other code to work around its stupidities correctly :-)
 * 
 * How it works:
 * 
 * a) The user clicks on a link or follows a redirect to a file of a type
 * that mozilla cannot handle. Mozilla passes the link to the
 * ExternalHelperAppService which in turn calls the Show() method of
 * nsIHelperAppDialog.
 * 
 * b) In our implementation of Show() we first compare the passed mime
 * type to gnome-vfs's mime list. If any helpers are available, we build
 * a list of them and offer the user the ability to open the file or save
 * it to disk. If there are no helpers, we just offer the option of saving
 * or cancelling the downlod.
 * 
 * c-1) The "Save to Disk" action. We first check galeon preferences to
 * see if the user wants to use the built-in mozilla downloader, or a
 * command-line executed downloader. We still have our gtm code but until
 * gtm is updated to use bonobo-activation, we can't use it effectively.
 *
 * c-2a) The built-in downloader.  This action is handled by the mozilla
 * backend. Our nsIHelperAppDialog does the same thing that the
 * mozilla-the-browser one does, which is to call the SaveToDisk() method
 * of nsIExternalHelperAppService. This in turn calls the
 * PromptForSaveToFile() method of nsIHelperAppDialog putting the ball
 * back in our court.
 * 
 * c-2b) Now, if galeon is configured to always ask for a download
 * directory, it will pop up a file selector so that the user can select
 * the directory and filename to save the file to.  Otherwise, it will
 * use galeon's default download directory and proceed without
 * interaction.
 * 
 * c-2c) When PromptForSaveToFile() returns, nsIExternalHelperAppService
 * will then call the ShowProgressDialog() method of
 * nsIHelperAppDialog. This progress dialog, obviously, tracks the
 * progress of the download. It is worth noting that mozilla starts the
 * actual download as soon as the user clicks on the link or follows the
 * redirect. While the user is deciding what action to take, the file is
 * downloading. Often, for small files, the file is already downloaded
 * when the user decides what directory to put it in. The progress dialog
 * does not appear in these cases. Also, we currently have a small
 * problem where our progress dialog times the download from the point
 * the dialog appears, not from the time the download starts. This is due
 * to the timestamp that is passed to us is just plain weird, and I
 * haven't worked out how to turn it into a useable time. The fact that
 * the download starts early means that the file is actually downloaded
 * to a temp file and only at the end is it moved to it's final location.
 * 
 * c-3a) The two external downloader options.  These options are
 * handled completely by galeon. The first thing that we do is call the
 * Cancel() method of nsIExternalHelperAppService to cancel the mozilla
 * download. We then pass the url to our own LaunchExternalDownloader()
 * method. This method will ask for a download directory as appropriate
 * as with the "Save to disk" action.
 * 
 * c-3b) Finally, depending on whether GTM or a command line handler was
 * selected in prefs, the external handler will be called with the url
 * passed and the directory selected.
 * 
 * d-1) The "Run with Helper App" action. This implementation is slightly
 * subversive with respect to the mozilla helper db but allows us to avoid
 * inventing an information passing mechanism between ContentHandler and
 * ProgressListener. Rather, we populate the mozilla MIME Info struct with
 * the handler we retrieved from gnome-vfs but explicitly tell mozilla not
 * to launch the helper. The ProgressListener retrieves this info when the
 * download completes and then runs the helper.
 *
 * e) General notes.  We cannot use this infrastructure to override
 * native mozilla types. mozilla will attempt to render these types and
 * never call out to us. We are at the end of the chain as the handler of
 * last resort, so native and plugin types will never reach us. This also
 * means that a file with an incorrect mime-type ( eg: .tar.bz2 marked as
 * text/plain ) will be incorrectly rendered by mozilla. We cannot help
 * this.
 * 
 * Despite the apparent user-side similarity with explicit downloads by
 * a shift-click or context-menu item, there is actually none at all.
 * Explicit downloads are handled by nsIWebBrowserPersist. We reuse the
 * progress dialog for these but nothing in ContentHandler is involved.
 * 
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif


#include "prefs-strings.h"
#include "eel-gconf-extensions.h"
#include "gul-download.h"
#include "gul-glade.h"
#include "gul-string.h"
#include "gul-general.h"
#include "gul-gui.h"
#include "galeon-embed-utils.h"
#include "gul-file-chooser.h"
#include "galeon-debug.h"
#include "hig-alert.h"

#include <glib/gi18n.h>
#include <gtk/gtkliststore.h>
#include <gtk/gtkwindow.h>
#include <gtk/gtklabel.h>
#include <gtk/gtktreeselection.h>
#include <gtk/gtkcellrenderertext.h>
#include <gtk/gtkexpander.h>
#include <gtk/gtkmain.h>
#include <libgnomevfs/gnome-vfs-mime.h>
#include <libgnomevfs/gnome-vfs-mime-handlers.h>

#include "AutoJSContextStack.h"
#include "ContentHandler.h"
#include "GaleonUtils.h"   /* GaleonUtils::FindGtkParent */
#include "ProgressListener.h" /* for BuildDownloadPath */
#include "GulString.h"

#include <nsIPromptService.h>
#include <nsIWebProgressListener.h>
#include <nsCOMPtr.h>
#include <nsServiceManagerUtils.h>
#include <nsIInterfaceRequestorUtils.h>
#include <nsIURI.h>
#include <nsIURL.h>
#include <nsIMIMEInfo.h>
#include <nsILocalFile.h>
#include <nsIDOMWindow.h>
#include <nsIExternalHelperAppService.h>
#include <nsCExternalHandlerService.h>
#include <nsMemory.h>
#include <nsNetError.h>

class GContentHandler;
struct MimeAskActionDialog;

extern "C"
void mime_ask_dialog_save_clicked_cb (GtkButton *button,
				      MimeAskActionDialog *dialog);
extern "C"
void mime_ask_dialog_open_clicked_cb (GtkButton *button,
				      MimeAskActionDialog *dialog);
extern "C"
gint mime_ask_dialog_cancel_clicked_cb (GtkButton *button,
					MimeAskActionDialog *dialog);

/*
 * MimeAskActionDialog: the representation of dialogs used to ask
 * about actions on MIME types
 */
struct MimeAskActionDialog
{
	MimeAskActionDialog(GContentHandler *aContentHandler,
			    GtkWidget *aParentWidget,
			    const char *aMimeType);
	~MimeAskActionDialog();

	GContentHandler* mContentHandler;
	GtkWidget *mDialogWidget;
	GtkWidget *mParent;
	GtkWidget *mListView;

	GList *mApps;

	enum
	{
		APP_COLUMN,
		N_COLUMNS
	};

	// How many rows to show in the applications list
	static const int NUM_APPLICATIONS = 4; 
};


/* ------------------------------------------------------------
 * Mini progress listener so that we can listen for errors
 * while downloading */
class MiniProgressListener
	: public nsIWebProgressListener2
{
public:
	MiniProgressListener(MimeAskActionDialog *dialog) : 
		mDialog( dialog ) 
	{ LOG ("MiniProgresListener ctor(%p)", this ); };

	~MiniProgressListener() 
	{ LOG ("MiniProgresListener dtor(%p)", this ); };

 	NS_DECL_ISUPPORTS
	NS_DECL_NSIWEBPROGRESSLISTENER
	NS_DECL_NSIWEBPROGRESSLISTENER2

	MimeAskActionDialog *mDialog;
};

NS_IMPL_ISUPPORTS2(MiniProgressListener, nsIWebProgressListener2,
		   nsIWebProgressListener)

// ------------------------------------------------------------

/* Implementation file */
NS_IMPL_ISUPPORTS1(GContentHandler, nsIHelperAppLauncherDialog)

GContentHandler::GContentHandler() : mUri(nsnull)
{
	/* member initializers and constructor code */
	LOG ("GContentHandler ctor(%p)", this );
}

GContentHandler::~GContentHandler()
{
	/* destructor code */
	LOG ("GContentHandler dtor(%p)", this );
}

////////////////////////////////////////////////////////////////////////////////
// begin nsIHelperAppLauncher impl
////////////////////////////////////////////////////////////////////////////////

/* void show (in nsIHelperAppLauncher aLauncher, in nsISupports aContext); */
NS_IMETHODIMP GContentHandler::Show(nsIHelperAppLauncher *aLauncher,
				    nsISupports *aContext,
				    PRUint32 aReason)
{
	/* aForced reflects if the content being sent is normally viewable
	 * in mozilla or not. That fact doesn't affect us, so ignore it
	 */
	nsresult rv;

	mLauncher = aLauncher;
	mContext = aContext;
	rv = Init ();
	
	MIMEAskAction ();

	return NS_OK;
}

/* nsILocalFile promptForSaveToFile (in nsISupports aWindowContext, in wstring aDefaultFile, in wstring aSuggestedFileExtension); */
NS_IMETHODIMP GContentHandler::PromptForSaveToFile(
						   nsIHelperAppLauncher *aLauncher,
						   nsISupports *aWindowContext,
						   const PRUnichar *aDefaultFile,
						   const PRUnichar *aSuggestedFileExtension,
#ifdef HAVE_NSIHELPERAPPLAUNCHERDIALOG_FORCEPROMPT
						   PRBool aForcePrompt,
#endif
						   nsILocalFile **_retval)
{
	mContext = aWindowContext;

	nsCOMPtr<nsIDOMWindow> parentDOMWindow = do_GetInterface (aWindowContext);
	GtkWidget *parentWindow = GaleonUtils::FindGtkParent (parentDOMWindow);

	/* Get the directory to use for downloading into */
#ifdef HAVE_NSIHELPERAPPLAUNCHERDIALOG_FORCEPROMPT
	if (!eel_gconf_get_boolean (CONF_DOWNLOADING_ASK_DIR) && !aForcePrompt)
#else
	if (!eel_gconf_get_boolean (CONF_DOWNLOADING_ASK_DIR))
#endif
	{
		nsresult rv =  BuildDownloadPath (GulCString (aDefaultFile).get(),
						  parentWindow, _retval);
		if (NS_SUCCEEDED (rv)) return rv;
	}

	nsresult rv;
	AutoJSContextStack stack;
	rv = stack.Init ();
	if (NS_FAILED (rv)) return rv;

	GulFileChooser *dialog;
	dialog = gul_file_chooser_new (_("Save"), parentWindow,
					GTK_FILE_CHOOSER_ACTION_SAVE,
					CONF_STATE_LAST_DOWNLOAD_DIR);
	gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog),
					   GulCString (aDefaultFile).get());

	while (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
	{
		gchar *filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
		if (!filename)
		{
			continue;
		}

		if (gul_gui_confirm_overwrite_file (GTK_WIDGET (dialog),
						    filename) == FALSE)
		{
			g_free (filename);
			continue;
		}

		nsCOMPtr <nsILocalFile> destFile;

		NS_NewNativeLocalFile (GulDependentCString (filename),
				       PR_TRUE,
				       getter_AddRefs(destFile));
		g_free (filename);

		NS_ADDREF (*_retval = destFile);

		gtk_widget_destroy (GTK_WIDGET (dialog));

		return NS_OK;
	}
	gtk_widget_destroy (GTK_WIDGET (dialog));

	return NS_ERROR_FAILURE;
}

////////////////////////////////////////////////////////////////////////////////
// begin local public methods impl
////////////////////////////////////////////////////////////////////////////////

NS_METHOD GContentHandler::LaunchExternalDownloader (void)
{
	gul_download_external_save_url (mUrl.get());
	return NS_OK;
}


NS_METHOD GContentHandler::FindHelperApp (void)
{
	if (mUrlHelper || mScheme.Equals("file"))
	{
		return LaunchHelperApp ();
	}
	else
	{
		if (NS_SUCCEEDED(SynchroniseMIMEInfo()))
		{
			return mLauncher->LaunchWithApplication(nsnull, PR_FALSE);
		}
		else
		{
			return NS_ERROR_FAILURE;
		}
	}
}

NS_METHOD GContentHandler::LaunchHelperApp (void)
{
	if (mMimeType.Length())
	{
		nsresult rv;
		nsCOMPtr<nsIExternalHelperAppService> helperService =
			do_GetService (NS_EXTERNALHELPERAPPSERVICE_CONTRACTID);

		nsCOMPtr<nsPIExternalAppLauncher> appLauncher =
			do_QueryInterface (helperService, &rv);
		if (NS_SUCCEEDED(rv))
		{
			appLauncher->DeleteTemporaryFileOnExit(mTempFile);
		}

		GulCString filename;
		mUri->GetPath(filename);

		/* FIXME: check return value */
		gul_general_launch_application (mHelperApp,
						mUrlHelper ? mUrl.get()
							   : filename.get(),
						gtk_get_current_event_time());

	}

	mLauncher->Cancel (NS_BINDING_ABORTED);
	return NS_OK;
}

NS_METHOD GContentHandler::GetLauncher (nsIHelperAppLauncher * *_retval)
{
	NS_IF_ADDREF (*_retval = mLauncher);
	return NS_OK;
}

NS_METHOD GContentHandler::GetContext (nsISupports * *_retval)
{
	NS_IF_ADDREF (*_retval = mContext);
	return NS_OK;
}


NS_METHOD GContentHandler::CheckAppSupportScheme (void)
{
	g_return_val_if_fail (mHelperApp, NS_ERROR_FAILURE);

#ifdef HAVE_NEW_GNOME_VFS_MIME_API

	/* There is no way to get the supported schemes in the new API */
	mUrlHelper = gnome_vfs_mime_application_supports_uris (mHelperApp);
#else
	mUrlHelper = FALSE;

	if (mHelperApp->expects_uris != GNOME_VFS_MIME_APPLICATION_ARGUMENT_TYPE_URIS)
	{
		return NS_OK;
	}
	
	GList *l;
	for (l = mHelperApp->supported_uri_schemes; l != NULL; l = l->next)
	{
		char *uri_scheme = (char *)l->data;
		g_return_val_if_fail (uri_scheme != NULL, FALSE);
		if (mScheme.Equals (uri_scheme))
		{
			mUrlHelper = TRUE;
			return NS_OK;
		}
	}
#endif

	return NS_OK;
}

NS_METHOD GContentHandler::SetHelperApp(GnomeVFSMimeApplication *aHelperApp,
					PRBool alwaysUse)
{
	mHelperApp = aHelperApp;

	CheckAppSupportScheme();

	return NS_OK;
}

NS_METHOD GContentHandler::SynchroniseMIMEInfo (void)
{
	nsresult rv;
	nsCOMPtr<nsIMIMEInfo> mimeInfo;
	rv = mLauncher->GetMIMEInfo(getter_AddRefs(mimeInfo));
	if(NS_FAILED(rv)) return NS_ERROR_FAILURE;

	// XXX information passing kludge (to ProgressListener)
	// TODO: should probably use some prefix, like 'gnomevfs:'
	
	const char * id;
#ifdef HAVE_NEW_GNOME_VFS_MIME_API
	id = gnome_vfs_mime_application_get_desktop_id (mHelperApp);
#else
	id = mHelperApp->id;
#endif

	/* The current time is fine here as the user has just clicked
	 * a button (it is used as the time for the application opening) */
	char * info = g_strdup_printf ("%d:%s", gtk_get_current_event_time(),
				       id);

	rv = mimeInfo->SetDescription(GulString(info));
	g_free (info);

	if(NS_FAILED(rv)) return NS_ERROR_FAILURE;

	rv = mimeInfo->SetPreferredAction(nsIMIMEInfo::useHelperApp);
	if(NS_FAILED(rv)) return NS_ERROR_FAILURE;

	return NS_OK;
}

////////////////////////////////////////////////////////////////////////////////
// begin local private methods impl
////////////////////////////////////////////////////////////////////////////////
NS_METHOD GContentHandler::Init (void)
{
	nsresult rv;

	nsCOMPtr<nsIMIMEInfo> MIMEInfo;
	rv = mLauncher->GetMIMEInfo (getter_AddRefs(MIMEInfo));
	rv = MIMEInfo->GetMIMEType (mMimeType);
	rv = mLauncher->GetSource(getter_AddRefs(mUri));
	rv = mLauncher->GetTargetFile(getter_AddRefs(mTempFile));

	rv = mUri->GetSpec (mUrl);
	rv = mUri->GetScheme (mScheme);

	ProcessMimeInfo ();

	return NS_OK;
}

NS_METHOD GContentHandler::ProcessMimeInfo (void)
{
	if (mMimeType.IsEmpty() ||
	    mMimeType.Equals("application/octet-stream"))
	{
		// suggested filename
		GulCString uriFileName;

		GulString filename;
		mLauncher->GetSuggestedFileName (filename);
		uriFileName = filename;

#ifdef HAVE_GNOME_VFS_GET_MIME_TYPE_FOR_NAME
		mMimeType.Assign(gnome_vfs_get_mime_type_for_name
				 (uriFileName.get()));
#else
		mMimeType.Assign(gnome_vfs_mime_type_from_name
				 (uriFileName.get()));
#endif
	}

	return NS_OK;
}

NS_METHOD GContentHandler::MIMEAskAction (void)
{
	nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(mContext);
	GtkWidget *parentWidget = GaleonUtils::FindGtkParent(parent);

	MimeAskActionDialog *dialog =
		new MimeAskActionDialog(this, parentWidget, mMimeType.get());

	/* Create a mini progress listener while the mime ask action
	 * dialog is being displayed. Using this listener, we can catch
	 * errors while the download is happening to a temporary file
	 * - bug 148739
	 */
	nsCOMPtr<nsIWebProgressListener2> listener = new MiniProgressListener( dialog );
	mLauncher->SetWebProgressListener( listener );

	return NS_OK;
}

////////////////////////////////////////////////////////////////////////////////
// begin MIMEAskActionDialog methods.
////////////////////////////////////////////////////////////////////////////////

MimeAskActionDialog::MimeAskActionDialog(GContentHandler *aContentHandler,
					 GtkWidget *aParentWidget,
					 const char *aMimeType) :
					 mContentHandler(aContentHandler),
					 mParent(aParentWidget)
{
	GtkWidget *label;
	GladeXML *GXml;
	char *markup;
	LOG ("MimeAskActionDialog ctor(%p)", this );

	mApps = gnome_vfs_mime_get_all_applications(aMimeType);
	if (mApps)
	{
		GtkListStore * liststore;

		GXml = gul_glade_widget_new("galeon.glade",
					     "mime_ask_open_dialog", 
					     &mDialogWidget, this);

		mListView = glade_xml_get_widget(GXml, "mime_ask_dialog_helper_list_view");

		GnomeVFSMimeApplication *defaultApp =
			gnome_vfs_mime_get_default_application(aMimeType);

		char *title;
		if (defaultApp)
		{
			title = g_strdup_printf (_("Open this file with \"%s\"?"), defaultApp->name);
		}
		else
		{
			// can this actually happen?
			title = g_strdup (_("Open this file with another application?"));
		}
		markup = g_strdup_printf ("<span size=\"larger\" weight=\"bold\">%s</span>", title);
		g_free (title);

		label = glade_xml_get_widget(GXml, "mime_ask_action_title");
		gtk_label_set_markup (GTK_LABEL(label), markup);
		g_free (markup);


		liststore = gtk_list_store_new(N_COLUMNS,
						G_TYPE_STRING);
		gtk_tree_view_set_model(GTK_TREE_VIEW(mListView),
					GTK_TREE_MODEL(liststore));

		GtkCellRenderer *renderer;
		renderer = gtk_cell_renderer_text_new();

		GtkTreeViewColumn *column;
		column = gtk_tree_view_column_new_with_attributes("Application",
						renderer,
						"text", APP_COLUMN,
						NULL);
		gtk_tree_view_append_column(GTK_TREE_VIEW(mListView), column);

		GtkTreeSelection *selection =
				gtk_tree_view_get_selection(GTK_TREE_VIEW(mListView));
		gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);

		guint index;
		for (GList *i = mApps ; i ; i = i->next, index++)
		{
			GnomeVFSMimeApplication *app =
				static_cast<GnomeVFSMimeApplication *>(i->data);

			GtkTreeIter iter;
			gtk_list_store_append (liststore, &iter);
			gtk_list_store_set (liststore, &iter,
					    APP_COLUMN, app->name,
					    -1);

			if (defaultApp &&
			    !g_ascii_strcasecmp(app->name, defaultApp->name))
			{
				gtk_tree_selection_select_iter(selection, &iter);
			}
		}

		g_object_unref (liststore);

		// Calculate the correct width for the list view for showing
		// NUM_APPLICATION rows.
		gint width, height, ypad;
		gtk_cell_renderer_get_size (renderer, GTK_WIDGET (mListView),
				            NULL, NULL, NULL, &width, &height);
		g_object_get (renderer, "ypad", &ypad, NULL);
		height = NUM_APPLICATIONS*(height + ypad) + 2*ypad;
		gtk_widget_set_size_request (GTK_WIDGET (mListView), 0, height);
	}
	else
	{
		GXml = gul_glade_widget_new("galeon.glade",
					     "mime_ask_save_dialog", 
					     &mDialogWidget, this);
		GtkWidget *w;
		w = glade_xml_get_widget(GXml, "mime_ask_dialog_save");
		gtk_widget_grab_default (w);
	}

	GtkWidget *mimeIcon = glade_xml_get_widget(GXml,
						   "mime_ask_action_icon");
	gul_gui_image_set_from_mime_type (mimeIcon, 
			                  aMimeType, GTK_ICON_SIZE_DIALOG);


	nsCOMPtr<nsIHelperAppLauncher> launcher;
	(void)mContentHandler->GetLauncher(getter_AddRefs(launcher));

	// suggested filename
	GulCString filename;
	GulString uFilename;
	launcher->GetSuggestedFileName (uFilename);
	filename = uFilename;

	markup = g_markup_printf_escaped("<b>%s</b>", filename.get());

	label = glade_xml_get_widget(GXml, "mime_ask_action_name");
	gtk_label_set_markup(GTK_LABEL(label), markup);
	g_free (markup);

	// MIME type description
	const char *description = gnome_vfs_mime_get_description(aMimeType);
	if (!description) description = aMimeType;
	
	label = glade_xml_get_widget(GXml, "mime_ask_action_description");
	gtk_label_set_text(GTK_LABEL(label), description);

	// source
	nsCOMPtr<nsIURI> source;
	launcher->GetSource(getter_AddRefs(source));

	GulCString spec;
	source->Resolve(NS_LITERAL_CSTRING("."), spec);

	markup = g_strdup_printf ("<i>%s</i>", spec.get());
	label = glade_xml_get_widget(GXml, "mime_ask_action_source");
	gtk_label_set_markup(GTK_LABEL(label), markup);
	g_free (markup);

	gtk_window_set_transient_for(GTK_WINDOW(mDialogWidget), 
				     GTK_WINDOW(aParentWidget));

	gtk_widget_show(mDialogWidget);

	g_object_unref(G_OBJECT(GXml));
}

MimeAskActionDialog::~MimeAskActionDialog()
{
	LOG ("MimeAskActionDialog dtor(%p)", this );

	if(mApps)
		gnome_vfs_mime_application_list_free(mApps);

	gtk_widget_destroy(mDialogWidget);
}

////////////////////////////////////////////////////////////////////////////////
// begin MIMEAskActionDialog callbacks.
////////////////////////////////////////////////////////////////////////////////

extern "C" void
mime_ask_dialog_save_clicked_cb(GtkButton *button, MimeAskActionDialog *dialog)
{
	gtk_widget_hide(dialog->mDialogWidget);

	nsCOMPtr<nsIHelperAppLauncher> launcher;
	dialog->mContentHandler->GetLauncher(getter_AddRefs(launcher));

	launcher->SetWebProgressListener( nsnull );
	
 	if (eel_gconf_get_boolean(CONF_DOWNLOADING_EXTERNAL_DOWNLOADER)
 	    == DOWNLOADER_BUILTIN)
 	{
		launcher->SaveToDisk(nsnull,PR_FALSE);
	}
	else
	{
		launcher->Cancel(NS_BINDING_ABORTED);
		dialog->mContentHandler->LaunchExternalDownloader();
	}
	
	delete dialog;
}

static void
mime_ask_dialog_download_cancel (MimeAskActionDialog *dialog)
{
	nsCOMPtr<nsIHelperAppLauncher> launcher;
	dialog->mContentHandler->GetLauncher(getter_AddRefs(launcher));

	launcher->SetWebProgressListener( nsnull );
	launcher->Cancel(NS_BINDING_ABORTED);

	delete dialog;
}

extern "C" void
mime_ask_dialog_open_clicked_cb (GtkButton *button, MimeAskActionDialog *dialog)
{
	nsCOMPtr<nsIHelperAppLauncher> launcher;
	dialog->mContentHandler->GetLauncher (getter_AddRefs(launcher));

	GnomeVFSMimeApplication *app(NULL);
	if (dialog->mApps)
	{
		GtkTreeSelection *selection =
			gtk_tree_view_get_selection(GTK_TREE_VIEW(dialog->mListView));

		GtkTreeModel *model;
		GtkTreeIter iter;
		if (gtk_tree_selection_get_selected (selection, &model, &iter))
		{
			GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
			gint selected = atoi (gtk_tree_path_to_string (path));
			gtk_tree_path_free (path);

			app = static_cast<GnomeVFSMimeApplication *>
				(g_list_nth_data (dialog->mApps, selected));
		}
	}

	if (app)
	{
		launcher->SetWebProgressListener( nsnull );
		dialog->mContentHandler->SetHelperApp(app, FALSE);
		dialog->mContentHandler->FindHelperApp();
		delete dialog;
	}
	else
	{	
		nsresult rv;
		AutoJSContextStack stack;
		rv = stack.Init ();
		if (NS_FAILED (rv)) return;

		mime_ask_dialog_download_cancel(dialog);
		galeon_embed_utils_nohandler_dialog_run(dialog->mParent);
	}
}

extern "C" gint
mime_ask_dialog_cancel_clicked_cb(GtkButton *button,
				   MimeAskActionDialog *dialog)
{
	mime_ask_dialog_download_cancel(dialog);
	return 0; /* FIXME: philipl, is this the right thing to return? */
}

extern "C" void
mime_ask_dialog_toggle_helpers_toggled_cb(GtkExpander *expander,
					  GParamSpec *pspec,
					  MimeAskActionDialog *dialog)
{
	gboolean val = gtk_expander_get_expanded (expander);
	gtk_window_set_resizable (GTK_WINDOW(dialog->mDialogWidget), val);
}

extern "C" void
mime_ask_dialog_close_cb(GtkWidget *dialogWidget, MimeAskActionDialog *dialog)
{
	nsresult rv;
	nsCOMPtr<nsIHelperAppLauncher> launcher;
	rv = dialog->mContentHandler->GetLauncher(getter_AddRefs(launcher));

	launcher->SetWebProgressListener( nsnull );
	launcher->Cancel(NS_BINDING_ABORTED);
}

// ------------------------------------------------------------

NS_IMETHODIMP MiniProgressListener::OnStatusChange(nsIWebProgress *aWebProgress, 
					       nsIRequest *aRequest, nsresult aStatus, 
					       const PRUnichar *aMessage)
{
	if (NS_SUCCEEDED (aStatus)) return NS_OK;

	nsresult rv;
	AutoJSContextStack stack;
	rv = stack.Init ();
	if (NS_FAILED (rv)) return rv;

	/* When the save fails, the mozilla code will call this, and
	 * after this point, the launcher isn't valid for some reason
	 * so we need to display an error, and get out of this code
	 * quickly */
	GtkWidget *dialog = 
		hig_alert_new (GTK_WINDOW (mDialog->mParent), 
			       (GtkDialogFlags)0,
			       HIG_ALERT_ERROR,
			       ("Failed to Save File."),
			       GulCString (aMessage).get(),
			       GTK_STOCK_OK, GTK_RESPONSE_OK,
			       NULL);

	delete mDialog; /* Close, and delete the MIME dialog */
	mDialog = NULL;

	gtk_dialog_run (GTK_DIALOG (dialog));
	gtk_widget_destroy (dialog);

	return NS_OK;
}

NS_IMETHODIMP MiniProgressListener::OnStateChange(nsIWebProgress *aWebProgress, 
					      nsIRequest *aRequest, PRUint32 aStateFlags, 
					      nsresult aStatus)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP MiniProgressListener::OnProgressChange(nsIWebProgress *aWebProgress, 
						 nsIRequest *aRequest, PRInt32 aCurSelfProgress,
						 PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress,
						 PRInt32 aMaxTotalProgress)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP MiniProgressListener::OnLocationChange(nsIWebProgress *aWebProgress, 
						 nsIRequest *aRequest, nsIURI *location)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP MiniProgressListener::OnSecurityChange(nsIWebProgress *aWebProgress, 
						 nsIRequest *aRequest, PRUint32 state)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP MiniProgressListener::OnProgressChange64(nsIWebProgress *aWebProgress,
						nsIRequest *aRequest, PRInt64 aCurSelfProgress,
						PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress,
						PRInt64 aMaxTotalProgress)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

#ifdef HAVE_NSIWEBPROGRESSLISTENER2_ONREFRESHATTEMPTED
NS_IMETHODIMP MiniProgressListener::OnRefreshAttempted(nsIWebProgress *aWebProgress,
						nsIURI *aRefreshURI, PRInt32 aMillis,
						PRBool aSameURI, PRBool *_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
#endif