]> git.decadent.org.uk Git - videolink.git/blobdiff - videolink.cpp
Release versions 1.2.11 and 1.2.11-1
[videolink.git] / videolink.cpp
index 3d2daebd0176644a008444e729c76e86ebd85be3..a15bbea1bfe125a2cf9c67e152935203a1e3e2a3 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
+// Copyright 2005-8 Ben Hutchings <ben@decadent.org.uk>.
 // See the file "COPYING" for licence details.
 
 #include <cassert>
 
 #include <stdlib.h>
 
-#include <boost/shared_ptr.hpp>
-
+#include <gdk/gdkkeysyms.h>
 #include <gdkmm/pixbuf.h>
 #include <glibmm/convert.h>
 #include <glibmm/spawn.h>
 #include <gtkmm/main.h>
 #include <gtkmm/window.h>
 
-#include <imglib2/ImageErrors.h>
+#include "videolink.hpp"
+#include "wchar_t_short.h"
+#include <ImageErrors.h>
+#if MOZ_VERSION_GE(1,9,0)
+#include <nsWeakPtr.h>
+/* For some reason <nsWeakPtr.h> no longer defines this */
+typedef nsCOMPtr<nsIWeakReference> nsWeakPtr;
+#endif
 #include <nsGUIEvent.h>
 #include <nsIBoxObject.h>
 #include <nsIContent.h>
 #include <nsILink.h>
 #include <nsIPrefBranch.h>
 #include <nsIPrefService.h>
-#include <nsIPresContext.h>
 #include <nsIPresShell.h>
-#include <nsIServiceManagerUtils.h>
+#include <nsServiceManagerUtils.h>
 #include <nsIWebBrowser.h>
+#ifdef MOZILLA_INTERNAL_API
 #include <nsString.h>
+#else
+#include <nsStringAPI.h>
+#endif
+#include "wchar_t_default.h"
 
 #include "browser_widget.hpp"
 #include "child_iterator.hpp"
 #include "dvd.hpp"
+#include "event_state_manager.hpp"
 #include "generate_dvd.hpp"
+#include "geometry.hpp"
 #include "link_iterator.hpp"
 #include "null_prompt_service.hpp"
 #include "pixbufs.hpp"
 #include "style_sheets.hpp"
 #include "temp_file.hpp"
 #include "video.hpp"
+#include "warp_pointer.hpp"
 #include "x_frame_buffer.hpp"
 #include "xml_utils.hpp"
 #include "xpcom_support.hpp"
@@ -68,66 +81,17 @@ using xpcom_support::check;
 
 namespace
 {
-    // We can try using any of these encoders to convert PNG to MPEG.
-    enum mpeg_encoder
-    {
-       mpeg_encoder_ffmpeg,         // ffmpeg
-       mpeg_encoder_mjpegtools_old, // mjpegtools before version 1.8
-       mpeg_encoder_mjpegtools_new  // mjpegtools from version 1.8
-    };
-
-    struct rectangle
-    {
-       int left, top;     // inclusive
-       int right, bottom; // exclusive
-
-       rectangle operator|=(const rectangle & other)
-           {
-               if (other.empty())
-               {
-                   // use current extents unchanged
-               }
-               else if (empty())
-               {
-                   // use other extents
-                   *this = other;
-               }
-               else
-               {
-                   // find rectangle enclosing both extents
-                   left = std::min(left, other.left);
-                   top = std::min(top, other.top);
-                   right = std::max(right, other.right);
-                   bottom = std::max(bottom, other.bottom);
-               }
-
-               return *this;
-           }
-
-       rectangle operator&=(const rectangle & other)
-           {
-               // find rectangle enclosed in both extents
-               left = std::max(left, other.left);
-               top = std::max(top, other.top);
-               right = std::max(left, std::min(right, other.right));
-               bottom = std::max(top, std::min(bottom, other.bottom));
-               return *this;
-           }
-
-       bool empty() const
-           {
-               return left == right || bottom == top;
-           }
-    };
-
-    rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
-                           nsIDOMElement * elem)
+#if MOZ_VERSION_GE(2,0,-1)
+    rectangle get_elem_rect(nsIDocument * doc, nsIDOMElement * elem)
+#else
+    rectangle get_elem_rect(nsIDOMNSDocument * doc, nsIDOMElement * elem)
+#endif
     {
        rectangle result;
 
        // Start with this element's bounding box
        nsCOMPtr<nsIBoxObject> box;
-       check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
+       check(doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
        int width, height;
        check(box->GetScreenX(&result.left));
        check(box->GetScreenY(&result.top));
@@ -146,7 +110,7 @@ namespace
            {
                nsCOMPtr<nsIDOMElement> child_elem(
                    do_QueryInterface(child_node));
-               result |= get_elem_rect(ns_doc, child_elem);
+               result |= get_elem_rect(doc, child_elem);
            }
        }
 
@@ -154,20 +118,122 @@ namespace
     }
 
 
