File: ProgressListener.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 (829 lines) | stat: -rw-r--r-- 22,068 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
/*
 *  Copyright (C) 2001 Philip Langdale, Matthew Aubury
 *
 *  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.
 */

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

#include "ProgressListener.h"

#include "gul-general.h"
#include "eel-gconf-extensions.h"
#include "egg-recent-model.h"
#include "prefs-strings.h"
#include "gul-gui.h"
#include "galeon-debug.h"

#include <unistd.h>
#include <libgnome/gnome-exec.h>
#include <libgnomevfs/gnome-vfs-utils.h>
#include <glib/gi18n.h>

#include <nsComponentManagerUtils.h>
#include <nsServiceManagerUtils.h>
#include <nsIWebBrowserPersist.h>
#include <nsCWebBrowserPersist.h>
#include <nsIFileURL.h>
#include <nsIFTPChannel.h>
#include <nsIHttpChannel.h>
#include <nsIMIMEInfo.h>
#include <nsNetError.h>                 // for NS_BINDING_ABORTED, see FIXME
#include <nsILocalFile.h>
#include <nsIObserver.h>
#include <nsCExternalHandlerService.h>
#include <nsMemory.h>

static const PRInt64 kInterval            = 500000;     /* in microsecs == 500ms == 0.5s */
static const PRInt64 kUnknownSizeInterval = 150000;     /* in microsecs == 150ms == 0.15s */

NS_IMPL_ISUPPORTS4(GProgressListener, nsIWebProgressListener, nsIWebProgressListener2,
		   nsITransfer, nsISupportsWeakReference)

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

static void
download_cancel_cb (Download *download, GProgressListener *self)
{
	self->Abort();
}

static void
download_resume_cb (Download *download, GProgressListener *self)
{
	self->Resume();
}

static void
download_pause_cb (Download *download, GProgressListener *self)
{
	self->Pause();
}

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

GProgressListener::GProgressListener () :
					  mCancelable(nsnull),
					  mGaleonPersist(nsnull),
					  mDownload(nsnull),
					  mContentLength(-1),
					  mMIMEInfo(nsnull)
{
	LOG ("GProgressListener ctor(%p)", this);
}

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

NS_METHOD GProgressListener::InitForPersist (nsIWebBrowserPersist *aPersist,
					      nsIURI *aURI,
					      nsIFile *aFile,
					      GaleonEmbedPersist *galeonPersist)
{
	/* fill in download details */
	mUri = aURI;
	mFile = aFile;
	mCancelable = aPersist;

	mGaleonPersist = (GaleonEmbedPersist *) g_object_ref (galeonPersist);

	mStartTime = PR_Now();

	/* do remaining init */
	nsresult rv = PrivateInit ();


	/* done */
	return rv;
}

static void
download_weak_ref_cb (gpointer data, GObject *object)
{
	GProgressListener *progress = (GProgressListener*)data;
	NS_RELEASE (progress);
}


NS_METHOD GProgressListener::PrivateInit (void)
{
	nsresult rv;

	/* setup this download */
	mCanPause            = PR_FALSE;
	mIsPaused            = PR_FALSE;
	mLastUpdate          = PR_Now ();

	guint flags = EMBED_PERSIST_ADD_TO_RECENT | EMBED_PERSIST_SHOW_PROGRESS;
        if (mGaleonPersist)
        {
                g_object_get (mGaleonPersist, "flags", &flags, NULL);
        }

	mAddToRecent = flags & EMBED_PERSIST_ADD_TO_RECENT;
 
        if (flags & EMBED_PERSIST_SHOW_PROGRESS)
	{
		GulString dest;
		GulCString source;

		rv = mFile->GetPath (dest);

		rv = mUri->GetSpec (source);

		DownloaderView *dv;
		dv = galeon_embed_shell_get_downloader_view (embed_shell);
		mDownload = downloader_view_add_download (dv, source.get(),
							  GulCString (dest).get());
		g_signal_connect (G_OBJECT (mDownload), "cancel",
				  G_CALLBACK (download_cancel_cb), this);
		g_signal_connect (G_OBJECT (mDownload), "pause",
				  G_CALLBACK (download_pause_cb), this);
		g_signal_connect (G_OBJECT (mDownload), "resume",
				  G_CALLBACK (download_resume_cb), this);
		g_object_add_weak_pointer (G_OBJECT (mDownload), (void **) &mDownload);

		/* Ensure that we stay around while the download is alive,
		 * bug 144067 */
		NS_ADDREF (this);
		g_object_weak_ref (G_OBJECT (mDownload), download_weak_ref_cb,
				   this);
	}

	/* done */
	return NS_OK;
}

