OSDN Git Service

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