]> git.decadent.org.uk Git - videolink.git/blob - videolink.cpp
Removed support for Mozilla 1.7.
[videolink.git] / videolink.cpp
1 // Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <cassert>
5 #include <cstring>
6 #include <exception>
7 #include <fstream>
8 #include <iomanip>
9 #include <iostream>
10 #include <memory>
11 #include <queue>
12 #include <set>
13 #include <sstream>
14 #include <string>
15
16 #include <stdlib.h>
17
18 #include <gdkmm/pixbuf.h>
19 #include <glibmm/convert.h>
20 #include <glibmm/spawn.h>
21 #include <gtkmm/main.h>
22 #include <gtkmm/window.h>
23
24 #include <imglib2/ImageErrors.h>
25 #include <nsGUIEvent.h>
26 #include <nsIBoxObject.h>
27 #include <nsIContent.h>
28 #include <nsIDocShell.h>
29 #include <nsIDOMAbstractView.h>
30 #include <nsIDOMBarProp.h>
31 #include <nsIDOMDocumentEvent.h>
32 #include <nsIDOMDocumentView.h>
33 #include <nsIDOMElement.h>
34 #include <nsIDOMEventTarget.h>
35 #include <nsIDOMHTMLDocument.h>
36 #include <nsIDOMMouseEvent.h>
37 #include <nsIDOMNSDocument.h>
38 #include <nsIDOMWindow.h>
39 #include <nsIEventStateManager.h>
40 #include <nsIInterfaceRequestorUtils.h>
41 #include <nsIURI.h> // required before nsILink.h
42 #include <nsILink.h>
43 #include <nsIPrefBranch.h>
44 #include <nsPresContext.h>
45 #include <nsIPrefService.h>
46 #include <nsIPresShell.h>
47 #include <nsServiceManagerUtils.h>
48 #include <nsIWebBrowser.h>
49 #include <nsString.h>
50
51 #include "browser_widget.hpp"
52 #include "child_iterator.hpp"
53 #include "dvd.hpp"
54 #include "generate_dvd.hpp"
55 #include "geometry.hpp"
56 #include "link_iterator.hpp"
57 #include "null_prompt_service.hpp"
58 #include "pixbufs.hpp"
59 #include "style_sheets.hpp"
60 #include "temp_file.hpp"
61 #include "video.hpp"
62 #include "warp_pointer.hpp"
63 #include "x_frame_buffer.hpp"
64 #include "xml_utils.hpp"
65 #include "xpcom_support.hpp"
66
67 using xpcom_support::check;
68
69 namespace
70 {
71     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
72                             nsIDOMElement * elem)
73     {
74         rectangle result;
75
76         // Start with this element's bounding box
77         nsCOMPtr<nsIBoxObject> box;
78         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
79         int width, height;
80         check(box->GetScreenX(&result.left));
81         check(box->GetScreenY(&result.top));
82         check(box->GetWidth(&width));
83         check(box->GetHeight(&height));
84         result.right = result.left + width;
85         result.bottom = result.top + height;
86
87         // Merge bounding boxes of all child elements
88         for (child_iterator it = child_iterator(elem), end; it != end; ++it)
89         {
90             nsCOMPtr<nsIDOMNode> child_node(*it);
91             PRUint16 child_type;
92             if (check(child_node->GetNodeType(&child_type)),
93                 child_type == nsIDOMNode::ELEMENT_NODE)
94             {
95                 nsCOMPtr<nsIDOMElement> child_elem(
96                     do_QueryInterface(child_node));
97                 result |= get_elem_rect(ns_doc, child_elem);
98             }
99         }
100
101         return result;
102     }
103
104
105     enum video_format
106     {
107         video_format_none,
108         video_format_mpeg2_ps,
109         video_format_vob_list
110     };
111
112     video_format video_format_from_uri(const std::string & uri)
113     {
114         // FIXME: This is a bit of a hack.  Perhaps we could decide
115         // later based on the MIME type determined by Mozilla?
116         static struct {
117             const char * extension;
118             video_format format;
119         } const mapping[] = {
120             {".vob",     video_format_mpeg2_ps},
121             {".mpeg",    video_format_mpeg2_ps},
122             {".mpeg2",   video_format_mpeg2_ps},
123             {".voblist", video_format_vob_list}
124         };
125         for (std::size_t i = 0;
126              i != sizeof(mapping) / sizeof(mapping[0]);
127              ++i)
128         {
129             std::size_t ext_len = std::strlen(mapping[i].extension);
130             if (uri.size() > ext_len
131                 && uri.compare(uri.size() - ext_len, ext_len,
132                                mapping[i].extension) == 0)
133                 return mapping[i].format;
134         }
135         return video_format_none;
136     }
137
138     
139     class videolink_window : public Gtk::Window
140     {
141     public:
142         videolink_window(
143             const video::frame_params & frame_params,
144             const std::string & main_page_uri,
145             const std::string & output_dir,
146             dvd_generator::mpeg_encoder encoder);
147
148         bool is_finished() const;
149
150     private:
151         struct page_state;
152
153         dvd_generator::pgc_ref add_menu(const std::string & uri);
154         dvd_generator::pgc_ref add_title(const std::string & uri,
155                                          video_format format);
156         void load_next_page();
157         bool on_idle();
158         void on_net_state_change(const char * uri, gint flags, guint status);
159         bool browser_is_busy() const
160             {
161                 return pending_window_update_ || pending_req_count_;
162             }
163         // Do as much processing as possible.  Return a flag indicating
164         // whether to call again once the browser is idle.
165         bool process();
166         // Return a Pixbuf containing a copy of the window contents.
167         Glib::RefPtr<Gdk::Pixbuf> get_screenshot();
168         // Do as much processing as possible on the page links.  Return
169         // a flag indicating whether to call again once the browser is
170         // idle.
171         bool process_links(
172             page_state * state,
173             nsIDOMDocument * basic_doc,
174             nsIPresShell * pres_shell,
175             nsPresContext * pres_context,
176             nsIDOMWindow * dom_window);
177
178         video::frame_params frame_params_;
179         std::string output_dir_;
180         browser_widget browser_widget_;
181
182         dvd_generator generator_;
183         typedef std::map<std::string, dvd_generator::pgc_ref>
184             resource_map_type;
185         resource_map_type resource_map_;
186
187         std::queue<std::string> page_queue_;
188         bool pending_window_update_;
189         int pending_req_count_;
190         bool have_tweaked_page_;
191         std::auto_ptr<page_state> page_state_;
192
193         bool finished_;
194     };
195
196     videolink_window::videolink_window(
197         const video::frame_params & frame_params,
198         const std::string & main_page_uri,
199         const std::string & output_dir,
200         dvd_generator::mpeg_encoder encoder)
201             : frame_params_(frame_params),
202               output_dir_(output_dir),
203               generator_(frame_params, encoder),
204               pending_window_update_(false),
205               pending_req_count_(0),
206               have_tweaked_page_(false),
207               finished_(false)
208     {
209         set_size_request(frame_params_.width, frame_params_.height);
210         set_resizable(false);
211
212         add(browser_widget_);
213         browser_widget_.show();
214         Glib::signal_idle().connect(
215             SigC::slot(*this, &videolink_window::on_idle));
216         browser_widget_.signal_net_state().connect(
217             SigC::slot(*this, &videolink_window::on_net_state_change));
218
219         add_menu(main_page_uri);
220     }
221
222     bool videolink_window::is_finished() const
223     {
224         return finished_;
225     }
226
227     dvd_generator::pgc_ref videolink_window::add_menu(const std::string & uri)
228     {
229         dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
230         if (pgc_ref.type == dvd_generator::unknown_pgc)
231         {
232             pgc_ref = generator_.add_menu();
233             page_queue_.push(uri);
234         }
235         return pgc_ref;
236     }
237
238     dvd_generator::pgc_ref videolink_window::add_title(const std::string & uri,
239                                                       video_format format)
240     {
241         dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
242
243         if (pgc_ref.type == dvd_generator::unknown_pgc)
244         {
245             Glib::ustring hostname;
246             std::string path(Glib::filename_from_uri(uri, hostname));
247             // FIXME: Should check the hostname
248
249             vob_list list;
250
251             // Store a reference to a linked VOB file, or the contents
252             // of a linked VOB list file.
253             if (format == video_format_mpeg2_ps)
254             {
255                 if (!Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR))
256                     throw std::runtime_error(
257                         path + " is missing or not a regular file");
258                 vob_ref ref;
259                 ref.file = path;
260                 list.push_back(ref);
261             }
262             else if (format == video_format_vob_list)
263             {
264                 read_vob_list(path).swap(list);
265             }
266             else
267             {
268                 assert(!"unrecognised format in add_title");
269             }
270
271             pgc_ref = generator_.add_title(list);
272         }
273
274         return pgc_ref;
275     }
276
277     void videolink_window::load_next_page()
278     {
279         assert(!page_queue_.empty());
280         const std::string & uri = page_queue_.front();
281         std::cout << "loading " << uri << std::endl;
282
283         browser_widget_.load_uri(uri);
284     }
285
286     bool videolink_window::on_idle()
287     {
288         if (!output_dir_.empty())
289         {
290             // Put pointer in the top-left so that no links appear in
291             // the hover state when we take a screenshot.
292             warp_pointer(get_window(),
293                          -frame_params_.width, -frame_params_.height);
294         }
295         
296         load_next_page();
297         return false; // don't call again thankyou
298     }
299
300     void videolink_window::on_net_state_change(const char * uri,
301                                            gint flags, guint status)
302     {
303 #       ifdef DEBUG_ON_NET_STATE_CHANGE
304         std::cout << "videolink_window::on_net_state_change(";
305         if (uri)
306             std::cout << '"' << uri << '"';
307         else
308             std::cout << "NULL";
309         std::cout << ", ";
310         {
311             gint flags_left = flags;
312             static const struct {
313                 gint value;
314                 const char * name;
315             } flag_names[] = {
316                 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
317                 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
318                 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
319                 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
320                 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
321                 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
322                 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
323                 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
324                 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
325             };
326             for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
327             {
328                 if (flags & flag_names[i].value)
329                 {
330                     std::cout << flag_names[i].name;
331                     flags_left -= flag_names[i].value;
332                     if (flags_left)
333                         std::cout << " | ";
334                 }
335             }
336             if (flags_left)
337                 std::cout << "0x" << std::setbase(16) << flags_left;
338         }
339         std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
340 #       endif // DEBUG_ON_NET_STATE_CHANGE
341
342         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
343         {
344             if (flags & GTK_MOZ_EMBED_FLAG_START)
345                 ++pending_req_count_;
346
347             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
348             {
349                 assert(pending_req_count_ != 0);
350                 --pending_req_count_;
351             }
352         }
353             
354         if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
355             && flags & GTK_MOZ_EMBED_FLAG_START)
356         {
357             pending_window_update_ = true;
358             have_tweaked_page_ = false;
359         }
360
361         if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
362             && flags & GTK_MOZ_EMBED_FLAG_STOP)
363         {
364             // Check whether the load was successful, ignoring this
365             // pseudo-error.
366             if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
367                 check(status);
368
369             pending_window_update_ = false;
370         }
371
372         if (!browser_is_busy())
373         {
374             try
375             {
376                 if (!process())
377                 {
378                     finished_ = true;
379                     Gtk::Main::quit();
380                 }
381             }
382             catch (std::exception & e)
383             {
384                 std::cerr << "Fatal error";
385                 if (!page_queue_.empty())
386                     std::cerr << " while processing <" << page_queue_.front()
387                               << ">";
388                 std::cerr << ": " << e.what() << "\n";
389                 Gtk::Main::quit();
390             }
391             catch (Glib::Exception & e)
392             {
393                 std::cerr << "Fatal error";
394                 if (!page_queue_.empty())
395                     std::cerr << " while processing <" << page_queue_.front()
396                               << ">";
397                 std::cerr << ": " << e.what() << "\n";
398                 Gtk::Main::quit();
399             }
400         }
401     }
402
403     struct videolink_window::page_state
404     {
405         page_state(Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf,
406                    nsIDOMDocument * doc, int width, int height)
407                 : norm_pixbuf(norm_pixbuf),
408                   diff_pixbuf(Gdk::Pixbuf::create(
409                                   Gdk::COLORSPACE_RGB,
410                                   true, 8, // has_alpha, bits_per_sample
411                                   width, height)),
412                   links_it(doc),
413                   link_changing(false)
414             {
415             }
416
417         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
418         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
419
420         link_iterator links_it, links_end;
421
422         rectangle link_rect;
423         bool link_changing;
424     };
425
426     bool videolink_window::process()
427     {
428         assert(!page_queue_.empty());
429
430         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
431         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
432         assert(doc_shell);
433         nsCOMPtr<nsIPresShell> pres_shell;
434         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
435         nsCOMPtr<nsPresContext> pres_context;
436         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
437         nsCOMPtr<nsIDOMWindow> dom_window;
438         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
439
440         // If we haven't done so already, disable scrollbars.
441         if (!have_tweaked_page_)
442         {
443             // This actually only needs to be done once.
444             nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
445             check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
446             check(dom_bar_prop->SetVisible(false));
447
448             have_tweaked_page_ = true;
449
450             // Might need to wait a while for things to load or more
451             // likely for a re-layout.
452             if (browser_is_busy())
453                 return true;
454         }
455
456         // All further work should only be done if we're not in preview mode.
457         if (!output_dir_.empty())
458         {
459             nsCOMPtr<nsIDOMDocument> basic_doc;
460             check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
461
462             // Start or continue processing links.
463             std::auto_ptr<page_state> state(page_state_);
464             if (!state.get())
465                 state.reset(
466                     new page_state(
467                         get_screenshot(),
468                         basic_doc, frame_params_.width, frame_params_.height));
469             if (process_links(
470                     state.get(),
471                     basic_doc, pres_shell, pres_context, dom_window))
472             {
473                 // Save iteration state for later.
474                 page_state_ = state;
475             }
476             else
477             {
478                 // We've finished work on the links so generate the
479                 // menu VOB.
480                 quantise_rgba_pixbuf(state->diff_pixbuf,
481                                      dvd::button_n_colours);
482                 generator_.generate_menu_vob(
483                     resource_map_[page_queue_.front()].index,
484                     state->norm_pixbuf, state->diff_pixbuf);
485
486                 // Move on to the next page, if any, or else generate
487                 // the DVD filesystem.
488                 page_queue_.pop();
489                 if (!page_queue_.empty())
490                 {
491                     load_next_page();
492                 }
493                 else
494                 {
495                     generator_.generate(output_dir_);
496                     return false;
497                 }
498             }
499         }
500
501         return true;
502     }
503
504     Glib::RefPtr<Gdk::Pixbuf> videolink_window::get_screenshot()
505     {
506         Glib::RefPtr<Gdk::Window> window(get_window());
507         assert(window);
508         window->process_updates(true);
509
510         return Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
511                                    window->get_colormap(),
512                                    0, 0, 0, 0,
513                                    frame_params_.width, frame_params_.height);
514     }
515
516     bool videolink_window::process_links(
517         page_state * state,
518         nsIDOMDocument * basic_doc,
519         nsIPresShell * pres_shell,
520         nsPresContext * pres_context,
521         nsIDOMWindow * dom_window)
522     {
523         Glib::RefPtr<Gdk::Window> window(get_window());
524         assert(window);
525
526         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
527         assert(ns_doc);
528         nsCOMPtr<nsIEventStateManager> event_state_man(
529             pres_context->EventStateManager()); // does not AddRef
530         assert(event_state_man);
531         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
532             do_QueryInterface(basic_doc));
533         assert(event_factory);
534         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
535         assert(doc_view);
536         nsCOMPtr<nsIDOMAbstractView> view;
537         check(doc_view->GetDefaultView(getter_AddRefs(view)));
538
539         rectangle window_rect = {
540             0, 0, frame_params_.width, frame_params_.height
541         };
542
543         unsigned menu_index = resource_map_[page_queue_.front()].index;
544
545         for (/* no initialisation */;
546              state->links_it != state->links_end;
547              ++state->links_it)
548         {
549             nsCOMPtr<nsIDOMNode> node(*state->links_it);
550
551             // Find the link URI and separate any fragment from it.
552             nsCOMPtr<nsILink> link(do_QueryInterface(node));
553             assert(link);
554             nsCOMPtr<nsIURI> uri_iface;
555             check(link->GetHrefURI(getter_AddRefs(uri_iface)));
556             std::string uri_and_fragment, uri, fragment;
557             {
558                 nsCString uri_and_fragment_ns;
559                 check(uri_iface->GetSpec(uri_and_fragment_ns));
560                 uri_and_fragment.assign(uri_and_fragment_ns.BeginReading(),
561                                         uri_and_fragment_ns.EndReading());
562
563                 std::size_t hash_pos = uri_and_fragment.find('#');
564                 uri.assign(uri_and_fragment, 0, hash_pos);
565                 if (hash_pos != std::string::npos)
566                     fragment.assign(uri_and_fragment,
567                                     hash_pos + 1, std::string::npos);
568             }
569
570             // Is this a new link?
571             if (!state->link_changing)
572             {
573                 // Find a rectangle enclosing the link and clip it to the
574                 // window.
575                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
576                 assert(elem);
577                 state->link_rect = get_elem_rect(ns_doc, elem);
578                 state->link_rect &= window_rect;
579
580                 if (state->link_rect.empty())
581                 {
582                     std::cerr << "Ignoring invisible link to "
583                               << uri_and_fragment << "\n";
584                     continue;
585                 }
586
587                 // Check whether this is a link to a video or a page then
588                 // add it to the known resources if not already seen; then
589                 // add it to the menu entries.
590                 dvd_generator::pgc_ref target;
591                 video_format format = video_format_from_uri(uri);
592                 if (format != video_format_none)
593                 {
594                     PRBool is_file;
595                     check(uri_iface->SchemeIs("file", &is_file));
596                     if (!is_file)
597                     {
598                         std::cerr << "Links to video must use the file:"
599                                   << " scheme\n";
600                         continue;
601                     }
602                     target = add_title(uri, format);
603                     target.sub_index =
604                         std::strtoul(fragment.c_str(), NULL, 10);
605                 }
606                 else // video_format == video_format_none
607                 {
608                     target = add_menu(uri);
609                     // TODO: If there's a fragment, work out which button
610                     // is closest and set target.sub_index.
611                 }
612
613                 generator_.add_menu_entry(menu_index,
614                                           state->link_rect, target);
615
616                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
617                 assert(content);
618                 nsCOMPtr<nsIDOMEventTarget> event_target(
619                     do_QueryInterface(node));
620                 assert(event_target);
621
622                 nsCOMPtr<nsIDOMEvent> event;
623                 check(event_factory->CreateEvent(
624                           NS_ConvertASCIItoUTF16("MouseEvents"),
625                           getter_AddRefs(event)));
626                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
627                     do_QueryInterface(event));
628                 assert(mouse_event);
629                 check(mouse_event->InitMouseEvent(
630                           NS_ConvertASCIItoUTF16("mouseover"),
631                           true,  // can bubble
632                           true,  // cancelable
633                           view,
634                           0,     // detail: mouse click count
635                           state->link_rect.left, // screenX
636                           state->link_rect.top,  // screenY
637                           state->link_rect.left, // clientX
638                           state->link_rect.top,  // clientY
639                           false, false, false, false, // qualifiers
640                           0,     // button: left (or primary)
641                           0));   // related target
642                 PRBool dummy;
643                 check(event_target->DispatchEvent(mouse_event,
644                                                   &dummy));
645                 check(event_state_man->SetContentState(content,
646                                                        NS_EVENT_STATE_HOVER));
647
648                 pres_shell->FlushPendingNotifications(Flush_Display);
649
650                 // We may have to exit and wait for image loading
651                 // to complete, at which point we will be called
652                 // again.
653                 if (browser_is_busy())
654                 {
655                     state->link_changing = true;
656                     return true;
657                 }
658             }
659
660             window->process_updates(true);
661
662             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
663                 Gdk::Pixbuf::create(
664                     Glib::RefPtr<Gdk::Drawable>(window),
665                     window->get_colormap(),
666                     state->link_rect.left,
667                     state->link_rect.top,
668                     0,
669                     0,
670                     state->link_rect.right - state->link_rect.left,
671                     state->link_rect.bottom - state->link_rect.top));
672             diff_rgb_pixbufs(
673                 state->norm_pixbuf,
674                 changed_pixbuf,
675                 state->diff_pixbuf,
676                 state->link_rect.left,
677                 state->link_rect.top,
678                 state->link_rect.right - state->link_rect.left,
679                 state->link_rect.bottom - state->link_rect.top);
680         }
681
682         return false;
683     }
684
685     const video::frame_params & lookup_frame_params(const char * str)
686     {
687         assert(str);
688         static const char * const known_strings[] = {
689             "525",    "625",
690             "525/60", "625/50",
691             "NTSC",   "PAL",
692             "ntsc",   "pal"
693         };
694         for (std::size_t i = 0;
695              i != sizeof(known_strings)/sizeof(known_strings[0]);
696              ++i)
697             if (std::strcmp(str, known_strings[i]) == 0)
698                 return (i & 1)
699                     ? video::frame_params_625
700                     : video::frame_params_525;
701         throw std::runtime_error(
702             std::string("Invalid video standard: ").append(str));
703     }
704
705     void print_usage(std::ostream & stream, const char * command_name)
706     {
707         stream <<
708             "Usage: " << command_name << " [gtk-options] [--preview]\n"
709             "           [--video-std {525|525/60|NTSC|ntsc"
710             " | 625|625/50|PAL|pal}]\n"
711             "           [--encoder {mjpegtools|mjpegtools-old}]\n"
712             "           menu-url [output-dir]\n";
713     }
714     
715     void set_browser_preferences()
716     {
717         nsCOMPtr<nsIPrefService> pref_service;
718         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
719         check(CallGetService<nsIPrefService>(pref_service_cid,
720                                              getter_AddRefs(pref_service)));
721         nsCOMPtr<nsIPrefBranch> pref_branch;
722         check(pref_service->GetBranch("", getter_AddRefs(pref_branch)));
723
724         // Disable IE-compatibility kluge that causes backgrounds to
725         // sometimes/usually be missing from snapshots.  This is only
726         // effective from Mozilla 1.8 onward.
727         check(pref_branch->SetBoolPref(
728                   "layout.fire_onload_after_image_background_loads",
729                   true));
730
731         // Set display resolution.  With standard-definition video we
732         // will be fitting ~600 pixels across a screen typically
733         // ranging from 10 to 25 inches wide, for a resolution of
734         // 24-60 dpi.  I therefore declare the average horizontal
735         // resolution to be 40 dpi.  The vertical resolution will be
736         // slightly different but unfortunately Mozilla doesn't
737         // support non-square pixels (and neither do fontconfig or Xft
738         // anyway).
739
740         // The browser.display.screen_resolution preference sets the
741         // the nominal resolution for dimensions expressed in pixels.
742         // (They may be scaled!)  In Mozilla 1.7 it also sets the
743         // assumed resolution of the display - hence pixel sizes are
744         // respected on-screen - but this is no longer the case in
745         // 1.8.  Therefore it was renamed to layout.css.dpi in 1.8.1.
746         // In 1.8 we need to set the assumed screen resolution
747         // separately, but don't know how yet.  Setting one to 40
748         // but not the other is *bad*, so currently we set neither.
749
750 #       if 0
751             check(pref_branch->SetIntPref("browser.display.screen_resolution",
752                                           40));
753 #       endif
754     }
755
756 } // namespace
757
758 void fatal_error(const std::string & message)
759 {
760     std::cerr << "Fatal error: " << message << "\n";
761     Gtk::Main::quit();
762 }
763
764 int main(int argc, char ** argv)
765 {
766     try
767     {
768         video::frame_params frame_params = video::frame_params_625;
769         bool preview_mode = false;
770         std::string menu_url;
771         std::string output_dir;
772         dvd_generator::mpeg_encoder encoder =
773             dvd_generator::mpeg_encoder_ffmpeg;
774
775         // Do initial option parsing.  We have to do this before
776         // letting Gtk parse the arguments since we may need to spawn
777         // Xvfb first.
778         int argi = 1;
779         while (argi != argc)
780         {
781             if (std::strcmp(argv[argi], "--") == 0)
782             {
783                 break;
784             }
785             else if (std::strcmp(argv[argi], "--help") == 0)
786             {
787                 print_usage(std::cout, argv[0]);
788                 return EXIT_SUCCESS;
789             }
790             else if (std::strcmp(argv[argi], "--preview") == 0)
791             {
792                 preview_mode = true;
793                 argi += 1;
794             }
795             else if (std::strcmp(argv[argi], "--video-std") == 0)
796             {
797                 if (argi + 1 == argc)
798                 {
799                     std::cerr << "Missing argument to --video-std\n";
800                     print_usage(std::cerr, argv[0]);
801                     return EXIT_FAILURE;
802                 }
803                 frame_params = lookup_frame_params(argv[argi + 1]);
804                 argi += 2;
805             }
806             else
807             {
808                 argi += 1;
809             }
810         }
811
812         std::auto_ptr<x_frame_buffer> fb;
813         if (!preview_mode)
814         {
815             // Spawn Xvfb and set env variables so that Xlib will use it
816             // Use 8 bits each for RGB components, which should translate into
817             // "enough" bits for YUV components.
818             fb.reset(new x_frame_buffer(frame_params.width,
819                                         frame_params.height,
820                                         3 * 8));
821             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
822             setenv("DISPLAY", fb->get_display().c_str(), true);
823         }
824
825         // Initialise Gtk
826         Gtk::Main kit(argc, argv);
827
828         // Complete option parsing with Gtk's options out of the way.
829         argi = 1;
830         while (argi != argc)
831         {
832             if (std::strcmp(argv[argi], "--") == 0)
833             {
834                 argi += 1;
835                 break;
836             }
837             else if (std::strcmp(argv[argi], "--preview") == 0)
838             {
839                 argi += 1;
840             }
841             else if (std::strcmp(argv[argi], "--video-std") == 0)
842             {
843                 argi += 2;
844             }
845             else if (std::strcmp(argv[argi], "--save-temps") == 0)
846             {
847                 temp_file::keep_all(true);
848                 argi += 1;
849             }
850             else if (std::strcmp(argv[argi], "--encoder") == 0)
851             {
852                 if (argi + 1 == argc)
853                 {
854                     std::cerr << "Missing argument to --encoder\n";
855                     print_usage(std::cerr, argv[0]);
856                     return EXIT_FAILURE;
857                 }
858                 if (std::strcmp(argv[argi + 1], "ffmpeg") == 0)
859                 {
860                     encoder = dvd_generator::mpeg_encoder_ffmpeg;
861                 }
862                 else if (std::strcmp(argv[argi + 1], "mjpegtools-old") == 0)
863                 {
864                     encoder = dvd_generator::mpeg_encoder_mjpegtools_old;
865                 }
866                 else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0
867                          || std::strcmp(argv[argi + 1], "mjpegtools-new") == 0)
868                 {
869                     encoder = dvd_generator::mpeg_encoder_mjpegtools_new;
870                 }
871                 else
872                 {
873                     std::cerr << "Invalid argument to --encoder\n";
874                     print_usage(std::cerr, argv[0]);
875                     return EXIT_FAILURE;
876                 }
877                 argi += 2;
878             }
879             else if (argv[argi][0] == '-')
880             {
881                 std::cerr << "Invalid option: " << argv[argi] << "\n";
882                 print_usage(std::cerr, argv[0]);
883                 return EXIT_FAILURE;
884             }
885             else
886             {
887                 break;
888             }
889         }
890
891         // Look for a starting URL or filename and (except in preview
892         // mode) an output directory after the options.
893         if (argc - argi != (preview_mode ? 1 : 2))
894         {
895             print_usage(std::cerr, argv[0]);
896             return EXIT_FAILURE;
897         }
898         if (std::strstr(argv[argi], "://"))
899         {
900             // It appears to be an absolute URL, so use it as-is.
901             menu_url = argv[argi];
902         }
903         else
904         {
905             // Assume it's a filename.  Resolve it to an absolute URL.
906             std::string path(argv[argi]);
907             if (!Glib::path_is_absolute(path))
908                 path = Glib::build_filename(Glib::get_current_dir(), path);
909             menu_url = Glib::filename_to_uri(path);             
910         }
911         if (!preview_mode)
912             output_dir = argv[argi + 1];
913
914         // Initialise Mozilla
915         browser_widget::initialiser browser_init;
916         set_browser_preferences();
917         init_agent_style_sheet("file://" VIDEOLINK_SHARE_DIR "/videolink.css");
918         init_agent_style_sheet(std::string("file://" VIDEOLINK_SHARE_DIR "/")
919                                .append(frame_params.common_name).append(".css")
920                                .c_str());
921         if (!preview_mode)
922             null_prompt_service::install();
923
924         // Run the browser/converter
925         videolink_window window(frame_params, menu_url, output_dir, encoder);
926         window.show();
927         window.signal_hide().connect(SigC::slot(&Gtk::Main::quit));
928         Gtk::Main::run();
929
930         return ((preview_mode || window.is_finished())
931                 ? EXIT_SUCCESS
932                 : EXIT_FAILURE);
933     }
934     catch (std::exception & e)
935     {
936         std::cerr << "Fatal error: " << e.what() << "\n";
937         return EXIT_FAILURE;
938     }
939 }