NS_IMETHODIMP GProgressListener::Init(nsIURI *aSource,
				      nsIURI *aTarget,
				      const nsAString &aDisplayName,
				      nsIMIMEInfo *aMIMEInfo,
                                      PRInt64 aStartTime,
				      nsILocalFile *aTempFile,
				      nsICancelable *aCancelable)
{
        mUri = aSource;
        mStartTime = aStartTime;
	mCancelable = aCancelable;

	mTarget = aTarget;
	nsCOMPtr<nsIFileURL> tFileUrl = do_QueryInterface(mTarget);
	if (tFileUrl)
	{
        	nsCOMPtr<nsIFile> tFileRef;
        	tFileUrl->GetFile(getter_AddRefs(tFileRef));
		tFileRef->Clone(getter_AddRefs(mFile));
	}

	if (aMIMEInfo)
	{
#ifdef HAVE_NSHANDLERINFOACTION
		nsHandlerInfoAction action;
#else
		nsMIMEInfoHandleAction action;
#endif
		if (NS_SUCCEEDED(aMIMEInfo->GetPreferredAction(&action)))
		{
			if (action == nsIMIMEInfo::useHelperApp)
			{
				mMIMEInfo = aMIMEInfo;
			}

			/* HACK, stop mozilla from opening the application, we
			 * do it ourselves */
			aMIMEInfo->SetPreferredAction(nsIMIMEInfo::saveToDisk);
		}
	}

        return PrivateInit();
}

static void LaunchHandler (GnomeVFSMimeApplication *aHandler, nsIFile *aFile,
			   guint32 user_time)
{
	nsCOMPtr<nsIExternalHelperAppService> helperService =
		do_GetService (NS_EXTERNALHELPERAPPSERVICE_CONTRACTID);

	nsCOMPtr<nsPIExternalAppLauncher> appLauncher =
		do_QueryInterface (helperService);
	if (appLauncher)
	{
		appLauncher->DeleteTemporaryFileOnExit(aFile);
	}

	GulString filename;
	aFile->GetPath(filename);
	
	/* FIXME: check return value */
	gul_general_launch_application (aHandler, GulCString(filename).get(), user_time);
}

/*
 * void onStateChange (in nsIWebProgress aWebProgress, 
 *                     in nsIRequest aRequest, 
 *		       in long aStateFlags, 
 *		       in unsigned long aStatus);
 */