-    class videolink_window : public Gtk::Window
+    enum video_format
+    {
+       video_format_none,
+       video_format_mpeg2_ps,
+       video_format_vob_list
+    };
+
+    video_format video_format_from_uri(const std::string & uri)
+    {
+       // FIXME: This is a bit of a hack.  Perhaps we could decide
+       // later based on the MIME type determined by Mozilla?
+       static struct {
+           const char * extension;
+           video_format format;
+       } const mapping[] = {
+           {".vob",     video_format_mpeg2_ps},
+           {".mpeg",    video_format_mpeg2_ps},
+           {".mpeg2",   video_format_mpeg2_ps},
+           {".mpg",     video_format_mpeg2_ps},
+           {".voblist", video_format_vob_list}
+       };
+       for (std::size_t i = 0;
+            i != sizeof(mapping) / sizeof(mapping[0]);
+            ++i)
+       {
+           std::size_t ext_len = std::strlen(mapping[i].extension);
+           if (uri.size() > ext_len
+               && uri.compare(uri.size() - ext_len, ext_len,
+                              mapping[i].extension) == 0)
+               return mapping[i].format;
+       }
+       return video_format_none;
+    }
+
+
+    class base_window : public Gtk::Window
+    {
+    public:
+       base_window(const video::frame_params & frame_params);
+
+    protected:
+       video::frame_params frame_params_;
+       browser_widget browser_widget_;
+    };
+
+    base_window::base_window(const video::frame_params & frame_params)
+       : frame_params_(frame_params)
+    {
+       set_size_request(frame_params_.width, frame_params_.height);
+       set_resizable(false);
+
+       add(browser_widget_);
+       browser_widget_.show();
+    }
+
+    class preview_window : public base_window
+    {
+    public:
+       preview_window(const video::frame_params & frame_params,
+                      const std::string & main_page_uri);
+
+    private:
+       bool on_idle();
+       bool on_key_press(GdkEventKey *);
+
+       std::string main_page_uri_;
+    };
+
+    preview_window::preview_window(const video::frame_params & frame_params,
+                                  const std::string & main_page_uri)
+       : base_window(frame_params),
+         main_page_uri_(main_page_uri)
+    {
+       Glib::signal_idle().connect(
+           sigc::mem_fun(this, &preview_window::on_idle));
+       signal_key_press_event().connect(
+           sigc::mem_fun(this, &preview_window::on_key_press));
+    }
+
+    bool preview_window::on_idle()
+    {
+       browser_widget_.load_uri(main_page_uri_);
+       return false; // don't call again
+    }
+
+    bool preview_window::on_key_press(GdkEventKey * event)
+    {
+       switch (event->keyval)
+       {
+       case GDK_t: // = top menu
+           browser_widget_.load_uri(main_page_uri_);
+           return true;
+       case GDK_q: // = quit
+           Gtk::Main::quit();
+           return true;
+       default:
+           return false;
+       }
+    }
+
+    class conversion_window : public base_window
     {
     public:
-       videolink_window(
-           const video::frame_params & frame_params,
-           const std::string & main_page_uri,
-           const std::string & output_dir,
-           mpeg_encoder encoder);
+       conversion_window(const video::frame_params & frame_params,
+                         const std::string & main_page_uri,
+                         const std::string & output_dir,
+                         dvd_generator::mpeg_encoder encoder);
 
        bool is_finished() const;
 
     private:
-       dvd_contents::pgc_ref add_menu(const std::string & uri);
-       dvd_contents::pgc_ref add_title(const std::string & uri);
+       struct page_state;
+
+       dvd_generator::pgc_ref add_menu(const std::string & uri);
+       dvd_generator::pgc_ref add_title(const std::string & uri,
+                                        video_format format);
        void load_next_page();
        bool on_idle();
        void on_net_state_change(const char * uri, gint flags, guint status);
@@ -175,96 +241,81 @@ namespace
            {
                return pending_window_update_ || pending_req_count_;
            }
-       bool process_page();
-       void save_screenshot();
-       void process_links(nsIPresShell * pres_shell,
-                          nsIPresContext * pres_context,
-                          nsIDOMWindow * dom_window);
+       // Do as much processing as possible.  Return a flag indicating
+       // whether to call again once the browser is idle.
+       bool process();
+       // Return a Pixbuf containing a copy of the window contents.
+       Glib::RefPtr<Gdk::Pixbuf> get_screenshot();
+       // Do as much processing as possible on the page links.  Return
+       // a flag indicating whether to call again once the browser is
+       // idle.
+       bool process_links(
+           page_state * state,
+           nsIDOMDocument * basic_doc,
+           nsIDocShell * doc_shell,
+           nsIDOMWindow * dom_window);
 
-       video::frame_params frame_params_;
        std::string output_dir_;
-       mpeg_encoder encoder_;
-       browser_widget browser_widget_;
-       nsCOMPtr<nsIStyleSheet> stylesheet_;
 
-       dvd_contents contents_;
-       typedef std::map<std::string, dvd_contents::pgc_ref> resource_map_type;
+       enum {
+           state_initial,
+           state_processing,
+           state_finished
+       } state_;
+
+       dvd_generator generator_;
+       typedef std::map<std::string, dvd_generator::pgc_ref>
+           resource_map_type;
        resource_map_type resource_map_;
 
        std::queue<std::string> page_queue_;
        bool pending_window_update_;
        int pending_req_count_;
-       bool have_tweaked_page_;
-       std::auto_ptr<temp_file> background_temp_;
-       struct page_state;
        std::auto_ptr<page_state> page_state_;
-
-       bool finished_;
     };
 
