OSDN Git Service

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