NS_IMETHODIMP GProgressListener::OnStateChange (nsIWebProgress *aWebProgress,
						 nsIRequest *aRequest,
						 PRUint32 aStateFlags,
						 PRUint32 aStatus)
{
	if (aStateFlags & nsIWebProgressListener::STATE_START &&
	    aStateFlags & nsIWebProgressListener::STATE_IS_REQUEST)
	{
		// HTTP is special as the download as a byte stream can
		// complete successfully, but what you get instead of the
		// desired file is a 404 error document (or whatever depending
		// on the error.)
		//
		// Only relevant when coming from mozilla-embed-persist.cpp
		nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(aRequest);
		if (http)
		{
			PRBool succeeded = PR_TRUE;
			http->GetRequestSucceeded(&succeeded);
			if (!succeeded)
			{
				Abort ();
				return NS_OK;
			}
		}
	}

	if ((aRequest != mRequest) && !(aStateFlags & nsIWebProgressListener::STATE_STOP))
	{
		SetRequest (aRequest);
	}

	if (aStateFlags & nsIWebProgressListener::STATE_STOP)
	{
		// We need to detach from the nsIWebBrowserPersist or it'll
                // keep us around forever.  Detaching would kill us instantly
                // so kungfu is needed to survive just long enough to do the
                // final clean up.
                nsCOMPtr<nsITransfer> kungFuDeathGrip(this);
		mCancelable = nsnull;

		if (NS_SUCCEEDED(aStatus))
		{
			if (mAddToRecent)
			{
				EggRecentModel *model;

				model = egg_recent_model_new (EGG_RECENT_MODEL_SORT_NONE);

				GulString dest;
				mFile->GetPath (dest);

				EggRecentItem *item;
			       
				if (mContentType.IsEmpty() || 
				    mContentType.EqualsAsciiIgnoreCase("application/octet-stream"))
				{
					item = egg_recent_item_new_from_uri (GulCString(dest).get());
				}
				else
				{
					item = egg_recent_item_new ();
					egg_recent_item_set_uri (item, GulCString(dest).get());
					egg_recent_item_set_mime_type (item, mContentType.get());
				}

				// keep in sync with PrintProgressListener.cpp
				egg_recent_item_add_group (item, "Galeon");
				egg_recent_item_add_group (item, "Web Browser");

				egg_recent_model_add_full (model, item);
				egg_recent_item_unref (item);

				g_object_unref (model);
			}

			if (mDownload)
			{
				g_object_remove_weak_pointer (G_OBJECT(mDownload), (void **) &mDownload);
				download_completed (mDownload);
			}

			if (G_IS_OBJECT(mGaleonPersist))
			{
				GnomeVFSMimeApplication *handler = NULL;
				guint32 user_time;
				g_object_get (mGaleonPersist,
			      		      "handler", &handler,
					      "user_time", &user_time,
			      		      NULL);
				if (handler)
				{
					LaunchHandler (handler, mFile, user_time);
				}

				g_signal_emit_by_name (mGaleonPersist, "completed");
				g_object_unref (mGaleonPersist);
			}
			else if (mMIMEInfo)
			{
				LaunchHelperApp();
			}
		}
		else
		{
			if (mDownload)
			{
				g_object_remove_weak_pointer (G_OBJECT(mDownload), (void **) &mDownload);
				download_cancelled (mDownload);
			}

			if (mGaleonPersist)
			{
				g_signal_emit_by_name (mGaleonPersist, "cancelled", NULL);
				g_object_unref (mGaleonPersist);
			}
		}

		mDownload = NULL;
		mGaleonPersist = NULL;
	}

	/* done */
	return NS_OK;
}

/*
 * void onProgressChange (in nsIWebProgress aWebProgress, 
 *                        in nsIRequest aRequest, 
 *                        in long aCurSelfProgress, 
 *                        in long aMaxSelfProgress, 
 *                        in long aCurTotalProgress, 
 *                        in long aMaxTotalProgress); 
 */
NS_IMETHODIMP GProgressListener::
			OnProgressChange (nsIWebProgress *aWebProgress,
					  nsIRequest *aRequest,
					  PRInt32 aCurSelfProgress,
					  PRInt32 aMaxSelfProgress,
					  PRInt32 aCurTotalProgress,
					  PRInt32 aMaxTotalProgress)
{
	return OnProgressChange64 (aWebProgress, aRequest, aCurSelfProgress,
				   aMaxSelfProgress, aCurTotalProgress,
				   aMaxTotalProgress);
}

/*
 * void onProgressChange64 (in nsIWebProgress aWebProgress, 
 *                          in nsIRequest aRequest, 
 *                          in long long aCurSelfProgress, 
 *                          in long long aMaxSelfProgress, 
 *                          in long long aCurTotalProgress, 
 *                          in long long aMaxTotalProgress); 
 */