-    videolink_window::videolink_window(
+    conversion_window::conversion_window(
        const video::frame_params & frame_params,
        const std::string & main_page_uri,
        const std::string & output_dir,
-       mpeg_encoder encoder)
-           : frame_params_(frame_params),
-             output_dir_(output_dir),
-             encoder_(encoder),
-             stylesheet_(load_css("file://" VIDEOLINK_LIB_DIR "/videolink.css")),
-             pending_window_update_(false),
-             pending_req_count_(0),
-             have_tweaked_page_(false),
-             finished_(false)
+       dvd_generator::mpeg_encoder encoder)
+       : base_window(frame_params),
+         output_dir_(output_dir),
+         state_(state_initial),
+         generator_(frame_params, encoder),
+         pending_window_update_(false),
+         pending_req_count_(0)
     {
-       set_size_request(frame_params_.width, frame_params_.height);
-       set_resizable(false);
-
-       add(browser_widget_);
-       browser_widget_.show();
        Glib::signal_idle().connect(
-           SigC::slot(*this, &videolink_window::on_idle));
+           sigc::mem_fun(this, &conversion_window::on_idle));
        browser_widget_.signal_net_state().connect(
-           SigC::slot(*this, &videolink_window::on_net_state_change));
+           sigc::mem_fun(this, &conversion_window::on_net_state_change));
 
        add_menu(main_page_uri);
     }
 
-    bool videolink_window::is_finished() const
+    bool conversion_window::is_finished() const
     {
-       return finished_;
+       return state_ == state_finished;
     }
 
-    dvd_contents::pgc_ref videolink_window::add_menu(const std::string & uri)
+    dvd_generator::pgc_ref conversion_window::add_menu(const std::string & uri)
     {
-       dvd_contents::pgc_ref next_menu(dvd_contents::menu_pgc,
-                                       contents_.menus.size());
-       std::pair<resource_map_type::iterator, bool> insert_result(
-           resource_map_.insert(std::make_pair(uri, next_menu)));
-
-       if (!insert_result.second)
-       {
-           return insert_result.first->second;
-       }
-       else
+       dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
+       if (pgc_ref.type == dvd_generator::unknown_pgc)
        {
+           pgc_ref = generator_.add_menu();
            page_queue_.push(uri);
-           contents_.menus.resize(contents_.menus.size() + 1);
-           return next_menu;
        }
+       return pgc_ref;
     }
 
-    dvd_contents::pgc_ref videolink_window::add_title(const std::string & uri)
+    dvd_generator::pgc_ref conversion_window::add_title(const std::string & uri,
+                                                     video_format format)
     {
-       dvd_contents::pgc_ref next_title(dvd_contents::title_pgc,
-                                        contents_.titles.size());
-       std::pair<resource_map_type::iterator, bool> insert_result(
-           resource_map_.insert(std::make_pair(uri, next_title)));
+       dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
 
-       if (!insert_result.second)
-       {
-           return insert_result.first->second;
-       }
-       else
+       if (pgc_ref.type == dvd_generator::unknown_pgc)
        {
            Glib::ustring hostname;
            std::string path(Glib::filename_from_uri(uri, hostname));
@@ -274,7 +325,7 @@ namespace
 
            // Store a reference to a linked VOB file, or the contents
            // of a linked VOB list file.
-           if (path.compare(path.size() - 4, 4, ".vob") == 0)
+           if (format == video_format_mpeg2_ps)
            {
                if (!Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR))
                    throw std::runtime_error(
@@ -283,38 +334,35 @@ namespace
                ref.file = path;
                list.push_back(ref);
            }
-           else
+           else if (format == video_format_vob_list)
            {
-               assert(path.compare(path.size() - 8, 8, ".voblist") == 0);
                read_vob_list(path).swap(list);
            }
+           else
+           {
+               assert(!"unrecognised format in add_title");
+           }
 
-           contents_.titles.resize(contents_.titles.size() + 1);
-           contents_.titles.back().swap(list);
-           return next_title;
+           pgc_ref = generator_.add_title(list);
        }
+
+       return pgc_ref;
     }
 
-    void videolink_window::load_next_page()
+    void conversion_window::load_next_page()
     {
        assert(!page_queue_.empty());
        const std::string & uri = page_queue_.front();
-       std::cout << "loading " << uri << std::endl;
+       std::cout << "INFO: Loading <" << uri << ">" << std::endl;
 
        browser_widget_.load_uri(uri);
     }
 
