OSDN Git Service

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