NS_IMETHODIMP GProgressListener::
			OnProgressChange64 (nsIWebProgress *aWebProgress,
					    nsIRequest *aRequest,
					    PRInt64 aCurSelfProgress,
					    PRInt64 aMaxSelfProgress,
					    PRInt64 aCurTotalProgress,
					    PRInt64 aMaxTotalProgress)
{
	// no point in calculating progress if there's no one watching
	if (!mDownload) return NS_OK;

	if (aRequest != mRequest)
	{
		// FIXME when Mozilla permits
		//
		// http://bugzilla.mozilla.org/show_bug.cgi?id=152224
		//
		// When used via GContentHandler we never get OnStateChange
		// with STATE_START.  As a workaround grab the nsIRequest here
		// as well.  To be removed when sanity is found.

		SetRequest (aRequest);
	}

	/* FIXME maxsize check here */

	if (aCurTotalProgress == -1)
	{
		// This seems to be a special case which we get if the file has
		// already been completely downloaded by the time we get to
		// show the progress dialog.  (Download begins when we click on
		// a link, then the save/open dialog pops up, then we get to
		// pick a file name, and so on...)
		//
		// So lacking other reliable information, let's try the file
		// size. Now that mozilla has clarified the api regarding large
		// (over 32bit size) files, there's no need for a joke here. :-)
		PRInt64 fileSize;
		if (NS_SUCCEEDED(mFile->GetFileSize(&fileSize)))
		{
			mContentLength    = fileSize;
			aCurTotalProgress = fileSize;
			aMaxTotalProgress = fileSize;
		}
	}
	else if (aMaxTotalProgress == -1 && mContentLength >= 0)
	{
		aMaxTotalProgress = mContentLength;
	}

	PRInt64 now = PR_Now ();

	/* get out if we're updating too quickly, but don't miss EOF */
	if (aCurTotalProgress != aMaxTotalProgress)
	{
		PRInt64 interval = (aMaxTotalProgress == -1) ? kUnknownSizeInterval : kInterval;
		if ((now - mLastUpdate) < interval)
		{
			return NS_OK;
		}
	}

	/* compute elapsed time */
	mLastUpdate = now;

	guint elapsed = (now - mStartTime) / PR_USEC_PER_SEC;

	/* compute download rate */
	guint64 speed = 0;
	if (elapsed > 0)
	{
		speed = aCurTotalProgress / elapsed;
	}

	/* compute time remaining */
	guint remaining = G_MAXUINT;
	if (speed > 0 && aMaxTotalProgress >= 0)
	{
		remaining = (aMaxTotalProgress - aCurTotalProgress) / speed;
	}

	download_set_progress (mDownload,
			       elapsed,
			       remaining,
			       speed,
			       aCurTotalProgress,
			       aMaxTotalProgress < 0 ? G_MAXUINT64 : aMaxTotalProgress);

	/* done */
	return NS_OK;
}

/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
NS_IMETHODIMP GProgressListener::
			OnLocationChange(nsIWebProgress *aWebProgress,
					 nsIRequest *aRequest, nsIURI *location)
{
    return NS_OK;
}

/* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
NS_IMETHODIMP GProgressListener::
			OnStatusChange(nsIWebProgress *aWebProgress,
				       nsIRequest *aRequest, nsresult aStatus,
				       const PRUnichar *aMessage)
{
    return NS_OK;
}

/* void onSecurityChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long state); */
NS_IMETHODIMP GProgressListener::
			OnSecurityChange(nsIWebProgress *aWebProgress,
					 nsIRequest *aRequest,
					 PRUint32 state)
{
    return NS_OK;
}

#ifdef HAVE_NSIWEBPROGRESSLISTENER2_ONREFRESHATTEMPTED
/* boolean onRefreshAttempted (in nsIWebProgress aWebProgress, in nsIURI aRefreshURI, in long aMillis, in boolean aSameURI); */
NS_IMETHODIMP GProgressListener::
			OnRefreshAttempted(nsIWebProgress *aWebProgress,
					   nsIURI *aRefreshURI, PRInt32 aMillis,
					   PRBool aSameURI, PRBool *_retval)
{
    *_retval = PR_TRUE;
    return NS_OK;
}
#endif

//---------------------------------------------------------------------------
NS_METHOD GProgressListener::SetRequest (nsIRequest *aRequest)
{
	mRequest = aRequest;

	nsCOMPtr<nsIChannel> channel = do_QueryInterface (mRequest);
	if (channel)
	{
		PRInt32 length;
		if (NS_SUCCEEDED(channel->GetContentLength(&length)) && length >= 0)
		{
			mContentLength = length;
			if (mDownload)
			{
				// Update the download with known content
				// length.  OnProgressChange might never be
				// called with aMaxTotalProgress reflecting the
				// full length, leaving the download "too short"
				download_set_size_total (mDownload, mContentLength);
			}
		}

		if (mContentType.IsEmpty())
		{
			GulCString type;
			if (NS_SUCCEEDED(channel->GetContentType(type)))
			{
				mContentType = type;
			}
		}
	}

	nsCOMPtr<nsIFTPChannel> ftp = do_QueryInterface(aRequest);
	mCanPause = ftp ? PR_TRUE : PR_FALSE;
	if (mDownload)
	{
		download_set_can_pause (mDownload, mCanPause);
	}

	return NS_OK;
}