-    bool videolink_window::on_idle()
-    {
-       load_next_page();
-       return false; // don't call again thankyou
-    }
-
-    void videolink_window::on_net_state_change(const char * uri,
-                                          gint flags, guint status)
+    void conversion_window::on_net_state_change(const char * uri,
+                                               gint flags, guint status)
     {
 #       ifdef DEBUG_ON_NET_STATE_CHANGE
-       std::cout << "videolink_window::on_net_state_change(";
+       std::cout << "conversion_window::on_net_state_change(";
        if (uri)
            std::cout << '"' << uri << '"';
        else
@@ -368,7 +416,6 @@ namespace
            && flags & GTK_MOZ_EMBED_FLAG_START)
        {
            pending_window_update_ = true;
-           have_tweaked_page_ = false;
        }
 
        if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
@@ -376,168 +423,178 @@ namespace
        {
            // Check whether the load was successful, ignoring this
            // pseudo-error.
+#ifdef NS_IMAGELIB_ERROR_LOAD_ABORTED
            if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
+#endif
                check(status);
 
            pending_window_update_ = false;
        }
+    }
 
-       if (!browser_is_busy())
+    struct conversion_window::page_state
+    {
+       page_state(Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf,
+                  nsIDOMDocument * doc, int width, int height)
+               : norm_pixbuf(norm_pixbuf),
+                 diff_pixbuf(Gdk::Pixbuf::create(
+                                 Gdk::COLORSPACE_RGB,
+                                 true, 8, // has_alpha, bits_per_sample
+                                 width, height)),
+                 links_it(doc),
+                 link_changing(false)
+           {
+           }
+
+       Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
+       Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
+
+       link_iterator links_it, links_end;
+
+       rectangle link_rect;
+       std::string link_target;
+       bool link_changing;
+    };
+
+    bool conversion_window::on_idle()
+    {
+       if (state_ == state_initial)
+       {
+           // Put pointer in the top-left so that no links appear in
+           // the hover state when we take a screenshot.
+           warp_pointer(get_window(),
+                        -frame_params_.width, -frame_params_.height);
+
+           load_next_page();
+
+           state_ = state_processing;
+       }
+       else if (state_ == state_processing && !browser_is_busy())
        {
            try
            {
-               if (!process_page())
+               if (!process())
                {
-                   finished_ = true;
+                   state_ = state_finished;
                    Gtk::Main::quit();
                }
            }
-           catch (std::exception & e)
+           catch (...)
            {
-               std::cerr << "Fatal error";
+               // Print context of exception.
                if (!page_queue_.empty())
-                   std::cerr << " while processing <" << page_queue_.front()
-                             << ">";
-               std::cerr << ": " << e.what() << "\n";
-               Gtk::Main::quit();
-           }
-           catch (Glib::Exception & e)
-           {
-               std::cerr << "Fatal error";
-               if (!page_queue_.empty())
-                   std::cerr << " while processing <" << page_queue_.front()
-                             << ">";
-               std::cerr << ": " << e.what() << "\n";
+               {
+                   std::cerr << "ERROR: While processing page <"
+                             << page_queue_.front() << ">:\n";
+                   if (page_state_.get() && !page_state_->link_target.empty())
+                       std::cerr << "ERROR: While processing link to <"
+                                 << page_state_->link_target << ">:\n";
+               }
+
+               // Print exception message.
+               try
+               {
+                   throw;
+               }
+               catch (std::exception & e)
+               {
+                   std::cerr << "ERROR: " << e.what() << "\n";
+               }
+               catch (Glib::Exception & e)
+               {
+                   std::cerr << "ERROR: " << e.what() << "\n";
+               }
+               catch (...)
+               {
+                   std::cerr << "ERROR: Unknown exception\n";
+               }
+
                Gtk::Main::quit();
            }
        }
+
+       // Call again if we're not done.
+       return state_ != state_finished;
     }
 
