OSDN Git Service

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