OSDN Git Service

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