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