OSDN Git Service

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