NS_METHOD GProgressListener::LaunchHelperApp (void)
{
	if (!mMIMEInfo)
		return NS_ERROR_FAILURE;

	nsresult rv;

	GulCString cFileName;
	rv = mFile->GetNativePath(cFileName);
	if(NS_FAILED(rv)) return NS_ERROR_FAILURE;

	GulString helperDesc;
	rv = mMIMEInfo->GetDescription(helperDesc);
	if(NS_FAILED(rv)) return NS_ERROR_FAILURE;

	// XXX information passing kludge (from ContentHandler)
	// TODO: should probably use some prefix, like 'gnomevfs:'
	GulCString helperId(helperDesc);

	// Format <usertime>:<helperapp id>
	char *colon = strchr (helperId.get(), ':');
	g_return_val_if_fail (colon, NS_ERROR_FAILURE);

	const char *helperappid = colon+1;

	guint32 usertime = strtoul (helperId.get(), &colon, 0);
	
	GnomeVFSMimeApplication *helper = 
#ifdef HAVE_NEW_GNOME_VFS_MIME_API
		gnome_vfs_mime_application_new_from_desktop_id (helperappid);
#else
		gnome_vfs_mime_application_new_from_id (helperappid);
#endif

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

	/* FIXME: check return value */
	gul_general_launch_application (helper, cFileName.get(), usertime);
	gnome_vfs_mime_application_free (helper);

	return NS_OK;
}

nsresult GProgressListener::Pause (void)
{
	NS_ENSURE_TRUE(mCanPause && !mIsPaused, NS_ERROR_FAILURE);

        nsresult rv = mRequest->Suspend ();
	if (NS_FAILED(rv))
	{
		mCanPause = PR_FALSE;
		download_set_can_pause (mDownload, FALSE);
		return rv;
	}

	mIsPaused = PR_TRUE;
	download_paused (mDownload);
	return NS_OK;
}

nsresult GProgressListener::Resume (void)
{
	NS_ENSURE_TRUE(mCanPause && mIsPaused, NS_ERROR_FAILURE);

        nsresult rv = mRequest->Resume ();
	NS_ENSURE_SUCCESS(rv, rv);

	mIsPaused = PR_FALSE;
	download_resumed (mDownload);
        return NS_OK;
}

nsresult GProgressListener::Abort (void)
{
	// Keep ourselves alive
	nsCOMPtr<nsITransfer> kungFuDeathGrip(this);

	// Suspended request doesn't seem to reach cancelled state until it's
	// resumed.  Better resume it first so that we get the right away.
        if (mIsPaused)
        {
                mRequest->Resume ();
        }

	if (mCancelable)
	{
		nsresult rv;
		rv =  mCancelable->Cancel(NS_BINDING_ABORTED);

		nsCOMPtr<nsIWebBrowserPersist> persist;
		persist = do_QueryInterface(mCancelable);
		if (persist) {
		   return rv;
		}
	}

	// Working assumption is that if mPersist is set CancelSave correctly
	// emits proper events to OnStateChange.  At the time of writing that
	// seems to be the case; mPersist is set only when the download is
	// initiated from mozilla-embed-persist.cpp
	//
	// This part is reached only if the download was initiated via
	// GContentHandler


	// FIXME remove workaround when Mozilla permits
	//
	// http://bugzilla.mozilla.org/show_bug.cgi?id=152224
	//
	// Mozilla isn't calling OnStateChange with STATE_STOP when the
	// download is cancelled, so we need to simulate it or mDownload and
	// mGaleonPersist "listeners" are left unaware of the cancellation.

	OnStateChange (nsnull, mRequest, nsIWebProgressListener::STATE_STOP, NS_BINDING_ABORTED);

	// XXX memory leak courtesy of Mozilla
	//
	// http://bugzilla.mozilla.org/show_bug.cgi?id=152224
	//
	// Mozilla is holding us hostage until someone calls
	// nsIHelperAppLauncher::CloseProgressWindow -- no one ever does.
	//
	// We could do 'delete this;' right here and plug the memory leak.
	// We'd still be leaking if the download is finished successfully.
	// We'd also crash and burn once Mozilla gets fixed.

	return NS_OK;
}

