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