-    bool videolink_window::process_page()
+    bool conversion_window::process()
     {
        assert(!page_queue_.empty());
 
        nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
        nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
        assert(doc_shell);
-       nsCOMPtr<nsIPresShell> pres_shell;
-       check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
-       nsCOMPtr<nsIPresContext> pres_context;
-       check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
        nsCOMPtr<nsIDOMWindow> dom_window;
        check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
 
-       // If we haven't done so already, apply the stylesheet and
-       // disable scrollbars.
-       if (!have_tweaked_page_)
-       {
-           apply_style_sheet(stylesheet_, pres_shell);
-
-           // This actually only needs to be done once.
-           nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
-           check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
-           check(dom_bar_prop->SetVisible(false));
-
-           have_tweaked_page_ = true;
-
-           // Might need to wait a while for things to load or more
-           // likely for a re-layout.
-           if (browser_is_busy())
-               return true;
-       }
+       nsCOMPtr<nsIDOMDocument> basic_doc;
+       check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
 
-       // All further work should only be done if we're not in preview mode.
-       if (!output_dir_.empty())
+       // Start or continue processing links.
+       if (!page_state_.get())
+           page_state_.reset(
+               new page_state(
+                   get_screenshot(),
+                   basic_doc, frame_params_.width, frame_params_.height));
+       if (!process_links(page_state_.get(), basic_doc, doc_shell, dom_window))
        {
-           // If we haven't already started work on this menu, save a
-           // screenshot of its normal appearance.
-           if (!page_state_.get())
-               save_screenshot();
-
-           // Start or continue processing links.
-           process_links(pres_shell, pres_context, dom_window);
-
-           // If we've finished work on the links, move on to the
-           // next page, if any, or else generate the DVD filesystem.
-           if (!page_state_.get())
+           // We've finished work on the links so generate the
+           // menu VOB.
+           quantise_rgba_pixbuf(page_state_->diff_pixbuf,
+                                dvd::button_n_colours);
+           generator_.generate_menu_vob(
+               resource_map_[page_queue_.front()].index,
+               page_state_->norm_pixbuf, page_state_->diff_pixbuf);
+
+           // Move on to the next page, if any, or else generate
+           // the DVD filesystem.
+           page_state_.reset();
+           page_queue_.pop();
+           if (!page_queue_.empty())
            {
-               page_queue_.pop();
-               if (page_queue_.empty())
-               {
-                   generate_dvd(contents_, output_dir_);
-                   return false;
-               }
-               else
-               {
-                   load_next_page();
-               }
+               load_next_page();
+           }
+           else
+           {
+               generator_.generate(output_dir_);
+               return false;
            }
        }
 
        return true;
     }
 
-    void videolink_window::save_screenshot()
+    Glib::RefPtr<Gdk::Pixbuf> conversion_window::get_screenshot()
     {
        Glib::RefPtr<Gdk::Window> window(get_window());
        assert(window);
        window->process_updates(true);
 
-       background_temp_.reset(new temp_file("videolink-back-"));
-       background_temp_->close();
-       std::cout << "saving " << background_temp_->get_name() << std::endl;
-       Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
-                           window->get_colormap(),
-                           0, 0, 0, 0,
-                           frame_params_.width, frame_params_.height)
-           ->save(background_temp_->get_name(), "png");
+       return Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
+                                  window->get_colormap(),
+                                  0, 0, 0, 0,
+                                  frame_params_.width, frame_params_.height);
     }
 
-    struct videolink_window::page_state
-    {
-       page_state(nsIDOMDocument * doc, int width, int height)
-               : diff_pixbuf(Gdk::Pixbuf::create(
-                                 Gdk::COLORSPACE_RGB,
-                                 true, 8, // has_alpha, bits_per_sample
-                                 width, height)),
-                 spumux_temp("videolink-spumux-"),
-                 links_temp("videolink-links-"),
-                 link_num(0),
-                 links_it(doc),
-                 link_changing(false)
-           {
-               spumux_temp.close();
-               links_temp.close();
-           }
-
-       Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
-
-       temp_file spumux_temp;
-       std::ofstream spumux_file;
-
-       temp_file links_temp;
-
-       unsigned link_num;
-       link_iterator links_it, links_end;
-
-       rectangle link_rect;
-       bool link_changing;
-       Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
-    };
-
-    void videolink_window::process_links(nsIPresShell * pres_shell,
-                                    nsIPresContext * pres_context,
-                                    nsIDOMWindow * dom_window)
+    bool conversion_window::process_links(
+       page_state * state,
+       nsIDOMDocument * basic_doc,
+       nsIDocShell * doc_shell,
+       nsIDOMWindow * dom_window)
     {
        Glib::RefPtr<Gdk::Window> window(get_window());
        assert(window);
 
-       nsCOMPtr<nsIDOMDocument> basic_doc;
-       check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
        nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
        assert(ns_doc);
+#if MOZ_VERSION_GE(2,0,-1)
+       nsCOMPtr<nsIDocument> doc(do_QueryInterface(basic_doc));
+       assert(doc);
+#endif
+       nsCOMPtr<nsIPresShell> pres_shell;
+       check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
        nsCOMPtr<nsIEventStateManager> event_state_man(
-           pres_context->EventStateManager()); // does not AddRef
+           get_event_state_manager(doc_shell));
        assert(event_state_man);
        nsCOMPtr<nsIDOMDocumentEvent> event_factory(
            do_QueryInterface(basic_doc));
@@ -547,28 +604,11 @@ namespace
        nsCOMPtr<nsIDOMAbstractView> view;
        check(doc_view->GetDefaultView(getter_AddRefs(view)));
 
-       // Set up or recover our iteration state.
-       std::auto_ptr<page_state> state(page_state_);
-       if (!state.get())
-       {
-           state.reset(
-               new page_state(
-                   basic_doc, frame_params_.width, frame_params_.height));
-           
-           state->spumux_file.open(state->spumux_temp.get_name().c_str());
-           state->spumux_file <<
-               "<subpictures>\n"
-               "  <stream>\n"
-               "    <spu force='yes' start='00:00:00.00'\n"
-               "        highlight='" << state->links_temp.get_name() << "'\n"
-               "        select='" << state->links_temp.get_name() << "'>\n";
-       }
-
        rectangle window_rect = {
            0, 0, frame_params_.width, frame_params_.height
        };
 
