OSDN Git Service

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