OSDN Git Service

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