-       unsigned menu_num = resource_map_[page_queue_.front()].index;
+       unsigned menu_index = resource_map_[page_queue_.front()].index;
 
        for (/* no initialisation */;
             state->links_it != state->links_end;
@@ -577,21 +617,29 @@ namespace
            nsCOMPtr<nsIDOMNode> node(*state->links_it);
 
            // Find the link URI and separate any fragment from it.
+           nsCOMPtr<nsIURI> uri_iface;
+#if MOZ_VERSION_GE(2,0,-1)
+           nsCOMPtr<nsIContent> content(do_QueryInterface(node));
+           assert(content);
+           uri_iface = content->GetHrefURI();
+           assert(uri_iface);
+#else
            nsCOMPtr<nsILink> link(do_QueryInterface(node));
            assert(link);
-           nsCOMPtr<nsIURI> uri_iface;
            check(link->GetHrefURI(getter_AddRefs(uri_iface)));
-           std::string uri_and_fragment, uri, fragment;
+#endif
+           std::string uri, fragment;
            {
-               nsCString uri_and_fragment_ns;
-               check(uri_iface->GetSpec(uri_and_fragment_ns));
-               uri_and_fragment.assign(uri_and_fragment_ns.BeginReading(),
-                                       uri_and_fragment_ns.EndReading());
-
-               std::size_t hash_pos = uri_and_fragment.find('#');
-               uri.assign(uri_and_fragment, 0, hash_pos);
+               nsCString link_target_ns;
+               check(uri_iface->GetSpec(link_target_ns));
+               const char * str;
+               PRUint32 len = NS_CStringGetData(link_target_ns, &str);
+               state->link_target.assign(str, len);
+
+               std::size_t hash_pos = state->link_target.find('#');
+               uri.assign(state->link_target, 0, hash_pos);
                if (hash_pos != std::string::npos)
-                   fragment.assign(uri_and_fragment,
+                   fragment.assign(state->link_target,
                                    hash_pos + 1, std::string::npos);
            }
 
@@ -602,64 +650,45 @@ namespace
                // window.
                nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
                assert(elem);
+#if MOZ_VERSION_GE(2,0,-1)
+               state->link_rect = get_elem_rect(doc, elem);
+#else
                state->link_rect = get_elem_rect(ns_doc, elem);
+#endif
                state->link_rect &= window_rect;
 
                if (state->link_rect.empty())
                {
-                   std::cerr << "Ignoring invisible link to "
-                             << uri_and_fragment << "\n";
-                   continue;
-               }
-
-               ++state->link_num;
-
-               if (state->link_num >= unsigned(dvd::menu_buttons_max))
-               {
-                   if (state->link_num == unsigned(dvd::menu_buttons_max))
-                       std::cerr << "No more than " << dvd::menu_buttons_max
-                                 << " buttons can be placed on a menu\n";
-                   std::cerr << "Ignoring link to " << uri_and_fragment
-                             << "\n";
+                   std::cerr << "WARN: Ignoring invisible link to <"
+                             << state->link_target << ">\n";
                    continue;
                }
 
-               state->spumux_file <<
-                   "      <button x0='" << state->link_rect.left << "'"
-                   " y0='" << state->link_rect.top << "'"
-                   " x1='" << state->link_rect.right - 1 << "'"
-                   " y1='" << state->link_rect.bottom - 1 << "'/>\n";
-
                // Check whether this is a link to a video or a page then
                // add it to the known resources if not already seen; then
                // add it to the menu entries.
-               dvd_contents::pgc_ref target;
-               // FIXME: This is a bit of a hack.  Perhaps we could decide
-               // later based on the MIME type determined by Mozilla?
-               if ((uri.size() > 4
-                    && uri.compare(uri.size() - 4, 4, ".vob") == 0)
-                   || (uri.size() > 8
-                       && uri.compare(uri.size() - 8, 8, ".voblist") == 0))
+               dvd_generator::pgc_ref target;
+               video_format format = video_format_from_uri(uri);
+               if (format != video_format_none)
                {
                    PRBool is_file;
                    check(uri_iface->SchemeIs("file", &is_file));
                    if (!is_file)
-                   {
-                       std::cerr << "Links to video must use the file:"
-                                 << " scheme\n";
-                       continue;
-                   }
-                   target = add_title(uri);
+                       throw std::runtime_error(
+                           "Link to video does not use file: scheme");
+                   target = add_title(uri, format);
                    target.sub_index =
                        std::strtoul(fragment.c_str(), NULL, 10);
                }
-               else
+               else // video_format == video_format_none
                {
                    target = add_menu(uri);
                    // TODO: If there's a fragment, work out which button
                    // is closest and set target.sub_index.
                }
-               contents_.menus[menu_num].entries.push_back(target);
+
+               generator_.add_menu_entry(menu_index,
+                                         state->link_rect, target);
 
                nsCOMPtr<nsIContent> content(do_QueryInterface(node));
                assert(content);
@@ -667,16 +696,6 @@ namespace
                    do_QueryInterface(node));
                assert(event_target);
 
-               state->norm_pixbuf = Gdk::Pixbuf::create(
-                   Glib::RefPtr<Gdk::Drawable>(window),
-                   window->get_colormap(),
-                   state->link_rect.left,
-                   state->link_rect.top,
-                   0,
-                   0,
-                   state->link_rect.right - state->link_rect.left,
-                   state->link_rect.bottom - state->link_rect.top);
-
                nsCOMPtr<nsIDOMEvent> event;
                check(event_factory->CreateEvent(
                          NS_ConvertASCIItoUTF16("MouseEvents"),
@@ -703,7 +722,7 @@ namespace
                check(event_state_man->SetContentState(content,
                                                       NS_EVENT_STATE_HOVER));
 
-               pres_shell->FlushPendingNotifications(true);
+               pres_shell->FlushPendingNotifications(Flush_Display);
 
                // We may have to exit and wait for image loading
                // to complete, at which point we will be called
@@ -711,8 +730,7 @@ namespace
                if (browser_is_busy())
                {
                    state->link_changing = true;
-                   page_state_ = state;
-                   return;
+                   return true;
                }
            }
 
@@ -738,79 +756,7 @@ namespace
                state->link_rect.bottom - state->link_rect.top);
        }
 
