OSDN Git Service

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