]> git.decadent.org.uk Git - videolink.git/blob - videolink.cpp
Moved generation of menu VOBs from videolink_window to dvd_generator.
[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                   link_num(0),
432                   links_it(doc),
433                   link_changing(false)
434             {
435             }
436
437         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
438         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
439
440         unsigned link_num;
441         link_iterator links_it, links_end;
442
443         rectangle link_rect;
444         bool link_changing;
445     };
446
447     bool videolink_window::process()
448     {
449         assert(!page_queue_.empty());
450
451         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
452         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
453         assert(doc_shell);
454         nsCOMPtr<nsIPresShell> pres_shell;
455         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
456         nsCOMPtr<nsPresContext> pres_context;
457         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
458         nsCOMPtr<nsIDOMWindow> dom_window;
459         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
460
461         // If we haven't done so already, apply the stylesheet and
462         // disable scrollbars.
463         if (!have_tweaked_page_)
464         {
465             apply_agent_style_sheet(main_style_sheet_, pres_shell);
466             apply_agent_style_sheet(frame_style_sheet_, pres_shell);
467
468             // This actually only needs to be done once.
469             nsCOMPtr<nsIDOMBarProp> dom_bar_prop;
470             check(dom_window->GetScrollbars(getter_AddRefs(dom_bar_prop)));
471             check(dom_bar_prop->SetVisible(false));
472
473             have_tweaked_page_ = true;
474
475             // Might need to wait a while for things to load or more
476             // likely for a re-layout.
477             if (browser_is_busy())
478                 return true;
479         }
480
481         // All further work should only be done if we're not in preview mode.
482         if (!output_dir_.empty())
483         {
484             nsCOMPtr<nsIDOMDocument> basic_doc;
485             check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
486
487             // Start or continue processing links.
488             std::auto_ptr<page_state> state(page_state_);
489             if (!state.get())
490                 state.reset(
491                     new page_state(
492                         get_screenshot(),
493                         basic_doc, frame_params_.width, frame_params_.height));
494             if (process_links(
495                     state.get(),
496                     basic_doc, pres_shell, pres_context, dom_window))
497             {
498                 // Save iteration state for later.
499                 page_state_ = state;
500             }
501             else
502             {
503                 // We've finished work on the links so generate the
504                 // menu VOB.
505                 quantise_rgba_pixbuf(state->diff_pixbuf,
506                                      dvd::button_n_colours);
507                 generator_.generate_menu_vob(
508                     resource_map_[page_queue_.front()].index,
509                     state->norm_pixbuf, state->diff_pixbuf);
510
511                 // Move on to the next page, if any, or else generate
512                 // the DVD filesystem.
513                 page_queue_.pop();
514                 if (!page_queue_.empty())
515                 {
516                     load_next_page();
517                 }
518                 else
519                 {
520                     generator_.generate(output_dir_);
521                     return false;
522                 }
523             }
524         }
525
526         return true;
527     }
528
529     Glib::RefPtr<Gdk::Pixbuf> videolink_window::get_screenshot()
530     {
531         Glib::RefPtr<Gdk::Window> window(get_window());
532         assert(window);
533         window->process_updates(true);
534
535         return Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
536                                    window->get_colormap(),
537                                    0, 0, 0, 0,
538                                    frame_params_.width, frame_params_.height);
539     }
540
541     bool videolink_window::process_links(
542         page_state * state,
543         nsIDOMDocument * basic_doc,
544         nsIPresShell * pres_shell,
545         nsPresContext * pres_context,
546         nsIDOMWindow * dom_window)
547     {
548         Glib::RefPtr<Gdk::Window> window(get_window());
549         assert(window);
550
551         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
552         assert(ns_doc);
553         nsCOMPtr<nsIEventStateManager> event_state_man(
554             pres_context->EventStateManager()); // does not AddRef
555         assert(event_state_man);
556         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
557             do_QueryInterface(basic_doc));
558         assert(event_factory);
559         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
560         assert(doc_view);
561         nsCOMPtr<nsIDOMAbstractView> view;
562         check(doc_view->GetDefaultView(getter_AddRefs(view)));
563
564         rectangle window_rect = {
565             0, 0, frame_params_.width, frame_params_.height
566         };
567
568         unsigned menu_index = resource_map_[page_queue_.front()].index;
569
570         for (/* no initialisation */;
571              state->links_it != state->links_end;
572              ++state->links_it)
573         {
574             nsCOMPtr<nsIDOMNode> node(*state->links_it);
575
576             // Find the link URI and separate any fragment from it.
577             nsCOMPtr<nsILink> link(do_QueryInterface(node));
578             assert(link);
579             nsCOMPtr<nsIURI> uri_iface;
580             check(link->GetHrefURI(getter_AddRefs(uri_iface)));
581             std::string uri_and_fragment, uri, fragment;
582             {
583                 nsCString uri_and_fragment_ns;
584                 check(uri_iface->GetSpec(uri_and_fragment_ns));
585                 uri_and_fragment.assign(uri_and_fragment_ns.BeginReading(),
586                                         uri_and_fragment_ns.EndReading());
587
588                 std::size_t hash_pos = uri_and_fragment.find('#');
589                 uri.assign(uri_and_fragment, 0, hash_pos);
590                 if (hash_pos != std::string::npos)
591                     fragment.assign(uri_and_fragment,
592                                     hash_pos + 1, std::string::npos);
593             }
594
595             // Is this a new link?
596             if (!state->link_changing)
597             {
598                 // Find a rectangle enclosing the link and clip it to the
599                 // window.
600                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
601                 assert(elem);
602                 state->link_rect = get_elem_rect(ns_doc, elem);
603                 state->link_rect &= window_rect;
604
605                 if (state->link_rect.empty())
606                 {
607                     std::cerr << "Ignoring invisible link to "
608                               << uri_and_fragment << "\n";
609                     continue;
610                 }
611
612                 ++state->link_num;
613
614                 if (state->link_num >= unsigned(dvd::menu_buttons_max))
615                 {
616                     if (state->link_num == unsigned(dvd::menu_buttons_max))
617                         std::cerr << "No more than " << dvd::menu_buttons_max
618                                   << " buttons can be placed on a menu\n";
619                     std::cerr << "Ignoring link to " << uri_and_fragment
620                               << "\n";
621                     continue;
622                 }
623
624                 // Check whether this is a link to a video or a page then
625                 // add it to the known resources if not already seen; then
626                 // add it to the menu entries.
627                 dvd_generator::pgc_ref target;
628                 video_format format = video_format_from_uri(uri);
629                 if (format != video_format_none)
630                 {
631                     PRBool is_file;
632                     check(uri_iface->SchemeIs("file", &is_file));
633                     if (!is_file)
634                     {
635                         std::cerr << "Links to video must use the file:"
636                                   << " scheme\n";
637                         continue;
638                     }
639                     target = add_title(uri, format);
640                     target.sub_index =
641                         std::strtoul(fragment.c_str(), NULL, 10);
642                 }
643                 else // video_format == video_format_none
644                 {
645                     target = add_menu(uri);
646                     // TODO: If there's a fragment, work out which button
647                     // is closest and set target.sub_index.
648                 }
649
650                 generator_.add_menu_entry(menu_index,
651                                           state->link_rect, target);
652
653                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
654                 assert(content);
655                 nsCOMPtr<nsIDOMEventTarget> event_target(
656                     do_QueryInterface(node));
657                 assert(event_target);
658
659                 nsCOMPtr<nsIDOMEvent> event;
660                 check(event_factory->CreateEvent(
661                           NS_ConvertASCIItoUTF16("MouseEvents"),
662                           getter_AddRefs(event)));
663                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
664                     do_QueryInterface(event));
665                 assert(mouse_event);
666                 check(mouse_event->InitMouseEvent(
667                           NS_ConvertASCIItoUTF16("mouseover"),
668                           true,  // can bubble
669                           true,  // cancelable
670                           view,
671                           0,     // detail: mouse click count
672                           state->link_rect.left, // screenX
673                           state->link_rect.top,  // screenY
674                           state->link_rect.left, // clientX
675                           state->link_rect.top,  // clientY
676                           false, false, false, false, // qualifiers
677                           0,     // button: left (or primary)
678                           0));   // related target
679                 PRBool dummy;
680                 check(event_target->DispatchEvent(mouse_event,
681                                                   &dummy));
682                 check(event_state_man->SetContentState(content,
683                                                        NS_EVENT_STATE_HOVER));
684
685 #               if MOZ_VERSION_MAJOR > 1                                   \
686                      || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
687                     pres_shell->FlushPendingNotifications(Flush_Display);
688 #               else
689                     pres_shell->FlushPendingNotifications(true);
690 #               endif
691
692                 // We may have to exit and wait for image loading
693                 // to complete, at which point we will be called
694                 // again.
695                 if (browser_is_busy())
696                 {
697                     state->link_changing = true;
698                     return true;
699                 }
700             }
701
702             window->process_updates(true);
703
704             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
705                 Gdk::Pixbuf::create(
706                     Glib::RefPtr<Gdk::Drawable>(window),
707                     window->get_colormap(),
708                     state->link_rect.left,
709                     state->link_rect.top,
710                     0,
711                     0,
712                     state->link_rect.right - state->link_rect.left,
713                     state->link_rect.bottom - state->link_rect.top));
714             diff_rgb_pixbufs(
715                 state->norm_pixbuf,
716                 changed_pixbuf,
717                 state->diff_pixbuf,
718                 state->link_rect.left,
719                 state->link_rect.top,
720                 state->link_rect.right - state->link_rect.left,
721                 state->link_rect.bottom - state->link_rect.top);
722         }
723
724         return false;
725     }
726
727     const video::frame_params & lookup_frame_params(const char * str)
728     {
729         assert(str);
730         static const char * const known_strings[] = {
731             "525",    "625",
732             "525/60", "625/50",
733             "NTSC",   "PAL",
734             "ntsc",   "pal"
735         };
736         for (std::size_t i = 0;
737              i != sizeof(known_strings)/sizeof(known_strings[0]);
738              ++i)
739             if (std::strcmp(str, known_strings[i]) == 0)
740                 return (i & 1)
741                     ? video::frame_params_625
742                     : video::frame_params_525;
743         throw std::runtime_error(
744             std::string("Invalid video standard: ").append(str));
745     }
746
747     void print_usage(std::ostream & stream, const char * command_name)
748     {
749         stream <<
750             "Usage: " << command_name << " [gtk-options] [--preview]\n"
751             "           [--video-std {525|525/60|NTSC|ntsc"
752             " | 625|625/50|PAL|pal}]\n"
753             "           [--encoder {mjpegtools|mjpegtools-old}]\n"
754             "           menu-url [output-dir]\n";
755     }
756     
757     void set_browser_preferences()
758     {
759         nsCOMPtr<nsIPrefService> pref_service;
760         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
761         check(CallGetService<nsIPrefService>(pref_service_cid,
762                                              getter_AddRefs(pref_service)));
763         nsCOMPtr<nsIPrefBranch> pref_branch;
764         check(pref_service->GetBranch("", getter_AddRefs(pref_branch)));
765
766 #       if MOZ_VERSION_MAJOR > 1                                 \
767            || (MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR >= 8)
768             // Disable IE-compatibility kluge that causes backgrounds to
769             // sometimes/usually be missing from snapshots.  This is only
770             // effective from Mozilla 1.8 onward.
771             check(pref_branch->SetBoolPref(
772                       "layout.fire_onload_after_image_background_loads",
773                       true));
774 #       endif
775
776         // Set display resolution.  With standard-definition video we
777         // will be fitting ~600 pixels across a screen typically
778         // ranging from 10 to 25 inches wide, for a resolution of
779         // 24-60 dpi.  I therefore declare the average horizontal
780         // resolution to be 40 dpi.  The vertical resolution will be
781         // slightly different but unfortunately Mozilla doesn't
782         // support non-square pixels (and neither do fontconfig or Xft
783         // anyway).
784
785         // The browser.display.screen_resolution preference sets the
786         // the nominal resolution for dimensions expressed in pixels.
787         // (They may be scaled!)  In Mozilla 1.7 it also sets the
788         // assumed resolution of the display - hence pixel sizes are
789         // respected on-screen - but this is no longer the case in
790         // 1.8.  Therefore it was renamed to layout.css.dpi in 1.8.1.
791         // In 1.8 we need to set the assumed screen resolution
792         // separately, but don't know how yet.  Setting one to 40
793         // but not the other is *bad*, so currently we set neither.
794
795 #       if MOZ_VERSION_MAJOR == 1 && MOZ_VERSION_MINOR < 8
796             check(pref_branch->SetIntPref("browser.display.screen_resolution",
797                                           40));
798 #       endif
799     }
800
801 } // namespace
802
803 void fatal_error(const std::string & message)
804 {
805     std::cerr << "Fatal error: " << message << "\n";
806     Gtk::Main::quit();
807 }
808
809 int main(int argc, char ** argv)
810 {
811     try
812     {
813         video::frame_params frame_params = video::frame_params_625;
814         bool preview_mode = false;
815         std::string menu_url;
816         std::string output_dir;
817         dvd_generator::mpeg_encoder encoder =
818             dvd_generator::mpeg_encoder_ffmpeg;
819
820         // Do initial option parsing.  We have to do this before
821         // letting Gtk parse the arguments since we may need to spawn
822         // Xvfb first.
823         int argi = 1;
824         while (argi != argc)
825         {
826             if (std::strcmp(argv[argi], "--") == 0)
827             {
828                 break;
829             }
830             else if (std::strcmp(argv[argi], "--help") == 0)
831             {
832                 print_usage(std::cout, argv[0]);
833                 return EXIT_SUCCESS;
834             }
835             else if (std::strcmp(argv[argi], "--preview") == 0)
836             {
837                 preview_mode = true;
838                 argi += 1;
839             }
840             else if (std::strcmp(argv[argi], "--video-std") == 0)
841             {
842                 if (argi + 1 == argc)
843                 {
844                     std::cerr << "Missing argument to --video-std\n";
845                     print_usage(std::cerr, argv[0]);
846                     return EXIT_FAILURE;
847                 }
848                 frame_params = lookup_frame_params(argv[argi + 1]);
849                 argi += 2;
850             }
851             else
852             {
853                 argi += 1;
854             }
855         }
856
857         std::auto_ptr<x_frame_buffer> fb;
858         if (!preview_mode)
859         {
860             // Spawn Xvfb and set env variables so that Xlib will use it
861             // Use 8 bits each for RGB components, which should translate into
862             // "enough" bits for YUV components.
863             fb.reset(new x_frame_buffer(frame_params.width,
864                                         frame_params.height,
865                                         3 * 8));
866             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
867             setenv("DISPLAY", fb->get_display().c_str(), true);
868         }
869
870         // Initialise Gtk
871         Gtk::Main kit(argc, argv);
872
873         // Complete option parsing with Gtk's options out of the way.
874         argi = 1;
875         while (argi != argc)
876         {
877             if (std::strcmp(argv[argi], "--") == 0)
878             {
879                 argi += 1;
880                 break;
881             }
882             else if (std::strcmp(argv[argi], "--preview") == 0)
883             {
884                 argi += 1;
885             }
886             else if (std::strcmp(argv[argi], "--video-std") == 0)
887             {
888                 argi += 2;
889             }
890             else if (std::strcmp(argv[argi], "--save-temps") == 0)
891             {
892                 temp_file::keep_all(true);
893                 argi += 1;
894             }
895             else if (std::strcmp(argv[argi], "--encoder") == 0)
896             {
897                 if (argi + 1 == argc)
898                 {
899                     std::cerr << "Missing argument to --encoder\n";
900                     print_usage(std::cerr, argv[0]);
901                     return EXIT_FAILURE;
902                 }
903                 if (std::strcmp(argv[argi + 1], "ffmpeg") == 0)
904                 {
905                     encoder = dvd_generator::mpeg_encoder_ffmpeg;
906                 }
907                 else if (std::strcmp(argv[argi + 1], "mjpegtools-old") == 0)
908                 {
909                     encoder = dvd_generator::mpeg_encoder_mjpegtools_old;
910                 }
911                 else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0
912                          || std::strcmp(argv[argi + 1], "mjpegtools-new") == 0)
913                 {
914                     encoder = dvd_generator::mpeg_encoder_mjpegtools_new;
915                 }
916                 else
917                 {
918                     std::cerr << "Invalid argument to --encoder\n";
919                     print_usage(std::cerr, argv[0]);
920                     return EXIT_FAILURE;
921                 }
922                 argi += 2;
923             }
924             else if (argv[argi][0] == '-')
925             {
926                 std::cerr << "Invalid option: " << argv[argi] << "\n";
927                 print_usage(std::cerr, argv[0]);
928                 return EXIT_FAILURE;
929             }
930             else
931             {
932                 break;
933             }
934         }
935
936         // Look for a starting URL or filename and (except in preview
937         // mode) an output directory after the options.
938         if (argc - argi != (preview_mode ? 1 : 2))
939         {
940             print_usage(std::cerr, argv[0]);
941             return EXIT_FAILURE;
942         }
943         if (std::strstr(argv[argi], "://"))
944         {
945             // It appears to be an absolute URL, so use it as-is.
946             menu_url = argv[argi];
947         }
948         else
949         {
950             // Assume it's a filename.  Resolve it to an absolute URL.
951             std::string path(argv[argi]);
952             if (!Glib::path_is_absolute(path))
953                 path = Glib::build_filename(Glib::get_current_dir(), path);
954             menu_url = Glib::filename_to_uri(path);             
955         }
956         if (!preview_mode)
957             output_dir = argv[argi + 1];
958
959         // Initialise Mozilla
960         browser_widget::initialiser browser_init;
961         set_browser_preferences();
962         if (!preview_mode)
963             null_prompt_service::install();
964
965         // Run the browser/converter
966         videolink_window window(frame_params, menu_url, output_dir, encoder);
967         window.show();
968         window.signal_hide().connect(SigC::slot(&Gtk::Main::quit));
969         Gtk::Main::run();
970
971         return ((preview_mode || window.is_finished())
972                 ? EXIT_SUCCESS
973                 : EXIT_FAILURE);
974     }
975     catch (std::exception & e)
976     {
977         std::cerr << "Fatal error: " << e.what() << "\n";
978         return EXIT_FAILURE;
979     }
980 }