OSDN Git Service

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