-       quantise_rgba_pixbuf(state->diff_pixbuf, dvd::button_n_colours);
-
-       std::cout << "saving " << state->links_temp.get_name()
-                 << std::endl;
-       state->diff_pixbuf->save(state->links_temp.get_name(), "png");
-
-       state->spumux_file <<
-           "    </spu>\n"
-           "  </stream>\n"
-           "</subpictures>\n";
-
-       state->spumux_file.close();
-
-       // TODO: if (!state->spumux_file) throw ...
-
-       {
-           std::ostringstream command_stream;
-           if (encoder_ == mpeg_encoder_ffmpeg)
-           {
-               command_stream
-                   << "ffmpeg"
-                   << " -f image2 -vcodec png -i "
-                   << background_temp_->get_name()
-                   << " -target " << frame_params_.ffmpeg_name <<  "-dvd"
-                   << " -vcodec mpeg2video -an -y /dev/stdout"
-                   << " | spumux -v0 -mdvd " << state->spumux_temp.get_name()
-                   << " > " << contents_.menus[menu_num].vob_temp->get_name();
-           }
-           else
-           {
-               assert(encoder_ == mpeg_encoder_mjpegtools_old
-                      || encoder_ == mpeg_encoder_mjpegtools_new);
-               command_stream
-                   << "pngtopnm "
-                   << background_temp_->get_name()
-                   << " | ppmtoy4m -v0 -n1 -F"
-                   << frame_params_.rate_numer
-                   << ":" << frame_params_.rate_denom
-                   << " -A" << frame_params_.pixel_ratio_width
-                   << ":" << frame_params_.pixel_ratio_height
-                   << " -Ip ";
-               // The chroma subsampling keywords changed between
-               // versions 1.6.2 and 1.8 of mjpegtools.  There is no
-               // keyword that works with both.
-               if (encoder_ == mpeg_encoder_mjpegtools_old)
-                   command_stream << "-S420_mpeg2";
-               else
-                   command_stream << "-S420mpeg2";
-               command_stream
-                   << (" | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
-                       " | mplex -v0 -f8 -o/dev/stdout /dev/stdin"
-                       " | spumux -v0 -mdvd ")
-                   << state->spumux_temp.get_name()
-                   << " > "
-                   << contents_.menus[menu_num].vob_temp->get_name();
-           }
-           std::string command(command_stream.str());
-           const char * argv[] = {
-               "/bin/sh", "-c", command.c_str(), 0
-           };
-           std::cout << "running " << argv[2] << std::endl;
-           int command_result;
-           Glib::spawn_sync(".",
-                            Glib::ArrayHandle<std::string>(
-                                argv, sizeof(argv)/sizeof(argv[0]),
-                                Glib::OWNERSHIP_NONE),
-                            Glib::SPAWN_STDOUT_TO_DEV_NULL,
-                            SigC::Slot0<void>(),
-                            0, 0,
-                            &command_result);
-           if (command_result != 0)
-               throw std::runtime_error("spumux pipeline failed");
-       }
+       return false;
     }
 
     const video::frame_params & lookup_frame_params(const char * str)
@@ -839,7 +785,7 @@ namespace
            "Usage: " << command_name << " [gtk-options] [--preview]\n"
            "           [--video-std {525|525/60|NTSC|ntsc"
            " | 625|625/50|PAL|pal}]\n"
-           "           [--encoder {mjpegtools|mjpegtools-old}]\n"
+           "           [--encoder {ffmpeg|mjpegtools}]\n"
            "           menu-url [output-dir]\n";
     }
     