nsresult 
InitiateMozillaDownload (nsIURI *sourceURI, nsILocalFile* inDestFile,
			 GaleonEmbedPersist *embedPersist,
			 nsIDOMDocument *domDocument, 
			 nsISupports *cacheKey,
			 nsIInputStream *postData,
			 PRBool decode,
			 nsIURI *displayURI)
{
	nsresult rv = NS_OK;

	EmbedPersistFlags flags;
	flags = galeon_embed_persist_get_flags (GALEON_EMBED_PERSIST (embedPersist));

	nsCOMPtr<nsIWebBrowserPersist> webPersist = 
		do_CreateInstance(NS_WEBBROWSERPERSIST_CONTRACTID, &rv);
	NS_ENSURE_SUCCESS (rv, rv);
  
	GProgressListener *listener = new GProgressListener ();
	rv = listener->InitForPersist (webPersist, displayURI, inDestFile, embedPersist);
	NS_ENSURE_SUCCESS (rv, rv);

	rv = webPersist->SetProgressListener (listener);
	NS_ENSURE_SUCCESS (rv, rv);

	PRInt32 persist_flags = nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES;
	if (!domDocument && !decode)
	{
		persist_flags |= nsIWebBrowserPersist::PERSIST_FLAGS_NO_CONVERSION;
	}

	if (flags & EMBED_PERSIST_BYPASSCACHE)
	{
		persist_flags |= nsIWebBrowserPersist::PERSIST_FLAGS_BYPASS_CACHE;
	}
	else
	{
		persist_flags |= nsIWebBrowserPersist::PERSIST_FLAGS_FROM_CACHE;
	}

	webPersist->SetPersistFlags(persist_flags);

	if (!domDocument)
	{
		/* TODO, fix this null referrer */
		rv = webPersist->SaveURI (sourceURI, cacheKey, nsnull,
					  postData, nsnull, inDestFile);
	}
	else
	{
		nsCOMPtr<nsILocalFile> filesFolder;
		if (flags & EMBED_PERSIST_SAVE_CONTENT)
		{
			/* Create a directory to hold the content, mozilla
			 * will create the directory as needed. */
			GulCString nativePath;
			inDestFile->GetNativePath(nativePath);
			
			nativePath.Append ("_content");

			NS_NewNativeLocalFile(nativePath, PR_TRUE, getter_AddRefs(filesFolder));
		}

		rv = webPersist->SaveDocument (domDocument, inDestFile, filesFolder,
					       nsnull, 0, 0);
	}
  
	return rv;
}

/**
 * Builds the download filename into the default download directory,
 *
 * returns NS_ERROR_FAILURE if the filename couldn't be generated
 */
nsresult
BuildDownloadPath (const char *defaultFileName, GtkWidget *parent,
		   nsILocalFile **_retval)
{
	gchar * dirName = eel_gconf_get_string (CONF_DOWNLOADING_DIR);
	if (dirName)
	{
		char *tmp = g_filename_from_utf8 (dirName, -1, NULL, NULL, NULL);
		g_free (dirName);
		dirName = tmp;
	}

	if (dirName)
	{
		char *tmp = gnome_vfs_expand_initial_tilde (dirName);
		g_free (dirName);
		dirName = tmp;
	}

	if (!dirName || dirName[0] == '\0' || 
	    !g_file_test (dirName, G_FILE_TEST_IS_DIR))
	{
		g_free (dirName);
		dirName = g_strdup (g_get_home_dir ());
	}


	char *filename = g_build_filename (dirName, defaultFileName, NULL);
	g_free (dirName);

	if (gul_gui_confirm_overwrite_file (parent, filename))
	{
		nsCOMPtr <nsILocalFile> saveFile;
		NS_NewNativeLocalFile (GulDependentCString (filename),
				       PR_TRUE,
				       getter_AddRefs(saveFile));
			
		NS_ADDREF (*_retval = saveFile);

		g_free (filename);
		return NS_OK;
	}
	g_free (filename);

	return NS_ERROR_FAILURE;
}