OSDN Git Service

LinGui: add CFR option for "Same as source" framerate.
[handbrake-jp/handbrake-jp-git.git] / gtk / src / callbacks.c
1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
2 /*
3  * callbacks.c
4  * Copyright (C) John Stebbins 2008-2011 <stebbins@stebbins>
5  * 
6  * callbacks.c is free software.
7  * 
8  * You may redistribute it and/or modify it under the terms of the
9  * GNU General Public License, as published by the Free Software
10  * Foundation; either version 2 of the License, or (at your option)
11  * any later version.
12  */
13
14 #ifdef HAVE_CONFIG_H
15 #  include <config.h>
16 #endif
17
18 #include <string.h>
19 #include <fcntl.h>
20 #include <sys/stat.h>
21 #include <time.h>
22
23 #if !defined(_WIN32)
24 #include <poll.h>
25 #define G_UDEV_API_IS_SUBJECT_TO_CHANGE 1
26 #include <gudev/gudev.h>
27 #include <dbus/dbus-glib.h>
28 #include <dbus/dbus-glib-lowlevel.h>
29
30 #include <netinet/in.h>
31 #include <netdb.h>
32
33 #if !defined(_NO_UPDATE_CHECK)
34 #if defined(_OLD_WEBKIT)
35 #include <webkit.h>
36 #else
37 #include <webkit/webkit.h>
38 #endif
39 #endif
40
41 #include <libnotify/notify.h>
42 #include <gdk/gdkx.h>
43 #else
44 #define WINVER 0x0500
45 #include <winsock2.h>
46 #include <dbt.h>
47 #endif
48
49 #include <gtk/gtk.h>
50 #include <gdk/gdkkeysyms.h>
51 #include <glib/gstdio.h>
52 #include <gio/gio.h>
53
54 #include "hb.h"
55 #include "callbacks.h"
56 #include "queuehandler.h"
57 #include "audiohandler.h"
58 #include "subtitlehandler.h"
59 #include "resources.h"
60 #include "settings.h"
61 #include "presets.h"
62 #include "preview.h"
63 #include "values.h"
64 #include "plist.h"
65 #include "appcast.h"
66 #include "hb-backend.h"
67 #include "ghb-dvd.h"
68 #include "ghbcellrenderertext.h"
69
70 static void reset_chapter_list(signal_user_data_t *ud, GValue *settings);
71 static void update_chapter_list(signal_user_data_t *ud);
72 static GList* dvd_device_list();
73 static void prune_logs(signal_user_data_t *ud);
74 void ghb_notify_done(signal_user_data_t *ud);
75 gpointer ghb_check_update(signal_user_data_t *ud);
76 static gboolean ghb_can_shutdown_gsm();
77 static void ghb_shutdown_gsm();
78 static gboolean ghb_can_suspend_gpm();
79 static void ghb_suspend_gpm();
80 static gboolean appcast_busy = FALSE;
81
82 // This is a dependency map used for greying widgets
83 // that are dependent on the state of another widget.
84 // The enable_value comes from the values that are
85 // obtained from ghb_widget_value().  For combo boxes
86 // you will have to look further to combo box options
87 // maps in hb-backend.c
88
89 GValue *dep_map;
90 GValue *rev_map;
91
92 void
93 ghb_init_dep_map()
94 {
95         dep_map = ghb_resource_get("widget-deps");
96         rev_map = ghb_resource_get("widget-reverse-deps");
97 }
98
99 static gboolean
100 dep_check(signal_user_data_t *ud, const gchar *name, gboolean *out_hide)
101 {
102         GtkWidget *widget;
103         GObject *dep_object;
104         gint ii;
105         gint count;
106         gboolean result = TRUE;
107         GValue *array, *data;
108         gchar *widget_name;
109         
110         g_debug("dep_check () %s", name);
111
112         if (rev_map == NULL) return TRUE;
113         array = ghb_dict_lookup(rev_map, name);
114         count = ghb_array_len(array);
115         *out_hide = FALSE;
116         for (ii = 0; ii < count; ii++)
117         {
118                 data = ghb_array_get_nth(array, ii);
119                 widget_name = ghb_value_string(ghb_array_get_nth(data, 0));
120                 widget = GHB_WIDGET(ud->builder, widget_name);
121                 dep_object = gtk_builder_get_object(ud->builder, name);
122                 if (widget != NULL && !GTK_WIDGET_SENSITIVE(widget))
123                         continue;
124                 if (dep_object == NULL)
125                 {
126                         g_message("Failed to find widget");
127                 }
128                 else
129                 {
130                         gchar *value;
131                         gint jj = 0;
132                         gchar **values;
133                         gboolean sensitive = FALSE;
134                         gboolean die, hide;
135
136                         die = ghb_value_boolean(ghb_array_get_nth(data, 2));
137                         hide = ghb_value_boolean(ghb_array_get_nth(data, 3));
138                         value = ghb_value_string(ghb_array_get_nth(data, 1));
139                         values = g_strsplit(value, "|", 10);
140                         g_free(value);
141
142                         if (widget)
143                                 value = ghb_widget_string(widget);
144                         else
145                                 value = ghb_settings_get_string(ud->settings, widget_name);
146                         while (values && values[jj])
147                         {
148                                 if (values[jj][0] == '>')
149                                 {
150                                         gdouble dbl = g_strtod (&values[jj][1], NULL);
151                                         gdouble dvalue = ghb_widget_double(widget);
152                                         if (dvalue > dbl)
153                                         {
154                                                 sensitive = TRUE;
155                                                 break;
156                                         }
157                                 }
158                                 else if (values[jj][0] == '<')
159                                 {
160                                         gdouble dbl = g_strtod (&values[jj][1], NULL);
161                                         gdouble dvalue = ghb_widget_double(widget);
162                                         if (dvalue < dbl)
163                                         {
164                                                 sensitive = TRUE;
165                                                 break;
166                                         }
167                                 }
168                                 if (strcmp(values[jj], value) == 0)
169                                 {
170                                         sensitive = TRUE;
171                                         break;
172                                 }
173                                 jj++;
174                         }
175                         sensitive = die ^ sensitive;
176                         if (!sensitive)
177                         {
178                                 result = FALSE;
179                                 *out_hide |= hide;
180                         }
181                         g_strfreev (values);
182                         g_free(value);
183                 }
184                 g_free(widget_name);
185         }
186         return result;
187 }
188
189 void
190 ghb_check_dependency(
191         signal_user_data_t *ud, 
192         GtkWidget *widget, 
193         const char *alt_name)
194 {
195         GObject *dep_object;
196         const gchar *name;
197         GValue *array, *data;
198         gint count, ii;
199         gchar *dep_name;
200         GType type;
201
202         if (widget != NULL)
203         {
204                 type = GTK_WIDGET_TYPE(widget);
205                 if (type == GTK_TYPE_COMBO_BOX || type == GTK_TYPE_COMBO_BOX_ENTRY)
206                         if (gtk_combo_box_get_active(GTK_COMBO_BOX(widget)) < 0) return;
207                 name = ghb_get_setting_key(widget);
208         }
209         else
210                 name = alt_name;
211
212         g_debug("ghb_check_dependency () %s", name);
213
214         if (dep_map == NULL) return;
215         array = ghb_dict_lookup(dep_map, name);
216         count = ghb_array_len(array);
217         for (ii = 0; ii < count; ii++)
218         {
219                 gboolean sensitive;
220                 gboolean hide;
221
222                 data = ghb_array_get_nth(array, ii);
223                 dep_name = ghb_value_string(data);
224                 dep_object = gtk_builder_get_object(ud->builder, dep_name);
225                 if (dep_object == NULL)
226                 {
227                         g_message("Failed to find dependent widget %s", dep_name);
228                         g_free(dep_name);
229                         continue;
230                 }
231                 sensitive = dep_check(ud, dep_name, &hide);
232                 g_free(dep_name);
233                 if (GTK_IS_ACTION(dep_object))
234                 {
235                         gtk_action_set_sensitive(GTK_ACTION(dep_object), sensitive);
236                         gtk_action_set_visible(GTK_ACTION(dep_object), sensitive || !hide);
237                 }
238                 else
239                 {
240                         gtk_widget_set_sensitive(GTK_WIDGET(dep_object), sensitive);
241                         if (!sensitive && hide)
242                         {
243                                 gtk_widget_hide(GTK_WIDGET(dep_object));
244                         }
245                         else
246                         {
247                                 gtk_widget_show_now(GTK_WIDGET(dep_object));
248                         }
249                 }
250         }
251 }
252
253 void
254 ghb_check_all_depencencies(signal_user_data_t *ud)
255 {
256         GHashTableIter iter;
257         gchar *dep_name;
258         GValue *value;
259         GObject *dep_object;
260
261         g_debug("ghb_check_all_depencencies ()");
262         if (rev_map == NULL) return;
263         ghb_dict_iter_init(&iter, rev_map);
264         // middle (void*) cast prevents gcc warning "defreferencing type-punned
265         // pointer will break strict-aliasing rules"
266         while (g_hash_table_iter_next(
267                         &iter, (gpointer*)(void*)&dep_name, (gpointer*)(void*)&value))
268         {
269                 gboolean sensitive;
270                 gboolean hide;
271
272                 dep_object = gtk_builder_get_object (ud->builder, dep_name);
273                 if (dep_object == NULL)
274                 {
275                         g_message("Failed to find dependent widget %s", dep_name);
276                         continue;
277                 }
278                 sensitive = dep_check(ud, dep_name, &hide);
279                 if (GTK_IS_ACTION(dep_object))
280                 {
281                         gtk_action_set_sensitive(GTK_ACTION(dep_object), sensitive);
282                         gtk_action_set_visible(GTK_ACTION(dep_object), sensitive || !hide);
283                 }
284                 else
285                 {
286                         gtk_widget_set_sensitive(GTK_WIDGET(dep_object), sensitive);
287                         if (!sensitive && hide)
288                         {
289                                 gtk_widget_hide(GTK_WIDGET(dep_object));
290                         }
291                         else
292                         {
293                                 gtk_widget_show_now(GTK_WIDGET(dep_object));
294                         }
295                 }
296         }
297 }
298
299 G_MODULE_EXPORT void
300 on_quit1_activate(GtkMenuItem *quit, signal_user_data_t *ud)
301 {
302         gint state = ghb_get_queue_state();
303         g_debug("on_quit1_activate ()");
304         if (state & (GHB_STATE_WORKING|GHB_STATE_SEARCHING))
305         {
306                 if (ghb_cancel_encode2(ud, "Closing HandBrake will terminate encoding.\n"))
307                 {
308                         ghb_hb_cleanup(FALSE);
309                         prune_logs(ud);
310                         gtk_main_quit();
311                         return;
312                 }
313                 return;
314         }
315         ghb_hb_cleanup(FALSE);
316         prune_logs(ud);
317         gtk_main_quit();
318 }
319
320 gboolean
321 uppers_and_unders(gchar *str)
322 {
323         if (str == NULL) return FALSE;
324         str = g_strchomp(g_strchug(str));
325         while (*str)
326         {
327                 if (*str == ' ')
328                 {
329                         return FALSE;
330                 }
331                 if (*str >= 'a' && *str <= 'z')
332                 {
333                         return FALSE;
334                 }
335                 str++;
336         }
337         return TRUE;
338 }
339
340 enum
341 {
342         CAMEL_FIRST_UPPER,
343         CAMEL_OTHER
344 };
345
346 void
347 camel_convert(gchar *str)
348 {
349         gint state = CAMEL_OTHER;
350         
351         if (str == NULL) return;
352         while (*str)
353         {
354                 if (*str == '_') *str = ' ';
355                 switch (state)
356                 {
357                         case CAMEL_OTHER:
358                         {
359                                 if (*str >= 'A' && *str <= 'Z')
360                                         state = CAMEL_FIRST_UPPER;
361                                 else
362                                         state = CAMEL_OTHER;
363                                 
364                         } break;
365                         case CAMEL_FIRST_UPPER:
366                         {
367                                 if (*str >= 'A' && *str <= 'Z')
368                                         *str = *str - 'A' + 'a';
369                                 else
370                                         state = CAMEL_OTHER;
371                         } break;
372                 }
373                 str++;
374         }
375 }
376
377 #if defined(_WIN32)
378 static gchar*
379 get_dvd_device_name(gchar *device)
380 {
381         return g_strdup(device);
382 }
383 #else
384 static gchar*
385 get_dvd_device_name(GDrive *gd)
386 {
387         return g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
388 }
389 #endif
390
391 static GHashTable *volname_hash = NULL;
392 static GMutex     *volname_mutex = NULL;
393
394 static void
395 free_volname_key(gpointer data)
396 {
397         if (data != NULL)
398                 g_free(data);
399 }
400
401 static void
402 free_volname_value(gpointer data)
403 {
404         if (data != NULL)
405                 g_free(data);
406 }
407
408 #if defined(_WIN32)
409 static gchar*
410 get_direct_dvd_volume_name(const gchar *drive)
411 {
412         gchar *result = NULL;
413         gchar vname[51], fsname[51];
414
415         if (GetVolumeInformation(drive, vname, 50, NULL, NULL, NULL, fsname, 50))
416         {
417                 result = g_strdup_printf("%s", vname);
418         }
419         return result;
420 }
421 #else
422 static gchar*
423 get_direct_dvd_volume_name(const gchar *drive)
424 {
425         gchar *result;
426
427         result = ghb_dvd_volname (drive);
428         return result;
429 }
430 #endif
431
432 static gchar*
433 get_dvd_volume_name(gpointer gd)
434 {
435         gchar *label = NULL;
436         gchar *result;
437         gchar *drive;
438
439         drive = get_dvd_device_name(gd);
440         g_mutex_lock(volname_mutex);
441         label = g_strdup(g_hash_table_lookup(volname_hash, drive));
442         g_mutex_unlock(volname_mutex);
443         if (label != NULL)
444         {
445                 if (uppers_and_unders(label))
446                 {
447                         camel_convert(label);
448                 }
449 #if defined(_WIN32)
450                 result = g_strdup_printf("%s (%s)", label, drive);
451 #else
452                 result = g_strdup_printf("%s - %s", drive, label);
453 #endif
454                 g_free(label);
455         }
456         else
457         {
458                 result = g_strdup_printf("%s", drive);
459         }
460         g_free(drive);
461         return result;
462 }
463
464 void
465 ghb_volname_cache_init(void)
466 {
467         volname_mutex = g_mutex_new();
468         volname_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
469                                                                                 free_volname_key, free_volname_value);
470 }
471
472 static void
473 free_drive(gpointer drive)
474 {
475 #if defined(_WIN32)
476                 g_free(drive);
477 #else
478                 g_object_unref(drive);
479 #endif
480 }
481
482 gpointer
483 ghb_cache_volnames(signal_user_data_t *ud)
484 {
485         GList *link, *drives;
486
487         g_debug("ghb_cache_volnames()");
488         link = drives = dvd_device_list();
489         if (drives == NULL)
490                 return NULL;
491
492         g_mutex_lock(volname_mutex);
493         g_hash_table_remove_all(volname_hash);
494         while (link != NULL)
495         {
496                 gchar *name, *drive;
497
498 #if !defined(_WIN32)
499                 if (!g_drive_has_media (link->data))
500                 {
501                         g_object_unref(link->data);
502                         link = link->next;
503                         continue;
504                 }
505 #endif
506                 drive = get_dvd_device_name(link->data);
507                 name = get_direct_dvd_volume_name(drive);
508
509                 if (drive != NULL && name != NULL)
510                 {
511                         g_hash_table_insert(volname_hash, drive, name);
512                 }
513                 else
514                 {
515                         if (drive != NULL)
516                                 g_free(drive);
517                         if (name != NULL)
518                                 g_free(name);
519                 }
520         
521                 free_drive(link->data);
522                 link = link->next;
523         }
524         g_mutex_unlock(volname_mutex);
525
526         g_list_free(drives);
527
528         g_idle_add((GSourceFunc)ghb_file_menu_add_dvd, ud);
529
530         return NULL;
531 }
532
533 static const gchar*
534 get_extension(signal_user_data_t *ud)
535 {
536         int container;
537         const gchar *extension = "error";
538         GValue *audio_list;
539         GValue *subtitle_list;
540
541         container = ghb_settings_combo_int(ud->settings, "FileFormat");
542         if (container == HB_MUX_MP4)
543         {
544                 extension = "mp4";
545                 audio_list = ghb_settings_get_value(ud->settings, "audio_list");
546                 subtitle_list = ghb_settings_get_value(ud->settings, "subtitle_list");
547                 if (ghb_ac3_in_audio_list(audio_list) ||
548                         ghb_soft_in_subtitle_list(subtitle_list) ||
549                         ghb_settings_get_boolean(ud->settings, "ChapterMarkers") ||
550                         ghb_settings_get_boolean(ud->settings, "UseM4v"))
551                 {
552                         extension = "m4v";
553                 }
554         }
555         else if (container == HB_MUX_MKV)
556         {
557                 extension = "mkv";
558         }
559         return extension;
560 }
561
562 static void
563 set_destination(signal_user_data_t *ud)
564 {
565         g_debug("set_destination");
566         if (ghb_settings_get_boolean(ud->settings, "use_source_name"))
567         {
568                 GString *str = g_string_new("");
569                 gchar *vol_name, *filename;
570                 const gchar *extension;
571                 gchar *new_name;
572                 gint title;
573                 
574                 filename = ghb_settings_get_string(ud->settings, "dest_file");
575                 extension = get_extension(ud);
576                 vol_name = ghb_settings_get_string(ud->settings, "volume_label");
577                 g_string_append_printf(str, "%s", vol_name);
578                 title = ghb_settings_combo_int(ud->settings, "title");
579                 if (title >= 0)
580                 {
581                         if (ghb_settings_get_boolean(
582                                         ud->settings, "title_no_in_destination"))
583                         {
584
585                                 title = ghb_settings_combo_int(ud->settings, "title");
586                                 g_string_append_printf(str, " - %d", title+1);
587                         }
588                         if (ghb_settings_combo_int(ud->settings, "PtoPType") == 0 && 
589                                 ghb_settings_get_boolean(
590                                         ud->settings, "chapters_in_destination"))
591                         {
592                                 gint start, end;
593
594                                 if (!ghb_settings_get_boolean(
595                                                 ud->settings, "title_no_in_destination"))
596                                 {
597                                         g_string_append_printf(str, " -");
598                                 }
599                                 start = ghb_settings_get_int(ud->settings, "start_point");
600                                 end = ghb_settings_get_int(ud->settings, "end_point");
601                                 if (start == end)
602                                         g_string_append_printf(str, " Ch %d", start);
603                                 else
604                                         g_string_append_printf(str, " Ch %d-%d", start, end);
605                         }
606                 }
607                 g_string_append_printf(str, ".%s", extension);
608                 new_name = g_string_free(str, FALSE);
609                 ghb_ui_update(ud, "dest_file", ghb_string_value(new_name));
610                 g_free(filename);
611                 g_free(vol_name);
612                 g_free(new_name);
613         }
614 }
615
616 static gchar*
617 get_file_label(const gchar *filename)
618 {
619         gchar *base, *pos, *end;
620
621         base = g_path_get_basename(filename);
622         pos = strrchr(base, '.');
623         if (pos != NULL)
624         {
625                 // If the last '.' is within 4 chars of end of name, assume
626                 // there is an extension we want to strip.
627                 end = &base[strlen(base) - 1];
628                 if (end - pos <= 4)
629                         *pos = 0;
630         }
631         return base;
632 }
633
634 static gchar*
635 resolve_drive_name(gchar *filename)
636 {
637 #if defined(_WIN32)
638         if (filename[1] == ':')
639         {
640                 gchar drive[4];
641                 gchar *name;
642                 gint dtype;
643
644                 g_strlcpy(drive, filename, 4);
645                 dtype = GetDriveType(drive);
646                 if (dtype == DRIVE_CDROM)
647                 {
648                         gchar vname[51], fsname[51];
649                         GetVolumeInformation(drive, vname, 50, NULL, 
650                                                                 NULL, NULL, fsname, 50);
651                         name = g_strdup(vname);
652                         return name;
653                 }
654         }
655         return NULL;
656 #else
657         return NULL;
658 #endif
659 }
660
661 static gboolean
662 update_source_label(signal_user_data_t *ud, const gchar *source, gboolean update_dest)
663 {
664         gchar *label = NULL;
665         gint len;
666         gchar **path;
667         gchar *start;
668         gchar *filename = g_strdup(source);
669         
670         g_debug("update_source_label()");
671         len = strlen(filename);
672         if (g_file_test(filename, G_FILE_TEST_IS_DIR))
673         {
674                 // Skip dos drive letters
675 #if defined(_WIN32)
676                 start = strchr(filename, ':');
677 #else
678                 start = filename;
679 #endif
680                 label = resolve_drive_name(filename);
681                 if (label != NULL)
682                 {
683                         if (uppers_and_unders(label))
684                         {
685                                 camel_convert(label);
686                         }
687                 }
688                 else
689                 {
690                         if (filename[len-1] == G_DIR_SEPARATOR) filename[len-1] = 0;
691                         if (start != NULL)
692                                 start++;
693                         else
694                                 start = filename;
695                         
696                         path = g_strsplit(start, G_DIR_SEPARATOR_S, -1);
697                         len = g_strv_length (path);
698                         if ((len > 1) && (strcmp("VIDEO_TS", path[len-1]) == 0))
699                         {
700                                 label = g_strdup(path[len-2]);
701                                 if (uppers_and_unders(label))
702                                 {
703                                         camel_convert(label);
704                                 }
705                         }
706                         else if (len > 0)
707                         {
708                                 if (path[len-1][0] != 0)
709                                 {
710                                         label = g_strdup(path[len-1]);
711                                         if (uppers_and_unders(label))
712                                         {
713                                                 camel_convert(label);
714                                         }
715                                 }
716                                 else
717                                         label = g_strdup("new_video");
718                         }
719                         else
720                                 label = g_strdup("new_video");
721                         g_strfreev (path);
722                 }
723         }
724         else
725         {
726                 // Is regular file or block dev.
727                 // Check to see if it is a dvd image
728                 label = ghb_dvd_volname (filename);
729                 if (label == NULL)
730                 {
731                         label = get_file_label(filename);
732                 }
733                 else
734                 {
735                         if (uppers_and_unders(label))
736                         {
737                                 camel_convert(label);
738                         }
739                 }
740         }
741         g_free(filename);
742         GtkWidget *widget = GHB_WIDGET (ud->builder, "source_title");
743         if (label != NULL)
744         {
745                 gtk_label_set_text (GTK_LABEL(widget), label);
746                 ghb_settings_set_string(ud->settings, "volume_label", label);
747                 g_free(label);
748                 if (update_dest)
749                         set_destination(ud);
750         }
751         else
752         {
753                 label = "No Title Found";
754                 gtk_label_set_text (GTK_LABEL(widget), label);
755                 ghb_settings_set_string(ud->settings, "volume_label", label);
756                 return FALSE;
757         }
758         return TRUE;
759 }
760
761 G_MODULE_EXPORT void
762 chooser_file_selected_cb(GtkFileChooser *dialog, signal_user_data_t *ud)
763 {
764         gchar *name = gtk_file_chooser_get_filename (dialog);
765         GtkTreeModel *store;
766         GtkTreeIter iter;
767         const gchar *device;
768         gboolean foundit = FALSE;
769         GtkComboBox *combo;
770         
771         g_debug("chooser_file_selected_cb ()");
772
773         if (name == NULL) return;
774         combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, "source_device"));
775         store = gtk_combo_box_get_model(combo);
776         if (gtk_tree_model_get_iter_first(store, &iter))
777         {
778                 do
779                 {
780                         gtk_tree_model_get(store, &iter, 0, &device, -1);
781                         if (strcmp(name, device) == 0)
782                         {
783                                 foundit = TRUE;
784                                 break;
785                         }
786                 } while (gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter));
787         }
788         if (foundit)
789                 gtk_combo_box_set_active_iter (combo, &iter);
790         else
791                 gtk_combo_box_set_active (combo, 0);
792
793         g_free(name);
794 }
795
796 G_MODULE_EXPORT void
797 dvd_device_changed_cb(GtkComboBox *combo, signal_user_data_t *ud)
798 {
799         GtkWidget *dialog;
800         gint ii;
801
802         g_debug("dvd_device_changed_cb ()");
803         ii = gtk_combo_box_get_active (combo);
804         if (ii > 0)
805         {
806                 const gchar *device;
807                 gchar *name;
808
809                 dialog = GHB_WIDGET(ud->builder, "source_dialog");
810                 device = gtk_combo_box_get_active_text (combo);
811                 name = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(dialog));
812                 if (name == NULL || strcmp(name, device) != 0)
813                         gtk_file_chooser_select_filename (GTK_FILE_CHOOSER(dialog), device);
814                 if (name != NULL)
815                         g_free(name);
816         }
817 }
818
819 static void
820 source_dialog_extra_widgets(
821         signal_user_data_t *ud,
822         GtkWidget *dialog)
823 {
824         GtkComboBox *combo;
825         GList *drives, *link;
826         
827         g_debug("source_dialog_extra_widgets ()");
828         combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, "source_device"));
829         gtk_list_store_clear(GTK_LIST_STORE(gtk_combo_box_get_model(combo)));
830
831         link = drives = dvd_device_list();
832         gtk_combo_box_append_text (combo, "Not Selected");
833         while (link != NULL)
834         {
835                 gchar *name = get_dvd_device_name(link->data);
836                 gtk_combo_box_append_text(combo, name);
837                 g_free(name);
838                 free_drive(link->data);
839                 link = link->next;
840         }
841         g_list_free(drives);
842         gtk_combo_box_set_active (combo, 0);
843 }
844
845 extern GValue *ghb_queue_edit_settings;
846 static gchar *last_scan_file = NULL;
847
848 static void 
849 show_scan_progress(signal_user_data_t *ud)
850 {
851         GtkProgressBar *progress;
852         GtkLabel *label;
853
854         progress = GTK_PROGRESS_BAR(GHB_WIDGET(ud->builder, "scan_prog"));
855         gtk_progress_bar_set_fraction (progress, 0);
856         gtk_widget_show(GTK_WIDGET(progress));
857
858         label = GTK_LABEL(GHB_WIDGET(ud->builder, "source_title"));
859         gtk_label_set_text( label, "Scanning ..." );
860 }
861
862 static void
863 start_scan(
864         signal_user_data_t *ud, 
865         const gchar *path, 
866         gint titlenum, 
867         gint preview_count)
868 {
869         GtkWidget *widget;
870         GtkAction *action;
871         ghb_status_t status;
872
873         ghb_get_status(&status);
874         if (status.scan.state != GHB_STATE_IDLE)
875                 return;
876
877         widget = GHB_WIDGET(ud->builder, "sourcetoolbutton");
878         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(widget), "hb-stop");
879         gtk_tool_button_set_label(GTK_TOOL_BUTTON(widget), "Stop Scan");
880         gtk_tool_item_set_tooltip_text(GTK_TOOL_ITEM(widget), "Stop Scan");
881         //gtk_widget_set_sensitive(widget, FALSE);
882
883         action = GHB_ACTION(ud->builder, "source_action");
884         gtk_action_set_sensitive(action, FALSE);
885         action = GHB_ACTION(ud->builder, "source_single_action");
886         gtk_action_set_sensitive(action, FALSE);
887         ghb_backend_scan(path, titlenum, preview_count, 
888                         90000L * ghb_settings_get_int64(ud->settings, "MinTitleDuration"));
889 }
890
891 gboolean
892 ghb_idle_scan(signal_user_data_t *ud)
893 {
894         gchar *path;
895         gint preview_count;
896
897         show_scan_progress(ud);
898         path = ghb_settings_get_string( ud->settings, "scan_source");
899         prune_logs(ud);
900
901         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
902         start_scan(ud, path, 0, preview_count);
903         g_free(path);
904         return FALSE;
905 }
906
907 void
908 ghb_do_scan(
909         signal_user_data_t *ud, 
910         const gchar *filename, 
911         gint titlenum, 
912         gboolean force)
913 {
914         g_debug("ghb_do_scan()");
915         if (!force && last_scan_file != NULL &&
916                 strcmp(last_scan_file, filename) == 0)
917         {
918                 if (ghb_queue_edit_settings)
919                 {
920                         ghb_settings_to_ui(ud, ghb_queue_edit_settings);
921                         ghb_set_audio(ud, ghb_queue_edit_settings);
922                         ghb_reset_subtitles(ud, ghb_queue_edit_settings);
923                         reset_chapter_list(ud, ghb_queue_edit_settings);
924                         ghb_value_free(ghb_queue_edit_settings);
925                         ghb_queue_edit_settings = NULL;
926                 }
927                 return;
928         }
929         if (last_scan_file != NULL)
930                 g_free(last_scan_file);
931         last_scan_file = NULL;
932         if (filename != NULL)
933         {
934                 last_scan_file = g_strdup(filename);
935                 ghb_settings_set_string(ud->settings, "scan_source", filename);
936                 if (update_source_label(ud, filename, TRUE))
937                 {
938                         gchar *path;
939                         gint preview_count;
940
941                         show_scan_progress(ud);
942                         path = ghb_settings_get_string( ud->settings, "scan_source");
943                         prune_logs(ud);
944
945                         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
946                         start_scan(ud, path, titlenum, preview_count);
947                         g_free(path);
948                 }
949                 else
950                 {
951                         // TODO: error dialog
952                 }
953         }
954 }
955
956 static void
957 do_source_dialog(GtkButton *button, gboolean single, signal_user_data_t *ud)
958 {
959         GtkWidget *dialog;
960         gchar *sourcename;
961         gint    response;
962
963         g_debug("source_browse_clicked_cb ()");
964         sourcename = ghb_settings_get_string(ud->settings, "scan_source");
965         GtkWidget *widget;
966         widget = GHB_WIDGET(ud->builder, "single_title_box");
967         if (single)
968                 gtk_widget_show(widget);
969         else
970                 gtk_widget_hide(widget);
971         dialog = GHB_WIDGET(ud->builder, "source_dialog");
972         source_dialog_extra_widgets(ud, dialog);
973         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), sourcename);
974         response = gtk_dialog_run(GTK_DIALOG (dialog));
975         gtk_widget_hide(dialog);
976         if (response == GTK_RESPONSE_NO)
977         {
978                 gchar *filename;
979
980                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
981                 if (filename != NULL)
982                 {
983                         gint titlenum;
984
985                         if (single)
986                                 titlenum = ghb_settings_get_int(ud->settings, "single_title");
987                         else
988                                 titlenum = 0;
989                         ghb_do_scan(ud, filename, titlenum, TRUE);
990                         if (strcmp(sourcename, filename) != 0)
991                         {
992                                 ghb_settings_set_string (ud->settings, 
993                                                                                 "default_source", filename);
994                                 ghb_pref_save (ud->settings, "default_source");
995                                 ghb_dvd_set_current (filename, ud);
996                         }
997                         g_free(filename);
998                 }
999         }
1000         g_free(sourcename);
1001 }
1002
1003 G_MODULE_EXPORT void
1004 source_button_clicked_cb(GtkButton *button, signal_user_data_t *ud)
1005 {
1006         ghb_status_t status;
1007         ghb_get_status(&status);
1008         if (status.scan.state & GHB_STATE_SCANNING)
1009         {
1010                 ghb_backend_scan_stop();
1011         }
1012         else
1013         {
1014                 do_source_dialog(button, FALSE, ud);
1015         }
1016 }
1017
1018 G_MODULE_EXPORT void
1019 single_title_source_cb(GtkButton *button, signal_user_data_t *ud)
1020 {
1021         do_source_dialog(button, TRUE, ud);
1022 }
1023
1024 G_MODULE_EXPORT void
1025 dvd_source_activate_cb(GtkAction *action, signal_user_data_t *ud)
1026 {
1027         const gchar *filename;
1028         gchar *sourcename;
1029
1030         sourcename = ghb_settings_get_string(ud->settings, "scan_source");
1031         filename = gtk_buildable_get_name(GTK_BUILDABLE(action));
1032         ghb_do_scan(ud, filename, 0, TRUE);
1033         if (strcmp(sourcename, filename) != 0)
1034         {
1035                 ghb_settings_set_string (ud->settings, "default_source", filename);
1036                 ghb_pref_save (ud->settings, "default_source");
1037                 ghb_dvd_set_current (filename, ud);
1038         }
1039         g_free(sourcename);
1040 }
1041
1042 void
1043 ghb_update_destination_extension(signal_user_data_t *ud)
1044 {
1045         static gchar *containers[] = {".mkv", ".mp4", ".m4v", NULL};
1046         gchar *filename;
1047         const gchar *extension;
1048         gint ii;
1049         GtkEntry *entry;
1050         static gboolean busy = FALSE;
1051
1052         g_debug("ghb_update_destination_extension ()");
1053         // Since this function modifies the thing that triggers it's
1054         // invocation, check to see if busy to prevent accidental infinite
1055         // recursion.
1056         if (busy)
1057                 return;
1058         busy = TRUE;
1059         extension = get_extension(ud);
1060         entry = GTK_ENTRY(GHB_WIDGET(ud->builder, "dest_file"));
1061         filename = g_strdup(gtk_entry_get_text(entry));
1062         for (ii = 0; containers[ii] != NULL; ii++)
1063         {
1064                 if (g_str_has_suffix(filename, containers[ii]))
1065                 {
1066                         gchar *pos;
1067                         gchar *new_name;
1068                         
1069                         pos = g_strrstr( filename, "." );
1070                         if (pos == NULL)
1071                         {
1072                                 // No period? shouldn't happen
1073                                 break;
1074                         }
1075                         *pos = 0;
1076                         if (strcmp(extension, &pos[1]) == 0)
1077                         {
1078                                 // Extension is already correct
1079                                 break;
1080                         }
1081                         new_name = g_strjoin(".", filename, extension, NULL); 
1082                         ghb_ui_update(ud, "dest_file", ghb_string_value(new_name));
1083                         g_free(new_name);
1084                         break;
1085                 }
1086         }
1087         g_free(filename);
1088         busy = FALSE;
1089 }
1090
1091 static void
1092 destination_select_title(GtkEntry *entry)
1093 {
1094         const gchar *dest;
1095         gint start, end;
1096
1097         dest = gtk_entry_get_text(entry);
1098         for (end = strlen(dest)-1; end > 0; end--)
1099         {
1100                 if (dest[end] == '.')
1101                 {
1102                         break;
1103                 }
1104         }
1105         for (start = end; start >= 0; start--)
1106         {
1107                 if (dest[start] == G_DIR_SEPARATOR)
1108                 {
1109                         start++;
1110                         break;
1111                 }
1112         }
1113         if (start < 0) start = 0;
1114         if (start < end)
1115         {
1116                 gtk_editable_select_region(GTK_EDITABLE(entry), start, end);
1117         }
1118 }
1119
1120 G_MODULE_EXPORT gboolean
1121 destination_grab_cb(
1122         GtkEntry *entry, 
1123         signal_user_data_t *ud)
1124 {
1125         destination_select_title(entry);
1126         return FALSE;
1127 }
1128
1129 static gboolean update_default_destination = FALSE;
1130
1131 G_MODULE_EXPORT void
1132 dest_dir_set_cb(GtkFileChooserButton *dest_chooser, signal_user_data_t *ud)
1133 {
1134         gchar *dest_file, *dest_dir, *dest;
1135         
1136         g_debug("dest_dir_set_cb ()");
1137         ghb_widget_to_setting(ud->settings, (GtkWidget*)dest_chooser);
1138         dest_file = ghb_settings_get_string(ud->settings, "dest_file");
1139         dest_dir = ghb_settings_get_string(ud->settings, "dest_dir");
1140         dest = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", dest_dir, dest_file);
1141         ghb_settings_set_string(ud->settings, "destination", dest);
1142         g_free(dest_file);
1143         g_free(dest_dir);
1144         g_free(dest);
1145         update_default_destination = TRUE;
1146 }
1147
1148 G_MODULE_EXPORT void
1149 dest_file_changed_cb(GtkEntry *entry, signal_user_data_t *ud)
1150 {
1151         gchar *dest_file, *dest_dir, *dest;
1152         
1153         g_debug("dest_file_changed_cb ()");
1154         ghb_update_destination_extension(ud);
1155         ghb_widget_to_setting(ud->settings, (GtkWidget*)entry);
1156         // This signal goes off with ever keystroke, so I'm putting this
1157         // update on the timer.
1158         dest_file = ghb_settings_get_string(ud->settings, "dest_file");
1159         dest_dir = ghb_settings_get_string(ud->settings, "dest_dir");
1160         dest = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", dest_dir, dest_file);
1161         ghb_settings_set_string(ud->settings, "destination", dest);
1162         g_free(dest_file);
1163         g_free(dest_dir);
1164         g_free(dest);
1165         update_default_destination = TRUE;
1166 }
1167
1168 G_MODULE_EXPORT void
1169 destination_browse_clicked_cb(GtkButton *button, signal_user_data_t *ud)
1170 {
1171         GtkWidget *dialog;
1172         GtkEntry *entry;
1173         gchar *destname;
1174         gchar *basename;
1175
1176         g_debug("destination_browse_clicked_cb ()");
1177         destname = ghb_settings_get_string(ud->settings, "destination");
1178         dialog = gtk_file_chooser_dialog_new ("Choose Destination",
1179                                           NULL,
1180                                           GTK_FILE_CHOOSER_ACTION_SAVE,
1181                                           GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1182                                           GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
1183                                           NULL);
1184         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), destname);
1185         basename = g_path_get_basename(destname);
1186         g_free(destname);
1187         gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), basename);
1188         g_free(basename);
1189         if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
1190         {
1191                 char *filename, *dirname;
1192                 GtkFileChooser *dest_chooser;
1193                 
1194                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
1195                 basename = g_path_get_basename(filename);
1196                 dirname = g_path_get_dirname(filename);
1197                 entry = (GtkEntry*)GHB_WIDGET(ud->builder, "dest_file");
1198                 gtk_entry_set_text(entry, basename);
1199                 dest_chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "dest_dir"));
1200                 gtk_file_chooser_set_filename(dest_chooser, dirname);
1201                 g_free (dirname);
1202                 g_free (basename);
1203                 g_free (filename);
1204         }
1205         gtk_widget_destroy(dialog);
1206 }
1207
1208 G_MODULE_EXPORT gboolean
1209 window_destroy_event_cb(GtkWidget *widget, GdkEvent *event, signal_user_data_t *ud)
1210 {
1211         g_debug("window_destroy_event_cb ()");
1212         ghb_hb_cleanup(FALSE);
1213         prune_logs(ud);
1214         gtk_main_quit();
1215         return FALSE;
1216 }
1217
1218 G_MODULE_EXPORT gboolean
1219 window_delete_event_cb(GtkWidget *widget, GdkEvent *event, signal_user_data_t *ud)
1220 {
1221         gint state = ghb_get_queue_state();
1222         g_debug("window_delete_event_cb ()");
1223         if (state & (GHB_STATE_WORKING|GHB_STATE_SEARCHING))
1224         {
1225                 if (ghb_cancel_encode2(ud, "Closing HandBrake will terminate encoding.\n"))
1226                 {
1227                         ghb_hb_cleanup(FALSE);
1228                         prune_logs(ud);
1229                         gtk_main_quit();
1230                         return FALSE;
1231                 }
1232                 return TRUE;
1233         }
1234         ghb_hb_cleanup(FALSE);
1235         prune_logs(ud);
1236         gtk_main_quit();
1237         return FALSE;
1238 }
1239
1240 static void
1241 update_acodec_combo(signal_user_data_t *ud)
1242 {
1243         ghb_grey_combo_options (ud->builder);
1244 }
1245
1246 G_MODULE_EXPORT void
1247 container_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1248 {
1249         g_debug("container_changed_cb ()");
1250         ghb_widget_to_setting(ud->settings, widget);
1251         ghb_check_dependency(ud, widget, NULL);
1252         update_acodec_combo(ud);
1253         ghb_update_destination_extension(ud);
1254         ghb_clear_presets_selection(ud);
1255         ghb_live_reset(ud);
1256         ghb_subtitle_prune(ud);
1257         ghb_audio_list_refresh_selected(ud);
1258 }
1259
1260 static gchar*
1261 get_aspect_string(gint aspect_n, gint aspect_d)
1262 {
1263         gchar *aspect;
1264
1265         if (aspect_d < 10)
1266         {
1267                 aspect = g_strdup_printf("%d:%d", aspect_n, aspect_d);
1268         }
1269         else
1270         {
1271                 gdouble aspect_nf = (gdouble)aspect_n / aspect_d;
1272                 aspect = g_strdup_printf("%.2f:1", aspect_nf);
1273         }
1274         return aspect;
1275 }
1276
1277 static gchar*
1278 get_rate_string(gint rate_base, gint rate)
1279 {
1280         gdouble rate_f = (gdouble)rate / rate_base;
1281         gchar *rate_s;
1282
1283         rate_s = g_strdup_printf("%.6g", rate_f);
1284         return rate_s;
1285 }
1286
1287 static void
1288 update_title_duration(signal_user_data_t *ud)
1289 {
1290         gint ti;
1291         gint hh, mm, ss, start, end;
1292         gchar *text;
1293         GtkWidget *widget;
1294
1295         ti = ghb_settings_combo_int(ud->settings, "title");
1296         widget = GHB_WIDGET (ud->builder, "title_duration");
1297
1298         if (ghb_settings_combo_int(ud->settings, "PtoPType") == 0)
1299         {
1300                 start = ghb_settings_get_int(ud->settings, "start_point");
1301                 end = ghb_settings_get_int(ud->settings, "end_point");
1302                 ghb_part_duration(ti, start, end, &hh, &mm, &ss);
1303         }
1304         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 1)
1305         {
1306                 gint duration;
1307
1308                 start = ghb_settings_get_int(ud->settings, "start_point");
1309                 end = ghb_settings_get_int(ud->settings, "end_point");
1310                 duration = end - start;
1311                 hh = duration / (60*60);
1312                 mm = (duration / 60) % 60;
1313                 ss = duration % 60;
1314         }
1315         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 2)
1316         {
1317                 ghb_title_info_t tinfo;
1318
1319                 if (ghb_get_title_info (&tinfo, ti))
1320                 {
1321                         gint64 frames;
1322                         gint duration;
1323
1324                         start = ghb_settings_get_int(ud->settings, "start_point");
1325                         end = ghb_settings_get_int(ud->settings, "end_point");
1326                         frames = end - start + 1;
1327                         duration = frames * tinfo.rate_base / tinfo.rate;
1328                         hh = duration / (60*60);
1329                         mm = (duration / 60) % 60;
1330                         ss = duration % 60;
1331                 }
1332                 else
1333                 {
1334                         hh = mm = ss = 0;
1335                 }
1336         }
1337         text = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
1338         gtk_label_set_text (GTK_LABEL(widget), text);
1339         g_free(text);
1340 }
1341
1342 static void
1343 show_title_info(signal_user_data_t *ud, ghb_title_info_t *tinfo)
1344 {
1345         GtkWidget *widget;
1346         gchar *text;
1347
1348         ghb_settings_set_string(ud->settings, "source", tinfo->path);
1349         if (tinfo->type == HB_STREAM_TYPE)
1350         {
1351                 GtkWidget *widget = GHB_WIDGET (ud->builder, "source_title");
1352                 if (tinfo->name != NULL && tinfo->name[0] != 0)
1353                 {
1354                         gtk_label_set_text (GTK_LABEL(widget), tinfo->name);
1355                         ghb_settings_set_string(ud->settings, "volume_label", tinfo->name);
1356                         set_destination(ud);
1357                 }
1358                 else
1359                 {
1360                         gchar *label = "No Title Found";
1361                         gtk_label_set_text (GTK_LABEL(widget), label);
1362                         ghb_settings_set_string(ud->settings, "volume_label", label);
1363                 }
1364         }
1365         ud->dont_clear_presets = TRUE;
1366         ud->scale_busy = TRUE;
1367         update_title_duration(ud);
1368         widget = GHB_WIDGET (ud->builder, "source_dimensions");
1369         text = g_strdup_printf ("%d x %d", tinfo->width, tinfo->height);
1370         gtk_label_set_text (GTK_LABEL(widget), text);
1371         ghb_settings_set_int(ud->settings, "source_width", tinfo->width);
1372         ghb_settings_set_int(ud->settings, "source_height", tinfo->height);
1373         g_free(text);
1374         widget = GHB_WIDGET (ud->builder, "source_aspect");
1375         text = get_aspect_string(tinfo->aspect_n, tinfo->aspect_d);
1376         gtk_label_set_text (GTK_LABEL(widget), text);
1377         g_free(text);
1378
1379         widget = GHB_WIDGET (ud->builder, "source_frame_rate");
1380         text = (gchar*)get_rate_string(tinfo->rate_base, tinfo->rate);
1381         gtk_label_set_text (GTK_LABEL(widget), text);
1382         g_free(text);
1383
1384         //widget = GHB_WIDGET (ud->builder, "source_interlaced");
1385         //gtk_label_set_text (GTK_LABEL(widget), tinfo->interlaced ? "Yes" : "No");
1386
1387         ghb_ui_update(ud, "scale_width", 
1388                 ghb_int64_value(tinfo->width - tinfo->crop[2] - tinfo->crop[3]));
1389         // If anamorphic or keep_aspect, the hight will be automatically calculated
1390         gboolean keep_aspect;
1391         gint pic_par;
1392         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
1393         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
1394         if (!(keep_aspect || pic_par) || pic_par == 3)
1395         {
1396                 ghb_ui_update(ud, "scale_height", 
1397                         ghb_int64_value(tinfo->height - tinfo->crop[0] - tinfo->crop[1]));
1398         }
1399
1400         // Set the limits of cropping.  hb_set_anamorphic_size crashes if
1401         // you pass it a cropped width or height == 0.
1402         gint bound;
1403         bound = tinfo->height / 2 - 8;
1404         widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
1405         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1406         widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
1407         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1408         bound = tinfo->width / 2 - 8;
1409         widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
1410         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1411         widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
1412         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1413         if (ghb_settings_get_boolean(ud->settings, "PictureAutoCrop"))
1414         {
1415                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(tinfo->crop[0]));
1416                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(tinfo->crop[1]));
1417                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(tinfo->crop[2]));
1418                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(tinfo->crop[3]));
1419         }
1420         ud->scale_busy = FALSE;
1421         ghb_set_scale (ud, GHB_PIC_KEEP_PAR|GHB_PIC_USE_MAX);
1422         gint width, height, crop[4];
1423         crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
1424         crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
1425         crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
1426         crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
1427         width = tinfo->width - crop[2] - crop[3];
1428         height = tinfo->height - crop[0] - crop[1];
1429         widget = GHB_WIDGET (ud->builder, "crop_dimensions");
1430         text = g_strdup_printf ("%d x %d", width, height);
1431         gtk_label_set_text (GTK_LABEL(widget), text);
1432         g_free(text);
1433
1434
1435         gint duration = tinfo->duration / 90000;
1436
1437         if (ghb_settings_combo_int(ud->settings, "PtoPType") == 0)
1438         {
1439                 widget = GHB_WIDGET (ud->builder, "start_point");
1440                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo->num_chapters);
1441                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 1);
1442
1443                 widget = GHB_WIDGET (ud->builder, "end_point");
1444                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo->num_chapters);
1445                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), tinfo->num_chapters);
1446         }
1447         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 1)
1448         {
1449
1450                 widget = GHB_WIDGET (ud->builder, "start_point");
1451                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, duration-1);
1452                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 0);
1453
1454                 widget = GHB_WIDGET (ud->builder, "end_point");
1455                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, duration);
1456                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), duration);
1457         }
1458         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 2)
1459         {
1460                 gdouble max_frames = (gdouble)duration * tinfo->rate / tinfo->rate_base;
1461                 widget = GHB_WIDGET (ud->builder, "start_point");
1462                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, max_frames);
1463                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 1);
1464
1465                 widget = GHB_WIDGET (ud->builder, "end_point");
1466                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, max_frames);
1467                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), max_frames);
1468         }
1469
1470         widget = GHB_WIDGET (ud->builder, "angle");
1471         gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 1);
1472         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo->angle_count);
1473         ghb_settings_set_int(ud->settings, "angle_count", tinfo->angle_count);
1474         ud->dont_clear_presets = FALSE;
1475 }
1476
1477 static gboolean update_preview = FALSE;
1478
1479 G_MODULE_EXPORT void
1480 title_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1481 {
1482         ghb_title_info_t tinfo;
1483         gint titleindex;
1484         
1485         g_debug("title_changed_cb ()");
1486         ghb_widget_to_setting(ud->settings, widget);
1487
1488         titleindex = ghb_settings_combo_int(ud->settings, "title");
1489         ghb_update_ui_combo_box (ud, "AudioTrack", titleindex, FALSE);
1490         ghb_update_ui_combo_box (ud, "SubtitleTrack", titleindex, FALSE);
1491
1492         if (ghb_get_title_info (&tinfo, titleindex))
1493         {
1494                 show_title_info(ud, &tinfo);
1495         }
1496         ghb_check_dependency(ud, widget, NULL);
1497         update_chapter_list (ud);
1498         ghb_adjust_audio_rate_combos(ud);
1499         ghb_set_pref_audio(titleindex, ud);
1500         ghb_set_pref_subtitle(titleindex, ud);
1501         if (ghb_settings_get_boolean(ud->settings, "vquality_type_target"))
1502         {
1503                 gint bitrate = ghb_calculate_target_bitrate (ud->settings, titleindex);
1504                 ghb_ui_update(ud, "VideoAvgBitrate", ghb_int64_value(bitrate));
1505         }
1506
1507         // Unfortunately, there is no way to query how many frames were
1508         // actually generated during the scan.
1509         // If I knew how many were generated, I would adjust the spin
1510         // control range here.
1511         // I do know how many were asked for.
1512         gint preview_count;
1513         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
1514         widget = GHB_WIDGET(ud->builder, "preview_frame");
1515         gtk_range_set_range (GTK_RANGE(widget), 1, preview_count);
1516         ghb_ui_update(ud, "preview_frame", ghb_int64_value(2));
1517
1518         ghb_set_preview_image (ud);
1519         if (ghb_settings_get_boolean(ud->settings, "title_no_in_destination"))
1520         {
1521                 set_destination(ud);
1522         }
1523         ghb_preview_set_visible(ud);
1524
1525         gint end;
1526         widget = GHB_WIDGET (ud->builder, "ChapterMarkers");
1527         gtk_widget_set_sensitive(widget, TRUE);
1528         end = ghb_settings_get_int(ud->settings, "end_point");
1529         if (1 == end)
1530         {
1531                 ud->dont_clear_presets = TRUE;
1532                 ghb_ui_update(ud, "ChapterMarkers", ghb_boolean_value(FALSE));
1533                 ud->dont_clear_presets = FALSE;
1534                 gtk_widget_set_sensitive(widget, FALSE);
1535         }
1536 }
1537
1538 G_MODULE_EXPORT void
1539 ptop_widget_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1540 {
1541         gint ti;
1542         ghb_title_info_t tinfo;
1543
1544         ghb_widget_to_setting(ud->settings, widget);
1545         ghb_check_dependency(ud, widget, NULL);
1546         ghb_live_reset(ud);
1547
1548         ti = ghb_settings_combo_int(ud->settings, "title");
1549         if (!ghb_get_title_info (&tinfo, ti))
1550                 return;
1551
1552         gint duration = tinfo.duration / 90000;
1553         if (ghb_settings_combo_int(ud->settings, "PtoPType") == 0)
1554         {
1555                 widget = GHB_WIDGET (ud->builder, "start_point");
1556                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo.num_chapters);
1557                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 1);
1558
1559                 widget = GHB_WIDGET (ud->builder, "end_point");
1560                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo.num_chapters);
1561                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), tinfo.num_chapters);
1562         }
1563         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 1)
1564         {
1565                 widget = GHB_WIDGET (ud->builder, "start_point");
1566                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, duration-1);
1567                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 0);
1568
1569                 widget = GHB_WIDGET (ud->builder, "end_point");
1570                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, duration);
1571                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), duration);
1572         }
1573         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 2)
1574         {
1575                 gdouble max_frames = (gdouble)duration * tinfo.rate / tinfo.rate_base;
1576                 widget = GHB_WIDGET (ud->builder, "start_point");
1577                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, max_frames);
1578                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 1);
1579
1580                 widget = GHB_WIDGET (ud->builder, "end_point");
1581                 gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, max_frames);
1582                 gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), max_frames);
1583         }
1584 }
1585
1586 G_MODULE_EXPORT void
1587 framerate_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1588 {
1589         ghb_widget_to_setting(ud->settings, widget);
1590
1591         if (ghb_settings_combo_int(ud->settings, "VideoFramerate") != 0)
1592         {
1593                 if (!ghb_settings_get_boolean(ud->settings, "VideoFrameratePFR"))
1594         {
1595                     ghb_ui_update(ud, "VideoFramerateCFR", ghb_boolean_value(TRUE));
1596         }
1597         }
1598         if (ghb_settings_combo_int(ud->settings, "VideoFramerate") == 0 &&
1599                 ghb_settings_get_boolean(ud->settings, "VideoFrameratePFR"))
1600         {
1601                 ghb_ui_update(ud, "VideoFramerateVFR", ghb_boolean_value(TRUE));
1602         }
1603         ghb_check_dependency(ud, widget, NULL);
1604         ghb_clear_presets_selection(ud);
1605         ghb_live_reset(ud);
1606 }
1607
1608 G_MODULE_EXPORT void
1609 setting_widget_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1610 {
1611         ghb_widget_to_setting(ud->settings, widget);
1612         ghb_check_dependency(ud, widget, NULL);
1613         ghb_clear_presets_selection(ud);
1614         ghb_live_reset(ud);
1615 }
1616
1617 G_MODULE_EXPORT void
1618 chapter_markers_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1619 {
1620         ghb_widget_to_setting(ud->settings, widget);
1621         ghb_check_dependency(ud, widget, NULL);
1622         ghb_clear_presets_selection(ud);
1623         ghb_live_reset(ud);
1624         ghb_update_destination_extension(ud);
1625 }
1626
1627 G_MODULE_EXPORT void
1628 vquality_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1629 {
1630         ghb_widget_to_setting(ud->settings, widget);
1631         ghb_check_dependency(ud, widget, NULL);
1632         ghb_clear_presets_selection(ud);
1633         ghb_live_reset(ud);
1634
1635         gint vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
1636         gdouble step;
1637         if (vcodec == HB_VCODEC_X264)
1638         {
1639                 step = ghb_settings_combo_double(ud->settings, 
1640                                                                                         "VideoQualityGranularity");
1641         }
1642         else
1643         {
1644                 step = 1;
1645         }
1646         gdouble val = gtk_range_get_value(GTK_RANGE(widget));
1647         val = ((int)((val + step / 2) / step)) * step;
1648         gtk_range_set_value(GTK_RANGE(widget), val);
1649 }
1650
1651 G_MODULE_EXPORT void
1652 http_opt_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1653 {
1654         ghb_widget_to_setting(ud->settings, widget);
1655         ghb_check_dependency(ud, widget, NULL);
1656         ghb_clear_presets_selection(ud);
1657         ghb_live_reset(ud);
1658         // AC3 is not allowed when Web optimized
1659         ghb_grey_combo_options (ud->builder);
1660 }
1661
1662 G_MODULE_EXPORT void
1663 vcodec_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1664 {
1665         gdouble vqmin, vqmax, step, page;
1666         gboolean inverted;
1667         gint digits;
1668
1669         ghb_widget_to_setting(ud->settings, widget);
1670         ghb_check_dependency(ud, widget, NULL);
1671         ghb_clear_presets_selection(ud);
1672         ghb_live_reset(ud);
1673         ghb_vquality_range(ud, &vqmin, &vqmax, &step, &page, &digits, &inverted);
1674         GtkWidget *qp = GHB_WIDGET(ud->builder, "VideoQualitySlider");
1675         gtk_range_set_range (GTK_RANGE(qp), vqmin, vqmax);
1676         gtk_range_set_increments (GTK_RANGE(qp), step, page);
1677         gtk_scale_set_digits(GTK_SCALE(qp), digits);
1678         gtk_range_set_inverted (GTK_RANGE(qp), inverted);
1679 }
1680
1681 G_MODULE_EXPORT void
1682 target_size_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1683 {
1684         const gchar *name = ghb_get_setting_key(widget);
1685         g_debug("target_size_changed_cb () %s", name);
1686         ghb_widget_to_setting(ud->settings, widget);
1687         ghb_check_dependency(ud, widget, NULL);
1688         ghb_clear_presets_selection(ud);
1689         ghb_live_reset(ud);
1690         if (ghb_settings_get_boolean(ud->settings, "vquality_type_target"))
1691         {
1692                 gint titleindex;
1693                 titleindex = ghb_settings_combo_int(ud->settings, "title");
1694                 gint bitrate = ghb_calculate_target_bitrate (ud->settings, titleindex);
1695                 ghb_ui_update(ud, "VideoAvgBitrate", ghb_int64_value(bitrate));
1696         }
1697 }
1698
1699 G_MODULE_EXPORT void
1700 start_point_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1701 {
1702         gint start, end;
1703         const gchar *name = ghb_get_setting_key(widget);
1704
1705         g_debug("start_point_changed_cb () %s", name);
1706         ghb_widget_to_setting(ud->settings, widget);
1707         if (ghb_settings_combo_int(ud->settings, "PtoPType") == 0)
1708         {
1709                 start = ghb_settings_get_int(ud->settings, "start_point");
1710                 end = ghb_settings_get_int(ud->settings, "end_point");
1711                 if (start > end)
1712                         ghb_ui_update(ud, "end_point", ghb_int_value(start));
1713                 ghb_check_dependency(ud, widget, NULL);
1714                 if (ghb_settings_get_boolean(ud->settings, "chapters_in_destination"))
1715                 {
1716                         set_destination(ud);
1717                 }
1718                 widget = GHB_WIDGET (ud->builder, "ChapterMarkers");
1719                 gtk_widget_set_sensitive(widget, TRUE);
1720                 // End may have been changed above, get it again
1721                 end = ghb_settings_get_int(ud->settings, "end_point");
1722                 if (start == end)
1723                 {
1724                         ud->dont_clear_presets = TRUE;
1725                         ghb_ui_update(ud, "ChapterMarkers", ghb_boolean_value(FALSE));
1726                         ud->dont_clear_presets = FALSE;
1727                         gtk_widget_set_sensitive(widget, FALSE);
1728                 }
1729                 update_title_duration(ud);
1730         }
1731         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 1)
1732         {
1733                 start = ghb_settings_get_int(ud->settings, "start_point");
1734                 end = ghb_settings_get_int(ud->settings, "end_point");
1735                 if (start >= end)
1736                         ghb_ui_update(ud, "end_point", ghb_int_value(start+1));
1737                 ghb_check_dependency(ud, widget, NULL);
1738                 update_title_duration(ud);
1739         }
1740         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 2)
1741         {
1742                 start = ghb_settings_get_int(ud->settings, "start_point");
1743                 end = ghb_settings_get_int(ud->settings, "end_point");
1744                 if (start > end)
1745                         ghb_ui_update(ud, "end_point", ghb_int_value(start));
1746                 ghb_check_dependency(ud, widget, NULL);
1747                 update_title_duration(ud);
1748         }
1749 }
1750
1751 G_MODULE_EXPORT void
1752 end_point_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1753 {
1754         gint start, end;
1755         const gchar *name = ghb_get_setting_key(widget);
1756
1757         g_debug("end_point_changed_cb () %s", name);
1758         ghb_widget_to_setting(ud->settings, widget);
1759         if (ghb_settings_combo_int(ud->settings, "PtoPType") == 0)
1760         {
1761                 start = ghb_settings_get_int(ud->settings, "start_point");
1762                 end = ghb_settings_get_int(ud->settings, "end_point");
1763                 if (start > end)
1764                         ghb_ui_update(ud, "start_point", ghb_int_value(end));
1765                 ghb_check_dependency(ud, widget, NULL);
1766                 if (ghb_settings_get_boolean(ud->settings, "chapters_in_destination"))
1767                 {
1768                         set_destination(ud);
1769                 }
1770                 widget = GHB_WIDGET (ud->builder, "ChapterMarkers");
1771                 gtk_widget_set_sensitive(widget, TRUE);
1772                 // Start may have been changed above, get it again
1773                 start = ghb_settings_get_int(ud->settings, "start_point");
1774                 if (start == end)
1775                 {
1776                         ud->dont_clear_presets = TRUE;
1777                         ghb_ui_update(ud, "ChapterMarkers", ghb_boolean_value(FALSE));
1778                         ud->dont_clear_presets = FALSE;
1779                         gtk_widget_set_sensitive(widget, FALSE);
1780                 }
1781                 update_title_duration(ud);
1782         }
1783         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 1)
1784         {
1785                 start = ghb_settings_get_int(ud->settings, "start_point");
1786                 end = ghb_settings_get_int(ud->settings, "end_point");
1787                 if (start >= end)
1788                         ghb_ui_update(ud, "start_point", ghb_int_value(end-1));
1789                 ghb_check_dependency(ud, widget, NULL);
1790                 update_title_duration(ud);
1791         }
1792         else if (ghb_settings_combo_int(ud->settings, "PtoPType") == 2)
1793         {
1794                 start = ghb_settings_get_int(ud->settings, "start_point");
1795                 end = ghb_settings_get_int(ud->settings, "end_point");
1796                 if (start > end)
1797                         ghb_ui_update(ud, "start_point", ghb_int_value(end));
1798                 ghb_check_dependency(ud, widget, NULL);
1799                 update_title_duration(ud);
1800         }
1801 }
1802
1803 G_MODULE_EXPORT void
1804 scale_width_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1805 {
1806         g_debug("scale_width_changed_cb ()");
1807         ghb_widget_to_setting(ud->settings, widget);
1808         ghb_check_dependency(ud, widget, NULL);
1809         ghb_clear_presets_selection(ud);
1810         if (GTK_WIDGET_SENSITIVE(widget))
1811                 ghb_set_scale (ud, GHB_PIC_KEEP_WIDTH);
1812         update_preview = TRUE;
1813         gchar *text;
1814         gint width = ghb_settings_get_int(ud->settings, "scale_width");
1815         gint height = ghb_settings_get_int(ud->settings, "scale_height");
1816         widget = GHB_WIDGET (ud->builder, "scale_dimensions");
1817         text = g_strdup_printf ("%d x %d", width, height);
1818         gtk_label_set_text (GTK_LABEL(widget), text);
1819         g_free(text);
1820         ghb_live_reset(ud);
1821 }
1822
1823 G_MODULE_EXPORT void
1824 scale_height_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1825 {
1826         g_debug("scale_height_changed_cb ()");
1827         ghb_widget_to_setting(ud->settings, widget);
1828         ghb_check_dependency(ud, widget, NULL);
1829         ghb_clear_presets_selection(ud);
1830         if (GTK_WIDGET_SENSITIVE(widget))
1831                 ghb_set_scale (ud, GHB_PIC_KEEP_HEIGHT);
1832         update_preview = TRUE;
1833         gchar *text;
1834         gint width = ghb_settings_get_int(ud->settings, "scale_width");
1835         gint height = ghb_settings_get_int(ud->settings, "scale_height");
1836         widget = GHB_WIDGET (ud->builder, "scale_dimensions");
1837         text = g_strdup_printf ("%d x %d", width, height);
1838         gtk_label_set_text (GTK_LABEL(widget), text);
1839         g_free(text);
1840         ghb_live_reset(ud);
1841 }
1842
1843 G_MODULE_EXPORT void
1844 crop_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1845 {
1846         gint titleindex, crop[4];
1847         ghb_title_info_t tinfo;
1848         
1849         g_debug("crop_changed_cb ()");
1850         ghb_widget_to_setting(ud->settings, widget);
1851         ghb_check_dependency(ud, widget, NULL);
1852         ghb_clear_presets_selection(ud);
1853         if (GTK_WIDGET_SENSITIVE(widget))
1854                 ghb_set_scale (ud, 0);
1855
1856         crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
1857         crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
1858         crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
1859         crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
1860         titleindex = ghb_settings_combo_int(ud->settings, "title");
1861         if (ghb_get_title_info (&tinfo, titleindex))
1862         {
1863                 gint width, height;
1864                 gchar *text;
1865                 
1866                 width = tinfo.width - crop[2] - crop[3];
1867                 height = tinfo.height - crop[0] - crop[1];
1868                 widget = GHB_WIDGET (ud->builder, "crop_dimensions");
1869                 text = g_strdup_printf ("%d x %d", width, height);
1870                 gtk_label_set_text (GTK_LABEL(widget), text);
1871                 widget = GHB_WIDGET (ud->builder, "crop_dimensions2");
1872                 gtk_label_set_text (GTK_LABEL(widget), text);
1873                 g_free(text);
1874         }
1875         gchar *text;
1876         widget = GHB_WIDGET (ud->builder, "crop_values");
1877         text = g_strdup_printf ("%d:%d:%d:%d", crop[0], crop[1], crop[2], crop[3]);
1878         gtk_label_set_text (GTK_LABEL(widget), text);
1879         g_free(text);
1880         update_preview = TRUE;
1881         ghb_live_reset(ud);
1882 }
1883
1884 G_MODULE_EXPORT void
1885 display_width_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1886 {
1887         g_debug("display_width_changed_cb ()");
1888         ghb_widget_to_setting(ud->settings, widget);
1889         ghb_check_dependency(ud, widget, NULL);
1890         ghb_clear_presets_selection(ud);
1891         ghb_live_reset(ud);
1892         if (GTK_WIDGET_SENSITIVE(widget))
1893                 ghb_set_scale (ud, GHB_PIC_KEEP_DISPLAY_WIDTH);
1894
1895         update_preview = TRUE;
1896 }
1897
1898 G_MODULE_EXPORT void
1899 display_height_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1900 {
1901         g_debug("display_height_changed_cb ()");
1902         ghb_widget_to_setting(ud->settings, widget);
1903         ghb_check_dependency(ud, widget, NULL);
1904         ghb_clear_presets_selection(ud);
1905         ghb_live_reset(ud);
1906         if (GTK_WIDGET_SENSITIVE(widget))
1907                 ghb_set_scale (ud, GHB_PIC_KEEP_DISPLAY_HEIGHT);
1908
1909         update_preview = TRUE;
1910 }
1911
1912 G_MODULE_EXPORT void
1913 par_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1914 {
1915         g_debug("par_changed_cb ()");
1916         ghb_widget_to_setting(ud->settings, widget);
1917         ghb_check_dependency(ud, widget, NULL);
1918         ghb_clear_presets_selection(ud);
1919         ghb_live_reset(ud);
1920         if (GTK_WIDGET_SENSITIVE(widget))
1921                 ghb_set_scale (ud, GHB_PIC_KEEP_PAR);
1922
1923         update_preview = TRUE;
1924 }
1925
1926 G_MODULE_EXPORT void
1927 scale_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1928 {
1929         g_debug("scale_changed_cb ()");
1930         ghb_widget_to_setting(ud->settings, widget);
1931         ghb_check_dependency(ud, widget, NULL);
1932         ghb_clear_presets_selection(ud);
1933         ghb_live_reset(ud);
1934         if (GTK_WIDGET_SENSITIVE(widget))
1935                 ghb_set_scale (ud, 0);
1936         update_preview = TRUE;
1937         
1938         gchar *text;
1939         
1940         text = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop") ? "On" : "Off";
1941         widget = GHB_WIDGET (ud->builder, "crop_auto");
1942         gtk_label_set_text (GTK_LABEL(widget), text);
1943         text = ghb_settings_get_boolean(ud->settings, "autoscale") ? "On" : "Off";
1944         widget = GHB_WIDGET (ud->builder, "scale_auto");
1945         gtk_label_set_text (GTK_LABEL(widget), text);
1946         switch (ghb_settings_combo_int(ud->settings, "PicturePAR"))
1947         {
1948                 case 0:
1949                         text = "Off";
1950                         break;
1951                 case 1:
1952                         text = "Strict";
1953                         break;
1954                 case 2:
1955                         text = "Loose";
1956                         break;
1957                 case 3:
1958                         text = "Custom";
1959                         break;
1960                 default:
1961                         text = "Unknown";
1962                         break;
1963         }
1964         widget = GHB_WIDGET (ud->builder, "scale_anamorphic");
1965         gtk_label_set_text (GTK_LABEL(widget), text);
1966 }
1967
1968 G_MODULE_EXPORT void
1969 show_crop_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1970 {
1971         g_debug("show_crop_changed_cb ()");
1972         ghb_widget_to_setting(ud->settings, widget);
1973         ghb_check_dependency(ud, widget, NULL);
1974         ghb_live_reset(ud);
1975         if (GTK_WIDGET_SENSITIVE(widget))
1976                 ghb_set_scale (ud, 0);
1977         update_preview = TRUE;
1978 }
1979
1980 G_MODULE_EXPORT void
1981 generic_entry_changed_cb(GtkEntry *entry, signal_user_data_t *ud)
1982 {
1983         // Normally (due to user input) I only want to process the entry
1984         // when editing is done and the focus-out signal is sent.
1985         // But... there's always a but.
1986         // If the entry is changed by software, the focus-out signal is not sent.
1987         // The changed signal is sent ... so here we are.
1988         // I don't want to process upon every keystroke, so I prevent processing
1989         // while the widget has focus.
1990         g_debug("generic_entry_changed_cb ()");
1991         if (!GTK_WIDGET_HAS_FOCUS((GtkWidget*)entry))
1992         {
1993                 ghb_widget_to_setting(ud->settings, (GtkWidget*)entry);
1994         }
1995 }
1996
1997 G_MODULE_EXPORT void
1998 prefs_dialog_cb(GtkWidget *xwidget, signal_user_data_t *ud)
1999 {
2000         GtkWidget *dialog;
2001         GtkResponseType response;
2002
2003         g_debug("prefs_dialog_cb ()");
2004         dialog = GHB_WIDGET(ud->builder, "prefs_dialog");
2005         response = gtk_dialog_run(GTK_DIALOG(dialog));
2006         gtk_widget_hide(dialog);
2007 }
2008
2009 typedef struct
2010 {
2011         GtkMessageDialog *dlg;
2012         const gchar *msg;
2013         const gchar *action;
2014         gint timeout;
2015         signal_user_data_t *ud;
2016 } countdown_t;
2017
2018 static gboolean
2019 quit_cb(countdown_t *cd)
2020 {
2021         gchar *str;
2022
2023         cd->timeout--;
2024         if (cd->timeout == 0)
2025         {
2026                 ghb_hb_cleanup(FALSE);
2027                 prune_logs(cd->ud);
2028
2029                 gtk_widget_destroy (GTK_WIDGET(cd->dlg));
2030                 gtk_main_quit();
2031                 return FALSE;
2032         }
2033         str = g_strdup_printf("%s\n\n%s in %d seconds ...", 
2034                                                         cd->msg, cd->action, cd->timeout);
2035         gtk_message_dialog_set_markup(cd->dlg, str);
2036         g_free(str);
2037         return TRUE;
2038 }
2039
2040 static gboolean
2041 shutdown_cb(countdown_t *cd)
2042 {
2043         gchar *str;
2044
2045         cd->timeout--;
2046         if (cd->timeout == 0)
2047         {
2048                 ghb_hb_cleanup(FALSE);
2049                 prune_logs(cd->ud);
2050
2051                 ghb_shutdown_gsm();
2052                 gtk_main_quit();
2053                 return FALSE;
2054         }
2055         str = g_strdup_printf("%s\n\n%s in %d seconds ...", 
2056                                                         cd->msg, cd->action, cd->timeout);
2057         gtk_message_dialog_set_markup(cd->dlg, str);
2058         g_free(str);
2059         return TRUE;
2060 }
2061
2062 static gboolean
2063 suspend_cb(countdown_t *cd)
2064 {
2065         gchar *str;
2066
2067         cd->timeout--;
2068         if (cd->timeout == 0)
2069         {
2070                 gtk_widget_destroy (GTK_WIDGET(cd->dlg));
2071                 ghb_suspend_gpm();
2072                 return FALSE;
2073         }
2074         str = g_strdup_printf("%s\n\n%s in %d seconds ...", 
2075                                                         cd->msg, cd->action, cd->timeout);
2076         gtk_message_dialog_set_markup(cd->dlg, str);
2077         g_free(str);
2078         return TRUE;
2079 }
2080
2081 void
2082 ghb_countdown_dialog(
2083         GtkMessageType type, 
2084         const gchar *message, 
2085         const gchar *action, 
2086         const gchar *cancel, 
2087         GSourceFunc action_func,
2088         signal_user_data_t *ud,
2089         gint timeout)
2090 {
2091         GtkWidget *dialog;
2092         GtkResponseType response;
2093         guint timeout_id;
2094         countdown_t cd;
2095                         
2096         cd.msg = message;
2097         cd.action = action;
2098         cd.timeout = timeout;
2099         cd.ud = ud;
2100
2101         // Toss up a warning dialog
2102         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
2103                                                         type, GTK_BUTTONS_NONE,
2104                                                         "%s\n\n%s in %d seconds ...", 
2105                                                         message, action, timeout);
2106         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
2107                                                    cancel, GTK_RESPONSE_CANCEL,
2108                                                    NULL);
2109
2110         cd.dlg = GTK_MESSAGE_DIALOG(dialog);
2111         timeout_id = g_timeout_add(1000, action_func, &cd);
2112         response = gtk_dialog_run(GTK_DIALOG(dialog));
2113         gtk_widget_destroy (dialog);
2114         if (response == GTK_RESPONSE_CANCEL)
2115         {
2116                 GMainContext *mc;
2117                 GSource *source;
2118
2119                 mc = g_main_context_default();
2120                 source = g_main_context_find_source_by_id(mc, timeout_id);
2121                 if (source != NULL)
2122                         g_source_destroy(source);
2123         }
2124 }
2125
2126 gboolean
2127 ghb_message_dialog(GtkMessageType type, const gchar *message, const gchar *no, const gchar *yes)
2128 {
2129         GtkWidget *dialog;
2130         GtkResponseType response;
2131                         
2132         // Toss up a warning dialog
2133         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
2134                                                         type, GTK_BUTTONS_NONE,
2135                                                         "%s", message);
2136         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
2137                                                    no, GTK_RESPONSE_NO,
2138                                                    yes, GTK_RESPONSE_YES, NULL);
2139         response = gtk_dialog_run(GTK_DIALOG(dialog));
2140         gtk_widget_destroy (dialog);
2141         if (response == GTK_RESPONSE_NO)
2142         {
2143                 return FALSE;
2144         }
2145         return TRUE;
2146 }
2147
2148 void
2149 ghb_error_dialog(GtkMessageType type, const gchar *message, const gchar *cancel)
2150 {
2151         GtkWidget *dialog;
2152         GtkResponseType response;
2153                         
2154         // Toss up a warning dialog
2155         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
2156                                                         type, GTK_BUTTONS_NONE,
2157                                                         "%s", message);
2158         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
2159                                                    cancel, GTK_RESPONSE_CANCEL, NULL);
2160         response = gtk_dialog_run(GTK_DIALOG(dialog));
2161         gtk_widget_destroy (dialog);
2162 }
2163
2164 void
2165 ghb_cancel_encode(signal_user_data_t *ud, const gchar *extra_msg)
2166 {
2167         GtkWidget *dialog;
2168         GtkResponseType response;
2169         
2170         if (extra_msg == NULL) extra_msg = "";
2171         // Toss up a warning dialog
2172         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
2173                                 GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE,
2174                                 "%sYour movie will be lost if you don't continue encoding.",
2175                                 extra_msg);
2176         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
2177                                                    "Cancel Current and Stop", 1,
2178                                                    "Cancel Current, Start Next", 2,
2179                                                    "Finish Current, then Stop", 3,
2180                                                    "Continue Encoding", 4,
2181                                                    NULL);
2182         response = gtk_dialog_run(GTK_DIALOG(dialog));
2183         gtk_widget_destroy (dialog);
2184         switch ((int)response)
2185         {
2186                 case 1:
2187                         ghb_stop_queue();
2188                         ud->cancel_encode = GHB_CANCEL_ALL;
2189                         break;
2190                 case 2:
2191                         ghb_stop_queue();
2192                         ud->cancel_encode = GHB_CANCEL_CURRENT;
2193                         break;
2194                 case 3:
2195                         ud->cancel_encode = GHB_CANCEL_FINISH;
2196                         break;
2197                 case 4:
2198                 default:
2199                         ud->cancel_encode = GHB_CANCEL_NONE;
2200                         break;
2201         }
2202 }
2203
2204 gboolean
2205 ghb_cancel_encode2(signal_user_data_t *ud, const gchar *extra_msg)
2206 {
2207         GtkWidget *dialog;
2208         GtkResponseType response;
2209         
2210         if (extra_msg == NULL) extra_msg = "";
2211         // Toss up a warning dialog
2212         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
2213                                 GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE,
2214                                 "%sYour movie will be lost if you don't continue encoding.",
2215                                 extra_msg);
2216         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
2217                                                    "Cancel Current and Stop", 1,
2218                                                    "Continue Encoding", 4,
2219                                                    NULL);
2220         response = gtk_dialog_run(GTK_DIALOG(dialog));
2221         gtk_widget_destroy (dialog);
2222         switch ((int)response)
2223         {
2224                 case 1:
2225                         ghb_stop_queue();
2226                         ud->cancel_encode = GHB_CANCEL_ALL;
2227                         return TRUE;
2228                 case 4:
2229                 default:
2230                         break;
2231         }
2232         return FALSE;
2233 }
2234
2235 static void
2236 submit_job(GValue *settings)
2237 {
2238         static gint unique_id = 1;
2239         gchar *type, *modified, *preset;
2240         const GValue *path;
2241         gboolean preset_modified;
2242
2243         g_debug("submit_job");
2244         if (settings == NULL) return;
2245         preset_modified = ghb_settings_get_boolean(settings, "preset_modified");
2246         path = ghb_settings_get_value(settings, "preset");
2247         preset = ghb_preset_path_string(path);
2248         type = ghb_preset_is_custom() ? "Custom " : "";
2249         modified = preset_modified ? "Modified " : "";
2250         ghb_log("%s%sPreset: %s", modified, type, preset);
2251         g_free(preset);
2252
2253         ghb_settings_set_int(settings, "job_unique_id", unique_id);
2254         ghb_settings_set_int(settings, "job_status", GHB_QUEUE_RUNNING);
2255         ghb_add_job (settings, unique_id);
2256         ghb_start_queue();
2257         unique_id++;
2258 }
2259
2260 static void
2261 prune_logs(signal_user_data_t *ud)
2262 {
2263         gchar *dest_dir;
2264         gint days;
2265
2266         // Only prune logs stored in the default config dir location
2267         days = ghb_settings_combo_int(ud->settings, "LogLongevity");
2268         if (days > 365)
2269                 return;
2270
2271         dest_dir = ghb_get_user_config_dir("EncodeLogs");
2272         if (g_file_test(dest_dir, G_FILE_TEST_IS_DIR))
2273         {
2274                 const gchar *file;
2275                 gint duration = days * 24 * 60 * 60;
2276                 
2277                 GDir *gdir = g_dir_open(dest_dir, 0, NULL);
2278                 time_t now;
2279
2280                 now = time(NULL);
2281                 file = g_dir_read_name(gdir);
2282                 while (file)
2283                 {
2284                         gchar *path;
2285                         struct stat stbuf;
2286
2287                         path = g_strdup_printf("%s/%s", dest_dir, file);
2288                         g_stat(path, &stbuf);
2289                         if (now - stbuf.st_mtime > duration)
2290                         {
2291                                 g_unlink(path);
2292                         }
2293                         g_free(path);
2294                         file = g_dir_read_name(gdir);
2295                 }
2296                 g_dir_close(gdir);
2297         }
2298         g_free(dest_dir);
2299         ghb_preview_cleanup(ud);
2300 }
2301
2302 static void
2303 queue_scan(signal_user_data_t *ud, GValue *js)
2304 {
2305         gchar *path;
2306         gint titlenum;
2307         time_t  _now;
2308         struct tm *now;
2309         gchar *log_path, *pos, *destname, *basename, *dest_dir;
2310
2311         _now = time(NULL);
2312         now = localtime(&_now);
2313         destname = ghb_settings_get_string(js, "destination");
2314         basename = g_path_get_basename(destname);
2315         if (ghb_settings_get_boolean(ud->settings, "EncodeLogLocation"))
2316         {
2317                 dest_dir = g_path_get_dirname (destname);
2318         }
2319         else
2320         {
2321                 dest_dir = ghb_get_user_config_dir("EncodeLogs");
2322         }
2323         g_free(destname);
2324         pos = g_strrstr( basename, "." );
2325         if (pos != NULL)
2326         {
2327                 *pos = 0;
2328         }
2329         log_path = g_strdup_printf("%s/%s %d-%02d-%02d %02d-%02d-%02d.log",
2330                 dest_dir,
2331                 basename,
2332                 now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
2333                 now->tm_hour, now->tm_min, now->tm_sec);
2334         g_free(basename);
2335         g_free(dest_dir);
2336         if (ud->job_activity_log)
2337                 g_io_channel_unref(ud->job_activity_log);
2338         ud->job_activity_log = g_io_channel_new_file (log_path, "w", NULL);
2339         if (ud->job_activity_log)
2340         {
2341                 gchar *ver_str;
2342
2343                 ver_str = g_strdup_printf("Handbrake Version: %s (%d)\n", 
2344                                                                         hb_get_version(NULL), hb_get_build(NULL));
2345                 g_io_channel_write_chars (ud->job_activity_log, ver_str, 
2346                                                                         -1, NULL, NULL);
2347                 g_free(ver_str);
2348         }
2349         g_free(log_path);
2350
2351         path = ghb_settings_get_string( js, "source");
2352         titlenum = ghb_settings_get_int(js, "titlenum");
2353         ghb_backend_queue_scan(path, titlenum);
2354         g_free(path);
2355 }
2356
2357 static gint
2358 queue_pending_count(GValue *queue)
2359 {
2360         gint nn, ii, count;
2361         GValue *js;
2362         gint status;
2363
2364         nn = 0;
2365         count = ghb_array_len(queue);
2366         for (ii = 0; ii < count; ii++)
2367         {
2368
2369                 js = ghb_array_get_nth(queue, ii);
2370                 status = ghb_settings_get_int(js, "job_status");
2371                 if (status == GHB_QUEUE_PENDING)
2372                 {
2373                         nn++;
2374                 }
2375         }
2376         return nn;
2377 }
2378
2379 void
2380 ghb_update_pending(signal_user_data_t *ud)
2381 {
2382         GtkLabel *label;
2383         gint pending;
2384         gchar *str;
2385
2386         label = GTK_LABEL(GHB_WIDGET(ud->builder, "pending_status"));
2387         pending = queue_pending_count(ud->queue);
2388         str = g_strdup_printf("%d encode(s) pending", pending);
2389         gtk_label_set_text(label, str);
2390         g_free(str);
2391 }
2392
2393 GValue* 
2394 ghb_start_next_job(signal_user_data_t *ud, gboolean find_first)
2395 {
2396         static gint current = 0;
2397         gint count, ii, jj;
2398         GValue *js;
2399         gint status;
2400         GtkWidget *prog;
2401
2402         g_debug("start_next_job");
2403         prog = GHB_WIDGET(ud->builder, "progressbar");
2404         gtk_widget_show(prog);
2405
2406         count = ghb_array_len(ud->queue);
2407         if (find_first)
2408         {       // Start the first pending item in the queue
2409                 current = 0;
2410                 for (ii = 0; ii < count; ii++)
2411                 {
2412
2413                         js = ghb_array_get_nth(ud->queue, ii);
2414                         status = ghb_settings_get_int(js, "job_status");
2415                         if (status == GHB_QUEUE_PENDING)
2416                         {
2417                                 current = ii;
2418                                 ghb_inhibit_gsm(ud);
2419                                 queue_scan(ud, js);
2420                                 ghb_update_pending(ud);
2421                                 return js;
2422                         }
2423                 }
2424                 // Nothing pending
2425                 ghb_uninhibit_gsm();
2426                 ghb_notify_done(ud);
2427                 return NULL;
2428         }
2429         // Find the next pending item after the current running item
2430         for (ii = 0; ii < count-1; ii++)
2431         {
2432                 js = ghb_array_get_nth(ud->queue, ii);
2433                 status = ghb_settings_get_int(js, "job_status");
2434                 if (status == GHB_QUEUE_RUNNING)
2435                 {
2436                         for (jj = ii+1; jj < count; jj++)
2437                         {
2438                                 js = ghb_array_get_nth(ud->queue, jj);
2439                                 status = ghb_settings_get_int(js, "job_status");
2440                                 if (status == GHB_QUEUE_PENDING)
2441                                 {
2442                                         current = jj;
2443                                         ghb_inhibit_gsm(ud);
2444                                         queue_scan(ud, js);
2445                                         ghb_update_pending(ud);
2446                                         return js;
2447                                 }
2448                         }
2449                 }
2450         }
2451         // No running item found? Maybe it was deleted
2452         // Look for a pending item starting from the last index we started
2453         for (ii = current; ii < count; ii++)
2454         {
2455                 js = ghb_array_get_nth(ud->queue, ii);
2456                 status = ghb_settings_get_int(js, "job_status");
2457                 if (status == GHB_QUEUE_PENDING)
2458                 {
2459                         current = ii;
2460                         ghb_inhibit_gsm(ud);
2461                         queue_scan(ud, js);
2462                         ghb_update_pending(ud);
2463                         return js;
2464                 }
2465         }
2466         // Nothing found
2467         ghb_uninhibit_gsm();
2468         ghb_notify_done(ud);
2469         ghb_update_pending(ud);
2470         gtk_widget_hide(prog);
2471         return NULL;
2472 }
2473
2474 static gint
2475 find_queue_job(GValue *queue, gint unique_id, GValue **job)
2476 {
2477         GValue *js;
2478         gint ii, count;
2479         gint job_unique_id;
2480         
2481         *job = NULL;
2482         g_debug("find_queue_job");
2483         if (unique_id == 0)  // Invalid Id
2484                 return -1;
2485
2486         count = ghb_array_len(queue);
2487         for (ii = 0; ii < count; ii++)
2488         {
2489                 js = ghb_array_get_nth(queue, ii);
2490                 job_unique_id = ghb_settings_get_int(js, "job_unique_id");
2491                 if (job_unique_id == unique_id)
2492                 {
2493                         *job = js;
2494                         return ii;
2495                 }
2496         }
2497         return -1;
2498 }
2499
2500 gchar*
2501 working_status_string(signal_user_data_t *ud, ghb_instance_status_t *status)
2502 {
2503         gchar *task_str, *job_str, *status_str;
2504         gint qcount;
2505         gint index;
2506         GValue *js;
2507         gboolean subtitle_scan = FALSE;
2508
2509         qcount = ghb_array_len(ud->queue);
2510         index = find_queue_job(ud->queue, status->unique_id, &js);
2511         if (js != NULL)
2512         {
2513                 subtitle_scan = ghb_settings_get_boolean(js, "subtitle_scan");
2514         }
2515         if (qcount > 1)
2516         {
2517                 job_str = g_strdup_printf("job %d of %d, ", index+1, qcount);
2518         }
2519         else
2520         {
2521                 job_str = g_strdup("");
2522         }
2523         if (status->job_count > 1)
2524         {
2525                 if (status->job_cur == 1 && subtitle_scan)
2526                 {
2527                         task_str = g_strdup_printf("pass %d (subtitle scan) of %d, ", 
2528                                 status->job_cur, status->job_count);
2529                 }
2530                 else
2531                 {
2532                         task_str = g_strdup_printf("pass %d of %d, ", 
2533                                 status->job_cur, status->job_count);
2534                 }
2535         }
2536         else
2537         {
2538                 task_str = g_strdup("");
2539         }
2540         if(status->seconds > -1)
2541         {
2542                 status_str= g_strdup_printf(
2543                         "Encoding: %s%s%.2f %%"
2544                         " (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)",
2545                         job_str, task_str,
2546                         100.0 * status->progress,
2547                         status->rate_cur, status->rate_avg, status->hours, 
2548                         status->minutes, status->seconds );
2549         }
2550         else
2551         {
2552                 status_str= g_strdup_printf(
2553                         "Encoding: %s%s%.2f %%",
2554                         job_str, task_str,
2555                         100.0 * status->progress );
2556         }
2557         g_free(task_str);
2558         g_free(job_str);
2559         return status_str;
2560 }
2561
2562 gchar*
2563 searching_status_string(signal_user_data_t *ud, ghb_instance_status_t *status)
2564 {
2565         gchar *task_str, *job_str, *status_str;
2566         gint qcount;
2567         gint index;
2568         GValue *js;
2569
2570         qcount = ghb_array_len(ud->queue);
2571         index = find_queue_job(ud->queue, status->unique_id, &js);
2572         if (qcount > 1)
2573         {
2574                 job_str = g_strdup_printf("job %d of %d, ", index+1, qcount);
2575         }
2576         else
2577         {
2578                 job_str = g_strdup("");
2579         }
2580         task_str = g_strdup_printf("Searching for start time, ");
2581         if(status->seconds > -1)
2582         {
2583                 status_str= g_strdup_printf(
2584                         "Encoding: %s%s%.2f %%"
2585                         " (ETA %02dh%02dm%02ds)",
2586                         job_str, task_str,
2587                         100.0 * status->progress,
2588                         status->hours, status->minutes, status->seconds );
2589         }
2590         else
2591         {
2592                 status_str= g_strdup_printf(
2593                         "Encoding: %s%s%.2f %%",
2594                         job_str, task_str,
2595                         100.0 * status->progress );
2596         }
2597         g_free(task_str);
2598         g_free(job_str);
2599         return status_str;
2600 }
2601
2602 static void
2603 ghb_backend_events(signal_user_data_t *ud)
2604 {
2605         ghb_status_t status;
2606         gchar *status_str;
2607         GtkProgressBar *progress;
2608         GtkLabel       *work_status;
2609         gint titleindex;
2610         GValue *js;
2611         gint index;
2612         GtkTreeView *treeview;
2613         GtkTreeStore *store;
2614         GtkTreeIter iter;
2615         static gint prev_scan_state = 0;
2616         static gint prev_queue_state = 0;
2617         
2618         ghb_track_status();
2619         ghb_get_status(&status);
2620         if (prev_scan_state != status.scan.state ||
2621                 prev_queue_state != status.queue.state)
2622         {
2623                 ghb_queue_buttons_grey(ud);
2624                 prev_scan_state = status.scan.state;
2625                 prev_queue_state = status.queue.state;
2626         }
2627         progress = GTK_PROGRESS_BAR(GHB_WIDGET (ud->builder, "progressbar"));
2628         work_status = GTK_LABEL(GHB_WIDGET (ud->builder, "work_status"));
2629         if (status.scan.state == GHB_STATE_IDLE && 
2630                 status.queue.state == GHB_STATE_IDLE)
2631         {
2632                 static gboolean prev_dvdnav;
2633                 gboolean dvdnav = ghb_settings_get_boolean(ud->settings, "use_dvdnav");
2634                 if (dvdnav != prev_dvdnav)
2635                 {
2636                         hb_dvd_set_dvdnav(dvdnav);
2637                         prev_dvdnav = dvdnav;
2638                 }
2639         }
2640         // First handle the status of title scans
2641         // Then handle the status of the queue
2642         if (status.scan.state & GHB_STATE_SCANNING)
2643         {
2644                 GtkProgressBar *scan_prog;
2645                 GtkLabel *label;
2646
2647                 scan_prog = GTK_PROGRESS_BAR(GHB_WIDGET (ud->builder, "scan_prog"));
2648                 label = GTK_LABEL(GHB_WIDGET (ud->builder, "source_title"));
2649
2650                 if (status.scan.title_cur == 0)
2651                 {
2652                         status_str = g_strdup ("Scanning...");
2653                 }
2654                 else
2655                 {
2656                         status_str = g_strdup_printf ("Scanning title %d of %d...", 
2657                                                           status.scan.title_cur, status.scan.title_count );
2658                 }
2659                 gtk_label_set_text (label, status_str);
2660                 g_free(status_str);
2661                 if (status.scan.title_count > 0)
2662                 {
2663                         gtk_progress_bar_set_fraction (scan_prog, 
2664                                 (gdouble)status.scan.title_cur / status.scan.title_count);
2665                 }
2666         }
2667         else if (status.scan.state & GHB_STATE_SCANDONE)
2668         {
2669                 gchar *source;
2670                 GtkProgressBar *scan_prog;
2671                 GtkLabel *label;
2672
2673                 GtkWidget *widget;
2674                 GtkAction *action;
2675
2676                 widget = GHB_WIDGET(ud->builder, "sourcetoolbutton");
2677                 gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(widget), "hb-source");
2678                 gtk_tool_button_set_label(GTK_TOOL_BUTTON(widget), "Source");
2679                 gtk_tool_item_set_tooltip_text(GTK_TOOL_ITEM(widget), "Choose Video Source");
2680
2681                 action = GHB_ACTION(ud->builder, "source_action");
2682                 gtk_action_set_sensitive(action, TRUE);
2683                 action = GHB_ACTION(ud->builder, "source_single_action");
2684                 gtk_action_set_sensitive(action, TRUE);
2685
2686                 source = ghb_settings_get_string(ud->settings, "scan_source");
2687                 update_source_label(ud, source, FALSE);
2688
2689                 scan_prog = GTK_PROGRESS_BAR(GHB_WIDGET (ud->builder, "scan_prog"));
2690                 gtk_progress_bar_set_fraction (scan_prog, 1.0);
2691                 gtk_widget_hide(GTK_WIDGET(scan_prog));
2692
2693                 if (!ghb_settings_get_boolean(ud->settings, "preset_modified"))
2694                 {
2695                         ghb_refresh_preset(ud);
2696                 }
2697
2698                 ghb_title_info_t tinfo;
2699                         
2700                 ghb_update_ui_combo_box(ud, "title", 0, FALSE);
2701                 titleindex = ghb_longest_title();
2702                 ghb_ui_update(ud, "title", ghb_int64_value(titleindex));
2703
2704                 label = GTK_LABEL(GHB_WIDGET (ud->builder, "source_title"));
2705                 // Are there really any titles.
2706                 if (!ghb_get_title_info(&tinfo, titleindex))
2707                 {
2708                         gtk_label_set_text(label, "None");
2709                 }
2710                 ghb_clear_scan_state(GHB_STATE_SCANDONE);
2711                 if (ghb_queue_edit_settings)
2712                 {
2713                         ghb_settings_to_ui(ud, ghb_queue_edit_settings);
2714                         ghb_set_audio(ud, ghb_queue_edit_settings);
2715                         ghb_reset_subtitles(ud, ghb_queue_edit_settings);
2716                         reset_chapter_list(ud, ghb_queue_edit_settings);
2717                         ghb_value_free(ghb_queue_edit_settings);
2718                         ghb_queue_edit_settings = NULL;
2719                 }
2720         }
2721
2722         if (status.queue.state & GHB_STATE_SCANNING)
2723         {
2724                 // This needs to be in scanning and working since scanning
2725                 // happens fast enough that it can be missed
2726                 gtk_label_set_text (work_status, "Scanning ...");
2727                 gtk_progress_bar_set_fraction (progress, 0);
2728         }
2729         else if (status.queue.state & GHB_STATE_SCANDONE)
2730         {
2731                 ghb_clear_queue_state(GHB_STATE_SCANDONE);
2732                 usleep(2000000);
2733                 submit_job(ud->current_job);
2734                 ghb_update_pending(ud);
2735         }
2736         else if (status.queue.state & GHB_STATE_PAUSED)
2737         {
2738                 gtk_label_set_text (work_status, "Paused");
2739         }
2740         else if (status.queue.state & GHB_STATE_SEARCHING)
2741         {
2742                 static gint working = 0;
2743
2744                 // This needs to be in scanning and working since scanning
2745                 // happens fast enough that it can be missed
2746                 index = find_queue_job(ud->queue, status.queue.unique_id, &js);
2747                 if (status.queue.unique_id != 0 && index >= 0)
2748                 {
2749                         gchar working_icon[] = "hb-working0";
2750                         working_icon[10] = '0' + working;
2751                         working = (working+1) % 6;
2752                         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "queue_list"));
2753                         store = GTK_TREE_STORE(gtk_tree_view_get_model(treeview));
2754                         gchar *path = g_strdup_printf ("%d", index);
2755                         if (gtk_tree_model_get_iter_from_string(
2756                                         GTK_TREE_MODEL(store), &iter, path))
2757                         {
2758                                 gtk_tree_store_set(store, &iter, 0, working_icon, -1);
2759                         }
2760                         g_free(path);
2761                 }
2762                 GtkLabel *label;
2763                 gchar *status_str;
2764
2765                 status_str = searching_status_string(ud, &status.queue);
2766                 label = GTK_LABEL(GHB_WIDGET(ud->builder, "queue_status"));
2767                 gtk_label_set_text (label, status_str);
2768 #if !GTK_CHECK_VERSION(2, 16, 0)
2769                 GtkStatusIcon *si;
2770
2771                 si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));
2772                 gtk_status_icon_set_tooltip(si, status_str);
2773 #endif
2774                 gtk_label_set_text (work_status, status_str);
2775                 gtk_progress_bar_set_fraction (progress, status.queue.progress);
2776                 g_free(status_str);
2777         }
2778         else if (status.queue.state & GHB_STATE_WORKING)
2779         {
2780                 static gint working = 0;
2781
2782                 // This needs to be in scanning and working since scanning
2783                 // happens fast enough that it can be missed
2784                 index = find_queue_job(ud->queue, status.queue.unique_id, &js);
2785                 if (status.queue.unique_id != 0 && index >= 0)
2786                 {
2787                         gchar working_icon[] = "hb-working0";
2788                         working_icon[10] = '0' + working;
2789                         working = (working+1) % 6;
2790                         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "queue_list"));
2791                         store = GTK_TREE_STORE(gtk_tree_view_get_model(treeview));
2792                         gchar *path = g_strdup_printf ("%d", index);
2793                         if (gtk_tree_model_get_iter_from_string(
2794                                         GTK_TREE_MODEL(store), &iter, path))
2795                         {
2796                                 gtk_tree_store_set(store, &iter, 0, working_icon, -1);
2797                         }
2798                         g_free(path);
2799                 }
2800                 GtkLabel *label;
2801                 gchar *status_str;
2802
2803                 status_str = working_status_string(ud, &status.queue);
2804                 label = GTK_LABEL(GHB_WIDGET(ud->builder, "queue_status"));
2805                 gtk_label_set_text (label, status_str);
2806 #if !GTK_CHECK_VERSION(2, 16, 0)
2807                 GtkStatusIcon *si;
2808
2809                 si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));
2810                 gtk_status_icon_set_tooltip(si, status_str);
2811 #endif
2812                 gtk_label_set_text (work_status, status_str);
2813                 gtk_progress_bar_set_fraction (progress, status.queue.progress);
2814                 g_free(status_str);
2815         }
2816         else if (status.queue.state & GHB_STATE_WORKDONE)
2817         {
2818                 gint qstatus;
2819
2820                 index = find_queue_job(ud->queue, status.queue.unique_id, &js);
2821                 treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "queue_list"));
2822                 store = GTK_TREE_STORE(gtk_tree_view_get_model(treeview));
2823                 if (ud->cancel_encode == GHB_CANCEL_ALL || 
2824                         ud->cancel_encode == GHB_CANCEL_CURRENT)
2825                         status.queue.error = GHB_ERROR_CANCELED;
2826                 switch( status.queue.error )
2827                 {
2828                         case GHB_ERROR_NONE:
2829                                 gtk_label_set_text (work_status, "Rip Done!");
2830                                 qstatus = GHB_QUEUE_DONE;
2831                                 if (js != NULL)
2832                                 {
2833                                         gchar *path = g_strdup_printf ("%d", index);
2834                                         if (gtk_tree_model_get_iter_from_string(
2835                                                         GTK_TREE_MODEL(store), &iter, path))
2836                                         {
2837                                                 gtk_tree_store_set(store, &iter, 0, "hb-complete", -1);
2838                                         }
2839                                         g_free(path);
2840                                 }
2841                                 break;
2842                         case GHB_ERROR_CANCELED:
2843                                 gtk_label_set_text (work_status, "Rip Canceled.");
2844                                 qstatus = GHB_QUEUE_CANCELED;
2845                                 if (js != NULL)
2846                                 {
2847                                         gchar *path = g_strdup_printf ("%d", index);
2848                                         if (gtk_tree_model_get_iter_from_string(
2849                                                         GTK_TREE_MODEL(store), &iter, path))
2850                                         {
2851                                                 gtk_tree_store_set(store, &iter, 0, "hb-canceled", -1);
2852                                         }
2853                                         g_free(path);
2854                                 }
2855                                 break;
2856                         default:
2857                                 gtk_label_set_text (work_status, "Rip Failed.");
2858                                 qstatus = GHB_QUEUE_CANCELED;
2859                                 if (js != NULL)
2860                                 {
2861                                         gchar *path = g_strdup_printf ("%d", index);
2862                                         if (gtk_tree_model_get_iter_from_string(
2863                                                         GTK_TREE_MODEL(store), &iter, path))
2864                                         {
2865                                                 gtk_tree_store_set(store, &iter, 0, "hb-canceled", -1);
2866                                         }
2867                                         g_free(path);
2868                                 }
2869                 }
2870                 gtk_progress_bar_set_fraction (progress, 1.0);
2871                 ghb_clear_queue_state(GHB_STATE_WORKDONE);
2872                 if (ud->job_activity_log)
2873                         g_io_channel_unref(ud->job_activity_log);
2874                 ud->job_activity_log = NULL;
2875                 if (ud->cancel_encode != GHB_CANCEL_ALL &&
2876                         ud->cancel_encode != GHB_CANCEL_FINISH)
2877                 {
2878                         ud->current_job = ghb_start_next_job(ud, FALSE);
2879                 }
2880                 else
2881                 {
2882                         ghb_uninhibit_gsm();
2883                         ud->current_job = NULL;
2884                         gtk_widget_hide(GTK_WIDGET(progress));
2885                 }
2886                 if (js)
2887                         ghb_settings_set_int(js, "job_status", qstatus);
2888                 ghb_save_queue(ud->queue);
2889                 ud->cancel_encode = GHB_CANCEL_NONE;
2890 #if !GTK_CHECK_VERSION(2, 16, 0)
2891                 GtkStatusIcon *si;
2892
2893                 si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));
2894                 gtk_status_icon_set_tooltip(si, "HandBrake");
2895 #endif
2896         }
2897         else if (status.queue.state & GHB_STATE_MUXING)
2898         {
2899                 gtk_label_set_text (work_status, "Muxing: This may take a while...");
2900         }
2901
2902         if (status.scan.state & GHB_STATE_WORKING)
2903         {
2904                 GtkProgressBar *live_progress;
2905                 live_progress = GTK_PROGRESS_BAR(
2906                         GHB_WIDGET(ud->builder, "live_encode_progress"));
2907                 status_str = working_status_string(ud, &status.scan);
2908                 gtk_progress_bar_set_text (live_progress, status_str);
2909                 gtk_progress_bar_set_fraction (live_progress, status.scan.progress);
2910                 g_free(status_str);
2911         }
2912         if (status.scan.state & GHB_STATE_WORKDONE)
2913         {
2914                 switch( status.scan.error )
2915                 {
2916                         case GHB_ERROR_NONE:
2917                         {
2918                                 ghb_live_encode_done(ud, TRUE);
2919                         } break;
2920                         default:
2921                         {
2922                                 ghb_live_encode_done(ud, FALSE);
2923                         } break;
2924                 }
2925                 ghb_clear_scan_state(GHB_STATE_WORKDONE);
2926         }
2927 }
2928
2929 #if GTK_CHECK_VERSION(2, 16, 0)
2930 G_MODULE_EXPORT gboolean
2931 status_icon_query_tooltip_cb(
2932         GtkStatusIcon *si,
2933         gint           x,
2934         gint           y,
2935         gboolean       kbd_mode,
2936         GtkTooltip    *tt,
2937         signal_user_data_t *ud)
2938 {
2939         ghb_status_t status;
2940         gchar *status_str;
2941
2942         ghb_get_status(&status);
2943         if (status.queue.state & GHB_STATE_WORKING)
2944                 status_str = working_status_string(ud, &status.queue);
2945         else if (status.queue.state & GHB_STATE_SEARCHING)
2946                 status_str = searching_status_string(ud, &status.queue);
2947         else if (status.queue.state & GHB_STATE_WORKDONE)
2948                 status_str = g_strdup("Encode Complete");
2949         else
2950                 status_str = g_strdup("HandBrake");
2951
2952         gtk_tooltip_set_text(tt, status_str);
2953         gtk_tooltip_set_icon_from_icon_name(tt, "hb-icon", GTK_ICON_SIZE_BUTTON);
2954         g_free(status_str);
2955         return TRUE;
2956 }
2957 #endif
2958
2959 G_MODULE_EXPORT gboolean
2960 ghb_timer_cb(gpointer data)
2961 {
2962         signal_user_data_t *ud = (signal_user_data_t*)data;
2963
2964         ghb_live_preview_progress(ud);
2965         ghb_backend_events(ud);
2966         if (update_default_destination)
2967         {
2968                 gchar *dest, *dest_dir, *def_dest;
2969                 dest = ghb_settings_get_string(ud->settings, "destination");
2970                 dest_dir = g_path_get_dirname (dest);
2971                 def_dest = ghb_settings_get_string(ud->settings, "destination_dir");
2972                 if (strcmp(dest_dir, def_dest) != 0)
2973                 {
2974                         ghb_settings_set_string (ud->settings, "destination_dir", dest_dir);
2975                         ghb_pref_save (ud->settings, "destination_dir");
2976                 }
2977                 g_free(dest);
2978                 g_free(dest_dir);
2979                 g_free(def_dest);
2980                 update_default_destination = FALSE;
2981         }
2982         if (update_preview)
2983         {
2984                 g_debug("Updating preview\n");
2985                 ghb_set_preview_image (ud);
2986                 update_preview = FALSE;
2987         }
2988
2989 #if !defined(_NO_UPDATE_CHECK)
2990         if (!appcast_busy)
2991         {
2992                 gchar *updates;
2993                 updates = ghb_settings_get_string(ud->settings, "check_updates");
2994                 gint64 duration = 0;
2995                 if (strcmp(updates, "daily") == 0)
2996                         duration = 60 * 60 * 24;
2997                 else if (strcmp(updates, "weekly") == 0)
2998                         duration = 60 * 60 * 24 * 7;
2999                 else if (strcmp(updates, "monthly") == 0)
3000                         duration = 60 * 60 * 24 * 7;
3001
3002                 g_free(updates);
3003                 if (duration != 0)
3004                 {
3005                         gint64 last;
3006                         time_t tt;
3007
3008                         last = ghb_settings_get_int64(ud->settings, "last_update_check");
3009                         time(&tt);
3010                         if (last + duration < tt)
3011                         {
3012                                 ghb_settings_set_int64(ud->settings, 
3013                                                                                 "last_update_check", tt);
3014                                 ghb_pref_save(ud->settings, "last_update_check");
3015                                 g_thread_create((GThreadFunc)ghb_check_update, ud, 
3016                                                                 FALSE, NULL);
3017                         }
3018                 }
3019         }
3020 #endif
3021         return TRUE;
3022 }
3023
3024 G_MODULE_EXPORT gboolean
3025 ghb_log_cb(GIOChannel *source, GIOCondition cond, gpointer data)
3026 {
3027         gchar *text = NULL;
3028         gsize length, outlength;
3029         GtkTextView *textview;
3030         GtkTextBuffer *buffer;
3031         GtkTextIter iter;
3032         GtkTextMark *mark;
3033         GError *gerror = NULL;
3034         GIOStatus status;
3035         
3036         signal_user_data_t *ud = (signal_user_data_t*)data;
3037
3038         status = g_io_channel_read_line (source, &text, &length, NULL, &gerror);
3039         // Trim nils from end of text, they cause g_io_channel_write_chars to
3040         // fail with an assertion that aborts
3041         while (length > 0 && text[length-1] == 0)
3042                 length--;
3043         if (text != NULL && length > 0)
3044         {
3045                 GdkWindow *window;
3046                 gint width, height;
3047                 gint x, y;
3048                 gboolean bottom = FALSE;
3049                 gchar *utf8_text;
3050
3051                 textview = GTK_TEXT_VIEW(GHB_WIDGET (ud->builder, "activity_view"));
3052                 buffer = gtk_text_view_get_buffer (textview);
3053                 // I would like to auto-scroll the window when the scrollbar
3054                 // is at the bottom, 
3055                 // must determine whether the insert point is at
3056                 // the bottom of the window 
3057                 window = gtk_text_view_get_window(textview, GTK_TEXT_WINDOW_TEXT);
3058                 if (window != NULL)
3059                 {
3060                         gdk_drawable_get_size(GDK_DRAWABLE(window), &width, &height);
3061                         gtk_text_view_window_to_buffer_coords(textview, 
3062                                 GTK_TEXT_WINDOW_TEXT, width, height, &x, &y);
3063                         gtk_text_view_get_iter_at_location(textview, &iter, x, y);
3064                         if (gtk_text_iter_is_end(&iter))
3065                         {
3066                                 bottom = TRUE;
3067                         }
3068                 }
3069                 else
3070                 {
3071                         // If the window isn't available, assume bottom
3072                         bottom = TRUE;
3073                 }
3074                 gtk_text_buffer_get_end_iter(buffer, &iter);
3075                 utf8_text = g_convert_with_fallback(text, -1, "UTF-8", "ISO-8859-1",
3076                                                                                         "?", NULL, &length, NULL);
3077                 if (utf8_text != NULL)
3078                 {
3079                         gtk_text_buffer_insert(buffer, &iter, utf8_text, -1);
3080                         if (bottom)
3081                         {
3082                                 gtk_text_buffer_get_end_iter(buffer, &iter);
3083                                 mark = gtk_text_buffer_create_mark(buffer, NULL, &iter, FALSE);
3084                                 gtk_text_view_scroll_mark_onscreen(textview, mark);
3085                                 gtk_text_buffer_delete_mark(buffer, mark);
3086                         }
3087 #if defined(_WIN32)
3088                         gsize one = 1;
3089                         utf8_text[length-1] = '\r';
3090 #endif
3091                         g_io_channel_write_chars (ud->activity_log, utf8_text, 
3092                                                                         length, &outlength, NULL);
3093 #if defined(_WIN32)
3094                         g_io_channel_write_chars (ud->activity_log, "\n", 
3095                                                                         one, &one, NULL);
3096 #endif
3097                         g_io_channel_flush(ud->activity_log, NULL);
3098                         if (ud->job_activity_log)
3099                         {
3100                                 g_io_channel_write_chars (ud->job_activity_log, utf8_text, 
3101                                                                                 length, &outlength, NULL);
3102 #if defined(_WIN32)
3103                                 g_io_channel_write_chars (ud->activity_log, "\n", 
3104                                                                                 one, &outlength, NULL);
3105 #endif
3106                                 g_io_channel_flush(ud->job_activity_log, NULL);
3107                         }
3108                         g_free(utf8_text);
3109                 }
3110         }
3111         if (text != NULL)
3112                 g_free(text);
3113
3114         if (status != G_IO_STATUS_NORMAL)
3115         {
3116                 // This should never happen, but if it does I would get into an
3117                 // infinite loop.  Returning false removes this callback.
3118                 g_warning("Error while reading activity from pipe");
3119                 if (gerror != NULL)
3120                 {
3121                         g_warning("%s", gerror->message);
3122                         g_error_free (gerror);
3123                 }
3124                 return FALSE;
3125         }
3126         if (gerror != NULL)
3127                 g_error_free (gerror);
3128         return TRUE;
3129 }
3130
3131 static void
3132 set_visible(GtkWidget *widget, gboolean visible)
3133 {
3134         if (visible)
3135         {
3136                 gtk_widget_show_now(widget);
3137         }
3138         else
3139         {
3140                 gtk_widget_hide(widget);
3141         }
3142 }
3143
3144 G_MODULE_EXPORT void
3145 show_activity_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
3146 {
3147         GtkWidget *widget = GHB_WIDGET (ud->builder, "activity_window");
3148         set_visible(widget, gtk_toggle_tool_button_get_active(
3149                                                 GTK_TOGGLE_TOOL_BUTTON(xwidget)));
3150 }
3151
3152 G_MODULE_EXPORT void
3153 show_activity_menu_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
3154 {
3155         GtkWidget *widget = GHB_WIDGET (ud->builder, "activity_window");
3156         set_visible(widget, TRUE);
3157         widget = GHB_WIDGET (ud->builder, "show_activity");
3158         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), TRUE);
3159 }
3160
3161 G_MODULE_EXPORT gboolean
3162 activity_window_delete_cb(GtkWidget *xwidget, GdkEvent *event, signal_user_data_t *ud)
3163 {
3164         set_visible(xwidget, FALSE);
3165         GtkWidget *widget = GHB_WIDGET (ud->builder, "show_activity");
3166         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), FALSE);
3167         return TRUE;
3168 }
3169
3170 void
3171 ghb_log(gchar *log, ...)
3172 {
3173         va_list args;
3174         time_t _now;
3175     struct tm *now;
3176         gchar fmt[362];
3177
3178         _now = time(NULL);
3179         now = localtime( &_now );
3180         snprintf(fmt, 362, "[%02d:%02d:%02d] gtkgui: %s\n", 
3181                         now->tm_hour, now->tm_min, now->tm_sec, log);
3182         va_start(args, log);
3183         vfprintf(stderr, fmt, args);
3184         va_end(args);
3185 }
3186
3187 static void
3188 browse_url(const gchar *url)
3189 {
3190 #if defined(_WIN32)
3191         HINSTANCE r;
3192         r = ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
3193 #else
3194         gboolean result;
3195         char *argv[] = 
3196                 {"xdg-open",NULL,NULL,NULL};
3197         argv[1] = (gchar*)url;
3198         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3199                                 NULL, NULL, NULL);
3200         if (result) return;
3201
3202         argv[0] = "gnome-open";
3203         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3204                                 NULL, NULL, NULL);
3205         if (result) return;
3206
3207         argv[0] = "kfmclient";
3208         argv[1] = "exec";
3209         argv[2] = "http://trac.handbrake.fr/wiki/HandBrakeGuide";
3210         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3211                                 NULL, NULL, NULL);
3212         if (result) return;
3213
3214         argv[0] = "firefox";
3215         argv[1] = "http://trac.handbrake.fr/wiki/HandBrakeGuide";
3216         argv[2] = NULL;
3217         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3218                                 NULL, NULL, NULL);
3219 #endif
3220 }
3221
3222 void
3223 about_web_hook(GtkAboutDialog *about, const gchar *link, gpointer data)
3224 {
3225         browse_url(link);
3226 }
3227
3228 G_MODULE_EXPORT void
3229 about_activate_cb(GtkWidget *xwidget, signal_user_data_t *ud)
3230 {
3231         GtkWidget *widget = GHB_WIDGET (ud->builder, "hb_about");
3232         gchar *ver;
3233
3234         ver = g_strdup_printf("%s (%s)", HB_PROJECT_VERSION, HB_PROJECT_BUILD_ARCH);
3235         gtk_about_dialog_set_url_hook(about_web_hook, NULL, NULL);
3236         gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(widget), ver);
3237         g_free(ver);
3238         gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(widget), 
3239                                                                 HB_PROJECT_URL_WEBSITE);
3240         gtk_about_dialog_set_website_label(GTK_ABOUT_DIALOG(widget), 
3241                                                                                 HB_PROJECT_URL_WEBSITE);
3242         gtk_widget_show (widget);
3243 }
3244
3245 G_MODULE_EXPORT void
3246 guide_activate_cb(GtkWidget *xwidget, signal_user_data_t *ud)
3247 {
3248         browse_url("http://trac.handbrake.fr/wiki/HandBrakeGuide");
3249 }
3250
3251 G_MODULE_EXPORT void
3252 hb_about_response_cb(GtkWidget *widget, gint response, signal_user_data_t *ud)
3253 {
3254         gtk_widget_hide (widget);
3255 }
3256
3257 G_MODULE_EXPORT void
3258 show_queue_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
3259 {
3260         GtkWidget *widget = GHB_WIDGET (ud->builder, "queue_window");
3261         set_visible(widget, gtk_toggle_tool_button_get_active(
3262                                                 GTK_TOGGLE_TOOL_BUTTON(xwidget)));
3263 }
3264
3265 G_MODULE_EXPORT void
3266 show_queue_menu_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
3267 {
3268         GtkWidget *widget = GHB_WIDGET (ud->builder, "queue_window");
3269         set_visible(widget, TRUE);
3270         widget = GHB_WIDGET (ud->builder, "show_queue");
3271         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), TRUE);
3272 }
3273
3274 G_MODULE_EXPORT gboolean
3275 queue_window_delete_cb(GtkWidget *xwidget, GdkEvent *event, signal_user_data_t *ud)
3276 {
3277         set_visible(xwidget, FALSE);
3278         GtkWidget *widget = GHB_WIDGET (ud->builder, "show_queue");
3279         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), FALSE);
3280         return TRUE;
3281 }
3282
3283 G_MODULE_EXPORT void
3284 show_presets_toggled_cb(GtkWidget *action, signal_user_data_t *ud)
3285 {
3286         GtkWidget *widget;
3287         GtkWindow *hb_window;
3288         
3289         g_debug("show_presets_clicked_cb ()");
3290         widget = GHB_WIDGET (ud->builder, "presets_frame");
3291         ghb_widget_to_setting(ud->settings, action);
3292         if (ghb_settings_get_boolean(ud->settings, "show_presets"))
3293         {
3294                 gtk_widget_show_now(widget);
3295         }
3296         else
3297         {
3298                 gtk_widget_hide(widget);
3299                 hb_window = GTK_WINDOW(GHB_WIDGET (ud->builder, "hb_window"));
3300                 gtk_window_resize(hb_window, 16, 16);
3301         }
3302         ghb_pref_save(ud->settings, "show_presets");
3303 }
3304
3305 static void
3306 reset_chapter_list(signal_user_data_t *ud, GValue *settings)
3307 {
3308         GtkTreeView *treeview;
3309         GtkTreeIter iter;
3310         GtkListStore *store;
3311         gboolean done;
3312         GValue *chapters;
3313         gint titleindex, ii;
3314         gint count;
3315         
3316         g_debug("reset_chapter_list ()");
3317         chapters = ghb_value_dup(ghb_settings_get_value(settings, "chapter_list"));
3318         count = ghb_array_len(chapters);
3319         ghb_settings_set_value(ud->settings, "chapter_list", chapters);
3320         titleindex = ghb_settings_combo_int(ud->settings, "title");
3321         
3322         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "chapters_list"));
3323         store = GTK_LIST_STORE(gtk_tree_view_get_model(treeview));
3324         ii = 0;
3325         if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter))
3326         {
3327                 do
3328                 {
3329
3330                         if (ii < count)
3331                         {
3332                                 gchar *chapter, *duration;
3333                                 gint hh, mm, ss;
3334
3335                                 // Update row with settings data
3336                                 g_debug("Updating row");
3337                                 chapter = ghb_value_string(ghb_array_get_nth(chapters, ii));
3338                                 ghb_get_chapter_duration(titleindex, ii, &hh, &mm, &ss);
3339                                 duration = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
3340                                 gtk_list_store_set(store, &iter, 
3341                                         0, ii+1,
3342                                         1, duration,
3343                                         2, chapter,
3344                                         3, TRUE,
3345                                         -1);
3346                                 g_free(chapter);
3347                                 g_free(duration);
3348                                 ii++;
3349                                 done = !gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
3350                         }
3351                         else
3352                         {
3353                                 // No more settings data, remove row
3354                                 g_debug("Removing row");
3355                                 done = !gtk_list_store_remove(store, &iter);
3356                         }
3357                 } while (!done);
3358         }
3359         while (ii < count)
3360         {
3361                 gchar *chapter, *duration;
3362                 gint hh, mm, ss;
3363
3364                 // Additional settings, add row
3365                 g_debug("Adding row");
3366                 chapter = ghb_value_string(ghb_array_get_nth(chapters, ii));
3367                 ghb_get_chapter_duration(titleindex, ii, &hh, &mm, &ss);
3368                 duration = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
3369                 gtk_list_store_append(store, &iter);
3370                 gtk_list_store_set(store, &iter, 
3371                         0, ii+1,
3372                         1, duration,
3373                         2, chapter,
3374                         3, TRUE,
3375                         -1);
3376                 g_free(chapter);
3377                 g_free(duration);
3378                 ii++;
3379         }
3380 }
3381
3382 static void
3383 update_chapter_list(signal_user_data_t *ud)
3384 {
3385         GtkTreeView *treeview;
3386         GtkTreeIter iter;
3387         GtkListStore *store;
3388         gboolean done;
3389         GValue *chapters;
3390         gint titleindex, ii;
3391         gint count;
3392         
3393         g_debug("update_chapter_list ()");
3394         titleindex = ghb_settings_combo_int(ud->settings, "title");
3395         chapters = ghb_get_chapters(titleindex);
3396         count = ghb_array_len(chapters);
3397         if (chapters)
3398                 ghb_settings_set_value(ud->settings, "chapter_list", chapters);
3399         
3400         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "chapters_list"));
3401         store = GTK_LIST_STORE(gtk_tree_view_get_model(treeview));
3402         ii = 0;
3403         if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter))
3404         {
3405                 do
3406                 {
3407
3408                         if (ii < count)
3409                         {
3410                                 gchar *chapter, *duration;
3411                                 gint hh, mm, ss;
3412
3413                                 // Update row with settings data
3414                                 g_debug("Updating row");
3415                                 chapter = ghb_value_string(ghb_array_get_nth(chapters, ii));
3416                                 ghb_get_chapter_duration(titleindex, ii, &hh, &mm, &ss);
3417                                 duration = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
3418                                 gtk_list_store_set(store, &iter, 
3419                                         0, ii+1,
3420                                         1, duration,
3421                                         2, chapter,
3422                                         3, TRUE,
3423                                         -1);
3424                                 g_free(chapter);
3425                                 g_free(duration);
3426                                 ii++;
3427                                 done = !gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
3428                         }
3429                         else
3430                         {
3431                                 // No more settings data, remove row
3432                                 g_debug("Removing row");
3433                                 done = !gtk_list_store_remove(store, &iter);
3434                         }
3435                 } while (!done);
3436         }
3437         while (ii < count)
3438         {
3439                 gchar *chapter, *duration;
3440                 gint hh, mm, ss;
3441
3442                 // Additional settings, add row
3443                 g_debug("Adding row");
3444                 chapter = ghb_value_string(ghb_array_get_nth(chapters, ii));
3445                 ghb_get_chapter_duration(titleindex, ii, &hh, &mm, &ss);
3446                 duration = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
3447                 gtk_list_store_append(store, &iter);
3448                 gtk_list_store_set(store, &iter, 
3449                         0, ii+1,
3450                         1, duration,
3451                         2, chapter,
3452                         3, TRUE,
3453                         -1);
3454                 g_free(chapter);
3455                 g_free(duration);
3456                 ii++;
3457         }
3458 }
3459
3460 static gint chapter_edit_key = 0;
3461
3462 G_MODULE_EXPORT gboolean
3463 chapter_keypress_cb(
3464         GhbCellRendererText *cell,
3465         GdkEventKey *event,
3466         signal_user_data_t *ud)
3467 {
3468         chapter_edit_key = event->keyval;
3469         return FALSE;
3470 }
3471
3472 G_MODULE_EXPORT void
3473 chapter_edited_cb(
3474         GhbCellRendererText *cell, 
3475         gchar *path, 
3476         gchar *text, 
3477         signal_user_data_t *ud)
3478 {
3479         GtkTreePath *treepath;
3480         GtkListStore *store;
3481         GtkTreeView *treeview;
3482         GtkTreeIter iter;
3483         gint index;
3484         gint *pi;
3485         gint row;
3486         
3487         g_debug("chapter_edited_cb ()");
3488         g_debug("path (%s)", path);
3489         g_debug("text (%s)", text);
3490         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "chapters_list"));
3491         store = GTK_LIST_STORE(gtk_tree_view_get_model(treeview));
3492         treepath = gtk_tree_path_new_from_string (path);
3493         pi = gtk_tree_path_get_indices(treepath);
3494         row = pi[0];
3495         gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, treepath);
3496         gtk_list_store_set(store, &iter, 
3497                 2, text,
3498                 3, TRUE,
3499                 -1);
3500         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &index, -1);
3501
3502         const GValue *chapters;
3503         GValue *chapter;
3504
3505         chapters = ghb_settings_get_value(ud->settings, "chapter_list");
3506         chapter = ghb_array_get_nth(chapters, index-1);
3507         g_value_set_string(chapter, text);
3508         if ((chapter_edit_key == GDK_Return || chapter_edit_key == GDK_Down) &&
3509                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter))
3510         {
3511                 GtkTreeViewColumn *column;
3512
3513                 gtk_tree_path_next(treepath);
3514                 // When a cell has been edited, I want to advance to the
3515                 // next cell and start editing it automaitcally.
3516                 // Unfortunately, we may not be in a state here where
3517                 // editing is allowed.  This happens when the user selects
3518                 // a new cell with the mouse instead of just hitting enter.
3519                 // Some kind of Gtk quirk.  widget_editable==NULL assertion.
3520                 // Editing is enabled again once the selection event has been
3521                 // processed.  So I'm queueing up a callback to be called
3522                 // when things go idle.  There, I will advance to the next
3523                 // cell and initiate editing.
3524                 //
3525                 // Now, you might be asking why I don't catch the keypress
3526                 // event and determine what action to take based on that.
3527                 // The Gtk developers in their infinite wisdom have made the 
3528                 // actual GtkEdit widget being used a private member of
3529                 // GtkCellRendererText, so it can not be accessed to hang a
3530                 // signal handler off of.  And they also do not propagate the
3531                 // keypress signals in any other way.  So that information is lost.
3532                 //g_idle_add((GSourceFunc)next_cell, ud);
3533                 //
3534                 // Keeping the above comment for posterity.
3535                 // I got industrious and made my own CellTextRendererText that
3536                 // passes on the key-press-event. So now I have much better
3537                 // control of this.
3538                 column = gtk_tree_view_get_column(treeview, 2);
3539                 gtk_tree_view_set_cursor(treeview, treepath, column, TRUE);
3540         }
3541         else if (chapter_edit_key == GDK_Up && row > 0)
3542         {
3543                 GtkTreeViewColumn *column;
3544                 gtk_tree_path_prev(treepath);
3545                 column = gtk_tree_view_get_column(treeview, 2);
3546                 gtk_tree_view_set_cursor(treeview, treepath, column, TRUE);
3547         }
3548         gtk_tree_path_free (treepath);
3549 }
3550
3551 void
3552 debug_log_handler(const gchar *domain, GLogLevelFlags flags, const gchar *msg, gpointer data)
3553 {
3554         signal_user_data_t *ud = (signal_user_data_t*)data;
3555         
3556         if (ud->debug)
3557         {
3558                 printf("%s: %s\n", domain, msg);
3559         }
3560 }
3561
3562 void
3563 warn_log_handler(const gchar *domain, GLogLevelFlags flags, const gchar *msg, gpointer data)
3564 {
3565         printf("%s: %s\n", domain, msg);
3566 }
3567
3568 void
3569 ghb_hbfd(signal_user_data_t *ud, gboolean hbfd)
3570 {
3571         GtkWidget *widget;
3572         g_debug("ghb_hbfd");
3573         widget = GHB_WIDGET(ud->builder, "queue_pause1");
3574         set_visible(widget, !hbfd);
3575         widget = GHB_WIDGET(ud->builder, "queue_add");
3576         set_visible(widget, !hbfd);
3577         widget = GHB_WIDGET(ud->builder, "show_queue");
3578         set_visible(widget, !hbfd);
3579         widget = GHB_WIDGET(ud->builder, "show_activity");
3580         set_visible(widget, !hbfd);
3581
3582         widget = GHB_WIDGET(ud->builder, "chapter_box");
3583         set_visible(widget, !hbfd);
3584         widget = GHB_WIDGET(ud->builder, "container_box");
3585         set_visible(widget, !hbfd);
3586         widget = GHB_WIDGET(ud->builder, "settings_box");
3587         set_visible(widget, !hbfd);
3588         widget = GHB_WIDGET(ud->builder, "presets_save");
3589         set_visible(widget, !hbfd);
3590         widget = GHB_WIDGET(ud->builder, "presets_remove");
3591         set_visible(widget, !hbfd);
3592         widget = GHB_WIDGET (ud->builder, "hb_window");
3593         gtk_window_resize(GTK_WINDOW(widget), 16, 16);
3594
3595 }
3596
3597 G_MODULE_EXPORT void
3598 hbfd_toggled_cb(GtkWidget *widget, signal_user_data_t *ud)
3599 {
3600         g_debug("hbfd_toggled_cb");
3601         ghb_widget_to_setting (ud->settings, widget);
3602         gboolean hbfd = ghb_settings_get_boolean(ud->settings, "hbfd");
3603         ghb_hbfd(ud, hbfd);
3604         ghb_pref_save(ud->settings, "hbfd");
3605 }
3606
3607 G_MODULE_EXPORT void
3608 pref_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
3609 {
3610         g_debug("pref_changed_cb");
3611         ghb_widget_to_setting (ud->settings, widget);
3612         ghb_check_dependency(ud, widget, NULL);
3613         const gchar *name = ghb_get_setting_key(widget);
3614         ghb_pref_save(ud->settings, name);
3615 }
3616
3617 G_MODULE_EXPORT void
3618 use_m4v_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
3619 {
3620         g_debug("use_m4v_changed_cb");
3621         ghb_widget_to_setting (ud->settings, widget);
3622         ghb_check_dependency(ud, widget, NULL);
3623         const gchar *name = ghb_get_setting_key(widget);
3624         ghb_pref_save(ud->settings, name);
3625         ghb_update_destination_extension(ud);
3626 }
3627
3628 G_MODULE_EXPORT void
3629 show_status_cb(GtkWidget *widget, signal_user_data_t *ud)
3630 {
3631         g_debug("show_status_cb");
3632         ghb_widget_to_setting (ud->settings, widget);
3633         ghb_check_dependency(ud, widget, NULL);
3634         const gchar *name = ghb_get_setting_key(widget);
3635         ghb_pref_save(ud->settings, name);
3636
3637         GtkStatusIcon *si;
3638
3639         si = GTK_STATUS_ICON(GHB_OBJECT (ud->builder, "hb_status"));
3640         gtk_status_icon_set_visible(si,
3641                         ghb_settings_get_boolean(ud->settings, "show_status"));
3642 }
3643
3644 G_MODULE_EXPORT void
3645 vqual_granularity_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
3646 {
3647         g_debug("vqual_granularity_changed_cb");
3648         ghb_widget_to_setting (ud->settings, widget);
3649         ghb_check_dependency(ud, widget, NULL);
3650
3651         const gchar *name = ghb_get_setting_key(widget);
3652         ghb_pref_save(ud->settings, name);
3653
3654         gdouble vqmin, vqmax, step, page;
3655         gboolean inverted;
3656         gint digits;
3657
3658         ghb_vquality_range(ud, &vqmin, &vqmax, &step, &page, &digits, &inverted);
3659         GtkWidget *qp = GHB_WIDGET(ud->builder, "VideoQualitySlider");
3660         gtk_range_set_increments (GTK_RANGE(qp), step, page);
3661 }
3662
3663 G_MODULE_EXPORT void
3664 tweaks_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
3665 {
3666         g_debug("tweaks_changed_cb");
3667         ghb_widget_to_setting (ud->settings, widget);
3668         const gchar *name = ghb_get_setting_key(widget);
3669         ghb_pref_save(ud->settings, name);
3670 }
3671
3672 G_MODULE_EXPORT void
3673 hbfd_feature_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
3674 {
3675         g_debug("hbfd_feature_changed_cb");
3676         ghb_widget_to_setting (ud->settings, widget);
3677         const gchar *name = ghb_get_setting_key(widget);
3678         ghb_pref_save(ud->settings, name);
3679
3680         gboolean hbfd = ghb_settings_get_boolean(ud->settings, "hbfd_feature");
3681         GtkAction *action;
3682         if (hbfd)
3683         {
3684                 const GValue *val;
3685                 val = ghb_settings_get_value(ud->settings, "hbfd");
3686                 ghb_ui_update(ud, "hbfd", val);
3687         }
3688         action = GHB_ACTION (ud->builder, "hbfd");
3689         gtk_action_set_visible(action, hbfd);
3690 }
3691
3692 gboolean
3693 ghb_file_menu_add_dvd(signal_user_data_t *ud)
3694 {
3695         GList *link, *drives;
3696         static GtkActionGroup *agroup = NULL;
3697         static gint merge_id;
3698
3699         g_debug("ghb_file_menu_add_dvd()");
3700         link = drives = dvd_device_list();
3701         if (drives != NULL)
3702         {
3703                 GtkUIManager *ui = GTK_UI_MANAGER(
3704                         gtk_builder_get_object(ud->builder, "uimanager1"));
3705
3706                 if (agroup == NULL)
3707                 {
3708                         agroup = gtk_action_group_new("dvdgroup");
3709                         gtk_ui_manager_insert_action_group(ui, agroup, 0);
3710                 }
3711                 else
3712                         gtk_ui_manager_remove_ui(ui, merge_id);
3713
3714                 merge_id = gtk_ui_manager_new_merge_id(ui);
3715                 // Add separator
3716                 gtk_ui_manager_add_ui(ui, merge_id, 
3717                         "ui/menubar1/menuitem1/quit1", "dvdsep", NULL,
3718                         GTK_UI_MANAGER_SEPARATOR, TRUE);
3719
3720                 while (link != NULL)
3721                 {
3722                         GtkAction *action;
3723                         gchar *drive = get_dvd_device_name(link->data);
3724                         gchar *name = get_dvd_volume_name(link->data);
3725                 
3726                         action = gtk_action_group_get_action(agroup, drive);
3727                         if (action != NULL)
3728                         {
3729                                 gtk_action_group_remove_action(agroup, action);
3730                                 g_object_unref(G_OBJECT(action));
3731                         }
3732                         // Create action for this drive
3733                         action = gtk_action_new(drive, name,
3734                                 "Scan this DVD source", "gtk-cdrom");
3735                         // Add action to action group
3736                         gtk_action_group_add_action_with_accel(agroup, action, NULL);
3737                         // Add to ui manager
3738                         gtk_ui_manager_add_ui(ui, merge_id, 
3739                                 "ui/menubar1/menuitem1/dvdsep", drive, drive,
3740                                 GTK_UI_MANAGER_AUTO, TRUE);
3741                         // Connect signal to action (menu item)
3742                         g_signal_connect(action, "activate", 
3743                                 (GCallback)dvd_source_activate_cb, ud);
3744                         g_free(name);
3745                         g_free(drive);
3746                         free_drive(link->data);
3747                         link = link->next;
3748                 }
3749                 g_list_free(drives);
3750         }
3751         return FALSE;
3752 }
3753
3754 gboolean ghb_is_cd(GDrive *gd);
3755
3756 static GList*
3757 dvd_device_list()
3758 {
3759         GList *dvd_devices = NULL;
3760
3761 #if defined(_WIN32)
3762         gint ii, drives;
3763         gchar drive[5];
3764
3765         strcpy(drive, "A:" G_DIR_SEPARATOR_S);
3766         drives = GetLogicalDrives();
3767         for (ii = 0; ii < 26; ii++)
3768         {
3769                 if (drives & 0x01)
3770                 {
3771                         guint dtype;
3772
3773                         drive[0] = 'A' + ii;
3774                         dtype = GetDriveType(drive);
3775                         if (dtype == DRIVE_CDROM)
3776                         {
3777                                 dvd_devices = g_list_append(dvd_devices, 
3778                                                 (gpointer)g_strdup(drive));
3779                         }
3780                 }
3781                 drives >>= 1;
3782         }
3783 #else
3784         GVolumeMonitor *gvm;
3785         GList *drives, *link;
3786         
3787         gvm = g_volume_monitor_get ();
3788         drives = g_volume_monitor_get_connected_drives (gvm);
3789         link = drives;
3790         while (link != NULL)
3791         {
3792                 GDrive *gd;
3793                 
3794                 gd = (GDrive*)link->data;
3795                 if (ghb_is_cd(gd))
3796                 {
3797                         dvd_devices = g_list_append(dvd_devices, gd);
3798                 }
3799                 else
3800                         g_object_unref (gd);
3801                 link = link->next;
3802         }
3803         g_list_free(drives);
3804 #endif
3805
3806         return dvd_devices;
3807 }
3808
3809 #if !defined(_WIN32)
3810 static GUdevClient *udev_ctx = NULL;
3811 #endif
3812
3813 gboolean
3814 ghb_is_cd(GDrive *gd)
3815 {
3816 #if !defined(_WIN32)
3817         gchar *device;
3818         GUdevDevice *udd;
3819
3820         if (udev_ctx == NULL)
3821                 return FALSE;
3822
3823         device = g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
3824         if (device == NULL)
3825                 return FALSE;
3826
3827         udd = g_udev_client_query_by_device_file(udev_ctx, device);
3828         g_free(device);
3829
3830         if (udd == NULL)
3831         {
3832                 g_message("udev: Failed to lookup device %s", device);
3833                 return FALSE;
3834         }
3835
3836         gint val;
3837         val = g_udev_device_get_property_as_int(udd, "ID_CDROM_DVD");
3838         if (val == 1)
3839                 return TRUE;
3840
3841         return FALSE;
3842 #else
3843         return FALSE;
3844 #endif
3845 }
3846
3847 void
3848 ghb_udev_init()
3849 {
3850 #if !defined(_WIN32)
3851         udev_ctx = g_udev_client_new(NULL);
3852 #endif
3853 }
3854
3855 #if defined(_WIN32)
3856 static void
3857 handle_media_change(const gchar *device, gboolean insert, signal_user_data_t *ud)
3858 {
3859         guint dtype;
3860         static gint ins_count = 0;
3861         static gint rem_count = 0;
3862
3863         // The media change event in windows bounces around a bit
3864         // so I debounce it here
3865         // DVD insertion detected.  Scan it.
3866         dtype = GetDriveType(device);
3867         if (dtype != DRIVE_CDROM)
3868                 return;
3869         if (insert)
3870         {
3871                 rem_count = 0;
3872                 ins_count++;
3873                 if (ins_count == 2)
3874                 {
3875                         g_thread_create((GThreadFunc)ghb_cache_volnames, ud, FALSE, NULL);
3876                         if (ghb_settings_get_boolean(ud->settings, "AutoScan") &&
3877                                 ud->current_dvd_device != NULL &&
3878                                 strcmp(device, ud->current_dvd_device) == 0)
3879                         {
3880                                 show_scan_progress(ud);
3881                                 update_source_label(ud, device, TRUE);
3882                                 gint preview_count;
3883                                 preview_count = ghb_settings_get_int(ud->settings, "preview_count");
3884                                 ghb_settings_set_string(ud->settings, "scan_source", device);
3885                                 start_scan(ud, device, 0, preview_count);
3886                         }
3887                 }
3888         }
3889         else
3890         {
3891                 ins_count = 0;
3892                 rem_count++;
3893                 if (rem_count == 2)
3894                 {
3895                         g_thread_create((GThreadFunc)ghb_cache_volnames, ud, FALSE, NULL);
3896                         if (ud->current_dvd_device != NULL &&
3897                                 strcmp(device, ud->current_dvd_device) == 0)
3898                         {
3899                                 ghb_hb_cleanup(TRUE);
3900                                 prune_logs(ud);
3901                                 ghb_settings_set_string(ud->settings, "scan_source", "/dev/null");
3902                                 start_scan(ud, "/dev/null", 0, 1);
3903                         }
3904                 }
3905         }
3906 }
3907
3908 static gchar
3909 FindDriveFromMask(ULONG unitmask)
3910 {
3911         gchar cc;
3912         for (cc = 0; cc < 26; cc++)
3913         {
3914                 if (unitmask & 0x01)
3915                         return 'A' + cc;
3916                 unitmask >>= 1;
3917         }
3918         return 0;
3919 }
3920
3921 void
3922 wm_drive_changed(MSG *msg, signal_user_data_t *ud)
3923 {
3924         PDEV_BROADCAST_HDR bch = (PDEV_BROADCAST_HDR)msg->lParam;
3925         gchar drive[4];
3926
3927         g_strlcpy(drive, "A:" G_DIR_SEPARATOR_S, 4);
3928         switch (msg->wParam)
3929         {
3930                 case DBT_DEVICEARRIVAL:
3931                 {
3932                         if (bch->dbch_devicetype == DBT_DEVTYP_VOLUME)
3933                         {
3934                                 PDEV_BROADCAST_VOLUME bcv = (PDEV_BROADCAST_VOLUME)bch;
3935
3936                                 if (bcv->dbcv_flags & DBTF_MEDIA)
3937                                 {
3938                                         drive[0] = FindDriveFromMask(bcv->dbcv_unitmask);
3939                                         handle_media_change(drive, TRUE, ud);
3940                                 }
3941                         }
3942                 } break;
3943
3944                 case DBT_DEVICEREMOVECOMPLETE:
3945                 {
3946                         if (bch->dbch_devicetype == DBT_DEVTYP_VOLUME)
3947                         {
3948                                 PDEV_BROADCAST_VOLUME bcv = (PDEV_BROADCAST_VOLUME)bch;
3949
3950                                 if (bcv->dbcv_flags & DBTF_MEDIA)
3951                                 {
3952                                         drive[0] = FindDriveFromMask(bcv->dbcv_unitmask);
3953                                         handle_media_change(drive, FALSE, ud);
3954                                 }
3955                         }
3956                 } break;
3957                 default: ;
3958         }
3959 }
3960
3961 #else
3962
3963 G_MODULE_EXPORT void
3964 drive_changed_cb(GVolumeMonitor *gvm, GDrive *gd, signal_user_data_t *ud)
3965 {
3966         gchar *device;
3967         gint state;
3968
3969         g_debug("drive_changed_cb()");
3970         g_thread_create((GThreadFunc)ghb_cache_volnames, ud, FALSE, NULL);
3971
3972         state = ghb_get_scan_state();
3973         device = g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
3974         if (ud->current_dvd_device == NULL ||
3975                 strcmp(device, ud->current_dvd_device) != 0 ||
3976                 state != GHB_STATE_IDLE )
3977         {
3978                 return;
3979         }
3980         if (g_drive_has_media(gd))
3981         {
3982                 if (ghb_settings_get_boolean(ud->settings, "AutoScan"))
3983                 {
3984                         show_scan_progress(ud);
3985                         update_source_label(ud, device, TRUE);
3986                         gint preview_count;
3987                         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
3988                         ghb_settings_set_string(ud->settings, "scan_source", device);
3989                         start_scan(ud, device, 0, preview_count);
3990                 }
3991         }
3992         else
3993         {
3994                 ghb_hb_cleanup(TRUE);
3995                 prune_logs(ud);
3996                 ghb_settings_set_string(ud->settings, "scan_source", "/dev/null");
3997                 start_scan(ud, "/dev/null", 0, 1);
3998         }
3999 }
4000 #endif
4001
4002 #if !defined(_WIN32)
4003 #define GPM_DBUS_PM_SERVICE                     "org.freedesktop.PowerManagement"
4004 #define GPM_DBUS_PM_PATH                        "/org/freedesktop/PowerManagement"
4005 #define GPM_DBUS_PM_INTERFACE           "org.freedesktop.PowerManagement"
4006 #define GPM_DBUS_INHIBIT_PATH           "/org/freedesktop/PowerManagement/Inhibit"
4007 #define GPM_DBUS_INHIBIT_INTERFACE      "org.freedesktop.PowerManagement.Inhibit" 
4008 static gboolean gpm_inhibited = FALSE;
4009 static guint gpm_cookie = -1;
4010 #endif
4011
4012 static gboolean
4013 ghb_can_suspend_gpm()
4014 {
4015         gboolean can_suspend = FALSE;
4016 #if !defined(_WIN32)
4017         DBusGConnection *conn;
4018         DBusGProxy      *proxy;
4019         GError *error = NULL;
4020         gboolean res;
4021         
4022
4023         g_debug("ghb_can_suspend_gpm()");
4024         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4025         if (error != NULL)
4026         {
4027                 g_warning("DBUS cannot connect: %s", error->message);
4028                 g_error_free(error);
4029                 return FALSE;
4030         }
4031         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_PM_SERVICE,
4032                                                         GPM_DBUS_PM_PATH, GPM_DBUS_PM_INTERFACE);
4033         if (proxy == NULL)
4034         {
4035                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_PM_SERVICE);
4036                 dbus_g_connection_unref(conn);
4037                 return FALSE;
4038         }
4039         res = dbus_g_proxy_call(proxy, "CanSuspend", &error,
4040                                                         G_TYPE_INVALID,
4041                                                         G_TYPE_BOOLEAN, &can_suspend,
4042                                                         G_TYPE_INVALID);
4043         if (!res)
4044         {
4045                 if (error != NULL)
4046                 {
4047                         g_warning("CanSuspend failed: %s", error->message);
4048                         g_error_free(error);
4049                 }
4050                 else
4051                         g_warning("CanSuspend failed");
4052                 // Try to shutdown anyway
4053                 can_suspend = TRUE;
4054         }
4055         g_object_unref(G_OBJECT(proxy));
4056         dbus_g_connection_unref(conn);
4057 #endif
4058         return can_suspend;
4059 }
4060
4061 static void
4062 ghb_suspend_gpm()
4063 {
4064 #if !defined(_WIN32)
4065         DBusGConnection *conn;
4066         DBusGProxy      *proxy;
4067         GError *error = NULL;
4068         gboolean res;
4069         
4070
4071         g_debug("ghb_suspend_gpm()");
4072         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4073         if (error != NULL)
4074         {
4075                 g_warning("DBUS cannot connect: %s", error->message);
4076                 g_error_free(error);
4077                 return;
4078         }
4079         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_PM_SERVICE,
4080                                                         GPM_DBUS_PM_PATH, GPM_DBUS_PM_INTERFACE);
4081         if (proxy == NULL)
4082         {
4083                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_PM_SERVICE);
4084                 dbus_g_connection_unref(conn);
4085                 return;
4086         }
4087         res = dbus_g_proxy_call(proxy, "Suspend", &error,
4088                                                         G_TYPE_INVALID,
4089                                                         G_TYPE_INVALID);
4090         if (!res)
4091         {
4092                 if (error != NULL)
4093                 {
4094                         g_warning("Suspend failed: %s", error->message);
4095                         g_error_free(error);
4096                 }
4097                 else
4098                         g_warning("Suspend failed");
4099         }
4100         g_object_unref(G_OBJECT(proxy));
4101         dbus_g_connection_unref(conn);
4102 #endif
4103 }
4104
4105 #if !defined(_WIN32)
4106 static gboolean
4107 ghb_can_shutdown_gpm()
4108 {
4109         gboolean can_shutdown = FALSE;
4110         DBusGConnection *conn;
4111         DBusGProxy      *proxy;
4112         GError *error = NULL;
4113         gboolean res;
4114         
4115
4116         g_debug("ghb_can_shutdown_gpm()");
4117         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4118         if (error != NULL)
4119         {
4120                 g_warning("DBUS cannot connect: %s", error->message);
4121                 g_error_free(error);
4122                 return FALSE;
4123         }
4124         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_PM_SERVICE,
4125                                                         GPM_DBUS_PM_PATH, GPM_DBUS_PM_INTERFACE);
4126         if (proxy == NULL)
4127         {
4128                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_PM_SERVICE);
4129                 dbus_g_connection_unref(conn);
4130                 return FALSE;
4131         }
4132         res = dbus_g_proxy_call(proxy, "CanShutdown", &error,
4133                                                         G_TYPE_INVALID,
4134                                                         G_TYPE_BOOLEAN, &can_shutdown,
4135                                                         G_TYPE_INVALID);
4136         if (!res)
4137         {
4138                 if (error != NULL)
4139                 {
4140                         g_warning("CanShutdown failed: %s", error->message);
4141                         g_error_free(error);
4142                 }
4143                 else
4144                         g_warning("CanShutdown failed");
4145                 // Try to shutdown anyway
4146                 can_shutdown = TRUE;
4147         }
4148         g_object_unref(G_OBJECT(proxy));
4149         dbus_g_connection_unref(conn);
4150         return can_shutdown;
4151 }
4152 #endif
4153
4154 #if !defined(_WIN32)
4155 static void
4156 ghb_shutdown_gpm()
4157 {
4158         DBusGConnection *conn;
4159         DBusGProxy      *proxy;
4160         GError *error = NULL;
4161         gboolean res;
4162         
4163
4164         g_debug("ghb_shutdown_gpm()");
4165         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4166         if (error != NULL)
4167         {
4168                 g_warning("DBUS cannot connect: %s", error->message);
4169                 g_error_free(error);
4170                 return;
4171         }
4172         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_PM_SERVICE,
4173                                                         GPM_DBUS_PM_PATH, GPM_DBUS_PM_INTERFACE);
4174         if (proxy == NULL)
4175         {
4176                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_PM_SERVICE);
4177                 dbus_g_connection_unref(conn);
4178                 return;
4179         }
4180         res = dbus_g_proxy_call(proxy, "Shutdown", &error,
4181                                                         G_TYPE_INVALID,
4182                                                         G_TYPE_INVALID);
4183         if (!res)
4184         {
4185                 if (error != NULL)
4186                 {
4187                         g_warning("Shutdown failed: %s", error->message);
4188                         g_error_free(error);
4189                 }
4190                 else
4191                         g_warning("Shutdown failed");
4192         }
4193         g_object_unref(G_OBJECT(proxy));
4194         dbus_g_connection_unref(conn);
4195 }
4196 #endif
4197
4198 void
4199 ghb_inhibit_gpm()
4200 {
4201 #if !defined(_WIN32)
4202         DBusGConnection *conn;
4203         DBusGProxy      *proxy;
4204         GError *error = NULL;
4205         gboolean res;
4206         
4207
4208         if (gpm_inhibited)
4209         {
4210                 // Already inhibited
4211                 return;
4212         }
4213         g_debug("ghb_inhibit_gpm()");
4214         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4215         if (error != NULL)
4216         {
4217                 g_warning("DBUS cannot connect: %s", error->message);
4218                 g_error_free(error);
4219                 return;
4220         }
4221         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_PM_SERVICE,
4222                                                         GPM_DBUS_INHIBIT_PATH, GPM_DBUS_INHIBIT_INTERFACE);
4223         if (proxy == NULL)
4224         {
4225                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_PM_SERVICE);
4226                 dbus_g_connection_unref(conn);
4227                 return;
4228         }
4229         res = dbus_g_proxy_call(proxy, "Inhibit", &error,
4230                                                         G_TYPE_STRING, "ghb",
4231                                                         G_TYPE_STRING, "Encoding",
4232                                                         G_TYPE_INVALID,
4233                                                         G_TYPE_UINT, &gpm_cookie,
4234                                                         G_TYPE_INVALID);
4235         gpm_inhibited = TRUE;
4236         if (!res)
4237         {
4238                 if (error != NULL)
4239                 {
4240                         g_warning("Inhibit failed: %s", error->message);
4241                         g_error_free(error);
4242                         gpm_cookie = -1;
4243                 }
4244                 else
4245                         g_warning("Inhibit failed");
4246                 gpm_cookie = -1;
4247                 gpm_inhibited = FALSE;
4248         }
4249         g_object_unref(G_OBJECT(proxy));
4250         dbus_g_connection_unref(conn);
4251 #endif
4252 }
4253
4254 void
4255 ghb_uninhibit_gpm()
4256 {
4257 #if !defined(_WIN32)
4258         DBusGConnection *conn;
4259         DBusGProxy      *proxy;
4260         GError *error = NULL;
4261         gboolean res;
4262         
4263         g_debug("ghb_uninhibit_gpm() gpm_cookie %u", gpm_cookie);
4264
4265         if (!gpm_inhibited)
4266         {
4267                 // Not inhibited
4268                 return;
4269         }
4270         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4271         if (error != NULL)
4272         {
4273                 g_warning("DBUS cannot connect: %s", error->message);
4274                 g_error_free(error);
4275                 return;
4276         }
4277         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_PM_SERVICE,
4278                                                         GPM_DBUS_INHIBIT_PATH, GPM_DBUS_INHIBIT_INTERFACE);
4279         if (proxy == NULL)
4280         {
4281                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_PM_SERVICE);
4282                 dbus_g_connection_unref(conn);
4283                 return;
4284         }
4285         res = dbus_g_proxy_call(proxy, "UnInhibit", &error,
4286                                                         G_TYPE_UINT, gpm_cookie,
4287                                                         G_TYPE_INVALID,
4288                                                         G_TYPE_INVALID);
4289         if (!res)
4290         {
4291                 if (error != NULL)
4292                 {
4293                         g_warning("UnInhibit failed: %s", error->message);
4294                         g_error_free(error);
4295                 }
4296                 else
4297                         g_warning("UnInhibit failed");
4298         }
4299         gpm_inhibited = FALSE;
4300         dbus_g_connection_unref(conn);
4301         g_object_unref(G_OBJECT(proxy));
4302 #endif
4303 }
4304
4305 #if !defined(_WIN32)
4306
4307 // For inhibit and shutdown
4308 #define GPM_DBUS_SM_SERVICE                     "org.gnome.SessionManager"
4309 #define GPM_DBUS_SM_PATH                        "/org/gnome/SessionManager"
4310 #define GPM_DBUS_SM_INTERFACE           "org.gnome.SessionManager"
4311
4312 #endif
4313
4314 static gboolean
4315 ghb_can_shutdown_gsm()
4316 {
4317         gboolean can_shutdown = FALSE;
4318 #if !defined(_WIN32)
4319         DBusGConnection *conn;
4320         DBusGProxy      *proxy;
4321         GError *error = NULL;
4322         gboolean res;
4323         
4324
4325         g_debug("ghb_can_shutdown_gpm()");
4326         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4327         if (error != NULL)
4328         {
4329                 g_warning("DBUS cannot connect: %s", error->message);
4330                 g_error_free(error);
4331                 return FALSE;
4332         }
4333         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_SM_SERVICE,
4334                                                         GPM_DBUS_SM_PATH, GPM_DBUS_SM_INTERFACE);
4335         if (proxy == NULL)
4336         {
4337                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_SM_SERVICE);
4338                 dbus_g_connection_unref(conn);
4339                 return FALSE;
4340         }
4341         res = dbus_g_proxy_call(proxy, "CanShutdown", &error,
4342                                                         G_TYPE_INVALID,
4343                                                         G_TYPE_BOOLEAN, &can_shutdown,
4344                                                         G_TYPE_INVALID);
4345         g_object_unref(G_OBJECT(proxy));
4346         dbus_g_connection_unref(conn);
4347         if (!res)
4348         {
4349                 if (error != NULL)
4350                 {
4351                         g_error_free(error);
4352                 }
4353                 // Try to shutdown anyway
4354                 can_shutdown = TRUE;
4355                 // Try the gpm version
4356                 return ghb_can_shutdown_gpm();
4357         }
4358 #endif
4359         return can_shutdown;
4360 }
4361
4362 static void
4363 ghb_shutdown_gsm()
4364 {
4365 #if !defined(_WIN32)
4366         DBusGConnection *conn;
4367         DBusGProxy      *proxy;
4368         GError *error = NULL;
4369         gboolean res;
4370         
4371
4372         g_debug("ghb_shutdown_gpm()");
4373         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4374         if (error != NULL)
4375         {
4376                 g_warning("DBUS cannot connect: %s", error->message);
4377                 g_error_free(error);
4378                 return;
4379         }
4380         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_SM_SERVICE,
4381                                                         GPM_DBUS_SM_PATH, GPM_DBUS_SM_INTERFACE);
4382         if (proxy == NULL)
4383         {
4384                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_SM_SERVICE);
4385                 dbus_g_connection_unref(conn);
4386                 return;
4387         }
4388         res = dbus_g_proxy_call(proxy, "Shutdown", &error,
4389                                                         G_TYPE_INVALID,
4390                                                         G_TYPE_INVALID);
4391         g_object_unref(G_OBJECT(proxy));
4392         dbus_g_connection_unref(conn);
4393         if (!res)
4394         {
4395                 if (error != NULL)
4396                 {
4397                         g_error_free(error);
4398                 }
4399                 // Try the gpm version
4400                 ghb_shutdown_gpm();
4401         }
4402 #endif
4403 }
4404
4405 void
4406 ghb_inhibit_gsm(signal_user_data_t *ud)
4407 {
4408 #if !defined(_WIN32)
4409         DBusGConnection *conn;
4410         DBusGProxy      *proxy;
4411         GError *error = NULL;
4412         gboolean res;
4413         guint xid;
4414         GtkWidget *widget;
4415         
4416
4417         if (gpm_inhibited)
4418         {
4419                 // Already inhibited
4420                 return;
4421         }
4422         g_debug("ghb_inhibit_gsm()");
4423         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4424         if (error != NULL)
4425         {
4426                 g_warning("DBUS cannot connect: %s", error->message);
4427                 g_error_free(error);
4428                 return;
4429         }
4430         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_SM_SERVICE,
4431                                                         GPM_DBUS_SM_PATH, GPM_DBUS_SM_INTERFACE);
4432         if (proxy == NULL)
4433         {
4434                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_SM_SERVICE);
4435                 dbus_g_connection_unref(conn);
4436                 return;
4437         }
4438         widget = GHB_WIDGET(ud->builder, "hb_window");
4439         xid = GDK_DRAWABLE_XID(widget->window);
4440         res = dbus_g_proxy_call(proxy, "Inhibit", &error,
4441                                                         G_TYPE_STRING, "ghb",
4442                                                         G_TYPE_UINT, xid,
4443                                                         G_TYPE_STRING, "Encoding",
4444                                                         G_TYPE_UINT, 1 | 4,
4445                                                         G_TYPE_INVALID,
4446                                                         G_TYPE_UINT, &gpm_cookie,
4447                                                         G_TYPE_INVALID);
4448         gpm_inhibited = TRUE;
4449         g_object_unref(G_OBJECT(proxy));
4450         dbus_g_connection_unref(conn);
4451         if (!res)
4452         {
4453                 if (error != NULL)
4454                 {
4455                         g_error_free(error);
4456                         gpm_cookie = -1;
4457                 }
4458                 gpm_cookie = -1;
4459                 gpm_inhibited = FALSE;
4460                 // Try the gpm version
4461                 ghb_inhibit_gpm();
4462         }
4463 #endif
4464 }
4465
4466 void
4467 ghb_uninhibit_gsm()
4468 {
4469 #if !defined(_WIN32)
4470         DBusGConnection *conn;
4471         DBusGProxy      *proxy;
4472         GError *error = NULL;
4473         gboolean res;
4474         
4475         g_debug("ghb_uninhibit_gsm() gpm_cookie %u", gpm_cookie);
4476
4477         if (!gpm_inhibited)
4478         {
4479                 // Not inhibited
4480                 return;
4481         }
4482         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
4483         if (error != NULL)
4484         {
4485                 g_warning("DBUS cannot connect: %s", error->message);
4486                 g_error_free(error);
4487                 return;
4488         }
4489         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_SM_SERVICE,
4490                                                         GPM_DBUS_SM_PATH, GPM_DBUS_SM_INTERFACE);
4491         if (proxy == NULL)
4492         {
4493                 g_warning("Could not get DBUS proxy: %s", GPM_DBUS_SM_SERVICE);
4494                 dbus_g_connection_unref(conn);
4495                 return;
4496         }
4497         res = dbus_g_proxy_call(proxy, "Uninhibit", &error,
4498                                                         G_TYPE_UINT, gpm_cookie,
4499                                                         G_TYPE_INVALID,
4500                                                         G_TYPE_INVALID);
4501         dbus_g_connection_unref(conn);
4502         g_object_unref(G_OBJECT(proxy));
4503         if (!res)
4504         {
4505                 if (error != NULL)
4506                 {
4507                         g_error_free(error);
4508                 }
4509                 ghb_uninhibit_gpm();
4510         }
4511         gpm_inhibited = FALSE;
4512 #endif
4513 }
4514
4515 G_MODULE_EXPORT gboolean 
4516 tweak_setting_cb(
4517         GtkWidget *widget, 
4518         GdkEventButton *event, 
4519         signal_user_data_t *ud)
4520 {
4521         const gchar *name;
4522         gchar *tweak_name;
4523         gboolean ret = FALSE;
4524         gboolean allow_tweaks;
4525
4526         g_debug("press %d %d", event->type, event->button);
4527         allow_tweaks = ghb_settings_get_boolean(ud->settings, "allow_tweaks");
4528         if (allow_tweaks && event->type == GDK_BUTTON_PRESS && event->button == 3)
4529         { // Its a right mouse click
4530                 GtkWidget *dialog;
4531                 GtkEntry *entry;
4532                 GtkResponseType response;
4533                 gchar *tweak = NULL;
4534
4535                 name = ghb_get_setting_key(widget);
4536                 if (g_str_has_prefix(name, "tweak_"))
4537                 {
4538                         tweak_name = g_strdup(name);
4539                 }
4540                 else
4541                 {
4542                         tweak_name = g_strdup_printf("tweak_%s", name);
4543                 }
4544
4545                 tweak = ghb_settings_get_string (ud->settings, tweak_name);
4546                 dialog = GHB_WIDGET(ud->builder, "tweak_dialog");
4547                 gtk_window_set_title(GTK_WINDOW(dialog), tweak_name);
4548                 entry = GTK_ENTRY(GHB_WIDGET(ud->builder, "tweak_setting"));
4549                 if (tweak)
4550                 {
4551                         gtk_entry_set_text(entry, tweak);
4552                         g_free(tweak);
4553                 }
4554                 response = gtk_dialog_run(GTK_DIALOG(dialog));
4555                 gtk_widget_hide(dialog);
4556                 if (response == GTK_RESPONSE_OK)
4557                 {
4558                         tweak = (gchar*)gtk_entry_get_text(entry);
4559                         if (ghb_validate_filter_string(tweak, -1))
4560                                 ghb_settings_set_string(ud->settings, tweak_name, tweak);
4561                         else
4562                         {
4563                                 gchar *message;
4564                                 message = g_strdup_printf(
4565                                                         "Invalid Settings:\n%s",
4566                                                         tweak);
4567                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
4568                                 g_free(message);
4569                         }
4570                 }
4571                 g_free(tweak_name);
4572                 ret = TRUE;
4573         }
4574         return ret;
4575 }
4576
4577 G_MODULE_EXPORT gboolean 
4578 easter_egg_cb(
4579         GtkWidget *widget, 
4580         GdkEventButton *event, 
4581         signal_user_data_t *ud)
4582 {
4583         g_debug("press %d %d", event->type, event->button);
4584         if (event->type == GDK_3BUTTON_PRESS && event->button == 1)
4585         { // Its a tripple left mouse button click
4586                 GtkWidget *widget;
4587                 widget = GHB_WIDGET(ud->builder, "allow_tweaks");
4588                 gtk_widget_show(widget);
4589                 widget = GHB_WIDGET(ud->builder, "hbfd_feature");
4590                 gtk_widget_show(widget);
4591         }
4592         else if (event->type == GDK_BUTTON_PRESS && event->button == 1)
4593         {
4594                 GtkWidget *widget;
4595                 widget = GHB_WIDGET(ud->builder, "allow_tweaks");
4596                 gtk_widget_hide(widget);
4597                 widget = GHB_WIDGET(ud->builder, "hbfd_feature");
4598                 gtk_widget_hide(widget);
4599         }
4600         return FALSE;
4601 }
4602
4603 G_MODULE_EXPORT gchar*
4604 format_deblock_cb(GtkScale *scale, gdouble val, signal_user_data_t *ud)
4605 {
4606         if (val < 5.0)
4607         {
4608                 return g_strdup_printf("Off");
4609         }
4610         else
4611         {
4612                 return g_strdup_printf("%d", (gint)val);
4613         }
4614 }
4615
4616 G_MODULE_EXPORT gchar*
4617 format_drc_cb(GtkScale *scale, gdouble val, signal_user_data_t *ud)
4618 {
4619         if (val <= 0.0)
4620         {
4621                 return g_strdup_printf("Off");
4622         }
4623         else
4624         {
4625                 return g_strdup_printf("%.1f", val);
4626         }
4627 }
4628
4629 G_MODULE_EXPORT gchar*
4630 format_vquality_cb(GtkScale *scale, gdouble val, signal_user_data_t *ud)
4631 {
4632         gint vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
4633         switch (vcodec)
4634         {
4635                 case HB_VCODEC_X264:
4636                 {
4637                         if (val == 0.0)
4638                         {
4639                                 return g_strdup_printf("RF: %.4g (Warning: lossless)", val);
4640                         }
4641                         else
4642                         {
4643                                 return g_strdup_printf("RF: %.4g", val);
4644                         }
4645                 } break;
4646
4647                 case HB_VCODEC_FFMPEG:
4648                 {
4649                         return g_strdup_printf("QP: %d", (int)val);
4650                 } break;
4651
4652                 case HB_VCODEC_THEORA:
4653                 {
4654                         return g_strdup_printf("QP: %d", (int)val);
4655                 } break;
4656
4657                 default:
4658                 {
4659                 } break;
4660         }
4661         return g_strdup_printf("QP: %.4g", val);
4662 }
4663
4664 static void
4665 process_appcast(signal_user_data_t *ud)
4666 {
4667         gchar *description = NULL, *build = NULL, *version = NULL, *msg;
4668 #if !defined(_WIN32)
4669         GtkWidget *window;
4670         static GtkWidget *html = NULL;
4671 #endif
4672         GtkWidget *dialog, *label;
4673         gint    response, ibuild = 0, skip;
4674
4675         if (ud->appcast == NULL || ud->appcast_len < 15 || 
4676                 strncmp(&(ud->appcast[9]), "200 OK", 6))
4677         {
4678                 goto done;
4679         }
4680         ghb_appcast_parse(ud->appcast, &description, &build, &version);
4681         if (build)
4682                 ibuild = g_strtod(build, NULL);
4683         skip = ghb_settings_get_int(ud->settings, "update_skip_version");
4684         if (description == NULL || build == NULL || version == NULL 
4685                 || ibuild <= hb_get_build(NULL) || skip == ibuild)
4686         {
4687                 goto done;
4688         }
4689         msg = g_strdup_printf("HandBrake %s/%s is now available (you have %s/%d).",
4690                         version, build, hb_get_version(NULL), hb_get_build(NULL));
4691         label = GHB_WIDGET(ud->builder, "update_message");
4692         gtk_label_set_text(GTK_LABEL(label), msg);
4693
4694 #if !defined(_WIN32)
4695 #if !defined(_NO_UPDATE_CHECK)
4696         if (html == NULL)
4697         {
4698                 html = webkit_web_view_new();
4699                 window = GHB_WIDGET(ud->builder, "update_scroll");
4700                 gtk_container_add(GTK_CONTAINER(window), html);
4701                 // Show it
4702                 gtk_widget_set_size_request(html, 420, 240);
4703                 gtk_widget_show(html);
4704         }
4705         webkit_web_view_open(WEBKIT_WEB_VIEW(html), description);
4706 #endif
4707 #endif
4708         dialog = GHB_WIDGET(ud->builder, "update_dialog");
4709         response = gtk_dialog_run(GTK_DIALOG(dialog));
4710         gtk_widget_hide(dialog);
4711         if (response == GTK_RESPONSE_OK)
4712         {
4713                 // Skip
4714                 ghb_settings_set_int(ud->settings, "update_skip_version", ibuild);
4715                 ghb_pref_save(ud->settings, "update_skip_version");
4716         }
4717         g_free(msg);
4718
4719 done:
4720         if (description) g_free(description);
4721         if (build) g_free(build);
4722         if (version) g_free(version);
4723         g_free(ud->appcast);
4724         ud->appcast_len = 0;
4725         ud->appcast = NULL;
4726         appcast_busy = FALSE;
4727 }
4728
4729 void
4730 ghb_net_close(GIOChannel *ioc)
4731 {
4732         gint fd;
4733
4734         g_debug("ghb_net_close");
4735         if (ioc == NULL) return;
4736         fd = g_io_channel_unix_get_fd(ioc);
4737         close(fd);
4738         g_io_channel_unref(ioc);
4739 }
4740
4741 G_MODULE_EXPORT gboolean
4742 ghb_net_recv_cb(GIOChannel *ioc, GIOCondition cond, gpointer data)
4743 {
4744         gchar buf[2048];
4745         gsize len;
4746         GError *gerror = NULL;
4747         GIOStatus status;
4748         
4749         g_debug("ghb_net_recv_cb");
4750         signal_user_data_t *ud = (signal_user_data_t*)data;
4751
4752         status = g_io_channel_read_chars (ioc, buf, 2048, &len, &gerror);
4753         if ((status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_EOF) &&
4754                 len > 0)
4755         {
4756                 gint new_len = ud->appcast_len + len;
4757                 ud->appcast = g_realloc(ud->appcast, new_len + 1);
4758                 memcpy(&(ud->appcast[ud->appcast_len]), buf, len);
4759                 ud->appcast_len = new_len;
4760         }
4761         if (status == G_IO_STATUS_EOF)
4762         {
4763                 if ( ud->appcast != NULL )
4764                 {
4765                         ud->appcast[ud->appcast_len] = 0;
4766                 }
4767                 ghb_net_close(ioc);
4768                 process_appcast(ud);
4769                 return FALSE;
4770         }
4771         return TRUE;
4772 }
4773
4774 GIOChannel*
4775 ghb_net_open(signal_user_data_t *ud, gchar *address, gint port)
4776 {
4777         GIOChannel *ioc;
4778         gint fd;
4779
4780         struct sockaddr_in   sock;
4781         struct hostent     * host;
4782
4783         g_debug("ghb_net_open");
4784         if( !( host = gethostbyname( address ) ) )
4785         {
4786                 g_warning( "gethostbyname failed (%s)", address );
4787                 appcast_busy = FALSE;
4788                 return NULL;
4789         }
4790
4791         memset( &sock, 0, sizeof( struct sockaddr_in ) );
4792         sock.sin_family = host->h_addrtype;
4793         sock.sin_port   = htons( port );
4794         memcpy( &sock.sin_addr, host->h_addr, host->h_length );
4795
4796         fd = socket(host->h_addrtype, SOCK_STREAM, 0);
4797         if( fd < 0 )
4798         {
4799                 g_debug( "socket failed" );
4800                 appcast_busy = FALSE;
4801                 return NULL;
4802         }
4803
4804         if(connect(fd, (struct sockaddr*)&sock, sizeof(struct sockaddr_in )) < 0 )
4805         {
4806                 g_debug( "connect failed" );
4807                 appcast_busy = FALSE;
4808                 return NULL;
4809         }
4810         ioc = g_io_channel_unix_new(fd);
4811         g_io_channel_set_encoding (ioc, NULL, NULL);
4812         g_io_channel_set_flags(ioc, G_IO_FLAG_NONBLOCK, NULL);
4813         g_io_add_watch (ioc, G_IO_IN, ghb_net_recv_cb, (gpointer)ud );
4814
4815         return ioc;
4816 }
4817
4818 gpointer
4819 ghb_check_update(signal_user_data_t *ud)
4820 {
4821         gchar *query;
4822         gsize len;
4823         GIOChannel *ioc;
4824         GError *gerror = NULL;
4825         GRegex *regex;
4826         GMatchInfo *mi;
4827         gchar *host, *appcast;
4828
4829         g_debug("ghb_check_update");
4830         appcast_busy = TRUE;
4831         regex = g_regex_new("^http://(.+)/(.+)$", 0, 0, NULL);
4832         if (!g_regex_match(regex, HB_PROJECT_URL_APPCAST, 0, &mi))
4833         {
4834                 return NULL;
4835         }
4836
4837         host = g_match_info_fetch(mi, 1);
4838         appcast = g_match_info_fetch(mi, 2);
4839
4840         if (host == NULL || appcast == NULL)
4841                 return NULL;
4842
4843         query = g_strdup_printf( "GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n",
4844                                                         appcast, host);
4845
4846         ioc = ghb_net_open(ud, host, 80);
4847         if (ioc == NULL)
4848                 return NULL;
4849
4850         g_io_channel_write_chars(ioc, query, strlen(query), &len, &gerror);
4851         g_io_channel_flush(ioc, &gerror);
4852         g_free(query);
4853         g_free(host);
4854         g_free(appcast);
4855         g_match_info_free(mi);
4856         g_regex_unref(regex);
4857         return NULL;
4858 }
4859
4860 G_MODULE_EXPORT gboolean
4861 hb_visibility_event_cb(
4862         GtkWidget *widget, 
4863         GdkEventVisibility *vs, 
4864         signal_user_data_t *ud)
4865 {
4866         ud->hb_visibility = vs->state;
4867         return FALSE;
4868 }
4869
4870 G_MODULE_EXPORT void
4871 status_activate_cb(GtkStatusIcon *si, signal_user_data_t *ud)
4872 {
4873         GtkWindow *window;
4874         GdkWindowState state;
4875
4876         window = GTK_WINDOW(GHB_WIDGET(ud->builder, "hb_window"));
4877         state = gdk_window_get_state(GTK_WIDGET(window)->window);
4878         if ((state & GDK_WINDOW_STATE_ICONIFIED) ||
4879                 (ud->hb_visibility != GDK_VISIBILITY_UNOBSCURED))
4880         {
4881                 gtk_window_present(window);
4882                 gtk_window_set_skip_taskbar_hint(window, FALSE);
4883         }
4884         else
4885         {
4886                 gtk_window_set_skip_taskbar_hint(window, TRUE);
4887                 gtk_window_iconify(window);
4888         }
4889 }
4890
4891 #if !defined(_WIN32)
4892 G_MODULE_EXPORT void
4893 notify_closed_cb(NotifyNotification *notification, signal_user_data_t *ud)
4894 {
4895         g_object_unref(G_OBJECT(notification));
4896 }
4897 #endif
4898
4899 void
4900 ghb_notify_done(signal_user_data_t *ud)
4901 {
4902         GtkStatusIcon *si;
4903
4904         if (ghb_settings_combo_int(ud->settings, "WhenComplete") == 0)
4905                 return;
4906
4907         si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));
4908
4909 #if !defined(_WIN32)
4910         NotifyNotification *notification;
4911         notification = notify_notification_new(
4912                 "Encode Complete",
4913                 "Put down that cocktail, Your HandBrake queue is done!",
4914                 "hb-icon",
4915                 NULL);
4916         notify_notification_attach_to_status_icon(notification, si);
4917         g_signal_connect(notification, "closed", (GCallback)notify_closed_cb, ud);
4918         notify_notification_show(notification, NULL);
4919 #endif
4920
4921         if (ghb_settings_combo_int(ud->settings, "WhenComplete") == 3)
4922         {
4923                 if (ghb_can_shutdown_gsm())
4924                 {
4925                         ghb_countdown_dialog(GTK_MESSAGE_WARNING, 
4926                                 "Your encode is complete.",
4927                                 "Shutting down the computer", 
4928                                 "Cancel", (GSourceFunc)shutdown_cb, ud, 60);
4929                 }
4930         }
4931         if (ghb_settings_combo_int(ud->settings, "WhenComplete") == 2)
4932         {
4933                 if (ghb_can_suspend_gpm())
4934                 {
4935                         ghb_countdown_dialog(GTK_MESSAGE_WARNING, 
4936                                 "Your encode is complete.",
4937                                 "Putting computer to sleep", 
4938                                 "Cancel", (GSourceFunc)suspend_cb, ud, 60);
4939                 }
4940         }
4941         if (ghb_settings_combo_int(ud->settings, "WhenComplete") == 4)
4942         {
4943                 ghb_countdown_dialog(GTK_MESSAGE_WARNING, 
4944                                                         "Your encode is complete.",
4945                                                         "Quiting Handbrake", 
4946                                                         "Cancel", (GSourceFunc)quit_cb, ud, 60);
4947         }
4948 }