OSDN Git Service

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