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