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