@@ -850,18 +796,14 @@ namespace
        check(CallGetService<nsIPrefService>(pref_service_cid,
                                             getter_AddRefs(pref_service)));
        nsCOMPtr<nsIPrefBranch> pref_branch;
+       check(pref_service->GetBranch("", getter_AddRefs(pref_branch)));
 
        // Disable IE-compatibility kluge that causes backgrounds to
        // sometimes/usually be missing from snapshots.  This is only
        // effective from Mozilla 1.8 onward.
-#      if MOZ_VERSION_MAJOR > 1                                 \
-           || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
-       check(pref_service->GetDefaultBranch("layout",
-                                            getter_AddRefs(pref_branch)));
        check(pref_branch->SetBoolPref(
-                 "fire_onload_after_image_background_loads",
+                 "layout.fire_onload_after_image_background_loads",
                  true));
-#      endif
 
        // Set display resolution.  With standard-definition video we
        // will be fitting ~600 pixels across a screen typically
@@ -871,16 +813,28 @@ namespace
        // slightly different but unfortunately Mozilla doesn't
        // support non-square pixels (and neither do fontconfig or Xft
        // anyway).
-       check(pref_service->GetDefaultBranch("browser.display",
-                                            getter_AddRefs(pref_branch)));
-       check(pref_branch->SetIntPref("screen_resolution", 40));
+
+       // The browser.display.screen_resolution preference sets the
+       // the nominal resolution for dimensions expressed in pixels.
+       // (They may be scaled!)  In Mozilla 1.7 it also sets the
+       // assumed resolution of the display - hence pixel sizes are
+       // respected on-screen - but this is no longer the case in
+       // 1.8.  Therefore it was renamed to layout.css.dpi in 1.8.1.
+       // In 1.8 we need to set the assumed screen resolution
+       // separately, but don't know how yet.  Setting one to 40
+       // but not the other is *bad*, so currently we set neither.
+
+#      if 0
+           check(pref_branch->SetIntPref("browser.display.screen_resolution",
+                                         40));
+#      endif
     }
 
 } // namespace
 
 void fatal_error(const std::string & message)
 {
-    std::cerr << "Fatal error: " << message << "\n";
+    std::cerr << "ERROR: " << message << "\n";
     Gtk::Main::quit();
 }
 
@@ -892,7 +846,8 @@ int main(int argc, char ** argv)
        bool preview_mode = false;
        std::string menu_url;
        std::string output_dir;
-       mpeg_encoder encoder = mpeg_encoder_ffmpeg;
+       dvd_generator::mpeg_encoder encoder =
+           dvd_generator::mpeg_encoder_ffmpeg;
 
        // Do initial option parsing.  We have to do this before
        // letting Gtk parse the arguments since we may need to spawn
@@ -979,16 +934,11 @@ int main(int argc, char ** argv)
                }
                if (std::strcmp(argv[argi + 1], "ffmpeg") == 0)
                {
-                   encoder = mpeg_encoder_ffmpeg;
+                   encoder = dvd_generator::mpeg_encoder_ffmpeg;
                }
-               else if (std::strcmp(argv[argi + 1], "mjpegtools-old") == 0)
+               else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0)
                {
-                   encoder = mpeg_encoder_mjpegtools_old;
-               }
-               else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0
-                        || std::strcmp(argv[argi + 1], "mjpegtools-new") == 0)
-               {
-                   encoder = mpeg_encoder_mjpegtools_new;
+                   encoder = dvd_generator::mpeg_encoder_mjpegtools;
                }
                else
                {
@@ -1036,22 +986,34 @@ int main(int argc, char ** argv)
        // Initialise Mozilla
        browser_widget::initialiser browser_init;
        set_browser_preferences();
+       init_agent_style_sheet("file://" VIDEOLINK_SHARE_DIR "/videolink.css");
+       init_agent_style_sheet(std::string("file://" VIDEOLINK_SHARE_DIR "/")
+                              .append(frame_params.common_name).append(".css")
+                              .c_str());
        if (!preview_mode)
            null_prompt_service::install();
 
        // Run the browser/converter
-       videolink_window window(frame_params, menu_url, output_dir, encoder);
-       window.show();
-       window.signal_hide().connect(SigC::slot(&Gtk::Main::quit));
-       Gtk::Main::run();
-
-       return ((preview_mode || window.is_finished())
-               ? EXIT_SUCCESS
-               : EXIT_FAILURE);
+       if (preview_mode)
+       {
+           preview_window window(frame_params, menu_url);
+           window.show();
+           window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
+           Gtk::Main::run();
+           return EXIT_SUCCESS;
+       }
+       else
+       {
+           conversion_window window(frame_params, menu_url, output_dir, encoder);
+           window.show();
+           window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
+           Gtk::Main::run();
+           return window.is_finished() ? EXIT_SUCCESS  : EXIT_FAILURE;
+       }
     }
     catch (std::exception & e)
     {
-       std::cerr << "Fatal error: " << e.what() << "\n";
+       std::cerr << "ERROR: " << e.what() << "\n";
        return EXIT_FAILURE;
     }
 }