OSDN Git Service

LinGui: more anamorphic settings changes
[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 <poll.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <netinet/in.h>
23 #include <netdb.h>
24 #include <libhal-storage.h>
25 #include <gtk/gtk.h>
26 #include <gtkhtml/gtkhtml.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <glib/gstdio.h>
29 #include <dbus/dbus-glib.h>
30 #include <dbus/dbus-glib-lowlevel.h>
31 #include <gio/gio.h>
32 #include <libnotify/notify.h>
33
34 #include "hb.h"
35 #include "callbacks.h"
36 #include "queuehandler.h"
37 #include "audiohandler.h"
38 #include "resources.h"
39 #include "settings.h"
40 #include "presets.h"
41 #include "preview.h"
42 #include "values.h"
43 #include "plist.h"
44 #include "appcast.h"
45 #include "hb-backend.h"
46 #include "ghb-dvd.h"
47 #include "ghbcellrenderertext.h"
48
49 static void update_chapter_list(signal_user_data_t *ud);
50 static GList* dvd_device_list();
51 static void prune_logs(signal_user_data_t *ud);
52 void ghb_notify_done(signal_user_data_t *ud);
53
54 // This is a dependency map used for greying widgets
55 // that are dependent on the state of another widget.
56 // The enable_value comes from the values that are
57 // obtained from ghb_widget_value().  For combo boxes
58 // you will have to look further to combo box options
59 // maps in hb-backend.c
60
61 GValue *dep_map;
62 GValue *rev_map;
63
64 void
65 ghb_init_dep_map()
66 {
67         dep_map = ghb_resource_get("widget-deps");
68         rev_map = ghb_resource_get("widget-reverse-deps");
69 }
70
71 static gboolean
72 dep_check(signal_user_data_t *ud, const gchar *name, gboolean *out_hide)
73 {
74         GtkWidget *widget;
75         GObject *dep_object;
76         gint ii;
77         gint count;
78         gboolean result = TRUE;
79         GValue *array, *data;
80         gchar *widget_name;
81         
82         g_debug("dep_check () %s", name);
83
84         if (rev_map == NULL) return TRUE;
85         array = ghb_dict_lookup(rev_map, name);
86         count = ghb_array_len(array);
87         *out_hide = FALSE;
88         for (ii = 0; ii < count; ii++)
89         {
90                 data = ghb_array_get_nth(array, ii);
91                 widget_name = ghb_value_string(ghb_array_get_nth(data, 0));
92                 widget = GHB_WIDGET(ud->builder, widget_name);
93                 dep_object = gtk_builder_get_object(ud->builder, name);
94                 g_free(widget_name);
95                 if (!GTK_WIDGET_SENSITIVE(widget))
96                         continue;
97                 if (dep_object == NULL)
98                 {
99                         g_message("Failed to find widget");
100                 }
101                 else
102                 {
103                         gchar *value;
104                         gint jj = 0;
105                         gchar **values;
106                         gboolean sensitive = FALSE;
107                         gboolean die, hide;
108
109                         die = ghb_value_boolean(ghb_array_get_nth(data, 2));
110                         hide = ghb_value_boolean(ghb_array_get_nth(data, 3));
111                         value = ghb_value_string(ghb_array_get_nth(data, 1));
112                         values = g_strsplit(value, "|", 10);
113                         g_free(value);
114
115                         if (widget)
116                                 value = ghb_widget_string(widget);
117                         else
118                                 value = ghb_settings_get_string(ud->settings, name);
119                         while (values && values[jj])
120                         {
121                                 if (values[jj][0] == '>')
122                                 {
123                                         gdouble dbl = g_strtod (&values[jj][1], NULL);
124                                         gdouble dvalue = ghb_widget_double(widget);
125                                         if (dvalue > dbl)
126                                         {
127                                                 sensitive = TRUE;
128                                                 break;
129                                         }
130                                 }
131                                 else if (values[jj][0] == '<')
132                                 {
133                                         gdouble dbl = g_strtod (&values[jj][1], NULL);
134                                         gdouble dvalue = ghb_widget_double(widget);
135                                         if (dvalue < dbl)
136                                         {
137                                                 sensitive = TRUE;
138                                                 break;
139                                         }
140                                 }
141                                 if (strcmp(values[jj], value) == 0)
142                                 {
143                                         sensitive = TRUE;
144                                         break;
145                                 }
146                                 jj++;
147                         }
148                         sensitive = die ^ sensitive;
149                         if (!sensitive)
150                         {
151                                 result = FALSE;
152                                 *out_hide |= hide;
153                         }
154                         g_strfreev (values);
155                         g_free(value);
156                 }
157         }
158         return result;
159 }
160
161 void
162 ghb_check_dependency(signal_user_data_t *ud, GtkWidget *widget)
163 {
164         GObject *dep_object;
165         const gchar *name;
166         GValue *array, *data;
167         gint count, ii;
168         gchar *dep_name;
169         GType type;
170
171         type = GTK_WIDGET_TYPE(widget);
172         if (type == GTK_TYPE_COMBO_BOX || type == GTK_TYPE_COMBO_BOX_ENTRY)
173                 if (gtk_combo_box_get_active(GTK_COMBO_BOX(widget)) < 0) return;
174
175         name = gtk_widget_get_name(widget);
176         g_debug("ghb_check_dependency () %s", name);
177
178         if (dep_map == NULL) return;
179         array = ghb_dict_lookup(dep_map, name);
180         count = ghb_array_len(array);
181         for (ii = 0; ii < count; ii++)
182         {
183                 gboolean sensitive;
184                 gboolean hide;
185
186                 data = ghb_array_get_nth(array, ii);
187                 dep_name = ghb_value_string(data);
188                 dep_object = gtk_builder_get_object(ud->builder, dep_name);
189                 if (dep_object == NULL)
190                 {
191                         g_message("Failed to find dependent widget %s", dep_name);
192                         g_free(dep_name);
193                         continue;
194                 }
195                 sensitive = dep_check(ud, dep_name, &hide);
196                 g_free(dep_name);
197                 if (GTK_IS_ACTION(dep_object))
198                 {
199                         gtk_action_set_sensitive(GTK_ACTION(dep_object), sensitive);
200                         gtk_action_set_visible(GTK_ACTION(dep_object), sensitive || !hide);
201                 }
202                 else
203                 {
204                         gtk_widget_set_sensitive(GTK_WIDGET(dep_object), sensitive);
205                         if (!sensitive && hide)
206                         {
207                                 gtk_widget_hide(GTK_WIDGET(dep_object));
208                         }
209                         else
210                         {
211                                 gtk_widget_show_now(GTK_WIDGET(dep_object));
212                         }
213                 }
214         }
215 }
216
217 void
218 ghb_check_all_depencencies(signal_user_data_t *ud)
219 {
220         GHashTableIter iter;
221         gchar *dep_name;
222         GValue *value;
223         GObject *dep_object;
224
225         g_debug("ghb_check_all_depencencies ()");
226         if (rev_map == NULL) return;
227         ghb_dict_iter_init(&iter, rev_map);
228         // middle (void*) cast prevents gcc warning "defreferencing type-punned
229         // pointer will break strict-aliasing rules"
230         while (g_hash_table_iter_next(
231                         &iter, (gpointer*)(void*)&dep_name, (gpointer*)(void*)&value))
232         {
233                 gboolean sensitive;
234                 gboolean hide;
235
236                 dep_object = gtk_builder_get_object (ud->builder, dep_name);
237                 if (dep_object == NULL)
238                 {
239                         g_message("Failed to find dependent widget %s", dep_name);
240                         continue;
241                 }
242                 sensitive = dep_check(ud, dep_name, &hide);
243                 if (GTK_IS_ACTION(dep_object))
244                 {
245                         gtk_action_set_sensitive(GTK_ACTION(dep_object), sensitive);
246                         gtk_action_set_visible(GTK_ACTION(dep_object), sensitive || !hide);
247                 }
248                 else
249                 {
250                         gtk_widget_set_sensitive(GTK_WIDGET(dep_object), sensitive);
251                         if (!sensitive && hide)
252                         {
253                                 gtk_widget_hide(GTK_WIDGET(dep_object));
254                         }
255                         else
256                         {
257                                 gtk_widget_show_now(GTK_WIDGET(dep_object));
258                         }
259                 }
260         }
261 }
262
263 void
264 on_quit1_activate(GtkMenuItem *quit, signal_user_data_t *ud)
265 {
266         gint state = ghb_get_queue_state();
267         g_debug("on_quit1_activate ()");
268         if (state & GHB_STATE_WORKING)
269         {
270                 if (ghb_cancel_encode("Closing HandBrake will terminate encoding.\n"))
271                 {
272                         ghb_hb_cleanup(FALSE);
273                         prune_logs(ud);
274                         gtk_main_quit();
275                         return;
276                 }
277                 return;
278         }
279         ghb_hb_cleanup(FALSE);
280         prune_logs(ud);
281         gtk_main_quit();
282 }
283
284 static void
285 set_destination(signal_user_data_t *ud)
286 {
287         g_debug("set_destination");
288         if (ghb_settings_get_boolean(ud->settings, "use_source_name"))
289         {
290                 GString *str = g_string_new("");
291                 gchar *vol_name, *filename, *extension;
292                 gchar *new_name;
293                 gint title;
294                 
295                 filename = ghb_settings_get_string(ud->settings, "dest_file");
296                 extension = ghb_settings_get_string(ud->settings, "FileFormat");
297                 vol_name = ghb_settings_get_string(ud->settings, "volume_label");
298                 g_string_append_printf(str, "%s", vol_name);
299                 title = ghb_settings_combo_int(ud->settings, "title");
300                 if (title >= 0)
301                 {
302                         if (ghb_settings_get_boolean(
303                                         ud->settings, "title_no_in_destination"))
304                         {
305
306                                 title = ghb_settings_combo_int(ud->settings, "title");
307                                 g_string_append_printf(str, " - %d", title+1);
308                         }
309                         if (ghb_settings_get_boolean(
310                                         ud->settings, "chapters_in_destination"))
311                         {
312                                 gint start, end;
313
314                                 if (!ghb_settings_get_boolean(
315                                                 ud->settings, "title_no_in_destination"))
316                                 {
317                                         g_string_append_printf(str, " -");
318                                 }
319                                 start = ghb_settings_get_int(ud->settings, "start_chapter");
320                                 end = ghb_settings_get_int(ud->settings, "end_chapter");
321                                 if (start == end)
322                                         g_string_append_printf(str, " Ch %d", start);
323                                 else
324                                         g_string_append_printf(str, " Ch %d-%d", start, end);
325                         }
326                 }
327                 g_string_append_printf(str, ".%s", extension);
328                 new_name = g_string_free(str, FALSE);
329                 ghb_ui_update(ud, "dest_file", ghb_string_value(new_name));
330                 g_free(filename);
331                 g_free(extension);
332                 g_free(vol_name);
333                 g_free(new_name);
334         }
335 }
336
337 gboolean
338 uppers_and_unders(const gchar *str)
339 {
340         if (str == NULL) return FALSE;
341         while (*str)
342         {
343                 if (*str == ' ')
344                 {
345                         return FALSE;
346                 }
347                 if (*str >= 'a' && *str <= 'z')
348                 {
349                         return FALSE;
350                 }
351                 str++;
352         }
353         return TRUE;
354 }
355
356 enum
357 {
358         CAMEL_FIRST_UPPER,
359         CAMEL_OTHER
360 };
361
362 void
363 camel_convert(gchar *str)
364 {
365         gint state = CAMEL_OTHER;
366         
367         if (str == NULL) return;
368         while (*str)
369         {
370                 if (*str == '_') *str = ' ';
371                 switch (state)
372                 {
373                         case CAMEL_OTHER:
374                         {
375                                 if (*str >= 'A' && *str <= 'Z')
376                                         state = CAMEL_FIRST_UPPER;
377                                 else
378                                         state = CAMEL_OTHER;
379                                 
380                         } break;
381                         case CAMEL_FIRST_UPPER:
382                         {
383                                 if (*str >= 'A' && *str <= 'Z')
384                                         *str = *str - 'A' + 'a';
385                                 else
386                                         state = CAMEL_OTHER;
387                         } break;
388                 }
389                 str++;
390         }
391 }
392
393 static gchar*
394 get_file_label(const gchar *filename)
395 {
396         static gchar *containers[] = 
397                 {".vob", ".mpg", ".m2ts", ".mkv", ".mp4", ".m4v", ".avi", ".ogm", NULL};
398         gchar *base;
399         gint ii;
400
401         base = g_path_get_basename(filename);
402         for (ii = 0; containers[ii] != NULL; ii++)
403         {
404                 if (g_str_has_suffix(base, containers[ii]))
405                 {
406                         gchar *pos;
407                         pos = strrchr(base, '.');
408                         *pos = 0;
409                         break;
410                 }
411         }
412         return base;
413 }
414
415 static gboolean
416 update_source_label(signal_user_data_t *ud, const gchar *source)
417 {
418         gchar *label = NULL;
419         gint len;
420         gchar **path;
421         gchar *filename = g_strdup(source);
422         
423         len = strlen(filename);
424         if (filename[len-1] == '/') filename[len-1] = 0;
425         if (g_file_test(filename, G_FILE_TEST_IS_DIR))
426         {
427                 path = g_strsplit(filename, "/", -1);
428                 len = g_strv_length (path);
429                 if ((len > 1) && (strcmp("VIDEO_TS", path[len-1]) == 0))
430                 {
431                         label = g_strdup(path[len-2]);
432                 }
433                 else
434                 {
435                         label = g_strdup(path[len-1]);
436                 }
437                 g_strfreev (path);
438         }
439         else
440         {
441                 // Is regular file or block dev.
442                 // Check to see if it is a dvd image
443                 label = ghb_dvd_volname (filename);
444                 if (label == NULL)
445                 {
446                         label = get_file_label(filename);
447                 }
448                 else
449                 {
450                         if (uppers_and_unders(label))
451                         {
452                                 camel_convert(label);
453                         }
454                 }
455         }
456         g_free(filename);
457         GtkWidget *widget = GHB_WIDGET (ud->builder, "source_title");
458         if (label != NULL)
459         {
460                 gtk_label_set_text (GTK_LABEL(widget), label);
461                 ghb_settings_set_string(ud->settings, "volume_label", label);
462                 g_free(label);
463                 set_destination(ud);
464         }
465         else
466         {
467                 label = "No Title Found";
468                 gtk_label_set_text (GTK_LABEL(widget), label);
469                 ghb_settings_set_string(ud->settings, "volume_label", label);
470                 return FALSE;
471         }
472         return TRUE;
473 }
474
475 void
476 chooser_file_selected_cb(GtkFileChooser *dialog, signal_user_data_t *ud)
477 {
478         const gchar *name = gtk_file_chooser_get_filename (dialog);
479         GtkTreeModel *store;
480         GtkTreeIter iter;
481         const gchar *device;
482         gboolean foundit = FALSE;
483         GtkComboBox *combo;
484         
485         if (name == NULL) return;
486         combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, "source_device"));
487         store = gtk_combo_box_get_model(combo);
488         if (gtk_tree_model_get_iter_first(store, &iter))
489         {
490                 do
491                 {
492                         gtk_tree_model_get(store, &iter, 0, &device, -1);
493                         if (strcmp(name, device) == 0)
494                         {
495                                 foundit = TRUE;
496                                 break;
497                         }
498                 } while (gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter));
499         }
500         if (foundit)
501                 gtk_combo_box_set_active_iter (combo, &iter);
502         else
503                 gtk_combo_box_set_active (combo, 0);
504 }
505
506 void
507 dvd_device_changed_cb(GtkComboBox *combo, signal_user_data_t *ud)
508 {
509         GtkWidget *dialog;
510         gint ii;
511
512         ii = gtk_combo_box_get_active (combo);
513         if (ii > 0)
514         {
515                 const gchar *device, *name;
516
517                 dialog = GHB_WIDGET(ud->builder, "source_dialog");
518                 device = gtk_combo_box_get_active_text (combo);
519                 name = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(dialog));
520                 if (name == NULL || strcmp(name, device) != 0)
521                         gtk_file_chooser_select_filename (GTK_FILE_CHOOSER(dialog), device);
522         }
523 }
524
525 void
526 source_type_changed_cb(GtkToggleButton *toggle, signal_user_data_t *ud)
527 {
528         gchar *folder;
529         GtkFileChooser *chooser;
530         GtkWidget *dvd_device_combo;
531         
532         g_debug("source_type_changed_cb ()");
533         chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "source_dialog"));
534         dvd_device_combo = GHB_WIDGET(ud->builder, "source_device");
535         folder = gtk_file_chooser_get_current_folder (chooser);
536         if (gtk_toggle_button_get_active (toggle))
537         {
538                 gtk_file_chooser_set_action (chooser, 
539                                                                         GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
540                 gtk_widget_set_sensitive (dvd_device_combo, FALSE);
541                 gtk_combo_box_set_active (GTK_COMBO_BOX(dvd_device_combo), 0);
542         }
543         else
544         {
545                 gtk_file_chooser_set_action (chooser, GTK_FILE_CHOOSER_ACTION_OPEN);
546                 gtk_widget_set_sensitive (dvd_device_combo, TRUE);
547         }
548         if (folder != NULL)
549         {
550                 gtk_file_chooser_set_current_folder(chooser, folder);
551                 g_free(folder);
552         }
553 }
554
555 static void
556 source_dialog_extra_widgets(
557         signal_user_data_t *ud,
558         GtkWidget *dialog, 
559         gboolean checkbutton_active)
560 {
561         GtkToggleButton *checkbutton;
562         GtkComboBox *combo;
563         GList *drives, *link;
564         
565         checkbutton = GTK_TOGGLE_BUTTON(
566                 GHB_WIDGET(ud->builder, "source_folder_flag"));
567         gtk_toggle_button_set_active(checkbutton, checkbutton_active);
568         combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, "source_device"));
569         gtk_list_store_clear(GTK_LIST_STORE(
570                                                 gtk_combo_box_get_model(combo)));
571
572         link = drives = dvd_device_list();
573         gtk_combo_box_append_text (combo, "Not Selected");
574         while (link != NULL)
575         {
576                 gchar *name = (gchar*)link->data;
577                 gtk_combo_box_append_text(combo, name);
578                 g_free(name);
579                 link = link->next;
580         }
581         g_list_free(drives);
582 }
583
584 extern GValue *ghb_queue_edit_settings;
585 static gchar *last_scan_file = NULL;
586
587 void
588 ghb_do_scan(
589         signal_user_data_t *ud, 
590         const gchar *filename, 
591         gint titlenum, 
592         gboolean force)
593 {
594         if (!force && last_scan_file != NULL &&
595                 strcmp(last_scan_file, filename) == 0)
596         {
597                 if (ghb_queue_edit_settings)
598                 {
599                         gint jstatus;
600
601                         jstatus = ghb_settings_get_int(ghb_queue_edit_settings, "job_status");
602                         ghb_settings_to_ui(ud, ghb_queue_edit_settings);
603                         ghb_set_audio(ud, ghb_queue_edit_settings);
604                         if (jstatus == GHB_QUEUE_PENDING)
605                         {
606                                 ghb_value_free(ghb_queue_edit_settings);
607                         }
608                         ghb_queue_edit_settings = NULL;
609                 }
610                 return;
611         }
612         if (last_scan_file != NULL)
613                 g_free(last_scan_file);
614         last_scan_file = NULL;
615         if (filename != NULL)
616         {
617                 last_scan_file = g_strdup(filename);
618                 ghb_settings_set_string(ud->settings, "source", filename);
619                 if (update_source_label(ud, filename))
620                 {
621                         GtkProgressBar *progress;
622                         progress = GTK_PROGRESS_BAR(GHB_WIDGET(ud->builder, "progressbar"));
623                         gchar *path;
624                         path = ghb_settings_get_string( ud->settings, "source");
625                         gtk_progress_bar_set_fraction (progress, 0);
626                         gtk_progress_bar_set_text (progress, "Scanning ...");
627                         prune_logs(ud);
628                         gint preview_count;
629                         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
630                         ghb_backend_scan(path, titlenum, preview_count);
631                         g_free(path);
632                 }
633                 else
634                 {
635                         // TODO: error dialog
636                 }
637         }
638 }
639
640 static gboolean 
641 update_source_name(gpointer data)
642 {
643         signal_user_data_t *ud = (signal_user_data_t*)data;
644         GtkWidget *dialog;
645         gchar *sourcename;
646
647         sourcename = ghb_settings_get_string(ud->settings, "source");
648         dialog = GHB_WIDGET(ud->builder, "source_dialog");
649         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), sourcename);
650         g_free(sourcename);
651         return FALSE;
652 }
653
654 static void
655 do_source_dialog(GtkButton *button, gboolean single, signal_user_data_t *ud)
656 {
657         GtkWidget *dialog;
658         gchar *sourcename;
659         gint    response;
660         GtkFileChooserAction action;
661         gboolean checkbutton_active;
662
663         g_debug("source_browse_clicked_cb ()");
664         sourcename = ghb_settings_get_string(ud->settings, "source");
665         checkbutton_active = FALSE;
666         if (g_file_test(sourcename, G_FILE_TEST_IS_DIR))
667         {
668                 action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
669                 checkbutton_active = TRUE;
670         }
671         else
672         {
673                 action = GTK_FILE_CHOOSER_ACTION_OPEN;
674         }
675         GtkWidget *widget;
676         widget = GHB_WIDGET(ud->builder, "single_title_box");
677         if (single)
678                 gtk_widget_show(widget);
679         else
680                 gtk_widget_hide(widget);
681         dialog = GHB_WIDGET(ud->builder, "source_dialog");
682         source_dialog_extra_widgets(ud, dialog, checkbutton_active);
683         gtk_file_chooser_set_action(GTK_FILE_CHOOSER(dialog), action);
684         // Updating the filename in the file chooser dialog doesn't seem
685         // to work unless the dialog is running for some reason.
686         // So handle it in an "idle" event.
687         //gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), sourcename);
688         g_idle_add((GSourceFunc)update_source_name, ud);
689         response = gtk_dialog_run(GTK_DIALOG (dialog));
690         gtk_widget_hide(dialog);
691         if (response == GTK_RESPONSE_ACCEPT)
692         {
693                 char *filename;
694
695                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
696                 if (filename != NULL)
697                 {
698                         gint titlenum;
699
700                         if (single)
701                                 titlenum = ghb_settings_get_int(ud->settings, "single_title");
702                         else
703                                 titlenum = 0;
704                         ghb_do_scan(ud, filename, titlenum, TRUE);
705                         if (strcmp(sourcename, filename) != 0)
706                         {
707                                 ghb_settings_set_string (ud->settings, 
708                                                                                 "default_source", filename);
709                                 ghb_pref_save (ud->settings, "default_source");
710                                 ghb_dvd_set_current (filename, ud);
711                         }
712                         g_free(filename);
713                 }
714         }
715         g_free(sourcename);
716 }
717
718 void
719 source_button_clicked_cb(GtkButton *button, signal_user_data_t *ud)
720 {
721         do_source_dialog(button, FALSE, ud);
722 }
723
724 void
725 single_title_source_cb(GtkButton *button, signal_user_data_t *ud)
726 {
727         do_source_dialog(button, TRUE, ud);
728 }
729
730 void
731 dvd_source_activate_cb(GtkAction *action, signal_user_data_t *ud)
732 {
733         const gchar *filename;
734         gchar *sourcename;
735
736         sourcename = ghb_settings_get_string(ud->settings, "source");
737         filename = gtk_action_get_name(action);
738         ghb_do_scan(ud, filename, 0, TRUE);
739         if (strcmp(sourcename, filename) != 0)
740         {
741                 ghb_settings_set_string (ud->settings, "default_source", filename);
742                 ghb_pref_save (ud->settings, "default_source");
743                 ghb_dvd_set_current (filename, ud);
744         }
745         g_free(sourcename);
746 }
747
748 static void
749 update_destination_extension(signal_user_data_t *ud)
750 {
751         static gchar *containers[] = {".mkv", ".mp4", ".m4v", ".avi", ".ogm", NULL};
752         gchar *filename;
753         gchar *extension;
754         gint ii;
755         GtkEntry *entry;
756
757         g_debug("update_destination_extension ()");
758         extension = ghb_settings_get_string(ud->settings, "FileFormat");
759         entry = GTK_ENTRY(GHB_WIDGET(ud->builder, "dest_file"));
760         filename = g_strdup(gtk_entry_get_text(entry));
761         for (ii = 0; containers[ii] != NULL; ii++)
762         {
763                 if (g_str_has_suffix(filename, containers[ii]))
764                 {
765                         gchar *pos;
766                         gchar *new_name;
767                         
768                         pos = g_strrstr( filename, "." );
769                         if (pos == NULL)
770                         {
771                                 // No period? shouldn't happen
772                                 break;
773                         }
774                         *pos = 0;
775                         if (strcmp(extension, &pos[1]) == 0)
776                         {
777                                 // Extension is already correct
778                                 break;
779                         }
780                         new_name = g_strjoin(".", filename, extension, NULL); 
781                         ghb_ui_update(ud, "dest_file", ghb_string_value(new_name));
782                         g_free(new_name);
783                         break;
784                 }
785         }
786         g_free(extension);
787         g_free(filename);
788 }
789
790 static void
791 destination_select_title(GtkEntry *entry)
792 {
793         const gchar *dest;
794         gint start, end;
795
796         dest = gtk_entry_get_text(entry);
797         for (end = strlen(dest)-1; end > 0; end--)
798         {
799                 if (dest[end] == '.')
800                 {
801                         break;
802                 }
803         }
804         for (start = end; start >= 0; start--)
805         {
806                 if (dest[start] == '/')
807                 {
808                         start++;
809                         break;
810                 }
811         }
812         if (start < 0) start = 0;
813         if (start < end)
814         {
815                 gtk_editable_select_region(GTK_EDITABLE(entry), start, end);
816         }
817 }
818
819 gboolean
820 destination_grab_cb(
821         GtkEntry *entry, 
822         signal_user_data_t *ud)
823 {
824         destination_select_title(entry);
825         return FALSE;
826 }
827
828 static gboolean update_default_destination = FALSE;
829
830 void
831 dest_dir_set_cb(GtkFileChooserButton *dest_chooser, signal_user_data_t *ud)
832 {
833         gchar *dest_file, *dest_dir, *dest;
834         
835         g_debug("dest_dir_set_cb ()");
836         ghb_widget_to_setting(ud->settings, (GtkWidget*)dest_chooser);
837         dest_file = ghb_settings_get_string(ud->settings, "dest_file");
838         dest_dir = ghb_settings_get_string(ud->settings, "dest_dir");
839         dest = g_strdup_printf("%s/%s", dest_dir, dest_file);
840         ghb_settings_set_string(ud->settings, "destination", dest);
841         g_free(dest_file);
842         g_free(dest_dir);
843         g_free(dest);
844         update_default_destination = TRUE;
845 }
846
847 void
848 dest_file_changed_cb(GtkEntry *entry, signal_user_data_t *ud)
849 {
850         gchar *dest_file, *dest_dir, *dest;
851         
852         g_debug("dest_file_changed_cb ()");
853         update_destination_extension(ud);
854         ghb_widget_to_setting(ud->settings, (GtkWidget*)entry);
855         // This signal goes off with ever keystroke, so I'm putting this
856         // update on the timer.
857         dest_file = ghb_settings_get_string(ud->settings, "dest_file");
858         dest_dir = ghb_settings_get_string(ud->settings, "dest_dir");
859         dest = g_strdup_printf("%s/%s", dest_dir, dest_file);
860         ghb_settings_set_string(ud->settings, "destination", dest);
861         g_free(dest_file);
862         g_free(dest_dir);
863         g_free(dest);
864         update_default_destination = TRUE;
865 }
866
867 void
868 destination_browse_clicked_cb(GtkButton *button, signal_user_data_t *ud)
869 {
870         GtkWidget *dialog;
871         GtkEntry *entry;
872         gchar *destname;
873         gchar *basename;
874
875         g_debug("destination_browse_clicked_cb ()");
876         destname = ghb_settings_get_string(ud->settings, "destination");
877         dialog = gtk_file_chooser_dialog_new ("Choose Destination",
878                                           NULL,
879                                           GTK_FILE_CHOOSER_ACTION_SAVE,
880                                           GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
881                                           GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
882                                           NULL);
883         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), destname);
884         basename = g_path_get_basename(destname);
885         g_free(destname);
886         gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), basename);
887         g_free(basename);
888         if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
889         {
890                 char *filename, *dirname;
891                 GtkFileChooser *dest_chooser;
892                 
893                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
894                 basename = g_path_get_basename(filename);
895                 dirname = g_path_get_dirname(filename);
896                 entry = (GtkEntry*)GHB_WIDGET(ud->builder, "dest_file");
897                 gtk_entry_set_text(entry, basename);
898                 dest_chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "dest_dir"));
899                 gtk_file_chooser_set_filename(dest_chooser, dirname);
900                 g_free (dirname);
901                 g_free (basename);
902                 g_free (filename);
903         }
904         gtk_widget_destroy(dialog);
905 }
906
907 gboolean
908 window_destroy_event_cb(GtkWidget *widget, GdkEvent *event, signal_user_data_t *ud)
909 {
910         g_debug("window_destroy_event_cb ()");
911         ghb_hb_cleanup(FALSE);
912         prune_logs(ud);
913         gtk_main_quit();
914         return FALSE;
915 }
916
917 gboolean
918 window_delete_event_cb(GtkWidget *widget, GdkEvent *event, signal_user_data_t *ud)
919 {
920         gint state = ghb_get_queue_state();
921         g_debug("window_delete_event_cb ()");
922         if (state & GHB_STATE_WORKING)
923         {
924                 if (ghb_cancel_encode("Closing HandBrake will terminate encoding.\n"))
925                 {
926                         ghb_hb_cleanup(FALSE);
927                         prune_logs(ud);
928                         gtk_main_quit();
929                         return FALSE;
930                 }
931                 return TRUE;
932         }
933         ghb_hb_cleanup(FALSE);
934         prune_logs(ud);
935         gtk_main_quit();
936         return FALSE;
937 }
938
939 static void
940 update_acodec_combo(signal_user_data_t *ud)
941 {
942         ghb_grey_combo_options (ud->builder);
943 }
944
945 void
946 container_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
947 {
948         const GValue *audio_list;
949         g_debug("container_changed_cb ()");
950         ghb_widget_to_setting(ud->settings, widget);
951         update_destination_extension(ud);
952         ghb_check_dependency(ud, widget);
953         update_acodec_combo(ud);
954         ghb_clear_presets_selection(ud);
955         ghb_live_reset(ud);
956
957         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
958         if (ghb_ac3_in_audio_list (audio_list))
959         {
960                 gchar *container;
961
962                 container = ghb_settings_get_string(ud->settings, "FileFormat");
963                 if (strcmp(container, "mp4") == 0)
964                 {
965                         ghb_ui_update(ud, "FileFormat", ghb_string_value("m4v"));
966                 }
967                 g_free(container);
968         }
969 }
970
971 static gchar*
972 get_aspect_string(gint aspect_n, gint aspect_d)
973 {
974         gchar *aspect;
975
976         if (aspect_d < 10)
977         {
978                 aspect = g_strdup_printf("%d:%d", aspect_n, aspect_d);
979         }
980         else
981         {
982                 gdouble aspect_nf = (gdouble)aspect_n / aspect_d;
983                 aspect = g_strdup_printf("%.2f:1", aspect_nf);
984         }
985         return aspect;
986 }
987
988 static gchar*
989 get_rate_string(gint rate_base, gint rate)
990 {
991         gdouble rate_f = (gdouble)rate / rate_base;
992         gchar *rate_s;
993
994         rate_s = g_strdup_printf("%.6g", rate_f);
995         return rate_s;
996 }
997 static void
998 show_title_info(signal_user_data_t *ud, ghb_title_info_t *tinfo)
999 {
1000         GtkWidget *widget;
1001         gchar *text;
1002
1003         ud->dont_clear_presets = TRUE;
1004         widget = GHB_WIDGET (ud->builder, "title_duration");
1005         if (tinfo->duration != 0)
1006         {
1007                 text = g_strdup_printf ("%02d:%02d:%02d", tinfo->hours, 
1008                                 tinfo->minutes, tinfo->seconds);
1009         }
1010         else
1011         {
1012                 text = g_strdup_printf ("Unknown");
1013         }
1014         gtk_label_set_text (GTK_LABEL(widget), text);
1015         g_free(text);
1016         widget = GHB_WIDGET (ud->builder, "source_dimensions");
1017         text = g_strdup_printf ("%d x %d", tinfo->width, tinfo->height);
1018         gtk_label_set_text (GTK_LABEL(widget), text);
1019         ghb_settings_set_int(ud->settings, "source_width", tinfo->width);
1020         ghb_settings_set_int(ud->settings, "source_height", tinfo->height);
1021         g_free(text);
1022         widget = GHB_WIDGET (ud->builder, "source_aspect");
1023         text = get_aspect_string(tinfo->aspect_n, tinfo->aspect_d);
1024         gtk_label_set_text (GTK_LABEL(widget), text);
1025         g_free(text);
1026
1027         widget = GHB_WIDGET (ud->builder, "source_frame_rate");
1028         text = (gchar*)get_rate_string(tinfo->rate_base, tinfo->rate);
1029         gtk_label_set_text (GTK_LABEL(widget), text);
1030         g_free(text);
1031
1032         ghb_ui_update(ud, "scale_width", 
1033                 ghb_int64_value(tinfo->width - tinfo->crop[2] - tinfo->crop[3]));
1034         // If anamorphic or keep_aspect, the hight will be automatically calculated
1035         gboolean keep_aspect;
1036         gint pic_par;
1037         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
1038         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
1039         if (!(keep_aspect || pic_par) || pic_par == 3)
1040         {
1041                 ghb_ui_update(ud, "scale_height", 
1042                         ghb_int64_value(tinfo->height - tinfo->crop[0] - tinfo->crop[1]));
1043         }
1044
1045         // Set the limits of cropping.  hb_set_anamorphic_size crashes if
1046         // you pass it a cropped width or height == 0.
1047         gint bound;
1048         bound = tinfo->height / 2 - 2;
1049         widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
1050         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1051         widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
1052         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1053         bound = tinfo->width / 2 - 2;
1054         widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
1055         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1056         widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
1057         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 0, bound);
1058         if (ghb_settings_get_boolean(ud->settings, "PictureAutoCrop"))
1059         {
1060                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(tinfo->crop[0]));
1061                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(tinfo->crop[1]));
1062                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(tinfo->crop[2]));
1063                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(tinfo->crop[3]));
1064         }
1065         ghb_set_scale (ud, GHB_PIC_KEEP_PAR);
1066         gint width, height, crop[4];
1067         crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
1068         crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
1069         crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
1070         crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
1071         width = tinfo->width - crop[2] - crop[3];
1072         height = tinfo->height - crop[0] - crop[1];
1073         widget = GHB_WIDGET (ud->builder, "crop_dimensions");
1074         text = g_strdup_printf ("%d x %d", width, height);
1075         gtk_label_set_text (GTK_LABEL(widget), text);
1076         g_free(text);
1077
1078         g_debug("setting max end chapter %d", tinfo->num_chapters);
1079         widget = GHB_WIDGET (ud->builder, "end_chapter");
1080         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo->num_chapters);
1081         gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), tinfo->num_chapters);
1082         widget = GHB_WIDGET (ud->builder, "start_chapter");
1083         gtk_spin_button_set_value (GTK_SPIN_BUTTON(widget), 1);
1084         gtk_spin_button_set_range (GTK_SPIN_BUTTON(widget), 1, tinfo->num_chapters);
1085         ud->dont_clear_presets = TRUE;
1086 }
1087
1088 static gboolean update_preview = FALSE;
1089
1090 void
1091 title_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1092 {
1093         ghb_title_info_t tinfo;
1094         gint titleindex;
1095         
1096         g_debug("title_changed_cb ()");
1097         ghb_widget_to_setting(ud->settings, widget);
1098         ghb_check_dependency(ud, widget);
1099
1100         titleindex = ghb_settings_combo_int(ud->settings, "title");
1101         ghb_update_ui_combo_box (ud->builder, "AudioTrack", titleindex, FALSE);
1102         ghb_update_ui_combo_box (ud->builder, "Subtitles", titleindex, FALSE);
1103
1104         ghb_update_from_preset(ud, "Subtitles");
1105         if (ghb_get_title_info (&tinfo, titleindex))
1106         {
1107                 show_title_info(ud, &tinfo);
1108         }
1109         update_chapter_list (ud);
1110         ghb_adjust_audio_rate_combos(ud);
1111         ghb_set_pref_audio(titleindex, ud);
1112         if (ghb_settings_get_boolean(ud->settings, "vquality_type_target"))
1113         {
1114                 gint bitrate = ghb_calculate_target_bitrate (ud->settings, titleindex);
1115                 ghb_ui_update(ud, "VideoAvgBitrate", ghb_int64_value(bitrate));
1116         }
1117
1118         // Unfortunately, there is no way to query how many frames were
1119         // actually generated during the scan.
1120         // If I knew how many were generated, I would adjust the spin
1121         // control range here.
1122         // I do know how many were asked for.
1123         gint preview_count;
1124         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
1125         widget = GHB_WIDGET(ud->builder, "preview_frame");
1126         gtk_range_set_range (GTK_RANGE(widget), 1, preview_count);
1127         ghb_ui_update(ud, "preview_frame", ghb_int64_value(2));
1128
1129         ghb_set_preview_image (ud);
1130         if (ghb_settings_get_boolean(ud->settings, "title_no_in_destination"))
1131         {
1132                 set_destination(ud);
1133         }
1134 }
1135
1136 void
1137 setting_widget_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1138 {
1139         ghb_widget_to_setting(ud->settings, widget);
1140         ghb_check_dependency(ud, widget);
1141         ghb_clear_presets_selection(ud);
1142         ghb_live_reset(ud);
1143 }
1144
1145 void
1146 vquality_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1147 {
1148         ghb_widget_to_setting(ud->settings, widget);
1149         ghb_check_dependency(ud, widget);
1150         ghb_clear_presets_selection(ud);
1151         ghb_live_reset(ud);
1152
1153         gint vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
1154         gdouble step;
1155         if (vcodec == HB_VCODEC_X264)
1156         {
1157                 step = ghb_settings_combo_double(ud->settings, 
1158                                                                                         "VideoQualityGranularity");
1159         }
1160         else
1161         {
1162                 step = 1;
1163         }
1164         gdouble val = gtk_range_get_value(GTK_RANGE(widget));
1165         val = ((int)((val + step / 2) / step)) * step;
1166         gtk_range_set_value(GTK_RANGE(widget), val);
1167 }
1168
1169 void
1170 http_opt_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1171 {
1172         ghb_widget_to_setting(ud->settings, widget);
1173         ghb_check_dependency(ud, widget);
1174         ghb_clear_presets_selection(ud);
1175         ghb_live_reset(ud);
1176         // AC3 is not allowed when Web optimized
1177         ghb_grey_combo_options (ud->builder);
1178 }
1179
1180 void
1181 vcodec_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1182 {
1183         gdouble vqmin, vqmax, step, page;
1184         gboolean inverted;
1185         gint digits;
1186
1187         ghb_widget_to_setting(ud->settings, widget);
1188         ghb_check_dependency(ud, widget);
1189         ghb_clear_presets_selection(ud);
1190         ghb_live_reset(ud);
1191         ghb_vquality_range(ud, &vqmin, &vqmax, &step, &page, &digits, &inverted);
1192         GtkWidget *qp = GHB_WIDGET(ud->builder, "VideoQualitySlider");
1193         gtk_range_set_range (GTK_RANGE(qp), vqmin, vqmax);
1194         gtk_range_set_increments (GTK_RANGE(qp), step, page);
1195         gtk_scale_set_digits(GTK_SCALE(qp), digits);
1196         gtk_range_set_inverted (GTK_RANGE(qp), inverted);
1197 }
1198
1199 void
1200 target_size_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1201 {
1202         const gchar *name = gtk_widget_get_name(widget);
1203         g_debug("target_size_changed_cb () %s", name);
1204         ghb_widget_to_setting(ud->settings, widget);
1205         ghb_check_dependency(ud, widget);
1206         ghb_clear_presets_selection(ud);
1207         ghb_live_reset(ud);
1208         if (ghb_settings_get_boolean(ud->settings, "vquality_type_target"))
1209         {
1210                 gint titleindex;
1211                 titleindex = ghb_settings_combo_int(ud->settings, "title");
1212                 gint bitrate = ghb_calculate_target_bitrate (ud->settings, titleindex);
1213                 ghb_ui_update(ud, "VideoAvgBitrate", ghb_int64_value(bitrate));
1214         }
1215 }
1216
1217 void
1218 start_chapter_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1219 {
1220         gint start, end;
1221         const gchar *name = gtk_widget_get_name(widget);
1222
1223         g_debug("start_chapter_changed_cb () %s", name);
1224         ghb_widget_to_setting(ud->settings, widget);
1225         start = ghb_settings_get_int(ud->settings, "start_chapter");
1226         end = ghb_settings_get_int(ud->settings, "end_chapter");
1227         if (start > end)
1228                 ghb_ui_update(ud, "end_chapter", ghb_int_value(start));
1229         ghb_check_dependency(ud, widget);
1230         if (ghb_settings_get_boolean(ud->settings, "chapters_in_destination"))
1231         {
1232                 set_destination(ud);
1233         }
1234 }
1235
1236 void
1237 end_chapter_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1238 {
1239         gint start, end;
1240         const gchar *name = gtk_widget_get_name(widget);
1241
1242         g_debug("end_chapter_changed_cb () %s", name);
1243         ghb_widget_to_setting(ud->settings, widget);
1244         start = ghb_settings_get_int(ud->settings, "start_chapter");
1245         end = ghb_settings_get_int(ud->settings, "end_chapter");
1246         if (start > end)
1247                 ghb_ui_update(ud, "start_chapter", ghb_int_value(end));
1248         ghb_check_dependency(ud, widget);
1249         if (ghb_settings_get_boolean(ud->settings, "chapters_in_destination"))
1250         {
1251                 set_destination(ud);
1252         }
1253 }
1254
1255 void
1256 scale_width_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1257 {
1258         g_debug("scale_width_changed_cb ()");
1259         ghb_widget_to_setting(ud->settings, widget);
1260         ghb_check_dependency(ud, widget);
1261         ghb_clear_presets_selection(ud);
1262         if (GTK_WIDGET_SENSITIVE(widget))
1263                 ghb_set_scale (ud, GHB_PIC_KEEP_WIDTH);
1264         update_preview = TRUE;
1265         gchar *text;
1266         gint width = ghb_settings_get_int(ud->settings, "scale_width");
1267         gint height = ghb_settings_get_int(ud->settings, "scale_height");
1268         widget = GHB_WIDGET (ud->builder, "scale_dimensions");
1269         text = g_strdup_printf ("%d x %d", width, height);
1270         gtk_label_set_text (GTK_LABEL(widget), text);
1271         g_free(text);
1272         ghb_live_reset(ud);
1273 }
1274
1275 void
1276 scale_height_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1277 {
1278         g_debug("scale_height_changed_cb ()");
1279         ghb_widget_to_setting(ud->settings, widget);
1280         ghb_check_dependency(ud, widget);
1281         ghb_clear_presets_selection(ud);
1282         if (GTK_WIDGET_SENSITIVE(widget))
1283                 ghb_set_scale (ud, GHB_PIC_KEEP_HEIGHT);
1284         update_preview = TRUE;
1285         gchar *text;
1286         gint width = ghb_settings_get_int(ud->settings, "scale_width");
1287         gint height = ghb_settings_get_int(ud->settings, "scale_height");
1288         widget = GHB_WIDGET (ud->builder, "scale_dimensions");
1289         text = g_strdup_printf ("%d x %d", width, height);
1290         gtk_label_set_text (GTK_LABEL(widget), text);
1291         g_free(text);
1292         ghb_live_reset(ud);
1293 }
1294
1295 void
1296 crop_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1297 {
1298         gint titleindex, crop[4];
1299         ghb_title_info_t tinfo;
1300         
1301         g_debug("crop_changed_cb ()");
1302         ghb_widget_to_setting(ud->settings, widget);
1303         ghb_check_dependency(ud, widget);
1304         ghb_clear_presets_selection(ud);
1305         if (GTK_WIDGET_SENSITIVE(widget))
1306                 ghb_set_scale (ud, 0);
1307
1308         crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
1309         crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
1310         crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
1311         crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
1312         titleindex = ghb_settings_combo_int(ud->settings, "title");
1313         if (ghb_get_title_info (&tinfo, titleindex))
1314         {
1315                 gint width, height;
1316                 gchar *text;
1317                 
1318                 width = tinfo.width - crop[2] - crop[3];
1319                 height = tinfo.height - crop[0] - crop[1];
1320                 widget = GHB_WIDGET (ud->builder, "crop_dimensions");
1321                 text = g_strdup_printf ("%d x %d", width, height);
1322                 gtk_label_set_text (GTK_LABEL(widget), text);
1323                 g_free(text);
1324         }
1325         gchar *text;
1326         widget = GHB_WIDGET (ud->builder, "crop_values");
1327         text = g_strdup_printf ("%d:%d:%d:%d", crop[0], crop[1], crop[2], crop[3]);
1328         gtk_label_set_text (GTK_LABEL(widget), text);
1329         g_free(text);
1330         update_preview = TRUE;
1331         ghb_live_reset(ud);
1332 }
1333
1334 void
1335 display_width_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1336 {
1337         g_debug("scale_changed_cb ()");
1338         ghb_widget_to_setting(ud->settings, widget);
1339         ghb_check_dependency(ud, widget);
1340         ghb_clear_presets_selection(ud);
1341         ghb_live_reset(ud);
1342         if (GTK_WIDGET_SENSITIVE(widget))
1343                 ghb_set_scale (ud, GHB_PIC_KEEP_DISPLAY_WIDTH);
1344
1345         gint pic_par;
1346
1347         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
1348         if (pic_par == 3)
1349         {
1350                 gint par_width, par_height;
1351
1352                 par_width = ghb_settings_get_int(ud->settings, "par_width");
1353                 par_height = ghb_settings_get_int(ud->settings, "par_height");
1354                 ghb_settings_set_int(ud->settings, "PicturePARWidth", par_width);
1355                 ghb_settings_set_int(ud->settings, "PicturePARHeight", par_height);
1356         }
1357         update_preview = TRUE;
1358 }
1359
1360 void
1361 display_height_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1362 {
1363         g_debug("scale_changed_cb ()");
1364         ghb_widget_to_setting(ud->settings, widget);
1365         ghb_check_dependency(ud, widget);
1366         ghb_clear_presets_selection(ud);
1367         ghb_live_reset(ud);
1368         if (GTK_WIDGET_SENSITIVE(widget))
1369                 ghb_set_scale (ud, GHB_PIC_KEEP_DISPLAY_HEIGHT);
1370
1371         gint pic_par;
1372
1373         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
1374         if (pic_par == 3)
1375         {
1376                 gint par_width, par_height;
1377
1378                 par_width = ghb_settings_get_int(ud->settings, "par_width");
1379                 par_height = ghb_settings_get_int(ud->settings, "par_height");
1380                 ghb_settings_set_int(ud->settings, "PicturePARWidth", par_width);
1381                 ghb_settings_set_int(ud->settings, "PicturePARHeight", par_height);
1382         }
1383         update_preview = TRUE;
1384 }
1385
1386 void
1387 scale_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
1388 {
1389         g_debug("scale_changed_cb ()");
1390         ghb_widget_to_setting(ud->settings, widget);
1391         ghb_check_dependency(ud, widget);
1392         ghb_clear_presets_selection(ud);
1393         ghb_live_reset(ud);
1394         if (GTK_WIDGET_SENSITIVE(widget))
1395                 ghb_set_scale (ud, 0);
1396         update_preview = TRUE;
1397         
1398         gchar *text;
1399         
1400         text = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop") ? "On" : "Off";
1401         widget = GHB_WIDGET (ud->builder, "crop_auto");
1402         gtk_label_set_text (GTK_LABEL(widget), text);
1403         text = ghb_settings_get_boolean(ud->settings, "autoscale") ? "On" : "Off";
1404         widget = GHB_WIDGET (ud->builder, "scale_auto");
1405         gtk_label_set_text (GTK_LABEL(widget), text);
1406         switch (ghb_settings_combo_int(ud->settings, "PicturePAR"))
1407         {
1408                 case 0:
1409                         text = "Off";
1410                         break;
1411                 case 1:
1412                         text = "Strict";
1413                         break;
1414                 case 2:
1415                         text = "Loose";
1416                         break;
1417                 case 3:
1418                         text = "Custom";
1419                         break;
1420                 default:
1421                         text = "Unknown";
1422                         break;
1423         }
1424         widget = GHB_WIDGET (ud->builder, "scale_anamorphic");
1425         gtk_label_set_text (GTK_LABEL(widget), text);
1426 }
1427
1428 void
1429 generic_entry_changed_cb(GtkEntry *entry, signal_user_data_t *ud)
1430 {
1431         // Normally (due to user input) I only want to process the entry
1432         // when editing is done and the focus-out signal is sent.
1433         // But... there's always a but.
1434         // If the entry is changed by software, the focus-out signal is not sent.
1435         // The changed signal is sent ... so here we are.
1436         // I don't want to process upon every keystroke, so I prevent processing
1437         // while the widget has focus.
1438         g_debug("generic_entry_changed_cb ()");
1439         if (!GTK_WIDGET_HAS_FOCUS((GtkWidget*)entry))
1440         {
1441                 ghb_widget_to_setting(ud->settings, (GtkWidget*)entry);
1442         }
1443 }
1444
1445 void
1446 prefs_dialog_cb(GtkWidget *xwidget, signal_user_data_t *ud)
1447 {
1448         GtkWidget *dialog;
1449         GtkResponseType response;
1450
1451         g_debug("prefs_dialog_cb ()");
1452         dialog = GHB_WIDGET(ud->builder, "prefs_dialog");
1453         response = gtk_dialog_run(GTK_DIALOG(dialog));
1454         gtk_widget_hide(dialog);
1455 }
1456
1457 gboolean
1458 ghb_message_dialog(GtkMessageType type, const gchar *message, const gchar *no, const gchar *yes)
1459 {
1460         GtkWidget *dialog;
1461         GtkResponseType response;
1462                         
1463         // Toss up a warning dialog
1464         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
1465                                                         type, GTK_BUTTONS_NONE,
1466                                                         "%s", message);
1467         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
1468                                                    no, GTK_RESPONSE_NO,
1469                                                    yes, GTK_RESPONSE_YES, NULL);
1470         response = gtk_dialog_run(GTK_DIALOG(dialog));
1471         gtk_widget_destroy (dialog);
1472         if (response == GTK_RESPONSE_NO)
1473         {
1474                 return FALSE;
1475         }
1476         return TRUE;
1477 }
1478
1479 gboolean
1480 ghb_cancel_encode(const gchar *extra_msg)
1481 {
1482         GtkWidget *dialog;
1483         GtkResponseType response;
1484         
1485         if (extra_msg == NULL) extra_msg = "";
1486         // Toss up a warning dialog
1487         dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
1488                                 GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE,
1489                                 "%sYour movie will be lost if you don't continue encoding.",
1490                                 extra_msg);
1491         gtk_dialog_add_buttons( GTK_DIALOG(dialog), 
1492                                                    "Continue Encoding", GTK_RESPONSE_NO,
1493                                                    "Stop Encoding", GTK_RESPONSE_YES, NULL);
1494         response = gtk_dialog_run(GTK_DIALOG(dialog));
1495         gtk_widget_destroy (dialog);
1496         if (response == GTK_RESPONSE_NO) return FALSE;
1497         ghb_stop_queue();
1498         return TRUE;
1499 }
1500
1501 static void
1502 submit_job(GValue *settings)
1503 {
1504         static gint unique_id = 1;
1505         gchar *type, *modified, *preset;
1506         const GValue *path;
1507         gboolean preset_modified;
1508
1509         g_debug("submit_job");
1510         if (settings == NULL) return;
1511         preset_modified = ghb_settings_get_boolean(settings, "preset_modified");
1512         path = ghb_settings_get_value(settings, "preset");
1513         preset = ghb_preset_path_string(path);
1514         type = ghb_preset_is_custom() ? "Custom " : "";
1515         modified = preset_modified ? "Modified " : "";
1516         ghb_log("%s%sPreset: %s", modified, type, preset);
1517         g_free(preset);
1518
1519         ghb_settings_set_int(settings, "job_unique_id", unique_id);
1520         ghb_settings_set_int(settings, "job_status", GHB_QUEUE_RUNNING);
1521         ghb_add_job (settings, unique_id);
1522         ghb_start_queue();
1523         unique_id++;
1524 }
1525
1526 static void
1527 prune_logs(signal_user_data_t *ud)
1528 {
1529         gchar *dest_dir;
1530
1531         // Only prune logs stored in the default config dir location
1532         dest_dir = ghb_get_user_config_dir("EncodeLogs");
1533         if (g_file_test(dest_dir, G_FILE_TEST_IS_DIR))
1534         {
1535                 const gchar *file;
1536                 int week = 7*24*60*60;
1537                 GDir *gdir = g_dir_open(dest_dir, 0, NULL);
1538                 time_t now;
1539
1540                 now = time(NULL);
1541                 file = g_dir_read_name(gdir);
1542                 while (file)
1543                 {
1544                         gchar *path;
1545                         struct stat stbuf;
1546
1547                         path = g_strdup_printf("%s/%s", dest_dir, file);
1548                         g_stat(path, &stbuf);
1549                         if (now - stbuf.st_mtime > week)
1550                         {
1551                                 g_unlink(path);
1552                         }
1553                         g_free(path);
1554                         file = g_dir_read_name(gdir);
1555                 }
1556                 g_dir_close(gdir);
1557         }
1558         g_free(dest_dir);
1559         ghb_preview_cleanup(ud);
1560 }
1561
1562 static void
1563 queue_scan(signal_user_data_t *ud, GValue *js)
1564 {
1565         gchar *path;
1566         gint titlenum;
1567         time_t  _now;
1568         struct tm *now;
1569         gchar *log_path, *pos, *destname, *basename, *dest_dir;
1570
1571         _now = time(NULL);
1572         now = localtime(&_now);
1573         destname = ghb_settings_get_string(js, "destination");
1574         basename = g_path_get_basename(destname);
1575         if (ghb_settings_get_boolean(ud->settings, "EncodeLogLocation"))
1576         {
1577                 dest_dir = g_path_get_dirname (destname);
1578         }
1579         else
1580         {
1581                 dest_dir = ghb_get_user_config_dir("EncodeLogs");
1582         }
1583         g_free(destname);
1584         pos = g_strrstr( basename, "." );
1585         if (pos != NULL)
1586         {
1587                 *pos = 0;
1588         }
1589         log_path = g_strdup_printf("%s/%d-%02d-%02d %02d-%02d-%02d %s.log",
1590                 dest_dir,
1591                 now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
1592                 now->tm_hour, now->tm_min, now->tm_sec, basename);
1593         g_free(basename);
1594         g_free(dest_dir);
1595         if (ud->job_activity_log)
1596                 g_io_channel_unref(ud->job_activity_log);
1597         ud->job_activity_log = g_io_channel_new_file (log_path, "w", NULL);
1598         if (ud->job_activity_log)
1599         {
1600                 gchar *ver_str;
1601
1602                 ver_str = g_strdup_printf("Handbrake Version: %s (%d)\n", 
1603                                                                         hb_get_version(NULL), hb_get_build(NULL));
1604                 g_io_channel_write_chars (ud->job_activity_log, ver_str, 
1605                                                                         -1, NULL, NULL);
1606                 g_free(ver_str);
1607         }
1608         g_free(log_path);
1609
1610         path = ghb_settings_get_string( js, "source");
1611         titlenum = ghb_settings_get_int(js, "titlenum");
1612         ghb_backend_queue_scan(path, titlenum);
1613         g_free(path);
1614 }
1615
1616 GValue* 
1617 ghb_start_next_job(signal_user_data_t *ud, gboolean find_first)
1618 {
1619         static gint current = 0;
1620         gint count, ii, jj;
1621         GValue *js;
1622         gint status;
1623
1624         g_debug("start_next_job");
1625         count = ghb_array_len(ud->queue);
1626         if (find_first)
1627         {       // Start the first pending item in the queue
1628                 current = 0;
1629                 for (ii = 0; ii < count; ii++)
1630                 {
1631
1632                         js = ghb_array_get_nth(ud->queue, ii);
1633                         status = ghb_settings_get_int(js, "job_status");
1634                         if (status == GHB_QUEUE_PENDING)
1635                         {
1636                                 current = ii;
1637                                 ghb_inhibit_gpm();
1638                                 queue_scan(ud, js);
1639                                 return js;
1640                         }
1641                 }
1642                 // Nothing pending
1643                 ghb_uninhibit_gpm();
1644                 ghb_notify_done(ud);
1645                 return NULL;
1646         }
1647         // Find the next pending item after the current running item
1648         for (ii = 0; ii < count-1; ii++)
1649         {
1650                 js = ghb_array_get_nth(ud->queue, ii);
1651                 status = ghb_settings_get_int(js, "job_status");
1652                 if (status == GHB_QUEUE_RUNNING)
1653                 {
1654                         for (jj = ii+1; jj < count; jj++)
1655                         {
1656                                 js = ghb_array_get_nth(ud->queue, jj);
1657                                 status = ghb_settings_get_int(js, "job_status");
1658                                 if (status == GHB_QUEUE_PENDING)
1659                                 {
1660                                         current = jj;
1661                                         ghb_inhibit_gpm();
1662                                         queue_scan(ud, js);
1663                                         return js;
1664                                 }
1665                         }
1666                 }
1667         }
1668         // No running item found? Maybe it was deleted
1669         // Look for a pending item starting from the last index we started
1670         for (ii = current; ii < count; ii++)
1671         {
1672                 js = ghb_array_get_nth(ud->queue, ii);
1673                 status = ghb_settings_get_int(js, "job_status");
1674                 if (status == GHB_QUEUE_PENDING)
1675                 {
1676                         current = ii;
1677                         ghb_inhibit_gpm();
1678                         queue_scan(ud, js);
1679                         return js;
1680                 }
1681         }
1682         // Nothing found
1683         ghb_uninhibit_gpm();
1684         ghb_notify_done(ud);
1685         return NULL;
1686 }
1687
1688 static gint
1689 find_queue_job(GValue *queue, gint unique_id, GValue **job)
1690 {
1691         GValue *js;
1692         gint ii, count;
1693         gint job_unique_id;
1694         
1695         *job = NULL;
1696         g_debug("find_queue_job");
1697         count = ghb_array_len(queue);
1698         for (ii = 0; ii < count; ii++)
1699         {
1700                 js = ghb_array_get_nth(queue, ii);
1701                 job_unique_id = ghb_settings_get_int(js, "job_unique_id");
1702                 if (job_unique_id == unique_id)
1703                 {
1704                         *job = js;
1705                         return ii;
1706                 }
1707         }
1708         return -1;
1709 }
1710
1711 gchar*
1712 working_status_string(signal_user_data_t *ud, ghb_instance_status_t *status)
1713 {
1714         gchar *task_str, *job_str, *status_str;
1715         gint qcount;
1716         gint index;
1717         GValue *js;
1718
1719         if (status->job_count > 1)
1720         {
1721                 task_str = g_strdup_printf("pass %d of %d, ", 
1722                         status->job_cur, status->job_count);
1723         }
1724         else
1725         {
1726                 task_str = g_strdup("");
1727         }
1728         qcount = ghb_array_len(ud->queue);
1729         if (qcount > 1)
1730         {
1731                 index = find_queue_job(ud->queue, status->unique_id, &js);
1732                 job_str = g_strdup_printf("job %d of %d, ", index+1, qcount);
1733         }
1734         else
1735         {
1736                 job_str = g_strdup("");
1737         }
1738         if(status->seconds > -1)
1739         {
1740                 status_str= g_strdup_printf(
1741                         "Encoding: %s%s%.2f %%"
1742                         " (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)",
1743                         job_str, task_str,
1744                         100.0 * status->progress,
1745                         status->rate_cur, status->rate_avg, status->hours, 
1746                         status->minutes, status->seconds );
1747         }
1748         else
1749         {
1750                 status_str= g_strdup_printf(
1751                         "Encoding: %s%s%.2f %%",
1752                         job_str, task_str,
1753                         100.0 * status->progress );
1754         }
1755         g_free(task_str);
1756         g_free(job_str);
1757         return status_str;
1758 }
1759
1760 static void
1761 ghb_backend_events(signal_user_data_t *ud)
1762 {
1763         ghb_status_t status;
1764         gchar *status_str;
1765         GtkProgressBar *progress;
1766         gint titleindex;
1767         GValue *js;
1768         gint index;
1769         GtkTreeView *treeview;
1770         GtkTreeStore *store;
1771         GtkTreeIter iter;
1772         static gint working = 0;
1773         static gboolean work_started = FALSE;
1774         
1775         ghb_track_status();
1776         ghb_get_status(&status);
1777         progress = GTK_PROGRESS_BAR(GHB_WIDGET (ud->builder, "progressbar"));
1778         // First handle the status of title scans
1779         // Then handle the status of the queue
1780         if (status.scan.state & GHB_STATE_SCANNING)
1781         {
1782                 if (status.scan.title_cur == 0)
1783                 {
1784                         status_str = g_strdup ("Scanning...");
1785                 }
1786                 else
1787                 {
1788                         status_str = g_strdup_printf ("Scanning title %d of %d...", 
1789                                                           status.scan.title_cur, status.scan.title_count );
1790                 }
1791                 gtk_progress_bar_set_text (progress, status_str);
1792                 g_free(status_str);
1793                 if (status.scan.title_count > 0)
1794                 {
1795                         gtk_progress_bar_set_fraction (progress, 
1796                                 (gdouble)status.scan.title_cur / status.scan.title_count);
1797                 }
1798         }
1799         else if (status.scan.state & GHB_STATE_SCANDONE)
1800         {
1801                 status_str = g_strdup_printf ("Scan done"); 
1802                 gtk_progress_bar_set_text (progress, status_str);
1803                 g_free(status_str);
1804                 gtk_progress_bar_set_fraction (progress, 1.0);
1805
1806                 ghb_title_info_t tinfo;
1807                         
1808                 ghb_update_ui_combo_box(ud->builder, "title", 0, FALSE);
1809                 titleindex = ghb_longest_title();
1810                 ghb_ui_update(ud, "title", ghb_int64_value(titleindex));
1811
1812                 // Are there really any titles.
1813                 if (!ghb_get_title_info(&tinfo, titleindex))
1814                 {
1815                         GtkProgressBar *progress;
1816                         progress = GTK_PROGRESS_BAR(GHB_WIDGET (ud->builder, "progressbar"));
1817                         gtk_progress_bar_set_fraction (progress, 0);
1818                         gtk_progress_bar_set_text (progress, "No Source");
1819                 }
1820                 ghb_clear_scan_state(GHB_STATE_SCANDONE);
1821                 ghb_queue_buttons_grey(ud, work_started);
1822                 if (ghb_queue_edit_settings)
1823                 {
1824                         gint jstatus;
1825
1826                         jstatus = ghb_settings_get_int(ghb_queue_edit_settings, "job_status");
1827                         ghb_settings_to_ui(ud, ghb_queue_edit_settings);
1828                         ghb_set_audio(ud, ghb_queue_edit_settings);
1829                         if (jstatus == GHB_QUEUE_PENDING)
1830                         {
1831                                 ghb_value_free(ghb_queue_edit_settings);
1832                         }
1833                         ghb_queue_edit_settings = NULL;
1834                 }
1835         }
1836         else if (status.queue.state & GHB_STATE_SCANNING)
1837         {
1838                 status_str = g_strdup_printf ("Scanning ...");
1839                 gtk_progress_bar_set_text (progress, status_str);
1840                 g_free(status_str);
1841                 gtk_progress_bar_set_fraction (progress, 0);
1842         }
1843         else if (status.queue.state & GHB_STATE_SCANDONE)
1844         {
1845                 ghb_clear_queue_state(GHB_STATE_SCANDONE);
1846                 usleep(2000000);
1847                 submit_job(ud->current_job);
1848         }
1849         else if (status.queue.state & GHB_STATE_PAUSED)
1850         {
1851                 status_str = g_strdup_printf ("Paused"); 
1852                 gtk_progress_bar_set_text (progress, status_str);
1853                 g_free(status_str);
1854         }
1855         else if (status.queue.state & GHB_STATE_WORKING)
1856         {
1857                 status_str = working_status_string(ud, &status.queue);
1858                 gtk_progress_bar_set_text (progress, status_str);
1859                 gtk_progress_bar_set_fraction (progress, status.queue.progress);
1860                 g_free(status_str);
1861         }
1862         else if (status.queue.state & GHB_STATE_WORKDONE)
1863         {
1864                 gint qstatus;
1865
1866                 work_started = FALSE;
1867                 ghb_queue_buttons_grey(ud, FALSE);
1868                 index = find_queue_job(ud->queue, status.queue.unique_id, &js);
1869                 treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "queue_list"));
1870                 store = GTK_TREE_STORE(gtk_tree_view_get_model(treeview));
1871                 if (ud->cancel_encode)
1872                         status.queue.error = GHB_ERROR_CANCELED;
1873                 switch( status.queue.error )
1874                 {
1875                         case GHB_ERROR_NONE:
1876                                 gtk_progress_bar_set_text( progress, "Rip done!" );
1877                                 qstatus = GHB_QUEUE_DONE;
1878                                 if (js != NULL)
1879                                 {
1880                                         gchar *path = g_strdup_printf ("%d", index);
1881                                         if (gtk_tree_model_get_iter_from_string(
1882                                                         GTK_TREE_MODEL(store), &iter, path))
1883                                         {
1884                                                 gtk_tree_store_set(store, &iter, 0, "hb-complete", -1);
1885                                         }
1886                                         g_free(path);
1887                                 }
1888                                 break;
1889                         case GHB_ERROR_CANCELED:
1890                                 gtk_progress_bar_set_text( progress, "Rip canceled." );
1891                                 qstatus = GHB_QUEUE_CANCELED;
1892                                 if (js != NULL)
1893                                 {
1894                                         gchar *path = g_strdup_printf ("%d", index);
1895                                         if (gtk_tree_model_get_iter_from_string(
1896                                                         GTK_TREE_MODEL(store), &iter, path))
1897                                         {
1898                                                 gtk_tree_store_set(store, &iter, 0, "hb-canceled", -1);
1899                                         }
1900                                         g_free(path);
1901                                 }
1902                                 break;
1903                         default:
1904                                 gtk_progress_bar_set_text( progress, "Rip failed.");
1905                                 qstatus = GHB_QUEUE_CANCELED;
1906                                 if (js != NULL)
1907                                 {
1908                                         gchar *path = g_strdup_printf ("%d", index);
1909                                         if (gtk_tree_model_get_iter_from_string(
1910                                                         GTK_TREE_MODEL(store), &iter, path))
1911                                         {
1912                                                 gtk_tree_store_set(store, &iter, 0, "hb-canceled", -1);
1913                                         }
1914                                         g_free(path);
1915                                 }
1916                 }
1917                 gtk_progress_bar_set_fraction (progress, 1.0);
1918                 ghb_clear_queue_state(GHB_STATE_WORKDONE);
1919                 if (ud->job_activity_log)
1920                         g_io_channel_unref(ud->job_activity_log);
1921                 ud->job_activity_log = NULL;
1922                 if (!ud->cancel_encode)
1923                 {
1924                         ud->current_job = ghb_start_next_job(ud, FALSE);
1925                 }
1926                 else
1927                 {
1928                         ghb_uninhibit_gpm();
1929                         ud->current_job = NULL;
1930                 }
1931                 if (js)
1932                         ghb_settings_set_int(js, "job_status", qstatus);
1933                 ghb_save_queue(ud->queue);
1934                 ud->cancel_encode = FALSE;
1935         }
1936         else if (status.queue.state & GHB_STATE_MUXING)
1937         {
1938                 gtk_progress_bar_set_text(progress, "Muxing: this may take awhile...");
1939         }
1940         if (status.queue.state & GHB_STATE_SCANNING)
1941         {
1942                 // This needs to be in scanning and working since scanning
1943                 // happens fast enough that it can be missed
1944                 if (!work_started)
1945                 {
1946                         work_started = TRUE;
1947                         ghb_queue_buttons_grey(ud, TRUE);
1948                 }
1949         }
1950         if (status.queue.state & GHB_STATE_WORKING)
1951         {
1952                 // This needs to be in scanning and working since scanning
1953                 // happens fast enough that it can be missed
1954                 if (!work_started)
1955                 {
1956                         work_started = TRUE;
1957                         ghb_queue_buttons_grey(ud, TRUE);
1958                 }
1959                 index = find_queue_job(ud->queue, status.queue.unique_id, &js);
1960                 if (status.queue.unique_id != 0 && index >= 0)
1961                 {
1962                         gchar working_icon[] = "hb-working0";
1963                         working_icon[10] = '0' + working;
1964                         working = (working+1) % 6;
1965                         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "queue_list"));
1966                         store = GTK_TREE_STORE(gtk_tree_view_get_model(treeview));
1967                         gchar *path = g_strdup_printf ("%d", index);
1968                         if (gtk_tree_model_get_iter_from_string(
1969                                         GTK_TREE_MODEL(store), &iter, path))
1970                         {
1971                                 gtk_tree_store_set(store, &iter, 0, working_icon, -1);
1972                         }
1973                         g_free(path);
1974                 }
1975                 GtkLabel *label;
1976                 gchar *status_str;
1977
1978                 status_str = working_status_string(ud, &status.queue);
1979                 label = GTK_LABEL(GHB_WIDGET(ud->builder, "queue_status"));
1980                 gtk_label_set_text (label, status_str);
1981                 g_free(status_str);
1982         }
1983         if (status.scan.state & GHB_STATE_WORKING)
1984         {
1985                 GtkProgressBar *live_progress;
1986                 live_progress = GTK_PROGRESS_BAR(
1987                         GHB_WIDGET(ud->builder, "live_encode_progress"));
1988                 status_str = working_status_string(ud, &status.scan);
1989                 gtk_progress_bar_set_text (live_progress, status_str);
1990                 gtk_progress_bar_set_fraction (live_progress, status.scan.progress);
1991                 g_free(status_str);
1992         }
1993         if (status.scan.state & GHB_STATE_WORKDONE)
1994         {
1995                 switch( status.scan.error )
1996                 {
1997                         case GHB_ERROR_NONE:
1998                         {
1999                                 ghb_live_encode_done(ud, TRUE);
2000                         } break;
2001                         default:
2002                         {
2003                                 ghb_live_encode_done(ud, FALSE);
2004                         } break;
2005                 }
2006                 ghb_clear_scan_state(GHB_STATE_WORKDONE);
2007         }
2008 }
2009
2010 gboolean
2011 ghb_timer_cb(gpointer data)
2012 {
2013         signal_user_data_t *ud = (signal_user_data_t*)data;
2014
2015         ghb_live_preview_progress(ud);
2016         ghb_backend_events(ud);
2017         if (update_default_destination)
2018         {
2019                 gchar *dest, *dest_dir, *def_dest;
2020                 dest = ghb_settings_get_string(ud->settings, "destination");
2021                 dest_dir = g_path_get_dirname (dest);
2022                 def_dest = ghb_settings_get_string(ud->settings, "destination_dir");
2023                 if (strcmp(dest_dir, def_dest) != 0)
2024                 {
2025                         ghb_settings_set_string (ud->settings, "destination_dir", dest_dir);
2026                         ghb_pref_save (ud->settings, "destination_dir");
2027                 }
2028                 g_free(dest);
2029                 g_free(dest_dir);
2030                 g_free(def_dest);
2031                 update_default_destination = FALSE;
2032         }
2033         if (update_preview)
2034         {
2035                 ghb_set_preview_image (ud);
2036                 update_preview = FALSE;
2037         }
2038         return TRUE;
2039 }
2040
2041 gboolean
2042 ghb_log_cb(GIOChannel *source, GIOCondition cond, gpointer data)
2043 {
2044         gchar *text = NULL;
2045         gsize length;
2046         GtkTextView *textview;
2047         GtkTextBuffer *buffer;
2048         GtkTextIter iter;
2049         GtkTextMark *mark;
2050         GError *gerror = NULL;
2051         GIOStatus status;
2052         
2053         signal_user_data_t *ud = (signal_user_data_t*)data;
2054
2055         status = g_io_channel_read_line (source, &text, &length, NULL, &gerror);
2056         if (text != NULL)
2057         {
2058                 GdkWindow *window;
2059                 gint width, height;
2060                 gint x, y;
2061                 gboolean bottom = FALSE;
2062
2063                 textview = GTK_TEXT_VIEW(GHB_WIDGET (ud->builder, "activity_view"));
2064                 buffer = gtk_text_view_get_buffer (textview);
2065                 // I would like to auto-scroll the window when the scrollbar
2066                 // is at the bottom, 
2067                 // must determine whether the insert point is at
2068                 // the bottom of the window 
2069                 window = gtk_text_view_get_window(textview, GTK_TEXT_WINDOW_TEXT);
2070                 if (window != NULL)
2071                 {
2072                         gdk_drawable_get_size(GDK_DRAWABLE(window), &width, &height);
2073                         gtk_text_view_window_to_buffer_coords(textview, 
2074                                 GTK_TEXT_WINDOW_TEXT, width, height, &x, &y);
2075                         gtk_text_view_get_iter_at_location(textview, &iter, x, y);
2076                         if (gtk_text_iter_is_end(&iter))
2077                         {
2078                                 bottom = TRUE;
2079                         }
2080                 }
2081                 else
2082                 {
2083                         // If the window isn't available, assume bottom
2084                         bottom = TRUE;
2085                 }
2086                 gtk_text_buffer_get_end_iter(buffer, &iter);
2087                 gtk_text_buffer_insert(buffer, &iter, text, -1);
2088                 if (bottom)
2089                 {
2090                         gtk_text_buffer_get_end_iter(buffer, &iter);
2091                         mark = gtk_text_buffer_create_mark(buffer, NULL, &iter, FALSE);
2092                         gtk_text_view_scroll_mark_onscreen(textview, mark);
2093                         gtk_text_buffer_delete_mark(buffer, mark);
2094                 }
2095                 g_io_channel_write_chars (ud->activity_log, text, 
2096                                                                 length, &length, NULL);
2097                 g_io_channel_flush(ud->activity_log, NULL);
2098                 if (ud->job_activity_log)
2099                 {
2100                         g_io_channel_write_chars (ud->job_activity_log, text, 
2101                                                                         length, &length, NULL);
2102                         g_io_channel_flush(ud->job_activity_log, NULL);
2103                 }
2104                 g_free(text);
2105         }
2106         if (status != G_IO_STATUS_NORMAL)
2107         {
2108                 // This should never happen, but if it does I would get into an
2109                 // infinite loop.  Returning false removes this callback.
2110                 g_warning("Error while reading activity from pipe");
2111                 if (gerror != NULL)
2112                 {
2113                         g_warning("%s", gerror->message);
2114                         g_error_free (gerror);
2115                 }
2116                 return FALSE;
2117         }
2118         if (gerror != NULL)
2119                 g_error_free (gerror);
2120         return TRUE;
2121 }
2122
2123 static void
2124 set_visible(GtkWidget *widget, gboolean visible)
2125 {
2126         if (visible)
2127         {
2128                 gtk_widget_show_now(widget);
2129         }
2130         else
2131         {
2132                 gtk_widget_hide(widget);
2133         }
2134 }
2135
2136 void
2137 show_activity_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
2138 {
2139         GtkWidget *widget = GHB_WIDGET (ud->builder, "activity_window");
2140         set_visible(widget, gtk_toggle_tool_button_get_active(
2141                                                 GTK_TOGGLE_TOOL_BUTTON(xwidget)));
2142 }
2143
2144 void
2145 show_activity_menu_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
2146 {
2147         GtkWidget *widget = GHB_WIDGET (ud->builder, "activity_window");
2148         set_visible(widget, TRUE);
2149         widget = GHB_WIDGET (ud->builder, "show_activity");
2150         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), TRUE);
2151 }
2152
2153 gboolean
2154 activity_window_delete_cb(GtkWidget *xwidget, GdkEvent *event, signal_user_data_t *ud)
2155 {
2156         set_visible(xwidget, FALSE);
2157         GtkWidget *widget = GHB_WIDGET (ud->builder, "show_activity");
2158         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), FALSE);
2159         return TRUE;
2160 }
2161
2162 void
2163 ghb_log(gchar *log, ...)
2164 {
2165         va_list args;
2166         time_t _now;
2167     struct tm *now;
2168         gchar fmt[362];
2169
2170         _now = time(NULL);
2171         now = localtime( &_now );
2172         snprintf(fmt, 362, "[%02d:%02d:%02d] lingui: %s\n", 
2173                         now->tm_hour, now->tm_min, now->tm_sec, log);
2174         va_start(args, log);
2175         vfprintf(stderr, fmt, args);
2176         va_end(args);
2177 }
2178
2179 static void
2180 browse_url(const gchar *url)
2181 {
2182         gboolean result;
2183         char *argv[] = 
2184                 {"xdg-open",NULL,NULL,NULL};
2185         argv[1] = (gchar*)url;
2186         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
2187                                 NULL, NULL, NULL);
2188         if (result) return;
2189
2190         argv[0] = "gnome-open";
2191         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
2192                                 NULL, NULL, NULL);
2193         if (result) return;
2194
2195         argv[0] = "kfmclient";
2196         argv[1] = "exec";
2197         argv[2] = "http://trac.handbrake.fr/wiki/HandBrakeGuide";
2198         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
2199                                 NULL, NULL, NULL);
2200         if (result) return;
2201
2202         argv[0] = "firefox";
2203         argv[1] = "http://trac.handbrake.fr/wiki/HandBrakeGuide";
2204         argv[2] = NULL;
2205         result = g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
2206                                 NULL, NULL, NULL);
2207 }
2208
2209 void
2210 about_web_hook(GtkAboutDialog *about, const gchar *link, gpointer data)
2211 {
2212         browse_url(link);
2213 }
2214
2215 void
2216 about_activate_cb(GtkWidget *xwidget, signal_user_data_t *ud)
2217 {
2218         GtkWidget *widget = GHB_WIDGET (ud->builder, "hb_about");
2219         gchar *ver;
2220
2221         ver = g_strdup_printf("%s (%s)", HB_PROJECT_VERSION, HB_PROJECT_BUILD_ARCH);
2222         gtk_about_dialog_set_url_hook(about_web_hook, NULL, NULL);
2223         gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(widget), ver);
2224         g_free(ver);
2225         gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(widget), 
2226                                                                 HB_PROJECT_URL_WEBSITE);
2227         gtk_about_dialog_set_website_label(GTK_ABOUT_DIALOG(widget), 
2228                                                                                 HB_PROJECT_URL_WEBSITE);
2229         gtk_widget_show (widget);
2230 }
2231
2232 void
2233 guide_activate_cb(GtkWidget *xwidget, signal_user_data_t *ud)
2234 {
2235         browse_url("http://trac.handbrake.fr/wiki/HandBrakeGuide");
2236 }
2237
2238 void
2239 hb_about_response_cb(GtkWidget *widget, gint response, signal_user_data_t *ud)
2240 {
2241         gtk_widget_hide (widget);
2242 }
2243
2244 void
2245 show_queue_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
2246 {
2247         GtkWidget *widget = GHB_WIDGET (ud->builder, "queue_window");
2248         set_visible(widget, gtk_toggle_tool_button_get_active(
2249                                                 GTK_TOGGLE_TOOL_BUTTON(xwidget)));
2250 }
2251
2252 void
2253 show_queue_menu_clicked_cb(GtkWidget *xwidget, signal_user_data_t *ud)
2254 {
2255         GtkWidget *widget = GHB_WIDGET (ud->builder, "queue_window");
2256         set_visible(widget, TRUE);
2257         widget = GHB_WIDGET (ud->builder, "show_queue");
2258         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), TRUE);
2259 }
2260
2261 gboolean
2262 queue_window_delete_cb(GtkWidget *xwidget, GdkEvent *event, signal_user_data_t *ud)
2263 {
2264         set_visible(xwidget, FALSE);
2265         GtkWidget *widget = GHB_WIDGET (ud->builder, "show_queue");
2266         gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(widget), FALSE);
2267         return TRUE;
2268 }
2269
2270 void
2271 show_presets_toggled_cb(GtkWidget *action, signal_user_data_t *ud)
2272 {
2273         GtkWidget *widget;
2274         GtkWindow *hb_window;
2275         
2276         g_debug("show_presets_clicked_cb ()");
2277         widget = GHB_WIDGET (ud->builder, "presets_frame");
2278         ghb_widget_to_setting(ud->settings, action);
2279         if (ghb_settings_get_boolean(ud->settings, "show_presets"))
2280         {
2281                 gtk_widget_show_now(widget);
2282         }
2283         else
2284         {
2285                 gtk_widget_hide(widget);
2286                 hb_window = GTK_WINDOW(GHB_WIDGET (ud->builder, "hb_window"));
2287                 gtk_window_resize(hb_window, 16, 16);
2288         }
2289         ghb_pref_save(ud->settings, "show_presets");
2290 }
2291
2292 static void
2293 update_chapter_list(signal_user_data_t *ud)
2294 {
2295         GtkTreeView *treeview;
2296         GtkTreeIter iter;
2297         GtkListStore *store;
2298         gboolean done;
2299         GValue *chapters;
2300         gint titleindex, ii;
2301         gint count;
2302         
2303         g_debug("update_chapter_list ()");
2304         titleindex = ghb_settings_combo_int(ud->settings, "title");
2305         chapters = ghb_get_chapters(titleindex);
2306         count = ghb_array_len(chapters);
2307         if (chapters)
2308                 ghb_settings_set_value(ud->settings, "chapter_list", chapters);
2309         
2310         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "chapters_list"));
2311         store = GTK_LIST_STORE(gtk_tree_view_get_model(treeview));
2312         ii = 0;
2313         if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter))
2314         {
2315                 do
2316                 {
2317
2318                         if (ii < count)
2319                         {
2320                                 gchar *chapter, *duration;
2321                                 gint hh, mm, ss;
2322
2323                                 // Update row with settings data
2324                                 g_debug("Updating row");
2325                                 chapter = ghb_value_string(ghb_array_get_nth(chapters, ii));
2326                                 ghb_get_chapter_duration(titleindex, ii, &hh, &mm, &ss);
2327                                 duration = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
2328                                 gtk_list_store_set(store, &iter, 
2329                                         0, ii+1,
2330                                         1, duration,
2331                                         2, chapter,
2332                                         3, TRUE,
2333                                         -1);
2334                                 g_free(chapter);
2335                                 g_free(duration);
2336                                 ii++;
2337                                 done = !gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
2338                         }
2339                         else
2340                         {
2341                                 // No more settings data, remove row
2342                                 g_debug("Removing row");
2343                                 done = !gtk_list_store_remove(store, &iter);
2344                         }
2345                 } while (!done);
2346         }
2347         while (ii < count)
2348         {
2349                 gchar *chapter, *duration;
2350                 gint hh, mm, ss;
2351
2352                 // Additional settings, add row
2353                 g_debug("Adding row");
2354                 chapter = ghb_value_string(ghb_array_get_nth(chapters, ii));
2355                 ghb_get_chapter_duration(titleindex, ii, &hh, &mm, &ss);
2356                 duration = g_strdup_printf("%02d:%02d:%02d", hh, mm, ss);
2357                 gtk_list_store_append(store, &iter);
2358                 gtk_list_store_set(store, &iter, 
2359                         0, ii+1,
2360                         1, duration,
2361                         2, chapter,
2362                         3, TRUE,
2363                         -1);
2364                 g_free(chapter);
2365                 g_free(duration);
2366                 ii++;
2367         }
2368 }
2369
2370 static gint chapter_edit_key = 0;
2371
2372 gboolean
2373 chapter_keypress_cb(
2374         GhbCellRendererText *cell,
2375         GdkEventKey *event,
2376         signal_user_data_t *ud)
2377 {
2378         chapter_edit_key = event->keyval;
2379         return FALSE;
2380 }
2381
2382 void
2383 chapter_edited_cb(
2384         GhbCellRendererText *cell, 
2385         gchar *path, 
2386         gchar *text, 
2387         signal_user_data_t *ud)
2388 {
2389         GtkTreePath *treepath;
2390         GtkListStore *store;
2391         GtkTreeView *treeview;
2392         GtkTreeIter iter;
2393         gint index;
2394         gint *pi;
2395         gint row;
2396         
2397         g_debug("chapter_edited_cb ()");
2398         g_debug("path (%s)", path);
2399         g_debug("text (%s)", text);
2400         treeview = GTK_TREE_VIEW(GHB_WIDGET(ud->builder, "chapters_list"));
2401         store = GTK_LIST_STORE(gtk_tree_view_get_model(treeview));
2402         treepath = gtk_tree_path_new_from_string (path);
2403         pi = gtk_tree_path_get_indices(treepath);
2404         row = pi[0];
2405         gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, treepath);
2406         gtk_list_store_set(store, &iter, 
2407                 2, text,
2408                 3, TRUE,
2409                 -1);
2410         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &index, -1);
2411
2412         const GValue *chapters;
2413         GValue *chapter;
2414
2415         chapters = ghb_settings_get_value(ud->settings, "chapter_list");
2416         chapter = ghb_array_get_nth(chapters, index-1);
2417         g_value_set_string(chapter, text);
2418         if ((chapter_edit_key == GDK_Return || chapter_edit_key == GDK_Down) &&
2419                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter))
2420         {
2421                 GtkTreeViewColumn *column;
2422
2423                 gtk_tree_path_next(treepath);
2424                 // When a cell has been edited, I want to advance to the
2425                 // next cell and start editing it automaitcally.
2426                 // Unfortunately, we may not be in a state here where
2427                 // editing is allowed.  This happens when the user selects
2428                 // a new cell with the mouse instead of just hitting enter.
2429                 // Some kind of Gtk quirk.  widget_editable==NULL assertion.
2430                 // Editing is enabled again once the selection event has been
2431                 // processed.  So I'm queueing up a callback to be called
2432                 // when things go idle.  There, I will advance to the next
2433                 // cell and initiate editing.
2434                 //
2435                 // Now, you might be asking why I don't catch the keypress
2436                 // event and determine what action to take based on that.
2437                 // The Gtk developers in their infinite wisdom have made the 
2438                 // actual GtkEdit widget being used a private member of
2439                 // GtkCellRendererText, so it can not be accessed to hang a
2440                 // signal handler off of.  And they also do not propagate the
2441                 // keypress signals in any other way.  So that information is lost.
2442                 //g_idle_add((GSourceFunc)next_cell, ud);
2443                 //
2444                 // Keeping the above comment for posterity.
2445                 // I got industrious and made my own CellTextRendererText that
2446                 // passes on the key-press-event. So now I have much better
2447                 // control of this.
2448                 column = gtk_tree_view_get_column(treeview, 2);
2449                 gtk_tree_view_set_cursor(treeview, treepath, column, TRUE);
2450         }
2451         else if (chapter_edit_key == GDK_Up && row > 0)
2452         {
2453                 GtkTreeViewColumn *column;
2454                 gtk_tree_path_prev(treepath);
2455                 column = gtk_tree_view_get_column(treeview, 2);
2456                 gtk_tree_view_set_cursor(treeview, treepath, column, TRUE);
2457         }
2458         gtk_tree_path_free (treepath);
2459 }
2460
2461 void
2462 chapter_list_selection_changed_cb(GtkTreeSelection *selection, signal_user_data_t *ud)
2463 {
2464         g_debug("chapter_list_selection_changed_cb ()");
2465         //chapter_selection_changed = TRUE;
2466 }
2467
2468 void
2469 debug_log_handler(const gchar *domain, GLogLevelFlags flags, const gchar *msg, gpointer data)
2470 {
2471         signal_user_data_t *ud = (signal_user_data_t*)data;
2472         
2473         if (ud->debug)
2474         {
2475                 printf("%s: %s\n", domain, msg);
2476         }
2477 }
2478
2479 void
2480 warn_log_handler(const gchar *domain, GLogLevelFlags flags, const gchar *msg, gpointer data)
2481 {
2482         printf("mywarning\n");
2483         printf("%s: %s\n", domain, msg);
2484 }
2485
2486 void
2487 ghb_hbfd(signal_user_data_t *ud, gboolean hbfd)
2488 {
2489         GtkWidget *widget;
2490         g_debug("ghb_hbfd");
2491         widget = GHB_WIDGET(ud->builder, "queue_pause1");
2492         set_visible(widget, !hbfd);
2493         widget = GHB_WIDGET(ud->builder, "queue_add");
2494         set_visible(widget, !hbfd);
2495         widget = GHB_WIDGET(ud->builder, "show_queue");
2496         set_visible(widget, !hbfd);
2497         widget = GHB_WIDGET(ud->builder, "show_activity");
2498         set_visible(widget, !hbfd);
2499
2500         widget = GHB_WIDGET(ud->builder, "chapter_box");
2501         set_visible(widget, !hbfd);
2502         widget = GHB_WIDGET(ud->builder, "container_box");
2503         set_visible(widget, !hbfd);
2504         widget = GHB_WIDGET(ud->builder, "settings_box");
2505         set_visible(widget, !hbfd);
2506         widget = GHB_WIDGET(ud->builder, "presets_save");
2507         set_visible(widget, !hbfd);
2508         widget = GHB_WIDGET(ud->builder, "presets_remove");
2509         set_visible(widget, !hbfd);
2510         widget = GHB_WIDGET (ud->builder, "hb_window");
2511         gtk_window_resize(GTK_WINDOW(widget), 16, 16);
2512
2513 }
2514
2515 void
2516 hbfd_toggled_cb(GtkWidget *widget, signal_user_data_t *ud)
2517 {
2518         g_debug("hbfd_toggled_cb");
2519         ghb_widget_to_setting (ud->settings, widget);
2520         gboolean hbfd = ghb_settings_get_boolean(ud->settings, "hbfd");
2521         ghb_hbfd(ud, hbfd);
2522         ghb_pref_save(ud->settings, "hbfd");
2523 }
2524
2525 void
2526 pref_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
2527 {
2528         g_debug("pref_changed_cb");
2529         ghb_widget_to_setting (ud->settings, widget);
2530         ghb_check_dependency(ud, widget);
2531         const gchar *name = gtk_widget_get_name(widget);
2532         ghb_pref_save(ud->settings, name);
2533 }
2534
2535 void
2536 vqual_granularity_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
2537 {
2538         g_debug("vqual_granularity_changed_cb");
2539         ghb_widget_to_setting (ud->settings, widget);
2540         ghb_check_dependency(ud, widget);
2541
2542         const gchar *name = gtk_widget_get_name(widget);
2543         ghb_pref_save(ud->settings, name);
2544
2545         gdouble vqmin, vqmax, step, page;
2546         gboolean inverted;
2547         gint digits;
2548
2549         ghb_vquality_range(ud, &vqmin, &vqmax, &step, &page, &digits, &inverted);
2550         GtkWidget *qp = GHB_WIDGET(ud->builder, "VideoQualitySlider");
2551         gtk_range_set_increments (GTK_RANGE(qp), step, page);
2552 }
2553
2554 void
2555 tweaks_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
2556 {
2557         g_debug("tweaks_changed_cb");
2558         ghb_widget_to_setting (ud->settings, widget);
2559         const gchar *name = gtk_widget_get_name(widget);
2560         ghb_pref_save(ud->settings, name);
2561 }
2562
2563 void
2564 hbfd_feature_changed_cb(GtkWidget *widget, signal_user_data_t *ud)
2565 {
2566         g_debug("hbfd_feature_changed_cb");
2567         ghb_widget_to_setting (ud->settings, widget);
2568         const gchar *name = gtk_widget_get_name(widget);
2569         ghb_pref_save(ud->settings, name);
2570
2571         gboolean hbfd = ghb_settings_get_boolean(ud->settings, "hbfd_feature");
2572         GtkAction *action;
2573         if (hbfd)
2574         {
2575                 const GValue *val;
2576                 val = ghb_settings_get_value(ud->settings, "hbfd");
2577                 ghb_ui_update(ud, "hbfd", val);
2578         }
2579         action = GHB_ACTION (ud->builder, "hbfd");
2580         gtk_action_set_visible(action, hbfd);
2581 }
2582
2583 void
2584 ghb_file_menu_add_dvd(signal_user_data_t *ud)
2585 {
2586         GList *link, *drives;
2587
2588         GtkActionGroup *agroup = GTK_ACTION_GROUP(
2589                 gtk_builder_get_object(ud->builder, "actiongroup1"));
2590         GtkUIManager *ui = GTK_UI_MANAGER(
2591                 gtk_builder_get_object(ud->builder, "uimanager1"));
2592         guint merge_id = gtk_ui_manager_new_merge_id(ui);
2593
2594         link = drives = dvd_device_list();
2595         while (link != NULL)
2596         {
2597                 gchar *name = (gchar*)link->data;
2598                 // Create action for this drive
2599                 GtkAction *action = gtk_action_new(name, name,
2600                         "Scan this DVD source", "gtk-cdrom");
2601                 // Add action to action group
2602                 gtk_action_group_add_action_with_accel(agroup, action, "");
2603                 // Add to ui manager
2604                 gtk_ui_manager_add_ui(ui, merge_id, 
2605                         "ui/menubar1/menuitem1/quit1", name, name,
2606                         GTK_UI_MANAGER_AUTO, TRUE);
2607                 // Connect signal to action (menu item)
2608                 g_signal_connect(action, "activate", 
2609                         (GCallback)dvd_source_activate_cb, ud);
2610                 g_free(name);
2611                 link = link->next;
2612         }
2613         g_list_free(drives);
2614
2615         // Add separator
2616         gtk_ui_manager_add_ui(ui, merge_id, 
2617                 "ui/menubar1/menuitem1/quit1", "", NULL,
2618                 GTK_UI_MANAGER_AUTO, TRUE);
2619 }
2620
2621 gboolean ghb_is_cd(GDrive *gd);
2622
2623 static GList*
2624 dvd_device_list()
2625 {
2626         GVolumeMonitor *gvm;
2627         GList *drives, *link;
2628         GList *dvd_devices = NULL;
2629         
2630         gvm = g_volume_monitor_get ();
2631         drives = g_volume_monitor_get_connected_drives (gvm);
2632         link = drives;
2633         while (link != NULL)
2634         {
2635                 GDrive *gd;
2636                 
2637                 gd = (GDrive*)link->data;
2638                 if (ghb_is_cd(gd))
2639                 {
2640                         gchar *device;
2641                         device = g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
2642                         dvd_devices = g_list_append(dvd_devices, (gpointer)device);
2643                 }
2644                 g_object_unref (gd);
2645                 link = link->next;
2646         }
2647         g_list_free(drives);
2648         return dvd_devices;
2649 }
2650
2651 static LibHalContext *hal_ctx;
2652
2653 gboolean
2654 ghb_is_cd(GDrive *gd)
2655 {
2656         gchar *device;
2657         LibHalDrive *halDrive;
2658         LibHalDriveType dtype;
2659
2660         device = g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
2661         halDrive = libhal_drive_from_device_file (hal_ctx, device);
2662         dtype = libhal_drive_get_type(halDrive);
2663         libhal_drive_free(halDrive);
2664         g_free(device);
2665         return (dtype == LIBHAL_DRIVE_TYPE_CDROM);
2666 }
2667
2668 void
2669 drive_changed_cb(GVolumeMonitor *gvm, GDrive *gd, signal_user_data_t *ud)
2670 {
2671         gchar *device;
2672         gint state = ghb_get_scan_state();
2673         static gboolean first_time = TRUE;
2674
2675         if (state != GHB_STATE_IDLE) return;
2676         if (ud->current_dvd_device == NULL) return;
2677         // A drive change event happens when the program initially starts
2678         // and I don't want to automatically scan at that time.
2679         if (first_time)
2680         {
2681                 first_time = FALSE;
2682                 return;
2683         }
2684         device = g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
2685         
2686         // DVD insertion detected.  Scan it.
2687         if (strcmp(device, ud->current_dvd_device) == 0)
2688         {
2689                 if (g_drive_has_media (gd))
2690                 {
2691                         GtkProgressBar *progress;
2692                         progress = GTK_PROGRESS_BAR(GHB_WIDGET (ud->builder, "progressbar"));
2693                         gtk_progress_bar_set_text (progress, "Scanning ...");
2694                         gtk_progress_bar_set_fraction (progress, 0);
2695                         update_source_label(ud, device);
2696                         prune_logs(ud);
2697                         gint preview_count;
2698                         preview_count = ghb_settings_get_int(ud->settings, "preview_count");
2699                         ghb_backend_scan(device, 0, preview_count);
2700                 }
2701                 else
2702                 {
2703                         prune_logs(ud);
2704                         ghb_backend_scan("/dev/null", 0, 1);
2705                 }
2706         }
2707         g_free(device);
2708 }
2709
2710
2711 static void
2712 dbus_init (void)
2713 {
2714         dbus_g_thread_init();
2715 }
2716
2717 #define GPM_DBUS_SERVICE                        "org.freedesktop.PowerManagement"
2718 #define GPM_DBUS_INHIBIT_PATH           "/org/freedesktop/PowerManagement/Inhibit"
2719 #define GPM_DBUS_INHIBIT_INTERFACE      "org.freedesktop.PowerManagement.Inhibit" 
2720 static gboolean gpm_inhibited = FALSE;
2721 static guint gpm_cookie = -1;
2722
2723 void
2724 ghb_inhibit_gpm()
2725 {
2726         DBusGConnection *conn;
2727         DBusGProxy      *proxy;
2728         GError *error = NULL;
2729         gboolean res;
2730         
2731
2732         if (gpm_inhibited)
2733         {
2734                 // Already inhibited
2735                 return;
2736         }
2737         g_debug("ghb_inhibit_gpm()");
2738         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
2739         if (error != NULL)
2740         {
2741                 g_debug("DBUS cannot connect: %s", error->message);
2742                 g_error_free(error);
2743                 return;
2744         }
2745         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_SERVICE,
2746                                                         GPM_DBUS_INHIBIT_PATH, GPM_DBUS_INHIBIT_INTERFACE);
2747         if (proxy == NULL)
2748         {
2749                 g_debug("Could not get DBUS proxy: %s", GPM_DBUS_SERVICE);
2750                 dbus_g_connection_unref(conn);
2751                 return;
2752         }
2753         res = dbus_g_proxy_call(proxy, "Inhibit", &error,
2754                                                         G_TYPE_STRING, "ghb",
2755                                                         G_TYPE_STRING, "Encoding",
2756                                                         G_TYPE_INVALID,
2757                                                         G_TYPE_UINT, &gpm_cookie,
2758                                                         G_TYPE_INVALID);
2759         if (!res)
2760         {
2761                 g_warning("Inhibit method failed");
2762                 gpm_cookie = -1;
2763         }
2764         if (error != NULL)
2765         {
2766                 g_warning("Inhibit problem: %s", error->message);
2767                 g_error_free(error);
2768                 gpm_cookie = -1;
2769         }
2770         gpm_inhibited = TRUE;
2771         g_object_unref(G_OBJECT(proxy));
2772         dbus_g_connection_unref(conn);
2773 }
2774
2775 void
2776 ghb_uninhibit_gpm()
2777 {
2778         DBusGConnection *conn;
2779         DBusGProxy      *proxy;
2780         GError *error = NULL;
2781         gboolean res;
2782         
2783         g_debug("ghb_uninhibit_gpm() gpm_cookie %u", gpm_cookie);
2784
2785         if (!gpm_inhibited)
2786         {
2787                 // Not inhibited
2788                 return;
2789         }
2790         conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
2791         if (error != NULL)
2792         {
2793                 g_debug("DBUS cannot connect: %s", error->message);
2794                 g_error_free(error);
2795                 return;
2796         }
2797         proxy = dbus_g_proxy_new_for_name(conn, GPM_DBUS_SERVICE,
2798                                                         GPM_DBUS_INHIBIT_PATH, GPM_DBUS_INHIBIT_INTERFACE);
2799         if (proxy == NULL)
2800         {
2801                 g_debug("Could not get DBUS proxy: %s", GPM_DBUS_SERVICE);
2802                 dbus_g_connection_unref(conn);
2803                 return;
2804         }
2805         res = dbus_g_proxy_call(proxy, "UnInhibit", &error,
2806                                                         G_TYPE_UINT, gpm_cookie,
2807                                                         G_TYPE_INVALID,
2808                                                         G_TYPE_INVALID);
2809         if (!res)
2810         {
2811                 g_warning("UnInhibit method failed");
2812         }
2813         if (error != NULL)
2814         {
2815                 g_warning("UnInhibit problem: %s", error->message);
2816                 g_error_free(error);
2817         }
2818         gpm_inhibited = FALSE;
2819         dbus_g_connection_unref(conn);
2820         g_object_unref(G_OBJECT(proxy));
2821 }
2822
2823 void
2824 ghb_hal_init()
2825 {
2826         DBusGConnection *gconn;
2827         DBusConnection *conn;
2828         GError *gerror = NULL;
2829         DBusError error;
2830         char **devices;
2831         int nr;
2832
2833         dbus_init ();
2834
2835         if (!(hal_ctx = libhal_ctx_new ())) {
2836                 g_warning ("failed to create a HAL context!");
2837                 return;
2838         }
2839
2840         gconn = dbus_g_bus_get(DBUS_BUS_SYSTEM, &gerror);
2841         if (gerror != NULL)
2842         {
2843                 g_warning("DBUS cannot connect: %s", gerror->message);
2844                 g_error_free(gerror);
2845                 return;
2846         }
2847         conn = dbus_g_connection_get_connection(gconn);
2848         libhal_ctx_set_dbus_connection (hal_ctx, conn);
2849         dbus_error_init (&error);
2850         if (!libhal_ctx_init (hal_ctx, &error)) {
2851                 g_warning ("libhal_ctx_init failed: %s", error.message ? error.message : "unknown");
2852                 dbus_error_free (&error);
2853                 libhal_ctx_free (hal_ctx);
2854                 dbus_g_connection_unref(gconn);
2855                 return;
2856         }
2857
2858         /*
2859          * Do something to ping the HAL daemon - the above functions will
2860          * succeed even if hald is not running, so long as DBUS is.  But we
2861          * want to exit silently if hald is not running, to behave on
2862          * pre-2.6 systems.
2863          */
2864         if (!(devices = libhal_get_all_devices (hal_ctx, &nr, &error))) {
2865                 g_warning ("seems that HAL is not running: %s", error.message ? error.message : "unknown");
2866                 dbus_error_free (&error);
2867
2868                 libhal_ctx_shutdown (hal_ctx, NULL);
2869                 libhal_ctx_free (hal_ctx);
2870                 dbus_g_connection_unref(gconn);
2871                 return;
2872         }
2873
2874         libhal_free_string_array (devices);
2875         dbus_g_connection_unref(gconn);
2876 }
2877
2878 gboolean 
2879 tweak_setting_cb(
2880         GtkWidget *widget, 
2881         GdkEventButton *event, 
2882         signal_user_data_t *ud)
2883 {
2884         const gchar *name;
2885         gchar *tweak_name;
2886         gboolean ret = FALSE;
2887         gboolean allow_tweaks;
2888
2889         g_debug("press %d %d", event->type, event->button);
2890         allow_tweaks = ghb_settings_get_boolean(ud->settings, "allow_tweaks");
2891         if (allow_tweaks && event->type == GDK_BUTTON_PRESS && event->button == 3)
2892         { // Its a right mouse click
2893                 GtkWidget *dialog;
2894                 GtkEntry *entry;
2895                 GtkResponseType response;
2896                 gchar *tweak = NULL;
2897
2898                 name = gtk_widget_get_name(widget);
2899                 if (g_str_has_prefix(name, "tweak_"))
2900                 {
2901                         tweak_name = g_strdup(name);
2902                 }
2903                 else
2904                 {
2905                         tweak_name = g_strdup_printf("tweak_%s", name);
2906                 }
2907
2908                 tweak = ghb_settings_get_string (ud->settings, tweak_name);
2909                 dialog = GHB_WIDGET(ud->builder, "tweak_dialog");
2910                 gtk_window_set_title(GTK_WINDOW(dialog), tweak_name);
2911                 entry = GTK_ENTRY(GHB_WIDGET(ud->builder, "tweak_setting"));
2912                 if (tweak)
2913                 {
2914                         gtk_entry_set_text(entry, tweak);
2915                         g_free(tweak);
2916                 }
2917                 response = gtk_dialog_run(GTK_DIALOG(dialog));
2918                 gtk_widget_hide(dialog);
2919                 if (response == GTK_RESPONSE_OK)
2920                 {
2921                         tweak = (gchar*)gtk_entry_get_text(entry);
2922                         if (ghb_validate_filter_string(tweak, -1))
2923                                 ghb_settings_set_string(ud->settings, tweak_name, tweak);
2924                         else
2925                         {
2926                                 gchar *message;
2927                                 message = g_strdup_printf(
2928                                                         "Invalid Settings:\n%s",
2929                                                         tweak);
2930                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2931                                 g_free(message);
2932                         }
2933                 }
2934                 g_free(tweak_name);
2935                 ret = TRUE;
2936         }
2937         return ret;
2938 }
2939
2940 gboolean 
2941 easter_egg_cb(
2942         GtkWidget *widget, 
2943         GdkEventButton *event, 
2944         signal_user_data_t *ud)
2945 {
2946         g_debug("press %d %d", event->type, event->button);
2947         if (event->type == GDK_3BUTTON_PRESS && event->button == 1)
2948         { // Its a tripple left mouse button click
2949                 GtkWidget *widget;
2950                 widget = GHB_WIDGET(ud->builder, "allow_tweaks");
2951                 gtk_widget_show(widget);
2952                 widget = GHB_WIDGET(ud->builder, "hbfd_feature");
2953                 gtk_widget_show(widget);
2954         }
2955         else if (event->type == GDK_BUTTON_PRESS && event->button == 1)
2956         {
2957                 GtkWidget *widget;
2958                 widget = GHB_WIDGET(ud->builder, "allow_tweaks");
2959                 gtk_widget_hide(widget);
2960                 widget = GHB_WIDGET(ud->builder, "hbfd_feature");
2961                 gtk_widget_hide(widget);
2962         }
2963         return FALSE;
2964 }
2965
2966 gchar*
2967 format_deblock_cb(GtkScale *scale, gdouble val, signal_user_data_t *ud)
2968 {
2969         if (val < 5.0)
2970         {
2971                 return g_strdup_printf("Off");
2972         }
2973         else
2974         {
2975                 return g_strdup_printf("%d", (gint)val);
2976         }
2977 }
2978
2979 gchar*
2980 format_drc_cb(GtkScale *scale, gdouble val, signal_user_data_t *ud)
2981 {
2982         if (val <= 0.0)
2983         {
2984                 return g_strdup_printf("Off");
2985         }
2986         else
2987         {
2988                 return g_strdup_printf("%.1f", val);
2989         }
2990 }
2991
2992 gchar*
2993 format_vquality_cb(GtkScale *scale, gdouble val, signal_user_data_t *ud)
2994 {
2995         gdouble percent;
2996
2997         gint vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
2998         switch (vcodec)
2999         {
3000                 case HB_VCODEC_X264:
3001                 {
3002                         gboolean crf;
3003                         crf = ghb_settings_get_boolean(ud->settings, "constant_rate_factor");
3004                         percent = 100. * (51 - val) / 51.;
3005                         if (crf)
3006                                 return g_strdup_printf("RF: %.4g (%.0f%%)", val, percent);
3007                         else
3008                                 return g_strdup_printf("QP: %.4g (%.0f%%)", val, percent);
3009                 } break;
3010
3011                 case HB_VCODEC_XVID:
3012                 case HB_VCODEC_FFMPEG:
3013                 {
3014                         percent = 100. * (30 - (val - 1)) / 30.;
3015                         return g_strdup_printf("QP: %d (%.0f%%)", (int)val, percent);
3016                 } break;
3017
3018                 case HB_VCODEC_THEORA:
3019                 {
3020                         percent = 100. * val / 63.;
3021                         return g_strdup_printf("QP: %d (%.0f%%)", (int)val, percent);
3022                 } break;
3023
3024                 default:
3025                 {
3026                         percent = 0;
3027                 } break;
3028         }
3029         return g_strdup_printf("QP: %.1f / %.1f%%", val, percent);
3030 }
3031
3032 static void
3033 html_link_cb(GtkHTML *html, const gchar *url, signal_user_data_t *ud)
3034 {
3035         browse_url(url);
3036 }
3037
3038 static gpointer check_stable_update(signal_user_data_t *ud);
3039 static gboolean stable_update_lock = FALSE;
3040
3041 static void
3042 process_appcast(signal_user_data_t *ud)
3043 {
3044         gchar *description = NULL, *build = NULL, *version = NULL, *msg;
3045         GtkWidget *html, *window, *dialog, *label;
3046         gint    response, ibuild = 0, skip;
3047
3048         if (ud->appcast == NULL || ud->appcast_len < 15 || 
3049                 strncmp(&(ud->appcast[9]), "200 OK", 6))
3050         {
3051                 if (!stable_update_lock && hb_get_build(NULL) % 100)
3052                         g_idle_add((GSourceFunc)check_stable_update, ud);
3053                 goto done;
3054         }
3055         ghb_appcast_parse(ud->appcast, &description, &build, &version);
3056         if (build)
3057                 ibuild = g_strtod(build, NULL);
3058         skip = ghb_settings_get_int(ud->settings, "update_skip_version");
3059         if (description == NULL || build == NULL || version == NULL 
3060                 || ibuild <= hb_get_build(NULL) || skip == ibuild)
3061         {
3062                 if (!stable_update_lock && hb_get_build(NULL) % 100)
3063                         g_thread_create((GThreadFunc)check_stable_update, ud, FALSE, NULL);
3064                 goto done;
3065         }
3066         msg = g_strdup_printf("HandBrake %s/%s is now available (you have %s/%d).",
3067                         version, build, hb_get_version(NULL), hb_get_build(NULL));
3068         label = GHB_WIDGET(ud->builder, "update_message");
3069         gtk_label_set_text(GTK_LABEL(label), msg);
3070         html = gtk_html_new_from_string(description, -1);
3071         g_signal_connect(html, "link_clicked", G_CALLBACK(html_link_cb), ud);
3072         window = GHB_WIDGET(ud->builder, "update_scroll");
3073         gtk_container_add(GTK_CONTAINER(window), html);
3074         // Show it
3075         dialog = GHB_WIDGET(ud->builder, "update_dialog");
3076         gtk_widget_set_size_request(html, 420, 240);
3077         gtk_widget_show(html);
3078         response = gtk_dialog_run(GTK_DIALOG(dialog));
3079         gtk_widget_hide(dialog);
3080         gtk_widget_destroy(html);
3081         if (response == GTK_RESPONSE_OK)
3082         {
3083                 // Skip
3084                 ghb_settings_set_int(ud->settings, "update_skip_version", ibuild);
3085                 ghb_pref_save(ud->settings, "update_skip_version");
3086         }
3087         g_free(msg);
3088
3089 done:
3090         if (description) g_free(description);
3091         if (build) g_free(build);
3092         if (version) g_free(version);
3093         g_free(ud->appcast);
3094         ud->appcast_len = 0;
3095         ud->appcast = NULL;
3096 }
3097
3098 void
3099 ghb_net_close(GIOChannel *ioc)
3100 {
3101         gint fd;
3102
3103         g_debug("ghb_net_close");
3104         if (ioc == NULL) return;
3105         fd = g_io_channel_unix_get_fd(ioc);
3106         close(fd);
3107         g_io_channel_unref(ioc);
3108 }
3109
3110 gboolean
3111 ghb_net_recv_cb(GIOChannel *ioc, GIOCondition cond, gpointer data)
3112 {
3113         gchar buf[2048];
3114         gsize len;
3115         GError *gerror = NULL;
3116         GIOStatus status;
3117         
3118         g_debug("ghb_net_recv_cb");
3119         signal_user_data_t *ud = (signal_user_data_t*)data;
3120
3121         status = g_io_channel_read_chars (ioc, buf, 2048, &len, &gerror);
3122         if ((status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_EOF) &&
3123                 len > 0)
3124         {
3125                 gint new_len = ud->appcast_len + len;
3126                 ud->appcast = g_realloc(ud->appcast, new_len + 1);
3127                 memcpy(&(ud->appcast[ud->appcast_len]), buf, len);
3128                 ud->appcast_len = new_len;
3129         }
3130         if (status == G_IO_STATUS_EOF)
3131         {
3132                 ud->appcast[ud->appcast_len] = 0;
3133                 ghb_net_close(ioc);
3134                 process_appcast(ud);
3135                 return FALSE;
3136         }
3137         return TRUE;
3138 }
3139
3140 GIOChannel*
3141 ghb_net_open(signal_user_data_t *ud, gchar *address, gint port)
3142 {
3143         GIOChannel *ioc;
3144         gint fd;
3145
3146         struct sockaddr_in   sock;
3147         struct hostent     * host;
3148
3149         g_debug("ghb_net_open");
3150         if( !( host = gethostbyname( address ) ) )
3151         {
3152                 g_warning( "gethostbyname failed (%s)", address );
3153                 return NULL;
3154         }
3155
3156         memset( &sock, 0, sizeof( struct sockaddr_in ) );
3157         sock.sin_family = host->h_addrtype;
3158         sock.sin_port   = htons( port );
3159         memcpy( &sock.sin_addr, host->h_addr, host->h_length );
3160
3161         fd = socket(host->h_addrtype, SOCK_STREAM, 0);
3162         if( fd < 0 )
3163         {
3164                 g_debug( "socket failed" );
3165                 return NULL;
3166         }
3167
3168         if(connect(fd, (struct sockaddr*)&sock, sizeof(struct sockaddr_in )) < 0 )
3169         {
3170                 g_debug( "connect failed" );
3171                 return NULL;
3172         }
3173         ioc = g_io_channel_unix_new(fd);
3174         g_io_channel_set_encoding (ioc, NULL, NULL);
3175         g_io_channel_set_flags(ioc, G_IO_FLAG_NONBLOCK, NULL);
3176         g_io_add_watch (ioc, G_IO_IN, ghb_net_recv_cb, (gpointer)ud );
3177
3178         return ioc;
3179 }
3180
3181 gpointer
3182 ghb_check_update(signal_user_data_t *ud)
3183 {
3184         gchar *query;
3185         gsize len;
3186         GIOChannel *ioc;
3187         GError *gerror = NULL;
3188
3189         g_debug("ghb_check_update");
3190         if (hb_get_build(NULL) % 100)
3191         {
3192         query = 
3193                 "GET /appcast_unstable.xml HTTP/1.0\r\nHost: handbrake.fr\r\n\r\n";
3194         }
3195         else
3196         {
3197                 stable_update_lock = TRUE;
3198         query = "GET /appcast.xml HTTP/1.0\r\nHost: handbrake.fr\r\n\r\n";
3199         }
3200         ioc = ghb_net_open(ud, "handbrake.fr", 80);
3201         if (ioc == NULL)
3202                 return NULL;
3203
3204         g_io_channel_write_chars(ioc, query, strlen(query), &len, &gerror);
3205         g_io_channel_flush(ioc, &gerror);
3206         // This function is initiated by g_idle_add.  Must return false
3207         // so that it is not called again
3208         return NULL;
3209 }
3210
3211 static gpointer
3212 check_stable_update(signal_user_data_t *ud)
3213 {
3214         gchar *query;
3215         gsize len;
3216         GIOChannel *ioc;
3217         GError *gerror = NULL;
3218
3219         g_debug("check_stable_update");
3220         stable_update_lock = TRUE;
3221         query = "GET /appcast.xml HTTP/1.0\r\nHost: handbrake.fr\r\n\r\n";
3222         ioc = ghb_net_open(ud, "handbrake.fr", 80);
3223         if (ioc == NULL)
3224                 return NULL;
3225
3226         g_io_channel_write_chars(ioc, query, strlen(query), &len, &gerror);
3227         g_io_channel_flush(ioc, &gerror);
3228         // This function is initiated by g_idle_add.  Must return false
3229         // so that it is not called again
3230         return NULL;
3231 }
3232
3233 void
3234 status_activate_cb(GtkStatusIcon *si, signal_user_data_t *ud)
3235 {
3236         GtkWindow *window;
3237
3238         window = GTK_WINDOW(GHB_WIDGET(ud->builder, "hb_window"));
3239         gtk_window_present(window);
3240 }
3241
3242 static void
3243 notify_closed_cb(NotifyNotification *notification, signal_user_data_t *ud)
3244 {
3245         g_object_unref(G_OBJECT(notification));
3246 }
3247
3248 void
3249 ghb_notify_done(signal_user_data_t *ud)
3250 {
3251         NotifyNotification *notification;
3252         GtkStatusIcon *si;
3253
3254         si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));
3255         gtk_status_icon_set_from_icon_name(si, "hb-status-empty");
3256         notification = notify_notification_new(
3257                 "Encode Complete",
3258                 "Put down that cocktail, Your HandBrake queue is done!",
3259                 "hb-icon",
3260                 NULL);
3261         notify_notification_attach_to_status_icon(notification, si);
3262         g_signal_connect(notification, "closed", (GCallback)notify_closed_cb, ud);
3263         notify_notification_show(notification, NULL);
3264 }