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