id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
401
./cinnamon-control-center/panels/unused/mouse/test-cinnamon-mouse-test.c
#include <config.h> #include <gtk/gtk.h> #include "cinnamon-mouse-test.h" static gboolean delete_event_cb (GtkWidget *widget, GdkEvent *event, gpointer user_data) { GtkWidget *window = user_data; gnome_mouse_test_dispose (window); gtk_main_quit (); return FALSE; } int main (int argc, char **argv) { GtkBuilder *builder; GtkWidget *window; GError *error = NULL; gtk_init (&argc, &argv); builder = gtk_builder_new (); gtk_builder_add_from_file (builder, "cinnamon-mouse-test.ui", &error); if (error != NULL) { g_warning ("Error loading UI file: %s", error->message); return 1; } window = gnome_mouse_test_init (builder); gtk_widget_show_all (window); g_signal_connect (G_OBJECT (window), "delete-event", G_CALLBACK (delete_event_cb), window); gtk_main (); return 0; }
402
./cinnamon-control-center/panels/unused/mouse/gsd-input-helper.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2010 Bastien Nocera <hadess@hadess.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <sys/types.h> #include <X11/Xatom.h> #include <X11/extensions/XInput2.h> #include "gsd-input-helper.h" #define INPUT_DEVICES_SCHEMA "org.cinnamon.settings-daemon.peripherals.input-devices" #define KEY_HOTPLUG_COMMAND "hotplug-command" typedef gboolean (* InfoIdentifyFunc) (XDeviceInfo *device_info); typedef gboolean (* DeviceIdentifyFunc) (XDevice *xdevice); gboolean device_set_property (XDevice *xdevice, const char *device_name, PropertyHelper *property) { int rc, i; Atom prop; Atom realtype; int realformat; unsigned long nitems, bytes_after; unsigned char *data; prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), property->name, False); if (!prop) return FALSE; gdk_error_trap_push (); rc = XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xdevice, prop, 0, property->nitems, False, AnyPropertyType, &realtype, &realformat, &nitems, &bytes_after, &data); if (rc != Success || realtype != property->type || realformat != property->format || nitems < property->nitems) { gdk_error_trap_pop_ignored (); g_warning ("Error reading property \"%s\" for \"%s\"", property->name, device_name); return FALSE; } for (i = 0; i < nitems; i++) { switch (property->format) { case 8: data[i] = property->data.c[i]; break; case 32: ((long*)data)[i] = property->data.i[i]; break; } } XChangeDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xdevice, prop, realtype, realformat, PropModeReplace, data, nitems); XFree (data); if (gdk_error_trap_pop ()) { g_warning ("Error in setting \"%s\" for \"%s\"", property->name, device_name); return FALSE; } return TRUE; } static gboolean supports_xinput_devices_with_opcode (int *opcode) { gint op_code, event, error; gboolean retval; retval = XQueryExtension (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "XInputExtension", &op_code, &event, &error); if (opcode) *opcode = op_code; return retval; } gboolean supports_xinput_devices (void) { return supports_xinput_devices_with_opcode (NULL); } gboolean supports_xinput2_devices (int *opcode) { int major, minor; if (supports_xinput_devices_with_opcode (opcode) == FALSE) return FALSE; gdk_error_trap_push (); major = 2; minor = 0; if (XIQueryVersion (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &major, &minor) != Success) { gdk_error_trap_pop_ignored (); /* try for 2.2, maybe gtk has already announced 2.2 support */ gdk_error_trap_push (); major = 2; minor = 2; if (XIQueryVersion (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &major, &minor) != Success) { gdk_error_trap_pop_ignored (); return FALSE; } } gdk_error_trap_pop_ignored (); if ((major * 1000 + minor) < (2000)) return FALSE; return TRUE; } gboolean device_is_touchpad (XDevice *xdevice) { Atom realtype, prop; int realformat; unsigned long nitems, bytes_after; unsigned char *data; /* we don't check on the type being XI_TOUCHPAD here, * but having a "Synaptics Off" property should be enough */ prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Synaptics Off", False); if (!prop) return FALSE; gdk_error_trap_push (); if ((XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xdevice, prop, 0, 1, False, XA_INTEGER, &realtype, &realformat, &nitems, &bytes_after, &data) == Success) && (realtype != None)) { gdk_error_trap_pop_ignored (); XFree (data); return TRUE; } gdk_error_trap_pop_ignored (); return FALSE; } gboolean device_info_is_touchpad (XDeviceInfo *device_info) { return (device_info->type == XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), XI_TOUCHPAD, False)); } gboolean device_info_is_touchscreen (XDeviceInfo *device_info) { return (device_info->type == XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), XI_TOUCHSCREEN, False)); } gboolean device_info_is_mouse (XDeviceInfo *device_info) { return (device_info->type == XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), XI_MOUSE, False)); } static gboolean device_type_is_present (InfoIdentifyFunc info_func, DeviceIdentifyFunc device_func) { XDeviceInfo *device_info; gint n_devices; guint i; gboolean retval; if (supports_xinput_devices () == FALSE) return TRUE; retval = FALSE; device_info = XListInputDevices (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &n_devices); if (device_info == NULL) return FALSE; for (i = 0; i < n_devices; i++) { XDevice *device; /* Check with the device info first */ retval = (info_func) (&device_info[i]); if (retval == FALSE) continue; /* If we only have an info func, we're done checking */ if (device_func == NULL) break; gdk_error_trap_push (); device = XOpenDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device_info[i].id); if (gdk_error_trap_pop () || (device == NULL)) continue; retval = (device_func) (device); if (retval) { XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device); break; } XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device); } XFreeDeviceList (device_info); return retval; } gboolean touchscreen_is_present (void) { return device_type_is_present (device_info_is_touchscreen, NULL); } gboolean touchpad_is_present (void) { return device_type_is_present (device_info_is_touchpad, device_is_touchpad); } gboolean mouse_is_present (void) { return device_type_is_present (device_info_is_mouse, NULL); } char * xdevice_get_device_node (int deviceid) { Atom prop; Atom act_type; int act_format; unsigned long nitems, bytes_after; unsigned char *data; char *ret; gdk_display_sync (gdk_display_get_default ()); prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Device Node", False); if (!prop) return NULL; gdk_error_trap_push (); if (!XIGetProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), deviceid, prop, 0, 1000, False, AnyPropertyType, &act_type, &act_format, &nitems, &bytes_after, &data) == Success) { gdk_error_trap_pop_ignored (); return NULL; } if (gdk_error_trap_pop ()) goto out; if (nitems == 0) goto out; if (act_type != XA_STRING) goto out; /* Unknown string format */ if (act_format != 8) goto out; ret = g_strdup ((char *) data); XFree (data); return ret; out: XFree (data); return NULL; } #define TOOL_ID_FORMAT_SIZE 32 static int get_id_for_index (guchar *data, guint idx) { guchar *ptr; int id; ptr = data; ptr += TOOL_ID_FORMAT_SIZE / 8 * idx; id = *((int32_t*)ptr); id = id & 0xfffff; return id; } #define STYLUS_DEVICE_ID 0x02 #define ERASER_DEVICE_ID 0x0A int xdevice_get_last_tool_id (int deviceid) { Atom prop; Atom act_type; int act_format; unsigned long nitems, bytes_after; unsigned char *data; int id; id = -1; gdk_display_sync (gdk_display_get_default ()); prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), WACOM_SERIAL_IDS_PROP, False); if (!prop) return -1; data = NULL; gdk_error_trap_push (); if (XIGetProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), deviceid, prop, 0, 1000, False, AnyPropertyType, &act_type, &act_format, &nitems, &bytes_after, &data) != Success) { gdk_error_trap_pop_ignored (); goto out; } if (gdk_error_trap_pop ()) goto out; if (nitems != 4 && nitems != 5) goto out; if (act_type != XA_INTEGER) goto out; if (act_format != TOOL_ID_FORMAT_SIZE) goto out; /* item 0 = tablet ID * item 1 = old device serial number (== last tool in proximity) * item 2 = old hardware serial number (including tool ID) * item 3 = current serial number (0 if no tool in proximity) * item 4 = current tool ID (since Feb 2012) * * Get the current tool ID first, if available, then the old one */ id = 0x0; if (nitems == 5) id = get_id_for_index (data, 4); if (id == 0x0) id = get_id_for_index (data, 2); /* That means that no tool was set down yet */ if (id == STYLUS_DEVICE_ID || id == ERASER_DEVICE_ID) id = 0x0; out: if (data != NULL) XFree (data); return id; } gboolean set_device_enabled (int device_id, gboolean enabled) { Atom prop; guchar value; prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Device Enabled", False); if (!prop) return FALSE; gdk_error_trap_push (); value = enabled ? 1 : 0; XIChangeProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device_id, prop, XA_INTEGER, 8, PropModeReplace, &value, 1); if (gdk_error_trap_pop ()) return FALSE; return TRUE; } static const char * custom_command_to_string (CustomCommand command) { switch (command) { case COMMAND_DEVICE_ADDED: return "added"; case COMMAND_DEVICE_REMOVED: return "removed"; case COMMAND_DEVICE_PRESENT: return "present"; default: g_assert_not_reached (); } } /* Run a custom command on device presence events. Parameters passed into * the custom command are: * command -t [added|removed|present] -i <device ID> <device name> * Type 'added' and 'removed' signal 'device added' and 'device removed', * respectively. Type 'present' signals 'device present at * gnome-settings-daemon init'. * * The script is expected to run synchronously, and an exit value * of "1" means that no other settings will be applied to this * particular device. * * More options may be added in the future. * * This function returns TRUE if we should not apply any more settings * to the device. */ gboolean run_custom_command (GdkDevice *device, CustomCommand command) { GSettings *settings; char *cmd; char *argv[7]; int exit_status; gboolean rc; int id; settings = g_settings_new (INPUT_DEVICES_SCHEMA); cmd = g_settings_get_string (settings, KEY_HOTPLUG_COMMAND); g_object_unref (settings); if (!cmd || cmd[0] == '\0') { g_free (cmd); return FALSE; } /* Easter egg! */ g_object_get (device, "device-id", &id, NULL); argv[0] = cmd; argv[1] = "-t"; argv[2] = (char *) custom_command_to_string (command); argv[3] = "-i"; argv[4] = g_strdup_printf ("%d", id); argv[5] = g_strdup_printf ("%s", gdk_device_get_name (device)); argv[6] = NULL; rc = g_spawn_sync (g_get_home_dir (), argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL, &exit_status, NULL); if (rc == FALSE) g_warning ("Couldn't execute command '%s', verify that this is a valid command.", cmd); g_free (argv[0]); g_free (argv[4]); g_free (argv[5]); return (exit_status == 0); } GList * get_disabled_devices (GdkDeviceManager *manager) { XDeviceInfo *device_info; gint n_devices; guint i; GList *ret; ret = NULL; device_info = XListInputDevices (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &n_devices); if (device_info == NULL) return ret; for (i = 0; i < n_devices; i++) { GdkDevice *device; /* Ignore core devices */ if (device_info[i].use == IsXKeyboard || device_info[i].use == IsXPointer) continue; /* Check whether the device is actually available */ device = gdk_x11_device_manager_lookup (manager, device_info[i].id); if (device != NULL) continue; ret = g_list_prepend (ret, GINT_TO_POINTER (device_info[i].id)); } XFreeDeviceList (device_info); return ret; }
403
./cinnamon-control-center/panels/unused/background/bg-wallpapers-source.c
/* bg-wallpapers-source.c */ /* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include "bg-wallpapers-source.h" #include "cc-background-item.h" #include "cc-background-xml.h" #include <libgnome-desktop/gnome-desktop-thumbnail.h> #include <gio/gio.h> G_DEFINE_TYPE (BgWallpapersSource, bg_wallpapers_source, BG_TYPE_SOURCE) #define WALLPAPERS_SOURCE_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), BG_TYPE_WALLPAPERS_SOURCE, BgWallpapersSourcePrivate)) struct _BgWallpapersSourcePrivate { GnomeDesktopThumbnailFactory *thumb_factory; CcBackgroundXml *xml; }; static void bg_wallpapers_source_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void bg_wallpapers_source_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void bg_wallpapers_source_dispose (GObject *object) { BgWallpapersSourcePrivate *priv = BG_WALLPAPERS_SOURCE (object)->priv; if (priv->thumb_factory) { g_object_unref (priv->thumb_factory); priv->thumb_factory = NULL; } if (priv->xml) { g_object_unref (priv->xml); priv->xml = NULL; } G_OBJECT_CLASS (bg_wallpapers_source_parent_class)->dispose (object); } static void bg_wallpapers_source_finalize (GObject *object) { G_OBJECT_CLASS (bg_wallpapers_source_parent_class)->finalize (object); } static void bg_wallpapers_source_class_init (BgWallpapersSourceClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (BgWallpapersSourcePrivate)); object_class->get_property = bg_wallpapers_source_get_property; object_class->set_property = bg_wallpapers_source_set_property; object_class->dispose = bg_wallpapers_source_dispose; object_class->finalize = bg_wallpapers_source_finalize; } static void load_wallpapers (gchar *key, CcBackgroundItem *item, BgWallpapersSource *source) { BgWallpapersSourcePrivate *priv = source->priv; GtkTreeIter iter; GIcon *pixbuf; GtkListStore *store = bg_source_get_liststore (BG_SOURCE (source)); gboolean deleted; g_object_get (G_OBJECT (item), "is-deleted", &deleted, NULL); if (deleted) return; gtk_list_store_append (store, &iter); pixbuf = cc_background_item_get_thumbnail (item, priv->thumb_factory, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); gtk_list_store_set (store, &iter, 0, pixbuf, 1, g_object_ref (item), 2, cc_background_item_get_name (item), -1); if (pixbuf) g_object_unref (pixbuf); } static void list_load_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { cc_background_xml_load_list_finish (res); } static void item_added (CcBackgroundXml *xml, CcBackgroundItem *item, BgWallpapersSource *self) { load_wallpapers (NULL, item, self); } static void load_default_bg (BgWallpapersSource *self) { const char * const *system_data_dirs; char *filename; guint i; /* FIXME We could do this nicer if we had the XML source in GSettings */ system_data_dirs = g_get_system_data_dirs (); for (i = 0; system_data_dirs[i]; i++) { filename = g_build_filename (system_data_dirs[i], "gnome-background-properties", "adwaita.xml", NULL); if (cc_background_xml_load_xml (self->priv->xml, filename)) { g_free (filename); break; } g_free (filename); } } static void bg_wallpapers_source_init (BgWallpapersSource *self) { BgWallpapersSourcePrivate *priv; priv = self->priv = WALLPAPERS_SOURCE_PRIVATE (self); priv->thumb_factory = gnome_desktop_thumbnail_factory_new (GNOME_DESKTOP_THUMBNAIL_SIZE_LARGE); priv->xml = cc_background_xml_new (); g_signal_connect (G_OBJECT (priv->xml), "added", G_CALLBACK (item_added), self); /* Try adding the default background first */ load_default_bg (self); cc_background_xml_load_list_async (priv->xml, NULL, list_load_cb, self); } BgWallpapersSource * bg_wallpapers_source_new (void) { return g_object_new (BG_TYPE_WALLPAPERS_SOURCE, NULL); }
404
./cinnamon-control-center/panels/unused/background/background-module.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include <config.h> #include "cc-background-panel.h" #include <glib/gi18n.h> void g_io_module_load (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); /* register the panel */ cc_background_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
405
./cinnamon-control-center/panels/unused/background/cc-background-chooser-dialog.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2012 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * */ #include "config.h" #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "cc-background-chooser-dialog.h" #include "bg-wallpapers-source.h" #include "bg-pictures-source.h" #include "bg-colors-source.h" #ifdef HAVE_LIBSOCIALWEB #include "bg-flickr-source.h" #endif #include "cc-background-item.h" #include "cc-background-xml.h" #define WP_PATH_ID "org.gnome.desktop.background" #define WP_URI_KEY "picture-uri" #define WP_OPTIONS_KEY "picture-options" #define WP_SHADING_KEY "color-shading-type" #define WP_PCOLOR_KEY "primary-color" #define WP_SCOLOR_KEY "secondary-color" enum { SOURCE_WALLPAPERS, SOURCE_PICTURES, SOURCE_COLORS, #ifdef HAVE_LIBSOCIALWEB SOURCE_FLICKR #endif }; struct _CcBackgroundChooserDialogPrivate { GtkListStore *sources; GtkWidget *icon_view; BgWallpapersSource *wallpapers_source; BgPicturesSource *pictures_source; BgColorsSource *colors_source; #ifdef HAVE_LIBSOCIALWEB BgFlickrSource *flickr_source; #endif GnomeDesktopThumbnailFactory *thumb_factory; gint current_source; GCancellable *copy_cancellable; GtkWidget *spinner; }; #define CC_CHOOSER_DIALOG_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), CC_TYPE_BACKGROUND_CHOOSER_DIALOG, CcBackgroundChooserDialogPrivate)) enum { PROP_0, }; G_DEFINE_TYPE (CcBackgroundChooserDialog, cc_background_chooser_dialog, GTK_TYPE_DIALOG) static void cc_background_chooser_dialog_realize (GtkWidget *widget) { CcBackgroundChooserDialog *chooser = CC_BACKGROUND_CHOOSER_DIALOG (widget); GtkWindow *parent; parent = gtk_window_get_transient_for (GTK_WINDOW (chooser)); if (parent != NULL) { gint width; gint height; gtk_window_get_size (parent, &width, &height); gtk_widget_set_size_request (GTK_WIDGET (chooser), (gint) (0.5 * width), (gint) (0.9 * height)); } gtk_icon_view_set_model (GTK_ICON_VIEW (chooser->priv->icon_view), GTK_TREE_MODEL (bg_source_get_liststore (BG_SOURCE (chooser->priv->wallpapers_source)))); GTK_WIDGET_CLASS (cc_background_chooser_dialog_parent_class)->realize (widget); } static void cc_background_chooser_dialog_dispose (GObject *object) { CcBackgroundChooserDialog *chooser = CC_BACKGROUND_CHOOSER_DIALOG (object); CcBackgroundChooserDialogPrivate *priv = chooser->priv; if (priv->copy_cancellable) { /* cancel any copy operation */ g_cancellable_cancel (priv->copy_cancellable); g_clear_object (&priv->copy_cancellable); } g_clear_object (&priv->pictures_source); g_clear_object (&priv->colors_source); g_clear_object (&priv->wallpapers_source); g_clear_object (&priv->thumb_factory); G_OBJECT_CLASS (cc_background_chooser_dialog_parent_class)->dispose (object); } static void cc_background_chooser_dialog_finalize (GObject *object) { G_OBJECT_CLASS (cc_background_chooser_dialog_parent_class)->finalize (object); } static void on_view_toggled (GtkToggleButton *button, CcBackgroundChooserDialog *chooser) { BgSource *source; if (!gtk_toggle_button_get_active (button)) return; source = g_object_get_data (G_OBJECT (button), "source"); gtk_icon_view_set_model (GTK_ICON_VIEW (chooser->priv->icon_view), GTK_TREE_MODEL (bg_source_get_liststore (source))); } static void on_selection_changed (GtkIconView *icon_view, CcBackgroundChooserDialog *chooser) { GList *list; list = gtk_icon_view_get_selected_items (icon_view); gtk_dialog_set_response_sensitive (GTK_DIALOG (chooser), GTK_RESPONSE_OK, (list != NULL)); g_list_free_full (list, (GDestroyNotify) gtk_tree_path_free); } static void on_item_activated (GtkIconView *icon_view, GtkTreePath *path, CcBackgroundChooserDialog *chooser) { gtk_dialog_response (GTK_DIALOG (chooser), GTK_RESPONSE_OK); } static void cc_background_chooser_dialog_init (CcBackgroundChooserDialog *chooser) { CcBackgroundChooserDialogPrivate *priv; GtkCellRenderer *renderer; GtkWidget *sw_content; GtkWidget *vbox; GtkWidget *button1; GtkWidget *button; GtkWidget *hbox; GtkWidget *grid; GtkStyleContext *context; chooser->priv = CC_CHOOSER_DIALOG_GET_PRIVATE (chooser); priv = chooser->priv; priv->wallpapers_source = bg_wallpapers_source_new (); priv->pictures_source = bg_pictures_source_new (); priv->colors_source = bg_colors_source_new (); #ifdef HAVE_LIBSOCIALWEB priv->flickr_source = bg_flickr_source_new (); #endif gtk_container_set_border_width (GTK_CONTAINER (chooser), 6); gtk_window_set_modal (GTK_WINDOW (chooser), TRUE); gtk_window_set_resizable (GTK_WINDOW (chooser), FALSE); /* translators: This is the title of the wallpaper chooser dialog. */ gtk_window_set_title (GTK_WINDOW (chooser), _("Select Background")); vbox = gtk_dialog_get_content_area (GTK_DIALOG (chooser)); grid = gtk_grid_new (); gtk_container_set_border_width (GTK_CONTAINER (grid), 5); gtk_widget_set_margin_bottom (grid, 6); gtk_orientable_set_orientation (GTK_ORIENTABLE (grid), GTK_ORIENTATION_VERTICAL); gtk_grid_set_row_spacing (GTK_GRID (grid), 12); gtk_grid_set_column_spacing (GTK_GRID (grid), 0); gtk_container_add (GTK_CONTAINER (vbox), grid); hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_set_homogeneous (GTK_BOX (hbox), TRUE); gtk_widget_set_halign (hbox, GTK_ALIGN_CENTER); gtk_widget_set_hexpand (hbox, TRUE); gtk_container_add (GTK_CONTAINER (grid), hbox); context = gtk_widget_get_style_context (hbox); gtk_style_context_add_class (context, "linked"); button1 = gtk_radio_button_new_with_label (NULL, _("Wallpapers")); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button1), TRUE); context = gtk_widget_get_style_context (button1); gtk_style_context_add_class (context, "raised"); gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (button1), FALSE); gtk_container_add (GTK_CONTAINER (hbox), button1); g_signal_connect (button1, "toggled", G_CALLBACK (on_view_toggled), chooser); g_object_set_data (G_OBJECT (button1), "source", priv->wallpapers_source); button = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (button1), _("Pictures")); context = gtk_widget_get_style_context (button); gtk_style_context_add_class (context, "raised"); gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (button), FALSE); gtk_container_add (GTK_CONTAINER (hbox), button); g_signal_connect (button, "toggled", G_CALLBACK (on_view_toggled), chooser); g_object_set_data (G_OBJECT (button), "source", priv->pictures_source); button = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (button1), _("Colors")); context = gtk_widget_get_style_context (button); gtk_style_context_add_class (context, "raised"); gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (button), FALSE); gtk_container_add (GTK_CONTAINER (hbox), button); g_signal_connect (button, "toggled", G_CALLBACK (on_view_toggled), chooser); g_object_set_data (G_OBJECT (button), "source", priv->colors_source); #ifdef HAVE_LIBSOCIALWEB button = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (button1), _("Flickr")); context = gtk_widget_get_style_context (button); gtk_style_context_add_class (context, "raised"); gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (button), FALSE); gtk_container_add (GTK_CONTAINER (hbox), button); g_signal_connect (button, "toggled", G_CALLBACK (on_view_toggled), chooser); g_object_set_data (G_OBJECT (button), "source", priv->flickr_source); #endif sw_content = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw_content), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw_content), GTK_SHADOW_IN); gtk_widget_set_hexpand (sw_content, TRUE); gtk_widget_set_vexpand (sw_content, TRUE); gtk_container_add (GTK_CONTAINER (grid), sw_content); g_object_set (sw_content, "width-request", 850, "height-request", 550, NULL); priv->icon_view = gtk_icon_view_new (); gtk_widget_set_hexpand (priv->icon_view, TRUE); gtk_container_add (GTK_CONTAINER (sw_content), priv->icon_view); g_signal_connect (priv->icon_view, "selection-changed", G_CALLBACK (on_selection_changed), chooser); g_signal_connect (priv->icon_view, "item-activated", G_CALLBACK (on_item_activated), chooser); renderer = gtk_cell_renderer_pixbuf_new (); /* set stock size to 32px so that emblems render at 16px. see: * https://bugzilla.gnome.org/show_bug.cgi?id=682123#c4 */ g_object_set (renderer, "stock-size", GTK_ICON_SIZE_DND, NULL); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (priv->icon_view), renderer, FALSE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (priv->icon_view), renderer, "gicon", 0, NULL); gtk_dialog_add_button (GTK_DIALOG (chooser), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL); gtk_dialog_add_button (GTK_DIALOG (chooser), _("Select"), GTK_RESPONSE_OK); gtk_dialog_set_default_response (GTK_DIALOG (chooser), GTK_RESPONSE_OK); gtk_dialog_set_response_sensitive (GTK_DIALOG (chooser), GTK_RESPONSE_OK, FALSE); gtk_widget_show_all (vbox); } static void cc_background_chooser_dialog_class_init (CcBackgroundChooserDialogClass *klass) { GObjectClass *object_class; GtkWidgetClass *widget_class; object_class = G_OBJECT_CLASS (klass); object_class->dispose = cc_background_chooser_dialog_dispose; object_class->finalize = cc_background_chooser_dialog_finalize; widget_class = GTK_WIDGET_CLASS (klass); widget_class->realize = cc_background_chooser_dialog_realize; g_type_class_add_private (object_class, sizeof (CcBackgroundChooserDialogPrivate)); } GtkWidget * cc_background_chooser_dialog_new (void) { return g_object_new (CC_TYPE_BACKGROUND_CHOOSER_DIALOG, NULL); } CcBackgroundItem * cc_background_chooser_dialog_get_item (CcBackgroundChooserDialog *chooser) { CcBackgroundChooserDialogPrivate *priv = chooser->priv; GtkTreeIter iter; GtkTreeModel *model; GList *list; CcBackgroundItem *item; item = NULL; list = gtk_icon_view_get_selected_items (GTK_ICON_VIEW (priv->icon_view)); if (!list) return NULL; model = gtk_icon_view_get_model (GTK_ICON_VIEW (priv->icon_view)); if (gtk_tree_model_get_iter (model, &iter, (GtkTreePath*) list->data) == FALSE) goto bail; gtk_tree_model_get (model, &iter, 1, &item, -1); bail: g_list_free_full (list, (GDestroyNotify) gtk_tree_path_free); return item; }
406
./cinnamon-control-center/panels/unused/background/cc-background-panel.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include <config.h> #include <string.h> #include <glib.h> #include <glib/gi18n-lib.h> #include <glib/gstdio.h> #include <gdesktop-enums.h> #include "cc-background-panel.h" #include "cc-background-item.h" #include "cc-background-xml.h" #include "cc-background-chooser-dialog.h" #include "bg-pictures-source.h" #define WP_PATH_ID "org.gnome.desktop.background" #define WP_URI_KEY "picture-uri" #define WP_OPTIONS_KEY "picture-options" #define WP_SHADING_KEY "color-shading-type" #define WP_PCOLOR_KEY "primary-color" #define WP_SCOLOR_KEY "secondary-color" CC_PANEL_REGISTER (CcBackgroundPanel, cc_background_panel) #define BACKGROUND_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_BACKGROUND_PANEL, CcBackgroundPanelPrivate)) struct _CcBackgroundPanelPrivate { GtkBuilder *builder; GDBusConnection *connection; GSettings *settings; GnomeDesktopThumbnailFactory *thumb_factory; CcBackgroundItem *current_background; GCancellable *copy_cancellable; GCancellable *capture_cancellable; GtkWidget *spinner; GdkPixbuf *display_screenshot; char *screenshot_path; }; #define WID(y) (GtkWidget *) gtk_builder_get_object (priv->builder, y) static const char * cc_background_panel_get_help_uri (CcPanel *panel) { return "help:cinnamon-help/look-background"; } static void cc_background_panel_dispose (GObject *object) { CcBackgroundPanelPrivate *priv = CC_BACKGROUND_PANEL (object)->priv; g_clear_object (&priv->builder); /* destroying the builder object will also destroy the spinner */ priv->spinner = NULL; g_clear_object (&priv->settings); if (priv->copy_cancellable) { /* cancel any copy operation */ g_cancellable_cancel (priv->copy_cancellable); g_object_unref (priv->copy_cancellable); priv->copy_cancellable = NULL; } if (priv->capture_cancellable) { /* cancel screenshot operations */ g_cancellable_cancel (priv->capture_cancellable); g_object_unref (priv->capture_cancellable); priv->capture_cancellable = NULL; } g_clear_object (&priv->thumb_factory); g_clear_object (&priv->display_screenshot); g_free (priv->screenshot_path); priv->screenshot_path = NULL; g_clear_object (&priv->connection); G_OBJECT_CLASS (cc_background_panel_parent_class)->dispose (object); } static void cc_background_panel_finalize (GObject *object) { CcBackgroundPanelPrivate *priv = CC_BACKGROUND_PANEL (object)->priv; g_clear_object (&priv->current_background); G_OBJECT_CLASS (cc_background_panel_parent_class)->finalize (object); } static void cc_background_panel_class_init (CcBackgroundPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcBackgroundPanelPrivate)); panel_class->get_help_uri = cc_background_panel_get_help_uri; object_class->dispose = cc_background_panel_dispose; object_class->finalize = cc_background_panel_finalize; } static void update_preview (CcBackgroundPanelPrivate *priv, CcBackgroundItem *item) { gboolean changes_with_time; if (item && priv->current_background) { g_object_unref (priv->current_background); priv->current_background = cc_background_item_copy (item); cc_background_item_load (priv->current_background, NULL); } changes_with_time = FALSE; if (priv->current_background) { changes_with_time = cc_background_item_changes_with_time (priv->current_background); } gtk_widget_set_visible (WID ("slide_image"), changes_with_time); gtk_widget_set_visible (WID ("slide-label"), changes_with_time); gtk_widget_queue_draw (WID ("background-desktop-drawingarea")); } static char * get_save_path (void) { return g_build_filename (g_get_user_config_dir (), "cinnamon-control-center", "backgrounds", "last-edited.xml", NULL); } static void update_display_preview (CcBackgroundPanel *panel) { CcBackgroundPanelPrivate *priv = panel->priv; GtkWidget *widget; GtkAllocation allocation; const gint preview_width = 416; const gint preview_height = 248; GdkPixbuf *pixbuf; GIcon *icon; cairo_t *cr; widget = WID ("background-desktop-drawingarea"); gtk_widget_get_allocation (widget, &allocation); if (!priv->current_background) return; icon = cc_background_item_get_frame_thumbnail (priv->current_background, priv->thumb_factory, preview_width, preview_height, -2, TRUE); pixbuf = GDK_PIXBUF (icon); cr = gdk_cairo_create (gtk_widget_get_window (widget)); gdk_cairo_set_source_pixbuf (cr, pixbuf, 0, 0); cairo_paint (cr); g_object_unref (pixbuf); pixbuf = NULL; if (panel->priv->display_screenshot != NULL) pixbuf = gdk_pixbuf_scale_simple (panel->priv->display_screenshot, preview_width, preview_height, GDK_INTERP_BILINEAR); if (pixbuf) { gdk_cairo_set_source_pixbuf (cr, pixbuf, 0, 0); cairo_paint (cr); } cairo_destroy (cr); } static void on_screenshot_finished (GObject *source, GAsyncResult *res, gpointer user_data) { CcBackgroundPanel *panel = user_data; CcBackgroundPanelPrivate *priv = panel->priv; GError *error; GdkRectangle rect; GdkRectangle workarea_rect; GtkWidget *widget; GdkPixbuf *pixbuf; cairo_surface_t *surface; cairo_t *cr; int width; int height; int primary; error = NULL; g_dbus_connection_call_finish (panel->priv->connection, res, &error); if (error != NULL) { if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { g_error_free (error); return; } g_debug ("Unable to get screenshot: %s", error->message); g_error_free (error); /* fallback? */ goto out; } pixbuf = gdk_pixbuf_new_from_file (panel->priv->screenshot_path, &error); if (error != NULL) { g_debug ("Unable to use GNOME Shell's builtin screenshot interface: %s", error->message); g_error_free (error); goto out; } width = gdk_pixbuf_get_width (pixbuf); height = gdk_pixbuf_get_height (pixbuf); surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); cr = cairo_create (surface); gdk_cairo_set_source_pixbuf (cr, pixbuf, 0, 0); cairo_paint (cr); g_object_unref (pixbuf); /* clear the workarea */ widget = WID ("background-desktop-drawingarea"); primary = gdk_screen_get_primary_monitor (gtk_widget_get_screen (widget)); gdk_screen_get_monitor_geometry (gtk_widget_get_screen (widget), primary, &rect); gdk_screen_get_monitor_workarea (gtk_widget_get_screen (widget), primary, &workarea_rect); cairo_save (cr); cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR); cairo_rectangle (cr, workarea_rect.x - rect.x, workarea_rect.y - rect.y, workarea_rect.width, workarea_rect.height); cairo_fill (cr); cairo_restore (cr); g_clear_object (&panel->priv->display_screenshot); panel->priv->display_screenshot = gdk_pixbuf_get_from_surface (surface, 0, 0, width, height); /* remove the temporary file created by the shell */ g_unlink (panel->priv->screenshot_path); g_free (priv->screenshot_path); priv->screenshot_path = NULL; cairo_destroy (cr); cairo_surface_destroy (surface); out: update_display_preview (panel); } static void get_screenshot_async (CcBackgroundPanel *panel, GdkRectangle *rectangle) { gchar *path, *tmpname; const gchar *method_name; GVariant *method_params; g_debug ("Trying to capture rectangle %dx%d (at %d,%d)", rectangle->width, rectangle->height, rectangle->x, rectangle->y); path = g_build_filename (g_get_user_cache_dir (), "cinnamon-control-center", NULL); g_mkdir_with_parents (path, 0700); tmpname = g_strdup_printf ("scr-%d.png", g_random_int ()); g_free (panel->priv->screenshot_path); panel->priv->screenshot_path = g_build_filename (path, tmpname, NULL); g_free (path); g_free (tmpname); method_name = "ScreenshotArea"; method_params = g_variant_new ("(iiiibs)", rectangle->x, rectangle->y, rectangle->width, rectangle->height, FALSE, /* flash */ panel->priv->screenshot_path); g_dbus_connection_call (panel->priv->connection, "org.gnome.Shell", "/org/gnome/Shell", "org.gnome.Shell", method_name, method_params, NULL, G_DBUS_CALL_FLAGS_NONE, -1, panel->priv->capture_cancellable, on_screenshot_finished, panel); } static gboolean on_preview_draw (GtkWidget *widget, cairo_t *cr, CcBackgroundPanel *panel) { /* we have another shot in flight or an existing cache */ if (panel->priv->display_screenshot == NULL && panel->priv->screenshot_path == NULL) { GdkRectangle rect; int primary; primary = gdk_screen_get_primary_monitor (gtk_widget_get_screen (widget)); gdk_screen_get_monitor_geometry (gtk_widget_get_screen (widget), primary, &rect); get_screenshot_async (panel, &rect); } else update_display_preview (panel); return TRUE; } static void reload_current_bg (CcBackgroundPanel *self) { CcBackgroundPanelPrivate *priv; CcBackgroundItem *saved, *configured; gchar *uri, *pcolor, *scolor; priv = self->priv; /* Load the saved configuration */ uri = get_save_path (); saved = cc_background_xml_get_item (uri); g_free (uri); /* initalise the current background information from settings */ uri = g_settings_get_string (priv->settings, WP_URI_KEY); if (uri && *uri == '\0') { g_free (uri); uri = NULL; } else { GFile *file; file = g_file_new_for_commandline_arg (uri); g_object_unref (file); } configured = cc_background_item_new (uri); g_free (uri); pcolor = g_settings_get_string (priv->settings, WP_PCOLOR_KEY); scolor = g_settings_get_string (priv->settings, WP_SCOLOR_KEY); g_object_set (G_OBJECT (configured), "name", _("Current background"), "placement", g_settings_get_enum (priv->settings, WP_OPTIONS_KEY), "shading", g_settings_get_enum (priv->settings, WP_SHADING_KEY), "primary-color", pcolor, "secondary-color", scolor, NULL); g_free (pcolor); g_free (scolor); if (saved != NULL && cc_background_item_compare (saved, configured)) { CcBackgroundItemFlags flags; flags = cc_background_item_get_flags (saved); /* Special case for colours */ if (cc_background_item_get_placement (saved) == G_DESKTOP_BACKGROUND_STYLE_NONE) flags &=~ (CC_BACKGROUND_ITEM_HAS_PCOLOR | CC_BACKGROUND_ITEM_HAS_SCOLOR); g_object_set (G_OBJECT (configured), "name", cc_background_item_get_name (saved), "flags", flags, "source-url", cc_background_item_get_source_url (saved), "source-xml", cc_background_item_get_source_xml (saved), NULL); } if (saved != NULL) g_object_unref (saved); g_clear_object (&priv->current_background); priv->current_background = configured; cc_background_item_load (priv->current_background, NULL); } static gboolean create_save_dir (void) { char *path; path = g_build_filename (g_get_user_config_dir (), "cinnamon-control-center", "backgrounds", NULL); if (g_mkdir_with_parents (path, 0755) < 0) { g_warning ("Failed to create directory '%s'", path); g_free (path); return FALSE; } g_free (path); return TRUE; } static void copy_finished_cb (GObject *source_object, GAsyncResult *result, gpointer pointer) { GError *err = NULL; CcBackgroundPanel *panel = (CcBackgroundPanel *) pointer; CcBackgroundPanelPrivate *priv = panel->priv; CcBackgroundItem *item; if (!g_file_copy_finish (G_FILE (source_object), result, &err)) { if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { g_error_free (err); return; } g_warning ("Failed to copy image to cache location: %s", err->message); g_error_free (err); } item = g_object_get_data (source_object, "item"); g_settings_apply (priv->settings); /* the panel may have been destroyed before the callback is run, so be sure * to check the widgets are not NULL */ if (priv->spinner) { gtk_widget_destroy (GTK_WIDGET (priv->spinner)); priv->spinner = NULL; } if (priv->current_background) cc_background_item_load (priv->current_background, NULL); if (priv->builder) { char *filename; update_preview (priv, item); /* Save the source XML if there is one */ filename = get_save_path (); if (create_save_dir ()) cc_background_xml_save (priv->current_background, filename); } /* remove the reference taken when the copy was set up */ g_object_unref (panel); } static void set_background (CcBackgroundPanel *panel, CcBackgroundItem *item) { CcBackgroundPanelPrivate *priv = panel->priv; GDesktopBackgroundStyle style; gboolean save_settings = TRUE; const char *uri; CcBackgroundItemFlags flags; char *filename; if (item == NULL) return; uri = cc_background_item_get_uri (item); flags = cc_background_item_get_flags (item); if ((flags & CC_BACKGROUND_ITEM_HAS_URI) && uri == NULL) { g_settings_set_enum (priv->settings, WP_OPTIONS_KEY, G_DESKTOP_BACKGROUND_STYLE_NONE); g_settings_set_string (priv->settings, WP_URI_KEY, ""); } else if (cc_background_item_get_source_url (item) != NULL && cc_background_item_get_needs_download (item)) { GFile *source, *dest; char *cache_path, *basename, *dest_path, *display_name, *dest_uri; GdkPixbuf *pixbuf; cache_path = bg_pictures_source_get_cache_path (); if (g_mkdir_with_parents (cache_path, 0755) < 0) { g_warning ("Failed to create directory '%s'", cache_path); g_free (cache_path); return; } g_free (cache_path); dest_path = bg_pictures_source_get_unique_path (cc_background_item_get_source_url (item)); dest = g_file_new_for_path (dest_path); g_free (dest_path); source = g_file_new_for_uri (cc_background_item_get_source_url (item)); basename = g_file_get_basename (source); display_name = g_filename_display_name (basename); dest_path = g_file_get_path (dest); g_free (basename); /* create a blank image to use until the source image is ready */ pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, 1, 1); gdk_pixbuf_fill (pixbuf, 0x00000000); gdk_pixbuf_save (pixbuf, dest_path, "png", NULL, NULL); g_object_unref (pixbuf); g_free (dest_path); if (priv->copy_cancellable) { g_cancellable_cancel (priv->copy_cancellable); g_cancellable_reset (priv->copy_cancellable); } if (priv->spinner) { gtk_widget_destroy (GTK_WIDGET (priv->spinner)); priv->spinner = NULL; } /* create a spinner while the file downloads */ priv->spinner = gtk_spinner_new (); gtk_spinner_start (GTK_SPINNER (priv->spinner)); gtk_box_pack_start (GTK_BOX (WID ("bottom-hbox")), priv->spinner, FALSE, FALSE, 6); gtk_widget_show (priv->spinner); /* reference the panel in case it is removed before the copy is * finished */ g_object_ref (panel); g_object_set_data_full (G_OBJECT (source), "item", g_object_ref (item), g_object_unref); g_file_copy_async (source, dest, G_FILE_COPY_OVERWRITE, G_PRIORITY_DEFAULT, priv->copy_cancellable, NULL, NULL, copy_finished_cb, panel); g_object_unref (source); dest_uri = g_file_get_uri (dest); g_object_unref (dest); g_settings_set_string (priv->settings, WP_URI_KEY, dest_uri); g_object_set (G_OBJECT (item), "uri", dest_uri, "needs-download", FALSE, "name", display_name, NULL); g_free (display_name); g_free (dest_uri); /* delay the updated drawing of the preview until the copy finishes */ save_settings = FALSE; } else { g_settings_set_string (priv->settings, WP_URI_KEY, uri); } /* Also set the placement if we have a URI and the previous value was none */ if (flags & CC_BACKGROUND_ITEM_HAS_PLACEMENT) { g_settings_set_enum (priv->settings, WP_OPTIONS_KEY, cc_background_item_get_placement (item)); } else if (uri != NULL) { style = g_settings_get_enum (priv->settings, WP_OPTIONS_KEY); if (style == G_DESKTOP_BACKGROUND_STYLE_NONE) g_settings_set_enum (priv->settings, WP_OPTIONS_KEY, cc_background_item_get_placement (item)); } if (flags & CC_BACKGROUND_ITEM_HAS_SHADING) g_settings_set_enum (priv->settings, WP_SHADING_KEY, cc_background_item_get_shading (item)); g_settings_set_string (priv->settings, WP_PCOLOR_KEY, cc_background_item_get_pcolor (item)); g_settings_set_string (priv->settings, WP_SCOLOR_KEY, cc_background_item_get_scolor (item)); /* update the preview information */ if (save_settings != FALSE) { /* Apply all changes */ g_settings_apply (priv->settings); /* Save the source XML if there is one */ filename = get_save_path (); if (create_save_dir ()) cc_background_xml_save (priv->current_background, filename); } } static void on_chooser_dialog_response (GtkDialog *dialog, int response_id, CcBackgroundPanel *self) { if (response_id == GTK_RESPONSE_OK) { CcBackgroundItem *item; item = cc_background_chooser_dialog_get_item (CC_BACKGROUND_CHOOSER_DIALOG (dialog)); if (item != NULL) { set_background (self, item); g_object_unref (item); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } static void on_background_button_clicked (GtkButton *button, CcBackgroundPanel *self) { CcBackgroundPanelPrivate *priv = self->priv; GtkWidget *dialog; dialog = cc_background_chooser_dialog_new (); gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (gtk_widget_get_toplevel (WID ("background-panel")))); gtk_widget_show (dialog); g_signal_connect (dialog, "response", G_CALLBACK (on_chooser_dialog_response), self); } static void on_settings_changed (GSettings *settings, gchar *key, CcBackgroundPanel *self) { reload_current_bg (self); update_preview (self->priv, NULL); } static void cc_background_panel_init (CcBackgroundPanel *self) { CcBackgroundPanelPrivate *priv; gchar *objects[] = {"background-panel", NULL }; GError *err = NULL; GtkWidget *widget; priv = self->priv = BACKGROUND_PANEL_PRIVATE (self); priv->builder = gtk_builder_new (); priv->connection = g_application_get_dbus_connection (g_application_get_default ()); gtk_builder_add_objects_from_file (priv->builder, UIDIR"/background.ui", objects, &err); if (err) { g_warning ("Could not load ui: %s", err->message); g_error_free (err); return; } priv->settings = g_settings_new (WP_PATH_ID); g_settings_delay (priv->settings); /* add the top level widget */ widget = WID ("background-panel"); gtk_container_add (GTK_CONTAINER (self), widget); gtk_widget_show_all (GTK_WIDGET (self)); /* setup preview area */ widget = WID ("background-desktop-drawingarea"); g_signal_connect (widget, "draw", G_CALLBACK (on_preview_draw), self); priv->copy_cancellable = g_cancellable_new (); priv->capture_cancellable = g_cancellable_new (); priv->thumb_factory = gnome_desktop_thumbnail_factory_new (GNOME_DESKTOP_THUMBNAIL_SIZE_LARGE); reload_current_bg (self); update_preview (priv, NULL); g_signal_connect (priv->settings, "changed", G_CALLBACK (on_settings_changed), self); widget = WID ("background-set-button"); g_signal_connect (widget, "clicked", G_CALLBACK (on_background_button_clicked), self); } void cc_background_panel_register (GIOModule *module) { cc_background_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_BACKGROUND_PANEL, "background", 0); }
407
./cinnamon-control-center/panels/unused/background/gdesktop-enums-types.c
#include <gdesktop-enums.h> #include "gdesktop-enums-types.h" #include "cc-background-item.h" /* enumerations from "/usr/include/gsettings-desktop-schemas/gdesktop-enums.h" */ GType g_desktop_proxy_mode_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_PROXY_MODE_NONE, "G_DESKTOP_PROXY_MODE_NONE", "none" }, { G_DESKTOP_PROXY_MODE_MANUAL, "G_DESKTOP_PROXY_MODE_MANUAL", "manual" }, { G_DESKTOP_PROXY_MODE_AUTO, "G_DESKTOP_PROXY_MODE_AUTO", "auto" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopProxyMode", values); } return etype; } GType g_desktop_toolbar_style_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_TOOLBAR_STYLE_BOTH, "G_DESKTOP_TOOLBAR_STYLE_BOTH", "both" }, { G_DESKTOP_TOOLBAR_STYLE_BOTH_HORIZ, "G_DESKTOP_TOOLBAR_STYLE_BOTH_HORIZ", "both-horiz" }, { G_DESKTOP_TOOLBAR_STYLE_ICONS, "G_DESKTOP_TOOLBAR_STYLE_ICONS", "icons" }, { G_DESKTOP_TOOLBAR_STYLE_TEXT, "G_DESKTOP_TOOLBAR_STYLE_TEXT", "text" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopToolbarStyle", values); } return etype; } GType g_desktop_toolbar_icon_size_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_TOOLBAR_ICON_SIZE_SMALL, "G_DESKTOP_TOOLBAR_ICON_SIZE_SMALL", "small" }, { G_DESKTOP_TOOLBAR_ICON_SIZE_LARGE, "G_DESKTOP_TOOLBAR_ICON_SIZE_LARGE", "large" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopToolbarIconSize", values); } return etype; } GType g_desktop_background_style_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_BACKGROUND_STYLE_NONE, "G_DESKTOP_BACKGROUND_STYLE_NONE", "none" }, { G_DESKTOP_BACKGROUND_STYLE_WALLPAPER, "G_DESKTOP_BACKGROUND_STYLE_WALLPAPER", "wallpaper" }, { G_DESKTOP_BACKGROUND_STYLE_CENTERED, "G_DESKTOP_BACKGROUND_STYLE_CENTERED", "centered" }, { G_DESKTOP_BACKGROUND_STYLE_SCALED, "G_DESKTOP_BACKGROUND_STYLE_SCALED", "scaled" }, { G_DESKTOP_BACKGROUND_STYLE_STRETCHED, "G_DESKTOP_BACKGROUND_STYLE_STRETCHED", "stretched" }, { G_DESKTOP_BACKGROUND_STYLE_ZOOM, "G_DESKTOP_BACKGROUND_STYLE_ZOOM", "zoom" }, { G_DESKTOP_BACKGROUND_STYLE_SPANNED, "G_DESKTOP_BACKGROUND_STYLE_SPANNED", "spanned" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopBackgroundStyle", values); } return etype; } GType g_desktop_background_shading_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_BACKGROUND_SHADING_SOLID, "G_DESKTOP_BACKGROUND_SHADING_SOLID", "solid" }, { G_DESKTOP_BACKGROUND_SHADING_VERTICAL, "G_DESKTOP_BACKGROUND_SHADING_VERTICAL", "vertical" }, { G_DESKTOP_BACKGROUND_SHADING_HORIZONTAL, "G_DESKTOP_BACKGROUND_SHADING_HORIZONTAL", "horizontal" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopBackgroundShading", values); } return etype; } GType g_desktop_mouse_dwell_mode_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_MOUSE_DWELL_MODE_WINDOW, "G_DESKTOP_MOUSE_DWELL_MODE_WINDOW", "window" }, { G_DESKTOP_MOUSE_DWELL_MODE_GESTURE, "G_DESKTOP_MOUSE_DWELL_MODE_GESTURE", "gesture" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopMouseDwellMode", values); } return etype; } GType g_desktop_mouse_dwell_direction_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_MOUSE_DWELL_DIRECTION_LEFT, "G_DESKTOP_MOUSE_DWELL_DIRECTION_LEFT", "left" }, { G_DESKTOP_MOUSE_DWELL_DIRECTION_RIGHT, "G_DESKTOP_MOUSE_DWELL_DIRECTION_RIGHT", "right" }, { G_DESKTOP_MOUSE_DWELL_DIRECTION_UP, "G_DESKTOP_MOUSE_DWELL_DIRECTION_UP", "up" }, { G_DESKTOP_MOUSE_DWELL_DIRECTION_DOWN, "G_DESKTOP_MOUSE_DWELL_DIRECTION_DOWN", "down" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopMouseDwellDirection", values); } return etype; } GType g_desktop_clock_format_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_CLOCK_FORMAT_24H, "G_DESKTOP_CLOCK_FORMAT_24H", "24h" }, { G_DESKTOP_CLOCK_FORMAT_12H, "G_DESKTOP_CLOCK_FORMAT_12H", "12h" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopClockFormat", values); } return etype; } GType g_desktop_screensaver_mode_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_SCREENSAVER_MODE_BLANK_ONLY, "G_DESKTOP_SCREENSAVER_MODE_BLANK_ONLY", "blank-only" }, { G_DESKTOP_SCREENSAVER_MODE_RANDOM, "G_DESKTOP_SCREENSAVER_MODE_RANDOM", "random" }, { G_DESKTOP_SCREENSAVER_MODE_SINGLE, "G_DESKTOP_SCREENSAVER_MODE_SINGLE", "single" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopScreensaverMode", values); } return etype; } GType g_desktop_magnifier_mouse_tracking_mode_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_NONE, "G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_NONE", "none" }, { G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_CENTERED, "G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_CENTERED", "centered" }, { G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_PROPORTIONAL, "G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_PROPORTIONAL", "proportional" }, { G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_PUSH, "G_DESKTOP_MAGNIFIER_MOUSE_TRACKING_MODE_PUSH", "push" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopMagnifierMouseTrackingMode", values); } return etype; } GType g_desktop_magnifier_screen_position_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_MAGNIFIER_SCREEN_POSITION_NONE, "G_DESKTOP_MAGNIFIER_SCREEN_POSITION_NONE", "none" }, { G_DESKTOP_MAGNIFIER_SCREEN_POSITION_FULL_SCREEN, "G_DESKTOP_MAGNIFIER_SCREEN_POSITION_FULL_SCREEN", "full-screen" }, { G_DESKTOP_MAGNIFIER_SCREEN_POSITION_TOP_HALF, "G_DESKTOP_MAGNIFIER_SCREEN_POSITION_TOP_HALF", "top-half" }, { G_DESKTOP_MAGNIFIER_SCREEN_POSITION_BOTTOM_HALF, "G_DESKTOP_MAGNIFIER_SCREEN_POSITION_BOTTOM_HALF", "bottom-half" }, { G_DESKTOP_MAGNIFIER_SCREEN_POSITION_LEFT_HALF, "G_DESKTOP_MAGNIFIER_SCREEN_POSITION_LEFT_HALF", "left-half" }, { G_DESKTOP_MAGNIFIER_SCREEN_POSITION_RIGHT_HALF, "G_DESKTOP_MAGNIFIER_SCREEN_POSITION_RIGHT_HALF", "right-half" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopMagnifierScreenPosition", values); } return etype; } GType g_desktop_titlebar_action_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_TITLEBAR_ACTION_TOGGLE_SHADE, "G_DESKTOP_TITLEBAR_ACTION_TOGGLE_SHADE", "toggle-shade" }, { G_DESKTOP_TITLEBAR_ACTION_TOGGLE_MAXIMIZE, "G_DESKTOP_TITLEBAR_ACTION_TOGGLE_MAXIMIZE", "toggle-maximize" }, { G_DESKTOP_TITLEBAR_ACTION_TOGGLE_MAXIMIZE_HORIZONTALLY, "G_DESKTOP_TITLEBAR_ACTION_TOGGLE_MAXIMIZE_HORIZONTALLY", "toggle-maximize-horizontally" }, { G_DESKTOP_TITLEBAR_ACTION_TOGGLE_MAXIMIZE_VERTICALLY, "G_DESKTOP_TITLEBAR_ACTION_TOGGLE_MAXIMIZE_VERTICALLY", "toggle-maximize-vertically" }, { G_DESKTOP_TITLEBAR_ACTION_MINIMIZE, "G_DESKTOP_TITLEBAR_ACTION_MINIMIZE", "minimize" }, { G_DESKTOP_TITLEBAR_ACTION_NONE, "G_DESKTOP_TITLEBAR_ACTION_NONE", "none" }, { G_DESKTOP_TITLEBAR_ACTION_LOWER, "G_DESKTOP_TITLEBAR_ACTION_LOWER", "lower" }, { G_DESKTOP_TITLEBAR_ACTION_MENU, "G_DESKTOP_TITLEBAR_ACTION_MENU", "menu" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopTitlebarAction", values); } return etype; } GType g_desktop_focus_mode_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_FOCUS_MODE_CLICK, "G_DESKTOP_FOCUS_MODE_CLICK", "click" }, { G_DESKTOP_FOCUS_MODE_SLOPPY, "G_DESKTOP_FOCUS_MODE_SLOPPY", "sloppy" }, { G_DESKTOP_FOCUS_MODE_MOUSE, "G_DESKTOP_FOCUS_MODE_MOUSE", "mouse" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopFocusMode", values); } return etype; } GType g_desktop_focus_new_windows_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_FOCUS_NEW_WINDOWS_SMART, "G_DESKTOP_FOCUS_NEW_WINDOWS_SMART", "smart" }, { G_DESKTOP_FOCUS_NEW_WINDOWS_STRICT, "G_DESKTOP_FOCUS_NEW_WINDOWS_STRICT", "strict" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopFocusNewWindows", values); } return etype; } GType g_desktop_visual_bell_type_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { { G_DESKTOP_VISUAL_BELL_FULLSCREEN_FLASH, "G_DESKTOP_VISUAL_BELL_FULLSCREEN_FLASH", "fullscreen-flash" }, { G_DESKTOP_VISUAL_BELL_FRAME_FLASH, "G_DESKTOP_VISUAL_BELL_FRAME_FLASH", "frame-flash" }, { 0, NULL, NULL } }; etype = g_enum_register_static ("GDesktopVisualBellType", values); } return etype; } /* enumerations from "cc-background-item.h" */ GType cc_background_item_flags_get_type (void) { static GType etype = 0; if (etype == 0) { static const GFlagsValue values[] = { { CC_BACKGROUND_ITEM_HAS_SHADING, "CC_BACKGROUND_ITEM_HAS_SHADING", "shading" }, { CC_BACKGROUND_ITEM_HAS_PLACEMENT, "CC_BACKGROUND_ITEM_HAS_PLACEMENT", "placement" }, { CC_BACKGROUND_ITEM_HAS_PCOLOR, "CC_BACKGROUND_ITEM_HAS_PCOLOR", "pcolor" }, { CC_BACKGROUND_ITEM_HAS_SCOLOR, "CC_BACKGROUND_ITEM_HAS_SCOLOR", "scolor" }, { CC_BACKGROUND_ITEM_HAS_URI, "CC_BACKGROUND_ITEM_HAS_URI", "uri" }, { 0, NULL, NULL } }; etype = g_flags_register_static ("CcBackgroundItemFlags", values); } return etype; }
408
./cinnamon-control-center/panels/unused/background/bg-pictures-source.c
/* bg-pictures-source.c */ /* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include "bg-pictures-source.h" #include "cc-background-item.h" #include <string.h> #include <gio/gio.h> #include <libgnome-desktop/gnome-desktop-thumbnail.h> #include <gdesktop-enums.h> G_DEFINE_TYPE (BgPicturesSource, bg_pictures_source, BG_TYPE_SOURCE) #define PICTURES_SOURCE_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), BG_TYPE_PICTURES_SOURCE, BgPicturesSourcePrivate)) #define ATTRIBUTES G_FILE_ATTRIBUTE_STANDARD_NAME "," \ G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE struct _BgPicturesSourcePrivate { GCancellable *cancellable; GnomeDesktopThumbnailFactory *thumb_factory; GHashTable *known_items; }; const char * const content_types[] = { "image/png", "image/jpeg", "image/bmp", "image/svg+xml", NULL }; static char *bg_pictures_source_get_unique_filename (const char *uri); static void bg_pictures_source_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void bg_pictures_source_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void bg_pictures_source_dispose (GObject *object) { BgPicturesSourcePrivate *priv = BG_PICTURES_SOURCE (object)->priv; if (priv->cancellable) { g_cancellable_cancel (priv->cancellable); g_object_unref (priv->cancellable); priv->cancellable = NULL; } if (priv->thumb_factory) { g_object_unref (priv->thumb_factory); priv->thumb_factory = NULL; } G_OBJECT_CLASS (bg_pictures_source_parent_class)->dispose (object); } static void bg_pictures_source_finalize (GObject *object) { BgPicturesSource *bg_source = BG_PICTURES_SOURCE (object); if (bg_source->priv->thumb_factory) { g_object_unref (bg_source->priv->thumb_factory); bg_source->priv->thumb_factory = NULL; } if (bg_source->priv->known_items) { g_hash_table_destroy (bg_source->priv->known_items); bg_source->priv->known_items = NULL; } G_OBJECT_CLASS (bg_pictures_source_parent_class)->finalize (object); } static void bg_pictures_source_class_init (BgPicturesSourceClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (BgPicturesSourcePrivate)); object_class->get_property = bg_pictures_source_get_property; object_class->set_property = bg_pictures_source_set_property; object_class->dispose = bg_pictures_source_dispose; object_class->finalize = bg_pictures_source_finalize; } static int sort_func (GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, BgPicturesSource *bg_source) { CcBackgroundItem *item_a; CcBackgroundItem *item_b; const char *name_a; const char *name_b; int retval; gtk_tree_model_get (model, a, 1, &item_a, -1); gtk_tree_model_get (model, b, 1, &item_b, -1); name_a = cc_background_item_get_name (item_a); name_b = cc_background_item_get_name (item_b); retval = g_utf8_collate (name_a, name_b); g_object_unref (item_a); g_object_unref (item_b); return retval; } static void picture_scaled (GObject *source_object, GAsyncResult *res, gpointer user_data) { BgPicturesSource *bg_source; CcBackgroundItem *item; GError *error = NULL; GdkPixbuf *pixbuf; const char *source_url; const char *software; GtkTreeIter iter; GtkListStore *store; pixbuf = gdk_pixbuf_new_from_stream_finish (res, &error); if (pixbuf == NULL) { if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning ("Failed to load image: %s", error->message); g_error_free (error); return; } /* since we were not cancelled, we can now cast user_data * back to BgPicturesSource. */ bg_source = BG_PICTURES_SOURCE (user_data); store = bg_source_get_liststore (BG_SOURCE (bg_source)); item = g_object_get_data (source_object, "item"); gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (store), 1, (GtkTreeIterCompareFunc)sort_func, bg_source, NULL); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (store), 1, GTK_SORT_ASCENDING); /* Ignore screenshots */ software = gdk_pixbuf_get_option (pixbuf, "tEXt::Software"); if (software != NULL && g_str_equal (software, "gnome-screenshot")) { g_debug ("Ignored URL '%s' as it's a screenshot from gnome-screenshot", cc_background_item_get_uri (item)); g_object_unref (pixbuf); g_object_unref (item); return; } cc_background_item_load (item, NULL); /* insert the item into the liststore */ gtk_list_store_insert_with_values (store, &iter, 0, 0, pixbuf, 1, item, -1); source_url = cc_background_item_get_source_url (item); if (source_url != NULL) { g_hash_table_insert (bg_source->priv->known_items, bg_pictures_source_get_unique_filename (source_url), GINT_TO_POINTER (TRUE)); } else { char *cache_path; GFile *file, *parent, *dir; cache_path = bg_pictures_source_get_cache_path (); dir = g_file_new_for_path (cache_path); g_free (cache_path); file = g_file_new_for_uri (cc_background_item_get_uri (item)); parent = g_file_get_parent (file); if (g_file_equal (parent, dir)) { char *basename; basename = g_file_get_basename (file); g_hash_table_insert (bg_source->priv->known_items, basename, GINT_TO_POINTER (TRUE)); } g_object_unref (file); g_object_unref (parent); } g_object_unref (pixbuf); } static void picture_opened_for_read (GObject *source_object, GAsyncResult *res, gpointer user_data) { BgPicturesSource *bg_source; CcBackgroundItem *item; GFileInputStream *stream; GError *error = NULL; item = g_object_get_data (source_object, "item"); stream = g_file_read_finish (G_FILE (source_object), res, &error); if (stream == NULL) { if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { char *filename = g_file_get_path (G_FILE (source_object)); g_warning ("Failed to load picture '%s': %s", filename, error->message); g_free (filename); } g_error_free (error); g_object_unref (item); return; } /* since we were not cancelled, we can now cast user_data * back to BgPicturesSource. */ bg_source = BG_PICTURES_SOURCE (user_data); g_object_set_data (G_OBJECT (stream), "item", item); gdk_pixbuf_new_from_stream_at_scale_async (G_INPUT_STREAM (stream), THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, TRUE, bg_source->priv->cancellable, picture_scaled, bg_source); g_object_unref (stream); } static gboolean in_content_types (const char *content_type) { guint i; for (i = 0; content_types[i]; i++) if (g_str_equal (content_types[i], content_type)) return TRUE; return FALSE; } static gboolean add_single_file (BgPicturesSource *bg_source, GFile *file, GFileInfo *info, const char *source_uri) { const gchar *content_type; CcBackgroundItem *item; char *uri; /* find png and jpeg files */ content_type = g_file_info_get_content_type (info); if (!content_type) return FALSE; if (!in_content_types (content_type)) return FALSE; /* create a new CcBackgroundItem */ uri = g_file_get_uri (file); item = cc_background_item_new (uri); g_free (uri); g_object_set (G_OBJECT (item), "flags", CC_BACKGROUND_ITEM_HAS_URI | CC_BACKGROUND_ITEM_HAS_SHADING, "shading", G_DESKTOP_BACKGROUND_SHADING_SOLID, "placement", G_DESKTOP_BACKGROUND_STYLE_ZOOM, NULL); if (source_uri != NULL && !g_file_is_native (file)) g_object_set (G_OBJECT (item), "source-url", source_uri, NULL); g_object_set_data (G_OBJECT (file), "item", item); g_file_read_async (file, G_PRIORITY_DEFAULT, bg_source->priv->cancellable, picture_opened_for_read, bg_source); g_object_unref (file); return TRUE; } gboolean bg_pictures_source_add (BgPicturesSource *bg_source, const char *uri) { GFile *file; GFileInfo *info; gboolean retval; file = g_file_new_for_uri (uri); info = g_file_query_info (file, ATTRIBUTES, G_FILE_QUERY_INFO_NONE, NULL, NULL); if (info == NULL) return FALSE; retval = add_single_file (bg_source, file, info, uri); return retval; } gboolean bg_pictures_source_remove (BgPicturesSource *bg_source, CcBackgroundItem *item) { GtkTreeModel *model; GtkTreeIter iter; gboolean cont; const char *uri; gboolean retval; retval = FALSE; model = GTK_TREE_MODEL (bg_source_get_liststore (BG_SOURCE (bg_source))); uri = cc_background_item_get_uri (item); cont = gtk_tree_model_get_iter_first (model, &iter); while (cont) { CcBackgroundItem *tmp_item; const char *tmp_uri; gtk_tree_model_get (model, &iter, 1, &tmp_item, -1); tmp_uri = cc_background_item_get_uri (tmp_item); if (g_str_equal (tmp_uri, uri)) { GFile *file; char *uuid; file = g_file_new_for_uri (uri); uuid = g_file_get_basename (file); g_hash_table_insert (bg_source->priv->known_items, uuid, NULL); gtk_list_store_remove (GTK_LIST_STORE (model), &iter); retval = TRUE; g_file_trash (file, NULL, NULL); g_object_unref (file); break; } g_object_unref (tmp_item); cont = gtk_tree_model_iter_next (model, &iter); } return retval; } static void file_info_async_ready (GObject *source, GAsyncResult *res, gpointer user_data) { BgPicturesSource *bg_source = BG_PICTURES_SOURCE (user_data); GList *files, *l; GError *err = NULL; GFile *parent; files = g_file_enumerator_next_files_finish (G_FILE_ENUMERATOR (source), res, &err); if (err) { g_warning ("Could not get pictures file information: %s", err->message); g_error_free (err); g_list_foreach (files, (GFunc) g_object_unref, NULL); g_list_free (files); return; } parent = g_file_enumerator_get_container (G_FILE_ENUMERATOR (source)); /* iterate over the available files */ for (l = files; l; l = g_list_next (l)) { GFileInfo *info = l->data; GFile *file; file = g_file_get_child (parent, g_file_info_get_name (info)); add_single_file (bg_source, file, info, NULL); } g_list_foreach (files, (GFunc) g_object_unref, NULL); g_list_free (files); } static void dir_enum_async_ready (GObject *source, GAsyncResult *res, gpointer user_data) { BgPicturesSourcePrivate *priv = BG_PICTURES_SOURCE (user_data)->priv; GFileEnumerator *enumerator; GError *err = NULL; enumerator = g_file_enumerate_children_finish (G_FILE (source), res, &err); if (err) { if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_NOT_FOUND) == FALSE) g_warning ("Could not fill pictures source: %s", err->message); g_error_free (err); return; } /* get the files */ g_file_enumerator_next_files_async (enumerator, G_MAXINT, G_PRIORITY_LOW, priv->cancellable, file_info_async_ready, user_data); } char * bg_pictures_source_get_cache_path (void) { return g_build_filename (g_get_user_cache_dir (), "cinnamon-control-center", "backgrounds", NULL); } static char * bg_pictures_source_get_unique_filename (const char *uri) { GChecksum *csum; char *ret; csum = g_checksum_new (G_CHECKSUM_SHA256); g_checksum_update (csum, (guchar *) uri, -1); ret = g_strdup (g_checksum_get_string (csum)); g_checksum_free (csum); return ret; } char * bg_pictures_source_get_unique_path (const char *uri) { GFile *parent, *file; char *cache_path; char *filename; char *ret; cache_path = bg_pictures_source_get_cache_path (); parent = g_file_new_for_path (cache_path); g_free (cache_path); filename = bg_pictures_source_get_unique_filename (uri); file = g_file_get_child (parent, filename); g_free (filename); ret = g_file_get_path (file); g_object_unref (file); return ret; } gboolean bg_pictures_source_is_known (BgPicturesSource *bg_source, const char *uri) { gboolean retval; char *uuid; uuid = bg_pictures_source_get_unique_filename (uri); retval = (GPOINTER_TO_INT (g_hash_table_lookup (bg_source->priv->known_items, uuid))); g_free (uuid); return retval; } static void bg_pictures_source_init (BgPicturesSource *self) { const gchar *pictures_path; BgPicturesSourcePrivate *priv; GFile *dir; char *cache_path; priv = self->priv = PICTURES_SOURCE_PRIVATE (self); priv->cancellable = g_cancellable_new (); priv->known_items = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, NULL); pictures_path = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES); dir = g_file_new_for_path (pictures_path); g_file_enumerate_children_async (dir, ATTRIBUTES, G_FILE_QUERY_INFO_NONE, G_PRIORITY_LOW, priv->cancellable, dir_enum_async_ready, self); g_object_unref (dir); cache_path = bg_pictures_source_get_cache_path (); dir = g_file_new_for_path (cache_path); g_file_enumerate_children_async (dir, ATTRIBUTES, G_FILE_QUERY_INFO_NONE, G_PRIORITY_LOW, priv->cancellable, dir_enum_async_ready, self); g_object_unref (dir); priv->thumb_factory = gnome_desktop_thumbnail_factory_new (GNOME_DESKTOP_THUMBNAIL_SIZE_LARGE); } BgPicturesSource * bg_pictures_source_new (void) { return g_object_new (BG_TYPE_PICTURES_SOURCE, NULL); } const char * const * bg_pictures_get_support_content_types (void) { return content_types; }
409
./cinnamon-control-center/panels/unused/background/bg-flickr-source.c
/* bg-flickr-source.c */ /* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include "bg-flickr-source.h" #include <libsocialweb-client/sw-client.h> #include <libsocialweb-client/sw-item.h> #include <libsocialweb-client/sw-client-service.h> #include "cc-background-item.h" #include <gdesktop-enums.h> G_DEFINE_TYPE (BgFlickrSource, bg_flickr_source, BG_TYPE_SOURCE) #define FLICKR_SOURCE_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), BG_TYPE_FLICKR_SOURCE, BgFlickrSourcePrivate)) struct _BgFlickrSourcePrivate { SwClient *client; SwClientService *service; }; static void bg_flickr_source_dispose (GObject *object) { BgFlickrSourcePrivate *priv = BG_FLICKR_SOURCE (object)->priv; if (priv->client) { g_object_unref (priv->client); priv->client = NULL; } if (priv->service) { g_object_unref (priv->service); priv->service = NULL; } G_OBJECT_CLASS (bg_flickr_source_parent_class)->dispose (object); } static void bg_flickr_source_finalize (GObject *object) { G_OBJECT_CLASS (bg_flickr_source_parent_class)->finalize (object); } static void bg_flickr_source_class_init (BgFlickrSourceClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (BgFlickrSourcePrivate)); object_class->dispose = bg_flickr_source_dispose; object_class->finalize = bg_flickr_source_finalize; } static void _view_items_added_cb (SwClientItemView *item_view, GList *items, gpointer userdata) { GList *l; BgFlickrSource *source = (BgFlickrSource *) userdata; GtkListStore *store = bg_source_get_liststore (BG_SOURCE (source)); for (l = items; l; l = l->next) { CcBackgroundItem *item; GdkPixbuf *pixbuf; SwItem *sw_item = (SwItem *) l->data; const gchar *thumb_url; item = cc_background_item_new (NULL); g_object_set (G_OBJECT (item), "placement", G_DESKTOP_BACKGROUND_STYLE_ZOOM, "name", sw_item_get_value (sw_item, "title"), "primary-color", "#000000000000", "seconday-color", "#000000000000", "shading", G_DESKTOP_BACKGROUND_SHADING_SOLID, "source-url", sw_item_get_value (sw_item, "x-flickr-photo-url"), NULL); //FIXME // cc_background_item_ensure_gnome_bg (item); /* insert the item into the liststore */ thumb_url = sw_item_get_value (sw_item, "thumbnail"); pixbuf = gdk_pixbuf_new_from_file_at_scale (thumb_url, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, TRUE, NULL); gtk_list_store_insert_with_values (store, NULL, 0, 0, pixbuf, 1, item, -1); g_object_unref (pixbuf); } } static void _query_open_view_cb (SwClientService *service, SwClientItemView *item_view, gpointer userdata) { if (!item_view) { g_warning ("Could not connect to Flickr service"); return; } g_signal_connect (item_view, "items-added", (GCallback)_view_items_added_cb, userdata); sw_client_item_view_start (item_view); } static void bg_flickr_source_init (BgFlickrSource *self) { GnomeDesktopThumbnailFactory *thumb_factory; BgFlickrSourcePrivate *priv; priv = self->priv = FLICKR_SOURCE_PRIVATE (self); priv->client = sw_client_new (); priv->service = sw_client_get_service (priv->client, "flickr"); sw_client_service_query_open_view (priv->service, "feed", NULL, _query_open_view_cb, self); thumb_factory = gnome_desktop_thumbnail_factory_new (GNOME_DESKTOP_THUMBNAIL_SIZE_LARGE); g_object_unref (thumb_factory); } BgFlickrSource * bg_flickr_source_new (void) { return g_object_new (BG_TYPE_FLICKR_SOURCE, NULL); }
410
./cinnamon-control-center/panels/unused/background/bg-source.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include "bg-source.h" #include "cc-background-item.h" G_DEFINE_ABSTRACT_TYPE (BgSource, bg_source, G_TYPE_OBJECT) #define SOURCE_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), BG_TYPE_SOURCE, BgSourcePrivate)) struct _BgSourcePrivate { GtkListStore *store; }; enum { PROP_LISTSTORE = 1 }; static void bg_source_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { BgSource *source = BG_SOURCE (object); switch (property_id) { case PROP_LISTSTORE: g_value_set_object (value, bg_source_get_liststore (source)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void bg_source_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void bg_source_dispose (GObject *object) { BgSourcePrivate *priv = BG_SOURCE (object)->priv; if (priv->store) { g_object_unref (priv->store); priv->store = NULL; } G_OBJECT_CLASS (bg_source_parent_class)->dispose (object); } static void bg_source_finalize (GObject *object) { G_OBJECT_CLASS (bg_source_parent_class)->finalize (object); } static void bg_source_class_init (BgSourceClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (BgSourcePrivate)); object_class->get_property = bg_source_get_property; object_class->set_property = bg_source_set_property; object_class->dispose = bg_source_dispose; object_class->finalize = bg_source_finalize; pspec = g_param_spec_object ("liststore", "Liststore", "Liststore used in the source", GTK_TYPE_LIST_STORE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_LISTSTORE, pspec); } static void bg_source_init (BgSource *self) { BgSourcePrivate *priv; priv = self->priv = SOURCE_PRIVATE (self); priv->store = gtk_list_store_new (3, G_TYPE_ICON, G_TYPE_OBJECT, G_TYPE_STRING); } GtkListStore* bg_source_get_liststore (BgSource *source) { g_return_val_if_fail (BG_IS_SOURCE (source), NULL); return source->priv->store; }
411
./cinnamon-control-center/panels/unused/background/cc-background-xml.c
/* * Authors: Rodney Dawes <dobey@ximian.com> * Bastien Nocera <hadess@hadess.net> * * Copyright 2003-2006 Novell, Inc. (www.novell.com) * Copyright 2011 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA. * */ #include <gio/gio.h> #include <string.h> #include <libxml/parser.h> #include <libgnome-desktop/gnome-bg.h> #include <gdesktop-enums.h> #include "gdesktop-enums-types.h" #include "cc-background-item.h" #include "cc-background-xml.h" /* The number of items we signal as "added" before * returning to the main loop */ #define NUM_ITEMS_PER_BATCH 1 struct CcBackgroundXmlPrivate { GHashTable *wp_hash; GAsyncQueue *item_added_queue; guint item_added_id; }; #define CC_BACKGROUND_XML_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_BACKGROUND_XML, CcBackgroundXmlPrivate)) enum { ADDED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; static void cc_background_xml_class_init (CcBackgroundXmlClass *klass); static void cc_background_xml_init (CcBackgroundXml *background_item); static void cc_background_xml_finalize (GObject *object); G_DEFINE_TYPE (CcBackgroundXml, cc_background_xml, G_TYPE_OBJECT) static gboolean cc_background_xml_get_bool (const xmlNode *parent, const gchar *prop_name) { xmlChar * prop; gboolean ret_val = FALSE; g_return_val_if_fail (parent != NULL, FALSE); g_return_val_if_fail (prop_name != NULL, FALSE); prop = xmlGetProp ((xmlNode *) parent, (xmlChar*)prop_name); if (prop != NULL) { if (!g_ascii_strcasecmp ((gchar *)prop, "true") || !g_ascii_strcasecmp ((gchar *)prop, "1")) { ret_val = TRUE; } else { ret_val = FALSE; } g_free (prop); } return ret_val; } static struct { int value; const char *string; } lookups[] = { { G_DESKTOP_BACKGROUND_SHADING_HORIZONTAL, "horizontal-gradient" }, { G_DESKTOP_BACKGROUND_SHADING_VERTICAL, "vertical-gradient" }, }; static int enum_string_to_value (GType type, const char *string) { GEnumClass *eclass; GEnumValue *value; eclass = G_ENUM_CLASS (g_type_class_peek (type)); value = g_enum_get_value_by_nick (eclass, string); /* Here's a bit of hand-made parsing, bad bad */ if (value == NULL) { guint i; for (i = 0; i < G_N_ELEMENTS (lookups); i++) { if (g_str_equal (lookups[i].string, string)) return lookups[i].value; } g_warning ("Unhandled value '%s' for enum '%s'", string, G_FLAGS_CLASS_TYPE_NAME (eclass)); return 0; } return value->value; } static gboolean idle_emit (CcBackgroundXml *xml) { GObject *item; guint i = NUM_ITEMS_PER_BATCH; g_async_queue_lock (xml->priv->item_added_queue); while (i > 0 && (item = g_async_queue_try_pop_unlocked (xml->priv->item_added_queue)) != NULL) { g_signal_emit (G_OBJECT (xml), signals[ADDED], 0, item); g_object_unref (item); i--; } g_async_queue_unlock (xml->priv->item_added_queue); if (g_async_queue_length (xml->priv->item_added_queue) > 0) { return TRUE; } else { xml->priv->item_added_id = 0; return FALSE; } } static void emit_added_in_idle (CcBackgroundXml *xml, GObject *object) { g_async_queue_lock (xml->priv->item_added_queue); g_async_queue_push_unlocked (xml->priv->item_added_queue, object); if (xml->priv->item_added_id == 0) xml->priv->item_added_id = g_idle_add ((GSourceFunc) idle_emit, xml); g_async_queue_unlock (xml->priv->item_added_queue); } #define NONE "(none)" #define UNSET_FLAG(flag) G_STMT_START{ (flags&=~(flag)); }G_STMT_END #define SET_FLAG(flag) G_STMT_START{ (flags|=flag); }G_STMT_END static gboolean cc_background_xml_load_xml_internal (CcBackgroundXml *xml, const gchar *filename, gboolean in_thread) { xmlDoc * wplist; xmlNode * root, * list, * wpa; xmlChar * nodelang; const gchar * const * syslangs; gint i; gboolean retval; wplist = xmlParseFile (filename); retval = FALSE; if (!wplist) return retval; syslangs = g_get_language_names (); root = xmlDocGetRootElement (wplist); for (list = root->children; list != NULL; list = list->next) { if (!strcmp ((gchar *)list->name, "wallpaper")) { CcBackgroundItem * item; CcBackgroundItemFlags flags; char *uri, *cname, *id; flags = 0; cname = NULL; item = cc_background_item_new (NULL); g_object_set (G_OBJECT (item), "is-deleted", cc_background_xml_get_bool (list, "deleted"), "source-xml", filename, NULL); for (wpa = list->children; wpa != NULL; wpa = wpa->next) { if (wpa->type == XML_COMMENT_NODE) { continue; } else if (!strcmp ((gchar *)wpa->name, "filename")) { if (wpa->last != NULL && wpa->last->content != NULL) { gchar *content = g_strstrip ((gchar *)wpa->last->content); char *bg_uri; /* FIXME same rubbish as in other parts of the code */ if (strcmp (content, NONE) == 0) { bg_uri = NULL; } else { GFile *file; file = g_file_new_for_commandline_arg (content); bg_uri = g_file_get_uri (file); g_object_unref (file); } SET_FLAG(CC_BACKGROUND_ITEM_HAS_URI); g_object_set (G_OBJECT (item), "uri", bg_uri, NULL); g_free (bg_uri); } else { break; } } else if (!strcmp ((gchar *)wpa->name, "name")) { if (wpa->last != NULL && wpa->last->content != NULL) { char *name; nodelang = xmlNodeGetLang (wpa->last); g_object_get (G_OBJECT (item), "name", &name, NULL); if (name == NULL && nodelang == NULL) { g_free (cname); cname = g_strdup (g_strstrip ((gchar *)wpa->last->content)); g_object_set (G_OBJECT (item), "name", cname, NULL); } else { for (i = 0; syslangs[i] != NULL; i++) { if (!strcmp (syslangs[i], (gchar *)nodelang)) { g_object_set (G_OBJECT (item), "name", g_strstrip ((gchar *)wpa->last->content), NULL); break; } } } g_free (name); xmlFree (nodelang); } else { break; } } else if (!strcmp ((gchar *)wpa->name, "options")) { if (wpa->last != NULL) { g_object_set (G_OBJECT (item), "placement", enum_string_to_value (G_DESKTOP_TYPE_DESKTOP_BACKGROUND_STYLE, g_strstrip ((gchar *)wpa->last->content)), NULL); SET_FLAG(CC_BACKGROUND_ITEM_HAS_PLACEMENT); } } else if (!strcmp ((gchar *)wpa->name, "shade_type")) { if (wpa->last != NULL) { g_object_set (G_OBJECT (item), "shading", enum_string_to_value (G_DESKTOP_TYPE_DESKTOP_BACKGROUND_SHADING, g_strstrip ((gchar *)wpa->last->content)), NULL); SET_FLAG(CC_BACKGROUND_ITEM_HAS_SHADING); } } else if (!strcmp ((gchar *)wpa->name, "pcolor")) { if (wpa->last != NULL) { g_object_set (G_OBJECT (item), "primary-color", g_strstrip ((gchar *)wpa->last->content), NULL); SET_FLAG(CC_BACKGROUND_ITEM_HAS_PCOLOR); } } else if (!strcmp ((gchar *)wpa->name, "scolor")) { if (wpa->last != NULL) { g_object_set (G_OBJECT (item), "secondary-color", g_strstrip ((gchar *)wpa->last->content), NULL); SET_FLAG(CC_BACKGROUND_ITEM_HAS_SCOLOR); } } else if (!strcmp ((gchar *)wpa->name, "source_url")) { if (wpa->last != NULL) { g_object_set (G_OBJECT (item), "source-url", g_strstrip ((gchar *)wpa->last->content), "needs-download", FALSE, NULL); } } else if (!strcmp ((gchar *)wpa->name, "text")) { /* Do nothing here, libxml2 is being weird */ } else { g_warning ("Unknown Tag: %s", wpa->name); } } /* Check whether the target file exists */ { GFile *file; const char *uri; uri = cc_background_item_get_uri (item); if (uri != NULL) { file = g_file_new_for_uri (uri); if (g_file_query_exists (file, NULL) == FALSE) { g_object_unref (item); continue; } } } /* FIXME, this is a broken way of doing, * need to use proper code here */ uri = g_filename_to_uri (filename, NULL, NULL); id = g_strdup_printf ("%s#%s", uri, cname); g_free (uri); /* Make sure we don't already have this one and that filename exists */ if (g_hash_table_lookup (xml->priv->wp_hash, id) != NULL) { g_object_unref (item); g_free (id); continue; } g_object_set (G_OBJECT (item), "flags", flags, NULL); g_hash_table_insert (xml->priv->wp_hash, id, item); /* Don't free ID, we added it to the hash table */ if (in_thread) emit_added_in_idle (xml, g_object_ref (item)); else g_signal_emit (G_OBJECT (xml), signals[ADDED], 0, item); retval = TRUE; } } xmlFreeDoc (wplist); return retval; } static void gnome_wp_file_changed (GFileMonitor *monitor, GFile *file, GFile *other_file, GFileMonitorEvent event_type, CcBackgroundXml *data) { gchar *filename; switch (event_type) { case G_FILE_MONITOR_EVENT_CHANGED: case G_FILE_MONITOR_EVENT_CREATED: filename = g_file_get_path (file); cc_background_xml_load_xml_internal (data, filename, FALSE); g_free (filename); break; default: break; } } static void cc_background_xml_add_monitor (GFile *directory, CcBackgroundXml *data) { GFileMonitor *monitor; GError *error = NULL; monitor = g_file_monitor_directory (directory, G_FILE_MONITOR_NONE, NULL, &error); if (error != NULL) { gchar *path; path = g_file_get_parse_name (directory); g_warning ("Unable to monitor directory %s: %s", path, error->message); g_error_free (error); g_free (path); return; } g_signal_connect (monitor, "changed", G_CALLBACK (gnome_wp_file_changed), data); } static void cc_background_xml_load_from_dir (const gchar *path, CcBackgroundXml *data, gboolean in_thread) { GFile *directory; GFileEnumerator *enumerator; GError *error = NULL; GFileInfo *info; if (!g_file_test (path, G_FILE_TEST_IS_DIR)) { return; } directory = g_file_new_for_path (path); enumerator = g_file_enumerate_children (directory, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NONE, NULL, &error); if (error != NULL) { g_warning ("Unable to check directory %s: %s", path, error->message); g_error_free (error); g_object_unref (directory); return; } while ((info = g_file_enumerator_next_file (enumerator, NULL, NULL))) { const gchar *filename; gchar *fullpath; filename = g_file_info_get_name (info); fullpath = g_build_filename (path, filename, NULL); g_object_unref (info); cc_background_xml_load_xml_internal (data, fullpath, in_thread); g_free (fullpath); } g_file_enumerator_close (enumerator, NULL, NULL); cc_background_xml_add_monitor (directory, data); g_object_unref (directory); g_object_unref (enumerator); } static void cc_background_xml_load_list (CcBackgroundXml *data, gboolean in_thread) { const char * const *system_data_dirs; gchar * datadir; gint i; datadir = g_build_filename (g_get_user_data_dir (), "gnome-background-properties", NULL); cc_background_xml_load_from_dir (datadir, data, in_thread); g_free (datadir); system_data_dirs = g_get_system_data_dirs (); for (i = 0; system_data_dirs[i]; i++) { datadir = g_build_filename (system_data_dirs[i], "gnome-background-properties", NULL); cc_background_xml_load_from_dir (datadir, data, in_thread); g_free (datadir); } } const GHashTable * cc_background_xml_load_list_finish (GAsyncResult *async_result) { GSimpleAsyncResult *result = G_SIMPLE_ASYNC_RESULT (async_result); CcBackgroundXml *data; g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); g_warn_if_fail (g_simple_async_result_get_source_tag (result) == cc_background_xml_load_list_async); data = CC_BACKGROUND_XML (g_simple_async_result_get_op_res_gpointer (result)); return data->priv->wp_hash; } static void load_list_thread (GSimpleAsyncResult *res, GObject *object, GCancellable *cancellable) { CcBackgroundXml *data; data = g_simple_async_result_get_op_res_gpointer (res); cc_background_xml_load_list (data, TRUE); } void cc_background_xml_load_list_async (CcBackgroundXml *xml, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *result; g_return_if_fail (CC_IS_BACKGROUND_XML (xml)); result = g_simple_async_result_new (G_OBJECT (xml), callback, user_data, cc_background_xml_load_list_async); g_simple_async_result_set_op_res_gpointer (result, xml, NULL); g_simple_async_result_run_in_thread (result, (GSimpleAsyncThreadFunc) load_list_thread, G_PRIORITY_LOW, cancellable); g_object_unref (result); } gboolean cc_background_xml_load_xml (CcBackgroundXml *xml, const gchar *filename) { g_return_val_if_fail (CC_IS_BACKGROUND_XML (xml), FALSE); if (g_file_test (filename, G_FILE_TEST_IS_REGULAR) == FALSE) return FALSE; return cc_background_xml_load_xml_internal (xml, filename, FALSE); } static void single_xml_added (CcBackgroundXml *xml, CcBackgroundItem *item, CcBackgroundItem **ret) { g_assert (*ret == NULL); *ret = g_object_ref (item); } CcBackgroundItem * cc_background_xml_get_item (const char *filename) { CcBackgroundXml *xml; CcBackgroundItem *item; if (g_file_test (filename, G_FILE_TEST_IS_REGULAR) == FALSE) return NULL; xml = cc_background_xml_new (); item = NULL; g_signal_connect (G_OBJECT (xml), "added", G_CALLBACK (single_xml_added), &item); if (cc_background_xml_load_xml (xml, filename) == FALSE) { g_object_unref (xml); return NULL; } return item; } static const char * enum_to_str (GType type, int v) { GEnumClass *eclass; GEnumValue *value; eclass = G_ENUM_CLASS (g_type_class_peek (type)); value = g_enum_get_value (eclass, v); g_assert (value); return value->value_nick; } void cc_background_xml_save (CcBackgroundItem *item, const char *filename) { xmlDoc *wp; xmlNode *root, *wallpaper; xmlNode *xml_item G_GNUC_UNUSED; const char * none = "(none)"; const char *placement_str, *shading_str; char *name, *pcolor, *scolor, *uri, *source_url; CcBackgroundItemFlags flags; GDesktopBackgroundStyle placement; GDesktopBackgroundShading shading; xmlKeepBlanksDefault (0); wp = xmlNewDoc ((xmlChar *)"1.0"); xmlCreateIntSubset (wp, (xmlChar *)"wallpapers", NULL, (xmlChar *)"gnome-wp-list.dtd"); root = xmlNewNode (NULL, (xmlChar *)"wallpapers"); xmlDocSetRootElement (wp, root); g_object_get (G_OBJECT (item), "name", &name, "uri", &uri, "shading", &shading, "placement", &placement, "primary-color", &pcolor, "secondary-color", &scolor, "source-url", &source_url, "flags", &flags, NULL); placement_str = enum_to_str (G_DESKTOP_TYPE_DESKTOP_BACKGROUND_STYLE, placement); shading_str = enum_to_str (G_DESKTOP_TYPE_DESKTOP_BACKGROUND_SHADING, shading); wallpaper = xmlNewChild (root, NULL, (xmlChar *)"wallpaper", NULL); xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"name", (xmlChar *)name); if (flags & CC_BACKGROUND_ITEM_HAS_URI && uri != NULL) { GFile *file; char *fname; file = g_file_new_for_commandline_arg (uri); fname = g_file_get_path (file); g_object_unref (file); xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"filename", (xmlChar *)fname); g_free (fname); } else if (flags & CC_BACKGROUND_ITEM_HAS_URI) { xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"filename", (xmlChar *)none); } if (flags & CC_BACKGROUND_ITEM_HAS_PLACEMENT) xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"options", (xmlChar *)placement_str); if (flags & CC_BACKGROUND_ITEM_HAS_SHADING) xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"shade_type", (xmlChar *)shading_str); if (flags & CC_BACKGROUND_ITEM_HAS_PCOLOR) xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"pcolor", (xmlChar *)pcolor); if (flags & CC_BACKGROUND_ITEM_HAS_SCOLOR) xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"scolor", (xmlChar *)scolor); if (source_url != NULL) xml_item = xmlNewTextChild (wallpaper, NULL, (xmlChar *)"source_url", (xmlChar *)source_url); g_free (name); g_free (pcolor); g_free (scolor); g_free (uri); g_free (source_url); xmlSaveFormatFile (filename, wp, 1); xmlFreeDoc (wp); } static void cc_background_xml_finalize (GObject *object) { CcBackgroundXml *xml; g_return_if_fail (object != NULL); g_return_if_fail (CC_IS_BACKGROUND_XML (object)); xml = CC_BACKGROUND_XML (object); g_return_if_fail (xml->priv != NULL); if (xml->priv->wp_hash) { g_hash_table_destroy (xml->priv->wp_hash); xml->priv->wp_hash = NULL; } if (xml->priv->item_added_id != 0) { g_source_remove (xml->priv->item_added_id); xml->priv->item_added_id = 0; } if (xml->priv->item_added_queue) { g_async_queue_unref (xml->priv->item_added_queue); xml->priv->item_added_queue = NULL; } } static void cc_background_xml_class_init (CcBackgroundXmlClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = cc_background_xml_finalize; signals[ADDED] = g_signal_new ("added", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, CC_TYPE_BACKGROUND_ITEM); g_type_class_add_private (klass, sizeof (CcBackgroundXmlPrivate)); } static void cc_background_xml_init (CcBackgroundXml *xml) { xml->priv = CC_BACKGROUND_XML_GET_PRIVATE (xml); xml->priv->wp_hash = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, (GDestroyNotify) g_object_unref); xml->priv->item_added_queue = g_async_queue_new_full ((GDestroyNotify) g_object_unref); } CcBackgroundXml * cc_background_xml_new (void) { return CC_BACKGROUND_XML (g_object_new (CC_TYPE_BACKGROUND_XML, NULL)); }
412
./cinnamon-control-center/panels/unused/background/bg-colors-source.c
/* bg-colors-source.c */ /* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include <config.h> #include "bg-colors-source.h" #include "cc-background-item.h" #include <glib/gi18n-lib.h> #include <gdesktop-enums.h> G_DEFINE_TYPE (BgColorsSource, bg_colors_source, BG_TYPE_SOURCE) #define COLORS_SOURCE_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), BG_TYPE_COLORS_SOURCE, BgColorsSourcePrivate)) static void bg_colors_source_class_init (BgColorsSourceClass *klass) { } struct { GDesktopBackgroundShading type; int orientation; const char *pcolor; } items[] = { { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#db5d33" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#008094" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#5d479d" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#ab2876" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#fad166" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#437740" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#d272c4" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#ed9116" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#ff89a9" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#7a8aa2" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#888888" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#475b52" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#425265" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#7a634b" }, { G_DESKTOP_BACKGROUND_SHADING_SOLID, -1, "#000000" }, }; static void bg_colors_source_init (BgColorsSource *self) { GnomeDesktopThumbnailFactory *thumb_factory; guint i; GtkListStore *store; store = bg_source_get_liststore (BG_SOURCE (self)); thumb_factory = gnome_desktop_thumbnail_factory_new (GNOME_DESKTOP_THUMBNAIL_SIZE_LARGE); for (i = 0; i < G_N_ELEMENTS (items); i++) { CcBackgroundItemFlags flags; CcBackgroundItem *item; GIcon *pixbuf; item = cc_background_item_new (NULL); flags = CC_BACKGROUND_ITEM_HAS_PCOLOR | CC_BACKGROUND_ITEM_HAS_SCOLOR | CC_BACKGROUND_ITEM_HAS_SHADING | CC_BACKGROUND_ITEM_HAS_PLACEMENT | CC_BACKGROUND_ITEM_HAS_URI; /* It does have a URI, it's "none" */ g_object_set (G_OBJECT (item), "uri", "file:///" DATADIR "/cinnamon-control-center/pixmaps/noise-texture-light.png", "primary-color", items[i].pcolor, "secondary-color", items[i].pcolor, "shading", items[i].type, "placement", G_DESKTOP_BACKGROUND_STYLE_WALLPAPER, "flags", flags, NULL); cc_background_item_load (item, NULL); /* insert the item into the liststore */ pixbuf = cc_background_item_get_thumbnail (item, thumb_factory, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); gtk_list_store_insert_with_values (store, NULL, 0, 0, pixbuf, 1, item, -1); g_object_unref (pixbuf); } g_object_unref (thumb_factory); } BgColorsSource * bg_colors_source_new (void) { return g_object_new (BG_TYPE_COLORS_SOURCE, NULL); }
413
./cinnamon-control-center/panels/unused/background/cc-background-item.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2010-2011 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <stdlib.h> #include <stdio.h> #include <gtk/gtk.h> #include <gio/gio.h> #include <glib/gi18n-lib.h> #include <libgnome-desktop/gnome-bg.h> #include <gdesktop-enums.h> #include "cc-background-item.h" #include "gdesktop-enums-types.h" #define CC_BACKGROUND_ITEM_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_BACKGROUND_ITEM, CcBackgroundItemPrivate)) struct CcBackgroundItemPrivate { /* properties */ char *name; char *uri; char *size; GDesktopBackgroundStyle placement; GDesktopBackgroundShading shading; char *primary_color; char *secondary_color; char *source_url; /* Used by the Flickr source */ char *source_xml; /* Used by the Wallpapers source */ gboolean is_deleted; gboolean needs_download; CcBackgroundItemFlags flags; /* internal */ GnomeBG *bg; char *mime_type; int width; int height; }; enum { PROP_0, PROP_NAME, PROP_URI, PROP_PLACEMENT, PROP_SHADING, PROP_PRIMARY_COLOR, PROP_SECONDARY_COLOR, PROP_IS_DELETED, PROP_SOURCE_URL, PROP_SOURCE_XML, PROP_FLAGS, PROP_SIZE, PROP_NEEDS_DOWNLOAD }; static void cc_background_item_class_init (CcBackgroundItemClass *klass); static void cc_background_item_init (CcBackgroundItem *background_item); static void cc_background_item_finalize (GObject *object); G_DEFINE_TYPE (CcBackgroundItem, cc_background_item, G_TYPE_OBJECT) static GEmblem * get_slideshow_icon (void) { GIcon *themed; GEmblem *emblem; themed = g_themed_icon_new ("slideshow-emblem"); emblem = g_emblem_new_with_origin (themed, G_EMBLEM_ORIGIN_DEVICE); g_object_unref (themed); return emblem; } static void set_bg_properties (CcBackgroundItem *item) { GdkColor pcolor = { 0, 0, 0, 0 }; GdkColor scolor = { 0, 0, 0, 0 }; if (item->priv->uri) { GFile *file; char *filename; file = g_file_new_for_commandline_arg (item->priv->uri); filename = g_file_get_path (file); g_object_unref (file); gnome_bg_set_filename (item->priv->bg, filename); g_free (filename); } if (item->priv->primary_color != NULL) { gdk_color_parse (item->priv->primary_color, &pcolor); } if (item->priv->secondary_color != NULL) { gdk_color_parse (item->priv->secondary_color, &scolor); } gnome_bg_set_color (item->priv->bg, item->priv->shading, &pcolor, &scolor); gnome_bg_set_placement (item->priv->bg, item->priv->placement); } gboolean cc_background_item_changes_with_time (CcBackgroundItem *item) { gboolean changes; g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), FALSE); changes = FALSE; if (item->priv->bg != NULL) { changes = gnome_bg_changes_with_time (item->priv->bg); } return changes; } static void update_size (CcBackgroundItem *item) { g_free (item->priv->size); item->priv->size = NULL; if (item->priv->uri == NULL) { item->priv->size = g_strdup (""); } else { if (gnome_bg_has_multiple_sizes (item->priv->bg) || gnome_bg_changes_with_time (item->priv->bg)) { item->priv->size = g_strdup (_("multiple sizes")); } else { /* translators: 100 × 100px * Note that this is not an "x", but U+00D7 MULTIPLICATION SIGN */ item->priv->size = g_strdup_printf (_("%d \303\227 %d"), item->priv->width, item->priv->height); } } } static GdkPixbuf * render_at_size (GnomeBG *bg, gint width, gint height) { GdkPixbuf *pixbuf; pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, FALSE, 8, width, height); gnome_bg_draw (bg, pixbuf, gdk_screen_get_default (), FALSE); return pixbuf; } GIcon * cc_background_item_get_frame_thumbnail (CcBackgroundItem *item, GnomeDesktopThumbnailFactory *thumbs, int width, int height, int frame, gboolean force_size) { GdkPixbuf *pixbuf = NULL; GIcon *icon = NULL; g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); g_return_val_if_fail (width > 0 && height > 0, NULL); set_bg_properties (item); if (force_size) { /* FIXME: this doesn't play nice with slideshow stepping at all, * because it will always render the current slideshow frame, which * might not be what we want. * We're lacking an API to draw a high-res GnomeBG manually choosing * the slideshow frame though, so we can't do much better than this * for now. */ pixbuf = render_at_size (item->priv->bg, width, height); } else { if (frame >= 0) { pixbuf = gnome_bg_create_frame_thumbnail (item->priv->bg, thumbs, gdk_screen_get_default (), width, height, frame); } else { pixbuf = gnome_bg_create_thumbnail (item->priv->bg, thumbs, gdk_screen_get_default (), width, height); } } if (pixbuf != NULL && frame != -2 && gnome_bg_changes_with_time (item->priv->bg)) { GEmblem *emblem; emblem = get_slideshow_icon (); icon = g_emblemed_icon_new (G_ICON (pixbuf), emblem); g_object_unref (emblem); g_object_unref (pixbuf); } else { icon = G_ICON (pixbuf); } gnome_bg_get_image_size (item->priv->bg, thumbs, width, height, &item->priv->width, &item->priv->height); update_size (item); return icon; } GIcon * cc_background_item_get_thumbnail (CcBackgroundItem *item, GnomeDesktopThumbnailFactory *thumbs, int width, int height) { return cc_background_item_get_frame_thumbnail (item, thumbs, width, height, -1, FALSE); } static void update_info (CcBackgroundItem *item, GFileInfo *_info) { GFile *file; GFileInfo *info; if (_info == NULL) { file = g_file_new_for_uri (item->priv->uri); info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_NAME "," G_FILE_ATTRIBUTE_STANDARD_SIZE "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, NULL, NULL); g_object_unref (file); } else { info = g_object_ref (_info); } g_free (item->priv->mime_type); item->priv->mime_type = NULL; if (info == NULL || g_file_info_get_content_type (info) == NULL) { if (item->priv->uri == NULL) { item->priv->mime_type = g_strdup ("image/x-no-data"); g_free (item->priv->name); item->priv->name = g_strdup (_("No Desktop Background")); } } else { if (item->priv->name == NULL) item->priv->name = g_strdup (g_file_info_get_display_name (info)); item->priv->mime_type = g_strdup (g_file_info_get_content_type (info)); } if (info != NULL) g_object_unref (info); } gboolean cc_background_item_load (CcBackgroundItem *item, GFileInfo *info) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), FALSE); if (item->priv->uri == NULL) return TRUE; update_info (item, info); if (item->priv->mime_type != NULL && (g_str_has_prefix (item->priv->mime_type, "image/") || strcmp (item->priv->mime_type, "application/xml") == 0)) { set_bg_properties (item); } else { return FALSE; } /* FIXME we should handle XML files as well */ if (item->priv->mime_type != NULL && g_str_has_prefix (item->priv->mime_type, "image/")) { char *filename; filename = g_filename_from_uri (item->priv->uri, NULL, NULL); gdk_pixbuf_get_file_info (filename, &item->priv->width, &item->priv->height); g_free (filename); update_size (item); } return TRUE; } static void _set_name (CcBackgroundItem *item, const char *value) { g_free (item->priv->name); item->priv->name = g_strdup (value); } const char * cc_background_item_get_name (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->name; } static void _set_uri (CcBackgroundItem *item, const char *value) { g_free (item->priv->uri); if (value && *value == '\0') { item->priv->uri = NULL; } else { if (value && strstr (value, "://") == NULL) g_warning ("URI '%s' is invalid", value); item->priv->uri = g_strdup (value); } } const char * cc_background_item_get_uri (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->uri; } static void _set_placement (CcBackgroundItem *item, GDesktopBackgroundStyle value) { item->priv->placement = value; } static void _set_shading (CcBackgroundItem *item, GDesktopBackgroundShading value) { item->priv->shading = value; } static void _set_primary_color (CcBackgroundItem *item, const char *value) { g_free (item->priv->primary_color); item->priv->primary_color = g_strdup (value); } const char * cc_background_item_get_pcolor (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->primary_color; } static void _set_secondary_color (CcBackgroundItem *item, const char *value) { g_free (item->priv->secondary_color); item->priv->secondary_color = g_strdup (value); } const char * cc_background_item_get_scolor (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->secondary_color; } GDesktopBackgroundStyle cc_background_item_get_placement (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), G_DESKTOP_BACKGROUND_STYLE_SCALED); return item->priv->placement; } GDesktopBackgroundShading cc_background_item_get_shading (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), G_DESKTOP_BACKGROUND_SHADING_SOLID); return item->priv->shading; } static void _set_is_deleted (CcBackgroundItem *item, gboolean value) { item->priv->is_deleted = value; } static void _set_source_url (CcBackgroundItem *item, const char *value) { g_free (item->priv->source_url); item->priv->source_url = g_strdup (value); } const char * cc_background_item_get_source_url (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->source_url; } static void _set_source_xml (CcBackgroundItem *item, const char *value) { g_free (item->priv->source_xml); item->priv->source_xml = g_strdup (value); } const char * cc_background_item_get_source_xml (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->source_xml; } static void _set_flags (CcBackgroundItem *item, CcBackgroundItemFlags value) { item->priv->flags = value; } CcBackgroundItemFlags cc_background_item_get_flags (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), 0); return item->priv->flags; } const char * cc_background_item_get_size (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), NULL); return item->priv->size; } static void _set_needs_download (CcBackgroundItem *item, gboolean value) { item->priv->needs_download = value; } gboolean cc_background_item_get_needs_download (CcBackgroundItem *item) { g_return_val_if_fail (CC_IS_BACKGROUND_ITEM (item), 0); return item->priv->needs_download; } static void cc_background_item_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { CcBackgroundItem *self; self = CC_BACKGROUND_ITEM (object); switch (prop_id) { case PROP_NAME: _set_name (self, g_value_get_string (value)); break; case PROP_URI: _set_uri (self, g_value_get_string (value)); break; case PROP_PLACEMENT: _set_placement (self, g_value_get_enum (value)); break; case PROP_SHADING: _set_shading (self, g_value_get_enum (value)); break; case PROP_PRIMARY_COLOR: _set_primary_color (self, g_value_get_string (value)); break; case PROP_SECONDARY_COLOR: _set_secondary_color (self, g_value_get_string (value)); break; case PROP_IS_DELETED: _set_is_deleted (self, g_value_get_boolean (value)); break; case PROP_SOURCE_URL: _set_source_url (self, g_value_get_string (value)); break; case PROP_SOURCE_XML: _set_source_xml (self, g_value_get_string (value)); break; case PROP_FLAGS: _set_flags (self, g_value_get_flags (value)); break; case PROP_NEEDS_DOWNLOAD: _set_needs_download (self, g_value_get_boolean (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void cc_background_item_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { CcBackgroundItem *self; self = CC_BACKGROUND_ITEM (object); switch (prop_id) { case PROP_NAME: g_value_set_string (value, self->priv->name); break; case PROP_URI: g_value_set_string (value, self->priv->uri); break; case PROP_PLACEMENT: g_value_set_enum (value, self->priv->placement); break; case PROP_SHADING: g_value_set_enum (value, self->priv->shading); break; case PROP_PRIMARY_COLOR: g_value_set_string (value, self->priv->primary_color); break; case PROP_SECONDARY_COLOR: g_value_set_string (value, self->priv->secondary_color); break; case PROP_IS_DELETED: g_value_set_boolean (value, self->priv->is_deleted); break; case PROP_SOURCE_URL: g_value_set_string (value, self->priv->source_url); break; case PROP_SOURCE_XML: g_value_set_string (value, self->priv->source_xml); break; case PROP_FLAGS: g_value_set_flags (value, self->priv->flags); break; case PROP_SIZE: g_value_set_string (value, self->priv->size); break; case PROP_NEEDS_DOWNLOAD: g_value_set_boolean (value, self->priv->needs_download); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GObject * cc_background_item_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_properties) { CcBackgroundItem *background_item; background_item = CC_BACKGROUND_ITEM (G_OBJECT_CLASS (cc_background_item_parent_class)->constructor (type, n_construct_properties, construct_properties)); return G_OBJECT (background_item); } static void cc_background_item_class_init (CcBackgroundItemClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->get_property = cc_background_item_get_property; object_class->set_property = cc_background_item_set_property; object_class->constructor = cc_background_item_constructor; object_class->finalize = cc_background_item_finalize; g_object_class_install_property (object_class, PROP_NAME, g_param_spec_string ("name", "name", "name", NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_URI, g_param_spec_string ("uri", "uri", "uri", NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_PLACEMENT, g_param_spec_enum ("placement", "placement", "placement", G_DESKTOP_TYPE_DESKTOP_BACKGROUND_STYLE, G_DESKTOP_BACKGROUND_STYLE_SCALED, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SHADING, g_param_spec_enum ("shading", "shading", "shading", G_DESKTOP_TYPE_DESKTOP_BACKGROUND_SHADING, G_DESKTOP_BACKGROUND_SHADING_SOLID, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_PRIMARY_COLOR, g_param_spec_string ("primary-color", "primary-color", "primary-color", "#000000000000", G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SECONDARY_COLOR, g_param_spec_string ("secondary-color", "secondary-color", "secondary-color", "#000000000000", G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_IS_DELETED, g_param_spec_boolean ("is-deleted", NULL, NULL, FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SOURCE_URL, g_param_spec_string ("source-url", "source-url", "source-url", NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SOURCE_XML, g_param_spec_string ("source-xml", "source-xml", "source-xml", NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_FLAGS, g_param_spec_flags ("flags", "flags", "flags", G_DESKTOP_TYPE_BACKGROUND_ITEM_FLAGS, 0, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SIZE, g_param_spec_string ("size", "size", "size", NULL, G_PARAM_READABLE)); g_object_class_install_property (object_class, PROP_NEEDS_DOWNLOAD, g_param_spec_boolean ("needs-download", NULL, NULL, TRUE, G_PARAM_READWRITE)); g_type_class_add_private (klass, sizeof (CcBackgroundItemPrivate)); } static void cc_background_item_init (CcBackgroundItem *item) { item->priv = CC_BACKGROUND_ITEM_GET_PRIVATE (item); item->priv->bg = gnome_bg_new (); item->priv->shading = G_DESKTOP_BACKGROUND_SHADING_SOLID; item->priv->placement = G_DESKTOP_BACKGROUND_STYLE_SCALED; item->priv->primary_color = g_strdup ("#000000000000"); item->priv->secondary_color = g_strdup ("#000000000000"); item->priv->needs_download = TRUE; item->priv->flags = 0; } static void cc_background_item_finalize (GObject *object) { CcBackgroundItem *item; g_return_if_fail (object != NULL); g_return_if_fail (CC_IS_BACKGROUND_ITEM (object)); item = CC_BACKGROUND_ITEM (object); g_return_if_fail (item->priv != NULL); g_free (item->priv->name); g_free (item->priv->uri); g_free (item->priv->primary_color); g_free (item->priv->secondary_color); g_free (item->priv->mime_type); g_free (item->priv->size); if (item->priv->bg != NULL) g_object_unref (item->priv->bg); G_OBJECT_CLASS (cc_background_item_parent_class)->finalize (object); } CcBackgroundItem * cc_background_item_new (const char *uri) { GObject *object; object = g_object_new (CC_TYPE_BACKGROUND_ITEM, "uri", uri, NULL); return CC_BACKGROUND_ITEM (object); } CcBackgroundItem * cc_background_item_copy (CcBackgroundItem *item) { CcBackgroundItem *ret; ret = cc_background_item_new (item->priv->uri); ret->priv->name = g_strdup (item->priv->name); ret->priv->size = g_strdup (item->priv->size); ret->priv->placement = item->priv->placement; ret->priv->shading = item->priv->shading; ret->priv->primary_color = g_strdup (item->priv->primary_color); ret->priv->secondary_color = g_strdup (item->priv->secondary_color); ret->priv->source_url = g_strdup (item->priv->source_url); ret->priv->source_xml = g_strdup (item->priv->source_xml); ret->priv->is_deleted = item->priv->is_deleted; ret->priv->needs_download = item->priv->needs_download; ret->priv->flags = item->priv->flags; return ret; } static const char * flags_to_str (CcBackgroundItemFlags flag) { GFlagsClass *fclass; GFlagsValue *value; fclass = G_FLAGS_CLASS (g_type_class_peek (G_DESKTOP_TYPE_BACKGROUND_ITEM_FLAGS)); value = g_flags_get_first_value (fclass, flag); g_assert (value); return value->value_nick; } static const char * enum_to_str (GType type, int v) { GEnumClass *eclass; GEnumValue *value; eclass = G_ENUM_CLASS (g_type_class_peek (type)); value = g_enum_get_value (eclass, v); g_assert (value); return value->value_nick; } void cc_background_item_dump (CcBackgroundItem *item) { CcBackgroundItemPrivate *priv; GString *flags; int i; g_return_if_fail (CC_IS_BACKGROUND_ITEM (item)); priv = item->priv; g_debug ("name:\t\t\t%s", priv->name); g_debug ("URI:\t\t\t%s", priv->uri ? priv->uri : "NULL"); if (priv->size) g_debug ("size:\t\t\t'%s'", priv->size); flags = g_string_new (NULL); for (i = 0; i < 5; i++) { if (priv->flags & (1 << i)) { g_string_append (flags, flags_to_str (1 << i)); g_string_append_c (flags, ' '); } } if (flags->len == 0) g_string_append (flags, "-none-"); g_debug ("flags:\t\t\t%s", flags->str); g_string_free (flags, TRUE); if (priv->primary_color) g_debug ("pcolor:\t\t%s", priv->primary_color); if (priv->secondary_color) g_debug ("scolor:\t\t%s", priv->secondary_color); g_debug ("placement:\t\t%s", enum_to_str (G_DESKTOP_TYPE_DESKTOP_BACKGROUND_STYLE, priv->placement)); g_debug ("shading:\t\t%s", enum_to_str (G_DESKTOP_TYPE_DESKTOP_BACKGROUND_SHADING, priv->shading)); if (priv->source_url) g_debug ("source URL:\t\t%s", priv->source_url); if (priv->source_xml) g_debug ("source XML:\t\t%s", priv->source_xml); g_debug ("deleted:\t\t%s", priv->is_deleted ? "yes" : "no"); if (priv->mime_type) g_debug ("mime-type:\t\t%s", priv->mime_type); g_debug ("dimensions:\t\t%d x %d", priv->width, priv->height); g_debug (" "); } static gboolean files_equal (const char *a, const char *b) { GFile *file1, *file2; gboolean retval; if (a == NULL && b == NULL) return TRUE; if (a == NULL || b == NULL) return FALSE; file1 = g_file_new_for_commandline_arg (a); file2 = g_file_new_for_commandline_arg (b); if (g_file_equal (file1, file2) == FALSE) retval = FALSE; else retval = TRUE; g_object_unref (file1); g_object_unref (file2); return retval; } static gboolean colors_equal (const char *a, const char *b) { GdkColor color1, color2; gdk_color_parse (a, &color1); gdk_color_parse (b, &color2); return gdk_color_equal (&color1, &color2); } gboolean cc_background_item_compare (CcBackgroundItem *saved, CcBackgroundItem *configured) { CcBackgroundItemFlags flags; flags = saved->priv->flags; if (flags == 0) return FALSE; if (flags & CC_BACKGROUND_ITEM_HAS_URI) { if (files_equal (saved->priv->uri, configured->priv->uri) == FALSE) return FALSE; } if (flags & CC_BACKGROUND_ITEM_HAS_SHADING) { if (saved->priv->shading != configured->priv->shading) return FALSE; } if (flags & CC_BACKGROUND_ITEM_HAS_PLACEMENT) { if (saved->priv->placement != configured->priv->placement) return FALSE; } if (flags & CC_BACKGROUND_ITEM_HAS_PCOLOR) { if (colors_equal (saved->priv->primary_color, configured->priv->primary_color) == FALSE) { return FALSE; } } if (flags & CC_BACKGROUND_ITEM_HAS_SCOLOR) { if (colors_equal (saved->priv->secondary_color, configured->priv->secondary_color) == FALSE) { return FALSE; } } return TRUE; }
414
./cinnamon-control-center/panels/unused/datetime/test-timezone.c
#include <gtk/gtk.h> #include "cc-timezone-map.h" #define TZ_DIR "/usr/share/zoneinfo/" static GList * get_timezone_list (GList *tzs, const char *top_path, const char *subpath) { GDir *dir; char *fullpath; const char *name; if (subpath == NULL) fullpath = g_strdup (top_path); else fullpath = g_build_filename (top_path, subpath, NULL); dir = g_dir_open (fullpath, 0, NULL); if (dir == NULL) { g_warning ("Could not open %s", fullpath); return NULL; } while ((name = g_dir_read_name (dir)) != NULL) { char *path; if (g_str_has_suffix (name, ".tab")) continue; if (subpath != NULL) path = g_build_filename (top_path, subpath, name, NULL); else path = g_build_filename (top_path, name, NULL); if (g_file_test (path, G_FILE_TEST_IS_DIR)) { if (subpath == NULL) { tzs = get_timezone_list (tzs, top_path, name); } else { char *new_subpath; new_subpath = g_strdup_printf ("%s/%s", subpath, name); tzs = get_timezone_list (tzs, top_path, new_subpath); g_free (new_subpath); } } else if (g_file_test (path, G_FILE_TEST_IS_REGULAR)) { if (subpath == NULL) tzs = g_list_prepend (tzs, g_strdup (name)); else { char *tz; tz = g_strdup_printf ("%s/%s", subpath, name); tzs = g_list_prepend (tzs, tz); } } g_free (path); } g_dir_close (dir); return tzs; } int main (int argc, char **argv) { CcTimezoneMap *map; TzDB *tz_db; GList *tzs, *l; GHashTable *ht; int ret = 0; gtk_init (&argc, &argv); ht = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); map = cc_timezone_map_new (); tz_db = tz_load_db (); tzs = get_timezone_list (NULL, TZ_DIR, NULL); for (l = tzs; l != NULL; l = l->next) { char *timezone = l->data; char *clean_tz; clean_tz = tz_info_get_clean_name (tz_db, timezone); if (cc_timezone_map_set_timezone (map, clean_tz) == FALSE) { if (g_hash_table_lookup (ht, clean_tz) == NULL) { if (g_strcmp0 (clean_tz, timezone) == 0) g_print ("Failed to locate timezone '%s'\n", timezone); else g_print ("Failed to locate timezone '%s' (original name: '%s')\n", clean_tz, timezone); g_hash_table_insert (ht, g_strdup (clean_tz), GINT_TO_POINTER (TRUE)); } /* We don't warn for those two, we'll just fallback * in the panel code */ if (!g_str_equal (clean_tz, "posixrules") && !g_str_equal (clean_tz, "Factory")) ret = 1; } g_free (timezone); g_free (clean_tz); } g_list_free (tzs); tz_db_free (tz_db); g_hash_table_destroy (ht); return ret; }
415
./cinnamon-control-center/panels/unused/datetime/timedated.c
/* * Generated by gdbus-codegen 2.34.1. DO NOT EDIT. * * The license of this code is the same as for the source it was derived from. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "timedated.h" #include <string.h> #ifdef G_OS_UNIX # include <gio/gunixfdlist.h> #endif typedef struct { GDBusArgInfo parent_struct; gboolean use_gvariant; } _ExtendedGDBusArgInfo; typedef struct { GDBusMethodInfo parent_struct; const gchar *signal_name; gboolean pass_fdlist; } _ExtendedGDBusMethodInfo; typedef struct { GDBusSignalInfo parent_struct; const gchar *signal_name; } _ExtendedGDBusSignalInfo; typedef struct { GDBusPropertyInfo parent_struct; const gchar *hyphen_name; gboolean use_gvariant; } _ExtendedGDBusPropertyInfo; typedef struct { GDBusInterfaceInfo parent_struct; const gchar *hyphen_name; } _ExtendedGDBusInterfaceInfo; typedef struct { const _ExtendedGDBusPropertyInfo *info; guint prop_id; GValue orig_value; /* the value before the change */ } ChangedProperty; static void _changed_property_free (ChangedProperty *data) { g_value_unset (&data->orig_value); g_free (data); } static gboolean _g_strv_equal0 (gchar **a, gchar **b) { gboolean ret = FALSE; guint n; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; if (g_strv_length (a) != g_strv_length (b)) goto out; for (n = 0; a[n] != NULL; n++) if (g_strcmp0 (a[n], b[n]) != 0) goto out; ret = TRUE; out: return ret; } static gboolean _g_variant_equal0 (GVariant *a, GVariant *b) { gboolean ret = FALSE; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; ret = g_variant_equal (a, b); out: return ret; } G_GNUC_UNUSED static gboolean _g_value_equal (const GValue *a, const GValue *b) { gboolean ret = FALSE; g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); switch (G_VALUE_TYPE (a)) { case G_TYPE_BOOLEAN: ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); break; case G_TYPE_UCHAR: ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); break; case G_TYPE_INT: ret = (g_value_get_int (a) == g_value_get_int (b)); break; case G_TYPE_UINT: ret = (g_value_get_uint (a) == g_value_get_uint (b)); break; case G_TYPE_INT64: ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); break; case G_TYPE_UINT64: ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); break; case G_TYPE_DOUBLE: { /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ gdouble da = g_value_get_double (a); gdouble db = g_value_get_double (b); ret = memcmp (&da, &db, sizeof (gdouble)) == 0; } break; case G_TYPE_STRING: ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); break; case G_TYPE_VARIANT: ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); break; default: if (G_VALUE_TYPE (a) == G_TYPE_STRV) ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); else g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); break; } return ret; } /* ------------------------------------------------------------------------ * Code for interface org.freedesktop.timedate1 * ------------------------------------------------------------------------ */ /** * SECTION:Timedate1 * @title: Timedate1 * @short_description: Generated C code for the org.freedesktop.timedate1 D-Bus interface * * This section contains code for working with the <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link> D-Bus interface in C. */ /* ---- Introspection data for org.freedesktop.timedate1 ---- */ static const _ExtendedGDBusArgInfo _timedate1_method_info_set_time_IN_ARG_usec_utc = { { -1, (gchar *) "usec_utc", (gchar *) "x", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_time_IN_ARG_relative = { { -1, (gchar *) "relative", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_time_IN_ARG_user_interaction = { { -1, (gchar *) "user_interaction", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _timedate1_method_info_set_time_IN_ARG_pointers[] = { &_timedate1_method_info_set_time_IN_ARG_usec_utc, &_timedate1_method_info_set_time_IN_ARG_relative, &_timedate1_method_info_set_time_IN_ARG_user_interaction, NULL }; static const _ExtendedGDBusMethodInfo _timedate1_method_info_set_time = { { -1, (gchar *) "SetTime", (GDBusArgInfo **) &_timedate1_method_info_set_time_IN_ARG_pointers, NULL, NULL }, "handle-set-time", FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_timezone_IN_ARG_timezone = { { -1, (gchar *) "timezone", (gchar *) "s", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_timezone_IN_ARG_user_interaction = { { -1, (gchar *) "user_interaction", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _timedate1_method_info_set_timezone_IN_ARG_pointers[] = { &_timedate1_method_info_set_timezone_IN_ARG_timezone, &_timedate1_method_info_set_timezone_IN_ARG_user_interaction, NULL }; static const _ExtendedGDBusMethodInfo _timedate1_method_info_set_timezone = { { -1, (gchar *) "SetTimezone", (GDBusArgInfo **) &_timedate1_method_info_set_timezone_IN_ARG_pointers, NULL, NULL }, "handle-set-timezone", FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_local_rtc_IN_ARG_local_rtc = { { -1, (gchar *) "local_rtc", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_local_rtc_IN_ARG_fix_system = { { -1, (gchar *) "fix_system", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_local_rtc_IN_ARG_user_interaction = { { -1, (gchar *) "user_interaction", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _timedate1_method_info_set_local_rtc_IN_ARG_pointers[] = { &_timedate1_method_info_set_local_rtc_IN_ARG_local_rtc, &_timedate1_method_info_set_local_rtc_IN_ARG_fix_system, &_timedate1_method_info_set_local_rtc_IN_ARG_user_interaction, NULL }; static const _ExtendedGDBusMethodInfo _timedate1_method_info_set_local_rtc = { { -1, (gchar *) "SetLocalRTC", (GDBusArgInfo **) &_timedate1_method_info_set_local_rtc_IN_ARG_pointers, NULL, NULL }, "handle-set-local-rtc", FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_ntp_IN_ARG_use_ntp = { { -1, (gchar *) "use_ntp", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _timedate1_method_info_set_ntp_IN_ARG_user_interaction = { { -1, (gchar *) "user_interaction", (gchar *) "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _timedate1_method_info_set_ntp_IN_ARG_pointers[] = { &_timedate1_method_info_set_ntp_IN_ARG_use_ntp, &_timedate1_method_info_set_ntp_IN_ARG_user_interaction, NULL }; static const _ExtendedGDBusMethodInfo _timedate1_method_info_set_ntp = { { -1, (gchar *) "SetNTP", (GDBusArgInfo **) &_timedate1_method_info_set_ntp_IN_ARG_pointers, NULL, NULL }, "handle-set-ntp", FALSE }; static const _ExtendedGDBusMethodInfo * const _timedate1_method_info_pointers[] = { &_timedate1_method_info_set_time, &_timedate1_method_info_set_timezone, &_timedate1_method_info_set_local_rtc, &_timedate1_method_info_set_ntp, NULL }; static const _ExtendedGDBusPropertyInfo _timedate1_property_info_timezone = { { -1, (gchar *) "Timezone", (gchar *) "s", G_DBUS_PROPERTY_INFO_FLAGS_READABLE, NULL }, "timezone", FALSE }; static const _ExtendedGDBusPropertyInfo _timedate1_property_info_local_rtc = { { -1, (gchar *) "LocalRTC", (gchar *) "b", G_DBUS_PROPERTY_INFO_FLAGS_READABLE, NULL }, "local-rtc", FALSE }; static const _ExtendedGDBusPropertyInfo _timedate1_property_info_ntp = { { -1, (gchar *) "NTP", (gchar *) "b", G_DBUS_PROPERTY_INFO_FLAGS_READABLE, NULL }, "ntp", FALSE }; static const _ExtendedGDBusPropertyInfo * const _timedate1_property_info_pointers[] = { &_timedate1_property_info_timezone, &_timedate1_property_info_local_rtc, &_timedate1_property_info_ntp, NULL }; static const _ExtendedGDBusInterfaceInfo _timedate1_interface_info = { { -1, (gchar *) "org.freedesktop.timedate1", (GDBusMethodInfo **) &_timedate1_method_info_pointers, NULL, (GDBusPropertyInfo **) &_timedate1_property_info_pointers, NULL }, "timedate1", }; /** * timedate1_interface_info: * * Gets a machine-readable description of the <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link> D-Bus interface. * * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. */ GDBusInterfaceInfo * timedate1_interface_info (void) { return (GDBusInterfaceInfo *) &_timedate1_interface_info.parent_struct; } /** * timedate1_override_properties: * @klass: The class structure for a #GObject<!-- -->-derived class. * @property_id_begin: The property id to assign to the first overridden property. * * Overrides all #GObject properties in the #Timedate1 interface for a concrete class. * The properties are overridden in the order they are defined. * * Returns: The last property id. */ guint timedate1_override_properties (GObjectClass *klass, guint property_id_begin) { g_object_class_override_property (klass, property_id_begin++, "timezone"); g_object_class_override_property (klass, property_id_begin++, "local-rtc"); g_object_class_override_property (klass, property_id_begin++, "ntp"); return property_id_begin - 1; } /** * Timedate1: * * Abstract interface type for the D-Bus interface <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link>. */ /** * Timedate1Iface: * @parent_iface: The parent interface. * @handle_set_local_rtc: Handler for the #Timedate1::handle-set-local-rtc signal. * @handle_set_ntp: Handler for the #Timedate1::handle-set-ntp signal. * @handle_set_time: Handler for the #Timedate1::handle-set-time signal. * @handle_set_timezone: Handler for the #Timedate1::handle-set-timezone signal. * @get_local_rtc: Getter for the #Timedate1:local-rtc property. * @get_ntp: Getter for the #Timedate1:ntp property. * @get_timezone: Getter for the #Timedate1:timezone property. * * Virtual table for the D-Bus interface <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link>. */ static void timedate1_default_init (Timedate1Iface *iface) { /* GObject signals for incoming D-Bus method calls: */ /** * Timedate1::handle-set-time: * @object: A #Timedate1. * @invocation: A #GDBusMethodInvocation. * @arg_usec_utc: Argument passed by remote caller. * @arg_relative: Argument passed by remote caller. * @arg_user_interaction: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTime">SetTime()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call timedate1_complete_set_time() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-time", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (Timedate1Iface, handle_set_time), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 4, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_INT64, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); /** * Timedate1::handle-set-timezone: * @object: A #Timedate1. * @invocation: A #GDBusMethodInvocation. * @arg_timezone: Argument passed by remote caller. * @arg_user_interaction: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTimezone">SetTimezone()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call timedate1_complete_set_timezone() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-timezone", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (Timedate1Iface, handle_set_timezone), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 3, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING, G_TYPE_BOOLEAN); /** * Timedate1::handle-set-local-rtc: * @object: A #Timedate1. * @invocation: A #GDBusMethodInvocation. * @arg_local_rtc: Argument passed by remote caller. * @arg_fix_system: Argument passed by remote caller. * @arg_user_interaction: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-freedesktop-timedate1.SetLocalRTC">SetLocalRTC()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call timedate1_complete_set_local_rtc() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-local-rtc", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (Timedate1Iface, handle_set_local_rtc), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 4, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); /** * Timedate1::handle-set-ntp: * @object: A #Timedate1. * @invocation: A #GDBusMethodInvocation. * @arg_use_ntp: Argument passed by remote caller. * @arg_user_interaction: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-freedesktop-timedate1.SetNTP">SetNTP()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call timedate1_complete_set_ntp() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-ntp", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (Timedate1Iface, handle_set_ntp), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 3, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); /* GObject properties for D-Bus properties: */ /** * Timedate1:timezone: * * Represents the D-Bus property <link linkend="gdbus-property-org-freedesktop-timedate1.Timezone">"Timezone"</link>. * * Since the D-Bus property for this #GObject property is readable but not writable, it is meaningful to read from it on both the client- and service-side. It is only meaningful, however, to write to it on the service-side. */ g_object_interface_install_property (iface, g_param_spec_string ("timezone", "Timezone", "Timezone", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * Timedate1:local-rtc: * * Represents the D-Bus property <link linkend="gdbus-property-org-freedesktop-timedate1.LocalRTC">"LocalRTC"</link>. * * Since the D-Bus property for this #GObject property is readable but not writable, it is meaningful to read from it on both the client- and service-side. It is only meaningful, however, to write to it on the service-side. */ g_object_interface_install_property (iface, g_param_spec_boolean ("local-rtc", "LocalRTC", "LocalRTC", FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * Timedate1:ntp: * * Represents the D-Bus property <link linkend="gdbus-property-org-freedesktop-timedate1.NTP">"NTP"</link>. * * Since the D-Bus property for this #GObject property is readable but not writable, it is meaningful to read from it on both the client- and service-side. It is only meaningful, however, to write to it on the service-side. */ g_object_interface_install_property (iface, g_param_spec_boolean ("ntp", "NTP", "NTP", FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); } typedef Timedate1Iface Timedate1Interface; G_DEFINE_INTERFACE (Timedate1, timedate1, G_TYPE_OBJECT); /** * timedate1_get_timezone: (skip) * @object: A #Timedate1. * * Gets the value of the <link linkend="gdbus-property-org-freedesktop-timedate1.Timezone">"Timezone"</link> D-Bus property. * * Since this D-Bus property is readable, it is meaningful to use this function on both the client- and service-side. * * <warning>The returned value is only valid until the property changes so on the client-side it is only safe to use this function on the thread where @object was constructed. Use timedate1_dup_timezone() if on another thread.</warning> * * Returns: (transfer none): The property value or %NULL if the property is not set. Do not free the returned value, it belongs to @object. */ const gchar * timedate1_get_timezone (Timedate1 *object) { return TIMEDATE1_GET_IFACE (object)->get_timezone (object); } /** * timedate1_dup_timezone: (skip) * @object: A #Timedate1. * * Gets a copy of the <link linkend="gdbus-property-org-freedesktop-timedate1.Timezone">"Timezone"</link> D-Bus property. * * Since this D-Bus property is readable, it is meaningful to use this function on both the client- and service-side. * * Returns: (transfer full): The property value or %NULL if the property is not set. The returned value should be freed with g_free(). */ gchar * timedate1_dup_timezone (Timedate1 *object) { gchar *value; g_object_get (G_OBJECT (object), "timezone", &value, NULL); return value; } /** * timedate1_set_timezone: (skip) * @object: A #Timedate1. * @value: The value to set. * * Sets the <link linkend="gdbus-property-org-freedesktop-timedate1.Timezone">"Timezone"</link> D-Bus property to @value. * * Since this D-Bus property is not writable, it is only meaningful to use this function on the service-side. */ void timedate1_set_timezone (Timedate1 *object, const gchar *value) { g_object_set (G_OBJECT (object), "timezone", value, NULL); } /** * timedate1_get_local_rtc: (skip) * @object: A #Timedate1. * * Gets the value of the <link linkend="gdbus-property-org-freedesktop-timedate1.LocalRTC">"LocalRTC"</link> D-Bus property. * * Since this D-Bus property is readable, it is meaningful to use this function on both the client- and service-side. * * Returns: The property value. */ gboolean timedate1_get_local_rtc (Timedate1 *object) { return TIMEDATE1_GET_IFACE (object)->get_local_rtc (object); } /** * timedate1_set_local_rtc: (skip) * @object: A #Timedate1. * @value: The value to set. * * Sets the <link linkend="gdbus-property-org-freedesktop-timedate1.LocalRTC">"LocalRTC"</link> D-Bus property to @value. * * Since this D-Bus property is not writable, it is only meaningful to use this function on the service-side. */ void timedate1_set_local_rtc (Timedate1 *object, gboolean value) { g_object_set (G_OBJECT (object), "local-rtc", value, NULL); } /** * timedate1_get_ntp: (skip) * @object: A #Timedate1. * * Gets the value of the <link linkend="gdbus-property-org-freedesktop-timedate1.NTP">"NTP"</link> D-Bus property. * * Since this D-Bus property is readable, it is meaningful to use this function on both the client- and service-side. * * Returns: The property value. */ gboolean timedate1_get_ntp (Timedate1 *object) { return TIMEDATE1_GET_IFACE (object)->get_ntp (object); } /** * timedate1_set_ntp: (skip) * @object: A #Timedate1. * @value: The value to set. * * Sets the <link linkend="gdbus-property-org-freedesktop-timedate1.NTP">"NTP"</link> D-Bus property to @value. * * Since this D-Bus property is not writable, it is only meaningful to use this function on the service-side. */ void timedate1_set_ntp (Timedate1 *object, gboolean value) { g_object_set (G_OBJECT (object), "ntp", value, NULL); } /** * timedate1_call_set_time: * @proxy: A #Timedate1Proxy. * @arg_usec_utc: Argument to pass with the method invocation. * @arg_relative: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTime">SetTime()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call timedate1_call_set_time_finish() to get the result of the operation. * * See timedate1_call_set_time_sync() for the synchronous, blocking version of this method. */ void timedate1_call_set_time ( Timedate1 *proxy, gint64 arg_usec_utc, gboolean arg_relative, gboolean arg_user_interaction, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetTime", g_variant_new ("(xbb)", arg_usec_utc, arg_relative, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * timedate1_call_set_time_finish: * @proxy: A #Timedate1Proxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to timedate1_call_set_time(). * @error: Return location for error or %NULL. * * Finishes an operation started with timedate1_call_set_time(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_time_finish ( Timedate1 *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_time_sync: * @proxy: A #Timedate1Proxy. * @arg_usec_utc: Argument to pass with the method invocation. * @arg_relative: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTime">SetTime()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See timedate1_call_set_time() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_time_sync ( Timedate1 *proxy, gint64 arg_usec_utc, gboolean arg_relative, gboolean arg_user_interaction, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetTime", g_variant_new ("(xbb)", arg_usec_utc, arg_relative, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_timezone: * @proxy: A #Timedate1Proxy. * @arg_timezone: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTimezone">SetTimezone()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call timedate1_call_set_timezone_finish() to get the result of the operation. * * See timedate1_call_set_timezone_sync() for the synchronous, blocking version of this method. */ void timedate1_call_set_timezone ( Timedate1 *proxy, const gchar *arg_timezone, gboolean arg_user_interaction, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetTimezone", g_variant_new ("(sb)", arg_timezone, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * timedate1_call_set_timezone_finish: * @proxy: A #Timedate1Proxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to timedate1_call_set_timezone(). * @error: Return location for error or %NULL. * * Finishes an operation started with timedate1_call_set_timezone(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_timezone_finish ( Timedate1 *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_timezone_sync: * @proxy: A #Timedate1Proxy. * @arg_timezone: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTimezone">SetTimezone()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See timedate1_call_set_timezone() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_timezone_sync ( Timedate1 *proxy, const gchar *arg_timezone, gboolean arg_user_interaction, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetTimezone", g_variant_new ("(sb)", arg_timezone, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_local_rtc: * @proxy: A #Timedate1Proxy. * @arg_local_rtc: Argument to pass with the method invocation. * @arg_fix_system: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetLocalRTC">SetLocalRTC()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call timedate1_call_set_local_rtc_finish() to get the result of the operation. * * See timedate1_call_set_local_rtc_sync() for the synchronous, blocking version of this method. */ void timedate1_call_set_local_rtc ( Timedate1 *proxy, gboolean arg_local_rtc, gboolean arg_fix_system, gboolean arg_user_interaction, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetLocalRTC", g_variant_new ("(bbb)", arg_local_rtc, arg_fix_system, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * timedate1_call_set_local_rtc_finish: * @proxy: A #Timedate1Proxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to timedate1_call_set_local_rtc(). * @error: Return location for error or %NULL. * * Finishes an operation started with timedate1_call_set_local_rtc(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_local_rtc_finish ( Timedate1 *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_local_rtc_sync: * @proxy: A #Timedate1Proxy. * @arg_local_rtc: Argument to pass with the method invocation. * @arg_fix_system: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetLocalRTC">SetLocalRTC()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See timedate1_call_set_local_rtc() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_local_rtc_sync ( Timedate1 *proxy, gboolean arg_local_rtc, gboolean arg_fix_system, gboolean arg_user_interaction, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetLocalRTC", g_variant_new ("(bbb)", arg_local_rtc, arg_fix_system, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_ntp: * @proxy: A #Timedate1Proxy. * @arg_use_ntp: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetNTP">SetNTP()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call timedate1_call_set_ntp_finish() to get the result of the operation. * * See timedate1_call_set_ntp_sync() for the synchronous, blocking version of this method. */ void timedate1_call_set_ntp ( Timedate1 *proxy, gboolean arg_use_ntp, gboolean arg_user_interaction, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetNTP", g_variant_new ("(bb)", arg_use_ntp, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * timedate1_call_set_ntp_finish: * @proxy: A #Timedate1Proxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to timedate1_call_set_ntp(). * @error: Return location for error or %NULL. * * Finishes an operation started with timedate1_call_set_ntp(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_ntp_finish ( Timedate1 *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_call_set_ntp_sync: * @proxy: A #Timedate1Proxy. * @arg_use_ntp: Argument to pass with the method invocation. * @arg_user_interaction: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-freedesktop-timedate1.SetNTP">SetNTP()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See timedate1_call_set_ntp() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean timedate1_call_set_ntp_sync ( Timedate1 *proxy, gboolean arg_use_ntp, gboolean arg_user_interaction, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetNTP", g_variant_new ("(bb)", arg_use_ntp, arg_user_interaction), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * timedate1_complete_set_time: * @object: A #Timedate1. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTime">SetTime()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void timedate1_complete_set_time ( Timedate1 *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * timedate1_complete_set_timezone: * @object: A #Timedate1. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-freedesktop-timedate1.SetTimezone">SetTimezone()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void timedate1_complete_set_timezone ( Timedate1 *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * timedate1_complete_set_local_rtc: * @object: A #Timedate1. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-freedesktop-timedate1.SetLocalRTC">SetLocalRTC()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void timedate1_complete_set_local_rtc ( Timedate1 *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * timedate1_complete_set_ntp: * @object: A #Timedate1. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-freedesktop-timedate1.SetNTP">SetNTP()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void timedate1_complete_set_ntp ( Timedate1 *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /* ------------------------------------------------------------------------ */ /** * Timedate1Proxy: * * The #Timedate1Proxy structure contains only private data and should only be accessed using the provided API. */ /** * Timedate1ProxyClass: * @parent_class: The parent class. * * Class structure for #Timedate1Proxy. */ struct _Timedate1ProxyPrivate { GData *qdata; }; static void timedate1_proxy_iface_init (Timedate1Iface *iface); G_DEFINE_TYPE_WITH_CODE (Timedate1Proxy, timedate1_proxy, G_TYPE_DBUS_PROXY, G_IMPLEMENT_INTERFACE (TYPE_TIMEDATE1, timedate1_proxy_iface_init)); static void timedate1_proxy_finalize (GObject *object) { Timedate1Proxy *proxy = TIMEDATE1_PROXY (object); g_datalist_clear (&proxy->priv->qdata); G_OBJECT_CLASS (timedate1_proxy_parent_class)->finalize (object); } static void timedate1_proxy_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { const _ExtendedGDBusPropertyInfo *info; GVariant *variant; g_assert (prop_id != 0 && prop_id - 1 < 3); info = _timedate1_property_info_pointers[prop_id - 1]; variant = g_dbus_proxy_get_cached_property (G_DBUS_PROXY (object), info->parent_struct.name); if (info->use_gvariant) { g_value_set_variant (value, variant); } else { if (variant != NULL) g_dbus_gvariant_to_gvalue (variant, value); } if (variant != NULL) g_variant_unref (variant); } static void timedate1_proxy_set_property_cb (GDBusProxy *proxy, GAsyncResult *res, gpointer user_data) { const _ExtendedGDBusPropertyInfo *info = user_data; GError *error; error = NULL; if (!g_dbus_proxy_call_finish (proxy, res, &error)) { g_warning ("Error setting property `%s' on interface org.freedesktop.timedate1: %s (%s, %d)", info->parent_struct.name, error->message, g_quark_to_string (error->domain), error->code); g_error_free (error); } } static void timedate1_proxy_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { const _ExtendedGDBusPropertyInfo *info; GVariant *variant; g_assert (prop_id != 0 && prop_id - 1 < 3); info = _timedate1_property_info_pointers[prop_id - 1]; variant = g_dbus_gvalue_to_gvariant (value, G_VARIANT_TYPE (info->parent_struct.signature)); g_dbus_proxy_call (G_DBUS_PROXY (object), "org.freedesktop.DBus.Properties.Set", g_variant_new ("(ssv)", "org.freedesktop.timedate1", info->parent_struct.name, variant), G_DBUS_CALL_FLAGS_NONE, -1, NULL, (GAsyncReadyCallback) timedate1_proxy_set_property_cb, (GDBusPropertyInfo *) &info->parent_struct); g_variant_unref (variant); } static void timedate1_proxy_g_signal (GDBusProxy *proxy, const gchar *sender_name, const gchar *signal_name, GVariant *parameters) { _ExtendedGDBusSignalInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint n; guint signal_id; info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_timedate1_interface_info.parent_struct, signal_name); if (info == NULL) return; num_params = g_variant_n_children (parameters); paramv = g_new0 (GValue, num_params + 1); g_value_init (&paramv[0], TYPE_TIMEDATE1); g_value_set_object (&paramv[0], proxy); g_variant_iter_init (&iter, parameters); n = 1; while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; if (arg_info->use_gvariant) { g_value_init (&paramv[n], G_TYPE_VARIANT); g_value_set_variant (&paramv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, &paramv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, TYPE_TIMEDATE1); g_signal_emitv (paramv, signal_id, 0, NULL); for (n = 0; n < num_params + 1; n++) g_value_unset (&paramv[n]); g_free (paramv); } static void timedate1_proxy_g_properties_changed (GDBusProxy *_proxy, GVariant *changed_properties, const gchar *const *invalidated_properties) { Timedate1Proxy *proxy = TIMEDATE1_PROXY (_proxy); guint n; const gchar *key; GVariantIter *iter; _ExtendedGDBusPropertyInfo *info; g_variant_get (changed_properties, "a{sv}", &iter); while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_timedate1_interface_info.parent_struct, key); g_datalist_remove_data (&proxy->priv->qdata, key); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } g_variant_iter_free (iter); for (n = 0; invalidated_properties[n] != NULL; n++) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_timedate1_interface_info.parent_struct, invalidated_properties[n]); g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } } static const gchar * timedate1_proxy_get_timezone (Timedate1 *object) { Timedate1Proxy *proxy = TIMEDATE1_PROXY (object); GVariant *variant; const gchar *value = NULL; variant = g_dbus_proxy_get_cached_property (G_DBUS_PROXY (proxy), "Timezone"); if (variant != NULL) { value = g_variant_get_string (variant, NULL); g_variant_unref (variant); } return value; } static gboolean timedate1_proxy_get_local_rtc (Timedate1 *object) { Timedate1Proxy *proxy = TIMEDATE1_PROXY (object); GVariant *variant; gboolean value = 0; variant = g_dbus_proxy_get_cached_property (G_DBUS_PROXY (proxy), "LocalRTC"); if (variant != NULL) { value = g_variant_get_boolean (variant); g_variant_unref (variant); } return value; } static gboolean timedate1_proxy_get_ntp (Timedate1 *object) { Timedate1Proxy *proxy = TIMEDATE1_PROXY (object); GVariant *variant; gboolean value = 0; variant = g_dbus_proxy_get_cached_property (G_DBUS_PROXY (proxy), "NTP"); if (variant != NULL) { value = g_variant_get_boolean (variant); g_variant_unref (variant); } return value; } static void timedate1_proxy_init (Timedate1Proxy *proxy) { proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_TIMEDATE1_PROXY, Timedate1ProxyPrivate); g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), timedate1_interface_info ()); } static void timedate1_proxy_class_init (Timedate1ProxyClass *klass) { GObjectClass *gobject_class; GDBusProxyClass *proxy_class; g_type_class_add_private (klass, sizeof (Timedate1ProxyPrivate)); gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = timedate1_proxy_finalize; gobject_class->get_property = timedate1_proxy_get_property; gobject_class->set_property = timedate1_proxy_set_property; proxy_class = G_DBUS_PROXY_CLASS (klass); proxy_class->g_signal = timedate1_proxy_g_signal; proxy_class->g_properties_changed = timedate1_proxy_g_properties_changed; timedate1_override_properties (gobject_class, 1); } static void timedate1_proxy_iface_init (Timedate1Iface *iface) { iface->get_timezone = timedate1_proxy_get_timezone; iface->get_local_rtc = timedate1_proxy_get_local_rtc; iface->get_ntp = timedate1_proxy_get_ntp; } /** * timedate1_proxy_new: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Asynchronously creates a proxy for the D-Bus interface <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link>. See g_dbus_proxy_new() for more details. * * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call timedate1_proxy_new_finish() to get the result of the operation. * * See timedate1_proxy_new_sync() for the synchronous, blocking version of this constructor. */ void timedate1_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (TYPE_TIMEDATE1_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.freedesktop.timedate1", NULL); } /** * timedate1_proxy_new_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to timedate1_proxy_new(). * @error: Return location for error or %NULL * * Finishes an operation started with timedate1_proxy_new(). * * Returns: (transfer full) (type Timedate1Proxy): The constructed proxy object or %NULL if @error is set. */ Timedate1 * timedate1_proxy_new_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return TIMEDATE1 (ret); else return NULL; } /** * timedate1_proxy_new_sync: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Synchronously creates a proxy for the D-Bus interface <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link>. See g_dbus_proxy_new_sync() for more details. * * The calling thread is blocked until a reply is received. * * See timedate1_proxy_new() for the asynchronous version of this constructor. * * Returns: (transfer full) (type Timedate1Proxy): The constructed proxy object or %NULL if @error is set. */ Timedate1 * timedate1_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (TYPE_TIMEDATE1_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.freedesktop.timedate1", NULL); if (ret != NULL) return TIMEDATE1 (ret); else return NULL; } /** * timedate1_proxy_new_for_bus: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Like timedate1_proxy_new() but takes a #GBusType instead of a #GDBusConnection. * * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call timedate1_proxy_new_for_bus_finish() to get the result of the operation. * * See timedate1_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. */ void timedate1_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (TYPE_TIMEDATE1_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.freedesktop.timedate1", NULL); } /** * timedate1_proxy_new_for_bus_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to timedate1_proxy_new_for_bus(). * @error: Return location for error or %NULL * * Finishes an operation started with timedate1_proxy_new_for_bus(). * * Returns: (transfer full) (type Timedate1Proxy): The constructed proxy object or %NULL if @error is set. */ Timedate1 * timedate1_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return TIMEDATE1 (ret); else return NULL; } /** * timedate1_proxy_new_for_bus_sync: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Like timedate1_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. * * The calling thread is blocked until a reply is received. * * See timedate1_proxy_new_for_bus() for the asynchronous version of this constructor. * * Returns: (transfer full) (type Timedate1Proxy): The constructed proxy object or %NULL if @error is set. */ Timedate1 * timedate1_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (TYPE_TIMEDATE1_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.freedesktop.timedate1", NULL); if (ret != NULL) return TIMEDATE1 (ret); else return NULL; } /* ------------------------------------------------------------------------ */ /** * Timedate1Skeleton: * * The #Timedate1Skeleton structure contains only private data and should only be accessed using the provided API. */ /** * Timedate1SkeletonClass: * @parent_class: The parent class. * * Class structure for #Timedate1Skeleton. */ struct _Timedate1SkeletonPrivate { GValue *properties; GList *changed_properties; GSource *changed_properties_idle_source; GMainContext *context; GMutex lock; }; static void _timedate1_skeleton_handle_method_call ( GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (user_data); _ExtendedGDBusMethodInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint num_extra; guint n; guint signal_id; GValue return_value = G_VALUE_INIT; info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); g_assert (info != NULL); num_params = g_variant_n_children (parameters); num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); n = 0; g_value_init (&paramv[n], TYPE_TIMEDATE1); g_value_set_object (&paramv[n++], skeleton); g_value_init (&paramv[n], G_TYPE_DBUS_METHOD_INVOCATION); g_value_set_object (&paramv[n++], invocation); if (info->pass_fdlist) { #ifdef G_OS_UNIX g_value_init (&paramv[n], G_TYPE_UNIX_FD_LIST); g_value_set_object (&paramv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); #else g_assert_not_reached (); #endif } g_variant_iter_init (&iter, parameters); while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; if (arg_info->use_gvariant) { g_value_init (&paramv[n], G_TYPE_VARIANT); g_value_set_variant (&paramv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, &paramv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, TYPE_TIMEDATE1); g_value_init (&return_value, G_TYPE_BOOLEAN); g_signal_emitv (paramv, signal_id, 0, &return_value); if (!g_value_get_boolean (&return_value)) g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); g_value_unset (&return_value); for (n = 0; n < num_params + num_extra; n++) g_value_unset (&paramv[n]); g_free (paramv); } static GVariant * _timedate1_skeleton_handle_get_property ( GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *property_name, GError **error, gpointer user_data) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; GVariant *ret; ret = NULL; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_timedate1_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { g_value_init (&value, pspec->value_type); g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); g_value_unset (&value); } return ret; } static gboolean _timedate1_skeleton_handle_set_property ( GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *property_name, GVariant *variant, GError **error, gpointer user_data) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; gboolean ret; ret = FALSE; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_timedate1_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { if (info->use_gvariant) g_value_set_variant (&value, variant); else g_dbus_gvariant_to_gvalue (variant, &value); g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); g_value_unset (&value); ret = TRUE; } return ret; } static const GDBusInterfaceVTable _timedate1_skeleton_vtable = { _timedate1_skeleton_handle_method_call, _timedate1_skeleton_handle_get_property, _timedate1_skeleton_handle_set_property }; static GDBusInterfaceInfo * timedate1_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton) { return timedate1_interface_info (); } static GDBusInterfaceVTable * timedate1_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton) { return (GDBusInterfaceVTable *) &_timedate1_skeleton_vtable; } static GVariant * timedate1_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (_skeleton); GVariantBuilder builder; guint n; g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); if (_timedate1_interface_info.parent_struct.properties == NULL) goto out; for (n = 0; _timedate1_interface_info.parent_struct.properties[n] != NULL; n++) { GDBusPropertyInfo *info = _timedate1_interface_info.parent_struct.properties[n]; if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) { GVariant *value; value = _timedate1_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "org.freedesktop.timedate1", info->name, NULL, skeleton); if (value != NULL) { g_variant_take_ref (value); g_variant_builder_add (&builder, "{sv}", info->name, value); g_variant_unref (value); } } } out: return g_variant_builder_end (&builder); } static gboolean _timedate1_emit_changed (gpointer user_data); static void timedate1_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (_skeleton); gboolean emit_changed = FALSE; g_mutex_lock (&skeleton->priv->lock); if (skeleton->priv->changed_properties_idle_source != NULL) { g_source_destroy (skeleton->priv->changed_properties_idle_source); skeleton->priv->changed_properties_idle_source = NULL; emit_changed = TRUE; } g_mutex_unlock (&skeleton->priv->lock); if (emit_changed) _timedate1_emit_changed (skeleton); } static void timedate1_skeleton_iface_init (Timedate1Iface *iface); G_DEFINE_TYPE_WITH_CODE (Timedate1Skeleton, timedate1_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_IMPLEMENT_INTERFACE (TYPE_TIMEDATE1, timedate1_skeleton_iface_init)); static void timedate1_skeleton_finalize (GObject *object) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); guint n; for (n = 0; n < 3; n++) g_value_unset (&skeleton->priv->properties[n]); g_free (skeleton->priv->properties); g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); if (skeleton->priv->changed_properties_idle_source != NULL) g_source_destroy (skeleton->priv->changed_properties_idle_source); g_main_context_unref (skeleton->priv->context); g_mutex_clear (&skeleton->priv->lock); G_OBJECT_CLASS (timedate1_skeleton_parent_class)->finalize (object); } static void timedate1_skeleton_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); g_assert (prop_id != 0 && prop_id - 1 < 3); g_mutex_lock (&skeleton->priv->lock); g_value_copy (&skeleton->priv->properties[prop_id - 1], value); g_mutex_unlock (&skeleton->priv->lock); } static gboolean _timedate1_emit_changed (gpointer user_data) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (user_data); GList *l; GVariantBuilder builder; GVariantBuilder invalidated_builder; guint num_changes; g_mutex_lock (&skeleton->priv->lock); g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as")); for (l = skeleton->priv->changed_properties, num_changes = 0; l != NULL; l = l->next) { ChangedProperty *cp = l->data; GVariant *variant; const GValue *cur_value; cur_value = &skeleton->priv->properties[cp->prop_id - 1]; if (!_g_value_equal (cur_value, &cp->orig_value)) { variant = g_dbus_gvalue_to_gvariant (cur_value, G_VARIANT_TYPE (cp->info->parent_struct.signature)); g_variant_builder_add (&builder, "{sv}", cp->info->parent_struct.name, variant); g_variant_unref (variant); num_changes++; } } if (num_changes > 0) { GList *connections, *ll; GVariant *signal_variant; signal_variant = g_variant_ref_sink (g_variant_new ("(sa{sv}as)", "org.freedesktop.timedate1", &builder, &invalidated_builder)); connections = g_dbus_interface_skeleton_get_connections (G_DBUS_INTERFACE_SKELETON (skeleton)); for (ll = connections; ll != NULL; ll = ll->next) { GDBusConnection *connection = ll->data; g_dbus_connection_emit_signal (connection, NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "org.freedesktop.DBus.Properties", "PropertiesChanged", signal_variant, NULL); } g_variant_unref (signal_variant); g_list_free_full (connections, g_object_unref); } else { g_variant_builder_clear (&builder); g_variant_builder_clear (&invalidated_builder); } g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); skeleton->priv->changed_properties = NULL; skeleton->priv->changed_properties_idle_source = NULL; g_mutex_unlock (&skeleton->priv->lock); return FALSE; } static void _timedate1_schedule_emit_changed (Timedate1Skeleton *skeleton, const _ExtendedGDBusPropertyInfo *info, guint prop_id, const GValue *orig_value) { ChangedProperty *cp; GList *l; cp = NULL; for (l = skeleton->priv->changed_properties; l != NULL; l = l->next) { ChangedProperty *i_cp = l->data; if (i_cp->info == info) { cp = i_cp; break; } } if (cp == NULL) { cp = g_new0 (ChangedProperty, 1); cp->prop_id = prop_id; cp->info = info; skeleton->priv->changed_properties = g_list_prepend (skeleton->priv->changed_properties, cp); g_value_init (&cp->orig_value, G_VALUE_TYPE (orig_value)); g_value_copy (orig_value, &cp->orig_value); } } static void timedate1_skeleton_notify (GObject *object, GParamSpec *pspec) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); g_mutex_lock (&skeleton->priv->lock); if (skeleton->priv->changed_properties != NULL && skeleton->priv->changed_properties_idle_source == NULL) { skeleton->priv->changed_properties_idle_source = g_idle_source_new (); g_source_set_priority (skeleton->priv->changed_properties_idle_source, G_PRIORITY_DEFAULT); g_source_set_callback (skeleton->priv->changed_properties_idle_source, _timedate1_emit_changed, g_object_ref (skeleton), (GDestroyNotify) g_object_unref); g_source_attach (skeleton->priv->changed_properties_idle_source, skeleton->priv->context); g_source_unref (skeleton->priv->changed_properties_idle_source); } g_mutex_unlock (&skeleton->priv->lock); } static void timedate1_skeleton_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); g_assert (prop_id != 0 && prop_id - 1 < 3); g_mutex_lock (&skeleton->priv->lock); g_object_freeze_notify (object); if (!_g_value_equal (value, &skeleton->priv->properties[prop_id - 1])) { if (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)) != NULL) _timedate1_schedule_emit_changed (skeleton, _timedate1_property_info_pointers[prop_id - 1], prop_id, &skeleton->priv->properties[prop_id - 1]); g_value_copy (value, &skeleton->priv->properties[prop_id - 1]); g_object_notify_by_pspec (object, pspec); } g_mutex_unlock (&skeleton->priv->lock); g_object_thaw_notify (object); } static void timedate1_skeleton_init (Timedate1Skeleton *skeleton) { skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_TIMEDATE1_SKELETON, Timedate1SkeletonPrivate); g_mutex_init (&skeleton->priv->lock); skeleton->priv->context = g_main_context_ref_thread_default (); skeleton->priv->properties = g_new0 (GValue, 3); g_value_init (&skeleton->priv->properties[0], G_TYPE_STRING); g_value_init (&skeleton->priv->properties[1], G_TYPE_BOOLEAN); g_value_init (&skeleton->priv->properties[2], G_TYPE_BOOLEAN); } static const gchar * timedate1_skeleton_get_timezone (Timedate1 *object) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); const gchar *value; g_mutex_lock (&skeleton->priv->lock); value = g_value_get_string (&(skeleton->priv->properties[0])); g_mutex_unlock (&skeleton->priv->lock); return value; } static gboolean timedate1_skeleton_get_local_rtc (Timedate1 *object) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); gboolean value; g_mutex_lock (&skeleton->priv->lock); value = g_value_get_boolean (&(skeleton->priv->properties[1])); g_mutex_unlock (&skeleton->priv->lock); return value; } static gboolean timedate1_skeleton_get_ntp (Timedate1 *object) { Timedate1Skeleton *skeleton = TIMEDATE1_SKELETON (object); gboolean value; g_mutex_lock (&skeleton->priv->lock); value = g_value_get_boolean (&(skeleton->priv->properties[2])); g_mutex_unlock (&skeleton->priv->lock); return value; } static void timedate1_skeleton_class_init (Timedate1SkeletonClass *klass) { GObjectClass *gobject_class; GDBusInterfaceSkeletonClass *skeleton_class; g_type_class_add_private (klass, sizeof (Timedate1SkeletonPrivate)); gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = timedate1_skeleton_finalize; gobject_class->get_property = timedate1_skeleton_get_property; gobject_class->set_property = timedate1_skeleton_set_property; gobject_class->notify = timedate1_skeleton_notify; timedate1_override_properties (gobject_class, 1); skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); skeleton_class->get_info = timedate1_skeleton_dbus_interface_get_info; skeleton_class->get_properties = timedate1_skeleton_dbus_interface_get_properties; skeleton_class->flush = timedate1_skeleton_dbus_interface_flush; skeleton_class->get_vtable = timedate1_skeleton_dbus_interface_get_vtable; } static void timedate1_skeleton_iface_init (Timedate1Iface *iface) { iface->get_timezone = timedate1_skeleton_get_timezone; iface->get_local_rtc = timedate1_skeleton_get_local_rtc; iface->get_ntp = timedate1_skeleton_get_ntp; } /** * timedate1_skeleton_new: * * Creates a skeleton object for the D-Bus interface <link linkend="gdbus-interface-org-freedesktop-timedate1.top_of_page">org.freedesktop.timedate1</link>. * * Returns: (transfer full) (type Timedate1Skeleton): The skeleton object. */ Timedate1 * timedate1_skeleton_new (void) { return TIMEDATE1 (g_object_new (TYPE_TIMEDATE1_SKELETON, NULL)); }
416
./cinnamon-control-center/panels/unused/datetime/datetime-module.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include <config.h> #include "cc-datetime-panel.h" #include <glib/gi18n-lib.h> #define GETTEXT_PACKAGE_TIMEZONES GETTEXT_PACKAGE "-timezones" void g_io_module_load (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); bindtextdomain (GETTEXT_PACKAGE_TIMEZONES, CINNAMONLOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE_TIMEZONES, "UTF-8"); /* register the panel */ cc_date_time_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
417
./cinnamon-control-center/panels/unused/datetime/tz.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* Generic timezone utilities. * * Copyright (C) 2000-2001 Ximian, Inc. * * Authors: Hans Petter Jansson <hpj@ximian.com> * * Largely based on Michael Fulbright's work on Anaconda. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ #include <glib.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <math.h> #include <string.h> #include "tz.h" /* Forward declarations for private functions */ static float convert_pos (gchar *pos, int digits); static int compare_country_names (const void *a, const void *b); static void sort_locations_by_country (GPtrArray *locations); static gchar * tz_data_file_get (void); static void load_backward_tz (TzDB *tz_db); /* ---------------- * * Public interface * * ---------------- */ TzDB * tz_load_db (void) { gchar *tz_data_file; TzDB *tz_db; FILE *tzfile; char buf[4096]; tz_data_file = tz_data_file_get (); if (!tz_data_file) { g_warning ("Could not get the TimeZone data file name"); return NULL; } tzfile = fopen (tz_data_file, "r"); if (!tzfile) { g_warning ("Could not open *%s*\n", tz_data_file); g_free (tz_data_file); return NULL; } tz_db = g_new0 (TzDB, 1); tz_db->locations = g_ptr_array_new (); while (fgets (buf, sizeof(buf), tzfile)) { gchar **tmpstrarr; gchar *latstr, *lngstr, *p; TzLocation *loc; if (*buf == '#') continue; g_strchomp(buf); tmpstrarr = g_strsplit(buf,"\t", 6); latstr = g_strdup (tmpstrarr[1]); p = latstr + 1; while (*p != '-' && *p != '+') p++; lngstr = g_strdup (p); *p = '\0'; loc = g_new0 (TzLocation, 1); loc->country = g_strdup (tmpstrarr[0]); loc->zone = g_strdup (tmpstrarr[2]); loc->latitude = convert_pos (latstr, 2); loc->longitude = convert_pos (lngstr, 3); #ifdef __sun if (tmpstrarr[3] && *tmpstrarr[3] == '-' && tmpstrarr[4]) loc->comment = g_strdup (tmpstrarr[4]); if (tmpstrarr[3] && *tmpstrarr[3] != '-' && !islower(loc->zone)) { TzLocation *locgrp; /* duplicate entry */ locgrp = g_new0 (TzLocation, 1); locgrp->country = g_strdup (tmpstrarr[0]); locgrp->zone = g_strdup (tmpstrarr[3]); locgrp->latitude = convert_pos (latstr, 2); locgrp->longitude = convert_pos (lngstr, 3); locgrp->comment = (tmpstrarr[4]) ? g_strdup (tmpstrarr[4]) : NULL; g_ptr_array_add (tz_db->locations, (gpointer) locgrp); } #else loc->comment = (tmpstrarr[3]) ? g_strdup(tmpstrarr[3]) : NULL; #endif g_ptr_array_add (tz_db->locations, (gpointer) loc); g_free (latstr); g_free (lngstr); g_strfreev (tmpstrarr); } fclose (tzfile); /* now sort by country */ sort_locations_by_country (tz_db->locations); g_free (tz_data_file); /* Load up the hashtable of backward links */ load_backward_tz (tz_db); return tz_db; } static void tz_location_free (TzLocation *loc) { g_free (loc->country); g_free (loc->zone); g_free (loc->comment); g_free (loc); } void tz_db_free (TzDB *db) { g_ptr_array_foreach (db->locations, (GFunc) tz_location_free, NULL); g_ptr_array_free (db->locations, TRUE); g_hash_table_destroy (db->backward); g_free (db); } GPtrArray * tz_get_locations (TzDB *db) { return db->locations; } gchar * tz_location_get_country (TzLocation *loc) { return loc->country; } gchar * tz_location_get_zone (TzLocation *loc) { return loc->zone; } gchar * tz_location_get_comment (TzLocation *loc) { return loc->comment; } void tz_location_get_position (TzLocation *loc, double *longitude, double *latitude) { *longitude = loc->longitude; *latitude = loc->latitude; } glong tz_location_get_utc_offset (TzLocation *loc) { TzInfo *tz_info; glong offset; tz_info = tz_info_from_location (loc); offset = tz_info->utc_offset; tz_info_free (tz_info); return offset; } TzInfo * tz_info_from_location (TzLocation *loc) { TzInfo *tzinfo; time_t curtime; struct tm *curzone; gchar *tz_env_value; g_return_val_if_fail (loc != NULL, NULL); g_return_val_if_fail (loc->zone != NULL, NULL); tz_env_value = g_strdup (getenv ("TZ")); setenv ("TZ", loc->zone, 1); #if 0 tzset (); #endif tzinfo = g_new0 (TzInfo, 1); curtime = time (NULL); curzone = localtime (&curtime); #ifndef __sun /* Currently this solution doesnt seem to work - I get that */ /* America/Phoenix uses daylight savings, which is wrong */ tzinfo->tzname_normal = g_strdup (curzone->tm_zone); if (curzone->tm_isdst) tzinfo->tzname_daylight = g_strdup (&curzone->tm_zone[curzone->tm_isdst]); else tzinfo->tzname_daylight = NULL; tzinfo->utc_offset = curzone->tm_gmtoff; #else tzinfo->tzname_normal = NULL; tzinfo->tzname_daylight = NULL; tzinfo->utc_offset = 0; #endif tzinfo->daylight = curzone->tm_isdst; if (tz_env_value) setenv ("TZ", tz_env_value, 1); else unsetenv ("TZ"); g_free (tz_env_value); return tzinfo; } void tz_info_free (TzInfo *tzinfo) { g_return_if_fail (tzinfo != NULL); if (tzinfo->tzname_normal) g_free (tzinfo->tzname_normal); if (tzinfo->tzname_daylight) g_free (tzinfo->tzname_daylight); g_free (tzinfo); } struct { const char *orig; const char *dest; } aliases[] = { { "Asia/Istanbul", "Europe/Istanbul" }, /* Istanbul is in both Europe and Asia */ { "Europe/Nicosia", "Asia/Nicosia" }, /* Ditto */ { "EET", "Europe/Istanbul" }, /* Same tz as the 2 above */ { "HST", "Pacific/Honolulu" }, { "WET", "Europe/Brussels" }, /* Other name for the mainland Europe tz */ { "CET", "Europe/Brussels" }, /* ditto */ { "MET", "Europe/Brussels" }, { "Etc/Zulu", "Etc/GMT" }, { "Etc/UTC", "Etc/GMT" }, { "GMT", "Etc/GMT" }, { "Greenwich", "Etc/GMT" }, { "Etc/UCT", "Etc/GMT" }, { "Etc/GMT0", "Etc/GMT" }, { "Etc/GMT+0", "Etc/GMT" }, { "Etc/GMT-0", "Etc/GMT" }, { "Etc/Universal", "Etc/GMT" }, { "PST8PDT", "America/Los_Angeles" }, /* Other name for the Atlantic tz */ { "EST", "America/New_York" }, /* Other name for the Eastern tz */ { "EST5EDT", "America/New_York" }, /* ditto */ { "CST6CDT", "America/Chicago" }, /* Other name for the Central tz */ { "MST", "America/Denver" }, /* Other name for the mountain tz */ { "MST7MDT", "America/Denver" }, /* ditto */ }; static gboolean compare_timezones (const char *a, const char *b) { if (g_str_equal (a, b)) return TRUE; if (strchr (b, '/') == NULL) { char *prefixed; prefixed = g_strdup_printf ("/%s", b); if (g_str_has_suffix (a, prefixed)) { g_free (prefixed); return TRUE; } g_free (prefixed); } return FALSE; } char * tz_info_get_clean_name (TzDB *tz_db, const char *tz) { char *ret; const char *timezone; guint i; gboolean replaced; /* Remove useless prefixes */ if (g_str_has_prefix (tz, "right/")) tz = tz + strlen ("right/"); else if (g_str_has_prefix (tz, "posix/")) tz = tz + strlen ("posix/"); /* Here start the crazies */ replaced = FALSE; for (i = 0; i < G_N_ELEMENTS (aliases); i++) { if (compare_timezones (tz, aliases[i].orig)) { replaced = TRUE; timezone = aliases[i].dest; break; } } /* Try again! */ if (!replaced) { /* Ignore crazy solar times from the '80s */ if (g_str_has_prefix (tz, "Asia/Riyadh") || g_str_has_prefix (tz, "Mideast/Riyadh")) { timezone = "Asia/Riyadh"; replaced = TRUE; } } if (!replaced) timezone = tz; ret = g_hash_table_lookup (tz_db->backward, timezone); if (ret == NULL) return g_strdup (timezone); return g_strdup (ret); } /* ----------------- * * Private functions * * ----------------- */ static gchar * tz_data_file_get (void) { gchar *file; file = g_strdup (TZ_DATA_FILE); return file; } static float convert_pos (gchar *pos, int digits) { gchar whole[10]; gchar *fraction; gint i; float t1, t2; if (!pos || strlen(pos) < 4 || digits > 9) return 0.0; for (i = 0; i < digits + 1; i++) whole[i] = pos[i]; whole[i] = '\0'; fraction = pos + digits + 1; t1 = g_strtod (whole, NULL); t2 = g_strtod (fraction, NULL); if (t1 >= 0.0) return t1 + t2/pow (10.0, strlen(fraction)); else return t1 - t2/pow (10.0, strlen(fraction)); } #if 0 /* Currently not working */ static void free_tzdata (TzLocation *tz) { if (tz->country) g_free(tz->country); if (tz->zone) g_free(tz->zone); if (tz->comment) g_free(tz->comment); g_free(tz); } #endif static int compare_country_names (const void *a, const void *b) { const TzLocation *tza = * (TzLocation **) a; const TzLocation *tzb = * (TzLocation **) b; return strcmp (tza->zone, tzb->zone); } static void sort_locations_by_country (GPtrArray *locations) { qsort (locations->pdata, locations->len, sizeof (gpointer), compare_country_names); } static void load_backward_tz (TzDB *tz_db) { GError *error = NULL; char **lines, *contents; guint i; tz_db->backward = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); if (g_file_get_contents (CINNAMONCC_DATA_DIR "/datetime/backward", &contents, NULL, &error) == FALSE) { g_warning ("Failed to load 'backward' file: %s", error->message); return; } lines = g_strsplit (contents, "\n", -1); g_free (contents); for (i = 0; lines[i] != NULL; i++) { char **items; guint j; char *real, *alias; if (g_ascii_strncasecmp (lines[i], "Link\t", 5) != 0) continue; items = g_strsplit (lines[i], "\t", -1); real = NULL; alias = NULL; /* Skip the "Link<tab>" part */ for (j = 1; items[j] != NULL; j++) { if (items[j][0] == '\0') continue; if (real == NULL) { real = items[j]; continue; } alias = items[j]; break; } if (real == NULL || alias == NULL) g_warning ("Could not parse line: %s", lines[i]); /* We don't need more than one name for it */ if (g_str_equal (real, "Etc/UTC") || g_str_equal (real, "Etc/UCT")) real = "Etc/GMT"; g_hash_table_insert (tz_db->backward, g_strdup (alias), g_strdup (real)); g_strfreev (items); } g_strfreev (lines); }
418
./cinnamon-control-center/panels/unused/datetime/set-timezone.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2007 David Zeuthen <david@fubar.dk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <dbus/dbus-glib.h> #include <dbus/dbus-glib-lowlevel.h> #include "set-timezone.h" static DBusGConnection * get_system_bus (GError **err) { GError *error; static DBusGConnection *bus = NULL; if (bus == NULL) { error = NULL; bus = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error); if (bus == NULL) { g_propagate_error (err, error); } } return bus; } #define CACHE_VALIDITY_SEC 2 typedef void (*CanDoFunc) (gint value); static void notify_can_do (DBusGProxy *proxy, DBusGProxyCall *call, void *user_data) { CanDoFunc callback = user_data; GError *error = NULL; gint value; if (dbus_g_proxy_end_call (proxy, call, &error, G_TYPE_INT, &value, G_TYPE_INVALID)) { callback (value); } } static void refresh_can_do (const gchar *action, CanDoFunc callback) { DBusGConnection *bus; DBusGProxy *proxy; bus = get_system_bus (NULL); if (bus == NULL) return; proxy = dbus_g_proxy_new_for_name (bus, "org.gnome.SettingsDaemon.DateTimeMechanism", "/", "org.gnome.SettingsDaemon.DateTimeMechanism"); dbus_g_proxy_begin_call_with_timeout (proxy, action, notify_can_do, callback, NULL, INT_MAX, G_TYPE_INVALID); } static gint settimezone_cache = 0; static time_t settimezone_stamp = 0; static void update_can_settimezone (gint res) { settimezone_cache = res; time (&settimezone_stamp); } gint can_set_system_timezone (void) { time_t now; time (&now); if (ABS (now - settimezone_stamp) > CACHE_VALIDITY_SEC) { refresh_can_do ("CanSetTimezone", update_can_settimezone); settimezone_stamp = now; } return settimezone_cache; } static gint settime_cache = 0; static time_t settime_stamp = 0; static void update_can_settime (gint res) { settime_cache = res; time (&settime_stamp); } gint can_set_system_time (void) { time_t now; time (&now); if (ABS (now - settime_stamp) > CACHE_VALIDITY_SEC) { refresh_can_do ("CanSetTime", update_can_settime); settime_stamp = now; } return settime_cache; } static gint usingntp_cache = 0; static time_t usingntp_stamp = 0; static void update_can_usingntp (gint res) { usingntp_cache = res; time (&usingntp_stamp); } gint can_set_using_ntp (void) { time_t now; time (&now); if (ABS (now - usingntp_stamp) > CACHE_VALIDITY_SEC) { refresh_can_do ("CanSetUsingNtp", update_can_usingntp); settime_stamp = now; } return usingntp_cache; } typedef struct { gint ref_count; gchar *call; gint64 time; gchar *tz; gboolean using_ntp; GFunc callback; gpointer data; GDestroyNotify notify; } SetTimeCallbackData; static void free_data (gpointer d) { SetTimeCallbackData *data = d; data->ref_count--; if (data->ref_count == 0) { if (data->notify) data->notify (data->data); g_free (data->tz); g_free (data); } } static void set_time_notify (DBusGProxy *proxy, DBusGProxyCall *call, void *user_data) { SetTimeCallbackData *data = user_data; GError *error = NULL; if (dbus_g_proxy_end_call (proxy, call, &error, G_TYPE_INVALID)) { if (data->callback) data->callback (data->data, NULL); } else { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_NO_REPLY) { /* these errors happen because dbus doesn't * use monotonic clocks */ g_warning ("ignoring no-reply error when setting time"); g_error_free (error); if (data->callback) data->callback (data->data, NULL); } else { if (data->callback) data->callback (data->data, error); else g_error_free (error); } } } static void set_time_async (SetTimeCallbackData *data) { DBusGConnection *bus; DBusGProxy *proxy; GError *err = NULL; bus = get_system_bus (&err); if (bus == NULL) { if (err) { if (data->callback) data->callback (data->data, err); g_clear_error (&err); } return; } proxy = dbus_g_proxy_new_for_name (bus, "org.gnome.SettingsDaemon.DateTimeMechanism", "/", "org.gnome.SettingsDaemon.DateTimeMechanism"); data->ref_count++; if (strcmp (data->call, "SetTime") == 0) dbus_g_proxy_begin_call_with_timeout (proxy, "SetTime", set_time_notify, data, free_data, INT_MAX, /* parameters: */ G_TYPE_INT64, data->time, G_TYPE_INVALID, /* return values: */ G_TYPE_INVALID); else if (strcmp (data->call, "SetTimezone") == 0) dbus_g_proxy_begin_call_with_timeout (proxy, "SetTimezone", set_time_notify, data, free_data, INT_MAX, /* parameters: */ G_TYPE_STRING, data->tz, G_TYPE_INVALID, /* return values: */ G_TYPE_INVALID); else if (strcmp (data->call, "SetUsingNtp") == 0) dbus_g_proxy_begin_call_with_timeout (proxy, "SetUsingNtp", set_time_notify, data, free_data, INT_MAX, /* parameters: */ G_TYPE_BOOLEAN, data->using_ntp, G_TYPE_INVALID, /* return values: */ G_TYPE_INVALID); } void set_system_time_async (gint64 time, GFunc callback, gpointer d, GDestroyNotify notify) { SetTimeCallbackData *data; if (time == -1) return; data = g_new0 (SetTimeCallbackData, 1); data->ref_count = 1; data->call = "SetTime"; data->time = time; data->tz = NULL; data->callback = callback; data->data = d; data->notify = notify; set_time_async (data); free_data (data); } void set_system_timezone_async (const gchar *tz, GFunc callback, gpointer d, GDestroyNotify notify) { SetTimeCallbackData *data; g_return_if_fail (tz != NULL); data = g_new0 (SetTimeCallbackData, 1); data->ref_count = 1; data->call = "SetTimezone"; data->time = -1; data->tz = g_strdup (tz); data->callback = callback; data->data = d; data->notify = notify; set_time_async (data); free_data (data); } /* get timezone */ typedef struct { GetTimezoneFunc callback; GDestroyNotify notify; gpointer data; } GetTimezoneData; static void get_timezone_destroy_notify (GetTimezoneData *data) { if (data->notify && data->data) data->notify (data); g_free (data); } static void get_timezone_notify (DBusGProxy *proxy, DBusGProxyCall *call, void *user_data) { GError *error = NULL; gboolean retval; gchar *string = NULL; GetTimezoneData *data = user_data; retval = dbus_g_proxy_end_call (proxy, call, &error, G_TYPE_STRING, &string, G_TYPE_INVALID); if (data->callback) { if (!retval) { data->callback (data->data, NULL, error); g_error_free (error); } else { data->callback (data->data, string, NULL); g_free (string); } } } void get_system_timezone_async (GetTimezoneFunc callback, gpointer user_data, GDestroyNotify notify) { DBusGConnection *bus; DBusGProxy *proxy; GetTimezoneData *data; GError *error = NULL; bus = get_system_bus (&error); if (bus == NULL) { if (error) { if (callback) callback (user_data, NULL, error); g_clear_error (&error); } return; } data = g_new0 (GetTimezoneData, 1); data->data = user_data; data->notify = notify; data->callback = callback; proxy = dbus_g_proxy_new_for_name (bus, "org.gnome.SettingsDaemon.DateTimeMechanism", "/", "org.gnome.SettingsDaemon.DateTimeMechanism"); dbus_g_proxy_begin_call (proxy, "GetTimezone", get_timezone_notify, data, (GDestroyNotify) get_timezone_destroy_notify, /* parameters: */ G_TYPE_INVALID, /* return values: */ G_TYPE_STRING, G_TYPE_INVALID); } gboolean get_using_ntp (void) { static gboolean is_using_cache = FALSE; static time_t last_refreshed = 0; time_t now; DBusGConnection *bus; DBusGProxy *proxy; time (&now); if (ABS (now - last_refreshed) > CACHE_VALIDITY_SEC) { gboolean cu, iu; bus = get_system_bus (NULL); if (bus == NULL) return FALSE; proxy = dbus_g_proxy_new_for_name (bus, "org.gnome.SettingsDaemon.DateTimeMechanism", "/", "org.gnome.SettingsDaemon.DateTimeMechanism"); if (dbus_g_proxy_call (proxy, "GetUsingNtp", NULL, G_TYPE_INVALID, G_TYPE_BOOLEAN, &cu, G_TYPE_BOOLEAN, &iu, G_TYPE_INVALID)) { is_using_cache = iu; last_refreshed = now; } } return is_using_cache; } void set_using_ntp_async (gboolean using_ntp, GFunc callback, gpointer d, GDestroyNotify notify) { SetTimeCallbackData *data; data = g_new0 (SetTimeCallbackData, 1); data->ref_count = 1; data->call = "SetUsingNtp"; data->time = -1; data->using_ntp = using_ntp; data->callback = callback; data->data = d; data->notify = notify; set_time_async (data); free_data (data); }
419
./cinnamon-control-center/panels/unused/datetime/cc-timezone-map.c
/* * Copyright (C) 2010 Intel, Inc * * Portions from Ubiquity, Copyright (C) 2009 Canonical Ltd. * Written by Evan Dandrea <evand@ubuntu.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include "cc-timezone-map.h" #include <math.h> #include <string.h> #include "tz.h" G_DEFINE_TYPE (CcTimezoneMap, cc_timezone_map, GTK_TYPE_WIDGET) #define TIMEZONE_MAP_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_TIMEZONE_MAP, CcTimezoneMapPrivate)) typedef struct { gdouble offset; guchar red; guchar green; guchar blue; guchar alpha; } CcTimezoneMapOffset; struct _CcTimezoneMapPrivate { GdkPixbuf *orig_background; GdkPixbuf *orig_background_dim; GdkPixbuf *orig_color_map; GdkPixbuf *background; GdkPixbuf *color_map; guchar *visible_map_pixels; gint visible_map_rowstride; gdouble selected_offset; TzDB *tzdb; TzLocation *location; }; enum { LOCATION_CHANGED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL]; static CcTimezoneMapOffset color_codes[] = { {-11.0, 43, 0, 0, 255 }, {-10.0, 85, 0, 0, 255 }, {-9.5, 102, 255, 0, 255 }, {-9.0, 128, 0, 0, 255 }, {-8.0, 170, 0, 0, 255 }, {-7.0, 212, 0, 0, 255 }, {-6.0, 255, 0, 1, 255 }, // north {-6.0, 255, 0, 0, 255 }, // south {-5.0, 255, 42, 42, 255 }, {-4.5, 192, 255, 0, 255 }, {-4.0, 255, 85, 85, 255 }, {-3.5, 0, 255, 0, 255 }, {-3.0, 255, 128, 128, 255 }, {-2.0, 255, 170, 170, 255 }, {-1.0, 255, 213, 213, 255 }, {0.0, 43, 17, 0, 255 }, {1.0, 85, 34, 0, 255 }, {2.0, 128, 51, 0, 255 }, {3.0, 170, 68, 0, 255 }, {3.5, 0, 255, 102, 255 }, {4.0, 212, 85, 0, 255 }, {4.5, 0, 204, 255, 255 }, {5.0, 255, 102, 0, 255 }, {5.5, 0, 102, 255, 255 }, {5.75, 0, 238, 207, 247 }, {6.0, 255, 127, 42, 255 }, {6.5, 204, 0, 254, 254 }, {7.0, 255, 153, 85, 255 }, {8.0, 255, 179, 128, 255 }, {9.0, 255, 204, 170, 255 }, {9.5, 170, 0, 68, 250 }, {10.0, 255, 230, 213, 255 }, {10.5, 212, 124, 21, 250 }, {11.0, 212, 170, 0, 255 }, {11.5, 249, 25, 87, 253 }, {12.0, 255, 204, 0, 255 }, {12.75, 254, 74, 100, 248 }, {13.0, 255, 85, 153, 250 }, {-100, 0, 0, 0, 0 } }; static void cc_timezone_map_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_timezone_map_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_timezone_map_dispose (GObject *object) { CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (object)->priv; g_clear_object (&priv->orig_background); g_clear_object (&priv->orig_background_dim); if (priv->orig_color_map) { g_object_unref (priv->orig_color_map); priv->orig_color_map = NULL; } if (priv->background) { g_object_unref (priv->background); priv->background = NULL; } if (priv->color_map) { g_object_unref (priv->color_map); priv->color_map = NULL; priv->visible_map_pixels = NULL; priv->visible_map_rowstride = 0; } G_OBJECT_CLASS (cc_timezone_map_parent_class)->dispose (object); } static void cc_timezone_map_finalize (GObject *object) { CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (object)->priv; if (priv->tzdb) { tz_db_free (priv->tzdb); priv->tzdb = NULL; } G_OBJECT_CLASS (cc_timezone_map_parent_class)->finalize (object); } /* GtkWidget functions */ static void cc_timezone_map_get_preferred_width (GtkWidget *widget, gint *minimum, gint *natural) { /* choose a minimum size small enough to prevent the window * from growing horizontally */ if (minimum != NULL) *minimum = 300; if (natural != NULL) *natural = 300; } static void cc_timezone_map_get_preferred_height (GtkWidget *widget, gint *minimum, gint *natural) { CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (widget)->priv; gint size; /* The + 20 here is a slight tweak to make the map fill the * panel better without causing horizontal growing */ size = 300 * gdk_pixbuf_get_height (priv->orig_background) / gdk_pixbuf_get_width (priv->orig_background) + 20; if (minimum != NULL) *minimum = size; if (natural != NULL) *natural = size; } static void cc_timezone_map_size_allocate (GtkWidget *widget, GtkAllocation *allocation) { CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (widget)->priv; GdkPixbuf *pixbuf; if (priv->background) g_object_unref (priv->background); if (!gtk_widget_is_sensitive (widget)) pixbuf = priv->orig_background_dim; else pixbuf = priv->orig_background; priv->background = gdk_pixbuf_scale_simple (pixbuf, allocation->width, allocation->height, GDK_INTERP_BILINEAR); if (priv->color_map) g_object_unref (priv->color_map); priv->color_map = gdk_pixbuf_scale_simple (priv->orig_color_map, allocation->width, allocation->height, GDK_INTERP_BILINEAR); priv->visible_map_pixels = gdk_pixbuf_get_pixels (priv->color_map); priv->visible_map_rowstride = gdk_pixbuf_get_rowstride (priv->color_map); GTK_WIDGET_CLASS (cc_timezone_map_parent_class)->size_allocate (widget, allocation); } static void cc_timezone_map_realize (GtkWidget *widget) { GdkWindowAttr attr = { 0, }; GtkAllocation allocation; GdkWindow *window; gtk_widget_get_allocation (widget, &allocation); gtk_widget_set_realized (widget, TRUE); attr.window_type = GDK_WINDOW_CHILD; attr.wclass = GDK_INPUT_OUTPUT; attr.width = allocation.width; attr.height = allocation.height; attr.x = allocation.x; attr.y = allocation.y; attr.event_mask = gtk_widget_get_events (widget) | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK; window = gdk_window_new (gtk_widget_get_parent_window (widget), &attr, GDK_WA_X | GDK_WA_Y); gdk_window_set_user_data (window, widget); gtk_widget_set_window (widget, window); } static gdouble convert_longtitude_to_x (gdouble longitude, gint map_width) { const gdouble xdeg_offset = -6; gdouble x; x = (map_width * (180.0 + longitude) / 360.0) + (map_width * xdeg_offset / 180.0); return x; } static gdouble radians (gdouble degrees) { return (degrees / 360.0) * G_PI * 2; } static gdouble convert_latitude_to_y (gdouble latitude, gdouble map_height) { gdouble bottom_lat = -59; gdouble top_lat = 81; gdouble top_per, y, full_range, top_offset, map_range; top_per = top_lat / 180.0; y = 1.25 * log (tan (G_PI_4 + 0.4 * radians (latitude))); full_range = 4.6068250867599998; top_offset = full_range * top_per; map_range = fabs (1.25 * log (tan (G_PI_4 + 0.4 * radians (bottom_lat))) - top_offset); y = fabs (y - top_offset); y = y / map_range; y = y * map_height; return y; } static gboolean cc_timezone_map_draw (GtkWidget *widget, cairo_t *cr) { CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (widget)->priv; GdkPixbuf *hilight, *orig_hilight, *pin; GtkAllocation alloc; gchar *file; GError *err = NULL; gdouble pointx, pointy; char buf[16]; const char *fmt; gtk_widget_get_allocation (widget, &alloc); /* paint background */ gdk_cairo_set_source_pixbuf (cr, priv->background, 0, 0); cairo_paint (cr); /* paint hilight */ if (gtk_widget_is_sensitive (widget)) fmt = DATADIR "/timezone_%s.png"; else fmt = DATADIR "/timezone_%s_dim.png"; file = g_strdup_printf (fmt, g_ascii_formatd (buf, sizeof (buf), "%g", priv->selected_offset)); orig_hilight = gdk_pixbuf_new_from_file (file, &err); g_free (file); file = NULL; if (!orig_hilight) { g_warning ("Could not load hilight: %s", (err) ? err->message : "Unknown Error"); if (err) g_clear_error (&err); } else { hilight = gdk_pixbuf_scale_simple (orig_hilight, alloc.width, alloc.height, GDK_INTERP_BILINEAR); gdk_cairo_set_source_pixbuf (cr, hilight, 0, 0); cairo_paint (cr); g_object_unref (hilight); g_object_unref (orig_hilight); } /* load pin icon */ pin = gdk_pixbuf_new_from_file (DATADIR "/pin.png", &err); if (err) { g_warning ("Could not load pin icon: %s", err->message); g_clear_error (&err); } if (priv->location) { pointx = convert_longtitude_to_x (priv->location->longitude, alloc.width); pointy = convert_latitude_to_y (priv->location->latitude, alloc.height); if (pointy > alloc.height) pointy = alloc.height; if (pin) { gdk_cairo_set_source_pixbuf (cr, pin, pointx - 8, pointy - 14); cairo_paint (cr); } } if (pin) { g_object_unref (pin); } return TRUE; } static void update_cursor (GtkWidget *widget) { GdkWindow *window; GdkCursor *cursor = NULL; if (!gtk_widget_get_realized (widget)) return; if (gtk_widget_is_sensitive (widget)) { GdkDisplay *display; display = gtk_widget_get_display (widget); cursor = gdk_cursor_new_for_display (display, GDK_HAND2); } window = gtk_widget_get_window (widget); gdk_window_set_cursor (window, cursor); if (cursor) g_object_unref (cursor); } static void cc_timezone_map_state_flags_changed (GtkWidget *widget, GtkStateFlags prev_state) { update_cursor (widget); if (GTK_WIDGET_CLASS (cc_timezone_map_parent_class)->state_flags_changed) GTK_WIDGET_CLASS (cc_timezone_map_parent_class)->state_flags_changed (widget, prev_state); } static void cc_timezone_map_class_init (CcTimezoneMapClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); g_type_class_add_private (klass, sizeof (CcTimezoneMapPrivate)); object_class->get_property = cc_timezone_map_get_property; object_class->set_property = cc_timezone_map_set_property; object_class->dispose = cc_timezone_map_dispose; object_class->finalize = cc_timezone_map_finalize; widget_class->get_preferred_width = cc_timezone_map_get_preferred_width; widget_class->get_preferred_height = cc_timezone_map_get_preferred_height; widget_class->size_allocate = cc_timezone_map_size_allocate; widget_class->realize = cc_timezone_map_realize; widget_class->draw = cc_timezone_map_draw; widget_class->state_flags_changed = cc_timezone_map_state_flags_changed; signals[LOCATION_CHANGED] = g_signal_new ("location-changed", CC_TYPE_TIMEZONE_MAP, G_SIGNAL_RUN_FIRST, 0, NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); } static gint sort_locations (TzLocation *a, TzLocation *b) { if (a->dist > b->dist) return 1; if (a->dist < b->dist) return -1; return 0; } static void set_location (CcTimezoneMap *map, TzLocation *location) { CcTimezoneMapPrivate *priv = map->priv; TzInfo *info; priv->location = location; info = tz_info_from_location (priv->location); priv->selected_offset = tz_location_get_utc_offset (priv->location) / (60.0*60.0) + ((info->daylight) ? -1.0 : 0.0); g_signal_emit (map, signals[LOCATION_CHANGED], 0, priv->location); tz_info_free (info); } static gboolean button_press_event (GtkWidget *widget, GdkEventButton *event) { CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (widget)->priv; gint x, y; guchar r, g, b, a; guchar *pixels; gint rowstride; gint i; const GPtrArray *array; gint width, height; GList *distances = NULL; GtkAllocation alloc; x = event->x; y = event->y; rowstride = priv->visible_map_rowstride; pixels = priv->visible_map_pixels; r = pixels[(rowstride * y + x * 4)]; g = pixels[(rowstride * y + x * 4) + 1]; b = pixels[(rowstride * y + x * 4) + 2]; a = pixels[(rowstride * y + x * 4) + 3]; for (i = 0; color_codes[i].offset != -100; i++) { if (color_codes[i].red == r && color_codes[i].green == g && color_codes[i].blue == b && color_codes[i].alpha == a) { priv->selected_offset = color_codes[i].offset; } } gtk_widget_queue_draw (widget); /* work out the co-ordinates */ array = tz_get_locations (priv->tzdb); gtk_widget_get_allocation (widget, &alloc); width = alloc.width; height = alloc.height; for (i = 0; i < array->len; i++) { gdouble pointx, pointy, dx, dy; TzLocation *loc = array->pdata[i]; pointx = convert_longtitude_to_x (loc->longitude, width); pointy = convert_latitude_to_y (loc->latitude, height); dx = pointx - x; dy = pointy - y; loc->dist = dx * dx + dy * dy; distances = g_list_prepend (distances, loc); } distances = g_list_sort (distances, (GCompareFunc) sort_locations); set_location (CC_TIMEZONE_MAP (widget), (TzLocation*) distances->data); g_list_free (distances); return TRUE; } static void cc_timezone_map_init (CcTimezoneMap *self) { CcTimezoneMapPrivate *priv; GError *err = NULL; priv = self->priv = TIMEZONE_MAP_PRIVATE (self); priv->orig_background = gdk_pixbuf_new_from_file (DATADIR "/bg.png", &err); if (!priv->orig_background) { g_warning ("Could not load background image: %s", (err) ? err->message : "Unknown error"); g_clear_error (&err); } priv->orig_background_dim = gdk_pixbuf_new_from_file (DATADIR "/bg_dim.png", &err); if (!priv->orig_background_dim) { g_warning ("Could not load background image: %s", (err) ? err->message : "Unknown error"); g_clear_error (&err); } priv->orig_color_map = gdk_pixbuf_new_from_file (DATADIR "/cc.png", &err); if (!priv->orig_color_map) { g_warning ("Could not load background image: %s", (err) ? err->message : "Unknown error"); g_clear_error (&err); } priv->tzdb = tz_load_db (); g_signal_connect (self, "button-press-event", G_CALLBACK (button_press_event), NULL); } CcTimezoneMap * cc_timezone_map_new (void) { return g_object_new (CC_TYPE_TIMEZONE_MAP, NULL); } gboolean cc_timezone_map_set_timezone (CcTimezoneMap *map, const gchar *timezone) { GPtrArray *locations; guint i; char *real_tz; gboolean ret; real_tz = tz_info_get_clean_name (map->priv->tzdb, timezone); locations = tz_get_locations (map->priv->tzdb); ret = FALSE; for (i = 0; i < locations->len; i++) { TzLocation *loc = locations->pdata[i]; if (!g_strcmp0 (loc->zone, real_tz ? real_tz : timezone)) { set_location (map, loc); ret = TRUE; break; } } if (ret) gtk_widget_queue_draw (GTK_WIDGET (map)); g_free (real_tz); return ret; } TzLocation * cc_timezone_map_get_location (CcTimezoneMap *map) { return map->priv->location; }
420
./cinnamon-control-center/panels/unused/datetime/date-endian.c
/* * Copyright (C) 2011 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Bastien Nocera <hadess@hadess.net> * */ #include <langinfo.h> #include <locale.h> #include <glib.h> #include <string.h> #include "date-endian.h" /* We default to returning DATE_ENDIANESS_MIDDLE because that's * what 3.2 billion people use */ #define DEFAULT_ENDIANESS DATE_ENDIANESS_LITTLE typedef enum { ITEM_NONE = 0, ITEM_DAY, ITEM_MONTH, ITEM_YEAR } Item; static gboolean has_item (Item *items, Item item) { guint i; for (i = 0; i < 3; i++) { if (items[i] == ITEM_NONE) return FALSE; if (items[i] == item) return TRUE; } return FALSE; } DateEndianess date_endian_get_default (gboolean verbose) { const char *fmt; const char *p; Item items[3]; guint i; fmt = nl_langinfo (D_FMT); g_return_val_if_fail (fmt != NULL, DEFAULT_ENDIANESS); if (verbose) g_print ("%s", fmt); if (g_str_equal (fmt, "%F")) return DATE_ENDIANESS_BIG; i = 0; memset (&items, 0, sizeof(items)); /* Assume ASCII only */ for (p = fmt; *p != '\0'; p++) { char c; /* Look for '%' */ if (*p != '%') continue; /* Only assert when we're sure we don't have another '%' */ if (i >= 4) { g_warning ("Could not parse format '%s', too many formats", fmt); return DEFAULT_ENDIANESS; } c = *(p + 1); /* Ignore alternative formats */ if (c == 'O' || c == '-' || c == 'E') c = *(p + 2); if (c == '\0') { g_warning ("Count not parse format '%s', unterminated '%%'", fmt); return DEFAULT_ENDIANESS; } switch (c) { case 'd': case 'e': if (has_item (items, ITEM_DAY) == FALSE) { items[i] = ITEM_DAY; i++; } break; case 'm': case 'b': case 'B': if (has_item (items, ITEM_MONTH) == FALSE) { items[i] = ITEM_MONTH; i++; } break; case 'y': case 'Y': if (has_item (items, ITEM_YEAR) == FALSE) { items[i] = ITEM_YEAR; i++; } break; case 'A': case 'a': /* Ignore */ ; } } if (items[0] == ITEM_DAY && items[1] == ITEM_MONTH && items[2] == ITEM_YEAR) return DATE_ENDIANESS_LITTLE; if (items[0] == ITEM_YEAR && items[1] == ITEM_MONTH && items[2] == ITEM_DAY) return DATE_ENDIANESS_BIG; if (items[0] == ITEM_MONTH && items[1] == ITEM_DAY && items[2] == ITEM_YEAR) return DATE_ENDIANESS_MIDDLE; g_warning ("Could not parse format '%s'", fmt); return DEFAULT_ENDIANESS; } DateEndianess date_endian_get_for_lang (const char *lang, gboolean verbose) { const char *old_lang; DateEndianess endian; old_lang = setlocale (LC_TIME, lang); endian = date_endian_get_default (verbose); setlocale (LC_TIME, old_lang); return endian; } const char * date_endian_to_string (DateEndianess endianess) { switch (endianess) { case DATE_ENDIANESS_LITTLE: return "Little (DD-MM-YYYY)"; case DATE_ENDIANESS_BIG: return "Big (YYYY-MM-DD)"; case DATE_ENDIANESS_MIDDLE: return "Middle (MM-DD-YYYY)"; default: g_assert_not_reached (); } }
421
./cinnamon-control-center/panels/unused/datetime/cc-datetime-panel.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include "config.h" #include "cc-datetime-panel.h" #include <sys/time.h> #include "cc-timezone-map.h" #include "dtm.h" #include "date-endian.h" #define GNOME_DESKTOP_USE_UNSTABLE_API #include <gdesktop-enums.h> #include <string.h> #include <stdlib.h> #include <libintl.h> #include <libgnome-desktop/gnome-wall-clock.h> #include <polkit/polkit.h> /* FIXME: This should be "Etc/GMT" instead */ #define DEFAULT_TZ "Europe/London" #define GETTEXT_PACKAGE_TIMEZONES GETTEXT_PACKAGE "-timezones" CC_PANEL_REGISTER (CcDateTimePanel, cc_date_time_panel) #define DATE_TIME_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_DATE_TIME_PANEL, CcDateTimePanelPrivate)) enum { CITY_COL_CITY, CITY_COL_REGION, CITY_COL_CITY_TRANSLATED, CITY_COL_REGION_TRANSLATED, CITY_COL_ZONE, CITY_NUM_COLS }; enum { REGION_COL_REGION, REGION_COL_REGION_TRANSLATED, REGION_NUM_COLS }; #define W(x) (GtkWidget*) gtk_builder_get_object (priv->builder, x) #define CLOCK_SCHEMA "org.gnome.desktop.interface" #define CLOCK_FORMAT_KEY "clock-format" struct _CcDateTimePanelPrivate { GtkBuilder *builder; GtkWidget *map; TzLocation *current_location; GtkTreeModel *locations; GtkTreeModelFilter *city_filter; GDateTime *date; GSettings *settings; GDesktopClockFormat clock_format; GnomeWallClock *clock_tracker; DateTimeMechanism *dtm; GCancellable *cancellable; GPermission *permission; }; static void update_time (CcDateTimePanel *self); static void cc_date_time_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_date_time_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_date_time_panel_dispose (GObject *object) { CcDateTimePanelPrivate *priv = CC_DATE_TIME_PANEL (object)->priv; if (priv->clock_tracker != NULL) { g_object_unref (priv->clock_tracker); priv->clock_tracker = NULL; } if (priv->builder) { g_object_unref (priv->builder); priv->builder = NULL; } if (priv->settings) { g_object_unref (priv->settings); priv->settings = NULL; } if (priv->date) { g_date_time_unref (priv->date); priv->date = NULL; } if (priv->cancellable) { g_cancellable_cancel (priv->cancellable); g_object_unref (priv->cancellable); priv->cancellable = NULL; } if (priv->dtm) { g_object_unref (priv->dtm); priv->dtm = NULL; } if (priv->permission) { g_object_unref (priv->permission); priv->permission = NULL; } G_OBJECT_CLASS (cc_date_time_panel_parent_class)->dispose (object); } static GPermission * cc_date_time_panel_get_permission (CcPanel *panel) { CcDateTimePanelPrivate *priv = CC_DATE_TIME_PANEL (panel)->priv; return priv->permission; } static const char * cc_date_time_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/clock"; else return "help:gnome-help/clock"; } static void cc_date_time_panel_class_init (CcDateTimePanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcDateTimePanelPrivate)); object_class->get_property = cc_date_time_panel_get_property; object_class->set_property = cc_date_time_panel_set_property; object_class->dispose = cc_date_time_panel_dispose; panel_class->get_permission = cc_date_time_panel_get_permission; panel_class->get_help_uri = cc_date_time_panel_get_help_uri; } static void clock_settings_changed_cb (GSettings *settings, gchar *key, CcDateTimePanel *panel); static void change_clock_settings (GObject *gobject, GParamSpec *pspec, CcDateTimePanel *panel) { CcDateTimePanelPrivate *priv = panel->priv; GDesktopClockFormat value; g_signal_handlers_block_by_func (priv->settings, clock_settings_changed_cb, panel); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (W ("24h_button")))) value = G_DESKTOP_CLOCK_FORMAT_24H; else value = G_DESKTOP_CLOCK_FORMAT_12H; g_settings_set_enum (priv->settings, CLOCK_FORMAT_KEY, value); priv->clock_format = value; update_time (panel); g_signal_handlers_unblock_by_func (priv->settings, clock_settings_changed_cb, panel); } static void clock_settings_changed_cb (GSettings *settings, gchar *key, CcDateTimePanel *panel) { CcDateTimePanelPrivate *priv = panel->priv; GtkWidget *button24h; GtkWidget *button12h; GDesktopClockFormat value; value = g_settings_get_enum (settings, CLOCK_FORMAT_KEY); priv->clock_format = value; button24h = W ("24h_button"); button12h = W ("12h_button"); g_signal_handlers_block_by_func (button24h, change_clock_settings, panel); if (value == G_DESKTOP_CLOCK_FORMAT_24H) gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button24h), TRUE); else gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button12h), TRUE); update_time (panel); g_signal_handlers_unblock_by_func (button24h, change_clock_settings, panel); } static void update_time (CcDateTimePanel *self) { CcDateTimePanelPrivate *priv = self->priv; char *label; char *am_pm_widgets[] = {"ampm_up_button", "ampm_down_button", "ampm_label" }; guint i; if (priv->clock_format == G_DESKTOP_CLOCK_FORMAT_24H) { /* Update the hours label */ label = g_date_time_format (priv->date, "%H"); gtk_label_set_text (GTK_LABEL (W("hours_label")), label); g_free (label); } else { /* Update the hours label */ label = g_date_time_format (priv->date, "%I"); gtk_label_set_text (GTK_LABEL (W("hours_label")), label); g_free (label); /* Set AM/PM */ label = g_date_time_format (priv->date, "%p"); gtk_label_set_text (GTK_LABEL (W("ampm_label")), label); g_free (label); } for (i = 0; i < G_N_ELEMENTS (am_pm_widgets); i++) gtk_widget_set_visible (W(am_pm_widgets[i]), priv->clock_format == G_DESKTOP_CLOCK_FORMAT_12H); /* Update the minutes label */ label = g_date_time_format (priv->date, "%M"); gtk_label_set_text (GTK_LABEL (W("minutes_label")), label); g_free (label); } static void set_time_cb (GObject *source, GAsyncResult *res, gpointer user_data) { CcDateTimePanel *self = user_data; GError *error; error = NULL; if (!date_time_mechanism_call_set_time_finish (self->priv->dtm, res, &error)) { /* TODO: display any error in a user friendly way */ g_warning ("Could not set system time: %s", error->message); g_error_free (error); } else { update_time (self); } } static void set_timezone_cb (GObject *source, GAsyncResult *res, gpointer user_data) { CcDateTimePanel *self = user_data; GError *error; error = NULL; if (!date_time_mechanism_call_set_timezone_finish (self->priv->dtm, res, &error)) { /* TODO: display any error in a user friendly way */ g_warning ("Could not set system timezone: %s", error->message); g_error_free (error); } } static void set_using_ntp_cb (GObject *source, GAsyncResult *res, gpointer user_data) { CcDateTimePanel *self = user_data; GError *error; error = NULL; if (!date_time_mechanism_call_set_using_ntp_finish (self->priv->dtm, res, &error)) { /* TODO: display any error in a user friendly way */ g_warning ("Could not set system to use NTP: %s", error->message); g_error_free (error); } } static void queue_set_datetime (CcDateTimePanel *self) { gint64 unixtime; /* for now just do it */ unixtime = g_date_time_to_unix (self->priv->date); date_time_mechanism_call_set_time (self->priv->dtm, unixtime, self->priv->cancellable, set_time_cb, self); } static void queue_set_ntp (CcDateTimePanel *self) { CcDateTimePanelPrivate *priv = self->priv; gboolean using_ntp; /* for now just do it */ using_ntp = gtk_switch_get_active (GTK_SWITCH (W("network_time_switch"))); date_time_mechanism_call_set_using_ntp (self->priv->dtm, using_ntp, self->priv->cancellable, set_using_ntp_cb, self); } static void queue_set_timezone (CcDateTimePanel *self) { /* for now just do it */ if (self->priv->current_location) { date_time_mechanism_call_set_timezone (self->priv->dtm, self->priv->current_location->zone, self->priv->cancellable, set_timezone_cb, self); } } static void change_date (CcDateTimePanel *self) { CcDateTimePanelPrivate *priv = self->priv; guint mon, y, d; GDateTime *old_date; old_date = priv->date; mon = 1 + gtk_combo_box_get_active (GTK_COMBO_BOX (W ("month-combobox"))); y = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (W ("year-spinbutton"))); d = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (W ("day-spinbutton"))); priv->date = g_date_time_new_local (y, mon, d, g_date_time_get_hour (old_date), g_date_time_get_minute (old_date), g_date_time_get_second (old_date)); g_date_time_unref (old_date); queue_set_datetime (self); } static void region_changed_cb (GtkComboBox *box, CcDateTimePanel *self) { GtkTreeModelFilter *modelfilter; modelfilter = GTK_TREE_MODEL_FILTER (gtk_builder_get_object (self->priv->builder, "city-modelfilter")); gtk_tree_model_filter_refilter (modelfilter); } static void city_changed_cb (GtkComboBox *box, CcDateTimePanel *self) { static gboolean inside = FALSE; GtkTreeIter iter; gchar *zone; /* prevent re-entry from location changed callback */ if (inside) return; inside = TRUE; if (gtk_combo_box_get_active_iter (box, &iter)) { gtk_tree_model_get (gtk_combo_box_get_model (box), &iter, CITY_COL_ZONE, &zone, -1); cc_timezone_map_set_timezone (CC_TIMEZONE_MAP (self->priv->map), zone); g_free (zone); } inside = FALSE; } static void update_timezone (CcDateTimePanel *self) { CcDateTimePanelPrivate *priv = self->priv; GtkWidget *widget; gchar **split; GtkTreeIter iter; GtkTreeModel *model; /* tz.c updates the local timezone, which means the spin buttons can be * updated with the current time of the new location */ split = g_strsplit (priv->current_location->zone, "/", 2); /* remove underscores */ g_strdelimit (split[1], "_", ' '); /* update region combo */ widget = (GtkWidget *) gtk_builder_get_object (priv->builder, "region_combobox"); model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget)); gtk_tree_model_get_iter_first (model, &iter); do { gchar *string; gtk_tree_model_get (model, &iter, CITY_COL_CITY, &string, -1); if (!g_strcmp0 (string, split[0])) { g_free (string); gtk_combo_box_set_active_iter (GTK_COMBO_BOX (widget), &iter); break; } g_free (string); } while (gtk_tree_model_iter_next (model, &iter)); /* update city combo */ widget = (GtkWidget *) gtk_builder_get_object (priv->builder, "city_combobox"); model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget)); gtk_tree_model_filter_refilter ((GtkTreeModelFilter *) gtk_builder_get_object (priv->builder, "city-modelfilter")); gtk_tree_model_get_iter_first (model, &iter); do { gchar *string; gtk_tree_model_get (model, &iter, CITY_COL_CITY, &string, -1); if (!g_strcmp0 (string, split[1])) { g_free (string); gtk_combo_box_set_active_iter (GTK_COMBO_BOX (widget), &iter); break; } g_free (string); } while (gtk_tree_model_iter_next (model, &iter)); g_strfreev (split); } static void location_changed_cb (CcTimezoneMap *map, TzLocation *location, CcDateTimePanel *self) { CcDateTimePanelPrivate *priv = self->priv; GtkWidget *region_combo, *city_combo; g_debug ("location changed to %s/%s", location->country, location->zone); self->priv->current_location = location; /* Update the combo boxes */ region_combo = W("region_combobox"); city_combo = W("city_combobox"); g_signal_handlers_block_by_func (region_combo, region_changed_cb, self); g_signal_handlers_block_by_func (city_combo, city_changed_cb, self); update_timezone (self); g_signal_handlers_unblock_by_func (region_combo, region_changed_cb, self); g_signal_handlers_unblock_by_func (city_combo, city_changed_cb, self); queue_set_timezone (self); } static void get_timezone_cb (GObject *source, GAsyncResult *res, gpointer user_data) { CcDateTimePanel *self = user_data; GtkWidget *widget; gchar *timezone; GError *error; error = NULL; if (!date_time_mechanism_call_get_timezone_finish (self->priv->dtm, &timezone, res, &error)) { g_warning ("Could not get current timezone: %s", error->message); g_error_free (error); } else { if (!cc_timezone_map_set_timezone (CC_TIMEZONE_MAP (self->priv->map), timezone)) { g_warning ("Timezone '%s' is unhandled, setting %s as default", timezone, DEFAULT_TZ); cc_timezone_map_set_timezone (CC_TIMEZONE_MAP (self->priv->map), DEFAULT_TZ); } self->priv->current_location = cc_timezone_map_get_location (CC_TIMEZONE_MAP (self->priv->map)); update_timezone (self); } /* now that the initial state is loaded set connect the signals */ widget = (GtkWidget*) gtk_builder_get_object (self->priv->builder, "region_combobox"); g_signal_connect (widget, "changed", G_CALLBACK (region_changed_cb), self); widget = (GtkWidget*) gtk_builder_get_object (self->priv->builder, "city_combobox"); g_signal_connect (widget, "changed", G_CALLBACK (city_changed_cb), self); g_signal_connect (self->priv->map, "location-changed", G_CALLBACK (location_changed_cb), self); g_free (timezone); } /* load region and city tree models */ struct get_region_data { GtkListStore *region_store; GtkListStore *city_store; GHashTable *table; }; /* Slash look-alikes that might be used in translations */ #define TRANSLATION_SPLIT \ "\342\201\204" /* FRACTION SLASH */ \ "\342\210\225" /* DIVISION SLASH */ \ "\342\247\270" /* BIG SOLIDUS */ \ "\357\274\217" /* FULLWIDTH SOLIDUS */ \ "/" static void get_regions (TzLocation *loc, struct get_region_data *data) { gchar *zone; gchar **split; gchar **split_translated; gchar *translated_city; zone = g_strdup (loc->zone); g_strdelimit (zone, "_", ' '); split = g_strsplit (zone, "/", 2); g_free (zone); /* Load the translation for it */ zone = g_strdup (dgettext (GETTEXT_PACKAGE_TIMEZONES, loc->zone)); g_strdelimit (zone, "_", ' '); split_translated = g_regex_split_simple ("[\\x{2044}\\x{2215}\\x{29f8}\\x{ff0f}/]", zone, 0, 0); g_free (zone); if (!g_hash_table_lookup_extended (data->table, split[0], NULL, NULL)) { g_hash_table_insert (data->table, g_strdup (split[0]), GINT_TO_POINTER (1)); gtk_list_store_insert_with_values (data->region_store, NULL, 0, REGION_COL_REGION, split[0], REGION_COL_REGION_TRANSLATED, split_translated[0], -1); } /* g_regex_split_simple() splits too much for us, and would break * America/Argentina/Buenos_Aires into 3 strings, so rejoin the city part */ translated_city = g_strjoinv ("/", split_translated + 1); gtk_list_store_insert_with_values (data->city_store, NULL, 0, CITY_COL_CITY, split[1], CITY_COL_CITY_TRANSLATED, translated_city, CITY_COL_REGION, split[0], CITY_COL_REGION_TRANSLATED, split_translated[0], CITY_COL_ZONE, loc->zone, -1); g_free (translated_city); g_strfreev (split); g_strfreev (split_translated); } static gboolean city_model_filter_func (GtkTreeModel *model, GtkTreeIter *iter, GtkComboBox *combo) { GtkTreeModel *combo_model; GtkTreeIter combo_iter; gchar *active_region = NULL; gchar *city_region = NULL; gboolean result; if (gtk_combo_box_get_active_iter (combo, &combo_iter) == FALSE) return FALSE; combo_model = gtk_combo_box_get_model (combo); gtk_tree_model_get (combo_model, &combo_iter, CITY_COL_CITY, &active_region, -1); gtk_tree_model_get (model, iter, CITY_COL_REGION, &city_region, -1); if (g_strcmp0 (active_region, city_region) == 0) result = TRUE; else result = FALSE; g_free (city_region); g_free (active_region); return result; } static void load_regions_model (GtkListStore *regions, GtkListStore *cities) { struct get_region_data data; TzDB *db; GHashTable *table; db = tz_load_db (); table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); data.table = table; data.region_store = regions; data.city_store = cities; g_ptr_array_foreach (db->locations, (GFunc) get_regions, &data); g_hash_table_destroy (table); tz_db_free (db); /* sort the models */ gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (regions), REGION_COL_REGION_TRANSLATED, GTK_SORT_ASCENDING); } static void update_widget_state_for_ntp (CcDateTimePanel *panel, gboolean using_ntp) { CcDateTimePanelPrivate *priv = panel->priv; gtk_widget_set_sensitive (W("table1"), !using_ntp); gtk_widget_set_sensitive (W("table2"), !using_ntp); } static void day_changed (GtkWidget *widget, CcDateTimePanel *panel) { change_date (panel); } static void month_year_changed (GtkWidget *widget, CcDateTimePanel *panel) { CcDateTimePanelPrivate *priv = panel->priv; guint mon, y; guint num_days; GtkAdjustment *adj; GtkSpinButton *day_spin; mon = 1 + gtk_combo_box_get_active (GTK_COMBO_BOX (W ("month-combobox"))); y = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (W ("year-spinbutton"))); /* Check the number of days in that month */ num_days = g_date_get_days_in_month (mon, y); day_spin = GTK_SPIN_BUTTON (W("day-spinbutton")); adj = GTK_ADJUSTMENT (gtk_spin_button_get_adjustment (day_spin)); gtk_adjustment_set_upper (adj, num_days + 1); if (gtk_spin_button_get_value_as_int (day_spin) > num_days) gtk_spin_button_set_value (day_spin, num_days); change_date (panel); } static void on_clock_changed (GnomeWallClock *clock, GParamSpec *pspec, CcDateTimePanel *panel) { CcDateTimePanelPrivate *priv = panel->priv; g_date_time_unref (priv->date); priv->date = g_date_time_new_now_local (); update_time (panel); } static void change_time (GtkButton *button, CcDateTimePanel *panel) { CcDateTimePanelPrivate *priv = panel->priv; const gchar *widget_name; gint direction; GDateTime *old_date; old_date = priv->date; widget_name = gtk_buildable_get_name (GTK_BUILDABLE (button)); if (strstr (widget_name, "up")) direction = 1; else direction = -1; if (widget_name[0] == 'h') { priv->date = g_date_time_add_hours (old_date, direction); } else if (widget_name[0] == 'm') { priv->date = g_date_time_add_minutes (old_date, direction); } else { int hour; hour = g_date_time_get_hour (old_date); if (hour >= 12) priv->date = g_date_time_add_hours (old_date, -12); else priv->date = g_date_time_add_hours (old_date, 12); } g_date_time_unref (old_date); update_time (panel); queue_set_datetime (panel); } static void change_ntp (GObject *gobject, GParamSpec *pspec, CcDateTimePanel *self) { update_widget_state_for_ntp (self, gtk_switch_get_active (GTK_SWITCH (gobject))); queue_set_ntp (self); } static void on_permission_changed (GPermission *permission, GParamSpec *pspec, gpointer data) { CcDateTimePanelPrivate *priv = CC_DATE_TIME_PANEL (data)->priv; gboolean allowed, using_ntp; allowed = g_permission_get_allowed (permission); using_ntp = gtk_switch_get_active (GTK_SWITCH (W("network_time_switch"))); /* All the widgets but the lock button and the 24h setting */ gtk_widget_set_sensitive (W("map-vbox"), allowed); gtk_widget_set_sensitive (W("hbox2"), allowed); gtk_widget_set_sensitive (W("alignment2"), allowed); gtk_widget_set_sensitive (W("table1"), allowed && !using_ntp); } static void reorder_date_widget (DateEndianess endianess, CcDateTimePanelPrivate *priv) { GtkWidget *month, *day, *year; GtkBox *box; if (endianess == DATE_ENDIANESS_MIDDLE) return; month = W ("month-combobox"); day = W ("day-spinbutton"); year = W("year-spinbutton"); box = GTK_BOX (W("table1")); switch (endianess) { case DATE_ENDIANESS_LITTLE: gtk_box_reorder_child (box, month, 0); gtk_box_reorder_child (box, day, 0); gtk_box_reorder_child (box, year, -1); break; case DATE_ENDIANESS_BIG: gtk_box_reorder_child (box, month, 0); gtk_box_reorder_child (box, year, 0); gtk_box_reorder_child (box, day, -1); break; case DATE_ENDIANESS_MIDDLE: /* Let's please GCC */ g_assert_not_reached (); break; } } static void cc_date_time_panel_init (CcDateTimePanel *self) { CcDateTimePanelPrivate *priv; gchar *objects[] = { "datetime-panel", "region-liststore", "city-liststore", "month-liststore", "city-modelfilter", "city-modelsort", NULL }; char *buttons[] = { "hour_up_button", "hour_down_button", "min_up_button", "min_down_button", "ampm_up_button", "ampm_down_button" }; GtkWidget *widget; GtkAdjustment *adjustment; GError *err = NULL; GtkTreeModelFilter *city_modelfilter; GtkTreeModelSort *city_modelsort; guint i, num_days; gboolean using_ntp; gboolean can_use_ntp; int ret; DateEndianess endianess; GError *error; priv = self->priv = DATE_TIME_PANEL_PRIVATE (self); priv->cancellable = g_cancellable_new (); error = NULL; priv->dtm = date_time_mechanism_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, "org.gnome.SettingsDaemon.DateTimeMechanism", "/", priv->cancellable, &error); if (priv->dtm == NULL) { g_warning ("could not get proxy for DateTimeMechanism: %s", error->message); g_error_free (error); } priv->builder = gtk_builder_new (); ret = gtk_builder_add_objects_from_file (priv->builder, DATADIR"/datetime.ui", objects, &err); if (ret == 0) { g_warning ("Could not load ui: %s", err ? err->message : "No reason"); if (err) g_error_free (err); return; } /* set up network time button */ error = NULL; using_ntp = can_use_ntp = FALSE; if (!date_time_mechanism_call_get_using_ntp_sync (priv->dtm, &can_use_ntp, &using_ntp, priv->cancellable, &error)) { g_warning ("Failed to get using ntp: %s", error->message); g_error_free (error); } gtk_switch_set_active (GTK_SWITCH (W("network_time_switch")), using_ntp); update_widget_state_for_ntp (self, using_ntp); g_signal_connect (W("network_time_switch"), "notify::active", G_CALLBACK (change_ntp), self); /* set up time editing widgets */ for (i = 0; i < G_N_ELEMENTS (buttons); i++) { g_signal_connect (W(buttons[i]), "clicked", G_CALLBACK (change_time), self); } /* set up date editing widgets */ priv->date = g_date_time_new_now_local (); endianess = date_endian_get_default (FALSE); reorder_date_widget (endianess, priv); /* Force the direction for the time, so that the time * is presented correctly for RTL languages */ gtk_widget_set_direction (W("table2"), GTK_TEXT_DIR_LTR); gtk_combo_box_set_active (GTK_COMBO_BOX (W ("month-combobox")), g_date_time_get_month (priv->date) - 1); g_signal_connect (G_OBJECT (W("month-combobox")), "changed", G_CALLBACK (month_year_changed), self); num_days = g_date_get_days_in_month (g_date_time_get_month (priv->date), g_date_time_get_year (priv->date)); adjustment = (GtkAdjustment*) gtk_adjustment_new (g_date_time_get_day_of_month (priv->date), 1, num_days + 1, 1, 10, 1); gtk_spin_button_set_adjustment (GTK_SPIN_BUTTON (W ("day-spinbutton")), adjustment); g_signal_connect (G_OBJECT (W("day-spinbutton")), "value-changed", G_CALLBACK (day_changed), self); adjustment = (GtkAdjustment*) gtk_adjustment_new (g_date_time_get_year (priv->date), G_MINDOUBLE, G_MAXDOUBLE, 1, 10, 1); gtk_spin_button_set_adjustment (GTK_SPIN_BUTTON (W ("year-spinbutton")), adjustment); g_signal_connect (G_OBJECT (W("year-spinbutton")), "value-changed", G_CALLBACK (month_year_changed), self); /* set up timezone map */ priv->map = widget = (GtkWidget *) cc_timezone_map_new (); gtk_widget_show (widget); gtk_container_add (GTK_CONTAINER (gtk_builder_get_object (priv->builder, "aspectmap")), widget); gtk_container_add (GTK_CONTAINER (self), GTK_WIDGET (gtk_builder_get_object (priv->builder, "datetime-panel"))); /* setup the time itself */ priv->clock_tracker = g_object_new (GNOME_TYPE_WALL_CLOCK, NULL); g_signal_connect (priv->clock_tracker, "notify::clock", G_CALLBACK (on_clock_changed), self); priv->settings = g_settings_new (CLOCK_SCHEMA); clock_settings_changed_cb (priv->settings, CLOCK_FORMAT_KEY, self); g_signal_connect (priv->settings, "changed::" CLOCK_FORMAT_KEY, G_CALLBACK (clock_settings_changed_cb), self); g_signal_connect (W("24h_button"), "notify::active", G_CALLBACK (change_clock_settings), self); update_time (self); priv->locations = (GtkTreeModel*) gtk_builder_get_object (priv->builder, "region-liststore"); load_regions_model (GTK_LIST_STORE (priv->locations), GTK_LIST_STORE (gtk_builder_get_object (priv->builder, "city-liststore"))); city_modelfilter = GTK_TREE_MODEL_FILTER (gtk_builder_get_object (priv->builder, "city-modelfilter")); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "region_combobox"); city_modelsort = GTK_TREE_MODEL_SORT (gtk_builder_get_object (priv->builder, "city-modelsort")); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (city_modelsort), CITY_COL_CITY_TRANSLATED, GTK_SORT_ASCENDING); gtk_tree_model_filter_set_visible_func (city_modelfilter, (GtkTreeModelFilterVisibleFunc) city_model_filter_func, widget, NULL); /* After the initial setup, so we can be sure that * the model is filled up */ date_time_mechanism_call_get_timezone (priv->dtm, priv->cancellable, get_timezone_cb, self); /* add the lock button */ priv->permission = polkit_permission_new_sync ("org.gnome.settingsdaemon.datetimemechanism.configure", NULL, NULL, NULL); if (priv->permission == NULL) { g_warning ("Your system does not have the '%s' PolicyKit files installed. Please check your installation", "org.gnome.settingsdaemon.datetimemechanism.configure"); return; } g_signal_connect (priv->permission, "notify", G_CALLBACK (on_permission_changed), self); on_permission_changed (priv->permission, NULL, self); } void cc_date_time_panel_register (GIOModule *module) { bind_textdomain_codeset (GETTEXT_PACKAGE_TIMEZONES, "UTF-8"); cc_date_time_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_DATE_TIME_PANEL, "datetime", 0); }
422
./cinnamon-control-center/panels/unused/datetime/test-timezone-gfx.c
#include <config.h> #include <locale.h> #include "tz.h" int main (int argc, char **argv) { TzDB *db; GPtrArray *locs; guint i; char *pixmap_dir; int retval = 0; setlocale (LC_ALL, ""); if (argc == 2) { pixmap_dir = g_strdup (argv[1]); } else if (argc == 1) { pixmap_dir = g_strdup ("data/"); } else { g_message ("Usage: %s [PIXMAP DIRECTORY]", argv[0]); return 1; } db = tz_load_db (); locs = tz_get_locations (db); for (i = 0; i < locs->len ; i++) { TzLocation *loc = locs->pdata[i]; TzInfo *info; char *filename, *path; gdouble selected_offset; char buf[16]; info = tz_info_from_location (loc); selected_offset = tz_location_get_utc_offset (loc) / (60.0*60.0) + ((info->daylight) ? -1.0 : 0.0); filename = g_strdup_printf ("timezone_%s.png", g_ascii_formatd (buf, sizeof (buf), "%g", selected_offset)); path = g_build_filename (pixmap_dir, filename, NULL); if (g_file_test (path, G_FILE_TEST_IS_REGULAR) == FALSE) { g_message ("File '%s' missing for zone '%s'", filename, loc->zone); retval = 1; } g_free (filename); g_free (path); } tz_db_free (db); g_free (pixmap_dir); return retval; }
423
./cinnamon-control-center/panels/unused/datetime/test-endianess.c
#include <glib.h> #include <glib/gi18n.h> #include <locale.h> #include "date-endian.h" static int verbose = 0; static void print_endianess (const char *lang) { DateEndianess endianess; if (lang != NULL) { setlocale (LC_TIME, lang); endianess = date_endian_get_for_lang (lang, verbose); } else { endianess = date_endian_get_default (verbose); } if (verbose) g_print ("\t\t%s\n", date_endian_to_string (endianess)); } int main (int argc, char **argv) { GDir *dir; const char *name; setlocale (LC_ALL, ""); bind_textdomain_codeset ("libc", "UTF-8"); if (argv[1] != NULL) { verbose = 1; if (g_str_equal (argv[1], "-c")) print_endianess (NULL); else print_endianess (argv[1]); return 0; } dir = g_dir_open ("/usr/share/i18n/locales/", 0, NULL); if (dir == NULL) { /* Try with /usr/share/locale/ * https://bugzilla.gnome.org/show_bug.cgi?id=646780 */ dir = g_dir_open ("/usr/share/locale/", 0, NULL); if (dir == NULL) { return 1; } } while ((name = g_dir_read_name (dir)) != NULL) print_endianess (name); return 0; }
424
./cinnamon-control-center/panels/unused/datetime/dtm.c
/* * Generated by gdbus-codegen 2.29.5. DO NOT EDIT. * * The license of this code is the same as for the source it was derived from. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "dtm.h" typedef struct { GDBusArgInfo parent_struct; gboolean use_gvariant; } _ExtendedGDBusArgInfo; typedef struct { GDBusMethodInfo parent_struct; const gchar *signal_name; } _ExtendedGDBusMethodInfo; typedef struct { GDBusSignalInfo parent_struct; const gchar *signal_name; } _ExtendedGDBusSignalInfo; typedef struct { GDBusPropertyInfo parent_struct; const gchar *hyphen_name; gboolean use_gvariant; } _ExtendedGDBusPropertyInfo; typedef struct { GDBusInterfaceInfo parent_struct; const gchar *hyphen_name; } _ExtendedGDBusInterfaceInfo; typedef struct { const _ExtendedGDBusPropertyInfo *info; guint prop_id; GValue orig_value; /* the value before the change */ } ChangedProperty; static void _changed_property_free (ChangedProperty *data) { g_value_unset (&data->orig_value); g_free (data); } static gboolean _g_strv_equal0 (gchar **a, gchar **b) { gboolean ret = FALSE; guint n; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; if (g_strv_length (a) != g_strv_length (b)) goto out; for (n = 0; a[n] != NULL; n++) if (g_strcmp0 (a[n], b[n]) != 0) goto out; ret = TRUE; out: return ret; } static gboolean _g_variant_equal0 (GVariant *a, GVariant *b) { gboolean ret = FALSE; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; ret = g_variant_equal (a, b); out: return ret; } G_GNUC_UNUSED static gboolean _g_value_equal (const GValue *a, const GValue *b) { gboolean ret = FALSE; g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); switch (G_VALUE_TYPE (a)) { case G_TYPE_BOOLEAN: ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); break; case G_TYPE_UCHAR: ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); break; case G_TYPE_INT: ret = (g_value_get_int (a) == g_value_get_int (b)); break; case G_TYPE_UINT: ret = (g_value_get_uint (a) == g_value_get_uint (b)); break; case G_TYPE_INT64: ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); break; case G_TYPE_UINT64: ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); break; case G_TYPE_DOUBLE: ret = (g_value_get_double (a) == g_value_get_double (b)); break; case G_TYPE_STRING: ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); break; case G_TYPE_VARIANT: ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); break; default: if (G_VALUE_TYPE (a) == G_TYPE_STRV) ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); else g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); break; } return ret; } /* ------------------------------------------------------------------------ * Code for interface org.gnome.SettingsDaemon.DateTimeMechanism * ------------------------------------------------------------------------ */ /** * SECTION:DateTimeMechanism * @title: DateTimeMechanism * @short_description: Generated C code for the org.gnome.SettingsDaemon.DateTimeMechanism D-Bus interface * * This section contains code for working with the <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link> D-Bus interface in C. */ /* ---- Introspection data for org.gnome.SettingsDaemon.DateTimeMechanism ---- */ static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_timezone_IN_ARG_tz = { { -1, "tz", "s", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_set_timezone_IN_ARG_pointers[] = { &_date_time_mechanism_method_info_set_timezone_IN_ARG_tz, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_set_timezone_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_set_timezone_annotation_info_pointers[] = { &_date_time_mechanism_method_set_timezone_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_set_timezone = { { -1, "SetTimezone", (GDBusArgInfo **) &_date_time_mechanism_method_info_set_timezone_IN_ARG_pointers, NULL, (GDBusAnnotationInfo **) &_date_time_mechanism_method_set_timezone_annotation_info_pointers }, "handle-set-timezone" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_get_timezone_OUT_ARG_timezone = { { -1, "timezone", "s", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_get_timezone_OUT_ARG_pointers[] = { &_date_time_mechanism_method_info_get_timezone_OUT_ARG_timezone, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_get_timezone_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_get_timezone_annotation_info_pointers[] = { &_date_time_mechanism_method_get_timezone_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_get_timezone = { { -1, "GetTimezone", NULL, (GDBusArgInfo **) &_date_time_mechanism_method_info_get_timezone_OUT_ARG_pointers, (GDBusAnnotationInfo **) &_date_time_mechanism_method_get_timezone_annotation_info_pointers }, "handle-get-timezone" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_can_set_timezone_OUT_ARG_value = { { -1, "value", "i", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_can_set_timezone_OUT_ARG_pointers[] = { &_date_time_mechanism_method_info_can_set_timezone_OUT_ARG_value, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_can_set_timezone_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_can_set_timezone_annotation_info_pointers[] = { &_date_time_mechanism_method_can_set_timezone_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_can_set_timezone = { { -1, "CanSetTimezone", NULL, (GDBusArgInfo **) &_date_time_mechanism_method_info_can_set_timezone_OUT_ARG_pointers, (GDBusAnnotationInfo **) &_date_time_mechanism_method_can_set_timezone_annotation_info_pointers }, "handle-can-set-timezone" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_date_IN_ARG_day = { { -1, "day", "u", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_date_IN_ARG_month = { { -1, "month", "u", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_date_IN_ARG_year = { { -1, "year", "u", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_set_date_IN_ARG_pointers[] = { &_date_time_mechanism_method_info_set_date_IN_ARG_day, &_date_time_mechanism_method_info_set_date_IN_ARG_month, &_date_time_mechanism_method_info_set_date_IN_ARG_year, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_set_date_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_set_date_annotation_info_pointers[] = { &_date_time_mechanism_method_set_date_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_set_date = { { -1, "SetDate", (GDBusArgInfo **) &_date_time_mechanism_method_info_set_date_IN_ARG_pointers, NULL, (GDBusAnnotationInfo **) &_date_time_mechanism_method_set_date_annotation_info_pointers }, "handle-set-date" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_time_IN_ARG_seconds_since_epoch = { { -1, "seconds_since_epoch", "x", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_set_time_IN_ARG_pointers[] = { &_date_time_mechanism_method_info_set_time_IN_ARG_seconds_since_epoch, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_set_time_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_set_time_annotation_info_pointers[] = { &_date_time_mechanism_method_set_time_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_set_time = { { -1, "SetTime", (GDBusArgInfo **) &_date_time_mechanism_method_info_set_time_IN_ARG_pointers, NULL, (GDBusAnnotationInfo **) &_date_time_mechanism_method_set_time_annotation_info_pointers }, "handle-set-time" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_can_set_time_OUT_ARG_value = { { -1, "value", "i", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_can_set_time_OUT_ARG_pointers[] = { &_date_time_mechanism_method_info_can_set_time_OUT_ARG_value, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_can_set_time_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_can_set_time_annotation_info_pointers[] = { &_date_time_mechanism_method_can_set_time_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_can_set_time = { { -1, "CanSetTime", NULL, (GDBusArgInfo **) &_date_time_mechanism_method_info_can_set_time_OUT_ARG_pointers, (GDBusAnnotationInfo **) &_date_time_mechanism_method_can_set_time_annotation_info_pointers }, "handle-can-set-time" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_adjust_time_IN_ARG_seconds_to_add = { { -1, "seconds_to_add", "x", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_adjust_time_IN_ARG_pointers[] = { &_date_time_mechanism_method_info_adjust_time_IN_ARG_seconds_to_add, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_adjust_time_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_adjust_time_annotation_info_pointers[] = { &_date_time_mechanism_method_adjust_time_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_adjust_time = { { -1, "AdjustTime", (GDBusArgInfo **) &_date_time_mechanism_method_info_adjust_time_IN_ARG_pointers, NULL, (GDBusAnnotationInfo **) &_date_time_mechanism_method_adjust_time_annotation_info_pointers }, "handle-adjust-time" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_get_hardware_clock_using_utc_OUT_ARG_is_using_utc = { { -1, "is_using_utc", "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_get_hardware_clock_using_utc_OUT_ARG_pointers[] = { &_date_time_mechanism_method_info_get_hardware_clock_using_utc_OUT_ARG_is_using_utc, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_get_hardware_clock_using_utc_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_get_hardware_clock_using_utc_annotation_info_pointers[] = { &_date_time_mechanism_method_get_hardware_clock_using_utc_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_get_hardware_clock_using_utc = { { -1, "GetHardwareClockUsingUtc", NULL, (GDBusArgInfo **) &_date_time_mechanism_method_info_get_hardware_clock_using_utc_OUT_ARG_pointers, (GDBusAnnotationInfo **) &_date_time_mechanism_method_get_hardware_clock_using_utc_annotation_info_pointers }, "handle-get-hardware-clock-using-utc" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_hardware_clock_using_utc_IN_ARG_is_using_utc = { { -1, "is_using_utc", "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_set_hardware_clock_using_utc_IN_ARG_pointers[] = { &_date_time_mechanism_method_info_set_hardware_clock_using_utc_IN_ARG_is_using_utc, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_set_hardware_clock_using_utc_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_set_hardware_clock_using_utc_annotation_info_pointers[] = { &_date_time_mechanism_method_set_hardware_clock_using_utc_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_set_hardware_clock_using_utc = { { -1, "SetHardwareClockUsingUtc", (GDBusArgInfo **) &_date_time_mechanism_method_info_set_hardware_clock_using_utc_IN_ARG_pointers, NULL, (GDBusAnnotationInfo **) &_date_time_mechanism_method_set_hardware_clock_using_utc_annotation_info_pointers }, "handle-set-hardware-clock-using-utc" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_get_using_ntp_OUT_ARG_can_use_ntp = { { -1, "can_use_ntp", "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_get_using_ntp_OUT_ARG_is_using_ntp = { { -1, "is_using_ntp", "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_get_using_ntp_OUT_ARG_pointers[] = { &_date_time_mechanism_method_info_get_using_ntp_OUT_ARG_can_use_ntp, &_date_time_mechanism_method_info_get_using_ntp_OUT_ARG_is_using_ntp, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_get_using_ntp_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_get_using_ntp_annotation_info_pointers[] = { &_date_time_mechanism_method_get_using_ntp_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_get_using_ntp = { { -1, "GetUsingNtp", NULL, (GDBusArgInfo **) &_date_time_mechanism_method_info_get_using_ntp_OUT_ARG_pointers, (GDBusAnnotationInfo **) &_date_time_mechanism_method_get_using_ntp_annotation_info_pointers }, "handle-get-using-ntp" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_set_using_ntp_IN_ARG_is_using_ntp = { { -1, "is_using_ntp", "b", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_set_using_ntp_IN_ARG_pointers[] = { &_date_time_mechanism_method_info_set_using_ntp_IN_ARG_is_using_ntp, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_set_using_ntp_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_set_using_ntp_annotation_info_pointers[] = { &_date_time_mechanism_method_set_using_ntp_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_set_using_ntp = { { -1, "SetUsingNtp", (GDBusArgInfo **) &_date_time_mechanism_method_info_set_using_ntp_IN_ARG_pointers, NULL, (GDBusAnnotationInfo **) &_date_time_mechanism_method_set_using_ntp_annotation_info_pointers }, "handle-set-using-ntp" }; static const _ExtendedGDBusArgInfo _date_time_mechanism_method_info_can_set_using_ntp_OUT_ARG_value = { { -1, "value", "i", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _date_time_mechanism_method_info_can_set_using_ntp_OUT_ARG_pointers[] = { &_date_time_mechanism_method_info_can_set_using_ntp_OUT_ARG_value, NULL }; static const GDBusAnnotationInfo _date_time_mechanism_method_can_set_using_ntp_annotation_info_0 = { -1, "org.freedesktop.DBus.GLib.Async", "", NULL }; static const GDBusAnnotationInfo * const _date_time_mechanism_method_can_set_using_ntp_annotation_info_pointers[] = { &_date_time_mechanism_method_can_set_using_ntp_annotation_info_0, NULL }; static const _ExtendedGDBusMethodInfo _date_time_mechanism_method_info_can_set_using_ntp = { { -1, "CanSetUsingNtp", NULL, (GDBusArgInfo **) &_date_time_mechanism_method_info_can_set_using_ntp_OUT_ARG_pointers, (GDBusAnnotationInfo **) &_date_time_mechanism_method_can_set_using_ntp_annotation_info_pointers }, "handle-can-set-using-ntp" }; static const _ExtendedGDBusMethodInfo * const _date_time_mechanism_method_info_pointers[] = { &_date_time_mechanism_method_info_set_timezone, &_date_time_mechanism_method_info_get_timezone, &_date_time_mechanism_method_info_can_set_timezone, &_date_time_mechanism_method_info_set_date, &_date_time_mechanism_method_info_set_time, &_date_time_mechanism_method_info_can_set_time, &_date_time_mechanism_method_info_adjust_time, &_date_time_mechanism_method_info_get_hardware_clock_using_utc, &_date_time_mechanism_method_info_set_hardware_clock_using_utc, &_date_time_mechanism_method_info_get_using_ntp, &_date_time_mechanism_method_info_set_using_ntp, &_date_time_mechanism_method_info_can_set_using_ntp, NULL }; static const _ExtendedGDBusInterfaceInfo _date_time_mechanism_interface_info = { { -1, "org.gnome.SettingsDaemon.DateTimeMechanism", (GDBusMethodInfo **) &_date_time_mechanism_method_info_pointers, NULL, NULL, NULL }, "date-time-mechanism", }; /** * date_time_mechanism_interface_info: * * Gets a machine-readable description of the <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link> D-Bus interface. * * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. */ GDBusInterfaceInfo * date_time_mechanism_interface_info (void) { return (GDBusInterfaceInfo *) &_date_time_mechanism_interface_info; } /** * DateTimeMechanism: * * Abstract interface type for the D-Bus interface <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link>. */ /** * DateTimeMechanismIface: * @parent_iface: The parent interface. * @handle_adjust_time: Handler for the #DateTimeMechanism::handle-adjust-time signal. * @handle_can_set_time: Handler for the #DateTimeMechanism::handle-can-set-time signal. * @handle_can_set_timezone: Handler for the #DateTimeMechanism::handle-can-set-timezone signal. * @handle_can_set_using_ntp: Handler for the #DateTimeMechanism::handle-can-set-using-ntp signal. * @handle_get_hardware_clock_using_utc: Handler for the #DateTimeMechanism::handle-get-hardware-clock-using-utc signal. * @handle_get_timezone: Handler for the #DateTimeMechanism::handle-get-timezone signal. * @handle_get_using_ntp: Handler for the #DateTimeMechanism::handle-get-using-ntp signal. * @handle_set_date: Handler for the #DateTimeMechanism::handle-set-date signal. * @handle_set_hardware_clock_using_utc: Handler for the #DateTimeMechanism::handle-set-hardware-clock-using-utc signal. * @handle_set_time: Handler for the #DateTimeMechanism::handle-set-time signal. * @handle_set_timezone: Handler for the #DateTimeMechanism::handle-set-timezone signal. * @handle_set_using_ntp: Handler for the #DateTimeMechanism::handle-set-using-ntp signal. * * Virtual table for the D-Bus interface <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link>. */ static void date_time_mechanism_default_init (DateTimeMechanismIface *iface) { /* GObject signals for incoming D-Bus method calls: */ /** * DateTimeMechanism::handle-set-timezone: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * @tz: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTimezone">SetTimezone()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_set_timezone() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-timezone", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_set_timezone), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); /** * DateTimeMechanism::handle-get-timezone: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetTimezone">GetTimezone()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_get_timezone() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-get-timezone", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_get_timezone), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); /** * DateTimeMechanism::handle-can-set-timezone: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTimezone">CanSetTimezone()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_can_set_timezone() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-can-set-timezone", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_can_set_timezone), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); /** * DateTimeMechanism::handle-set-date: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * @day: Argument passed by remote caller. * @month: Argument passed by remote caller. * @year: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetDate">SetDate()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_set_date() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-date", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_set_date), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 4, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT); /** * DateTimeMechanism::handle-set-time: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * @seconds_since_epoch: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTime">SetTime()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_set_time() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-time", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_set_time), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_INT64); /** * DateTimeMechanism::handle-can-set-time: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTime">CanSetTime()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_can_set_time() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-can-set-time", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_can_set_time), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); /** * DateTimeMechanism::handle-adjust-time: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * @seconds_to_add: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.AdjustTime">AdjustTime()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_adjust_time() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-adjust-time", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_adjust_time), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_INT64); /** * DateTimeMechanism::handle-get-hardware-clock-using-utc: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetHardwareClockUsingUtc">GetHardwareClockUsingUtc()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_get_hardware_clock_using_utc() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-get-hardware-clock-using-utc", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_get_hardware_clock_using_utc), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); /** * DateTimeMechanism::handle-set-hardware-clock-using-utc: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * @is_using_utc: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetHardwareClockUsingUtc">SetHardwareClockUsingUtc()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_set_hardware_clock_using_utc() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-hardware-clock-using-utc", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_set_hardware_clock_using_utc), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_BOOLEAN); /** * DateTimeMechanism::handle-get-using-ntp: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetUsingNtp">GetUsingNtp()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_get_using_ntp() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-get-using-ntp", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_get_using_ntp), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); /** * DateTimeMechanism::handle-set-using-ntp: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * @is_using_ntp: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetUsingNtp">SetUsingNtp()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_set_using_ntp() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-set-using-ntp", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_set_using_ntp), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_BOOLEAN); /** * DateTimeMechanism::handle-can-set-using-ntp: * @object: A #DateTimeMechanism. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetUsingNtp">CanSetUsingNtp()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call date_time_mechanism_complete_can_set_using_ntp() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-can-set-using-ntp", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (DateTimeMechanismIface, handle_can_set_using_ntp), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); } typedef DateTimeMechanismIface DateTimeMechanismInterface; G_DEFINE_INTERFACE (DateTimeMechanism, date_time_mechanism, G_TYPE_OBJECT); /** * date_time_mechanism_call_set_timezone: * @proxy: A #DateTimeMechanismProxy. * @tz: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTimezone">SetTimezone()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_set_timezone_finish() to get the result of the operation. * * See date_time_mechanism_call_set_timezone_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_set_timezone ( DateTimeMechanism *proxy, const gchar *tz, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetTimezone", g_variant_new ("(s)", tz), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_set_timezone_finish: * @proxy: A #DateTimeMechanismProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_set_timezone(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_set_timezone(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_timezone_finish ( DateTimeMechanism *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_timezone_sync: * @proxy: A #DateTimeMechanismProxy. * @tz: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTimezone">SetTimezone()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_set_timezone() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_timezone_sync ( DateTimeMechanism *proxy, const gchar *tz, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetTimezone", g_variant_new ("(s)", tz), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_get_timezone: * @proxy: A #DateTimeMechanismProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetTimezone">GetTimezone()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_get_timezone_finish() to get the result of the operation. * * See date_time_mechanism_call_get_timezone_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_get_timezone ( DateTimeMechanism *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "GetTimezone", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_get_timezone_finish: * @proxy: A #DateTimeMechanismProxy. * @out_timezone: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_get_timezone(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_get_timezone(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_get_timezone_finish ( DateTimeMechanism *proxy, gchar **out_timezone, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(s)", out_timezone); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_get_timezone_sync: * @proxy: A #DateTimeMechanismProxy. * @out_timezone: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetTimezone">GetTimezone()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_get_timezone() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_get_timezone_sync ( DateTimeMechanism *proxy, gchar **out_timezone, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "GetTimezone", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(s)", out_timezone); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_can_set_timezone: * @proxy: A #DateTimeMechanismProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTimezone">CanSetTimezone()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_can_set_timezone_finish() to get the result of the operation. * * See date_time_mechanism_call_can_set_timezone_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_can_set_timezone ( DateTimeMechanism *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "CanSetTimezone", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_can_set_timezone_finish: * @proxy: A #DateTimeMechanismProxy. * @out_value: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_can_set_timezone(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_can_set_timezone(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_can_set_timezone_finish ( DateTimeMechanism *proxy, gint *out_value, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(i)", out_value); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_can_set_timezone_sync: * @proxy: A #DateTimeMechanismProxy. * @out_value: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTimezone">CanSetTimezone()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_can_set_timezone() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_can_set_timezone_sync ( DateTimeMechanism *proxy, gint *out_value, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "CanSetTimezone", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(i)", out_value); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_date: * @proxy: A #DateTimeMechanismProxy. * @day: Argument to pass with the method invocation. * @month: Argument to pass with the method invocation. * @year: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetDate">SetDate()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_set_date_finish() to get the result of the operation. * * See date_time_mechanism_call_set_date_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_set_date ( DateTimeMechanism *proxy, guint day, guint month, guint year, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetDate", g_variant_new ("(uuu)", day, month, year), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_set_date_finish: * @proxy: A #DateTimeMechanismProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_set_date(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_set_date(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_date_finish ( DateTimeMechanism *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_date_sync: * @proxy: A #DateTimeMechanismProxy. * @day: Argument to pass with the method invocation. * @month: Argument to pass with the method invocation. * @year: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetDate">SetDate()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_set_date() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_date_sync ( DateTimeMechanism *proxy, guint day, guint month, guint year, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetDate", g_variant_new ("(uuu)", day, month, year), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_time: * @proxy: A #DateTimeMechanismProxy. * @seconds_since_epoch: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTime">SetTime()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_set_time_finish() to get the result of the operation. * * See date_time_mechanism_call_set_time_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_set_time ( DateTimeMechanism *proxy, gint64 seconds_since_epoch, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetTime", g_variant_new ("(x)", seconds_since_epoch), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_set_time_finish: * @proxy: A #DateTimeMechanismProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_set_time(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_set_time(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_time_finish ( DateTimeMechanism *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_time_sync: * @proxy: A #DateTimeMechanismProxy. * @seconds_since_epoch: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTime">SetTime()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_set_time() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_time_sync ( DateTimeMechanism *proxy, gint64 seconds_since_epoch, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetTime", g_variant_new ("(x)", seconds_since_epoch), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_can_set_time: * @proxy: A #DateTimeMechanismProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTime">CanSetTime()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_can_set_time_finish() to get the result of the operation. * * See date_time_mechanism_call_can_set_time_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_can_set_time ( DateTimeMechanism *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "CanSetTime", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_can_set_time_finish: * @proxy: A #DateTimeMechanismProxy. * @out_value: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_can_set_time(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_can_set_time(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_can_set_time_finish ( DateTimeMechanism *proxy, gint *out_value, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(i)", out_value); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_can_set_time_sync: * @proxy: A #DateTimeMechanismProxy. * @out_value: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTime">CanSetTime()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_can_set_time() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_can_set_time_sync ( DateTimeMechanism *proxy, gint *out_value, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "CanSetTime", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(i)", out_value); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_adjust_time: * @proxy: A #DateTimeMechanismProxy. * @seconds_to_add: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.AdjustTime">AdjustTime()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_adjust_time_finish() to get the result of the operation. * * See date_time_mechanism_call_adjust_time_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_adjust_time ( DateTimeMechanism *proxy, gint64 seconds_to_add, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "AdjustTime", g_variant_new ("(x)", seconds_to_add), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_adjust_time_finish: * @proxy: A #DateTimeMechanismProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_adjust_time(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_adjust_time(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_adjust_time_finish ( DateTimeMechanism *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_adjust_time_sync: * @proxy: A #DateTimeMechanismProxy. * @seconds_to_add: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.AdjustTime">AdjustTime()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_adjust_time() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_adjust_time_sync ( DateTimeMechanism *proxy, gint64 seconds_to_add, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "AdjustTime", g_variant_new ("(x)", seconds_to_add), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_get_hardware_clock_using_utc: * @proxy: A #DateTimeMechanismProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetHardwareClockUsingUtc">GetHardwareClockUsingUtc()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_get_hardware_clock_using_utc_finish() to get the result of the operation. * * See date_time_mechanism_call_get_hardware_clock_using_utc_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_get_hardware_clock_using_utc ( DateTimeMechanism *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "GetHardwareClockUsingUtc", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_get_hardware_clock_using_utc_finish: * @proxy: A #DateTimeMechanismProxy. * @out_is_using_utc: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_get_hardware_clock_using_utc(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_get_hardware_clock_using_utc(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_get_hardware_clock_using_utc_finish ( DateTimeMechanism *proxy, gboolean *out_is_using_utc, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(b)", out_is_using_utc); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_get_hardware_clock_using_utc_sync: * @proxy: A #DateTimeMechanismProxy. * @out_is_using_utc: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetHardwareClockUsingUtc">GetHardwareClockUsingUtc()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_get_hardware_clock_using_utc() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_get_hardware_clock_using_utc_sync ( DateTimeMechanism *proxy, gboolean *out_is_using_utc, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "GetHardwareClockUsingUtc", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(b)", out_is_using_utc); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_hardware_clock_using_utc: * @proxy: A #DateTimeMechanismProxy. * @is_using_utc: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetHardwareClockUsingUtc">SetHardwareClockUsingUtc()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_set_hardware_clock_using_utc_finish() to get the result of the operation. * * See date_time_mechanism_call_set_hardware_clock_using_utc_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_set_hardware_clock_using_utc ( DateTimeMechanism *proxy, gboolean is_using_utc, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetHardwareClockUsingUtc", g_variant_new ("(b)", is_using_utc), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_set_hardware_clock_using_utc_finish: * @proxy: A #DateTimeMechanismProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_set_hardware_clock_using_utc(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_set_hardware_clock_using_utc(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_hardware_clock_using_utc_finish ( DateTimeMechanism *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_hardware_clock_using_utc_sync: * @proxy: A #DateTimeMechanismProxy. * @is_using_utc: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetHardwareClockUsingUtc">SetHardwareClockUsingUtc()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_set_hardware_clock_using_utc() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_hardware_clock_using_utc_sync ( DateTimeMechanism *proxy, gboolean is_using_utc, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetHardwareClockUsingUtc", g_variant_new ("(b)", is_using_utc), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_get_using_ntp: * @proxy: A #DateTimeMechanismProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetUsingNtp">GetUsingNtp()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_get_using_ntp_finish() to get the result of the operation. * * See date_time_mechanism_call_get_using_ntp_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_get_using_ntp ( DateTimeMechanism *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "GetUsingNtp", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_get_using_ntp_finish: * @proxy: A #DateTimeMechanismProxy. * @out_can_use_ntp: (out): Return location for return parameter or %NULL to ignore. * @out_is_using_ntp: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_get_using_ntp(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_get_using_ntp(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_get_using_ntp_finish ( DateTimeMechanism *proxy, gboolean *out_can_use_ntp, gboolean *out_is_using_ntp, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(bb)", out_can_use_ntp, out_is_using_ntp); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_get_using_ntp_sync: * @proxy: A #DateTimeMechanismProxy. * @out_can_use_ntp: (out): Return location for return parameter or %NULL to ignore. * @out_is_using_ntp: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetUsingNtp">GetUsingNtp()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_get_using_ntp() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_get_using_ntp_sync ( DateTimeMechanism *proxy, gboolean *out_can_use_ntp, gboolean *out_is_using_ntp, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "GetUsingNtp", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(bb)", out_can_use_ntp, out_is_using_ntp); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_using_ntp: * @proxy: A #DateTimeMechanismProxy. * @is_using_ntp: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetUsingNtp">SetUsingNtp()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_set_using_ntp_finish() to get the result of the operation. * * See date_time_mechanism_call_set_using_ntp_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_set_using_ntp ( DateTimeMechanism *proxy, gboolean is_using_ntp, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "SetUsingNtp", g_variant_new ("(b)", is_using_ntp), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_set_using_ntp_finish: * @proxy: A #DateTimeMechanismProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_set_using_ntp(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_set_using_ntp(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_using_ntp_finish ( DateTimeMechanism *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_set_using_ntp_sync: * @proxy: A #DateTimeMechanismProxy. * @is_using_ntp: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetUsingNtp">SetUsingNtp()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_set_using_ntp() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_set_using_ntp_sync ( DateTimeMechanism *proxy, gboolean is_using_ntp, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "SetUsingNtp", g_variant_new ("(b)", is_using_ntp), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_can_set_using_ntp: * @proxy: A #DateTimeMechanismProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetUsingNtp">CanSetUsingNtp()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_call_can_set_using_ntp_finish() to get the result of the operation. * * See date_time_mechanism_call_can_set_using_ntp_sync() for the synchronous, blocking version of this method. */ void date_time_mechanism_call_can_set_using_ntp ( DateTimeMechanism *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "CanSetUsingNtp", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * date_time_mechanism_call_can_set_using_ntp_finish: * @proxy: A #DateTimeMechanismProxy. * @out_value: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_call_can_set_using_ntp(). * @error: Return location for error or %NULL. * * Finishes an operation started with date_time_mechanism_call_can_set_using_ntp(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_can_set_using_ntp_finish ( DateTimeMechanism *proxy, gint *out_value, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(i)", out_value); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_call_can_set_using_ntp_sync: * @proxy: A #DateTimeMechanismProxy. * @out_value: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetUsingNtp">CanSetUsingNtp()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See date_time_mechanism_call_can_set_using_ntp() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean date_time_mechanism_call_can_set_using_ntp_sync ( DateTimeMechanism *proxy, gint *out_value, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "CanSetUsingNtp", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(i)", out_value); g_variant_unref (_ret); _out: return _ret != NULL; } /** * date_time_mechanism_complete_set_timezone: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTimezone">SetTimezone()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_set_timezone ( DateTimeMechanism *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * date_time_mechanism_complete_get_timezone: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * @timezone: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetTimezone">GetTimezone()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_get_timezone ( DateTimeMechanism *object, GDBusMethodInvocation *invocation, const gchar *timezone) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(s)", timezone)); } /** * date_time_mechanism_complete_can_set_timezone: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * @value: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTimezone">CanSetTimezone()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_can_set_timezone ( DateTimeMechanism *object, GDBusMethodInvocation *invocation, gint value) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(i)", value)); } /** * date_time_mechanism_complete_set_date: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetDate">SetDate()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_set_date ( DateTimeMechanism *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * date_time_mechanism_complete_set_time: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetTime">SetTime()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_set_time ( DateTimeMechanism *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * date_time_mechanism_complete_can_set_time: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * @value: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetTime">CanSetTime()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_can_set_time ( DateTimeMechanism *object, GDBusMethodInvocation *invocation, gint value) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(i)", value)); } /** * date_time_mechanism_complete_adjust_time: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.AdjustTime">AdjustTime()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_adjust_time ( DateTimeMechanism *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * date_time_mechanism_complete_get_hardware_clock_using_utc: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * @is_using_utc: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetHardwareClockUsingUtc">GetHardwareClockUsingUtc()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_get_hardware_clock_using_utc ( DateTimeMechanism *object, GDBusMethodInvocation *invocation, gboolean is_using_utc) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(b)", is_using_utc)); } /** * date_time_mechanism_complete_set_hardware_clock_using_utc: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetHardwareClockUsingUtc">SetHardwareClockUsingUtc()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_set_hardware_clock_using_utc ( DateTimeMechanism *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * date_time_mechanism_complete_get_using_ntp: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * @can_use_ntp: Parameter to return. * @is_using_ntp: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.GetUsingNtp">GetUsingNtp()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_get_using_ntp ( DateTimeMechanism *object, GDBusMethodInvocation *invocation, gboolean can_use_ntp, gboolean is_using_ntp) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(bb)", can_use_ntp, is_using_ntp)); } /** * date_time_mechanism_complete_set_using_ntp: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.SetUsingNtp">SetUsingNtp()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_set_using_ntp ( DateTimeMechanism *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * date_time_mechanism_complete_can_set_using_ntp: * @object: A #DateTimeMechanism. * @invocation: (transfer full): A #GDBusMethodInvocation. * @value: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-SettingsDaemon-DateTimeMechanism.CanSetUsingNtp">CanSetUsingNtp()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void date_time_mechanism_complete_can_set_using_ntp ( DateTimeMechanism *object, GDBusMethodInvocation *invocation, gint value) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(i)", value)); } /* ------------------------------------------------------------------------ */ /** * DateTimeMechanismProxy: * * The #DateTimeMechanismProxy structure contains only private data and should only be accessed using the provided API. */ /** * DateTimeMechanismProxyClass: * @parent_class: The parent class. * * Class structure for #DateTimeMechanismProxy. */ static void date_time_mechanism_proxy_iface_init (DateTimeMechanismIface *iface) { } #define date_time_mechanism_proxy_get_type date_time_mechanism_proxy_get_type G_DEFINE_TYPE_WITH_CODE (DateTimeMechanismProxy, date_time_mechanism_proxy, G_TYPE_DBUS_PROXY, G_IMPLEMENT_INTERFACE (TYPE_DATE_TIME_MECHANISM, date_time_mechanism_proxy_iface_init)); #undef date_time_mechanism_proxy_get_type static void date_time_mechanism_proxy_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { } static void date_time_mechanism_proxy_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { } static void date_time_mechanism_proxy_g_signal (GDBusProxy *proxy, const gchar *sender_name, const gchar *signal_name, GVariant *parameters) { _ExtendedGDBusSignalInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint n; guint signal_id; info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_date_time_mechanism_interface_info, signal_name); if (info == NULL) return; num_params = g_variant_n_children (parameters); paramv = g_new0 (GValue, num_params + 1); g_value_init (&paramv[0], TYPE_DATE_TIME_MECHANISM); g_value_set_object (&paramv[0], proxy); g_variant_iter_init (&iter, parameters); n = 1; while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; if (arg_info->use_gvariant) { g_value_init (&paramv[n], G_TYPE_VARIANT); g_value_set_variant (&paramv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, &paramv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, TYPE_DATE_TIME_MECHANISM); g_signal_emitv (paramv, signal_id, 0, NULL); for (n = 0; n < num_params + 1; n++) g_value_unset (&paramv[n]); g_free (paramv); } static void date_time_mechanism_proxy_g_properties_changed (GDBusProxy *proxy, GVariant *changed_properties, const gchar *const *invalidated_properties) { guint n; const gchar *key; GVariantIter *iter; _ExtendedGDBusPropertyInfo *info; g_variant_get (changed_properties, "a{sv}", &iter); while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_date_time_mechanism_interface_info, key); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } g_variant_iter_free (iter); for (n = 0; invalidated_properties[n] != NULL; n++) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_date_time_mechanism_interface_info, invalidated_properties[n]); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } } static void date_time_mechanism_proxy_init (DateTimeMechanismProxy *proxy) { g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), date_time_mechanism_interface_info ()); } static void date_time_mechanism_proxy_class_init (DateTimeMechanismProxyClass *klass) { GObjectClass *gobject_class; GDBusProxyClass *proxy_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->get_property = date_time_mechanism_proxy_get_property; gobject_class->set_property = date_time_mechanism_proxy_set_property; proxy_class = G_DBUS_PROXY_CLASS (klass); proxy_class->g_signal = date_time_mechanism_proxy_g_signal; proxy_class->g_properties_changed = date_time_mechanism_proxy_g_properties_changed; } /** * date_time_mechanism_proxy_new: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Asynchronously creates a proxy for the D-Bus interface <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link>. See g_dbus_proxy_new() for more details. * * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_proxy_new_finish() to get the result of the operation. * * See date_time_mechanism_proxy_new_sync() for the synchronous, blocking version of this constructor. */ void date_time_mechanism_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (TYPE_DATE_TIME_MECHANISM_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gnome.SettingsDaemon.DateTimeMechanism", NULL); } /** * date_time_mechanism_proxy_new_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_proxy_new(). * @error: Return location for error or %NULL * * Finishes an operation started with date_time_mechanism_proxy_new(). * * Returns: (transfer full) (type DateTimeMechanismProxy): The constructed proxy object or %NULL if @error is set. */ DateTimeMechanism * date_time_mechanism_proxy_new_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return DATE_TIME_MECHANISM (ret); else return NULL; } /** * date_time_mechanism_proxy_new_sync: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Synchronously creates a proxy for the D-Bus interface <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link>. See g_dbus_proxy_new_sync() for more details. * * The calling thread is blocked until a reply is received. * * See date_time_mechanism_proxy_new() for the asynchronous version of this constructor. * * Returns: (transfer full) (type DateTimeMechanismProxy): The constructed proxy object or %NULL if @error is set. */ DateTimeMechanism * date_time_mechanism_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (TYPE_DATE_TIME_MECHANISM_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gnome.SettingsDaemon.DateTimeMechanism", NULL); if (ret != NULL) return DATE_TIME_MECHANISM (ret); else return NULL; } /** * date_time_mechanism_proxy_new_for_bus: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Like date_time_mechanism_proxy_new() but takes a #GBusType instead of a #GDBusConnection. * * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call date_time_mechanism_proxy_new_for_bus_finish() to get the result of the operation. * * See date_time_mechanism_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. */ void date_time_mechanism_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (TYPE_DATE_TIME_MECHANISM_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gnome.SettingsDaemon.DateTimeMechanism", NULL); } /** * date_time_mechanism_proxy_new_for_bus_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to date_time_mechanism_proxy_new_for_bus(). * @error: Return location for error or %NULL * * Finishes an operation started with date_time_mechanism_proxy_new_for_bus(). * * Returns: (transfer full) (type DateTimeMechanismProxy): The constructed proxy object or %NULL if @error is set. */ DateTimeMechanism * date_time_mechanism_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return DATE_TIME_MECHANISM (ret); else return NULL; } /** * date_time_mechanism_proxy_new_for_bus_sync: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Like date_time_mechanism_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. * * The calling thread is blocked until a reply is received. * * See date_time_mechanism_proxy_new_for_bus() for the asynchronous version of this constructor. * * Returns: (transfer full) (type DateTimeMechanismProxy): The constructed proxy object or %NULL if @error is set. */ DateTimeMechanism * date_time_mechanism_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (TYPE_DATE_TIME_MECHANISM_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gnome.SettingsDaemon.DateTimeMechanism", NULL); if (ret != NULL) return DATE_TIME_MECHANISM (ret); else return NULL; } /* ------------------------------------------------------------------------ */ /** * DateTimeMechanismSkeleton: * * The #DateTimeMechanismSkeleton structure contains only private data and should only be accessed using the provided API. */ /** * DateTimeMechanismSkeletonClass: * @parent_class: The parent class. * * Class structure for #DateTimeMechanismSkeleton. */ struct _DateTimeMechanismSkeletonPrivate { GValueArray *properties; GList *changed_properties; GSource *changed_properties_idle_source; GMainContext *context; GMutex *lock; }; static void _date_time_mechanism_skeleton_handle_method_call ( GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { DateTimeMechanismSkeleton *skeleton = DATE_TIME_MECHANISM_SKELETON (user_data); _ExtendedGDBusMethodInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint n; guint signal_id; GValue return_value = {0}; info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); g_assert (info != NULL); num_params = g_variant_n_children (parameters); paramv = g_new0 (GValue, num_params + 2); g_value_init (&paramv[0], TYPE_DATE_TIME_MECHANISM); g_value_set_object (&paramv[0], skeleton); g_value_init (&paramv[1], G_TYPE_DBUS_METHOD_INVOCATION); g_value_set_object (&paramv[1], invocation); g_variant_iter_init (&iter, parameters); n = 2; while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - 2]; if (arg_info->use_gvariant) { g_value_init (&paramv[n], G_TYPE_VARIANT); g_value_set_variant (&paramv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, &paramv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, TYPE_DATE_TIME_MECHANISM); g_value_init (&return_value, G_TYPE_BOOLEAN); g_signal_emitv (paramv, signal_id, 0, &return_value); if (!g_value_get_boolean (&return_value)) g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); g_value_unset (&return_value); for (n = 0; n < num_params + 2; n++) g_value_unset (&paramv[n]); g_free (paramv); } static GVariant * _date_time_mechanism_skeleton_handle_get_property ( GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *property_name, GError **error, gpointer user_data) { DateTimeMechanismSkeleton *skeleton = DATE_TIME_MECHANISM_SKELETON (user_data); GValue value = {0}; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; GVariant *ret; ret = NULL; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_date_time_mechanism_interface_info, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { g_value_init (&value, pspec->value_type); g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); g_value_unset (&value); } return ret; } static gboolean _date_time_mechanism_skeleton_handle_set_property ( GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *property_name, GVariant *variant, GError **error, gpointer user_data) { DateTimeMechanismSkeleton *skeleton = DATE_TIME_MECHANISM_SKELETON (user_data); GValue value = {0}; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; gboolean ret; ret = FALSE; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_date_time_mechanism_interface_info, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { if (info->use_gvariant) g_value_set_variant (&value, variant); else g_dbus_gvariant_to_gvalue (variant, &value); g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); g_value_unset (&value); ret = TRUE; } return ret; } static const GDBusInterfaceVTable _date_time_mechanism_skeleton_vtable = { _date_time_mechanism_skeleton_handle_method_call, _date_time_mechanism_skeleton_handle_get_property, _date_time_mechanism_skeleton_handle_set_property }; static GDBusInterfaceInfo * date_time_mechanism_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton) { return date_time_mechanism_interface_info (); } static GDBusInterfaceVTable * date_time_mechanism_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton) { return (GDBusInterfaceVTable *) &_date_time_mechanism_skeleton_vtable; } static GVariant * date_time_mechanism_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) { DateTimeMechanismSkeleton *skeleton = DATE_TIME_MECHANISM_SKELETON (_skeleton); GVariantBuilder builder; guint n; g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); if (_date_time_mechanism_interface_info.parent_struct.properties == NULL) goto out; for (n = 0; _date_time_mechanism_interface_info.parent_struct.properties[n] != NULL; n++) { GDBusPropertyInfo *info = _date_time_mechanism_interface_info.parent_struct.properties[n]; if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) { GVariant *value; value = _date_time_mechanism_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "org.gnome.SettingsDaemon.DateTimeMechanism", info->name, NULL, skeleton); if (value != NULL) { if (g_variant_is_floating (value)) g_variant_ref_sink (value); g_variant_builder_add (&builder, "{sv}", info->name, value); g_variant_unref (value); } } } out: return g_variant_builder_end (&builder); } static void date_time_mechanism_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) { } static void date_time_mechanism_skeleton_iface_init (DateTimeMechanismIface *iface) { } #define date_time_mechanism_skeleton_get_type date_time_mechanism_skeleton_get_type G_DEFINE_TYPE_WITH_CODE (DateTimeMechanismSkeleton, date_time_mechanism_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_IMPLEMENT_INTERFACE (TYPE_DATE_TIME_MECHANISM, date_time_mechanism_skeleton_iface_init)); #undef date_time_mechanism_skeleton_get_type static void date_time_mechanism_skeleton_finalize (GObject *object) { DateTimeMechanismSkeleton *skeleton = DATE_TIME_MECHANISM_SKELETON (object); g_list_foreach (skeleton->priv->changed_properties, (GFunc) _changed_property_free, NULL); g_list_free (skeleton->priv->changed_properties); if (skeleton->priv->changed_properties_idle_source != NULL) g_source_destroy (skeleton->priv->changed_properties_idle_source); if (skeleton->priv->context != NULL) g_main_context_unref (skeleton->priv->context); g_mutex_free (skeleton->priv->lock); G_OBJECT_CLASS (date_time_mechanism_skeleton_parent_class)->finalize (object); } static void date_time_mechanism_skeleton_init (DateTimeMechanismSkeleton *skeleton) { skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_DATE_TIME_MECHANISM_SKELETON, DateTimeMechanismSkeletonPrivate); skeleton->priv->lock = g_mutex_new (); skeleton->priv->context = g_main_context_get_thread_default (); if (skeleton->priv->context != NULL) g_main_context_ref (skeleton->priv->context); } static void date_time_mechanism_skeleton_class_init (DateTimeMechanismSkeletonClass *klass) { GObjectClass *gobject_class; GDBusInterfaceSkeletonClass *skeleton_class; g_type_class_add_private (klass, sizeof (DateTimeMechanismSkeletonPrivate)); gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = date_time_mechanism_skeleton_finalize; skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); skeleton_class->get_info = date_time_mechanism_skeleton_dbus_interface_get_info; skeleton_class->get_properties = date_time_mechanism_skeleton_dbus_interface_get_properties; skeleton_class->flush = date_time_mechanism_skeleton_dbus_interface_flush; skeleton_class->get_vtable = date_time_mechanism_skeleton_dbus_interface_get_vtable; } /** * date_time_mechanism_skeleton_new: * * Creates a skeleton object for the D-Bus interface <link linkend="gdbus-interface-org-gnome-SettingsDaemon-DateTimeMechanism.top_of_page">org.gnome.SettingsDaemon.DateTimeMechanism</link>. * * Returns: (transfer full) (type DateTimeMechanismSkeleton): The skeleton object. */ DateTimeMechanism * date_time_mechanism_skeleton_new (void) { return DATE_TIME_MECHANISM (g_object_new (TYPE_DATE_TIME_MECHANISM_SKELETON, NULL)); }
425
./cinnamon-control-center/panels/unused/printers/printers-module.c
/* * Copyright (C) 2010 Red Hat, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <config.h> #include "cc-printers-panel.h" #include <glib/gi18n.h> void g_io_module_load (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); /* register the panel */ cc_printers_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
426
./cinnamon-control-center/panels/unused/printers/pp-new-printer-dialog.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2009-2010 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <unistd.h> #include <stdlib.h> #include <glib.h> #include <glib/gi18n.h> #include <glib/gstdio.h> #include <gtk/gtk.h> #include <cups/cups.h> #include "pp-new-printer-dialog.h" #include "pp-utils.h" #include "pp-host.h" #include "pp-cups.h" #include "pp-new-printer.h" #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #if (CUPS_VERSION_MAJOR > 1) || (CUPS_VERSION_MINOR > 5) #define HAVE_CUPS_1_6 1 #endif #ifndef HAVE_CUPS_1_6 #define ippGetState(ipp) ipp->state #endif static void actualize_devices_list (PpNewPrinterDialog *dialog); static void populate_devices_list (PpNewPrinterDialog *dialog); static void search_address_cb2 (GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event, gpointer user_data); static void search_address_cb (GtkEntry *entry, gpointer user_data); static void new_printer_dialog_response_cb (GtkDialog *_dialog, gint response_id, gpointer user_data); static void t_device_free (gpointer data); enum { DEVICE_ICON_COLUMN = 0, DEVICE_NAME_COLUMN, DEVICE_DISPLAY_NAME_COLUMN, DEVICE_N_COLUMNS }; typedef struct { gchar *display_name; gchar *device_name; gchar *device_original_name; gchar *device_info; gchar *device_location; gchar *device_make_and_model; gchar *device_uri; gchar *device_id; gchar *device_ppd; gchar *host_name; gint host_port; gboolean network_device; gint acquisition_method; gboolean show; } TDevice; struct _PpNewPrinterDialogPrivate { GtkBuilder *builder; GList *devices; GList *new_devices; cups_dest_t *dests; gint num_of_dests; GCancellable *cancellable; gboolean cups_searching; gboolean remote_cups_searching; gboolean snmp_searching; GtkCellRenderer *text_renderer; GtkCellRenderer *icon_renderer; GtkWidget *dialog; }; #define PP_NEW_PRINTER_DIALOG_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), PP_TYPE_NEW_PRINTER_DIALOG, PpNewPrinterDialogPrivate)) static void pp_new_printer_dialog_finalize (GObject *object); enum { PRE_RESPONSE, RESPONSE, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE (PpNewPrinterDialog, pp_new_printer_dialog, G_TYPE_OBJECT) static void pp_new_printer_dialog_class_init (PpNewPrinterDialogClass *klass) { GObjectClass *object_class; object_class = G_OBJECT_CLASS (klass); object_class->finalize = pp_new_printer_dialog_finalize; g_type_class_add_private (object_class, sizeof (PpNewPrinterDialogPrivate)); /** * PpNewPrinterDialog::pre-response: * @device: the device that is being added * * The signal which gets emitted when the new printer dialog is closed. */ signals[PRE_RESPONSE] = g_signal_new ("pre-response", G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (PpNewPrinterDialogClass, pre_response), NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN); /** * PpNewPrinterDialog::response: * @response-id: response id of dialog * * The signal which gets emitted after the printer is added and configured. */ signals[RESPONSE] = g_signal_new ("response", G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (PpNewPrinterDialogClass, response), NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1, G_TYPE_INT); } PpNewPrinterDialog * pp_new_printer_dialog_new (GtkWindow *parent) { PpNewPrinterDialogPrivate *priv; PpNewPrinterDialog *dialog; dialog = g_object_new (PP_TYPE_NEW_PRINTER_DIALOG, NULL); priv = dialog->priv; gtk_window_set_transient_for (GTK_WINDOW (priv->dialog), GTK_WINDOW (parent)); return PP_NEW_PRINTER_DIALOG (dialog); } static void emit_pre_response (PpNewPrinterDialog *dialog, const gchar *device_name, const gchar *device_location, const gchar *device_make_and_model, gboolean network_device) { g_signal_emit (dialog, signals[PRE_RESPONSE], 0, device_name, device_location, device_make_and_model, network_device); } static void emit_response (PpNewPrinterDialog *dialog, gint response_id) { g_signal_emit (dialog, signals[RESPONSE], 0, response_id); } /* * Modify padding of the content area of the GtkDialog * so it is aligned with the action area. */ static void update_alignment_padding (GtkWidget *widget, GtkAllocation *allocation, gpointer user_data) { PpNewPrinterDialog *dialog = (PpNewPrinterDialog*) user_data; PpNewPrinterDialogPrivate *priv = dialog->priv; GtkAllocation allocation1, allocation2; GtkWidget *action_area; GtkWidget *content_area; gint offset_left, offset_right; guint padding_left, padding_right, padding_top, padding_bottom; action_area = (GtkWidget*) gtk_builder_get_object (priv->builder, "dialog-action-area1"); gtk_widget_get_allocation (action_area, &allocation2); content_area = (GtkWidget*) gtk_builder_get_object (priv->builder, "content-alignment"); gtk_widget_get_allocation (content_area, &allocation1); offset_left = allocation2.x - allocation1.x; offset_right = (allocation1.x + allocation1.width) - (allocation2.x + allocation2.width); gtk_alignment_get_padding (GTK_ALIGNMENT (content_area), &padding_top, &padding_bottom, &padding_left, &padding_right); if (allocation1.x >= 0 && allocation2.x >= 0) { if (offset_left > 0 && offset_left != padding_left) gtk_alignment_set_padding (GTK_ALIGNMENT (content_area), padding_top, padding_bottom, offset_left, padding_right); gtk_alignment_get_padding (GTK_ALIGNMENT (content_area), &padding_top, &padding_bottom, &padding_left, &padding_right); if (offset_right > 0 && offset_right != padding_right) gtk_alignment_set_padding (GTK_ALIGNMENT (content_area), padding_top, padding_bottom, padding_left, offset_right); } } static void pp_new_printer_dialog_init (PpNewPrinterDialog *dialog) { PpNewPrinterDialogPrivate *priv; GtkStyleContext *context; GtkWidget *widget; GError *error = NULL; gchar *objects[] = { "dialog", NULL }; guint builder_result; priv = PP_NEW_PRINTER_DIALOG_GET_PRIVATE (dialog); dialog->priv = priv; priv->builder = gtk_builder_new (); builder_result = gtk_builder_add_objects_from_file (priv->builder, DATADIR"/new-printer-dialog.ui", objects, &error); if (builder_result == 0) { g_warning ("Could not load ui: %s", error->message); g_error_free (error); } /* GCancellable for cancelling of async operations */ priv->cancellable = g_cancellable_new (); priv->devices = NULL; priv->new_devices = NULL; priv->dests = NULL; priv->num_of_dests = 0; priv->cups_searching = FALSE; priv->remote_cups_searching = FALSE; priv->snmp_searching = FALSE; priv->text_renderer = NULL; priv->icon_renderer = NULL; /* Construct dialog */ priv->dialog = (GtkWidget*) gtk_builder_get_object (priv->builder, "dialog"); /* Connect signals */ g_signal_connect (priv->dialog, "response", G_CALLBACK (new_printer_dialog_response_cb), dialog); g_signal_connect (priv->dialog, "size-allocate", G_CALLBACK (update_alignment_padding), dialog); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "search-entry"); g_signal_connect (widget, "icon-press", G_CALLBACK (search_address_cb2), dialog); g_signal_connect (widget, "activate", G_CALLBACK (search_address_cb), dialog); /* Set junctions */ widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "scrolledwindow1"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "toolbar1"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); /* Fill with data */ populate_devices_list (dialog); gtk_widget_show (priv->dialog); } static void pp_new_printer_dialog_finalize (GObject *object) { PpNewPrinterDialog *dialog = PP_NEW_PRINTER_DIALOG (object); PpNewPrinterDialogPrivate *priv = dialog->priv; priv->text_renderer = NULL; priv->icon_renderer = NULL; if (priv->cancellable) { g_cancellable_cancel (priv->cancellable); g_clear_object (&priv->cancellable); } if (priv->builder) g_clear_object (&priv->builder); g_list_free_full (priv->devices, t_device_free); priv->devices = NULL; g_list_free_full (priv->new_devices, t_device_free); priv->new_devices = NULL; if (priv->num_of_dests > 0) { cupsFreeDests (priv->num_of_dests, priv->dests); priv->num_of_dests = 0; priv->dests = NULL; } G_OBJECT_CLASS (pp_new_printer_dialog_parent_class)->finalize (object); } static void device_selection_changed_cb (GtkTreeSelection *selection, gpointer user_data) { PpNewPrinterDialog *dialog = PP_NEW_PRINTER_DIALOG (user_data); PpNewPrinterDialogPrivate *priv = dialog->priv; GtkTreeModel *model; GtkTreeIter iter; GtkWidget *treeview = NULL; GtkWidget *widget; treeview = (GtkWidget*) gtk_builder_get_object (priv->builder, "devices-treeview"); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "new-printer-add-button"); if (treeview) gtk_widget_set_sensitive (widget, gtk_tree_selection_get_selected ( gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), &model, &iter)); } static void add_device_to_list (PpNewPrinterDialog *dialog, PpPrintDevice *device, gboolean new_device) { PpNewPrinterDialogPrivate *priv = dialog->priv; gboolean network_device; gboolean already_present; TDevice *store_device; TDevice *item; GList *iter; gchar *name = NULL; gchar *canonized_name = NULL; gchar *new_name; gchar *new_canonized_name = NULL; gint name_index, j; if (device) { if (device->device_id || device->device_ppd || (device->host_name && device->acquisition_method == ACQUISITION_METHOD_REMOTE_CUPS_SERVER)) { network_device = FALSE; if (device->device_class && g_strcmp0 (device->device_class, "network") == 0) network_device = TRUE; store_device = g_new0 (TDevice, 1); store_device->device_original_name = g_strdup (device->device_name); store_device->device_info = g_strdup (device->device_info); store_device->device_location = g_strdup (device->device_location); store_device->device_make_and_model = g_strdup (device->device_make_and_model); store_device->device_uri = g_strdup (device->device_uri); store_device->device_id = g_strdup (device->device_id); store_device->device_ppd = g_strdup (device->device_ppd); store_device->host_name = g_strdup (device->host_name); store_device->host_port = device->host_port; store_device->network_device = network_device; store_device->acquisition_method = device->acquisition_method; store_device->show = TRUE; if (device->device_id) { name = get_tag_value (device->device_id, "mdl"); if (!name) name = get_tag_value (device->device_id, "model"); } if (!name && device->device_make_and_model && device->device_make_and_model[0] != '\0') { name = g_strdup (device->device_make_and_model); } if (!name && device->device_name && device->device_name[0] != '\0') { name = g_strdup (device->device_name); } if (!name && device->device_info && device->device_info[0] != '\0') { name = g_strdup (device->device_info); } g_strstrip (name); name_index = 2; already_present = FALSE; do { if (already_present) { new_name = g_strdup_printf ("%s %d", name, name_index); name_index++; } else { new_name = g_strdup (name); } if (new_name) { new_canonized_name = g_strcanon (g_strdup (new_name), ALLOWED_CHARACTERS, '-'); } already_present = FALSE; for (j = 0; j < priv->num_of_dests; j++) if (g_strcmp0 (priv->dests[j].name, new_canonized_name) == 0) already_present = TRUE; for (iter = priv->devices; iter; iter = iter->next) { item = (TDevice *) iter->data; if (g_strcmp0 (item->device_name, new_canonized_name) == 0) already_present = TRUE; } for (iter = priv->new_devices; iter; iter = iter->next) { item = (TDevice *) iter->data; if (g_strcmp0 (item->device_name, new_canonized_name) == 0) already_present = TRUE; } if (already_present) { g_free (new_name); g_free (new_canonized_name); } else { g_free (name); g_free (canonized_name); name = new_name; canonized_name = new_canonized_name; } } while (already_present); store_device->display_name = g_strdup (canonized_name); store_device->device_name = canonized_name; g_free (name); if (new_device) priv->new_devices = g_list_append (priv->new_devices, store_device); else priv->devices = g_list_append (priv->devices, store_device); } } } static void add_devices_to_list (PpNewPrinterDialog *dialog, GList *devices, gboolean new_device) { GList *iter; for (iter = devices; iter; iter = iter->next) { add_device_to_list (dialog, (PpPrintDevice *) iter->data, new_device); } } static TDevice * device_in_list (gchar *device_uri, GList *device_list) { GList *iter; TDevice *device; for (iter = device_list; iter; iter = iter->next) { device = (TDevice *) iter->data; /* GroupPhysicalDevices returns uris without port numbers */ if (g_str_has_prefix (device->device_uri, device_uri)) return device; } return NULL; } static void t_device_free (gpointer data) { if (data) { TDevice *device = (TDevice *) data; g_free (device->display_name); g_free (device->device_name); g_free (device->device_original_name); g_free (device->device_info); g_free (device->device_location); g_free (device->device_make_and_model); g_free (device->device_uri); g_free (device->device_id); g_free (device->device_ppd); g_free (device); } } static void update_spinner_state (PpNewPrinterDialog *dialog) { PpNewPrinterDialogPrivate *priv = dialog->priv; GtkWidget *spinner; if (priv->cups_searching || priv->remote_cups_searching || priv->snmp_searching) { spinner = (GtkWidget*) gtk_builder_get_object (priv->builder, "spinner"); gtk_spinner_start (GTK_SPINNER (spinner)); gtk_widget_show (spinner); } else { spinner = (GtkWidget*) gtk_builder_get_object (priv->builder, "spinner"); gtk_spinner_stop (GTK_SPINNER (spinner)); gtk_widget_hide (spinner); } } static void group_physical_devices_cb (gchar ***device_uris, gpointer user_data) { PpNewPrinterDialog *dialog = (PpNewPrinterDialog *) user_data; PpNewPrinterDialogPrivate *priv = dialog->priv; TDevice *device, *tmp; gint i, j; if (device_uris) { for (i = 0; device_uris[i]; i++) { if (device_uris[i]) { for (j = 0; device_uris[i][j]; j++) { device = device_in_list (device_uris[i][j], priv->devices); if (device) break; } if (device) { for (j = 0; device_uris[i][j]; j++) { tmp = device_in_list (device_uris[i][j], priv->new_devices); if (tmp) { priv->new_devices = g_list_remove (priv->new_devices, tmp); t_device_free (tmp); } } } else { for (j = 0; device_uris[i][j]; j++) { tmp = device_in_list (device_uris[i][j], priv->new_devices); if (tmp) { priv->new_devices = g_list_remove (priv->new_devices, tmp); if (j == 0) { priv->devices = g_list_append (priv->devices, tmp); } else { t_device_free (tmp); } } } } } } for (i = 0; device_uris[i]; i++) { for (j = 0; device_uris[i][j]; j++) { g_free (device_uris[i][j]); } g_free (device_uris[i]); } g_free (device_uris); } else { priv->devices = g_list_concat (priv->devices, priv->new_devices); priv->new_devices = NULL; } actualize_devices_list (dialog); } static void group_physical_devices_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; GError *error = NULL; gchar ***result = NULL; gint i, j; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { GVariant *array; g_variant_get (output, "(@aas)", &array); if (array) { GVariantIter *iter; GVariantIter *subiter; GVariant *item; GVariant *subitem; gchar *device_uri; result = g_new0 (gchar **, g_variant_n_children (array) + 1); g_variant_get (array, "aas", &iter); i = 0; while ((item = g_variant_iter_next_value (iter))) { result[i] = g_new0 (gchar *, g_variant_n_children (item) + 1); g_variant_get (item, "as", &subiter); j = 0; while ((subitem = g_variant_iter_next_value (subiter))) { g_variant_get (subitem, "s", &device_uri); result[i][j] = device_uri; g_variant_unref (subitem); j++; } g_variant_unref (item); i++; } g_variant_unref (array); } g_variant_unref (output); } else if (error && error->domain == G_DBUS_ERROR && (error->code == G_DBUS_ERROR_SERVICE_UNKNOWN || error->code == G_DBUS_ERROR_UNKNOWN_METHOD)) { g_warning ("Install system-config-printer which provides \ DBus method \"GroupPhysicalDevices\" to group duplicates in device list."); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); } if (!error || error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) group_physical_devices_cb (result, user_data); if (error) g_error_free (error); } static void get_cups_devices_cb (GList *devices, gboolean finished, gboolean cancelled, gpointer user_data) { PpNewPrinterDialog *dialog; PpNewPrinterDialogPrivate *priv; GDBusConnection *bus; GVariantBuilder device_list; GVariantBuilder device_hash; PpPrintDevice **all_devices; PpPrintDevice *pp_device; TDevice *device; GError *error = NULL; GList *iter; gint length, i; if (!cancelled) { dialog = (PpNewPrinterDialog*) user_data; priv = dialog->priv; if (finished) { priv->cups_searching = FALSE; } if (devices) { add_devices_to_list (dialog, devices, TRUE); length = g_list_length (priv->devices) + g_list_length (devices); if (length > 0) { all_devices = g_new0 (PpPrintDevice *, length); i = 0; for (iter = priv->devices; iter; iter = iter->next) { device = (TDevice *) iter->data; if (device) { all_devices[i] = g_new0 (PpPrintDevice, 1); all_devices[i]->device_id = g_strdup (device->device_id); all_devices[i]->device_make_and_model = g_strdup (device->device_make_and_model); all_devices[i]->device_class = device->network_device ? g_strdup ("network") : strdup ("direct"); all_devices[i]->device_uri = g_strdup (device->device_uri); } i++; } for (iter = devices; iter; iter = iter->next) { pp_device = (PpPrintDevice *) iter->data; if (pp_device) { all_devices[i] = g_new0 (PpPrintDevice, 1); all_devices[i]->device_id = g_strdup (pp_device->device_id); all_devices[i]->device_make_and_model = g_strdup (pp_device->device_make_and_model); all_devices[i]->device_class = g_strdup (pp_device->device_class); all_devices[i]->device_uri = g_strdup (pp_device->device_uri); } i++; } bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (bus) { g_variant_builder_init (&device_list, G_VARIANT_TYPE ("a{sv}")); for (i = 0; i < length; i++) { if (all_devices[i]->device_uri) { g_variant_builder_init (&device_hash, G_VARIANT_TYPE ("a{ss}")); if (all_devices[i]->device_id) g_variant_builder_add (&device_hash, "{ss}", "device-id", all_devices[i]->device_id); if (all_devices[i]->device_make_and_model) g_variant_builder_add (&device_hash, "{ss}", "device-make-and-model", all_devices[i]->device_make_and_model); if (all_devices[i]->device_class) g_variant_builder_add (&device_hash, "{ss}", "device-class", all_devices[i]->device_class); g_variant_builder_add (&device_list, "{sv}", all_devices[i]->device_uri, g_variant_builder_end (&device_hash)); } } g_dbus_connection_call (bus, SCP_BUS, SCP_PATH, SCP_IFACE, "GroupPhysicalDevices", g_variant_new ("(v)", g_variant_builder_end (&device_list)), G_VARIANT_TYPE ("(aas)"), G_DBUS_CALL_FLAGS_NONE, -1, priv->cancellable, group_physical_devices_dbus_cb, dialog); } else { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); group_physical_devices_cb (NULL, user_data); } for (i = 0; i < length; i++) { if (all_devices[i]) { g_free (all_devices[i]->device_id); g_free (all_devices[i]->device_make_and_model); g_free (all_devices[i]->device_class); g_free (all_devices[i]->device_uri); g_free (all_devices[i]); } } g_free (all_devices); } else { actualize_devices_list (dialog); } } else { actualize_devices_list (dialog); } } for (iter = devices; iter; iter = iter->next) pp_print_device_free ((PpPrintDevice *) iter->data); g_list_free (devices); } static void get_snmp_devices_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinterDialog *dialog; PpNewPrinterDialogPrivate *priv; PpHost *host = (PpHost *) source_object; GError *error = NULL; PpDevicesList *result; GList *iter; result = pp_host_get_snmp_devices_finish (host, res, &error); g_object_unref (source_object); if (result) { dialog = PP_NEW_PRINTER_DIALOG (user_data); priv = dialog->priv; priv->snmp_searching = FALSE; update_spinner_state (dialog); if (result->devices) { add_devices_to_list (dialog, result->devices, FALSE); } actualize_devices_list (dialog); for (iter = result->devices; iter; iter = iter->next) pp_print_device_free ((PpPrintDevice *) iter->data); g_list_free (result->devices); g_free (result); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { dialog = PP_NEW_PRINTER_DIALOG (user_data); priv = dialog->priv; g_warning ("%s", error->message); priv->snmp_searching = FALSE; update_spinner_state (dialog); } g_error_free (error); } } static void get_remote_cups_devices_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinterDialog *dialog; PpNewPrinterDialogPrivate *priv; PpHost *host = (PpHost *) source_object; GError *error = NULL; PpDevicesList *result; GList *iter; result = pp_host_get_remote_cups_devices_finish (host, res, &error); g_object_unref (source_object); if (result) { dialog = PP_NEW_PRINTER_DIALOG (user_data); priv = dialog->priv; priv->remote_cups_searching = FALSE; update_spinner_state (dialog); if (result->devices) { add_devices_to_list (dialog, result->devices, FALSE); } actualize_devices_list (dialog); for (iter = result->devices; iter; iter = iter->next) pp_print_device_free ((PpPrintDevice *) iter->data); g_list_free (result->devices); g_free (result); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { dialog = PP_NEW_PRINTER_DIALOG (user_data); priv = dialog->priv; g_warning ("%s", error->message); priv->remote_cups_searching = FALSE; update_spinner_state (dialog); } g_error_free (error); } } static void get_cups_devices (PpNewPrinterDialog *dialog) { PpNewPrinterDialogPrivate *priv = dialog->priv; priv->cups_searching = TRUE; update_spinner_state (dialog); get_cups_devices_async (priv->cancellable, get_cups_devices_cb, dialog); } static gboolean parse_uri (gchar *uri, gchar **host, gint *port) { gchar *tmp = NULL; gchar *resulting_host = NULL; gchar *port_string = NULL; gchar *position; int resulting_port = 631; if (g_strrstr (uri, "://")) tmp = g_strrstr (uri, "://") + 3; else tmp = uri; if (g_strrstr (tmp, "@")) tmp = g_strrstr (tmp, "@") + 1; if ((position = g_strrstr (tmp, "/"))) { *position = '\0'; resulting_host = g_strdup (tmp); *position = '/'; } else resulting_host = g_strdup (tmp); if ((position = g_strrstr (resulting_host, ":"))) { *position = '\0'; port_string = position + 1; } if (port_string) resulting_port = atoi (port_string); *host = resulting_host; *port = resulting_port; return TRUE; } static void search_address_cb (GtkEntry *entry, gpointer user_data) { PpNewPrinterDialog *dialog = PP_NEW_PRINTER_DIALOG (user_data); PpNewPrinterDialogPrivate *priv = dialog->priv; gboolean found = FALSE; gboolean subfound; TDevice *device; GList *iter, *tmp; gchar *text; gchar *lowercase_name; gchar *lowercase_location; gchar *lowercase_text; gchar **words; gint words_length = 0; gint i; text = g_strdup (gtk_entry_get_text (entry)); lowercase_text = g_ascii_strdown (text, -1); words = g_strsplit_set (lowercase_text, " ", -1); g_free (lowercase_text); if (words) { words_length = g_strv_length (words); for (iter = priv->devices; iter; iter = iter->next) { device = iter->data; lowercase_name = g_ascii_strdown (device->device_name, -1); if (device->device_location) lowercase_location = g_ascii_strdown (device->device_location, -1); else lowercase_location = NULL; subfound = TRUE; for (i = 0; words[i]; i++) { if (!g_strrstr (lowercase_name, words[i]) && (!lowercase_location || !g_strrstr (lowercase_location, words[i]))) subfound = FALSE; } if (subfound) { device->show = TRUE; found = TRUE; } else { device->show = FALSE; } g_free (lowercase_location); g_free (lowercase_name); } g_strfreev (words); } if (!found && words_length == 1) { iter = priv->devices; while (iter) { device = iter->data; device->show = TRUE; if (device->acquisition_method == ACQUISITION_METHOD_REMOTE_CUPS_SERVER || device->acquisition_method == ACQUISITION_METHOD_SNMP) { tmp = iter; iter = iter->next; priv->devices = g_list_remove_link (priv->devices, tmp); g_list_free_full (tmp, t_device_free); } else iter = iter->next; } iter = priv->new_devices; while (iter) { device = iter->data; if (device->acquisition_method == ACQUISITION_METHOD_REMOTE_CUPS_SERVER || device->acquisition_method == ACQUISITION_METHOD_SNMP) { tmp = iter; iter = iter->next; priv->new_devices = g_list_remove_link (priv->new_devices, tmp); g_list_free_full (tmp, t_device_free); } else iter = iter->next; } if (text && text[0] != '\0') { gchar *host = NULL; gint port = 631; parse_uri (text, &host, &port); if (host) { PpHost *snmp_host; PpHost *remote_cups_host; snmp_host = pp_host_new (host, port); remote_cups_host = g_object_ref (snmp_host); priv->remote_cups_searching = TRUE; priv->snmp_searching = TRUE; update_spinner_state (dialog); pp_host_get_remote_cups_devices_async (snmp_host, priv->cancellable, get_remote_cups_devices_cb, dialog); pp_host_get_snmp_devices_async (remote_cups_host, priv->cancellable, get_snmp_devices_cb, dialog); g_free (host); } } } actualize_devices_list (dialog); g_free (text); } static void search_address_cb2 (GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event, gpointer user_data) { search_address_cb (entry, user_data); } static void actualize_devices_list (PpNewPrinterDialog *dialog) { PpNewPrinterDialogPrivate *priv = dialog->priv; GtkTreeViewColumn *column; GtkTreeSelection *selection; GtkListStore *store; GtkTreeView *treeview; GtkTreeIter iter; gboolean no_device = TRUE; TDevice *device; gfloat yalign; GList *item; gchar *display_string; treeview = (GtkTreeView *) gtk_builder_get_object (priv->builder, "devices-treeview"); store = gtk_list_store_new (3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); for (item = priv->devices; item; item = item->next) { device = (TDevice *) item->data; if (device->display_name && (device->device_id || device->device_ppd || (device->host_name && device->acquisition_method == ACQUISITION_METHOD_REMOTE_CUPS_SERVER)) && device->show) { if (device->device_location) display_string = g_markup_printf_escaped ("<b>%s</b>\n<small><span foreground=\"#555555\">%s</span></small>", device->display_name, device->device_location); else display_string = g_markup_printf_escaped ("<b>%s</b>\n ", device->display_name); gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, DEVICE_ICON_COLUMN, device->network_device ? "printer-network" : "printer", DEVICE_NAME_COLUMN, device->device_name, DEVICE_DISPLAY_NAME_COLUMN, display_string, -1); no_device = FALSE; g_free (display_string); } } column = gtk_tree_view_get_column (treeview, 0); if (priv->text_renderer) gtk_cell_renderer_get_alignment (priv->text_renderer, NULL, &yalign); if (no_device && !priv->cups_searching && !priv->remote_cups_searching && !priv->snmp_searching) { if (priv->text_renderer) gtk_cell_renderer_set_alignment (priv->text_renderer, 0.5, yalign); if (column) gtk_tree_view_column_set_max_width (column, 0); gtk_widget_set_sensitive (GTK_WIDGET (treeview), FALSE); display_string = g_markup_printf_escaped ("<b>%s</b>\n", /* Translators: No printers were found */ _("No printers detected.")); gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, DEVICE_DISPLAY_NAME_COLUMN, display_string, -1); g_free (display_string); } else { if (priv->text_renderer) gtk_cell_renderer_set_alignment (priv->text_renderer, 0.0, yalign); if (column) { gtk_tree_view_column_set_max_width (column, -1); gtk_tree_view_column_set_min_width (column, 80); } gtk_widget_set_sensitive (GTK_WIDGET (treeview), TRUE); } gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (store)); if (!no_device && gtk_tree_model_get_iter_first ((GtkTreeModel *) store, &iter) && (selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview))) != NULL) gtk_tree_selection_select_iter (selection, &iter); g_object_unref (store); update_spinner_state (dialog); } static void cups_get_dests_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinterDialog *dialog; PpNewPrinterDialogPrivate *priv; PpCupsDests *dests; PpCups *cups = (PpCups *) source_object; GError *error = NULL; dests = pp_cups_get_dests_finish (cups, res, &error); g_object_unref (source_object); if (dests) { dialog = PP_NEW_PRINTER_DIALOG (user_data); priv = dialog->priv; priv->dests = dests->dests; priv->num_of_dests = dests->num_of_dests; get_cups_devices (dialog); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { dialog = PP_NEW_PRINTER_DIALOG (user_data); g_warning ("%s", error->message); get_cups_devices (dialog); } g_error_free (error); } } static void populate_devices_list (PpNewPrinterDialog *dialog) { PpNewPrinterDialogPrivate *priv = dialog->priv; GtkTreeViewColumn *column; GtkWidget *treeview; PpCups *cups; treeview = (GtkWidget*) gtk_builder_get_object (priv->builder, "devices-treeview"); g_signal_connect (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), "changed", G_CALLBACK (device_selection_changed_cb), dialog); priv->icon_renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (priv->icon_renderer, "stock-size", GTK_ICON_SIZE_DIALOG, NULL); gtk_cell_renderer_set_alignment (priv->icon_renderer, 1.0, 0.5); gtk_cell_renderer_set_padding (priv->icon_renderer, 4, 4); column = gtk_tree_view_column_new_with_attributes ("Icon", priv->icon_renderer, "icon-name", DEVICE_ICON_COLUMN, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); priv->text_renderer = gtk_cell_renderer_text_new (); column = gtk_tree_view_column_new_with_attributes ("Devices", priv->text_renderer, "markup", DEVICE_DISPLAY_NAME_COLUMN, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); cups = pp_cups_new (); pp_cups_get_dests_async (cups, priv->cancellable, cups_get_dests_cb, dialog); } static void printer_add_async_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinterDialog *dialog; GtkResponseType response_id = GTK_RESPONSE_OK; PpNewPrinter *new_printer = (PpNewPrinter *) source_object; gboolean success; GError *error = NULL; success = pp_new_printer_add_finish (new_printer, res, &error); g_object_unref (source_object); if (success) { dialog = PP_NEW_PRINTER_DIALOG (user_data); emit_response (dialog, response_id); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { dialog = PP_NEW_PRINTER_DIALOG (user_data); g_warning ("%s", error->message); response_id = GTK_RESPONSE_REJECT; emit_response (dialog, response_id); } g_error_free (error); } } static void new_printer_dialog_response_cb (GtkDialog *_dialog, gint response_id, gpointer user_data) { PpNewPrinterDialog *dialog = (PpNewPrinterDialog*) user_data; PpNewPrinterDialogPrivate *priv = dialog->priv; GtkTreeModel *model; GtkTreeIter iter; GtkWidget *treeview; TDevice *device = NULL; TDevice *tmp; GList *list_iter; gchar *device_name = NULL; gtk_widget_hide (GTK_WIDGET (_dialog)); if (response_id == GTK_RESPONSE_OK) { g_cancellable_cancel (priv->cancellable); g_clear_object (&priv->cancellable); treeview = (GtkWidget*) gtk_builder_get_object (priv->builder, "devices-treeview"); if (treeview && gtk_tree_selection_get_selected ( gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), &model, &iter)) { gtk_tree_model_get (model, &iter, DEVICE_NAME_COLUMN, &device_name, -1); } for (list_iter = priv->devices; list_iter; list_iter = list_iter->next) { tmp = (TDevice *) list_iter->data; if (tmp && g_strcmp0 (tmp->device_name, device_name) == 0) { device = tmp; break; } } if (device) { PpNewPrinter *new_printer; guint window_id = 0; emit_pre_response (dialog, device->device_name, device->device_location, device->device_make_and_model, device->network_device); #ifdef GDK_WINDOWING_X11 window_id = GDK_WINDOW_XID (gtk_widget_get_window (GTK_WIDGET (_dialog))); #endif new_printer = pp_new_printer_new (); g_object_set (new_printer, "name", device->device_name, "original-name""", device->device_original_name, "device-uri", device->device_uri, "device-id", device->device_id, "ppd-name", device->device_ppd, "ppd-file-name", device->device_ppd, "info", device->device_info, "location", device->device_location, "make-and-model", device->device_make_and_model, "host-name", device->host_name, "host-port", device->host_port, "is-network-device", device->network_device, "window-id", window_id, NULL); priv->cancellable = g_cancellable_new (); pp_new_printer_add_async (new_printer, priv->cancellable, printer_add_async_cb, dialog); } } else { emit_response (dialog, GTK_RESPONSE_CANCEL); } }
427
./cinnamon-control-center/panels/unused/printers/pp-ppd-selection-dialog.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "config.h" #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <glib.h> #include <glib/gi18n.h> #include <glib/gstdio.h> #include <gtk/gtk.h> #include <cups/cups.h> #include <cups/ppd.h> #include "pp-ppd-selection-dialog.h" static void pp_ppd_selection_dialog_hide (PpPPDSelectionDialog *dialog); enum { PPD_NAMES_COLUMN = 0, PPD_DISPLAY_NAMES_COLUMN }; enum { PPD_MANUFACTURERS_NAMES_COLUMN = 0, PPD_MANUFACTURERS_DISPLAY_NAMES_COLUMN }; struct _PpPPDSelectionDialog { GtkBuilder *builder; GtkWidget *parent; GtkWidget *dialog; UserResponseCallback user_callback; gpointer user_data; gchar *ppd_name; GtkResponseType response; gchar *manufacturer; PPDList *list; }; static void manufacturer_selection_changed_cb (GtkTreeSelection *selection, gpointer user_data) { PpPPDSelectionDialog *dialog = (PpPPDSelectionDialog *) user_data; GtkListStore *store; GtkTreeModel *model; GtkTreeIter iter; GtkTreeView *models_treeview; gchar *manufacturer_name = NULL; gint i, index; if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, PPD_MANUFACTURERS_NAMES_COLUMN, &manufacturer_name, -1); } if (manufacturer_name) { index = -1; for (i = 0; i < dialog->list->num_of_manufacturers; i++) { if (g_strcmp0 (manufacturer_name, dialog->list->manufacturers[i]->manufacturer_name) == 0) { index = i; break; } } if (index >= 0) { models_treeview = (GtkTreeView*) gtk_builder_get_object (dialog->builder, "ppd-selection-models-treeview"); store = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_STRING); for (i = 0; i < dialog->list->manufacturers[index]->num_of_ppds; i++) { gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, PPD_NAMES_COLUMN, dialog->list->manufacturers[index]->ppds[i]->ppd_name, PPD_DISPLAY_NAMES_COLUMN, dialog->list->manufacturers[index]->ppds[i]->ppd_display_name, -1); } gtk_tree_view_set_model (models_treeview, GTK_TREE_MODEL (store)); g_object_unref (store); } g_free (manufacturer_name); } } static void model_selection_changed_cb (GtkTreeSelection *selection, gpointer user_data) { PpPPDSelectionDialog *dialog = (PpPPDSelectionDialog *) user_data; GtkTreeModel *model; GtkTreeIter iter; GtkWidget *widget; gchar *model_name = NULL; if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, PPD_NAMES_COLUMN, &model_name, -1); } widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "ppd-selection-select-button"); if (model_name) { gtk_widget_set_sensitive (widget, TRUE); g_free (model_name); } else { gtk_widget_set_sensitive (widget, FALSE); } } static void fill_ppds_list (PpPPDSelectionDialog *dialog) { GtkTreeSelection *selection; GtkListStore *store; GtkTreePath *path; GtkTreeView *treeview; GtkTreeIter iter; GtkTreeIter *preselect_iter = NULL; GtkWidget *widget; gint i; widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "ppd-spinner"); gtk_widget_hide (widget); gtk_spinner_stop (GTK_SPINNER (widget)); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "progress-label"); gtk_widget_hide (widget); treeview = (GtkTreeView*) gtk_builder_get_object (dialog->builder, "ppd-selection-manufacturers-treeview"); if (dialog->list) { store = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_STRING); for (i = 0; i < dialog->list->num_of_manufacturers; i++) { gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, PPD_MANUFACTURERS_NAMES_COLUMN, dialog->list->manufacturers[i]->manufacturer_name, PPD_MANUFACTURERS_DISPLAY_NAMES_COLUMN, dialog->list->manufacturers[i]->manufacturer_display_name, -1); if (g_strcmp0 (dialog->manufacturer, dialog->list->manufacturers[i]->manufacturer_display_name) == 0) { preselect_iter = gtk_tree_iter_copy (&iter); } } gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (store)); if (preselect_iter && (selection = gtk_tree_view_get_selection (treeview)) != NULL) { gtk_tree_selection_select_iter (selection, preselect_iter); path = gtk_tree_model_get_path (GTK_TREE_MODEL (store), preselect_iter); gtk_tree_view_scroll_to_cell (treeview, path, NULL, TRUE, 0.5, 0.0); gtk_tree_path_free (path); gtk_tree_iter_free (preselect_iter); } g_object_unref (store); } } static void populate_dialog (PpPPDSelectionDialog *dialog) { GtkTreeViewColumn *column; GtkCellRenderer *renderer; GtkTreeView *manufacturers_treeview; GtkTreeView *models_treeview; GtkWidget *widget; manufacturers_treeview = (GtkTreeView*) gtk_builder_get_object (dialog->builder, "ppd-selection-manufacturers-treeview"); renderer = gtk_cell_renderer_text_new (); /* Translators: Name of column showing printer manufacturers */ column = gtk_tree_view_column_new_with_attributes (_("Manufacturers"), renderer, "text", PPD_MANUFACTURERS_DISPLAY_NAMES_COLUMN, NULL); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_view_append_column (manufacturers_treeview, column); models_treeview = (GtkTreeView*) gtk_builder_get_object (dialog->builder, "ppd-selection-models-treeview"); renderer = gtk_cell_renderer_text_new (); /* Translators: Name of column showing printer drivers */ column = gtk_tree_view_column_new_with_attributes (_("Drivers"), renderer, "text", PPD_DISPLAY_NAMES_COLUMN, NULL); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_view_append_column (models_treeview, column); g_signal_connect (gtk_tree_view_get_selection (models_treeview), "changed", G_CALLBACK (model_selection_changed_cb), dialog); g_signal_connect (gtk_tree_view_get_selection (manufacturers_treeview), "changed", G_CALLBACK (manufacturer_selection_changed_cb), dialog); gtk_widget_show_all (dialog->dialog); if (!dialog->list) { widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "ppd-spinner"); gtk_widget_show (widget); gtk_spinner_start (GTK_SPINNER (widget)); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "progress-label"); gtk_widget_show (widget); } else { fill_ppds_list (dialog); } } static void ppd_selection_dialog_response_cb (GtkDialog *dialog, gint response_id, gpointer user_data) { PpPPDSelectionDialog *ppd_selection_dialog = (PpPPDSelectionDialog*) user_data; GtkTreeSelection *selection; GtkTreeModel *model; GtkTreeView *models_treeview; GtkTreeIter iter; pp_ppd_selection_dialog_hide (ppd_selection_dialog); ppd_selection_dialog->response = response_id; if (response_id == GTK_RESPONSE_OK) { models_treeview = (GtkTreeView*) gtk_builder_get_object (ppd_selection_dialog->builder, "ppd-selection-models-treeview"); if (models_treeview) { selection = gtk_tree_view_get_selection (models_treeview); if (selection) { if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, PPD_NAMES_COLUMN, &ppd_selection_dialog->ppd_name, -1); } } } } ppd_selection_dialog->user_callback (GTK_DIALOG (ppd_selection_dialog->dialog), response_id, ppd_selection_dialog->user_data); } static void update_alignment_padding (GtkWidget *widget, GtkAllocation *allocation, gpointer user_data) { PpPPDSelectionDialog *dialog = (PpPPDSelectionDialog*) user_data; GtkAllocation allocation2; GtkWidget *action_area; gint offset_left, offset_right; guint padding_left, padding_right, padding_top, padding_bottom; action_area = (GtkWidget*) gtk_builder_get_object (dialog->builder, "dialog-action-area1"); gtk_widget_get_allocation (action_area, &allocation2); offset_left = allocation2.x - allocation->x; offset_right = (allocation->x + allocation->width) - (allocation2.x + allocation2.width); gtk_alignment_get_padding (GTK_ALIGNMENT (widget), &padding_top, &padding_bottom, &padding_left, &padding_right); if (allocation->x >= 0 && allocation2.x >= 0) { if (offset_left > 0 && offset_left != padding_left) gtk_alignment_set_padding (GTK_ALIGNMENT (widget), padding_top, padding_bottom, offset_left, padding_right); gtk_alignment_get_padding (GTK_ALIGNMENT (widget), &padding_top, &padding_bottom, &padding_left, &padding_right); if (offset_right > 0 && offset_right != padding_right) gtk_alignment_set_padding (GTK_ALIGNMENT (widget), padding_top, padding_bottom, padding_left, offset_right); } } PpPPDSelectionDialog * pp_ppd_selection_dialog_new (GtkWindow *parent, PPDList *ppd_list, gchar *manufacturer, UserResponseCallback user_callback, gpointer user_data) { PpPPDSelectionDialog *dialog; GtkWidget *widget; GError *error = NULL; gchar *objects[] = { "ppd-selection-dialog", NULL }; guint builder_result; dialog = g_new0 (PpPPDSelectionDialog, 1); dialog->builder = gtk_builder_new (); dialog->parent = GTK_WIDGET (parent); builder_result = gtk_builder_add_objects_from_file (dialog->builder, DATADIR"/ppd-selection-dialog.ui", objects, &error); if (builder_result == 0) { g_warning ("Could not load ui: %s", error->message); g_error_free (error); return NULL; } dialog->dialog = (GtkWidget *) gtk_builder_get_object (dialog->builder, "ppd-selection-dialog"); dialog->user_callback = user_callback; dialog->user_data = user_data; dialog->response = GTK_RESPONSE_NONE; dialog->list = ppd_list_copy (ppd_list); dialog->manufacturer = get_standard_manufacturers_name (manufacturer); /* connect signals */ g_signal_connect (dialog->dialog, "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL); g_signal_connect (dialog->dialog, "response", G_CALLBACK (ppd_selection_dialog_response_cb), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "content-alignment"); g_signal_connect (widget, "size-allocate", G_CALLBACK (update_alignment_padding), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "ppd-spinner"); gtk_spinner_start (GTK_SPINNER (widget)); populate_dialog (dialog); gtk_window_set_transient_for (GTK_WINDOW (dialog->dialog), GTK_WINDOW (parent)); gtk_window_present (GTK_WINDOW (dialog->dialog)); gtk_widget_show_all (GTK_WIDGET (dialog->dialog)); return dialog; } void pp_ppd_selection_dialog_free (PpPPDSelectionDialog *dialog) { gtk_widget_destroy (GTK_WIDGET (dialog->dialog)); g_object_unref (dialog->builder); g_free (dialog->ppd_name); g_free (dialog->manufacturer); g_free (dialog); } gchar * pp_ppd_selection_dialog_get_ppd_name (PpPPDSelectionDialog *dialog) { return g_strdup (dialog->ppd_name); } void pp_ppd_selection_dialog_set_ppd_list (PpPPDSelectionDialog *dialog, PPDList *list) { dialog->list = list; fill_ppds_list (dialog); } static void pp_ppd_selection_dialog_hide (PpPPDSelectionDialog *dialog) { gtk_widget_hide (GTK_WIDGET (dialog->dialog)); }
428
./cinnamon-control-center/panels/unused/printers/pp-cups.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "pp-cups.h" G_DEFINE_TYPE (PpCups, pp_cups, G_TYPE_OBJECT); static void pp_cups_finalize (GObject *object) { G_OBJECT_CLASS (pp_cups_parent_class)->finalize (object); } static void pp_cups_class_init (PpCupsClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = pp_cups_finalize; } static void pp_cups_init (PpCups *cups) { } PpCups * pp_cups_new () { return g_object_new (PP_TYPE_CUPS, NULL); } typedef struct { PpCupsDests *dests; } CGDData; static void _pp_cups_get_dests_thread (GSimpleAsyncResult *res, GObject *object, GCancellable *cancellable) { CGDData *data; data = g_simple_async_result_get_op_res_gpointer (res); data->dests = g_new0 (PpCupsDests, 1); data->dests->num_of_dests = cupsGetDests (&data->dests->dests); } static void cgd_data_free (CGDData *data) { if (data) { if (data->dests) { cupsFreeDests (data->dests->num_of_dests, data->dests->dests); g_free (data->dests); } g_free (data); } } void pp_cups_get_dests_async (PpCups *cups, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *res; CGDData *data; res = g_simple_async_result_new (G_OBJECT (cups), callback, user_data, pp_cups_get_dests_async); data = g_new0 (CGDData, 1); data->dests = NULL; g_simple_async_result_set_check_cancellable (res, cancellable); g_simple_async_result_set_op_res_gpointer (res, data, (GDestroyNotify) cgd_data_free); g_simple_async_result_run_in_thread (res, _pp_cups_get_dests_thread, 0, cancellable); g_object_unref (res); } PpCupsDests * pp_cups_get_dests_finish (PpCups *cups, GAsyncResult *res, GError **error) { GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res); PpCupsDests *result = NULL; CGDData *data; g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == pp_cups_get_dests_async); if (g_simple_async_result_propagate_error (simple, error)) { return NULL; } data = g_simple_async_result_get_op_res_gpointer (simple); result = data->dests; data->dests = NULL; return result; }
429
./cinnamon-control-center/panels/unused/printers/pp-ppd-option-widget.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "config.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <glib/gi18n-lib.h> #include <glib/gstdio.h> #include "pp-ppd-option-widget.h" #include "pp-utils.h" #define PP_PPD_OPTION_WIDGET_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), PP_TYPE_PPD_OPTION_WIDGET, PpPPDOptionWidgetPrivate)) static void pp_ppd_option_widget_finalize (GObject *object); static gboolean construct_widget (PpPPDOptionWidget *widget); static void update_widget (PpPPDOptionWidget *widget); static void update_widget_real (PpPPDOptionWidget *widget); struct PpPPDOptionWidgetPrivate { GtkWidget *switch_button; GtkWidget *combo; GtkWidget *image; GtkWidget *box; ppd_option_t *option; gchar *printer_name; gchar *option_name; cups_dest_t *destination; gboolean destination_set; gchar *ppd_filename; gboolean ppd_filename_set; }; G_DEFINE_TYPE (PpPPDOptionWidget, pp_ppd_option_widget, GTK_TYPE_HBOX) /* This list comes from Gtk+ */ static const struct { const char *keyword; const char *choice; const char *translation; } ppd_choice_translations[] = { { "Duplex", "None", N_("One Sided") }, /* Translators: this is an option of "Two Sided" */ { "Duplex", "DuplexNoTumble", N_("Long Edge (Standard)") }, /* Translators: this is an option of "Two Sided" */ { "Duplex", "DuplexTumble", N_("Short Edge (Flip)") }, /* Translators: this is an option of "Paper Source" */ { "InputSlot", "Auto", N_("Auto Select") }, /* Translators: this is an option of "Paper Source" */ { "InputSlot", "AutoSelect", N_("Auto Select") }, /* Translators: this is an option of "Paper Source" */ { "InputSlot", "Default", N_("Printer Default") }, /* Translators: this is an option of "Paper Source" */ { "InputSlot", "None", N_("Printer Default") }, /* Translators: this is an option of "Paper Source" */ { "InputSlot", "PrinterDefault", N_("Printer Default") }, /* Translators: this is an option of "Paper Source" */ { "InputSlot", "Unspecified", N_("Auto Select") }, /* Translators: this is an option of "Resolution" */ { "Resolution", "default", N_("Printer Default") }, /* Translators: this is an option of "GhostScript" */ { "PreFilter", "EmbedFonts", N_("Embed GhostScript fonts only") }, /* Translators: this is an option of "GhostScript" */ { "PreFilter", "Level1", N_("Convert to PS level 1") }, /* Translators: this is an option of "GhostScript" */ { "PreFilter", "Level2", N_("Convert to PS level 2") }, /* Translators: this is an option of "GhostScript" */ { "PreFilter", "No", N_("No pre-filtering") }, }; static ppd_option_t * cups_option_copy (ppd_option_t *option) { ppd_option_t *result; gint i; result = g_new0 (ppd_option_t, 1); *result = *option; result->choices = g_new (ppd_choice_t, result->num_choices); for (i = 0; i < result->num_choices; i++) { result->choices[i] = option->choices[i]; result->choices[i].code = g_strdup (option->choices[i].code); result->choices[i].option = result; } return result; } static void cups_option_free (ppd_option_t *option) { gint i; if (option) { for (i = 0; i < option->num_choices; i++) g_free (option->choices[i].code); g_free (option->choices); g_free (option); } } static void pp_ppd_option_widget_class_init (PpPPDOptionWidgetClass *class) { GObjectClass *object_class; object_class = G_OBJECT_CLASS (class); object_class->finalize = pp_ppd_option_widget_finalize; g_type_class_add_private (class, sizeof (PpPPDOptionWidgetPrivate)); } static void pp_ppd_option_widget_init (PpPPDOptionWidget *widget) { PpPPDOptionWidgetPrivate *priv; priv = widget->priv = PP_PPD_OPTION_WIDGET_GET_PRIVATE (widget); priv->switch_button = NULL; priv->combo = NULL; priv->image = NULL; priv->box = NULL; priv->printer_name = NULL; priv->option_name = NULL; priv->destination = NULL; priv->destination_set = FALSE; priv->ppd_filename = NULL; priv->ppd_filename_set = FALSE; } static void pp_ppd_option_widget_finalize (GObject *object) { PpPPDOptionWidget *widget = PP_PPD_OPTION_WIDGET (object); PpPPDOptionWidgetPrivate *priv = widget->priv; if (priv) { if (priv->option) { cups_option_free (priv->option); priv->option = NULL; } if (priv->printer_name) { g_free (priv->printer_name); priv->printer_name = NULL; } if (priv->option_name) { g_free (priv->printer_name); priv->printer_name = NULL; } if (priv->destination) { cupsFreeDests (1, priv->destination); priv->destination = NULL; } if (priv->ppd_filename) { g_unlink (priv->ppd_filename); g_free (priv->ppd_filename); priv->ppd_filename = NULL; } } G_OBJECT_CLASS (pp_ppd_option_widget_parent_class)->finalize (object); } static const gchar * ppd_choice_translate (ppd_choice_t *choice) { const gchar *keyword = choice->option->keyword; gint i; for (i = 0; i < G_N_ELEMENTS (ppd_choice_translations); i++) { if (g_strcmp0 (ppd_choice_translations[i].keyword, keyword) == 0 && g_strcmp0 (ppd_choice_translations[i].choice, choice->choice) == 0) return _(ppd_choice_translations[i].translation); } return choice->text; } GtkWidget * pp_ppd_option_widget_new (ppd_option_t *option, const gchar *printer_name) { PpPPDOptionWidgetPrivate *priv; PpPPDOptionWidget *widget = NULL; if (option && printer_name) { widget = g_object_new (PP_TYPE_PPD_OPTION_WIDGET, NULL); priv = PP_PPD_OPTION_WIDGET_GET_PRIVATE (widget); priv->printer_name = g_strdup (printer_name); priv->option = cups_option_copy (option); priv->option_name = g_strdup (option->keyword); if (construct_widget (widget)) { update_widget_real (widget); } else { g_object_ref_sink (widget); g_object_unref (widget); widget = NULL; } } return (GtkWidget *) widget; } enum { NAME_COLUMN, VALUE_COLUMN, N_COLUMNS }; static GtkWidget * combo_box_new (void) { GtkCellRenderer *cell; GtkListStore *store; GtkWidget *combo_box; combo_box = gtk_combo_box_new (); store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING); gtk_combo_box_set_model (GTK_COMBO_BOX (combo_box), GTK_TREE_MODEL (store)); g_object_unref (store); cell = gtk_cell_renderer_text_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), cell, TRUE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), cell, "text", NAME_COLUMN, NULL); return combo_box; } static void combo_box_append (GtkWidget *combo, const gchar *display_text, const gchar *value) { GtkTreeModel *model; GtkListStore *store; GtkTreeIter iter; model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo)); store = GTK_LIST_STORE (model); gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, NAME_COLUMN, display_text, VALUE_COLUMN, value, -1); } struct ComboSet { GtkComboBox *combo; const gchar *value; }; static gboolean set_cb (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data) { struct ComboSet *set_data = data; gboolean found; char *value; gtk_tree_model_get (model, iter, VALUE_COLUMN, &value, -1); found = (strcmp (value, set_data->value) == 0); g_free (value); if (found) gtk_combo_box_set_active_iter (set_data->combo, iter); return found; } static void combo_box_set (GtkWidget *combo, const gchar *value) { struct ComboSet set_data; GtkTreeModel *model; model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo)); set_data.combo = GTK_COMBO_BOX (combo); set_data.value = value; gtk_tree_model_foreach (model, set_cb, &set_data); } static char * combo_box_get (GtkWidget *combo) { GtkTreeModel *model; GtkTreeIter iter; gchar *value = NULL; model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo)); if (gtk_combo_box_get_active_iter (GTK_COMBO_BOX (combo), &iter)) gtk_tree_model_get (model, &iter, VALUE_COLUMN, &value, -1); return value; } static void printer_add_option_async_cb (gboolean success, gpointer user_data) { update_widget (user_data); } static void switch_changed_cb (GtkWidget *switch_button, GParamSpec *pspec, PpPPDOptionWidget *widget) { PpPPDOptionWidgetPrivate *priv = widget->priv; gchar **values; values = g_new0 (gchar *, 2); if (gtk_switch_get_active (GTK_SWITCH (switch_button))) values[0] = g_strdup ("True"); else values[0] = g_strdup ("False"); printer_add_option_async (priv->printer_name, priv->option_name, values, FALSE, NULL, printer_add_option_async_cb, widget); g_strfreev (values); } static void combo_changed_cb (GtkWidget *combo, PpPPDOptionWidget *widget) { PpPPDOptionWidgetPrivate *priv = widget->priv; gchar **values; values = g_new0 (gchar *, 2); values[0] = combo_box_get (combo); printer_add_option_async (priv->printer_name, priv->option_name, values, FALSE, NULL, printer_add_option_async_cb, widget); g_strfreev (values); } static gboolean construct_widget (PpPPDOptionWidget *widget) { PpPPDOptionWidgetPrivate *priv = widget->priv; gint i; /* Don't show options which has only one choice */ if (priv->option && priv->option->num_choices > 1) { switch (priv->option->ui) { case PPD_UI_BOOLEAN: priv->switch_button = gtk_switch_new (); g_signal_connect (priv->switch_button, "notify::active", G_CALLBACK (switch_changed_cb), widget); gtk_box_pack_start (GTK_BOX (widget), priv->switch_button, FALSE, FALSE, 0); break; case PPD_UI_PICKONE: priv->combo = combo_box_new (); for (i = 0; i < priv->option->num_choices; i++) { combo_box_append (priv->combo, ppd_choice_translate (&priv->option->choices[i]), priv->option->choices[i].choice); } gtk_box_pack_start (GTK_BOX (widget), priv->combo, FALSE, FALSE, 0); g_signal_connect (priv->combo, "changed", G_CALLBACK (combo_changed_cb), widget); break; case PPD_UI_PICKMANY: priv->combo = combo_box_new (); for (i = 0; i < priv->option->num_choices; i++) { combo_box_append (priv->combo, ppd_choice_translate (&priv->option->choices[i]), priv->option->choices[i].choice); } gtk_box_pack_start (GTK_BOX (widget), priv->combo, TRUE, TRUE, 0); g_signal_connect (priv->combo, "changed", G_CALLBACK (combo_changed_cb), widget); break; default: break; } priv->image = gtk_image_new_from_icon_name ("dialog-warning-symbolic", GTK_ICON_SIZE_MENU); if (!priv->image) priv->image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_MENU); gtk_box_pack_start (GTK_BOX (widget), priv->image, FALSE, FALSE, 0); gtk_widget_set_no_show_all (GTK_WIDGET (priv->image), TRUE); return TRUE; } else { return FALSE; } } static void update_widget_real (PpPPDOptionWidget *widget) { PpPPDOptionWidgetPrivate *priv = widget->priv; ppd_option_t *option = NULL, *iter; ppd_file_t *ppd_file; gchar *value = NULL; gint i; if (priv->option) { option = cups_option_copy (priv->option); cups_option_free (priv->option); priv->option = NULL; } else if (priv->ppd_filename) { ppd_file = ppdOpenFile (priv->ppd_filename); ppdLocalize (ppd_file); if (ppd_file) { ppdMarkDefaults (ppd_file); cupsMarkOptions (ppd_file, priv->destination->num_options, priv->destination->options); for (iter = ppdFirstOption(ppd_file); iter; iter = ppdNextOption(ppd_file)) { if (g_str_equal (iter->keyword, priv->option_name)) { option = cups_option_copy (iter); break; } } ppdClose (ppd_file); } g_unlink (priv->ppd_filename); g_free (priv->ppd_filename); priv->ppd_filename = NULL; } if (option) { for (i = 0; i < option->num_choices; i++) if (option->choices[i].marked) value = g_strdup (option->choices[i].choice); if (value == NULL) value = g_strdup (option->defchoice); if (value) { switch (option->ui) { case PPD_UI_BOOLEAN: g_signal_handlers_block_by_func (priv->switch_button, switch_changed_cb, widget); if (g_ascii_strcasecmp (value, "True") == 0) gtk_switch_set_active (GTK_SWITCH (priv->switch_button), TRUE); else gtk_switch_set_active (GTK_SWITCH (priv->switch_button), FALSE); g_signal_handlers_unblock_by_func (priv->switch_button, switch_changed_cb, widget); break; case PPD_UI_PICKONE: g_signal_handlers_block_by_func (priv->combo, combo_changed_cb, widget); combo_box_set (priv->combo, value); g_signal_handlers_unblock_by_func (priv->combo, combo_changed_cb, widget); break; case PPD_UI_PICKMANY: g_signal_handlers_block_by_func (priv->combo, combo_changed_cb, widget); combo_box_set (priv->combo, value); g_signal_handlers_unblock_by_func (priv->combo, combo_changed_cb, widget); break; default: break; } g_free (value); } if (option->conflicted) gtk_widget_show (priv->image); else gtk_widget_hide (priv->image); } cups_option_free (option); } static void get_named_dest_cb (cups_dest_t *dest, gpointer user_data) { PpPPDOptionWidget *widget = (PpPPDOptionWidget *) user_data; PpPPDOptionWidgetPrivate *priv = widget->priv; if (priv->destination) cupsFreeDests (1, priv->destination); priv->destination = dest; priv->destination_set = TRUE; if (priv->ppd_filename_set) { update_widget_real (widget); } } static void printer_get_ppd_cb (const gchar *ppd_filename, gpointer user_data) { PpPPDOptionWidget *widget = (PpPPDOptionWidget *) user_data; PpPPDOptionWidgetPrivate *priv = widget->priv; if (priv->ppd_filename) { g_unlink (priv->ppd_filename); g_free (priv->ppd_filename); } priv->ppd_filename = g_strdup (ppd_filename); priv->ppd_filename_set = TRUE; if (priv->destination_set) { update_widget_real (widget); } } static void update_widget (PpPPDOptionWidget *widget) { PpPPDOptionWidgetPrivate *priv = widget->priv; get_named_dest_async (priv->printer_name, get_named_dest_cb, widget); printer_get_ppd_async (priv->printer_name, NULL, 0, printer_get_ppd_cb, widget); }
430
./cinnamon-control-center/panels/unused/printers/pp-utils.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2009-2010 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <glib.h> #include <glib/gi18n.h> #include <glib/gstdio.h> #include <gtk/gtk.h> #include <cups/cups.h> #include <cups/ppd.h> #include "pp-utils.h" #define DBUS_TIMEOUT 120000 #define DBUS_TIMEOUT_LONG 600000 #if (CUPS_VERSION_MAJOR > 1) || (CUPS_VERSION_MINOR > 5) #define HAVE_CUPS_1_6 1 #endif #ifndef HAVE_CUPS_1_6 #define ippGetCount(attr) attr->num_values #define ippGetGroupTag(attr) attr->group_tag #define ippGetValueTag(attr) attr->value_tag #define ippGetName(attr) attr->name #define ippGetStatusCode(ipp) ipp->request.status.status_code #define ippGetInteger(attr, element) attr->values[element].integer #define ippGetString(attr, element, language) attr->values[element].string.text #define ippGetBoolean(attr, element) attr->values[element].boolean static int ippGetRange (ipp_attribute_t *attr, int element, int *upper) { *upper = attr->values[element].range.upper; return (attr->values[element].range.lower); } static ipp_attribute_t * ippFirstAttribute (ipp_t *ipp) { if (!ipp) return (NULL); return (ipp->current = ipp->attrs); } static ipp_attribute_t * ippNextAttribute (ipp_t *ipp) { if (!ipp || !ipp->current) return (NULL); return (ipp->current = ipp->current->next); } #endif gchar * get_tag_value (const gchar *tag_string, const gchar *tag_name) { gchar **tag_string_splitted = NULL; gchar *tag_value = NULL; gint tag_name_length; gint i; if (tag_string && tag_name) { tag_name_length = strlen (tag_name); tag_string_splitted = g_strsplit (tag_string, ";", 0); if (tag_string_splitted) { for (i = 0; i < g_strv_length (tag_string_splitted); i++) if (g_ascii_strncasecmp (tag_string_splitted[i], tag_name, tag_name_length) == 0) if (strlen (tag_string_splitted[i]) > tag_name_length + 1) tag_value = g_strdup (tag_string_splitted[i] + tag_name_length + 1); g_strfreev (tag_string_splitted); } } return tag_value; } /* * Normalize given string so that it is lowercase, doesn't * have trailing or leading whitespaces and digits doesn't * neighbour with alphabetic. * (see cupshelpers/ppds.py from system-config-printer) */ static gchar * normalize (const gchar *input_string) { gchar *tmp = NULL; gchar *res = NULL; gchar *result = NULL; gint i, j = 0, k = -1; if (input_string) { tmp = g_strstrip (g_ascii_strdown (input_string, -1)); if (tmp) { res = g_new (gchar, 2 * strlen (tmp)); for (i = 0; i < strlen (tmp); i++) { if ((g_ascii_isalpha (tmp[i]) && k >= 0 && g_ascii_isdigit (res[k])) || (g_ascii_isdigit (tmp[i]) && k >= 0 && g_ascii_isalpha (res[k]))) { res[j] = ' '; k = j++; res[j] = tmp[i]; k = j++; } else { if (g_ascii_isspace (tmp[i]) || !g_ascii_isalnum (tmp[i])) { if (!(k >= 0 && res[k] == ' ')) { res[j] = ' '; k = j++; } } else { res[j] = tmp[i]; k = j++; } } } res[j] = '\0'; result = g_strdup (res); g_free (tmp); g_free (res); } } return result; } char * get_dest_attr (const char *dest_name, const char *attr) { cups_dest_t *dests; int num_dests; cups_dest_t *dest; const char *value; char *ret; if (dest_name == NULL) return NULL; ret = NULL; num_dests = cupsGetDests (&dests); if (num_dests < 1) { g_debug ("Unable to get printer destinations"); return NULL; } dest = cupsGetDest (dest_name, NULL, num_dests, dests); if (dest == NULL) { g_debug ("Unable to find a printer named '%s'", dest_name); goto out; } value = cupsGetOption (attr, dest->num_options, dest->options); if (value == NULL) { g_debug ("Unable to get %s for '%s'", attr, dest_name); goto out; } ret = g_strdup (value); out: cupsFreeDests (num_dests, dests); return ret; } gchar * get_ppd_attribute (const gchar *ppd_file_name, const gchar *attribute_name) { ppd_file_t *ppd_file = NULL; ppd_attr_t *ppd_attr = NULL; gchar *result = NULL; if (ppd_file_name) { ppd_file = ppdOpenFile (ppd_file_name); if (ppd_file) { ppd_attr = ppdFindAttr (ppd_file, attribute_name, NULL); if (ppd_attr != NULL) result = g_strdup (ppd_attr->value); ppdClose (ppd_file); } } return result; } /* Cancels subscription of given id */ void cancel_cups_subscription (gint id) { http_t *http; ipp_t *request; if (id >= 0 && ((http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ())) != NULL)) { request = ippNewRequest (IPP_CANCEL_SUBSCRIPTION); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-id", id); ippDelete (cupsDoRequest (http, request, "/")); httpClose (http); } } /* Returns id of renewed subscription or new id */ gint renew_cups_subscription (gint id, const char * const *events, gint num_events, gint lease_duration) { ipp_attribute_t *attr = NULL; http_t *http; ipp_t *request; ipp_t *response = NULL; gint result = -1; if ((http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ())) == NULL) { g_debug ("Connection to CUPS server \'%s\' failed.", cupsServer ()); } else { if (id >= 0) { request = ippNewRequest (IPP_RENEW_SUBSCRIPTION); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-id", id); ippAddInteger (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER, "notify-lease-duration", lease_duration); response = cupsDoRequest (http, request, "/"); if (response != NULL && ippGetStatusCode (response) <= IPP_OK_CONFLICT) { if ((attr = ippFindAttribute (response, "notify-lease-duration", IPP_TAG_INTEGER)) == NULL) g_debug ("No notify-lease-duration in response!\n"); else if (ippGetInteger (attr, 0) == lease_duration) result = id; } } if (result < 0) { request = ippNewRequest (IPP_CREATE_PRINTER_SUBSCRIPTION); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddStrings (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-events", num_events, NULL, events); ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-pull-method", NULL, "ippget"); ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI, "notify-recipient-uri", NULL, "dbus://"); ippAddInteger (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER, "notify-lease-duration", lease_duration); response = cupsDoRequest (http, request, "/"); if (response != NULL && ippGetStatusCode (response) <= IPP_OK_CONFLICT) { if ((attr = ippFindAttribute (response, "notify-subscription-id", IPP_TAG_INTEGER)) == NULL) g_debug ("No notify-subscription-id in response!\n"); else result = ippGetInteger (attr, 0); } } if (response) ippDelete (response); httpClose (http); } return result; } /* Set default destination in ~/.cups/lpoptions. * Unset default destination if "dest" is NULL. */ void set_local_default_printer (const gchar *printer_name) { cups_dest_t *dests = NULL; int num_dests = 0; int i; num_dests = cupsGetDests (&dests); for (i = 0; i < num_dests; i ++) { if (printer_name && g_strcmp0 (dests[i].name, printer_name) == 0) dests[i].is_default = 1; else dests[i].is_default = 0; } cupsSetDests (num_dests, dests); } /* * This function does something which should be provided by CUPS... * It returns FALSE if the renaming fails. */ gboolean printer_rename (const gchar *old_name, const gchar *new_name) { ipp_attribute_t *attr = NULL; cups_ptype_t printer_type = 0; cups_dest_t *dests = NULL; cups_dest_t *dest = NULL; cups_job_t *jobs = NULL; GDBusConnection *bus; const char *printer_location = NULL; const char *printer_info = NULL; const char *printer_uri = NULL; const char *device_uri = NULL; const char *job_sheets = NULL; gboolean result = FALSE; gboolean accepting = TRUE; gboolean printer_paused = FALSE; gboolean default_printer = FALSE; gboolean printer_shared = FALSE; GError *error = NULL; http_t *http; gchar *ppd_link; gchar *ppd_filename = NULL; gchar **sheets = NULL; gchar **users_allowed = NULL; gchar **users_denied = NULL; gchar **member_names = NULL; gchar *start_sheet = NULL; gchar *end_sheet = NULL; gchar *error_policy = NULL; gchar *op_policy = NULL; ipp_t *request; ipp_t *response; gint i; int num_dests = 0; int num_jobs = 0; static const char * const requested_attrs[] = { "printer-error-policy", "printer-op-policy", "requesting-user-name-allowed", "requesting-user-name-denied", "member-names"}; if (old_name == NULL || old_name[0] == '\0' || new_name == NULL || new_name[0] == '\0' || g_strcmp0 (old_name, new_name) == 0) return FALSE; num_dests = cupsGetDests (&dests); dest = cupsGetDest (new_name, NULL, num_dests, dests); if (dest) { cupsFreeDests (num_dests, dests); return FALSE; } num_jobs = cupsGetJobs (&jobs, old_name, 0, CUPS_WHICHJOBS_ACTIVE); cupsFreeJobs (num_jobs, jobs); if (num_jobs > 1) { g_warning ("There are queued jobs on printer %s!", old_name); cupsFreeDests (num_dests, dests); return FALSE; } /* * Gather some informations about the original printer */ dest = cupsGetDest (old_name, NULL, num_dests, dests); if (dest) { for (i = 0; i < dest->num_options; i++) { if (g_strcmp0 (dest->options[i].name, "printer-is-accepting-jobs") == 0) accepting = g_strcmp0 (dest->options[i].value, "true") == 0; else if (g_strcmp0 (dest->options[i].name, "printer-is-shared") == 0) printer_shared = g_strcmp0 (dest->options[i].value, "true") == 0; else if (g_strcmp0 (dest->options[i].name, "device-uri") == 0) device_uri = dest->options[i].value; else if (g_strcmp0 (dest->options[i].name, "printer-uri-supported") == 0) printer_uri = dest->options[i].value; else if (g_strcmp0 (dest->options[i].name, "printer-info") == 0) printer_info = dest->options[i].value; else if (g_strcmp0 (dest->options[i].name, "printer-location") == 0) printer_location = dest->options[i].value; else if (g_strcmp0 (dest->options[i].name, "printer-state") == 0) printer_paused = g_strcmp0 (dest->options[i].value, "5") == 0; else if (g_strcmp0 (dest->options[i].name, "job-sheets") == 0) job_sheets = dest->options[i].value; else if (g_strcmp0 (dest->options[i].name, "printer-type") == 0) printer_type = atoi (dest->options[i].value); } default_printer = dest->is_default; } cupsFreeDests (num_dests, dests); if (accepting) { printer_set_accepting_jobs (old_name, FALSE, NULL); num_jobs = cupsGetJobs (&jobs, old_name, 0, CUPS_WHICHJOBS_ACTIVE); cupsFreeJobs (num_jobs, jobs); if (num_jobs > 1) { printer_set_accepting_jobs (old_name, accepting, NULL); g_warning ("There are queued jobs on printer %s!", old_name); return FALSE; } } /* * Gather additional informations about the original printer */ if ((http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ())) != NULL) { request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", G_N_ELEMENTS (requested_attrs), NULL, requested_attrs); response = cupsDoRequest (http, request, "/"); if (response) { if (ippGetStatusCode (response) <= IPP_OK_CONFLICT) { attr = ippFindAttribute (response, "printer-error-policy", IPP_TAG_NAME); if (attr) error_policy = g_strdup (ippGetString (attr, 0, NULL)); attr = ippFindAttribute (response, "printer-op-policy", IPP_TAG_NAME); if (attr) op_policy = g_strdup (ippGetString (attr, 0, NULL)); attr = ippFindAttribute (response, "requesting-user-name-allowed", IPP_TAG_NAME); if (attr && ippGetCount (attr) > 0) { users_allowed = g_new0 (gchar *, ippGetCount (attr) + 1); for (i = 0; i < ippGetCount (attr); i++) users_allowed[i] = g_strdup (ippGetString (attr, i, NULL)); } attr = ippFindAttribute (response, "requesting-user-name-denied", IPP_TAG_NAME); if (attr && ippGetCount (attr) > 0) { users_denied = g_new0 (gchar *, ippGetCount (attr) + 1); for (i = 0; i < ippGetCount (attr); i++) users_denied[i] = g_strdup (ippGetString (attr, i, NULL)); } attr = ippFindAttribute (response, "member-names", IPP_TAG_NAME); if (attr && ippGetCount (attr) > 0) { member_names = g_new0 (gchar *, ippGetCount (attr) + 1); for (i = 0; i < ippGetCount (attr); i++) member_names[i] = g_strdup (ippGetString (attr, i, NULL)); } } ippDelete (response); } httpClose (http); } if (job_sheets) { sheets = g_strsplit (job_sheets, ",", 0); if (g_strv_length (sheets) > 1) { start_sheet = sheets[0]; end_sheet = sheets[1]; } } ppd_link = g_strdup (cupsGetPPD (old_name)); if (ppd_link) { ppd_filename = g_file_read_link (ppd_link, NULL); if (!ppd_filename) ppd_filename = g_strdup (ppd_link); } bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); } else { if (printer_type & CUPS_PRINTER_CLASS) { if (member_names) for (i = 0; i < g_strv_length (member_names); i++) class_add_printer (new_name, member_names[i]); } else { GVariant *output; output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterAddWithPpdFile", g_variant_new ("(sssss)", new_name, device_uri ? device_uri : "", ppd_filename ? ppd_filename : "", printer_info ? printer_info : "", printer_location ? printer_location : ""), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } } } if (ppd_link) { g_unlink (ppd_link); g_free (ppd_link); g_free (ppd_filename); } num_dests = cupsGetDests (&dests); dest = cupsGetDest (new_name, NULL, num_dests, dests); if (dest) { printer_set_accepting_jobs (new_name, accepting, NULL); printer_set_enabled (new_name, !printer_paused); printer_set_shared (new_name, printer_shared); printer_set_job_sheets (new_name, start_sheet, end_sheet); printer_set_policy (new_name, op_policy, FALSE); printer_set_policy (new_name, error_policy, TRUE); printer_set_users (new_name, users_allowed, TRUE); printer_set_users (new_name, users_denied, FALSE); if (default_printer) printer_set_default (new_name); printer_delete (old_name); result = TRUE; } else printer_set_accepting_jobs (old_name, accepting, NULL); cupsFreeDests (num_dests, dests); g_free (op_policy); g_free (error_policy); if (sheets) g_strfreev (sheets); if (users_allowed) g_strfreev (users_allowed); if (users_denied) g_strfreev (users_denied); return result; } gboolean printer_set_location (const gchar *printer_name, const gchar *location) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name || !location) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetLocation", g_variant_new ("(ss)", printer_name, location), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_set_accepting_jobs (const gchar *printer_name, gboolean accepting_jobs, const gchar *reason) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetAcceptJobs", g_variant_new ("(sbs)", printer_name, accepting_jobs, reason ? reason : ""), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_set_enabled (const gchar *printer_name, gboolean enabled) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetEnabled", g_variant_new ("(sb)", printer_name, enabled), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_delete (const gchar *printer_name) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterDelete", g_variant_new ("(s)", printer_name), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_set_default (const gchar *printer_name) { GDBusConnection *bus; const char *cups_server; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name) return TRUE; cups_server = cupsServer (); if (g_ascii_strncasecmp (cups_server, "localhost", 9) == 0 || g_ascii_strncasecmp (cups_server, "127.0.0.1", 9) == 0 || g_ascii_strncasecmp (cups_server, "::1", 3) == 0 || cups_server[0] == '/') { /* Clean .cups/lpoptions before setting * default printer on local CUPS server. */ set_local_default_printer (NULL); bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); } else { output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetDefault", g_variant_new ("(s)", printer_name), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } } } else /* Store default printer to .cups/lpoptions * if we are connected to a remote CUPS server. */ { set_local_default_printer (printer_name); } return result; } gboolean printer_set_shared (const gchar *printer_name, gboolean shared) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetShared", g_variant_new ("(sb)", printer_name, shared), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_set_job_sheets (const gchar *printer_name, const gchar *start_sheet, const gchar *end_sheet) { GDBusConnection *bus; GVariant *output; GError *error = NULL; gboolean result = FALSE; if (!printer_name || !start_sheet || !end_sheet) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetJobSheets", g_variant_new ("(sss)", printer_name, start_sheet, end_sheet), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_set_policy (const gchar *printer_name, const gchar *policy, gboolean error_policy) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name || !policy) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } if (error_policy) output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetErrorPolicy", g_variant_new ("(ss)", printer_name, policy), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); else output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetOpPolicy", g_variant_new ("(ss)", printer_name, policy), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_set_users (const gchar *printer_name, gchar **users, gboolean allowed) { GDBusConnection *bus; GVariantBuilder array_builder; gint i; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!printer_name || !users) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("as")); for (i = 0; users[i]; i++) g_variant_builder_add (&array_builder, "s", users[i]); if (allowed) output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetUsersAllowed", g_variant_new ("(sas)", printer_name, &array_builder), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); else output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetUsersDenied", g_variant_new ("(sas)", printer_name, &array_builder), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean class_add_printer (const gchar *class_name, const gchar *printer_name) { GDBusConnection *bus; GVariant *output; gboolean result = FALSE; GError *error = NULL; if (!class_name || !printer_name) return TRUE; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return TRUE; } output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "ClassAddPrinter", g_variant_new ("(ss)", class_name, printer_name), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { g_warning ("%s", error->message); g_error_free (error); } return result; } gboolean printer_is_local (cups_ptype_t printer_type, const gchar *device_uri) { gboolean result = TRUE; char scheme[HTTP_MAX_URI]; char username[HTTP_MAX_URI]; char hostname[HTTP_MAX_URI]; char resource[HTTP_MAX_URI]; int port; if (printer_type & (CUPS_PRINTER_DISCOVERED | CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT)) result = FALSE; if (device_uri == NULL || !result) return result; httpSeparateURI (HTTP_URI_CODING_ALL, device_uri, scheme, sizeof (scheme), username, sizeof (username), hostname, sizeof (hostname), &port, resource, sizeof (resource)); if (g_str_equal (scheme, "ipp") || g_str_equal (scheme, "smb") || g_str_equal (scheme, "socket") || g_str_equal (scheme, "lpd")) result = FALSE; return result; } gchar* printer_get_hostname (cups_ptype_t printer_type, const gchar *device_uri, const gchar *printer_uri) { gboolean local = TRUE; gchar *result = NULL; char scheme[HTTP_MAX_URI]; char username[HTTP_MAX_URI]; char hostname[HTTP_MAX_URI]; char resource[HTTP_MAX_URI]; int port; if (device_uri == NULL) return result; if (printer_type & (CUPS_PRINTER_DISCOVERED | CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT)) { if (printer_uri) { httpSeparateURI (HTTP_URI_CODING_ALL, printer_uri, scheme, sizeof (scheme), username, sizeof (username), hostname, sizeof (hostname), &port, resource, sizeof (resource)); if (hostname[0] != '\0') result = g_strdup (hostname); } local = FALSE; } if (result == NULL && device_uri) { httpSeparateURI (HTTP_URI_CODING_ALL, device_uri, scheme, sizeof (scheme), username, sizeof (username), hostname, sizeof (hostname), &port, resource, sizeof (resource)); if (g_str_equal (scheme, "ipp") || g_str_equal (scheme, "smb") || g_str_equal (scheme, "socket") || g_str_equal (scheme, "lpd")) { if (hostname[0] != '\0') result = g_strdup (hostname); local = FALSE; } } if (local) result = g_strdup ("localhost"); return result; } /* Returns default media size for current locale */ const gchar * get_paper_size_from_locale () { if (g_str_equal (gtk_paper_size_get_default (), GTK_PAPER_NAME_LETTER)) return "na-letter"; else return "iso-a4"; } /* Set default media size according to the locale */ void printer_set_default_media_size (const gchar *printer_name) { GVariantBuilder array_builder; GDBusConnection *bus; GVariant *output; GError *error = NULL; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); return; } g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("as")); g_variant_builder_add (&array_builder, "s", get_paper_size_from_locale ()); output = g_dbus_connection_call_sync (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterAddOption", g_variant_new ("(ssas)", printer_name, "media", &array_builder), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); g_variant_unref (output); } else { if (!(error->domain == G_DBUS_ERROR && (error->code == G_DBUS_ERROR_SERVICE_UNKNOWN || error->code == G_DBUS_ERROR_UNKNOWN_METHOD))) g_warning ("%s", error->message); g_error_free (error); } } typedef struct { gchar *printer_name; gchar **attributes_names; GHashTable *result; GIACallback callback; gpointer user_data; GMainContext *context; } GIAData; static gboolean get_ipp_attributes_idle_cb (gpointer user_data) { GIAData *data = (GIAData *) user_data; data->callback (data->result, data->user_data); return FALSE; } static void get_ipp_attributes_data_free (gpointer user_data) { GIAData *data = (GIAData *) user_data; if (data->context) g_main_context_unref (data->context); g_free (data->printer_name); if (data->attributes_names) g_strfreev (data->attributes_names); g_free (data); } static void get_ipp_attributes_cb (gpointer user_data) { GIAData *data = (GIAData *) user_data; GSource *idle_source; idle_source = g_idle_source_new (); g_source_set_callback (idle_source, get_ipp_attributes_idle_cb, data, get_ipp_attributes_data_free); g_source_attach (idle_source, data->context); g_source_unref (idle_source); } static void ipp_attribute_free2 (gpointer attr) { IPPAttribute *attribute = (IPPAttribute *) attr; ipp_attribute_free (attribute); } static gpointer get_ipp_attributes_func (gpointer user_data) { ipp_attribute_t *attr = NULL; GIAData *data = (GIAData *) user_data; ipp_t *request; ipp_t *response = NULL; gchar *printer_uri; char **requested_attrs = NULL; gint i, j, length = 0; printer_uri = g_strdup_printf ("ipp://localhost/printers/%s", data->printer_name); if (data->attributes_names) { length = g_strv_length (data->attributes_names); requested_attrs = g_new0 (char *, length); for (i = 0; data->attributes_names[i]; i++) requested_attrs[i] = g_strdup (data->attributes_names[i]); request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", length, NULL, (const char **) requested_attrs); response = cupsDoRequest (CUPS_HTTP_DEFAULT, request, "/"); } if (response) { if (ippGetStatusCode (response) <= IPP_OK_CONFLICT) { for (j = 0; j < length; j++) { attr = ippFindAttribute (response, requested_attrs[j], IPP_TAG_ZERO); if (attr && ippGetCount (attr) > 0 && ippGetValueTag (attr) != IPP_TAG_NOVALUE) { IPPAttribute *attribute; attribute = g_new0 (IPPAttribute, 1); attribute->attribute_name = g_strdup (requested_attrs[j]); attribute->attribute_values = g_new0 (IPPAttributeValue, ippGetCount (attr)); attribute->num_of_values = ippGetCount (attr); if (ippGetValueTag (attr) == IPP_TAG_INTEGER || ippGetValueTag (attr) == IPP_TAG_ENUM) { attribute->attribute_type = IPP_ATTRIBUTE_TYPE_INTEGER; for (i = 0; i < ippGetCount (attr); i++) attribute->attribute_values[i].integer_value = ippGetInteger (attr, i); } else if (ippGetValueTag (attr) == IPP_TAG_NAME || ippGetValueTag (attr) == IPP_TAG_STRING || ippGetValueTag (attr) == IPP_TAG_TEXT || ippGetValueTag (attr) == IPP_TAG_URI || ippGetValueTag (attr) == IPP_TAG_KEYWORD || ippGetValueTag (attr) == IPP_TAG_URISCHEME) { attribute->attribute_type = IPP_ATTRIBUTE_TYPE_STRING; for (i = 0; i < ippGetCount (attr); i++) attribute->attribute_values[i].string_value = g_strdup (ippGetString (attr, i, NULL)); } else if (ippGetValueTag (attr) == IPP_TAG_RANGE) { attribute->attribute_type = IPP_ATTRIBUTE_TYPE_RANGE; for (i = 0; i < ippGetCount (attr); i++) { attribute->attribute_values[i].lower_range = ippGetRange (attr, i, &(attribute->attribute_values[i].upper_range)); } } else if (ippGetValueTag (attr) == IPP_TAG_BOOLEAN) { attribute->attribute_type = IPP_ATTRIBUTE_TYPE_BOOLEAN; for (i = 0; i < ippGetCount (attr); i++) attribute->attribute_values[i].boolean_value = ippGetBoolean (attr, i); } if (!data->result) data->result = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, ipp_attribute_free2); g_hash_table_insert (data->result, g_strdup (requested_attrs[j]), attribute); } } } ippDelete (response); } for (i = 0; i < length; i++) g_free (requested_attrs[i]); g_free (requested_attrs); g_free (printer_uri); get_ipp_attributes_cb (data); return NULL; } void get_ipp_attributes_async (const gchar *printer_name, gchar **attributes_names, GIACallback callback, gpointer user_data) { GIAData *data; GThread *thread; GError *error = NULL; data = g_new0 (GIAData, 1); data->printer_name = g_strdup (printer_name); data->attributes_names = g_strdupv (attributes_names); data->callback = callback; data->user_data = user_data; data->context = g_main_context_ref_thread_default (); thread = g_thread_try_new ("get-ipp-attributes", get_ipp_attributes_func, data, &error); if (!thread) { g_warning ("%s", error->message); callback (NULL, user_data); g_error_free (error); get_ipp_attributes_data_free (data); } else { g_thread_unref (thread); } } IPPAttribute * ipp_attribute_copy (IPPAttribute *attr) { IPPAttribute *result = NULL; gint i; if (attr) { result = g_new0 (IPPAttribute, 1); *result = *attr; result->attribute_name = g_strdup (attr->attribute_name); result->attribute_values = g_new0 (IPPAttributeValue, attr->num_of_values); for (i = 0; i < attr->num_of_values; i++) { result->attribute_values[i] = attr->attribute_values[i]; if (attr->attribute_values[i].string_value) result->attribute_values[i].string_value = g_strdup (attr->attribute_values[i].string_value); } } return result; } void ipp_attribute_free (IPPAttribute *attr) { gint i; if (attr) { for (i = 0; i < attr->num_of_values; i++) g_free (attr->attribute_values[i].string_value); g_free (attr->attribute_values); g_free (attr->attribute_name); g_free (attr); } } typedef struct { gchar *printer_name; gchar *ppd_copy; GCancellable *cancellable; PSPCallback callback; gpointer user_data; } PSPData; static void printer_set_ppd_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; gboolean result = FALSE; PSPData *data = (PSPData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else result = TRUE; g_variant_unref (output); } else { if (error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } /* Don't call callback if cancelled */ if (!data->cancellable || !g_cancellable_is_cancelled (data->cancellable)) data->callback (g_strdup (data->printer_name), result, data->user_data); if (data->cancellable) g_object_unref (data->cancellable); if (data->ppd_copy) { g_unlink (data->ppd_copy); g_free (data->ppd_copy); } g_free (data->printer_name); g_free (data); } /* * Set ppd for given printer. * Don't use this for classes, just for printers. */ void printer_set_ppd_async (const gchar *printer_name, const gchar *ppd_name, GCancellable *cancellable, PSPCallback callback, gpointer user_data) { GDBusConnection *bus; PSPData *data; GError *error = NULL; data = g_new0 (PSPData, 1); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; data->printer_name = g_strdup (printer_name); if (printer_name == NULL || printer_name[0] == '\0') { goto out; } bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); goto out; } g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterAdd", g_variant_new ("(sssss)", printer_name, "", ppd_name, "", ""), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, data->cancellable, printer_set_ppd_async_dbus_cb, data); return; out: callback (g_strdup (printer_name), FALSE, user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->printer_name); g_free (data); } static void printer_set_ppd_file_async_scb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GDBusConnection *bus; gboolean success; PSPData *data = (PSPData *) user_data; GError *error = NULL; success = g_file_copy_finish (G_FILE (source_object), res, &error); g_object_unref (source_object); if (!success) { g_warning ("%s", error->message); g_error_free (error); goto out; } bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); goto out; } g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterAddWithPpdFile", g_variant_new ("(sssss)", data->printer_name, "", data->ppd_copy, "", ""), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, data->cancellable, printer_set_ppd_async_dbus_cb, data); return; out: data->callback (g_strdup (data->printer_name), FALSE, data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->printer_name); g_free (data->ppd_copy); g_free (data); } /* * Set ppd for given printer. * Don't use this for classes, just for printers. */ void printer_set_ppd_file_async (const gchar *printer_name, const gchar *ppd_filename, GCancellable *cancellable, PSPCallback callback, gpointer user_data) { GFileIOStream *stream; PSPData *data; GFile *source_ppd_file; GFile *destination_ppd_file; data = g_new0 (PSPData, 1); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; data->printer_name = g_strdup (printer_name); if (printer_name == NULL || printer_name[0] == '\0') { goto out; } /* * We need to copy the PPD to temp directory at first. * This is needed because of SELinux. */ source_ppd_file = g_file_new_for_path (ppd_filename); destination_ppd_file = g_file_new_tmp ("g-c-c-XXXXXX.ppd", &stream, NULL); g_object_unref (stream); data->ppd_copy = g_strdup (g_file_get_path (destination_ppd_file)); g_file_copy_async (source_ppd_file, destination_ppd_file, G_FILE_COPY_OVERWRITE, G_PRIORITY_DEFAULT, cancellable, NULL, NULL, printer_set_ppd_file_async_scb, data); g_object_unref (destination_ppd_file); return; out: callback (g_strdup (printer_name), FALSE, user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->printer_name); g_free (data); } typedef void (*GPACallback) (gchar **attribute_values, gpointer user_data); typedef struct { gchar *attribute_name; gchar **ppds_names; gchar **result; GPACallback callback; gpointer user_data; GMainContext *context; } GPAData; static gboolean get_ppds_attribute_idle_cb (gpointer user_data) { GPAData *data = (GPAData *) user_data; data->callback (data->result, data->user_data); return FALSE; } static void get_ppds_attribute_data_free (gpointer user_data) { GPAData *data = (GPAData *) user_data; if (data->context) g_main_context_unref (data->context); g_free (data->attribute_name); g_strfreev (data->ppds_names); g_free (data); } static void get_ppds_attribute_cb (gpointer user_data) { GPAData *data = (GPAData *) user_data; GSource *idle_source; idle_source = g_idle_source_new (); g_source_set_callback (idle_source, get_ppds_attribute_idle_cb, data, get_ppds_attribute_data_free); g_source_attach (idle_source, data->context); g_source_unref (idle_source); } static gpointer get_ppds_attribute_func (gpointer user_data) { ppd_file_t *ppd_file; ppd_attr_t *ppd_attr; GPAData *data = (GPAData *) user_data; gchar *ppd_filename; gint i; data->result = g_new0 (gchar *, g_strv_length (data->ppds_names) + 1); for (i = 0; data->ppds_names[i]; i++) { ppd_filename = g_strdup (cupsGetServerPPD (CUPS_HTTP_DEFAULT, data->ppds_names[i])); if (ppd_filename) { ppd_file = ppdOpenFile (ppd_filename); if (ppd_file) { ppd_attr = ppdFindAttr (ppd_file, data->attribute_name, NULL); if (ppd_attr != NULL) data->result[i] = g_strdup (ppd_attr->value); ppdClose (ppd_file); } g_unlink (ppd_filename); g_free (ppd_filename); } } get_ppds_attribute_cb (data); return NULL; } /* * Get values of requested PPD attribute for given PPDs. */ static void get_ppds_attribute_async (gchar **ppds_names, gchar *attribute_name, GPACallback callback, gpointer user_data) { GPAData *data; GThread *thread; GError *error = NULL; if (!ppds_names || !attribute_name) { callback (NULL, user_data); return; } data = g_new0 (GPAData, 1); data->ppds_names = g_strdupv (ppds_names); data->attribute_name = g_strdup (attribute_name); data->callback = callback; data->user_data = user_data; data->context = g_main_context_ref_thread_default (); thread = g_thread_try_new ("get-ppds-attribute", get_ppds_attribute_func, data, &error); if (!thread) { g_warning ("%s", error->message); callback (NULL, user_data); g_error_free (error); get_ppds_attribute_data_free (data); } else { g_thread_unref (thread); } } typedef void (*GDACallback) (gchar *device_id, gchar *device_make_and_model, gchar *device_uri, gpointer user_data); typedef struct { gchar *printer_name; gchar *device_uri; GCancellable *cancellable; GList *backend_list; GDACallback callback; gpointer user_data; } GDAData; typedef struct { gchar *printer_name; gint count; PPDName **result; GCancellable *cancellable; GPNCallback callback; gpointer user_data; } GPNData; static void get_ppd_names_async_cb (gchar **attribute_values, gpointer user_data) { GPNData *data = (GPNData *) user_data; gint i; if (g_cancellable_is_cancelled (data->cancellable)) { g_strfreev (attribute_values); for (i = 0; data->result[i]; i++) { g_free (data->result[i]->ppd_name); g_free (data->result[i]); } g_free (data->result); data->result = NULL; goto out; } if (attribute_values) { for (i = 0; attribute_values[i]; i++) data->result[i]->ppd_display_name = attribute_values[i]; g_free (attribute_values); } out: data->callback (data->result, data->printer_name, g_cancellable_is_cancelled (data->cancellable), data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->printer_name); g_free (data); } static void get_ppd_names_async_dbus_scb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; PPDName *ppd_item; PPDName **result = NULL; GPNData *data = (GPNData *) user_data; GError *error = NULL; GList *driver_list = NULL; GList *iter; gint i, j, n = 0; static const char * const match_levels[] = { "exact-cmd", "exact", "close", "generic", "none"}; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { GVariant *array; g_variant_get (output, "(@a(ss))", &array); if (array) { GVariantIter *iter; GVariant *item; gchar *driver; gchar *match; for (j = 0; j < G_N_ELEMENTS (match_levels) && n < data->count; j++) { g_variant_get (array, "a(ss)", &iter); while ((item = g_variant_iter_next_value (iter))) { g_variant_get (item, "(ss)", &driver, &match); if (g_str_equal (match, match_levels[j]) && n < data->count) { ppd_item = g_new0 (PPDName, 1); ppd_item->ppd_name = g_strdup (driver); if (g_strcmp0 (match, "exact-cmd") == 0) ppd_item->ppd_match_level = PPD_EXACT_CMD_MATCH; else if (g_strcmp0 (match, "exact") == 0) ppd_item->ppd_match_level = PPD_EXACT_MATCH; else if (g_strcmp0 (match, "close") == 0) ppd_item->ppd_match_level = PPD_CLOSE_MATCH; else if (g_strcmp0 (match, "generic") == 0) ppd_item->ppd_match_level = PPD_GENERIC_MATCH; else if (g_strcmp0 (match, "none") == 0) ppd_item->ppd_match_level = PPD_NO_MATCH; driver_list = g_list_append (driver_list, ppd_item); n++; } g_free (driver); g_free (match); g_variant_unref (item); } } g_variant_unref (array); } g_variant_unref (output); } else { if (error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } if (n > 0) { result = g_new0 (PPDName *, n + 1); i = 0; for (iter = driver_list; iter; iter = iter->next) { result[i] = iter->data; i++; } } if (result) { gchar **ppds_names; data->result = result; ppds_names = g_new0 (gchar *, n + 1); for (i = 0; i < n; i++) ppds_names[i] = g_strdup (result[i]->ppd_name); get_ppds_attribute_async (ppds_names, "NickName", get_ppd_names_async_cb, data); g_strfreev (ppds_names); } else { data->callback (NULL, data->printer_name, g_cancellable_is_cancelled (data->cancellable), data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->printer_name); g_free (data); } } static void get_device_attributes_cb (gchar *device_id, gchar *device_make_and_model, gchar *device_uri, gpointer user_data) { GDBusConnection *bus; GError *error = NULL; GPNData *data = (GPNData *) user_data; if (g_cancellable_is_cancelled (data->cancellable)) goto out; if (!device_id || !device_make_and_model || !device_uri) goto out; bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); goto out; } g_dbus_connection_call (bus, SCP_BUS, SCP_PATH, SCP_IFACE, "GetBestDrivers", g_variant_new ("(sss)", device_id, device_make_and_model, device_uri), G_VARIANT_TYPE ("(a(ss))"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, data->cancellable, get_ppd_names_async_dbus_scb, data); return; out: data->callback (NULL, data->printer_name, g_cancellable_is_cancelled (data->cancellable), data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->printer_name); g_free (data); } static void get_device_attributes_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; GDAData *data = (GDAData *) user_data; GError *error = NULL; GList *tmp; gchar *device_id = NULL; gchar *device_make_and_model = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { const gchar *ret_error; GVariant *devices_variant = NULL; g_variant_get (output, "(&s@a{ss})", &ret_error, &devices_variant); if (ret_error[0] != '\0') { g_warning ("%s", ret_error); } if (devices_variant) { GVariantIter *iter; GVariant *item; gint index = -1; if (data->device_uri) { gchar *key; gchar *value; gchar *number; gchar *endptr; gchar *suffix; g_variant_get (devices_variant, "a{ss}", &iter); while ((item = g_variant_iter_next_value (iter))) { g_variant_get (item, "{ss}", &key, &value); if (g_str_equal (value, data->device_uri)) { number = g_strrstr (key, ":"); if (number != NULL) { number++; index = g_ascii_strtoll (number, &endptr, 10); if (index == 0 && endptr == (number)) index = -1; } } g_free (key); g_free (value); g_variant_unref (item); } suffix = g_strdup_printf (":%d", index); g_variant_get (devices_variant, "a{ss}", &iter); while ((item = g_variant_iter_next_value (iter))) { gchar *key; gchar *value; g_variant_get (item, "{ss}", &key, &value); if (g_str_has_suffix (key, suffix)) { if (g_str_has_prefix (key, "device-id")) { device_id = g_strdup (value); } if (g_str_has_prefix (key, "device-make-and-model")) { device_make_and_model = g_strdup (value); } } g_free (key); g_free (value); g_variant_unref (item); } g_free (suffix); } g_variant_unref (devices_variant); } g_variant_unref (output); } else { if (error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } if (!device_id || !device_make_and_model) { GVariantBuilder include_scheme_builder; g_free (device_id); g_free (device_make_and_model); device_id = NULL; device_make_and_model = NULL; if (data->backend_list && !g_cancellable_is_cancelled (data->cancellable)) { g_variant_builder_init (&include_scheme_builder, G_VARIANT_TYPE ("as")); g_variant_builder_add (&include_scheme_builder, "s", data->backend_list->data); tmp = data->backend_list; data->backend_list = g_list_remove_link (data->backend_list, tmp); g_list_free_full (tmp, g_free); g_dbus_connection_call (G_DBUS_CONNECTION (g_object_ref (source_object)), MECHANISM_BUS, "/", MECHANISM_BUS, "DevicesGet", g_variant_new ("(iiasas)", 0, 0, &include_scheme_builder, NULL), G_VARIANT_TYPE ("(sa{ss})"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, data->cancellable, get_device_attributes_async_dbus_cb, user_data); return; } } g_object_unref (source_object); if (data->backend_list) { g_list_free_full (data->backend_list, g_free); data->backend_list = NULL; } data->callback (device_id, device_make_and_model, data->device_uri, data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->device_uri); g_free (data->printer_name); g_free (data); } static void get_device_attributes_async_scb (GHashTable *result, gpointer user_data) { GDBusConnection *bus; GVariantBuilder include_scheme_builder; IPPAttribute *attr; GDAData *data = (GDAData *) user_data; GError *error = NULL; GList *tmp; gint i; const gchar *backends[] = {"hpfax", "ncp", "beh", "bluetooth", "snmp", "dnssd", "hp", "ipp", "lpd", "parallel", "serial", "socket", "usb", NULL}; if (result) { attr = g_hash_table_lookup (result, "device-uri"); if (attr && attr->attribute_type == IPP_ATTRIBUTE_TYPE_STRING && attr->num_of_values > 0) data->device_uri = g_strdup (attr->attribute_values[0].string_value); g_hash_table_unref (result); } if (g_cancellable_is_cancelled (data->cancellable)) goto out; if (!data->device_uri) goto out; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); goto out; } for (i = 0; backends[i]; i++) data->backend_list = g_list_prepend (data->backend_list, g_strdup (backends[i])); g_variant_builder_init (&include_scheme_builder, G_VARIANT_TYPE ("as")); g_variant_builder_add (&include_scheme_builder, "s", data->backend_list->data); tmp = data->backend_list; data->backend_list = g_list_remove_link (data->backend_list, tmp); g_list_free_full (tmp, g_free); g_dbus_connection_call (g_object_ref (bus), MECHANISM_BUS, "/", MECHANISM_BUS, "DevicesGet", g_variant_new ("(iiasas)", 0, 0, &include_scheme_builder, NULL), G_VARIANT_TYPE ("(sa{ss})"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, data->cancellable, get_device_attributes_async_dbus_cb, data); return; out: data->callback (NULL, NULL, NULL, data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data->device_uri); g_free (data->printer_name); g_free (data); } /* * Get device-id, device-make-and-model and device-uri for given printer. */ static void get_device_attributes_async (const gchar *printer_name, GCancellable *cancellable, GDACallback callback, gpointer user_data) { GDAData *data; gchar **attributes; if (!printer_name) { callback (NULL, NULL, NULL, user_data); return; } data = g_new0 (GDAData, 1); data->printer_name = g_strdup (printer_name); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; attributes = g_new0 (gchar *, 2); attributes[0] = g_strdup ("device-uri"); get_ipp_attributes_async (printer_name, attributes, get_device_attributes_async_scb, data); g_strfreev (attributes); } /* * Return "count" best matching driver names for given printer. */ void get_ppd_names_async (gchar *printer_name, gint count, GCancellable *cancellable, GPNCallback callback, gpointer user_data) { GPNData *data; if (!printer_name) { callback (NULL, NULL, TRUE, user_data); return; } data = g_new0 (GPNData, 1); data->printer_name = g_strdup (printer_name); data->count = count; if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; /* * We have to find out device-id for this printer at first. */ get_device_attributes_async (printer_name, cancellable, get_device_attributes_cb, data); } typedef struct { PPDList *result; GCancellable *cancellable; GAPCallback callback; gpointer user_data; GMainContext *context; } GAPData; static gboolean get_all_ppds_idle_cb (gpointer user_data) { GAPData *data = (GAPData *) user_data; /* Don't call callback if cancelled */ if (data->cancellable && g_cancellable_is_cancelled (data->cancellable)) { ppd_list_free (data->result); data->result = NULL; } else { data->callback (data->result, data->user_data); } return FALSE; } static void get_all_ppds_data_free (gpointer user_data) { GAPData *data = (GAPData *) user_data; if (data->context) g_main_context_unref (data->context); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); } static void get_all_ppds_cb (gpointer user_data) { GAPData *data = (GAPData *) user_data; GSource *idle_source; idle_source = g_idle_source_new (); g_source_set_callback (idle_source, get_all_ppds_idle_cb, data, get_all_ppds_data_free); g_source_attach (idle_source, data->context); g_source_unref (idle_source); } static const struct { const char *normalized_name; const char *display_name; } manufacturers_names[] = { { "alps", "Alps" }, { "anitech", "Anitech" }, { "apple", "Apple" }, { "apollo", "Apollo" }, { "brother", "Brother" }, { "canon", "Canon" }, { "citizen", "Citizen" }, { "citoh", "Citoh" }, { "compaq", "Compaq" }, { "dec", "DEC" }, { "dell", "Dell" }, { "dnp", "DNP" }, { "dymo", "Dymo" }, { "epson", "Epson" }, { "fujifilm", "Fujifilm" }, { "fujitsu", "Fujitsu" }, { "gelsprinter", "Ricoh" }, { "generic", "Generic" }, { "genicom", "Genicom" }, { "gestetner", "Gestetner" }, { "hewlett packard", "Hewlett-Packard" }, { "heidelberg", "Heidelberg" }, { "hitachi", "Hitachi" }, { "hp", "Hewlett-Packard" }, { "ibm", "IBM" }, { "imagen", "Imagen" }, { "imagistics", "Imagistics" }, { "infoprint", "InfoPrint" }, { "infotec", "Infotec" }, { "intellitech", "Intellitech" }, { "kodak", "Kodak" }, { "konica minolta", "Minolta" }, { "kyocera", "Kyocera" }, { "kyocera mita", "Kyocera" }, { "lanier", "Lanier" }, { "lexmark international", "Lexmark" }, { "lexmark", "Lexmark" }, { "minolta", "Minolta" }, { "minolta qms", "Minolta" }, { "mitsubishi", "Mitsubishi" }, { "nec", "NEC" }, { "nrg", "NRG" }, { "oce", "Oce" }, { "oki", "Oki" }, { "oki data corp", "Oki" }, { "olivetti", "Olivetti" }, { "olympus", "Olympus" }, { "panasonic", "Panasonic" }, { "pcpi", "PCPI" }, { "pentax", "Pentax" }, { "qms", "QMS" }, { "raven", "Raven" }, { "raw", "Raw" }, { "ricoh", "Ricoh" }, { "samsung", "Samsung" }, { "savin", "Savin" }, { "seiko", "Seiko" }, { "sharp", "Sharp" }, { "shinko", "Shinko" }, { "sipix", "SiPix" }, { "sony", "Sony" }, { "star", "Star" }, { "tally", "Tally" }, { "tektronix", "Tektronix" }, { "texas instruments", "Texas Instruments" }, { "toshiba", "Toshiba" }, { "toshiba tec corp.", "Toshiba" }, { "xante", "Xante" }, { "xerox", "Xerox" }, { "zebra", "Zebra" }, }; static gpointer get_all_ppds_func (gpointer user_data) { ipp_attribute_t *attr; GHashTable *ppds_hash = NULL; GHashTable *manufacturers_hash = NULL; GAPData *data = (GAPData *) user_data; PPDName *item; ipp_t *request; ipp_t *response; GList *list; const gchar *ppd_make_and_model; const gchar *ppd_device_id; const gchar *ppd_name; const gchar *ppd_product; const gchar *ppd_make; gchar *mfg; gchar *mfg_normalized; gchar *mdl; gchar *manufacturer_display_name; gint i, j; request = ippNewRequest (CUPS_GET_PPDS); response = cupsDoRequest (CUPS_HTTP_DEFAULT, request, "/"); if (response && ippGetStatusCode (response) <= IPP_OK_CONFLICT) { /* * This hash contains names of manufacturers as keys and * values are GLists of PPD names. */ ppds_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); /* * This hash contains all possible names of manufacturers as keys * and values are just first occurences of their equivalents. * This is for mapping of e.g. "Hewlett Packard" and "HP" to the same name * (the one which comes first). */ manufacturers_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); for (i = 0; i < G_N_ELEMENTS (manufacturers_names); i++) { g_hash_table_insert (manufacturers_hash, g_strdup (manufacturers_names[i].normalized_name), g_strdup (manufacturers_names[i].display_name)); } for (attr = ippFirstAttribute (response); attr != NULL; attr = ippNextAttribute (response)) { while (attr != NULL && ippGetGroupTag (attr) != IPP_TAG_PRINTER) attr = ippNextAttribute (response); if (attr == NULL) break; ppd_device_id = NULL; ppd_make_and_model = NULL; ppd_name = NULL; ppd_product = NULL; ppd_make = NULL; mfg = NULL; mfg_normalized = NULL; mdl = NULL; while (attr != NULL && ippGetGroupTag (attr) == IPP_TAG_PRINTER) { if (g_strcmp0 (ippGetName (attr), "ppd-device-id") == 0 && ippGetValueTag (attr) == IPP_TAG_TEXT) ppd_device_id = ippGetString (attr, 0, NULL); else if (g_strcmp0 (ippGetName (attr), "ppd-make-and-model") == 0 && ippGetValueTag (attr) == IPP_TAG_TEXT) ppd_make_and_model = ippGetString (attr, 0, NULL); else if (g_strcmp0 (ippGetName (attr), "ppd-name") == 0 && ippGetValueTag (attr) == IPP_TAG_NAME) ppd_name = ippGetString (attr, 0, NULL); else if (g_strcmp0 (ippGetName (attr), "ppd-product") == 0 && ippGetValueTag (attr) == IPP_TAG_TEXT) ppd_product = ippGetString (attr, 0, NULL); else if (g_strcmp0 (ippGetName (attr), "ppd-make") == 0 && ippGetValueTag (attr) == IPP_TAG_TEXT) ppd_make = ippGetString (attr, 0, NULL); attr = ippNextAttribute (response); } /* Get manufacturer's name */ if (ppd_device_id && ppd_device_id[0] != '\0') { mfg = get_tag_value (ppd_device_id, "mfg"); if (!mfg) mfg = get_tag_value (ppd_device_id, "manufacturer"); mfg_normalized = normalize (mfg); } if (!mfg && ppd_make && ppd_make[0] != '\0') { mfg = g_strdup (ppd_make); mfg_normalized = normalize (ppd_make); } /* Get model */ if (ppd_make_and_model && ppd_make_and_model[0] != '\0') { mdl = g_strdup (ppd_make_and_model); } if (!mdl && ppd_product && ppd_product[0] != '\0') { mdl = g_strdup (ppd_product); } if (!mdl && ppd_device_id && ppd_device_id[0] != '\0') { mdl = get_tag_value (ppd_device_id, "mdl"); if (!mdl) mdl = get_tag_value (ppd_device_id, "model"); } if (ppd_name && ppd_name[0] != '\0' && mdl && mdl[0] != '\0' && mfg && mfg[0] != '\0') { manufacturer_display_name = g_hash_table_lookup (manufacturers_hash, mfg_normalized); if (!manufacturer_display_name) { g_hash_table_insert (manufacturers_hash, g_strdup (mfg_normalized), g_strdup (mfg)); } else { g_free (mfg_normalized); mfg_normalized = normalize (manufacturer_display_name); } item = g_new0 (PPDName, 1); item->ppd_name = g_strdup (ppd_name); item->ppd_display_name = g_strdup (mdl); item->ppd_match_level = -1; list = g_hash_table_lookup (ppds_hash, mfg_normalized); if (list) { list = g_list_append (list, item); } else { list = g_list_append (list, item); g_hash_table_insert (ppds_hash, g_strdup (mfg_normalized), list); } } g_free (mdl); g_free (mfg); g_free (mfg_normalized); if (attr == NULL) break; } } if (response) ippDelete(response); if (ppds_hash && manufacturers_hash) { GHashTableIter iter; gpointer key; gpointer value; GList *ppd_item; GList *sort_list = NULL; GList *list_iter; gchar *name; data->result = g_new0 (PPDList, 1); data->result->num_of_manufacturers = g_hash_table_size (ppds_hash); data->result->manufacturers = g_new0 (PPDManufacturerItem *, data->result->num_of_manufacturers); g_hash_table_iter_init (&iter, ppds_hash); while (g_hash_table_iter_next (&iter, &key, &value)) { sort_list = g_list_append (sort_list, g_strdup (key)); } /* Sort list of manufacturers */ sort_list = g_list_sort (sort_list, (GCompareFunc) g_strcmp0); /* * Fill resulting list of lists (list of manufacturers where * each item contains list of PPD names) */ i = 0; for (list_iter = sort_list; list_iter; list_iter = list_iter->next) { name = (gchar *) list_iter->data; value = g_hash_table_lookup (ppds_hash, name); data->result->manufacturers[i] = g_new0 (PPDManufacturerItem, 1); data->result->manufacturers[i]->manufacturer_name = g_strdup (name); data->result->manufacturers[i]->manufacturer_display_name = g_strdup (g_hash_table_lookup (manufacturers_hash, name)); data->result->manufacturers[i]->num_of_ppds = g_list_length ((GList *) value); data->result->manufacturers[i]->ppds = g_new0 (PPDName *, data->result->manufacturers[i]->num_of_ppds); for (ppd_item = (GList *) value, j = 0; ppd_item; ppd_item = ppd_item->next, j++) { data->result->manufacturers[i]->ppds[j] = ppd_item->data; } g_list_free ((GList *) value); i++; } g_list_free_full (sort_list, g_free); g_hash_table_destroy (ppds_hash); g_hash_table_destroy (manufacturers_hash); } get_all_ppds_cb (data); return NULL; } /* * Get names of all installed PPDs sorted by manufacturers names. */ void get_all_ppds_async (GCancellable *cancellable, GAPCallback callback, gpointer user_data) { GAPData *data; GThread *thread; GError *error = NULL; data = g_new0 (GAPData, 1); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; data->context = g_main_context_ref_thread_default (); thread = g_thread_try_new ("get-all-ppds", get_all_ppds_func, data, &error); if (!thread) { g_warning ("%s", error->message); callback (NULL, user_data); g_error_free (error); get_all_ppds_data_free (data); } else { g_thread_unref (thread); } } PPDList * ppd_list_copy (PPDList *list) { PPDList *result = NULL; gint i, j; if (list) { result = g_new0 (PPDList, 1); result->num_of_manufacturers = list->num_of_manufacturers; result->manufacturers = g_new0 (PPDManufacturerItem *, list->num_of_manufacturers); for (i = 0; i < result->num_of_manufacturers; i++) { result->manufacturers[i] = g_new0 (PPDManufacturerItem, 1); result->manufacturers[i]->num_of_ppds = list->manufacturers[i]->num_of_ppds; result->manufacturers[i]->ppds = g_new0 (PPDName *, result->manufacturers[i]->num_of_ppds); result->manufacturers[i]->manufacturer_display_name = g_strdup (list->manufacturers[i]->manufacturer_display_name); result->manufacturers[i]->manufacturer_name = g_strdup (list->manufacturers[i]->manufacturer_name); for (j = 0; j < result->manufacturers[i]->num_of_ppds; j++) { result->manufacturers[i]->ppds[j] = g_new0 (PPDName, 1); result->manufacturers[i]->ppds[j]->ppd_display_name = g_strdup (list->manufacturers[i]->ppds[j]->ppd_display_name); result->manufacturers[i]->ppds[j]->ppd_name = g_strdup (list->manufacturers[i]->ppds[j]->ppd_name); result->manufacturers[i]->ppds[j]->ppd_match_level = list->manufacturers[i]->ppds[j]->ppd_match_level; } } } return result; } void ppd_list_free (PPDList *list) { gint i, j; if (list) { for (i = 0; i < list->num_of_manufacturers; i++) { for (j = 0; j < list->manufacturers[i]->num_of_ppds; j++) { g_free (list->manufacturers[i]->ppds[j]->ppd_name); g_free (list->manufacturers[i]->ppds[j]->ppd_display_name); g_free (list->manufacturers[i]->ppds[j]); } g_free (list->manufacturers[i]->manufacturer_name); g_free (list->manufacturers[i]->manufacturer_display_name); g_free (list->manufacturers[i]->ppds); g_free (list->manufacturers[i]); } g_free (list->manufacturers); g_free (list); } } gchar * get_standard_manufacturers_name (gchar *name) { gchar *normalized_name; gchar *result = NULL; gint i; if (name) { normalized_name = normalize (name); for (i = 0; i < G_N_ELEMENTS (manufacturers_names); i++) { if (g_strcmp0 (manufacturers_names[i].normalized_name, normalized_name) == 0) { result = g_strdup (manufacturers_names[i].display_name); break; } } g_free (normalized_name); } return result; } typedef struct { gchar *printer_name; gchar *host_name; gint port; gchar *result; PGPCallback callback; gpointer user_data; GMainContext *context; } PGPData; static gboolean printer_get_ppd_idle_cb (gpointer user_data) { PGPData *data = (PGPData *) user_data; data->callback (data->result, data->user_data); return FALSE; } static void printer_get_ppd_data_free (gpointer user_data) { PGPData *data = (PGPData *) user_data; if (data->context) g_main_context_unref (data->context); g_free (data->result); g_free (data->printer_name); g_free (data->host_name); g_free (data); } static void printer_get_ppd_cb (gpointer user_data) { PGPData *data = (PGPData *) user_data; GSource *idle_source; idle_source = g_idle_source_new (); g_source_set_callback (idle_source, printer_get_ppd_idle_cb, data, printer_get_ppd_data_free); g_source_attach (idle_source, data->context); g_source_unref (idle_source); } static gpointer printer_get_ppd_func (gpointer user_data) { PGPData *data = (PGPData *) user_data; if (data->host_name) { http_t *http; http = httpConnect (data->host_name, data->port); if (http) { data->result = g_strdup (cupsGetPPD2 (http, data->printer_name)); httpClose (http); } } else { data->result = g_strdup (cupsGetPPD (data->printer_name)); } printer_get_ppd_cb (data); return NULL; } void printer_get_ppd_async (const gchar *printer_name, const gchar *host_name, gint port, PGPCallback callback, gpointer user_data) { PGPData *data; GThread *thread; GError *error = NULL; data = g_new0 (PGPData, 1); data->printer_name = g_strdup (printer_name); data->host_name = g_strdup (host_name); data->port = port; data->callback = callback; data->user_data = user_data; data->context = g_main_context_ref_thread_default (); thread = g_thread_try_new ("printer-get-ppd", printer_get_ppd_func, data, &error); if (!thread) { g_warning ("%s", error->message); callback (NULL, user_data); g_error_free (error); printer_get_ppd_data_free (data); } else { g_thread_unref (thread); } } typedef struct { gchar *printer_name; cups_dest_t *result; GNDCallback callback; gpointer user_data; GMainContext *context; } GNDData; static gboolean get_named_dest_idle_cb (gpointer user_data) { GNDData *data = (GNDData *) user_data; data->callback (data->result, data->user_data); return FALSE; } static void get_named_dest_data_free (gpointer user_data) { GNDData *data = (GNDData *) user_data; if (data->context) g_main_context_unref (data->context); g_free (data->printer_name); g_free (data); } static void get_named_dest_cb (gpointer user_data) { GNDData *data = (GNDData *) user_data; GSource *idle_source; idle_source = g_idle_source_new (); g_source_set_callback (idle_source, get_named_dest_idle_cb, data, get_named_dest_data_free); g_source_attach (idle_source, data->context); g_source_unref (idle_source); } static gpointer get_named_dest_func (gpointer user_data) { GNDData *data = (GNDData *) user_data; data->result = cupsGetNamedDest (CUPS_HTTP_DEFAULT, data->printer_name, NULL); get_named_dest_cb (data); return NULL; } void get_named_dest_async (const gchar *printer_name, GNDCallback callback, gpointer user_data) { GNDData *data; GThread *thread; GError *error = NULL; data = g_new0 (GNDData, 1); data->printer_name = g_strdup (printer_name); data->callback = callback; data->user_data = user_data; data->context = g_main_context_ref_thread_default (); thread = g_thread_try_new ("get-named-dest", get_named_dest_func, data, &error); if (!thread) { g_warning ("%s", error->message); callback (NULL, user_data); g_error_free (error); get_named_dest_data_free (data); } else { g_thread_unref (thread); } } typedef struct { GCancellable *cancellable; PAOCallback callback; gpointer user_data; } PAOData; static void printer_add_option_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; gboolean success = FALSE; PAOData *data = (PAOData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') g_warning ("%s", ret_error); else success = TRUE; g_variant_unref (output); } else { if (error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } data->callback (success, data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); } void printer_add_option_async (const gchar *printer_name, const gchar *option_name, gchar **values, gboolean set_default, GCancellable *cancellable, PAOCallback callback, gpointer user_data) { GVariantBuilder array_builder; GDBusConnection *bus; PAOData *data; GError *error = NULL; gint i; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); callback (FALSE, user_data); return; } g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("as")); if (values) { for (i = 0; values[i]; i++) g_variant_builder_add (&array_builder, "s", values[i]); } data = g_new0 (PAOData, 1); data->cancellable = cancellable; data->callback = callback; data->user_data = user_data; g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, set_default ? "PrinterAddOptionDefault" : "PrinterAddOption", g_variant_new ("(ssas)", printer_name, option_name, &array_builder), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, cancellable, printer_add_option_async_dbus_cb, data); } typedef struct { GCancellable *cancellable; GCDCallback callback; gpointer user_data; GList *backend_list; } GCDData; static gint get_suffix_index (gchar *string) { gchar *number; gchar *endptr; gint index = -1; number = g_strrstr (string, ":"); if (number) { number++; index = g_ascii_strtoll (number, &endptr, 10); if (index == 0 && endptr == number) index = -1; } return index; } static void get_cups_devices_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpPrintDevice **devices = NULL; GVariant *output; GCDData *data = (GCDData *) user_data; GError *error = NULL; GList *result = NULL; gint num_of_devices = 0; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); if (output) { const gchar *ret_error; GVariant *devices_variant = NULL; g_variant_get (output, "(&s@a{ss})", &ret_error, &devices_variant); if (ret_error[0] != '\0') { g_warning ("%s", ret_error); } if (devices_variant) { GVariantIter *iter; GVariant *item; gchar *key; gchar *value; gint index = -1, max_index = -1, i; g_variant_get (devices_variant, "a{ss}", &iter); while ((item = g_variant_iter_next_value (iter))) { g_variant_get (item, "{ss}", &key, &value); index = get_suffix_index (key); if (index > max_index) max_index = index; g_free (key); g_free (value); g_variant_unref (item); } if (max_index >= 0) { num_of_devices = max_index + 1; devices = g_new0 (PpPrintDevice *, num_of_devices); g_variant_get (devices_variant, "a{ss}", &iter); while ((item = g_variant_iter_next_value (iter))) { g_variant_get (item, "{ss}", &key, &value); index = get_suffix_index (key); if (index >= 0) { if (!devices[index]) devices[index] = g_new0 (PpPrintDevice, 1); if (g_str_has_prefix (key, "device-class")) devices[index]->device_class = g_strdup (value); else if (g_str_has_prefix (key, "device-id")) devices[index]->device_id = g_strdup (value); else if (g_str_has_prefix (key, "device-info")) devices[index]->device_info = g_strdup (value); else if (g_str_has_prefix (key, "device-make-and-model")) { devices[index]->device_make_and_model = g_strdup (value); devices[index]->device_name = g_strdup (value); } else if (g_str_has_prefix (key, "device-uri")) devices[index]->device_uri = g_strdup (value); else if (g_str_has_prefix (key, "device-location")) devices[index]->device_location = g_strdup (value); devices[index]->acquisition_method = ACQUISITION_METHOD_DEFAULT_CUPS_SERVER; } g_free (key); g_free (value); g_variant_unref (item); } for (i = 0; i < num_of_devices; i++) result = g_list_append (result, devices[i]); g_free (devices); } g_variant_unref (devices_variant); } g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); data->callback (result, TRUE, g_cancellable_is_cancelled (data->cancellable), data->user_data); g_list_free_full (data->backend_list, g_free); data->backend_list = NULL; g_object_unref (source_object); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); return; } if (data->backend_list) { if (!g_cancellable_is_cancelled (data->cancellable)) { GVariantBuilder include_scheme_builder; data->callback (result, FALSE, FALSE, data->user_data); g_variant_builder_init (&include_scheme_builder, G_VARIANT_TYPE ("as")); g_variant_builder_add (&include_scheme_builder, "s", data->backend_list->data); g_free (data->backend_list->data); data->backend_list = g_list_remove_link (data->backend_list, data->backend_list); g_dbus_connection_call (G_DBUS_CONNECTION (g_object_ref (source_object)), MECHANISM_BUS, "/", MECHANISM_BUS, "DevicesGet", g_variant_new ("(iiasas)", 0, 0, &include_scheme_builder, NULL), G_VARIANT_TYPE ("(sa{ss})"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, data->cancellable, get_cups_devices_async_dbus_cb, user_data); return; } else { data->callback (result, TRUE, TRUE, data->user_data); g_list_free_full (data->backend_list, g_free); data->backend_list = NULL; } } else { data->callback (result, TRUE, g_cancellable_is_cancelled (data->cancellable), data->user_data); } g_object_unref (source_object); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); } void get_cups_devices_async (GCancellable *cancellable, GCDCallback callback, gpointer user_data) { GDBusConnection *bus; GVariantBuilder include_scheme_builder; GCDData *data; GError *error = NULL; gint i; const gchar *backends[] = {"hpfax", "ncp", "beh", "bluetooth", "snmp", "dnssd", "hp", "ipp", "lpd", "parallel", "serial", "socket", "usb", NULL}; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); callback (NULL, TRUE, FALSE, user_data); return; } data = g_new0 (GCDData, 1); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; for (i = 0; backends[i]; i++) data->backend_list = g_list_prepend (data->backend_list, g_strdup (backends[i])); g_variant_builder_init (&include_scheme_builder, G_VARIANT_TYPE ("as")); g_variant_builder_add (&include_scheme_builder, "s", data->backend_list->data); g_free (data->backend_list->data); data->backend_list = g_list_remove_link (data->backend_list, data->backend_list); g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "DevicesGet", g_variant_new ("(iiasas)", 0, 0, &include_scheme_builder, NULL), G_VARIANT_TYPE ("(sa{ss})"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, cancellable, get_cups_devices_async_dbus_cb, data); } void pp_print_device_free (PpPrintDevice *device) { if (device) { g_free (device->device_class); g_free (device->device_id); g_free (device->device_info); g_free (device->device_make_and_model); g_free (device->device_uri); g_free (device->device_location); g_free (device->device_name); g_free (device->device_ppd); g_free (device); } } typedef struct { gchar *printer_name; gboolean my_jobs; gint which_jobs; cups_job_t *jobs; gint num_of_jobs; CGJCallback callback; gpointer user_data; GMainContext *context; } CGJData; static gboolean cups_get_jobs_idle_cb (gpointer user_data) { CGJData *data = (CGJData *) user_data; data->callback (data->jobs, data->num_of_jobs, data->user_data); return FALSE; } static void cups_get_jobs_data_free (gpointer user_data) { CGJData *data = (CGJData *) user_data; if (data->context) g_main_context_unref (data->context); g_free (data->printer_name); g_free (data); } static void cups_get_jobs_cb (gpointer user_data) { CGJData *data = (CGJData *) user_data; GSource *idle_source; idle_source = g_idle_source_new (); g_source_set_callback (idle_source, cups_get_jobs_idle_cb, data, cups_get_jobs_data_free); g_source_attach (idle_source, data->context); g_source_unref (idle_source); } static gpointer cups_get_jobs_func (gpointer user_data) { CGJData *data = (CGJData *) user_data; data->num_of_jobs = cupsGetJobs (&data->jobs, data->printer_name, data->my_jobs ? 1 : 0, data->which_jobs); cups_get_jobs_cb (data); return NULL; } void cups_get_jobs_async (const gchar *printer_name, gboolean my_jobs, gint which_jobs, CGJCallback callback, gpointer user_data) { CGJData *data; GThread *thread; GError *error = NULL; data = g_new0 (CGJData, 1); data->printer_name = g_strdup (printer_name); data->my_jobs = my_jobs; data->which_jobs = which_jobs; data->callback = callback; data->user_data = user_data; data->context = g_main_context_ref_thread_default (); thread = g_thread_try_new ("cups-get-jobs", cups_get_jobs_func, data, &error); if (!thread) { g_warning ("%s", error->message); callback (NULL, 0, user_data); g_error_free (error); cups_get_jobs_data_free (data); } else { g_thread_unref (thread); } } typedef struct { GCancellable *cancellable; JCPCallback callback; gpointer user_data; } JCPData; static void job_cancel_purge_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; JCPData *data = (JCPData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { g_variant_unref (output); } else { if (!g_cancellable_is_cancelled (data->cancellable)) g_warning ("%s", error->message); g_error_free (error); } data->callback (data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); } void job_cancel_purge_async (gint job_id, gboolean job_purge, GCancellable *cancellable, JCPCallback callback, gpointer user_data) { GDBusConnection *bus; JCPData *data; GError *error = NULL; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get session bus: %s", error->message); g_error_free (error); callback (user_data); return; } data = g_new0 (JCPData, 1); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "JobCancelPurge", g_variant_new ("(ib)", job_id, job_purge), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, job_cancel_purge_async_dbus_cb, data); } typedef struct { GCancellable *cancellable; JSHUCallback callback; gpointer user_data; } JSHUData; static void job_set_hold_until_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; JSHUData *data = (JSHUData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { g_variant_unref (output); } else { if (!g_cancellable_is_cancelled (data->cancellable)) g_warning ("%s", error->message); g_error_free (error); } data->callback (data->user_data); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); } void job_set_hold_until_async (gint job_id, const gchar *job_hold_until, GCancellable *cancellable, JSHUCallback callback, gpointer user_data) { GDBusConnection *bus; JSHUData *data; GError *error = NULL; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get session bus: %s", error->message); g_error_free (error); callback (user_data); return; } data = g_new0 (JSHUData, 1); if (cancellable) data->cancellable = g_object_ref (cancellable); data->callback = callback; data->user_data = user_data; g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "JobSetHoldUntil", g_variant_new ("(is)", job_id, job_hold_until), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, job_set_hold_until_async_dbus_cb, data); }
431
./cinnamon-control-center/panels/unused/printers/pp-ipp-option-widget.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "config.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <glib/gi18n-lib.h> #include "pp-ipp-option-widget.h" #include "pp-utils.h" #define PP_IPP_OPTION_WIDGET_GET_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), PP_TYPE_IPP_OPTION_WIDGET, PpIPPOptionWidgetPrivate)) static void pp_ipp_option_widget_finalize (GObject *object); static gboolean construct_widget (PpIPPOptionWidget *widget); static void update_widget (PpIPPOptionWidget *widget); static void update_widget_real (PpIPPOptionWidget *widget); struct PpIPPOptionWidgetPrivate { GtkWidget *switch_button; GtkWidget *spin_button; GtkWidget *combo; GtkWidget *box; IPPAttribute *option_supported; IPPAttribute *option_default; gchar *printer_name; gchar *option_name; GHashTable *ipp_attribute; }; G_DEFINE_TYPE (PpIPPOptionWidget, pp_ipp_option_widget, GTK_TYPE_HBOX) static const struct { const char *keyword; const char *choice; const char *translation; } ipp_choice_translations[] = { /* Translators: this is an option of "Two Sided" */ { "sides", "one-sided", N_("One Sided") }, /* Translators: this is an option of "Two Sided" */ { "sides", "two-sided-long-edge", N_("Long Edge (Standard)") }, /* Translators: this is an option of "Two Sided" */ { "sides", "two-sided-short-edge", N_("Short Edge (Flip)") }, /* Translators: this is an option of "Orientation" */ { "orientation-requested", "3", N_("Portrait") }, /* Translators: this is an option of "Orientation" */ { "orientation-requested", "4", N_("Landscape") }, /* Translators: this is an option of "Orientation" */ { "orientation-requested", "5", N_("Reverse landscape") }, /* Translators: this is an option of "Orientation" */ { "orientation-requested", "6", N_("Reverse portrait") }, }; static const gchar * ipp_choice_translate (const gchar *option, const gchar *choice) { gint i; for (i = 0; i < G_N_ELEMENTS (ipp_choice_translations); i++) { if (g_strcmp0 (ipp_choice_translations[i].keyword, option) == 0 && g_strcmp0 (ipp_choice_translations[i].choice, choice) == 0) return _(ipp_choice_translations[i].translation); } return choice; } static void pp_ipp_option_widget_class_init (PpIPPOptionWidgetClass *class) { GObjectClass *object_class; object_class = G_OBJECT_CLASS (class); object_class->finalize = pp_ipp_option_widget_finalize; g_type_class_add_private (class, sizeof (PpIPPOptionWidgetPrivate)); } static void pp_ipp_option_widget_init (PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv; priv = widget->priv = PP_IPP_OPTION_WIDGET_GET_PRIVATE (widget); priv->switch_button = NULL; priv->spin_button = NULL; priv->combo = NULL; priv->box = NULL; priv->printer_name = NULL; priv->option_name = NULL; priv->option_supported = NULL; priv->option_default = NULL; priv->ipp_attribute = NULL; } static void pp_ipp_option_widget_finalize (GObject *object) { PpIPPOptionWidget *widget = PP_IPP_OPTION_WIDGET (object); PpIPPOptionWidgetPrivate *priv = widget->priv; if (priv) { if (priv->option_name) { g_free (priv->option_name); priv->option_name = NULL; } if (priv->printer_name) { g_free (priv->printer_name); priv->printer_name = NULL; } if (priv->option_supported) { ipp_attribute_free (priv->option_supported); priv->option_supported = NULL; } if (priv->option_default) { ipp_attribute_free (priv->option_default); priv->option_default = NULL; } if (priv->ipp_attribute) { g_hash_table_unref (priv->ipp_attribute); priv->ipp_attribute = NULL; } } G_OBJECT_CLASS (pp_ipp_option_widget_parent_class)->finalize (object); } GtkWidget * pp_ipp_option_widget_new (IPPAttribute *attr_supported, IPPAttribute *attr_default, const gchar *option_name, const gchar *printer) { PpIPPOptionWidgetPrivate *priv; PpIPPOptionWidget *widget = NULL; if (attr_supported && option_name && printer) { widget = g_object_new (PP_TYPE_IPP_OPTION_WIDGET, NULL); priv = PP_IPP_OPTION_WIDGET_GET_PRIVATE (widget); priv->printer_name = g_strdup (printer); priv->option_name = g_strdup (option_name); priv->option_supported = ipp_attribute_copy (attr_supported); priv->option_default = ipp_attribute_copy (attr_default); if (construct_widget (widget)) { update_widget_real (widget); } else { g_object_ref_sink (widget); g_object_unref (widget); widget = NULL; } } return (GtkWidget *) widget; } enum { NAME_COLUMN, VALUE_COLUMN, N_COLUMNS }; static GtkWidget * combo_box_new (void) { GtkCellRenderer *cell; GtkListStore *store; GtkWidget *combo_box; combo_box = gtk_combo_box_new (); store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING); gtk_combo_box_set_model (GTK_COMBO_BOX (combo_box), GTK_TREE_MODEL (store)); g_object_unref (store); cell = gtk_cell_renderer_text_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), cell, TRUE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), cell, "text", NAME_COLUMN, NULL); return combo_box; } static void combo_box_append (GtkWidget *combo, const gchar *display_text, const gchar *value) { GtkTreeModel *model; GtkListStore *store; GtkTreeIter iter; model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo)); store = GTK_LIST_STORE (model); gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, NAME_COLUMN, display_text, VALUE_COLUMN, value, -1); } struct ComboSet { GtkComboBox *combo; const gchar *value; }; static gboolean set_cb (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data) { struct ComboSet *set_data = data; gboolean found; char *value; gtk_tree_model_get (model, iter, VALUE_COLUMN, &value, -1); found = (strcmp (value, set_data->value) == 0); g_free (value); if (found) gtk_combo_box_set_active_iter (set_data->combo, iter); return found; } static void combo_box_set (GtkWidget *combo, const gchar *value) { struct ComboSet set_data; GtkTreeModel *model; model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo)); set_data.combo = GTK_COMBO_BOX (combo); set_data.value = value; gtk_tree_model_foreach (model, set_cb, &set_data); } static char * combo_box_get (GtkWidget *combo) { GtkTreeModel *model; GtkTreeIter iter; gchar *value = NULL; model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo)); if (gtk_combo_box_get_active_iter (GTK_COMBO_BOX (combo), &iter)) gtk_tree_model_get (model, &iter, VALUE_COLUMN, &value, -1); return value; } static void printer_add_option_async_cb (gboolean success, gpointer user_data) { update_widget (user_data); } static void switch_changed_cb (GtkWidget *switch_button, GParamSpec *pspec, PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv = widget->priv; gchar **values; values = g_new0 (gchar *, 2); if (gtk_switch_get_active (GTK_SWITCH (switch_button))) values[0] = g_strdup ("True"); else values[0] = g_strdup ("False"); printer_add_option_async (priv->printer_name, priv->option_name, values, TRUE, NULL, printer_add_option_async_cb, widget); g_strfreev (values); } static void combo_changed_cb (GtkWidget *combo, PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv = widget->priv; gchar **values; values = g_new0 (gchar *, 2); values[0] = combo_box_get (combo); printer_add_option_async (priv->printer_name, priv->option_name, values, TRUE, NULL, printer_add_option_async_cb, widget); g_strfreev (values); } static void spin_button_changed_cb (GtkWidget *spin_button, PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv = widget->priv; gchar **values; values = g_new0 (gchar *, 2); values[0] = g_strdup_printf ("%d", gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (spin_button))); printer_add_option_async (priv->printer_name, priv->option_name, values, TRUE, NULL, printer_add_option_async_cb, widget); g_strfreev (values); } static gboolean construct_widget (PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv = widget->priv; gboolean trivial_option = FALSE; gboolean result = FALSE; gchar *value; gint i; if (priv->option_supported) { switch (priv->option_supported->attribute_type) { case IPP_ATTRIBUTE_TYPE_INTEGER: if (priv->option_supported->num_of_values <= 1) trivial_option = TRUE; break; case IPP_ATTRIBUTE_TYPE_STRING: if (priv->option_supported->num_of_values <= 1) trivial_option = TRUE; break; case IPP_ATTRIBUTE_TYPE_RANGE: if (priv->option_supported->attribute_values[0].lower_range == priv->option_supported->attribute_values[0].upper_range) trivial_option = TRUE; break; } if (!trivial_option) { switch (priv->option_supported->attribute_type) { case IPP_ATTRIBUTE_TYPE_BOOLEAN: priv->switch_button = gtk_switch_new (); gtk_box_pack_start (GTK_BOX (widget), priv->switch_button, FALSE, FALSE, 0); g_signal_connect (priv->switch_button, "notify::active", G_CALLBACK (switch_changed_cb), widget); break; case IPP_ATTRIBUTE_TYPE_INTEGER: priv->combo = combo_box_new (); for (i = 0; i < priv->option_supported->num_of_values; i++) { value = g_strdup_printf ("%d", priv->option_supported->attribute_values[i].integer_value); combo_box_append (priv->combo, ipp_choice_translate (priv->option_name, value), value); g_free (value); } gtk_box_pack_start (GTK_BOX (widget), priv->combo, FALSE, FALSE, 0); g_signal_connect (priv->combo, "changed", G_CALLBACK (combo_changed_cb), widget); break; case IPP_ATTRIBUTE_TYPE_STRING: priv->combo = combo_box_new (); for (i = 0; i < priv->option_supported->num_of_values; i++) combo_box_append (priv->combo, ipp_choice_translate (priv->option_name, priv->option_supported->attribute_values[i].string_value), priv->option_supported->attribute_values[i].string_value); gtk_box_pack_start (GTK_BOX (widget), priv->combo, FALSE, FALSE, 0); g_signal_connect (priv->combo, "changed", G_CALLBACK (combo_changed_cb), widget); break; case IPP_ATTRIBUTE_TYPE_RANGE: priv->spin_button = gtk_spin_button_new_with_range ( priv->option_supported->attribute_values[0].lower_range, priv->option_supported->attribute_values[0].upper_range, 1); gtk_box_pack_start (GTK_BOX (widget), priv->spin_button, FALSE, FALSE, 0); g_signal_connect (priv->spin_button, "value-changed", G_CALLBACK (spin_button_changed_cb), widget); break; default: break; } result = TRUE; } } return result; } static void update_widget_real (PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv = widget->priv; IPPAttribute *attr = NULL; gchar *value; gchar *attr_name; if (priv->option_default) { attr = ipp_attribute_copy (priv->option_default); ipp_attribute_free (priv->option_default); priv->option_default = NULL; } else if (priv->ipp_attribute) { attr_name = g_strdup_printf ("%s-default", priv->option_name); attr = ipp_attribute_copy (g_hash_table_lookup (priv->ipp_attribute, attr_name)); g_free (attr_name); g_hash_table_unref (priv->ipp_attribute); priv->ipp_attribute = NULL; } switch (priv->option_supported->attribute_type) { case IPP_ATTRIBUTE_TYPE_BOOLEAN: g_signal_handlers_block_by_func (priv->switch_button, switch_changed_cb, widget); if (attr && attr->num_of_values > 0 && attr->attribute_type == IPP_ATTRIBUTE_TYPE_BOOLEAN) { gtk_switch_set_active (GTK_SWITCH (priv->switch_button), attr->attribute_values[0].boolean_value); } g_signal_handlers_unblock_by_func (priv->switch_button, switch_changed_cb, widget); break; case IPP_ATTRIBUTE_TYPE_INTEGER: g_signal_handlers_block_by_func (priv->combo, combo_changed_cb, widget); if (attr && attr->num_of_values > 0 && attr->attribute_type == IPP_ATTRIBUTE_TYPE_INTEGER) { value = g_strdup_printf ("%d", attr->attribute_values[0].integer_value); combo_box_set (priv->combo, value); g_free (value); } else { value = g_strdup_printf ("%d", priv->option_supported->attribute_values[0].integer_value); combo_box_set (priv->combo, value); g_free (value); } g_signal_handlers_unblock_by_func (priv->combo, combo_changed_cb, widget); break; case IPP_ATTRIBUTE_TYPE_STRING: g_signal_handlers_block_by_func (priv->combo, combo_changed_cb, widget); if (attr && attr->num_of_values > 0 && attr->attribute_type == IPP_ATTRIBUTE_TYPE_STRING) { combo_box_set (priv->combo, attr->attribute_values[0].string_value); } else { combo_box_set (priv->combo, priv->option_supported->attribute_values[0].string_value); } g_signal_handlers_unblock_by_func (priv->combo, combo_changed_cb, widget); break; case IPP_ATTRIBUTE_TYPE_RANGE: g_signal_handlers_block_by_func (priv->spin_button, spin_button_changed_cb, widget); if (attr && attr->num_of_values > 0 && attr->attribute_type == IPP_ATTRIBUTE_TYPE_INTEGER) { gtk_spin_button_set_value (GTK_SPIN_BUTTON (priv->spin_button), attr->attribute_values[0].integer_value); } else { gtk_spin_button_set_value (GTK_SPIN_BUTTON (priv->spin_button), priv->option_supported->attribute_values[0].lower_range); } g_signal_handlers_unblock_by_func (priv->spin_button, spin_button_changed_cb, widget); break; default: break; } ipp_attribute_free (attr); } static void get_ipp_attributes_cb (GHashTable *table, gpointer user_data) { PpIPPOptionWidget *widget = (PpIPPOptionWidget *) user_data; PpIPPOptionWidgetPrivate *priv = widget->priv; if (priv->ipp_attribute) g_hash_table_unref (priv->ipp_attribute); priv->ipp_attribute = table; update_widget_real (widget); } static void update_widget (PpIPPOptionWidget *widget) { PpIPPOptionWidgetPrivate *priv = widget->priv; gchar **attributes_names; attributes_names = g_new0 (gchar *, 2); attributes_names[0] = g_strdup_printf ("%s-default", priv->option_name); get_ipp_attributes_async (priv->printer_name, attributes_names, get_ipp_attributes_cb, widget); g_strfreev (attributes_names); }
432
./cinnamon-control-center/panels/unused/printers/pp-new-printer.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "pp-new-printer.h" #include <glib/gstdio.h> #include <glib/gi18n.h> #include "pp-utils.h" #include "pp-maintenance-command.h" #define PACKAGE_KIT_BUS "org.freedesktop.PackageKit" #define PACKAGE_KIT_PATH "/org/freedesktop/PackageKit" #define PACKAGE_KIT_MODIFY_IFACE "org.freedesktop.PackageKit.Modify" #define PACKAGE_KIT_QUERY_IFACE "org.freedesktop.PackageKit.Query" #define DBUS_TIMEOUT 120000 #define DBUS_TIMEOUT_LONG 600000 #if (CUPS_VERSION_MAJOR > 1) || (CUPS_VERSION_MINOR > 5) #define HAVE_CUPS_1_6 1 #endif #ifndef HAVE_CUPS_1_6 #define ippGetState(ipp) ipp->state #endif struct _PpNewPrinterPrivate { gchar *name; gchar *original_name; gchar *device_uri; gchar *device_id; gchar *ppd_name; gchar *ppd_file_name; gchar *info; gchar *location; gchar *make_and_model; gchar *host_name; gint host_port; gboolean is_network_device; guint window_id; gboolean unlink_ppd_file; GSimpleAsyncResult *res; GCancellable *cancellable; }; G_DEFINE_TYPE (PpNewPrinter, pp_new_printer, G_TYPE_OBJECT); enum { PROP_0 = 0, PROP_NAME, PROP_ORIGINAL_NAME, PROP_DEVICE_URI, PROP_DEVICE_ID, PROP_PPD_NAME, PROP_PPD_FILE_NAME, PROP_INFO, PROP_LOCATION, PROP_MAKE_AND_MODEL, PROP_HOST_NAME, PROP_HOST_PORT, PROP_IS_NETWORK_DEVICE, PROP_WINDOW_ID }; static void char_clear_pointer (gchar *pointer) { if (pointer) { g_free (pointer); pointer = NULL; } } static void pp_new_printer_finalize (GObject *object) { PpNewPrinterPrivate *priv; priv = PP_NEW_PRINTER (object)->priv; if (priv->unlink_ppd_file && priv->ppd_file_name) g_unlink (priv->ppd_file_name); char_clear_pointer (priv->name); char_clear_pointer (priv->original_name); char_clear_pointer (priv->device_uri); char_clear_pointer (priv->device_id); char_clear_pointer (priv->ppd_name); char_clear_pointer (priv->ppd_file_name); char_clear_pointer (priv->info); char_clear_pointer (priv->location); char_clear_pointer (priv->make_and_model); char_clear_pointer (priv->host_name); if (priv->res) g_object_unref (priv->res); if (priv->cancellable) g_object_unref (priv->cancellable); G_OBJECT_CLASS (pp_new_printer_parent_class)->finalize (object); } static void pp_new_printer_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *param_spec) { PpNewPrinter *self; self = PP_NEW_PRINTER (object); switch (prop_id) { case PROP_NAME: g_value_set_string (value, self->priv->name); break; case PROP_ORIGINAL_NAME: g_value_set_string (value, self->priv->original_name); break; case PROP_DEVICE_URI: g_value_set_string (value, self->priv->device_uri); break; case PROP_DEVICE_ID: g_value_set_string (value, self->priv->device_id); break; case PROP_PPD_NAME: g_value_set_string (value, self->priv->ppd_name); break; case PROP_PPD_FILE_NAME: g_value_set_string (value, self->priv->ppd_file_name); break; case PROP_INFO: g_value_set_string (value, self->priv->info); break; case PROP_LOCATION: g_value_set_string (value, self->priv->location); break; case PROP_MAKE_AND_MODEL: g_value_set_string (value, self->priv->make_and_model); break; case PROP_HOST_NAME: g_value_set_string (value, self->priv->host_name); break; case PROP_HOST_PORT: g_value_set_int (value, self->priv->host_port); break; case PROP_IS_NETWORK_DEVICE: g_value_set_boolean (value, self->priv->is_network_device); break; case PROP_WINDOW_ID: g_value_set_int (value, self->priv->window_id); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, param_spec); break; } } static void pp_new_printer_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *param_spec) { PpNewPrinter *self = PP_NEW_PRINTER (object); switch (prop_id) { case PROP_NAME: g_free (self->priv->name); self->priv->name = g_value_dup_string (value); break; case PROP_ORIGINAL_NAME: g_free (self->priv->original_name); self->priv->original_name = g_value_dup_string (value); break; case PROP_DEVICE_URI: g_free (self->priv->device_uri); self->priv->device_uri = g_value_dup_string (value); break; case PROP_DEVICE_ID: g_free (self->priv->device_id); self->priv->device_id = g_value_dup_string (value); break; case PROP_PPD_NAME: g_free (self->priv->ppd_name); self->priv->ppd_name = g_value_dup_string (value); break; case PROP_PPD_FILE_NAME: g_free (self->priv->ppd_file_name); self->priv->ppd_file_name = g_value_dup_string (value); break; case PROP_INFO: g_free (self->priv->info); self->priv->info = g_value_dup_string (value); break; case PROP_LOCATION: g_free (self->priv->location); self->priv->location = g_value_dup_string (value); break; case PROP_MAKE_AND_MODEL: g_free (self->priv->make_and_model); self->priv->make_and_model = g_value_dup_string (value); break; case PROP_HOST_NAME: g_free (self->priv->host_name); self->priv->host_name = g_value_dup_string (value); break; case PROP_HOST_PORT: self->priv->host_port = g_value_get_int (value); break; case PROP_IS_NETWORK_DEVICE: self->priv->is_network_device = g_value_get_boolean (value); break; case PROP_WINDOW_ID: self->priv->window_id = g_value_get_int (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, param_spec); break; } } static void pp_new_printer_class_init (PpNewPrinterClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (PpNewPrinterPrivate)); gobject_class->set_property = pp_new_printer_set_property; gobject_class->get_property = pp_new_printer_get_property; gobject_class->finalize = pp_new_printer_finalize; g_object_class_install_property (gobject_class, PROP_NAME, g_param_spec_string ("name", "Name", "The new printer's name", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_ORIGINAL_NAME, g_param_spec_string ("original-name", "Original name", "Original name of the new printer", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_DEVICE_URI, g_param_spec_string ("device-uri", "Device URI", "The new printer's device URI", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_DEVICE_ID, g_param_spec_string ("device-id", "DeviceID", "The new printer's DeviceID", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_PPD_NAME, g_param_spec_string ("ppd-name", "PPD name", "Name of PPD for the new printer", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_PPD_FILE_NAME, g_param_spec_string ("ppd-file-name", "PPD file name", "PPD file for the new printer", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_INFO, g_param_spec_string ("info", "Printer info", "The new printer's info", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_LOCATION, g_param_spec_string ("location", "Printer location", "The new printer's location", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_MAKE_AND_MODEL, g_param_spec_string ("make-and-model", "Printer make and model", "The new printer's make and model", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_HOST_NAME, g_param_spec_string ("host-name", "Hostname", "The new printer's hostname", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_HOST_PORT, g_param_spec_int ("host-port", "Host port", "The port of the host", 0, G_MAXINT32, 631, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_IS_NETWORK_DEVICE, g_param_spec_boolean ("is-network-device", "Network device", "Whether the new printer is a network device", FALSE, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_WINDOW_ID, g_param_spec_int ("window-id", "WindowID", "Window ID of parent window", 0, G_MAXINT32, 631, G_PARAM_READWRITE)); } static void pp_new_printer_init (PpNewPrinter *printer) { printer->priv = G_TYPE_INSTANCE_GET_PRIVATE (printer, PP_TYPE_NEW_PRINTER, PpNewPrinterPrivate); printer->priv->unlink_ppd_file = FALSE; printer->priv->cancellable = NULL; printer->priv->res = NULL; } PpNewPrinter * pp_new_printer_new () { return g_object_new (PP_TYPE_NEW_PRINTER, NULL); } static void printer_configure_async (PpNewPrinter *new_printer); static void _pp_new_printer_add_async_cb (gboolean success, PpNewPrinter *printer) { PpNewPrinterPrivate *priv = printer->priv; if (!success) { g_simple_async_result_set_error (priv->res, G_IO_ERROR, G_IO_ERROR_FAILED, "Installation of the new printer failed."); } g_simple_async_result_set_op_res_gboolean (priv->res, success); g_simple_async_result_complete_in_idle (priv->res); } static void printer_add_real_async_cb (cups_dest_t *destination, gpointer user_data) { PpNewPrinter *printer = (PpNewPrinter *) user_data; gboolean success = FALSE; if (destination) { success = TRUE; cupsFreeDests (1, destination); } if (success) { printer_configure_async (printer); } else { _pp_new_printer_add_async_cb (FALSE, printer); } } static void printer_add_real_async_dbus_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinter *printer; PpNewPrinterPrivate *priv; GVariant *output; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { const gchar *ret_error; g_variant_get (output, "(&s)", &ret_error); if (ret_error[0] != '\0') { g_warning ("%s", ret_error); } g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); } if (!error || error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { printer = (PpNewPrinter *) user_data; priv = printer->priv; get_named_dest_async (priv->name, printer_add_real_async_cb, printer); } if (error) g_error_free (error); } static void printer_add_real_async (PpNewPrinter *printer) { PpNewPrinterPrivate *priv = printer->priv; GDBusConnection *bus; GError *error = NULL; if (!priv->ppd_name && !priv->ppd_file_name) { _pp_new_printer_add_async_cb (FALSE, printer); return; } bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (!bus) { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); _pp_new_printer_add_async_cb (FALSE, printer); return; } g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, priv->ppd_name ? "PrinterAdd" : "PrinterAddWithPpdFile", g_variant_new ("(sssss)", priv->name, priv->device_uri, priv->ppd_name ? priv->ppd_name : priv->ppd_file_name, priv->info ? priv->info : "", priv->location ? priv->location : ""), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, NULL, printer_add_real_async_dbus_cb, printer); } static PPDName * get_ppd_item_from_output (GVariant *output) { GVariant *array; PPDName *ppd_item = NULL; gint j; static const char * const match_levels[] = { "exact-cmd", "exact", "close", "generic", "none"}; if (output) { g_variant_get (output, "(@a(ss))", &array); if (array) { GVariantIter *iter; GVariant *item; gchar *driver; gchar *match; for (j = 0; j < G_N_ELEMENTS (match_levels) && !ppd_item; j++) { g_variant_get (array, "a(ss)", &iter); while ((item = g_variant_iter_next_value (iter)) && !ppd_item) { g_variant_get (item, "(ss)", &driver, &match); if (g_str_equal (match, match_levels[j])) { ppd_item = g_new0 (PPDName, 1); ppd_item->ppd_name = g_strdup (driver); if (g_strcmp0 (match, "exact-cmd") == 0) ppd_item->ppd_match_level = PPD_EXACT_CMD_MATCH; else if (g_strcmp0 (match, "exact") == 0) ppd_item->ppd_match_level = PPD_EXACT_MATCH; else if (g_strcmp0 (match, "close") == 0) ppd_item->ppd_match_level = PPD_CLOSE_MATCH; else if (g_strcmp0 (match, "generic") == 0) ppd_item->ppd_match_level = PPD_GENERIC_MATCH; else if (g_strcmp0 (match, "none") == 0) ppd_item->ppd_match_level = PPD_NO_MATCH; } g_free (driver); g_free (match); g_variant_unref (item); } } g_variant_unref (array); } } return ppd_item; } static void printer_add_async_scb3 (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinter *printer = (PpNewPrinter *) user_data; PpNewPrinterPrivate *priv = printer->priv; GVariant *output; PPDName *ppd_item = NULL; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { ppd_item = get_ppd_item_from_output (output); g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); } if ((!error || error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) && ppd_item && ppd_item->ppd_name) { priv->ppd_name = g_strdup (ppd_item->ppd_name); printer_add_real_async (printer); } else { _pp_new_printer_add_async_cb (FALSE, printer); } if (error) { g_error_free (error); } if (ppd_item) { g_free (ppd_item->ppd_name); g_free (ppd_item); } } static void install_printer_drivers_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinterPrivate *priv; PpNewPrinter *printer; GVariant *output; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); } if (!error || error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { GDBusConnection *bus; GError *error = NULL; printer = (PpNewPrinter *) user_data; priv = printer->priv; /* Try whether CUPS has a driver for the new printer */ bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (bus) { g_dbus_connection_call (bus, SCP_BUS, SCP_PATH, SCP_IFACE, "GetBestDrivers", g_variant_new ("(sss)", priv->device_id, priv->make_and_model ? priv->make_and_model : "", priv->device_uri ? priv->device_uri : ""), G_VARIANT_TYPE ("(a(ss))"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, priv->cancellable, printer_add_async_scb3, printer); } else { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); _pp_new_printer_add_async_cb (FALSE, printer); } } if (error) g_error_free (error); } static void printer_add_async_scb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpNewPrinter *printer = (PpNewPrinter *) user_data; PpNewPrinterPrivate *priv = printer->priv; GDBusConnection *bus; GVariantBuilder array_builder; GVariant *output; PPDName *ppd_item = NULL; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { ppd_item = get_ppd_item_from_output (output); g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } if (!error || error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { if (ppd_item == NULL || ppd_item->ppd_match_level < PPD_EXACT_MATCH) { bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (bus) { g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("as")); g_variant_builder_add (&array_builder, "s", priv->device_id); g_dbus_connection_call (bus, PACKAGE_KIT_BUS, PACKAGE_KIT_PATH, PACKAGE_KIT_MODIFY_IFACE, "InstallPrinterDrivers", g_variant_new ("(uass)", priv->window_id, &array_builder, "hide-finished"), G_VARIANT_TYPE ("()"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, NULL, install_printer_drivers_cb, printer); } else { g_warning ("Failed to get session bus: %s", error->message); g_error_free (error); _pp_new_printer_add_async_cb (FALSE, printer); } } else if (ppd_item && ppd_item->ppd_name) { priv->ppd_name = g_strdup (ppd_item->ppd_name); printer_add_real_async (printer); } else { _pp_new_printer_add_async_cb (FALSE, printer); } } if (ppd_item) { g_free (ppd_item->ppd_name); g_free (ppd_item); } } static void printer_add_async_scb4 (const gchar *ppd_filename, gpointer user_data) { PpNewPrinter *printer = (PpNewPrinter *) user_data; PpNewPrinterPrivate *priv = printer->priv; priv->ppd_file_name = g_strdup (ppd_filename); if (priv->ppd_file_name) { priv->unlink_ppd_file = TRUE; printer_add_real_async (printer); } else { _pp_new_printer_add_async_cb (FALSE, printer); } } static GList * glist_uniq (GList *list) { GList *result = NULL; GList *iter = NULL; GList *tmp = NULL; for (iter = list; iter; iter = iter->next) { if (tmp == NULL || g_strcmp0 ((gchar *) tmp->data, (gchar *) iter->data) != 0) { tmp = iter; result = g_list_append (result, g_strdup (iter->data)); } } g_list_free_full (list, g_free); return result; } typedef struct { PpNewPrinter *new_printer; GCancellable *cancellable; gboolean set_accept_jobs_finished; gboolean set_enabled_finished; gboolean autoconfigure_finished; gboolean set_media_size_finished; gboolean install_missing_executables_finished; } PCData; static void printer_configure_async_finish (PCData *data) { PpNewPrinterPrivate *priv = data->new_printer->priv; if (data->set_accept_jobs_finished && data->set_enabled_finished && (data->autoconfigure_finished || priv->is_network_device) && data->set_media_size_finished && data->install_missing_executables_finished) { _pp_new_printer_add_async_cb (TRUE, data->new_printer); if (data->cancellable) g_object_unref (data->cancellable); g_free (data); } } static void pao_cb (gboolean success, gpointer user_data) { PCData *data = (PCData *) user_data; data->set_media_size_finished = TRUE; printer_configure_async_finish (data); } static void printer_set_accepting_jobs_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; PCData *data = (PCData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } data->set_accept_jobs_finished = TRUE; printer_configure_async_finish (data); } static void printer_set_enabled_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; PCData *data = (PCData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } data->set_enabled_finished = TRUE; printer_configure_async_finish (data); } typedef struct { GList *executables; GList *packages; guint window_id; gchar *ppd_file_name; GCancellable *cancellable; gpointer user_data; } IMEData; static void install_missing_executables_cb (IMEData *data) { PCData *pc_data = (PCData *) data->user_data; pc_data->install_missing_executables_finished = TRUE; printer_configure_async_finish (pc_data); if (data->ppd_file_name) { g_unlink (data->ppd_file_name); char_clear_pointer (data->ppd_file_name); } if (data->executables) { g_list_free_full (data->executables, g_free); data->executables = NULL; } if (data->packages) { g_list_free_full (data->packages, g_free); data->packages = NULL; } if (data->cancellable) g_clear_object (&data->cancellable); g_free (data); } static void install_package_names_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; IMEData *data = (IMEData *) user_data; GError *error = NULL; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); g_object_unref (source_object); if (output) { g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } install_missing_executables_cb (data); } static void search_files_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; IMEData *data = (IMEData *) user_data; GError *error = NULL; GList *item; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); if (output) { gboolean installed; gchar *package; g_variant_get (output, "(bs)", &installed, &package); if (!installed) data->packages = g_list_append (data->packages, g_strdup (package)); g_variant_unref (output); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } if (data->executables) { item = data->executables; g_dbus_connection_call (G_DBUS_CONNECTION (source_object), PACKAGE_KIT_BUS, PACKAGE_KIT_PATH, PACKAGE_KIT_QUERY_IFACE, "SearchFile", g_variant_new ("(ss)", (gchar *) item->data, ""), G_VARIANT_TYPE ("(bs)"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, data->cancellable, search_files_cb, data); data->executables = g_list_remove_link (data->executables, item); g_list_free_full (item, g_free); } else { GVariantBuilder array_builder; GList *pkg_iter; data->packages = g_list_sort (data->packages, (GCompareFunc) g_strcmp0); data->packages = glist_uniq (data->packages); if (data->packages) { g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("as")); for (pkg_iter = data->packages; pkg_iter; pkg_iter = pkg_iter->next) g_variant_builder_add (&array_builder, "s", (gchar *) pkg_iter->data); g_dbus_connection_call (G_DBUS_CONNECTION (source_object), PACKAGE_KIT_BUS, PACKAGE_KIT_PATH, PACKAGE_KIT_MODIFY_IFACE, "InstallPackageNames", g_variant_new ("(uass)", data->window_id, &array_builder, "hide-finished"), NULL, G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, data->cancellable, install_package_names_cb, data); g_list_free_full (data->packages, g_free); data->packages = NULL; } else { g_object_unref (source_object); install_missing_executables_cb (data); } } } static void get_missing_executables_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GVariant *output; IMEData *data = (IMEData *) user_data; GError *error = NULL; GList *executables = NULL; GList *item; output = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object), res, &error); if (output) { GVariant *array; g_variant_get (output, "(@as)", &array); if (array) { GVariantIter *iter; GVariant *item; gchar *executable; g_variant_get (array, "as", &iter); while ((item = g_variant_iter_next_value (iter))) { g_variant_get (item, "s", &executable); executables = g_list_append (executables, executable); g_variant_unref (item); } g_variant_unref (array); } g_variant_unref (output); } else if (error->domain == G_DBUS_ERROR && (error->code == G_DBUS_ERROR_SERVICE_UNKNOWN || error->code == G_DBUS_ERROR_UNKNOWN_METHOD)) { g_warning ("Install system-config-printer which provides \ DBus method \"MissingExecutables\" to find missing executables and filters."); g_error_free (error); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) g_warning ("%s", error->message); g_error_free (error); } executables = g_list_sort (executables, (GCompareFunc) g_strcmp0); executables = glist_uniq (executables); if (executables) { data->executables = executables; item = data->executables; g_dbus_connection_call (g_object_ref (source_object), PACKAGE_KIT_BUS, PACKAGE_KIT_PATH, PACKAGE_KIT_QUERY_IFACE, "SearchFile", g_variant_new ("(ss)", (gchar *) item->data, ""), G_VARIANT_TYPE ("(bs)"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, data->cancellable, search_files_cb, data); data->executables = g_list_remove_link (data->executables, item); g_list_free_full (item, g_free); } else { g_object_unref (source_object); install_missing_executables_cb (data); } if (data->ppd_file_name) { g_unlink (data->ppd_file_name); char_clear_pointer (data->ppd_file_name); } } static void printer_get_ppd_cb (const gchar *ppd_filename, gpointer user_data) { GDBusConnection *bus; IMEData *data = (IMEData *) user_data; GError *error = NULL; data->ppd_file_name = g_strdup (ppd_filename); if (data->ppd_file_name) { bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (!bus) { g_warning ("%s", error->message); g_error_free (error); } else { g_dbus_connection_call (bus, SCP_BUS, SCP_PATH, SCP_IFACE, "MissingExecutables", g_variant_new ("(s)", data->ppd_file_name), G_VARIANT_TYPE ("(as)"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT, data->cancellable, get_missing_executables_cb, data); return; } } install_missing_executables_cb (data); } static void pp_maintenance_command_execute_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpMaintenanceCommand *command = (PpMaintenanceCommand *) source_object; GError *error = NULL; PCData *data; gboolean result; result = pp_maintenance_command_execute_finish (command, res, &error); g_object_unref (source_object); if (result) { data = (PCData *) user_data; data->autoconfigure_finished = TRUE; printer_configure_async_finish (data); } else { if (error->domain != G_IO_ERROR || error->code != G_IO_ERROR_CANCELLED) { data = (PCData *) user_data; g_warning ("%s", error->message); data->autoconfigure_finished = TRUE; printer_configure_async_finish (data); } g_error_free (error); } } static void printer_configure_async (PpNewPrinter *new_printer) { PpNewPrinterPrivate *priv = new_printer->priv; GDBusConnection *bus; PCData *data; IMEData *ime_data; gchar **values; GError *error = NULL; data = g_new0 (PCData, 1); data->new_printer = new_printer; data->set_accept_jobs_finished = FALSE; data->set_enabled_finished = FALSE; data->autoconfigure_finished = FALSE; data->set_media_size_finished = FALSE; data->install_missing_executables_finished = FALSE; /* Enable printer and make it accept jobs */ if (priv->name) { bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (bus) { g_dbus_connection_call (bus, MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetAcceptJobs", g_variant_new ("(sbs)", priv->name, TRUE, ""), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, printer_set_accepting_jobs_cb, data); g_dbus_connection_call (g_object_ref (bus), MECHANISM_BUS, "/", MECHANISM_BUS, "PrinterSetEnabled", g_variant_new ("(sb)", priv->name, TRUE), G_VARIANT_TYPE ("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, printer_set_enabled_cb, data); } else { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); data->set_accept_jobs_finished = TRUE; data->set_enabled_finished = TRUE; } } else { data->set_accept_jobs_finished = TRUE; data->set_enabled_finished = TRUE; } /* Run autoconfiguration of printer */ if (!priv->is_network_device) { PpMaintenanceCommand *command; command = pp_maintenance_command_new (priv->name, "autoconfigure", /* Translators: Name of job which makes printer to autoconfigure itself */ _("Automatic configuration")); pp_maintenance_command_execute_async (command, NULL, pp_maintenance_command_execute_cb, data); } /* Set media size for printer */ values = g_new0 (gchar *, 2); values[0] = g_strdup (get_paper_size_from_locale ()); printer_add_option_async (priv->name, "media", values, TRUE, NULL, pao_cb, data); g_strfreev (values); /* Install missing executables for printer */ ime_data = g_new0 (IMEData, 1); ime_data->window_id = priv->window_id; if (data->cancellable) ime_data->cancellable = g_object_ref (data->cancellable); ime_data->user_data = data; printer_get_ppd_async (priv->name, NULL, 0, printer_get_ppd_cb, ime_data); } static void _pp_new_printer_add_async (GSimpleAsyncResult *res, GObject *object, GCancellable *cancellable) { PpNewPrinter *printer = PP_NEW_PRINTER (object); PpNewPrinterPrivate *priv = printer->priv; priv->res = g_object_ref (res); priv->cancellable = g_object_ref (cancellable); if (priv->ppd_name || priv->ppd_file_name) { /* We have everything we need */ printer_add_real_async (printer); } else if (priv->device_id) { GDBusConnection *bus; GError *error = NULL; /* Try whether CUPS has a driver for the new printer */ bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (bus) { g_dbus_connection_call (bus, SCP_BUS, SCP_PATH, SCP_IFACE, "GetBestDrivers", g_variant_new ("(sss)", priv->device_id, priv->make_and_model ? priv->make_and_model : "", priv->device_uri ? priv->device_uri : ""), G_VARIANT_TYPE ("(a(ss))"), G_DBUS_CALL_FLAGS_NONE, DBUS_TIMEOUT_LONG, cancellable, printer_add_async_scb, printer); } else { g_warning ("Failed to get system bus: %s", error->message); g_error_free (error); _pp_new_printer_add_async_cb (FALSE, printer); } } else if (priv->original_name && priv->host_name) { /* Try to get PPD from remote CUPS */ printer_get_ppd_async (priv->original_name, priv->host_name, priv->host_port, printer_add_async_scb4, printer); } else { _pp_new_printer_add_async_cb (FALSE, printer); } } void pp_new_printer_add_async (PpNewPrinter *printer, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *res; res = g_simple_async_result_new (G_OBJECT (printer), callback, user_data, pp_new_printer_add_async); g_simple_async_result_set_check_cancellable (res, cancellable); _pp_new_printer_add_async (res, G_OBJECT (printer), cancellable); g_object_unref (res); } gboolean pp_new_printer_add_finish (PpNewPrinter *printer, GAsyncResult *res, GError **error) { GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res); g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == pp_new_printer_add_async); if (g_simple_async_result_propagate_error (simple, error)) return FALSE; return g_simple_async_result_get_op_res_gboolean (simple); }
433
./cinnamon-control-center/panels/unused/printers/pp-jobs-dialog.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "config.h" #include <unistd.h> #include <stdlib.h> #include <glib.h> #include <glib/gi18n.h> #include <glib/gstdio.h> #include <gtk/gtk.h> #include <gdesktop-enums.h> #include <cups/cups.h> #include "pp-jobs-dialog.h" #include "pp-utils.h" #define EMPTY_TEXT "\xe2\x80\x94" #define CLOCK_SCHEMA "org.gnome.desktop.interface" #define CLOCK_FORMAT_KEY "clock-format" static void pp_jobs_dialog_hide (PpJobsDialog *dialog); struct _PpJobsDialog { GtkBuilder *builder; GtkWidget *parent; GtkWidget *dialog; UserResponseCallback user_callback; gpointer user_data; gchar *printer_name; cups_job_t *jobs; gint num_jobs; gint current_job_id; gint ref_count; }; enum { JOB_ID_COLUMN, JOB_TITLE_COLUMN, JOB_STATE_COLUMN, JOB_CREATION_TIME_COLUMN, JOB_N_COLUMNS }; static void update_jobs_list_cb (cups_job_t *jobs, gint num_of_jobs, gpointer user_data) { GtkTreeSelection *selection; PpJobsDialog *dialog = (PpJobsDialog *) user_data; GtkListStore *store; GtkTreeView *treeview; GtkTreeIter select_iter; GtkTreeIter iter; GSettings *settings; gboolean select_iter_set = FALSE; gint i; gint select_index = 0; treeview = (GtkTreeView*) gtk_builder_get_object (dialog->builder, "job-treeview"); if (dialog->num_jobs > 0) cupsFreeJobs (dialog->num_jobs, dialog->jobs); dialog->num_jobs = num_of_jobs; dialog->jobs = jobs; store = gtk_list_store_new (JOB_N_COLUMNS, G_TYPE_INT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); if (dialog->current_job_id >= 0) { for (i = 0; i < dialog->num_jobs; i++) { select_index = i; if (dialog->jobs[i].id >= dialog->current_job_id) break; } } for (i = 0; i < dialog->num_jobs; i++) { GDesktopClockFormat value; GDateTime *time; struct tm *ts; gchar *time_string; gchar *state = NULL; ts = localtime (&(dialog->jobs[i].creation_time)); time = g_date_time_new_local (ts->tm_year, ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec); settings = g_settings_new (CLOCK_SCHEMA); value = g_settings_get_enum (settings, CLOCK_FORMAT_KEY); if (value == G_DESKTOP_CLOCK_FORMAT_24H) time_string = g_date_time_format (time, "%k:%M"); else time_string = g_date_time_format (time, "%l:%M %p"); g_date_time_unref (time); switch (dialog->jobs[i].state) { case IPP_JOB_PENDING: /* Translators: Job's state (job is waiting to be printed) */ state = g_strdup (C_("print job", "Pending")); break; case IPP_JOB_HELD: /* Translators: Job's state (job is held for printing) */ state = g_strdup (C_("print job", "Held")); break; case IPP_JOB_PROCESSING: /* Translators: Job's state (job is currently printing) */ state = g_strdup (C_("print job", "Processing")); break; case IPP_JOB_STOPPED: /* Translators: Job's state (job has been stopped) */ state = g_strdup (C_("print job", "Stopped")); break; case IPP_JOB_CANCELED: /* Translators: Job's state (job has been canceled) */ state = g_strdup (C_("print job", "Canceled")); break; case IPP_JOB_ABORTED: /* Translators: Job's state (job has aborted due to error) */ state = g_strdup (C_("print job", "Aborted")); break; case IPP_JOB_COMPLETED: /* Translators: Job's state (job has completed successfully) */ state = g_strdup (C_("print job", "Completed")); break; } gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, JOB_ID_COLUMN, dialog->jobs[i].id, JOB_TITLE_COLUMN, dialog->jobs[i].title, JOB_STATE_COLUMN, state, JOB_CREATION_TIME_COLUMN, time_string, -1); if (i == select_index) { select_iter = iter; select_iter_set = TRUE; dialog->current_job_id = dialog->jobs[i].id; } g_free (time_string); g_free (state); } gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (store)); if (select_iter_set && (selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)))) { gtk_tree_selection_select_iter (selection, &select_iter); } g_object_unref (store); dialog->ref_count--; } static void update_jobs_list (PpJobsDialog *dialog) { if (dialog->printer_name) { dialog->ref_count++; cups_get_jobs_async (dialog->printer_name, TRUE, CUPS_WHICHJOBS_ACTIVE, update_jobs_list_cb, dialog); } } static void job_selection_changed_cb (GtkTreeSelection *selection, gpointer user_data) { PpJobsDialog *dialog = (PpJobsDialog *) user_data; GtkTreeModel *model; GtkTreeIter iter; GtkWidget *widget; gboolean release_button_sensitive = FALSE; gboolean hold_button_sensitive = FALSE; gboolean cancel_button_sensitive = FALSE; gint id = -1; gint i; if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, JOB_ID_COLUMN, &id, -1); } else { id = -1; } dialog->current_job_id = id; if (dialog->current_job_id >= 0 && dialog->jobs != NULL) { for (i = 0; i < dialog->num_jobs; i++) { if (dialog->jobs[i].id == dialog->current_job_id) { ipp_jstate_t job_state = dialog->jobs[i].state; release_button_sensitive = job_state == IPP_JOB_HELD; hold_button_sensitive = job_state == IPP_JOB_PENDING; cancel_button_sensitive = job_state < IPP_JOB_CANCELED; break; } } } widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-release-button"); gtk_widget_set_sensitive (widget, release_button_sensitive); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-hold-button"); gtk_widget_set_sensitive (widget, hold_button_sensitive); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-cancel-button"); gtk_widget_set_sensitive (widget, cancel_button_sensitive); } static void populate_jobs_list (PpJobsDialog *dialog) { GtkTreeViewColumn *column; GtkCellRenderer *renderer; GtkCellRenderer *title_renderer; GtkTreeView *treeview; treeview = (GtkTreeView*) gtk_builder_get_object (dialog->builder, "job-treeview"); renderer = gtk_cell_renderer_text_new (); title_renderer = gtk_cell_renderer_text_new (); /* Translators: Name of column showing titles of print jobs */ column = gtk_tree_view_column_new_with_attributes (_("Job Title"), title_renderer, "text", JOB_TITLE_COLUMN, NULL); g_object_set (G_OBJECT (title_renderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_tree_view_column_set_fixed_width (column, 180); gtk_tree_view_column_set_min_width (column, 180); gtk_tree_view_column_set_max_width (column, 180); gtk_tree_view_append_column (treeview, column); /* Translators: Name of column showing statuses of print jobs */ column = gtk_tree_view_column_new_with_attributes (_("Job State"), renderer, "text", JOB_STATE_COLUMN, NULL); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_view_append_column (treeview, column); /* Translators: Name of column showing times of creation of print jobs */ column = gtk_tree_view_column_new_with_attributes (_("Time"), renderer, "text", JOB_CREATION_TIME_COLUMN, NULL); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_view_append_column (treeview, column); g_signal_connect (gtk_tree_view_get_selection (treeview), "changed", G_CALLBACK (job_selection_changed_cb), dialog); update_jobs_list (dialog); } static void job_process_cb_cb (gpointer user_data) { } static void job_process_cb (GtkButton *button, gpointer user_data) { PpJobsDialog *dialog = (PpJobsDialog *) user_data; GtkWidget *widget; if (dialog->current_job_id >= 0) { if ((GtkButton*) gtk_builder_get_object (dialog->builder, "job-cancel-button") == button) { job_cancel_purge_async (dialog->current_job_id, FALSE, NULL, job_process_cb_cb, dialog); } else if ((GtkButton*) gtk_builder_get_object (dialog->builder, "job-hold-button") == button) { job_set_hold_until_async (dialog->current_job_id, "indefinite", NULL, job_process_cb_cb, dialog); } else { job_set_hold_until_async (dialog->current_job_id, "no-hold", NULL, job_process_cb_cb, dialog); } } widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-release-button"); gtk_widget_set_sensitive (widget, FALSE); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-hold-button"); gtk_widget_set_sensitive (widget, FALSE); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-cancel-button"); gtk_widget_set_sensitive (widget, FALSE); } static void jobs_dialog_response_cb (GtkDialog *dialog, gint response_id, gpointer user_data) { PpJobsDialog *jobs_dialog = (PpJobsDialog*) user_data; pp_jobs_dialog_hide (jobs_dialog); jobs_dialog->user_callback (GTK_DIALOG (jobs_dialog->dialog), response_id, jobs_dialog->user_data); } static void update_alignment_padding (GtkWidget *widget, GtkAllocation *allocation, gpointer user_data) { GtkAllocation allocation2; PpJobsDialog *dialog = (PpJobsDialog*) user_data; GtkWidget *action_area; gint offset_left, offset_right; guint padding_left, padding_right, padding_top, padding_bottom; action_area = (GtkWidget*) gtk_builder_get_object (dialog->builder, "dialog-action-area1"); gtk_widget_get_allocation (action_area, &allocation2); offset_left = allocation2.x - allocation->x; offset_right = (allocation->x + allocation->width) - (allocation2.x + allocation2.width); gtk_alignment_get_padding (GTK_ALIGNMENT (widget), &padding_top, &padding_bottom, &padding_left, &padding_right); if (allocation->x >= 0 && allocation2.x >= 0) { if (offset_left > 0 && offset_left != padding_left) gtk_alignment_set_padding (GTK_ALIGNMENT (widget), padding_top, padding_bottom, offset_left, padding_right); gtk_alignment_get_padding (GTK_ALIGNMENT (widget), &padding_top, &padding_bottom, &padding_left, &padding_right); if (offset_right > 0 && offset_right != padding_right) gtk_alignment_set_padding (GTK_ALIGNMENT (widget), padding_top, padding_bottom, padding_left, offset_right); } } PpJobsDialog * pp_jobs_dialog_new (GtkWindow *parent, UserResponseCallback user_callback, gpointer user_data, gchar *printer_name) { PpJobsDialog *dialog; GtkWidget *widget; GError *error = NULL; gchar *objects[] = { "jobs-dialog", NULL }; guint builder_result; gchar *title; dialog = g_new0 (PpJobsDialog, 1); dialog->builder = gtk_builder_new (); dialog->parent = GTK_WIDGET (parent); builder_result = gtk_builder_add_objects_from_file (dialog->builder, DATADIR"/jobs-dialog.ui", objects, &error); if (builder_result == 0) { g_warning ("Could not load ui: %s", error->message); g_error_free (error); return NULL; } dialog->dialog = (GtkWidget *) gtk_builder_get_object (dialog->builder, "jobs-dialog"); dialog->user_callback = user_callback; dialog->user_data = user_data; dialog->printer_name = g_strdup (printer_name); dialog->current_job_id = -1; dialog->ref_count = 0; /* connect signals */ g_signal_connect (dialog->dialog, "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL); g_signal_connect (dialog->dialog, "response", G_CALLBACK (jobs_dialog_response_cb), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "content-alignment"); g_signal_connect (widget, "size-allocate", G_CALLBACK (update_alignment_padding), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-cancel-button"); g_signal_connect (widget, "clicked", G_CALLBACK (job_process_cb), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-hold-button"); g_signal_connect (widget, "clicked", G_CALLBACK (job_process_cb), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "job-release-button"); g_signal_connect (widget, "clicked", G_CALLBACK (job_process_cb), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "jobs-title"); title = g_strdup_printf (_("%s Active Jobs"), printer_name); gtk_label_set_label (GTK_LABEL (widget), title); g_free (title); populate_jobs_list (dialog); gtk_window_set_transient_for (GTK_WINDOW (dialog->dialog), GTK_WINDOW (parent)); gtk_window_present (GTK_WINDOW (dialog->dialog)); gtk_widget_show_all (GTK_WIDGET (dialog->dialog)); return dialog; } void pp_jobs_dialog_update (PpJobsDialog *dialog) { update_jobs_list (dialog); } static gboolean pp_jobs_dialog_free_idle (gpointer user_data) { PpJobsDialog *dialog = (PpJobsDialog*) user_data; if (dialog->ref_count == 0) { gtk_widget_destroy (GTK_WIDGET (dialog->dialog)); dialog->dialog = NULL; g_object_unref (dialog->builder); dialog->builder = NULL; if (dialog->num_jobs > 0) cupsFreeJobs (dialog->num_jobs, dialog->jobs); g_free (dialog->printer_name); g_free (dialog); return FALSE; } else { return TRUE; } } void pp_jobs_dialog_free (PpJobsDialog *dialog) { g_idle_add (pp_jobs_dialog_free_idle, dialog); } static void pp_jobs_dialog_hide (PpJobsDialog *dialog) { gtk_widget_hide (GTK_WIDGET (dialog->dialog)); }
434
./cinnamon-control-center/panels/unused/printers/pp-options-dialog.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "config.h" #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <glib.h> #include <glib/gi18n.h> #include <glib/gstdio.h> #include <gtk/gtk.h> #include <cups/cups.h> #include <cups/ppd.h> #include "pp-options-dialog.h" #include "pp-ppd-option-widget.h" #include "pp-ipp-option-widget.h" #include "pp-utils.h" struct _PpOptionsDialog { GtkBuilder *builder; GtkWidget *parent; GtkWidget *dialog; UserResponseCallback user_callback; gpointer user_data; gchar *printer_name; gchar *ppd_filename; gboolean ppd_filename_set; cups_dest_t *destination; gboolean destination_set; GHashTable *ipp_attributes; gboolean ipp_attributes_set; gboolean populating_dialog; GtkResponseType response; gboolean sensitive; }; static void pp_options_dialog_hide (PpOptionsDialog *dialog); enum { CATEGORY_IDS_COLUMN = 0, CATEGORY_NAMES_COLUMN }; /* These lists come from Gtk+ */ static const struct { const char *keyword; const char *translation; } ppd_option_translations[] = { { "Duplex", N_("Two Sided") }, { "MediaType", N_("Paper Type") }, { "InputSlot", N_("Paper Source") }, { "OutputBin", N_("Output Tray") }, { "Resolution", N_("Resolution") }, { "PreFilter", N_("GhostScript pre-filtering") }, }; /* keep sorted when changing */ static const char *page_setup_option_whitelist[] = { "InputSlot", "MediaType", "OutputBin", "PageSize", }; /* keep sorted when changing */ static const char *color_option_whitelist[] = { "BRColorEnhancement", "BRColorMatching", "BRColorMatching", "BRColorMode", "BRGammaValue", "BRImprovedGray", "BlackSubstitution", "ColorModel", "HPCMYKInks", "HPCSGraphics", "HPCSImages", "HPCSText", "HPColorSmart", "RPSBlackMode", "RPSBlackOverPrint", "Rcmyksimulation", }; /* keep sorted when changing */ static const char *color_group_whitelist[] = { "Color", "Color1", "Color2", "ColorBalance", "ColorPage", "ColorSettings1", "ColorSettings2", "ColorSettings3", "ColorSettings4", "EPColorSettings", "FPColorWise1", "FPColorWise2", "FPColorWise3", "FPColorWise4", "FPColorWise5", "HPCMYKInksPanel", "HPColorOptions", "HPColorOptionsPanel", "HPColorQualityOptionsPanel", "ManualColor", }; /* keep sorted when changing */ static const char *image_quality_option_whitelist[] = { "BRDocument", "BRHalfTonePattern", "BRNormalPrt", "BRPrintQuality", "BitsPerPixel", "Darkness", "Dithering", "EconoMode", "Economode", "HPEconoMode", "HPEdgeControl", "HPGraphicsHalftone", "HPHalftone", "HPImagingOptions", "HPLJDensity", "HPPhotoHalftone", "HPPrintQualityOptions", "HPResolutionOptions", "OutputMode", "REt", "RPSBitsPerPixel", "RPSDitherType", "Resolution", "ScreenLock", "Smoothing", "TonerSaveMode", "UCRGCRForImage", }; /* keep sorted when changing */ static const char *image_quality_group_whitelist[] = { "EPQualitySettings", "FPImageQuality1", "FPImageQuality2", "FPImageQuality3", "ImageQualityPage", "Quality", }; /* keep sorted when changing */ static const char * finishing_option_whitelist[] = { "BindColor", "BindEdge", "BindType", "BindWhen", "Booklet", "FoldType", "FoldWhen", "HPStaplerOptions", "Jog", "Slipsheet", "Sorter", "StapleLocation", "StapleOrientation", "StapleWhen", "StapleX", "StapleY", }; /* keep sorted when changing */ static const char *job_group_whitelist[] = { "JobHandling", "JobLog", }; /* keep sorted when changing */ static const char *finishing_group_whitelist[] = { "Booklet", "BookletCover", "BookletModeOptions", "FPFinishing1", "FPFinishing2", "FPFinishing3", "FPFinishing4", "Finishing", "FinishingOptions", "FinishingPage", "HPBookletPanel", "HPFinishing", "HPFinishingOptions", "HPFinishingPanel", }; /* keep sorted when changing */ static const char *installable_options_group_whitelist[] = { "InstallableOptions", }; /* keep sorted when changing */ static const char *page_setup_group_whitelist[] = { "HPMarginAndLayout", "OutputControl", "PaperHandling", "Paper", "Source", }; /* keep sorted when changing */ static const char *ppd_option_blacklist[] = { "Collate", "Copies", "Duplex", "HPManualDuplexOrientation", "HPManualDuplexSwitch", "OutputOrder", "PageRegion" }; static int strptr_cmp (const void *a, const void *b) { char **aa = (char **)a; char **bb = (char **)b; return strcmp (*aa, *bb); } static gboolean string_in_table (gchar *str, const gchar *table[], gint table_len) { return bsearch (&str, table, table_len, sizeof (char *), (void *)strptr_cmp) != NULL; } #define STRING_IN_TABLE(_str, _table) (string_in_table (_str, _table, G_N_ELEMENTS (_table))) static gchar * ppd_option_name_translate (ppd_option_t *option) { gint i; for (i = 0; i < G_N_ELEMENTS (ppd_option_translations); i++) { if (g_strcmp0 (ppd_option_translations[i].keyword, option->keyword) == 0) return g_strdup (_(ppd_option_translations[i].translation)); } return g_strdup (option->text); } static gint grid_get_height (GtkWidget *grid) { GList *children; GList *child; gint height = 0; gint top_attach = 0; gint max = 0; children = gtk_container_get_children (GTK_CONTAINER (grid)); for (child = children; child; child = g_list_next (child)) { gtk_container_child_get (GTK_CONTAINER (grid), child->data, "top-attach", &top_attach, "height", &height, NULL); if (height + top_attach > max) max = height + top_attach; } g_list_free (children); return max; } static gboolean grid_is_empty (GtkWidget *grid) { GList *children; children = gtk_container_get_children (GTK_CONTAINER (grid)); if (children) { g_list_free (children); return FALSE; } else { return TRUE; } } static GtkWidget * ipp_option_add (IPPAttribute *attr_supported, IPPAttribute *attr_default, const gchar *option_name, const gchar *option_display_name, const gchar *printer_name, GtkWidget *grid, gboolean sensitive) { GtkStyleContext *context; GtkWidget *widget; GtkWidget *label; gint position; widget = (GtkWidget *) pp_ipp_option_widget_new (attr_supported, attr_default, option_name, printer_name); if (widget) { gtk_widget_set_sensitive (widget, sensitive); position = grid_get_height (grid); label = gtk_label_new (option_display_name); context = gtk_widget_get_style_context (label); gtk_style_context_add_class (context, "dim-label"); gtk_misc_set_alignment (GTK_MISC (label), 1.0, 0.5); gtk_widget_set_margin_left (label, 10); gtk_grid_attach (GTK_GRID (grid), label, 0, position, 1, 1); gtk_widget_set_margin_left (widget, 20); gtk_grid_attach (GTK_GRID (grid), widget, 1, position, 1, 1); } return widget; } static GtkWidget * ppd_option_add (ppd_option_t option, const gchar *printer_name, GtkWidget *grid, gboolean sensitive) { GtkStyleContext *context; GtkWidget *widget; GtkWidget *label; gint position; widget = (GtkWidget *) pp_ppd_option_widget_new (&option, printer_name); if (widget) { gtk_widget_set_sensitive (widget, sensitive); position = grid_get_height (grid); label = gtk_label_new (ppd_option_name_translate (&option)); context = gtk_widget_get_style_context (label); gtk_style_context_add_class (context, "dim-label"); gtk_misc_set_alignment (GTK_MISC (label), 1.0, 0.5); gtk_widget_set_margin_left (label, 10); gtk_grid_attach (GTK_GRID (grid), label, 0, position, 1, 1); gtk_widget_set_margin_left (widget, 20); gtk_grid_attach (GTK_GRID (grid), widget, 1, position, 1, 1); } return widget; } static GtkWidget * tab_grid_new () { GtkWidget *grid; grid = gtk_grid_new (); gtk_container_set_border_width (GTK_CONTAINER (grid), 20); gtk_grid_set_row_spacing (GTK_GRID (grid), 15); return grid; } static void tab_add (const gchar *tab_name, GtkWidget *options_notebook, GtkTreeView *treeview, GtkWidget *grid) { GtkListStore *store; GtkTreeIter iter; GtkWidget *scrolled_window; gboolean unref_store = FALSE; gint id; if (!grid_is_empty (grid)) { scrolled_window = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrolled_window), grid); id = gtk_notebook_append_page (GTK_NOTEBOOK (options_notebook), scrolled_window, NULL); if (id >= 0) { store = GTK_LIST_STORE (gtk_tree_view_get_model (treeview)); if (!store) { store = gtk_list_store_new (2, G_TYPE_INT, G_TYPE_STRING); unref_store = TRUE; } gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, CATEGORY_IDS_COLUMN, id, CATEGORY_NAMES_COLUMN, tab_name, -1); if (unref_store) { gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (store)); g_object_unref (store); } } } else { g_object_ref_sink (grid); g_object_unref (grid); } } static void category_selection_changed_cb (GtkTreeSelection *selection, gpointer user_data) { PpOptionsDialog *dialog = (PpOptionsDialog *) user_data; GtkTreeModel *model; GtkTreeIter iter; GtkWidget *options_notebook; gint id = -1; if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, CATEGORY_IDS_COLUMN, &id, -1); } if (id >= 0) { options_notebook = (GtkWidget*) gtk_builder_get_object (dialog->builder, "options-notebook"); gtk_notebook_set_current_page (GTK_NOTEBOOK (options_notebook), id); } } static void populate_options_real (PpOptionsDialog *dialog) { GtkTreeSelection *selection; GtkTreeModel *model; GtkTreeView *treeview; GtkTreeIter iter; ppd_file_t *ppd_file; GtkWidget *notebook; GtkWidget *grid; GtkWidget *general_tab_grid = tab_grid_new (); GtkWidget *page_setup_tab_grid = tab_grid_new (); GtkWidget *installable_options_tab_grid = tab_grid_new (); GtkWidget *job_tab_grid = tab_grid_new (); GtkWidget *image_quality_tab_grid = tab_grid_new (); GtkWidget *color_tab_grid = tab_grid_new (); GtkWidget *finishing_tab_grid = tab_grid_new (); GtkWidget *advanced_tab_grid = tab_grid_new (); GtkWidget *widget; gint i, j; widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "options-spinner"); gtk_widget_hide (widget); gtk_spinner_stop (GTK_SPINNER (widget)); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "progress-label"); gtk_widget_hide (widget); treeview = (GtkTreeView *) gtk_builder_get_object (dialog->builder, "options-categories-treeview"); notebook = (GtkWidget *) gtk_builder_get_object (dialog->builder, "options-notebook"); if (dialog->ipp_attributes) { /* Add number-up option to Page Setup tab */ ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes, "number-up-supported"), g_hash_table_lookup (dialog->ipp_attributes, "number-up-default"), "number-up", /* Translators: This option sets number of pages printed on one sheet */ _("Pages per side"), dialog->printer_name, page_setup_tab_grid, dialog->sensitive); /* Add sides option to Page Setup tab */ ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes, "sides-supported"), g_hash_table_lookup (dialog->ipp_attributes, "sides-default"), "sides", /* Translators: This option sets whether to print on both sides of paper */ _("Two-sided"), dialog->printer_name, page_setup_tab_grid, dialog->sensitive); /* Add orientation-requested option to Page Setup tab */ ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes, "orientation-requested-supported"), g_hash_table_lookup (dialog->ipp_attributes, "orientation-requested-default"), "orientation-requested", /* Translators: This option sets orientation of print (portrait, landscape...) */ _("Orientation"), dialog->printer_name, page_setup_tab_grid, dialog->sensitive); } if (dialog->destination && dialog->ppd_filename) { ppd_file = ppdOpenFile (dialog->ppd_filename); ppdLocalize (ppd_file); if (ppd_file) { ppdMarkDefaults (ppd_file); cupsMarkOptions (ppd_file, dialog->destination->num_options, dialog->destination->options); for (i = 0; i < ppd_file->num_groups; i++) { for (j = 0; j < ppd_file->groups[i].num_options; j++) { grid = NULL; if (STRING_IN_TABLE (ppd_file->groups[i].name, color_group_whitelist)) grid = color_tab_grid; else if (STRING_IN_TABLE (ppd_file->groups[i].name, image_quality_group_whitelist)) grid = image_quality_tab_grid; else if (STRING_IN_TABLE (ppd_file->groups[i].name, job_group_whitelist)) grid = job_tab_grid; else if (STRING_IN_TABLE (ppd_file->groups[i].name, finishing_group_whitelist)) grid = finishing_tab_grid; else if (STRING_IN_TABLE (ppd_file->groups[i].name, installable_options_group_whitelist)) grid = installable_options_tab_grid; else if (STRING_IN_TABLE (ppd_file->groups[i].name, page_setup_group_whitelist)) grid = page_setup_tab_grid; if (!STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword, ppd_option_blacklist)) { if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword, color_option_whitelist)) grid = color_tab_grid; else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword, image_quality_option_whitelist)) grid = image_quality_tab_grid; else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword, finishing_option_whitelist)) grid = finishing_tab_grid; else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword, page_setup_option_whitelist)) grid = page_setup_tab_grid; if (!grid) grid = advanced_tab_grid; ppd_option_add (ppd_file->groups[i].options[j], dialog->printer_name, grid, dialog->sensitive); } } } ppdClose (ppd_file); } } dialog->ppd_filename_set = FALSE; if (dialog->ppd_filename) { g_unlink (dialog->ppd_filename); g_free (dialog->ppd_filename); dialog->ppd_filename = NULL; } dialog->destination_set = FALSE; if (dialog->destination) { cupsFreeDests (1, dialog->destination); dialog->destination = NULL; } dialog->ipp_attributes_set = FALSE; if (dialog->ipp_attributes) { g_hash_table_unref (dialog->ipp_attributes); dialog->ipp_attributes = NULL; } /* Translators: "General" tab contains general printer options */ tab_add (C_("Printer Option Group", "General"), notebook, treeview, general_tab_grid); /* Translators: "Page Setup" tab contains settings related to pages (page size, paper source, etc.) */ tab_add (C_("Printer Option Group", "Page Setup"), notebook, treeview, page_setup_tab_grid); /* Translators: "Installable Options" tab contains settings of presence of installed options (amount of RAM, duplex unit, etc.) */ tab_add (C_("Printer Option Group", "Installable Options"), notebook, treeview, installable_options_tab_grid); /* Translators: "Job" tab contains settings for jobs */ tab_add (C_("Printer Option Group", "Job"), notebook, treeview, job_tab_grid); /* Translators: "Image Quality" tab contains settings for quality of output print (e.g. resolution) */ tab_add (C_("Printer Option Group", "Image Quality"), notebook, treeview, image_quality_tab_grid); /* Translators: "Color" tab contains color settings (e.g. color printing) */ tab_add (C_("Printer Option Group", "Color"), notebook, treeview, color_tab_grid); /* Translators: "Finishing" tab contains finishing settings (e.g. booklet printing) */ tab_add (C_("Printer Option Group", "Finishing"), notebook, treeview, finishing_tab_grid); /* Translators: "Advanced" tab contains all others settings */ tab_add (C_("Printer Option Group", "Advanced"), notebook, treeview, advanced_tab_grid); gtk_widget_show_all (GTK_WIDGET (notebook)); /* Select the first option group */ if ((selection = gtk_tree_view_get_selection (treeview)) != NULL) { g_signal_connect (selection, "changed", G_CALLBACK (category_selection_changed_cb), dialog); if ((model = gtk_tree_view_get_model (treeview)) != NULL && gtk_tree_model_get_iter_first (model, &iter)) gtk_tree_selection_select_iter (selection, &iter); } dialog->populating_dialog = FALSE; if (dialog->response != GTK_RESPONSE_NONE) { dialog->user_callback (GTK_DIALOG (dialog->dialog), dialog->response, dialog->user_data); } } static void printer_get_ppd_cb (const gchar *ppd_filename, gpointer user_data) { PpOptionsDialog *dialog = (PpOptionsDialog *) user_data; if (dialog->ppd_filename) { g_unlink (dialog->ppd_filename); g_free (dialog->ppd_filename); } dialog->ppd_filename = g_strdup (ppd_filename); dialog->ppd_filename_set = TRUE; if (dialog->destination_set && dialog->ipp_attributes_set) { populate_options_real (dialog); } } static void get_named_dest_cb (cups_dest_t *dest, gpointer user_data) { PpOptionsDialog *dialog = (PpOptionsDialog *) user_data; if (dialog->destination) cupsFreeDests (1, dialog->destination); dialog->destination = dest; dialog->destination_set = TRUE; if (dialog->ppd_filename_set && dialog->ipp_attributes_set) { populate_options_real (dialog); } } static void get_ipp_attributes_cb (GHashTable *table, gpointer user_data) { PpOptionsDialog *dialog = (PpOptionsDialog *) user_data; if (dialog->ipp_attributes) g_hash_table_unref (dialog->ipp_attributes); dialog->ipp_attributes = table; dialog->ipp_attributes_set = TRUE; if (dialog->ppd_filename_set && dialog->destination_set) { populate_options_real (dialog); } } static void populate_options (PpOptionsDialog *dialog) { GtkTreeViewColumn *column; GtkCellRenderer *renderer; GtkTreeView *treeview; GtkWidget *widget; /* * Options which we need to obtain through an IPP request * to be able to fill the options dialog. * *-supported - possible values of the option * *-default - actual value of the option */ const gchar *attributes[] = { "number-up-supported", "number-up-default", "sides-supported", "sides-default", "orientation-requested-supported", "orientation-requested-default", NULL}; treeview = (GtkTreeView *) gtk_builder_get_object (dialog->builder, "options-categories-treeview"); renderer = gtk_cell_renderer_text_new (); column = gtk_tree_view_column_new_with_attributes ("Categories", renderer, "text", CATEGORY_NAMES_COLUMN, NULL); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_view_append_column (treeview, column); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "options-spinner"); gtk_widget_show (widget); gtk_spinner_start (GTK_SPINNER (widget)); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "progress-label"); gtk_widget_show (widget); printer_get_ppd_async (dialog->printer_name, NULL, 0, printer_get_ppd_cb, dialog); get_named_dest_async (dialog->printer_name, get_named_dest_cb, dialog); get_ipp_attributes_async (dialog->printer_name, (gchar **) attributes, get_ipp_attributes_cb, dialog); } /* * Modify padding of the content area of the GtkDialog * so it is aligned with the action area. */ static void update_alignment_padding (GtkWidget *widget, GtkAllocation *allocation, gpointer user_data) { PpOptionsDialog *dialog = (PpOptionsDialog*) user_data; GtkAllocation allocation1, allocation2; GtkWidget *action_area; GtkWidget *content_area; gint offset_left, offset_right; guint padding_left, padding_right, padding_top, padding_bottom; action_area = (GtkWidget*) gtk_builder_get_object (dialog->builder, "dialog-action-area1"); gtk_widget_get_allocation (action_area, &allocation2); content_area = (GtkWidget*) gtk_builder_get_object (dialog->builder, "content-alignment"); gtk_widget_get_allocation (content_area, &allocation1); offset_left = allocation2.x - allocation1.x; offset_right = (allocation1.x + allocation1.width) - (allocation2.x + allocation2.width); gtk_alignment_get_padding (GTK_ALIGNMENT (content_area), &padding_top, &padding_bottom, &padding_left, &padding_right); if (allocation1.x >= 0 && allocation2.x >= 0) { if (offset_left > 0 && offset_left != padding_left) gtk_alignment_set_padding (GTK_ALIGNMENT (content_area), padding_top, padding_bottom, offset_left, padding_right); gtk_alignment_get_padding (GTK_ALIGNMENT (content_area), &padding_top, &padding_bottom, &padding_left, &padding_right); if (offset_right > 0 && offset_right != padding_right) gtk_alignment_set_padding (GTK_ALIGNMENT (content_area), padding_top, padding_bottom, padding_left, offset_right); } } static void options_dialog_response_cb (GtkDialog *_dialog, gint response_id, gpointer user_data) { PpOptionsDialog *dialog = (PpOptionsDialog*) user_data; pp_options_dialog_hide (dialog); dialog->response = response_id; if (!dialog->populating_dialog) dialog->user_callback (GTK_DIALOG (dialog->dialog), response_id, dialog->user_data); } PpOptionsDialog * pp_options_dialog_new (GtkWindow *parent, UserResponseCallback user_callback, gpointer user_data, gchar *printer_name, gboolean sensitive) { PpOptionsDialog *dialog; GtkWidget *widget; GError *error = NULL; gchar *objects[] = { "options-dialog", NULL }; guint builder_result; gchar *title; dialog = g_new0 (PpOptionsDialog, 1); dialog->builder = gtk_builder_new (); dialog->parent = GTK_WIDGET (parent); builder_result = gtk_builder_add_objects_from_file (dialog->builder, DATADIR"/options-dialog.ui", objects, &error); if (builder_result == 0) { g_warning ("Could not load ui: %s", error->message); g_error_free (error); return NULL; } dialog->dialog = (GtkWidget *) gtk_builder_get_object (dialog->builder, "options-dialog"); gtk_window_set_transient_for (GTK_WINDOW (dialog->dialog), GTK_WINDOW (parent)); dialog->user_callback = user_callback; dialog->user_data = user_data; dialog->printer_name = g_strdup (printer_name); dialog->ppd_filename = NULL; dialog->ppd_filename_set = FALSE; dialog->destination = NULL; dialog->destination_set = FALSE; dialog->ipp_attributes = NULL; dialog->ipp_attributes_set = FALSE; dialog->response = GTK_RESPONSE_NONE; dialog->sensitive = sensitive; /* connect signals */ g_signal_connect (dialog->dialog, "response", G_CALLBACK (options_dialog_response_cb), dialog); g_signal_connect (dialog->dialog, "size-allocate", G_CALLBACK (update_alignment_padding), dialog); widget = (GtkWidget*) gtk_builder_get_object (dialog->builder, "options-title"); /* Translators: Options of given printer (e.g. "MyPrinter Options") */ title = g_strdup_printf (_("%s Options"), printer_name); gtk_label_set_label (GTK_LABEL (widget), title); g_free (title); gtk_widget_show_all (GTK_WIDGET (dialog->dialog)); dialog->populating_dialog = TRUE; populate_options (dialog); return dialog; } void pp_options_dialog_free (PpOptionsDialog *dialog) { gtk_widget_destroy (GTK_WIDGET (dialog->dialog)); dialog->dialog = NULL; g_object_unref (dialog->builder); dialog->builder = NULL; g_free (dialog->printer_name); dialog->printer_name = NULL; if (dialog->ppd_filename) { g_unlink (dialog->ppd_filename); g_free (dialog->ppd_filename); dialog->ppd_filename = NULL; } if (dialog->destination) { cupsFreeDests (1, dialog->destination); dialog->destination = NULL; } if (dialog->ipp_attributes) { g_hash_table_unref (dialog->ipp_attributes); dialog->ipp_attributes = NULL; } g_free (dialog); } static void pp_options_dialog_hide (PpOptionsDialog *dialog) { gtk_widget_hide (GTK_WIDGET (dialog->dialog)); }
435
./cinnamon-control-center/panels/unused/printers/pp-maintenance-command.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include <glib/gstdio.h> #include "pp-maintenance-command.h" #include "pp-utils.h" #if (CUPS_VERSION_MAJOR > 1) || (CUPS_VERSION_MINOR > 5) #define HAVE_CUPS_1_6 1 #endif #ifndef HAVE_CUPS_1_6 #define ippGetCount(attr) attr->num_values #define ippGetValueTag(attr) attr->value_tag #define ippGetStatusCode(ipp) ipp->request.status.status_code #define ippGetString(attr, element, language) attr->values[element].string.text #endif struct _PpMaintenanceCommandPrivate { gchar *printer_name; gchar *command; gchar *title; }; G_DEFINE_TYPE (PpMaintenanceCommand, pp_maintenance_command, G_TYPE_OBJECT); enum { PROP_0 = 0, PROP_PRINTER_NAME, PROP_COMMAND, PROP_TITLE }; static void char_clear_pointer (gchar *pointer) { if (pointer) { g_free (pointer); pointer = NULL; } } static void pp_maintenance_command_finalize (GObject *object) { PpMaintenanceCommandPrivate *priv; priv = PP_MAINTENANCE_COMMAND (object)->priv; char_clear_pointer (priv->printer_name); char_clear_pointer (priv->command); char_clear_pointer (priv->title); G_OBJECT_CLASS (pp_maintenance_command_parent_class)->finalize (object); } static void pp_maintenance_command_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *param_spec) { PpMaintenanceCommand *self; self = PP_MAINTENANCE_COMMAND (object); switch (prop_id) { case PROP_PRINTER_NAME: g_value_set_string (value, self->priv->printer_name); break; case PROP_COMMAND: g_value_set_string (value, self->priv->command); break; case PROP_TITLE: g_value_set_string (value, self->priv->title); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, param_spec); break; } } static void pp_maintenance_command_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *param_spec) { PpMaintenanceCommand *self = PP_MAINTENANCE_COMMAND (object); switch (prop_id) { case PROP_PRINTER_NAME: g_free (self->priv->printer_name); self->priv->printer_name = g_value_dup_string (value); break; case PROP_COMMAND: g_free (self->priv->command); self->priv->command = g_value_dup_string (value); break; case PROP_TITLE: g_free (self->priv->title); self->priv->title = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, param_spec); break; } } static void pp_maintenance_command_class_init (PpMaintenanceCommandClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (PpMaintenanceCommandPrivate)); gobject_class->set_property = pp_maintenance_command_set_property; gobject_class->get_property = pp_maintenance_command_get_property; gobject_class->finalize = pp_maintenance_command_finalize; g_object_class_install_property (gobject_class, PROP_PRINTER_NAME, g_param_spec_string ("printer-name", "Printer name", "Name of the printer", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_COMMAND, g_param_spec_string ("command", "Maintenance command", "Command to execute", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_TITLE, g_param_spec_string ("title", "Command title", "Title of the job by which the command will be executed", NULL, G_PARAM_READWRITE)); } static void pp_maintenance_command_init (PpMaintenanceCommand *command) { command->priv = G_TYPE_INSTANCE_GET_PRIVATE (command, PP_TYPE_MAINTENANCE_COMMAND, PpMaintenanceCommandPrivate); } PpMaintenanceCommand * pp_maintenance_command_new (const gchar *printer_name, const gchar *command, const gchar *title) { return g_object_new (PP_TYPE_MAINTENANCE_COMMAND, "printer-name", printer_name, "command", command, "title", title, NULL); } static void _pp_maintenance_command_execute_thread (GSimpleAsyncResult *res, GObject *object, GCancellable *cancellable) { PpMaintenanceCommand *command = (PpMaintenanceCommand *) object; PpMaintenanceCommandPrivate *priv = command->priv; static const char *attrs[] = {"printer-commands"}; ipp_attribute_t *attr = NULL; gboolean success = FALSE; GError *error = NULL; ipp_t *request; ipp_t *response = NULL; gchar *printer_uri; gchar *printer_commands = NULL; gchar *printer_commands_lowercase = NULL; gchar *command_lowercase; gchar *file_name = NULL; int fd = -1; printer_uri = g_strdup_printf ("ipp://localhost/printers/%s", priv->printer_name); request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", 1, NULL, attrs); response = cupsDoRequest (CUPS_HTTP_DEFAULT, request, "/"); if (response) { if (ippGetStatusCode (response) <= IPP_OK_CONFLICT) { attr = ippFindAttribute (response, "printer-commands", IPP_TAG_ZERO); if (attr && ippGetCount (attr) > 0 && ippGetValueTag (attr) != IPP_TAG_NOVALUE) { if (ippGetValueTag (attr) == IPP_TAG_KEYWORD) { printer_commands = g_strdup (ippGetString (attr, 0, NULL)); } } else { success = TRUE; } } ippDelete (response); } if (printer_commands) { command_lowercase = g_ascii_strdown (priv->command, -1); printer_commands_lowercase = g_ascii_strdown (printer_commands, -1); if (g_strrstr (printer_commands_lowercase, command_lowercase)) { request = ippNewRequest (IPP_PRINT_JOB); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL, priv->title); ippAddString (request, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format", NULL, "application/vnd.cups-command"); fd = g_file_open_tmp ("ccXXXXXX", &file_name, &error); if (fd != -1) { FILE *file; file = fdopen (fd, "w"); fprintf (file, "#CUPS-COMMAND\n"); fprintf (file, "%s\n", priv->command); fclose (file); response = cupsDoFileRequest (CUPS_HTTP_DEFAULT, request, "/", file_name); g_unlink (file_name); if (response) { if (ippGetStatusCode (response) <= IPP_OK_CONFLICT) { success = TRUE; } ippDelete (response); } } g_free (file_name); } else { success = TRUE; } g_free (command_lowercase); g_free (printer_commands_lowercase); g_free (printer_commands); } g_free (printer_uri); if (!success) { g_simple_async_result_set_error (res, G_IO_ERROR, G_IO_ERROR_FAILED, "Execution of maintenance command failed."); } g_simple_async_result_set_op_res_gboolean (res, success); } void pp_maintenance_command_execute_async (PpMaintenanceCommand *command, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *res; res = g_simple_async_result_new (G_OBJECT (command), callback, user_data, pp_maintenance_command_execute_async); g_simple_async_result_set_check_cancellable (res, cancellable); g_simple_async_result_run_in_thread (res, _pp_maintenance_command_execute_thread, 0, cancellable); g_object_unref (res); } gboolean pp_maintenance_command_execute_finish (PpMaintenanceCommand *command, GAsyncResult *res, GError **error) { GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res); g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == pp_maintenance_command_execute_async); if (g_simple_async_result_propagate_error (simple, error)) { return FALSE; } return g_simple_async_result_get_op_res_gboolean (simple); }
436
./cinnamon-control-center/panels/unused/printers/cc-printers-panel.c
/* * Copyright (C) 2010 Red Hat, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <config.h> #include "cc-printers-panel.h" #include <string.h> #include <glib/gi18n-lib.h> #include <glib/gstdio.h> #include <polkit/polkit.h> #include <gdesktop-enums.h> #include <cups/cups.h> #include <math.h> #include "cc-editable-entry.h" #include "pp-new-printer-dialog.h" #include "pp-ppd-selection-dialog.h" #include "pp-options-dialog.h" #include "pp-jobs-dialog.h" #include "pp-utils.h" #include "pp-maintenance-command.h" CC_PANEL_REGISTER (CcPrintersPanel, cc_printers_panel) #define PRINTERS_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_PRINTERS_PANEL, CcPrintersPanelPrivate)) #define SUPPLY_BAR_HEIGHT 20 #define EMPTY_TEXT "\xe2\x80\x94" #define RENEW_INTERVAL 500 #define SUBSCRIPTION_DURATION 600 #define CUPS_DBUS_NAME "org.cups.cupsd.Notifier" #define CUPS_DBUS_PATH "/org/cups/cupsd/Notifier" #define CUPS_DBUS_INTERFACE "org.cups.cupsd.Notifier" #define CUPS_STATUS_CHECK_INTERVAL 5 #if (CUPS_VERSION_MAJOR > 1) || (CUPS_VERSION_MINOR > 5) #define HAVE_CUPS_1_6 1 #endif #ifndef HAVE_CUPS_1_6 #define ippGetState(ipp) ipp->state #define ippGetStatusCode(ipp) ipp->request.status.status_code #define ippGetString(attr, element, language) attr->values[element].string.text #endif struct _CcPrintersPanelPrivate { GtkBuilder *builder; cups_dest_t *dests; gchar **dest_model_names; gchar **ppd_file_names; int num_dests; int current_dest; int num_jobs; GdkRGBA background_color; GPermission *permission; GSettings *lockdown_settings; PpNewPrinterDialog *pp_new_printer_dialog; PpPPDSelectionDialog *pp_ppd_selection_dialog; PpOptionsDialog *pp_options_dialog; PpJobsDialog *pp_jobs_dialog; GDBusProxy *cups_proxy; GDBusConnection *cups_bus_connection; gint subscription_id; guint subscription_renewal_id; guint cups_status_check_id; guint dbus_subscription_id; GtkWidget *popup_menu; GList *driver_change_list; GCancellable *get_ppd_name_cancellable; gboolean getting_ppd_names; PPDList *all_ppds_list; GHashTable *preferred_drivers; GCancellable *get_all_ppds_cancellable; gchar *new_printer_name; gchar *new_printer_location; gchar *new_printer_make_and_model; gboolean new_printer_on_network; gboolean select_new_printer; gpointer dummy; }; typedef struct { gchar *printer_name; GCancellable *cancellable; } SetPPDItem; static void update_jobs_count (CcPrintersPanel *self); static void actualize_printers_list (CcPrintersPanel *self); static void update_sensitivity (gpointer user_data); static void printer_disable_cb (GObject *gobject, GParamSpec *pspec, gpointer user_data); static void printer_set_default_cb (GtkToggleButton *button, gpointer user_data); static void detach_from_cups_notifier (gpointer data); static void free_dests (CcPrintersPanel *self); static void cc_printers_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_printers_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void char_clear_pointer (gchar *pointer) { if (pointer) { g_free (pointer); pointer = NULL; } } static void cc_printers_panel_dispose (GObject *object) { CcPrintersPanelPrivate *priv = CC_PRINTERS_PANEL (object)->priv; if (priv->pp_new_printer_dialog) g_clear_object (&priv->pp_new_printer_dialog); free_dests (CC_PRINTERS_PANEL (object)); char_clear_pointer (priv->new_printer_name); char_clear_pointer (priv->new_printer_location); char_clear_pointer (priv->new_printer_make_and_model); if (priv->builder) { g_object_unref (priv->builder); priv->builder = NULL; } if (priv->lockdown_settings) { g_object_unref (priv->lockdown_settings); priv->lockdown_settings = NULL; } if (priv->permission) { g_object_unref (priv->permission); priv->permission = NULL; } detach_from_cups_notifier (CC_PRINTERS_PANEL (object)); if (priv->cups_status_check_id > 0) { g_source_remove (priv->cups_status_check_id); priv->cups_status_check_id = 0; } if (priv->all_ppds_list) { ppd_list_free (priv->all_ppds_list); priv->all_ppds_list = NULL; } if (priv->preferred_drivers) { g_hash_table_unref (priv->preferred_drivers); priv->preferred_drivers = NULL; } if (priv->get_all_ppds_cancellable) { g_cancellable_cancel (priv->get_all_ppds_cancellable); g_object_unref (priv->get_all_ppds_cancellable); priv->get_all_ppds_cancellable = NULL; } if (priv->driver_change_list) { GList *iter; for (iter = priv->driver_change_list; iter; iter = iter->next) { SetPPDItem *item = (SetPPDItem *) iter->data; g_cancellable_cancel (item->cancellable); g_object_unref (item->cancellable); g_free (item->printer_name); g_free (item); } g_list_free (priv->driver_change_list); priv->driver_change_list = NULL; } G_OBJECT_CLASS (cc_printers_panel_parent_class)->dispose (object); } static void cc_printers_panel_finalize (GObject *object) { G_OBJECT_CLASS (cc_printers_panel_parent_class)->finalize (object); } static GPermission * cc_printers_panel_get_permission (CcPanel *panel) { CcPrintersPanelPrivate *priv = CC_PRINTERS_PANEL (panel)->priv; return priv->permission; } static const char * cc_printers_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/printing"; else return "help:gnome-help/printing"; } static void cc_printers_panel_class_init (CcPrintersPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcPrintersPanelPrivate)); object_class->get_property = cc_printers_panel_get_property; object_class->set_property = cc_printers_panel_set_property; object_class->dispose = cc_printers_panel_dispose; object_class->finalize = cc_printers_panel_finalize; panel_class->get_permission = cc_printers_panel_get_permission; panel_class->get_help_uri = cc_printers_panel_get_help_uri; } static void on_cups_notification (GDBusConnection *connection, const char *sender_name, const char *object_path, const char *interface_name, const char *signal_name, GVariant *parameters, gpointer user_data) { CcPrintersPanel *self = (CcPrintersPanel*) user_data; CcPrintersPanelPrivate *priv; gboolean printer_is_accepting_jobs; gchar *printer_name = NULL; gchar *text = NULL; gchar *printer_uri = NULL; gchar *printer_state_reasons = NULL; gchar *job_state_reasons = NULL; gchar *job_name = NULL; guint job_id; gint printer_state; gint job_state; gint job_impressions_completed; static const char * const requested_attrs[] = { "job-printer-uri", "job-originating-user-name"}; priv = PRINTERS_PANEL_PRIVATE (self); if (g_strcmp0 (signal_name, "PrinterAdded") != 0 && g_strcmp0 (signal_name, "PrinterDeleted") != 0 && g_strcmp0 (signal_name, "PrinterStateChanged") != 0 && g_strcmp0 (signal_name, "PrinterStopped") != 0 && g_strcmp0 (signal_name, "JobCreated") != 0 && g_strcmp0 (signal_name, "JobCompleted") != 0) return; if (g_variant_n_children (parameters) == 1) g_variant_get (parameters, "(&s)", &text); else if (g_variant_n_children (parameters) == 6) { g_variant_get (parameters, "(&s&s&su&sb)", &text, &printer_uri, &printer_name, &printer_state, &printer_state_reasons, &printer_is_accepting_jobs); } else if (g_variant_n_children (parameters) == 11) { g_variant_get (parameters, "(&s&s&su&sbuu&s&su)", &text, &printer_uri, &printer_name, &printer_state, &printer_state_reasons, &printer_is_accepting_jobs, &job_id, &job_state, &job_state_reasons, &job_name, &job_impressions_completed); } if (g_strcmp0 (signal_name, "PrinterAdded") == 0 || g_strcmp0 (signal_name, "PrinterDeleted") == 0 || g_strcmp0 (signal_name, "PrinterStateChanged") == 0 || g_strcmp0 (signal_name, "PrinterStopped") == 0) actualize_printers_list (self); else if (g_strcmp0 (signal_name, "JobCreated") == 0 || g_strcmp0 (signal_name, "JobCompleted") == 0) { http_t *http; gchar *job_uri; ipp_t *request, *response; job_uri = g_strdup_printf ("ipp://localhost/jobs/%d", job_id); if ((http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ())) != NULL) { request = ippNewRequest (IPP_GET_JOB_ATTRIBUTES); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, job_uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", G_N_ELEMENTS (requested_attrs), NULL, requested_attrs); response = cupsDoRequest (http, request, "/"); if (response) { if (ippGetStatusCode (response) <= IPP_OK_CONFLICT) { ipp_attribute_t *attr_username = NULL; ipp_attribute_t *attr_printer_uri = NULL; attr_username = ippFindAttribute(response, "job-originating-user-name", IPP_TAG_NAME); attr_printer_uri = ippFindAttribute(response, "job-printer-uri", IPP_TAG_URI); if (attr_username && attr_printer_uri && g_strcmp0 (ippGetString (attr_username, 0, NULL), cupsUser ()) == 0 && g_strrstr (ippGetString (attr_printer_uri, 0, NULL), "/") != 0 && priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL && g_strcmp0 (g_strrstr (ippGetString (attr_printer_uri, 0, NULL), "/") + 1, priv->dests[priv->current_dest].name) == 0) update_jobs_count (self); } ippDelete(response); } httpClose (http); } g_free (job_uri); } } static gboolean renew_subscription (gpointer data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) data; static const char * const events[] = { "printer-added", "printer-deleted", "printer-stopped", "printer-state-changed", "job-created", "job-completed"}; priv = PRINTERS_PANEL_PRIVATE (self); priv->subscription_id = renew_cups_subscription (priv->subscription_id, events, G_N_ELEMENTS (events), SUBSCRIPTION_DURATION); if (priv->subscription_id > 0) return TRUE; else return FALSE; } static void attach_to_cups_notifier (gpointer data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) data; GError *error = NULL; priv = PRINTERS_PANEL_PRIVATE (self); if (renew_subscription (self)) { priv->subscription_renewal_id = g_timeout_add_seconds (RENEW_INTERVAL, renew_subscription, self); priv->cups_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, 0, NULL, CUPS_DBUS_NAME, CUPS_DBUS_PATH, CUPS_DBUS_INTERFACE, NULL, &error); if (!priv->cups_proxy) { g_warning ("%s", error->message); g_error_free (error); return; } priv->cups_bus_connection = g_dbus_proxy_get_connection (priv->cups_proxy); priv->dbus_subscription_id = g_dbus_connection_signal_subscribe (priv->cups_bus_connection, NULL, CUPS_DBUS_INTERFACE, NULL, CUPS_DBUS_PATH, NULL, 0, on_cups_notification, self, NULL); } } static void detach_from_cups_notifier (gpointer data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) data; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->dbus_subscription_id != 0) { g_dbus_connection_signal_unsubscribe (priv->cups_bus_connection, priv->dbus_subscription_id); priv->dbus_subscription_id = 0; } cancel_cups_subscription (priv->subscription_id); priv->subscription_id = 0; if (priv->subscription_renewal_id != 0) { g_source_remove (priv->subscription_renewal_id); priv->subscription_renewal_id = 0; } if (priv->cups_proxy != NULL) { g_object_unref (priv->cups_proxy); priv->cups_proxy = NULL; } } static void free_dests (CcPrintersPanel *self) { CcPrintersPanelPrivate *priv; gint i; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->num_dests > 0) { for (i = 0; i < priv->num_dests; i++) { g_free (priv->dest_model_names[i]); if (priv->ppd_file_names[i]) { g_unlink (priv->ppd_file_names[i]); g_free (priv->ppd_file_names[i]); } } g_free (priv->dest_model_names); g_free (priv->ppd_file_names); cupsFreeDests (priv->num_dests, priv->dests); } priv->dests = NULL; priv->num_dests = 0; priv->current_dest = -1; priv->dest_model_names = NULL; priv->ppd_file_names = NULL; } enum { NOTEBOOK_INFO_PAGE = 0, NOTEBOOK_NO_PRINTERS_PAGE, NOTEBOOK_NO_CUPS_PAGE, NOTEBOOK_N_PAGES }; enum { PRINTER_ID_COLUMN, PRINTER_NAME_COLUMN, PRINTER_PAUSED_COLUMN, PRINTER_DEFAULT_ICON_COLUMN, PRINTER_ICON_COLUMN, PRINTER_N_COLUMNS }; static void printer_selection_changed_cb (GtkTreeSelection *selection, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkTreeModel *model; cups_ptype_t type = 0; GtkTreeIter iter; GtkWidget *widget; GtkWidget *model_button; GtkWidget *model_label; GValue value = G_VALUE_INIT; gchar *printer_make_and_model = NULL; gchar *printer_model = NULL; gchar *reason = NULL; gchar **printer_reasons = NULL; gchar *marker_types = NULL; gchar *printer_name = NULL; gchar *printer_icon = NULL; gchar *printer_type = NULL; gchar *supply_type = NULL; gchar *printer_uri = NULL; gchar *location = NULL; gchar *status = NULL; gchar *device_uri = NULL; gchar *printer_hostname = NULL; int printer_state = 3; int id = -1; int i, j; static const char * const reasons[] = { "toner-low", "toner-empty", "developer-low", "developer-empty", "marker-supply-low", "marker-supply-empty", "cover-open", "door-open", "media-low", "media-empty", "offline", "paused", "marker-waste-almost-full", "marker-waste-full", "opc-near-eol", "opc-life-over" }; static const char * statuses[] = { /* Translators: The printer is low on toner */ N_("Low on toner"), /* Translators: The printer has no toner left */ N_("Out of toner"), /* Translators: "Developer" is a chemical for photo development, * http://en.wikipedia.org/wiki/Photographic_developer */ N_("Low on developer"), /* Translators: "Developer" is a chemical for photo development, * http://en.wikipedia.org/wiki/Photographic_developer */ N_("Out of developer"), /* Translators: "marker" is one color bin of the printer */ N_("Low on a marker supply"), /* Translators: "marker" is one color bin of the printer */ N_("Out of a marker supply"), /* Translators: One or more covers on the printer are open */ N_("Open cover"), /* Translators: One or more doors on the printer are open */ N_("Open door"), /* Translators: At least one input tray is low on media */ N_("Low on paper"), /* Translators: At least one input tray is empty */ N_("Out of paper"), /* Translators: The printer is offline */ NC_("printer state", "Offline"), /* Translators: Someone has paused the Printer */ NC_("printer state", "Paused"), /* Translators: The printer marker supply waste receptacle is almost full */ N_("Waste receptacle almost full"), /* Translators: The printer marker supply waste receptacle is full */ N_("Waste receptacle full"), /* Translators: Optical photo conductors are used in laser printers */ N_("The optical photo conductor is near end of life"), /* Translators: Optical photo conductors are used in laser printers */ N_("The optical photo conductor is no longer functioning") }; priv = PRINTERS_PANEL_PRIVATE (self); if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, PRINTER_ID_COLUMN, &id, PRINTER_NAME_COLUMN, &printer_name, PRINTER_ICON_COLUMN, &printer_icon, -1); } else id = -1; priv->current_dest = id; update_jobs_count (self); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "notebook"); if (gtk_notebook_get_current_page (GTK_NOTEBOOK (widget)) >= NOTEBOOK_NO_PRINTERS_PAGE) gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), NOTEBOOK_INFO_PAGE); for (i = 0; i < priv->dests[id].num_options; i++) { if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-location") == 0) location = g_strdup (priv->dests[priv->current_dest].options[i].value); else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-state") == 0) printer_state = atoi (priv->dests[priv->current_dest].options[i].value); else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-state-reasons") == 0) reason = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "marker-types") == 0) marker_types = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-make-and-model") == 0) printer_make_and_model = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-uri-supported") == 0) printer_uri = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-type") == 0) printer_type = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "device-uri") == 0) device_uri = priv->dests[priv->current_dest].options[i].value; } if (priv->ppd_file_names[priv->current_dest] == NULL) priv->ppd_file_names[priv->current_dest] = g_strdup (cupsGetPPD (priv->dests[priv->current_dest].name)); if (priv->dest_model_names[priv->current_dest] == NULL) priv->dest_model_names[priv->current_dest] = get_ppd_attribute (priv->ppd_file_names[priv->current_dest], "ModelName"); printer_model = g_strdup (priv->dest_model_names[priv->current_dest]); if (printer_model == NULL && printer_make_and_model) { gchar *breakpoint = NULL, *tmp = NULL, *tmp2 = NULL; gchar backup; size_t length = 0; gchar *forbiden[] = { "foomatic", ",", "hpijs", "hpcups", "(recommended)", "postscript (recommended)", NULL }; tmp = g_ascii_strdown (printer_make_and_model, -1); for (i = 0; i < g_strv_length (forbiden); i++) { tmp2 = g_strrstr (tmp, forbiden[i]); if (breakpoint == NULL || (tmp2 != NULL && tmp2 < breakpoint)) breakpoint = tmp2; } if (breakpoint) { backup = *breakpoint; *breakpoint = '\0'; length = strlen (tmp); *breakpoint = backup; g_free (tmp); if (length > 0) printer_model = g_strndup (printer_make_and_model, length); } else printer_model = g_strdup (printer_make_and_model); } if (priv->new_printer_name && g_strcmp0 (priv->new_printer_name, printer_name) == 0) { /* Translators: Printer's state (printer is being configured right now) */ status = g_strdup ( C_("printer state", "Configuring")); } /* Find the first of the most severe reasons * and show it in the status field */ if (!status && reason && !g_str_equal (reason, "none")) { int errors = 0, warnings = 0, reports = 0; int error_index = -1, warning_index = -1, report_index = -1; printer_reasons = g_strsplit (reason, ",", -1); for (i = 0; i < g_strv_length (printer_reasons); i++) { for (j = 0; j < G_N_ELEMENTS (reasons); j++) if (strncmp (printer_reasons[i], reasons[j], strlen (reasons[j])) == 0) { if (g_str_has_suffix (printer_reasons[i], "-report")) { if (reports == 0) report_index = j; reports++; } else if (g_str_has_suffix (printer_reasons[i], "-warning")) { if (warnings == 0) warning_index = j; warnings++; } else { if (errors == 0) error_index = j; errors++; } } } g_strfreev (printer_reasons); if (error_index >= 0) status = g_strdup (_(statuses[error_index])); else if (warning_index >= 0) status = g_strdup (_(statuses[warning_index])); else if (report_index >= 0) status = g_strdup (_(statuses[report_index])); } if (status == NULL) { switch (printer_state) { case 3: /* Translators: Printer's state (can start new job without waiting) */ status = g_strdup ( C_("printer state", "Ready")); break; case 4: /* Translators: Printer's state (jobs are processing) */ status = g_strdup ( C_("printer state", "Processing")); break; case 5: /* Translators: Printer's state (no jobs can be processed) */ status = g_strdup ( C_("printer state", "Stopped")); break; } } widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-icon"); g_value_init (&value, G_TYPE_INT); g_object_get_property ((GObject *) widget, "icon-size", &value); if (printer_icon) { gtk_image_set_from_icon_name ((GtkImage *) widget, printer_icon, g_value_get_int (&value)); g_free (printer_icon); } else gtk_image_set_from_icon_name ((GtkImage *) widget, "printer", g_value_get_int (&value)); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-name-label"); if (printer_name) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), printer_name); g_free (printer_name); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-status-label"); if (status) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), status); g_free (status); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-location-label"); if (location) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), location); g_free (location); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); model_button = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-button"); model_label = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-label"); if (printer_model) { gtk_button_set_label (GTK_BUTTON (model_button), printer_model); gtk_label_set_text (GTK_LABEL (model_label), printer_model); g_free (printer_model); } else { gtk_button_set_label (GTK_BUTTON (model_button), EMPTY_TEXT); gtk_label_set_text (GTK_LABEL (model_label), EMPTY_TEXT); } widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-ip-address-label"); if (printer_type) type = atoi (printer_type); printer_hostname = printer_get_hostname (type, device_uri, printer_uri); if (printer_hostname) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), printer_hostname); g_free (printer_hostname); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-disable-switch"); g_signal_handlers_block_by_func (G_OBJECT (widget), printer_disable_cb, self); gtk_switch_set_active (GTK_SWITCH (widget), printer_state != 5); g_signal_handlers_unblock_by_func (G_OBJECT (widget), printer_disable_cb, self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-default-check-button"); g_signal_handlers_block_by_func (G_OBJECT (widget), printer_set_default_cb, self); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widget), priv->dests[id].is_default); g_signal_handlers_unblock_by_func (G_OBJECT (widget), printer_set_default_cb, self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "supply-drawing-area"); gtk_widget_set_size_request (widget, -1, SUPPLY_BAR_HEIGHT); gtk_widget_queue_draw (widget); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "supply-label"); if (marker_types && g_strrstr (marker_types, "toner") != NULL) /* Translators: Toner supply */ supply_type = g_strdup ( _("Toner Level")); else if (marker_types && g_strrstr (marker_types, "ink") != NULL) /* Translators: Ink supply */ supply_type = g_strdup ( _("Ink Level")); else /* Translators: By supply we mean ink, toner, staples, water, ... */ supply_type = g_strdup ( _("Supply Level")); if (supply_type) { gtk_label_set_text (GTK_LABEL (widget), supply_type); g_free (supply_type); } else gtk_label_set_text (GTK_LABEL (widget), EMPTY_TEXT); } else { if (id == -1) { if (priv->new_printer_name && g_strcmp0 (priv->new_printer_name, printer_name) == 0) { /* Translators: Printer's state (printer is being installed right now) */ status = g_strdup ( C_("printer state", "Installing")); location = g_strdup (priv->new_printer_location); printer_model = g_strdup (priv->new_printer_make_and_model); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "notebook"); if (gtk_notebook_get_current_page (GTK_NOTEBOOK (widget)) >= NOTEBOOK_NO_PRINTERS_PAGE) gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), NOTEBOOK_INFO_PAGE); } } widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-icon"); g_value_init (&value, G_TYPE_INT); g_object_get_property ((GObject *) widget, "icon-size", &value); if (printer_icon) { gtk_image_set_from_icon_name ((GtkImage *) widget, printer_icon, g_value_get_int (&value)); g_free (printer_icon); } else gtk_image_set_from_icon_name ((GtkImage *) widget, "printer", g_value_get_int (&value)); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-name-label"); if (printer_name) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), printer_name); g_free (printer_name); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-status-label"); if (status) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), status); g_free (status); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-location-label"); if (location) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), location); g_free (location); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); model_button = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-button"); model_label = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-label"); if (printer_model) { gtk_button_set_label (GTK_BUTTON (model_button), printer_model); gtk_label_set_text (GTK_LABEL (model_label), printer_model); g_free (printer_model); } else { gtk_button_set_label (GTK_BUTTON (model_button), EMPTY_TEXT); gtk_label_set_text (GTK_LABEL (model_label), EMPTY_TEXT); } widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-ip-address-label"); cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-jobs-label"); cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-disable-switch"); g_signal_handlers_block_by_func (G_OBJECT (widget), printer_disable_cb, self); gtk_switch_set_active (GTK_SWITCH (widget), FALSE); g_signal_handlers_unblock_by_func (G_OBJECT (widget), printer_disable_cb, self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-default-check-button"); g_signal_handlers_block_by_func (G_OBJECT (widget), printer_set_default_cb, self); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widget), FALSE); g_signal_handlers_unblock_by_func (G_OBJECT (widget), printer_set_default_cb, self); } update_sensitivity (self); } static void actualize_printers_list (CcPrintersPanel *self) { CcPrintersPanelPrivate *priv; GtkTreeSelection *selection; GtkListStore *store; cups_ptype_t printer_type = 0; GtkTreeModel *model; GtkTreeIter selected_iter; GtkTreeView *treeview; GtkTreeIter iter; cups_job_t *jobs = NULL; GtkWidget *widget; gboolean paused = FALSE; gboolean selected_iter_set = FALSE; gboolean valid = FALSE; http_t *http; gchar *current_printer_name = NULL; gchar *printer_icon_name = NULL; gchar *default_icon_name = NULL; gchar *device_uri = NULL; gint new_printer_position = 0; int current_dest = -1; int i, j; int num_jobs = 0; priv = PRINTERS_PANEL_PRIVATE (self); treeview = (GtkTreeView*) gtk_builder_get_object (priv->builder, "printers-treeview"); if ((selection = gtk_tree_view_get_selection (treeview)) != NULL && gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get (model, &iter, PRINTER_NAME_COLUMN, &current_printer_name, -1); } if (priv->new_printer_name && priv->select_new_printer) { g_free (current_printer_name); current_printer_name = g_strdup (priv->new_printer_name); priv->select_new_printer = FALSE; } free_dests (self); priv->num_dests = cupsGetDests (&priv->dests); priv->dest_model_names = g_new0 (gchar *, priv->num_dests); priv->ppd_file_names = g_new0 (gchar *, priv->num_dests); store = gtk_list_store_new (PRINTER_N_COLUMNS, G_TYPE_INT, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING); if (priv->num_dests == 0 && !priv->new_printer_name) { widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "notebook"); http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ()); if (http) { httpClose (http); gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), NOTEBOOK_NO_PRINTERS_PAGE); } else gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), NOTEBOOK_NO_CUPS_PAGE); gtk_list_store_append (store, &iter); gtk_list_store_set (store, &iter, PRINTER_ID_COLUMN, 0, /* Translators: There are no printers available (none is configured or CUPS is not running) */ PRINTER_NAME_COLUMN, _("No printers available"), PRINTER_PAUSED_COLUMN, TRUE, PRINTER_DEFAULT_ICON_COLUMN, NULL, PRINTER_ICON_COLUMN, NULL, -1); gtk_widget_set_sensitive (GTK_WIDGET (treeview), FALSE); } else gtk_widget_set_sensitive (GTK_WIDGET (treeview), TRUE); for (i = 0; i < priv->num_dests; i++) { gchar *instance; if (priv->new_printer_name && new_printer_position >= 0) { gint comparison_result = g_ascii_strcasecmp (priv->dests[i].name, priv->new_printer_name); if (comparison_result < 0) new_printer_position = i + 1; else if (comparison_result == 0) new_printer_position = -1; } gtk_list_store_append (store, &iter); if (priv->dests[i].instance) { instance = g_strdup_printf ("%s / %s", priv->dests[i].name, priv->dests[i].instance); } else { instance = g_strdup (priv->dests[i].name); } for (j = 0; j < priv->dests[i].num_options; j++) { if (g_strcmp0 (priv->dests[i].options[j].name, "printer-state") == 0) paused = (g_strcmp0 (priv->dests[i].options[j].value, "5") == 0); else if (g_strcmp0 (priv->dests[i].options[j].name, "device-uri") == 0) device_uri = priv->dests[i].options[j].value; else if (g_strcmp0 (priv->dests[i].options[j].name, "printer-type") == 0) printer_type = atoi (priv->dests[i].options[j].value); } if (priv->dests[i].is_default) default_icon_name = g_strdup ("emblem-default-symbolic"); else default_icon_name = NULL; if (printer_is_local (printer_type, device_uri)) printer_icon_name = g_strdup ("printer"); else printer_icon_name = g_strdup ("printer-network"); gtk_list_store_set (store, &iter, PRINTER_ID_COLUMN, i, PRINTER_NAME_COLUMN, instance, PRINTER_PAUSED_COLUMN, paused, PRINTER_DEFAULT_ICON_COLUMN, default_icon_name, PRINTER_ICON_COLUMN, printer_icon_name, -1); if (g_strcmp0 (current_printer_name, instance) == 0) { current_dest = i; selected_iter = iter; selected_iter_set = TRUE; } g_free (instance); g_free (printer_icon_name); g_free (default_icon_name); } if (priv->new_printer_name && new_printer_position >= 0) { gtk_list_store_insert (store, &iter, new_printer_position); gtk_list_store_set (store, &iter, PRINTER_ID_COLUMN, -1, PRINTER_NAME_COLUMN, priv->new_printer_name, PRINTER_PAUSED_COLUMN, TRUE, PRINTER_DEFAULT_ICON_COLUMN, NULL, PRINTER_ICON_COLUMN, priv->new_printer_on_network ? "printer-network" : "printer", -1); if (g_strcmp0 (current_printer_name, priv->new_printer_name) == 0) { selected_iter = iter; selected_iter_set = TRUE; } } g_signal_handlers_block_by_func ( G_OBJECT (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview))), printer_selection_changed_cb, self); gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (store)); g_signal_handlers_unblock_by_func ( G_OBJECT (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview))), printer_selection_changed_cb, self); if (selected_iter_set) { priv->current_dest = current_dest; gtk_tree_selection_select_iter ( gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), &selected_iter); } else { num_jobs = cupsGetJobs (&jobs, NULL, 1, CUPS_WHICHJOBS_ALL); /* Select last used printer */ if (num_jobs > 0) { for (i = 0; i < priv->num_dests; i++) if (g_strcmp0 (priv->dests[i].name, jobs[num_jobs - 1].dest) == 0) { priv->current_dest = i; break; } cupsFreeJobs (num_jobs, jobs); } /* Select default printer */ if (priv->current_dest < 0) { for (i = 0; i < priv->num_dests; i++) if (priv->dests[i].is_default) { priv->current_dest = i; break; } } if (priv->current_dest >= 0) { gint id; valid = gtk_tree_model_get_iter_first ((GtkTreeModel *) store, &selected_iter); while (valid) { gtk_tree_model_get ((GtkTreeModel *) store, &selected_iter, PRINTER_ID_COLUMN, &id, -1); if (id == priv->current_dest) break; valid = gtk_tree_model_iter_next ((GtkTreeModel *) store, &selected_iter); } gtk_tree_selection_select_iter ( gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), &selected_iter); } else if (priv->num_dests > 0) { /* Select first printer */ gtk_tree_model_get_iter_first ((GtkTreeModel *) store, &selected_iter); gtk_tree_selection_select_iter ( gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), &selected_iter); } } g_free (current_printer_name); g_object_unref (store); update_sensitivity (self); } static void set_cell_sensitivity_func (GtkTreeViewColumn *tree_column, GtkCellRenderer *cell, GtkTreeModel *tree_model, GtkTreeIter *iter, gpointer func_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) func_data; gboolean paused = FALSE; priv = PRINTERS_PANEL_PRIVATE (self); gtk_tree_model_get (tree_model, iter, PRINTER_PAUSED_COLUMN, &paused, -1); if (priv->num_dests == 0) g_object_set (G_OBJECT (cell), "ellipsize", PANGO_ELLIPSIZE_NONE, "width-chars", -1, NULL); else g_object_set (G_OBJECT (cell), "ellipsize", PANGO_ELLIPSIZE_END, "width-chars", 18, NULL); g_object_set (cell, "sensitive", !paused, NULL); } static void set_pixbuf_cell_sensitivity_func (GtkTreeViewColumn *tree_column, GtkCellRenderer *cell, GtkTreeModel *tree_model, GtkTreeIter *iter, gpointer func_data) { gboolean paused = FALSE; gtk_tree_model_get (tree_model, iter, PRINTER_PAUSED_COLUMN, &paused, -1); g_object_set (cell, "sensitive", !paused, NULL); } static void populate_printers_list (CcPrintersPanel *self) { CcPrintersPanelPrivate *priv; GtkTreeViewColumn *column; GtkCellRenderer *icon_renderer; GtkCellRenderer *icon_renderer2; GtkCellRenderer *renderer; GtkWidget *treeview; priv = PRINTERS_PANEL_PRIVATE (self); treeview = (GtkWidget*) gtk_builder_get_object (priv->builder, "printers-treeview"); g_signal_connect (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)), "changed", G_CALLBACK (printer_selection_changed_cb), self); actualize_printers_list (self); icon_renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (icon_renderer, "stock-size", gtk_icon_size_from_name ("cc-sidebar-list"), NULL); gtk_cell_renderer_set_padding (icon_renderer, 4, 4); column = gtk_tree_view_column_new_with_attributes ("Icon", icon_renderer, "icon-name", PRINTER_ICON_COLUMN, NULL); gtk_tree_view_column_set_cell_data_func (column, icon_renderer, set_pixbuf_cell_sensitivity_func, self, NULL); gtk_tree_view_column_set_expand (column, FALSE); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); renderer = gtk_cell_renderer_text_new (); g_object_set (G_OBJECT (renderer), "ellipsize", PANGO_ELLIPSIZE_END, "width-chars", 18, NULL); column = gtk_tree_view_column_new_with_attributes ("Printer", renderer, "text", PRINTER_NAME_COLUMN, NULL); gtk_tree_view_column_set_cell_data_func (column, renderer, set_cell_sensitivity_func, self, NULL); gtk_tree_view_column_set_expand (column, FALSE); gtk_tree_view_column_set_min_width (column, 120); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); icon_renderer2 = gtk_cell_renderer_pixbuf_new (); column = gtk_tree_view_column_new_with_attributes ("Default", icon_renderer2, "icon-name", PRINTER_DEFAULT_ICON_COLUMN, NULL); gtk_tree_view_column_set_expand (column, FALSE); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); } enum { JOB_ID_COLUMN, JOB_TITLE_COLUMN, JOB_STATE_COLUMN, JOB_CREATION_TIME_COLUMN, JOB_N_COLUMNS }; static void update_jobs_count (CcPrintersPanel *self) { CcPrintersPanelPrivate *priv; cups_job_t *jobs; GtkWidget *widget; gchar *active_jobs = NULL; gint num_jobs; priv = PRINTERS_PANEL_PRIVATE (self); priv->num_jobs = -1; if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { priv->num_jobs = cupsGetJobs (&jobs, priv->dests[priv->current_dest].name, 1, CUPS_WHICHJOBS_ACTIVE); if (priv->num_jobs > 0) cupsFreeJobs (priv->num_jobs, jobs); num_jobs = priv->num_jobs < 0 ? 0 : (guint) priv->num_jobs; /* Translators: there is n active print jobs on this printer */ active_jobs = g_strdup_printf (ngettext ("%u active", "%u active", num_jobs), num_jobs); } widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-jobs-label"); if (active_jobs) { cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), active_jobs); g_free (active_jobs); } else cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), EMPTY_TEXT); if (priv->pp_jobs_dialog) { pp_jobs_dialog_update (priv->pp_jobs_dialog); } } static void printer_disable_cb (GObject *gobject, GParamSpec *pspec, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; gboolean paused = FALSE; char *name = NULL; int i; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { name = priv->dests[priv->current_dest].name; for (i = 0; i < priv->dests[priv->current_dest].num_options; i++) { if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-state") == 0) paused = (g_strcmp0 (priv->dests[priv->current_dest].options[i].value, "5") == 0); } } if (name && printer_set_enabled (name, paused)) actualize_printers_list (self); } typedef struct { gchar *color; gchar *type; gchar *name; gint level; } MarkerItem; static gint markers_cmp (gconstpointer a, gconstpointer b) { MarkerItem *x = (MarkerItem*) a; MarkerItem *y = (MarkerItem*) b; if (x->level < y->level) return 1; else if (x->level == y->level) return 0; else return -1; } static void rounded_rectangle (cairo_t *cr, double x, double y, double w, double h, double r) { cairo_new_sub_path (cr); cairo_arc (cr, x + r, y + r, r, M_PI, 3 * M_PI / 2); cairo_arc (cr, x + w - r, y + r, r, 3 *M_PI / 2, 2 * M_PI); cairo_arc (cr, x + w - r, y + h - r, r, 0, M_PI / 2); cairo_arc (cr, x + r, y + h - r, r, M_PI / 2, M_PI); cairo_close_path (cr); } static gboolean supply_levels_draw_cb (GtkWidget *widget, cairo_t *cr, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkStyleContext *context; gchar *marker_levels = NULL; gchar *marker_colors = NULL; gchar *marker_names = NULL; gchar *marker_types = NULL; gchar *tooltip_text = NULL; gint width; gint height; int i; priv = PRINTERS_PANEL_PRIVATE (self); width = gtk_widget_get_allocated_width (widget); height = gtk_widget_get_allocated_height (widget); cairo_rectangle (cr, 0.0, 0.0, width, height); gdk_cairo_set_source_rgba (cr, &priv->background_color); cairo_fill (cr); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { for (i = 0; i < priv->dests[priv->current_dest].num_options; i++) { if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "marker-names") == 0) marker_names = g_strcompress (priv->dests[priv->current_dest].options[i].value); else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "marker-levels") == 0) marker_levels = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "marker-colors") == 0) marker_colors = priv->dests[priv->current_dest].options[i].value; else if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "marker-types") == 0) marker_types = priv->dests[priv->current_dest].options[i].value; } if (marker_levels && marker_colors && marker_names && marker_types) { GdkRGBA border_color = {0.0, 0.0, 0.0, 1.0}; GSList *markers = NULL; GSList *tmp_list = NULL; GValue int_val = G_VALUE_INIT; gchar **marker_levelsv = NULL; gchar **marker_colorsv = NULL; gchar **marker_namesv = NULL; gchar **marker_typesv = NULL; gchar *tmp = NULL; gint border_radius = 0; context = gtk_widget_get_style_context ((GtkWidget *) gtk_builder_get_object (priv->builder, "printer-options-button")); gtk_style_context_get_border_color (context, 0, &border_color); gtk_style_context_get_property ( context, GTK_STYLE_PROPERTY_BORDER_RADIUS, 0, &int_val); if (G_VALUE_HOLDS_INT (&int_val)) border_radius = g_value_get_int (&int_val); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "supply-drawing-area"); marker_levelsv = g_strsplit (marker_levels, ",", -1); marker_colorsv = g_strsplit (marker_colors, ",", -1); marker_namesv = g_strsplit (marker_names, ",", -1); marker_typesv = g_strsplit (marker_types, ",", -1); if (g_strv_length (marker_levelsv) == g_strv_length (marker_colorsv) && g_strv_length (marker_colorsv) == g_strv_length (marker_namesv) && g_strv_length (marker_namesv) == g_strv_length (marker_typesv)) { for (i = 0; i < g_strv_length (marker_levelsv); i++) { MarkerItem *marker; if (g_strcmp0 (marker_typesv[i], "ink") == 0 || g_strcmp0 (marker_typesv[i], "toner") == 0) { marker = g_new0 (MarkerItem, 1); marker->type = g_strdup (marker_typesv[i]); marker->name = g_strdup (marker_namesv[i]); marker->color = g_strdup (marker_colorsv[i]); marker->level = atoi (marker_levelsv[i]); markers = g_slist_prepend (markers, marker); } } markers = g_slist_sort (markers, markers_cmp); for (tmp_list = markers; tmp_list; tmp_list = tmp_list->next) { GdkRGBA color = {0.0, 0.0, 0.0, 1.0}; double display_value; int value; value = ((MarkerItem*) tmp_list->data)->level; gdk_rgba_parse (&color, ((MarkerItem*) tmp_list->data)->color); if (value > 0) { display_value = value / 100.0 * (width - 3.0); gdk_cairo_set_source_rgba (cr, &color); rounded_rectangle (cr, 1.5, 1.5, display_value, SUPPLY_BAR_HEIGHT - 3.0, border_radius); cairo_fill (cr); } if (tooltip_text) { tmp = g_strdup_printf ("%s\n%s", tooltip_text, ((MarkerItem*) tmp_list->data)->name); g_free (tooltip_text); tooltip_text = tmp; tmp = NULL; } else tooltip_text = g_strdup_printf ("%s", ((MarkerItem*) tmp_list->data)->name); } cairo_set_line_width (cr, 1.0); gdk_cairo_set_source_rgba (cr, &border_color); rounded_rectangle (cr, 1.5, 1.5, width - 3.0, SUPPLY_BAR_HEIGHT - 3.0, border_radius); cairo_stroke (cr); for (tmp_list = markers; tmp_list; tmp_list = tmp_list->next) { g_free (((MarkerItem*) tmp_list->data)->name); g_free (((MarkerItem*) tmp_list->data)->type); g_free (((MarkerItem*) tmp_list->data)->color); } g_slist_free_full (markers, g_free); } g_strfreev (marker_levelsv); g_strfreev (marker_colorsv); g_strfreev (marker_namesv); g_strfreev (marker_typesv); } g_free (marker_names); if (tooltip_text) { gtk_widget_set_tooltip_text (widget, tooltip_text); g_free (tooltip_text); } else { gtk_widget_set_tooltip_text (widget, NULL); gtk_widget_set_has_tooltip (widget, FALSE); } } return TRUE; } static void printer_set_default_cb (GtkToggleButton *button, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; char *name = NULL; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) name = priv->dests[priv->current_dest].name; if (name) { printer_set_default (name); actualize_printers_list (self); g_signal_handlers_block_by_func (G_OBJECT (button), printer_set_default_cb, self); gtk_toggle_button_set_active (button, priv->dests[priv->current_dest].is_default); g_signal_handlers_unblock_by_func (G_OBJECT (button), printer_set_default_cb, self); } } static void new_printer_dialog_pre_response_cb (PpNewPrinterDialog *dialog, const gchar *device_name, const gchar *device_location, const gchar *device_make_and_model, gboolean is_network_device, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; priv = PRINTERS_PANEL_PRIVATE (self); priv->new_printer_name = g_strdup (device_name); priv->new_printer_location = g_strdup (device_location); priv->new_printer_make_and_model = g_strdup (device_make_and_model); priv->new_printer_on_network = is_network_device; priv->select_new_printer = TRUE; actualize_printers_list (self); } static void new_printer_dialog_response_cb (PpNewPrinterDialog *dialog, gint response_id, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->pp_new_printer_dialog) g_clear_object (&priv->pp_new_printer_dialog); char_clear_pointer (priv->new_printer_name); char_clear_pointer (priv->new_printer_location); char_clear_pointer (priv->new_printer_make_and_model); if (response_id == GTK_RESPONSE_REJECT) { GtkWidget *message_dialog; message_dialog = gtk_message_dialog_new (NULL, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, /* Translators: Addition of the new printer failed. */ _("Failed to add new printer.")); g_signal_connect (message_dialog, "response", G_CALLBACK (gtk_widget_destroy), NULL); gtk_widget_show (message_dialog); } actualize_printers_list (self); } static void printer_add_cb (GtkToolButton *toolbutton, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkWidget *toplevel; priv = PRINTERS_PANEL_PRIVATE (self); toplevel = gtk_widget_get_toplevel (GTK_WIDGET (self)); priv->pp_new_printer_dialog = PP_NEW_PRINTER_DIALOG (pp_new_printer_dialog_new (GTK_WINDOW (toplevel))); g_signal_connect (priv->pp_new_printer_dialog, "pre-response", G_CALLBACK (new_printer_dialog_pre_response_cb), self); g_signal_connect (priv->pp_new_printer_dialog, "response", G_CALLBACK (new_printer_dialog_response_cb), self); } static void printer_remove_cb (GtkToolButton *toolbutton, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; char *printer_name = NULL; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) printer_name = priv->dests[priv->current_dest].name; if (printer_name && printer_delete (printer_name)) actualize_printers_list (self); } static void printer_name_edit_cb (GtkWidget *entry, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; const gchar *new_name; gchar *old_name = NULL; gint i; priv = PRINTERS_PANEL_PRIVATE (self); new_name = cc_editable_entry_get_text (CC_EDITABLE_ENTRY (entry)); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) old_name = priv->dests[priv->current_dest].name; if (printer_rename (old_name, new_name)) { free_dests (self); priv->num_dests = cupsGetDests (&priv->dests); priv->dest_model_names = g_new0 (gchar *, priv->num_dests); priv->ppd_file_names = g_new0 (gchar *, priv->num_dests); for (i = 0; i < priv->num_dests; i++) if (g_strcmp0 (priv->dests[i].name, new_name) == 0) { priv->current_dest = i; break; } } actualize_printers_list (self); } static void printer_location_edit_cb (GtkWidget *entry, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; const gchar *location; gchar *printer_name = NULL; priv = PRINTERS_PANEL_PRIVATE (self); location = cc_editable_entry_get_text (CC_EDITABLE_ENTRY (entry)); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) printer_name = priv->dests[priv->current_dest].name; if (printer_name && location && printer_set_location (printer_name, location)) actualize_printers_list (self); } static void set_ppd_cb (gchar *printer_name, gboolean success, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GList *iter; priv = PRINTERS_PANEL_PRIVATE (self); for (iter = priv->driver_change_list; iter; iter = iter->next) { SetPPDItem *item = (SetPPDItem *) iter->data; if (g_strcmp0 (item->printer_name, printer_name) == 0) { priv->driver_change_list = g_list_remove_link (priv->driver_change_list, iter); g_object_unref (item->cancellable); g_free (item->printer_name); g_free (item); g_list_free (iter); break; } } update_sensitivity (self); if (success) { actualize_printers_list (self); } g_free (printer_name); } static void select_ppd_manually (GtkMenuItem *menuitem, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkFileFilter *filter; GtkWidget *dialog; gchar *printer_name = NULL; priv = PRINTERS_PANEL_PRIVATE (self); gtk_menu_shell_cancel (GTK_MENU_SHELL (priv->popup_menu)); dialog = gtk_file_chooser_dialog_new (_("Select PPD File"), NULL, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); filter = gtk_file_filter_new (); gtk_file_filter_set_name (filter, _("PostScript Printer Description files (*.ppd, *.PPD, *.ppd.gz, *.PPD.gz, *.PPD.GZ)")); gtk_file_filter_add_pattern (filter, "*.ppd"); gtk_file_filter_add_pattern (filter, "*.PPD"); gtk_file_filter_add_pattern (filter, "*.ppd.gz"); gtk_file_filter_add_pattern (filter, "*.PPD.gz"); gtk_file_filter_add_pattern (filter, "*.PPD.GZ"); gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dialog), filter); if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { gchar *ppd_filename; ppd_filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) printer_name = priv->dests[priv->current_dest].name; if (printer_name && ppd_filename) { SetPPDItem *item; item = g_new0 (SetPPDItem, 1); item->printer_name = g_strdup (printer_name); item->cancellable = g_cancellable_new (); priv->driver_change_list = g_list_prepend (priv->driver_change_list, item); update_sensitivity (self); printer_set_ppd_file_async (printer_name, ppd_filename, item->cancellable, set_ppd_cb, user_data); } g_free (ppd_filename); } gtk_widget_destroy (dialog); } static void ppd_selection_dialog_response_cb (GtkDialog *dialog, gint response_id, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; gchar *printer_name = NULL; priv = PRINTERS_PANEL_PRIVATE (self); if (response_id == GTK_RESPONSE_OK) { gchar *ppd_name; ppd_name = pp_ppd_selection_dialog_get_ppd_name (priv->pp_ppd_selection_dialog); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) printer_name = priv->dests[priv->current_dest].name; if (printer_name && ppd_name) { SetPPDItem *item; item = g_new0 (SetPPDItem, 1); item->printer_name = g_strdup (printer_name); item->cancellable = g_cancellable_new (); priv->driver_change_list = g_list_prepend (priv->driver_change_list, item); update_sensitivity (self); printer_set_ppd_async (printer_name, ppd_name, item->cancellable, set_ppd_cb, user_data); } g_free (ppd_name); } pp_ppd_selection_dialog_free (priv->pp_ppd_selection_dialog); priv->pp_ppd_selection_dialog = NULL; } static void select_ppd_in_dialog (GtkMenuItem *menuitem, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkWidget *widget; gchar *device_id = NULL; gchar *manufacturer = NULL; priv = PRINTERS_PANEL_PRIVATE (self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "main-vbox"); if (!priv->pp_ppd_selection_dialog) { if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests) { device_id = get_ppd_attribute (priv->ppd_file_names[priv->current_dest], "1284DeviceID"); if (device_id) { manufacturer = get_tag_value (device_id, "mfg"); if (!manufacturer) manufacturer = get_tag_value (device_id, "manufacturer"); } if (manufacturer == NULL) { manufacturer = get_ppd_attribute (priv->ppd_file_names[priv->current_dest], "Manufacturer"); } if (manufacturer == NULL) { manufacturer = g_strdup ("Raw"); } } priv->pp_ppd_selection_dialog = pp_ppd_selection_dialog_new ( GTK_WINDOW (gtk_widget_get_toplevel (widget)), priv->all_ppds_list, manufacturer, ppd_selection_dialog_response_cb, self); g_free (manufacturer); g_free (device_id); } } static void set_ppd_from_list (GtkMenuItem *menuitem, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; gchar *printer_name = NULL; gchar *ppd_name; priv = PRINTERS_PANEL_PRIVATE (self); ppd_name = (gchar *) g_object_get_data (G_OBJECT (menuitem), "ppd-name"); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) printer_name = priv->dests[priv->current_dest].name; if (printer_name && ppd_name) { SetPPDItem *item; item = g_new0 (SetPPDItem, 1); item->printer_name = g_strdup (printer_name); item->cancellable = g_cancellable_new (); priv->driver_change_list = g_list_prepend (priv->driver_change_list, item); update_sensitivity (self); printer_set_ppd_async (printer_name, ppd_name, item->cancellable, set_ppd_cb, user_data); } } static void ppd_names_free (gpointer user_data) { PPDName **names = (PPDName **) user_data; gint i; if (names) { for (i = 0; names[i]; i++) { g_free (names[i]->ppd_name); g_free (names[i]->ppd_display_name); g_free (names[i]); } g_free (names); } } static void get_ppd_names_cb (PPDName **names, const gchar *printer_name, gboolean cancelled, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkWidget *informal = NULL; GtkWidget *placeholders[3]; GtkWidget *spinner; gpointer value = NULL; gboolean found = FALSE; PPDName **hash_names = NULL; GList *children, *iter; gint i; priv = PRINTERS_PANEL_PRIVATE (self); priv->getting_ppd_names = FALSE; for (i = 0; i < 3; i++) placeholders[i] = NULL; children = gtk_container_get_children (GTK_CONTAINER (priv->popup_menu)); if (children) { for (iter = children; iter; iter = iter->next) { if (g_strcmp0 ((gchar *) g_object_get_data (G_OBJECT (iter->data), "purpose"), "informal") == 0) informal = GTK_WIDGET (iter->data); else if (g_strcmp0 ((gchar *) g_object_get_data (G_OBJECT (iter->data), "purpose"), "placeholder1") == 0) placeholders[0] = GTK_WIDGET (iter->data); else if (g_strcmp0 ((gchar *) g_object_get_data (G_OBJECT (iter->data), "purpose"), "placeholder2") == 0) placeholders[1] = GTK_WIDGET (iter->data); else if (g_strcmp0 ((gchar *) g_object_get_data (G_OBJECT (iter->data), "purpose"), "placeholder3") == 0) placeholders[2] = GTK_WIDGET (iter->data); } g_list_free (children); } if (!priv->preferred_drivers) { priv->preferred_drivers = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, ppd_names_free); } if (!cancelled && !g_hash_table_lookup_extended (priv->preferred_drivers, printer_name, NULL, NULL)) g_hash_table_insert (priv->preferred_drivers, g_strdup (printer_name), names); if (priv->preferred_drivers && g_hash_table_lookup_extended (priv->preferred_drivers, printer_name, NULL, &value)) { hash_names = (PPDName **) value; if (hash_names) { for (i = 0; hash_names[i]; i++) { if (placeholders[i]) { gtk_menu_item_set_label (GTK_MENU_ITEM (placeholders[i]), hash_names[i]->ppd_display_name); g_object_set_data_full (G_OBJECT (placeholders[i]), "ppd-name", g_strdup (hash_names[i]->ppd_name), g_free); g_signal_connect (placeholders[i], "activate", G_CALLBACK (set_ppd_from_list), self); gtk_widget_set_sensitive (GTK_WIDGET (placeholders[i]), TRUE); gtk_widget_show (placeholders[i]); } } found = TRUE; } else { found = FALSE; } } if (informal) { gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (informal), FALSE); spinner = gtk_image_menu_item_get_image (GTK_IMAGE_MENU_ITEM (informal)); if (spinner) gtk_spinner_stop (GTK_SPINNER (spinner)); if (found) gtk_widget_hide (informal); else gtk_menu_item_set_label (GTK_MENU_ITEM (informal), _("No suitable driver found")); } gtk_widget_show_all (priv->popup_menu); update_sensitivity (self); } static void popup_menu_done (GtkMenuShell *menushell, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->get_ppd_name_cancellable) { g_cancellable_cancel (priv->get_ppd_name_cancellable); g_object_unref (priv->get_ppd_name_cancellable); priv->get_ppd_name_cancellable = NULL; } } static void popup_model_menu_cb (GtkButton *button, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkWidget *spinner; GtkWidget *item; priv = PRINTERS_PANEL_PRIVATE (self); priv->popup_menu = gtk_menu_new (); g_signal_connect (priv->popup_menu, "selection-done", G_CALLBACK (popup_menu_done), user_data); /* * These placeholders are a workaround for a situation * when we want to actually append new menu item in a callback. * But unfortunately it is not possible to connect to "activate" * signal of such menu item (appended after gtk_menu_popup()). */ item = gtk_image_menu_item_new_with_label (""); g_object_set_data_full (G_OBJECT (item), "purpose", g_strdup ("placeholder1"), g_free); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); gtk_widget_set_no_show_all (item, TRUE); gtk_widget_hide (item); item = gtk_image_menu_item_new_with_label (""); g_object_set_data_full (G_OBJECT (item), "purpose", g_strdup ("placeholder2"), g_free); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); gtk_widget_set_no_show_all (item, TRUE); gtk_widget_hide (item); item = gtk_image_menu_item_new_with_label (""); g_object_set_data_full (G_OBJECT (item), "purpose", g_strdup ("placeholder3"), g_free); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); gtk_widget_set_no_show_all (item, TRUE); gtk_widget_hide (item); item = gtk_image_menu_item_new_with_label (_("Searching for preferred drivers...")); spinner = gtk_spinner_new (); gtk_spinner_start (GTK_SPINNER (spinner)); gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), spinner); gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (item), TRUE); g_object_set_data_full (G_OBJECT (item), "purpose", g_strdup ("informal"), g_free); gtk_widget_set_sensitive (item, FALSE); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); gtk_widget_set_no_show_all (item, TRUE); gtk_widget_show (item); item = gtk_separator_menu_item_new (); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); item = gtk_menu_item_new_with_label (_("Select from database...")); g_object_set_data_full (G_OBJECT (item), "purpose", g_strdup ("ppd-select"), g_free); g_signal_connect (item, "activate", G_CALLBACK (select_ppd_in_dialog), self); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); item = gtk_separator_menu_item_new (); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); item = gtk_menu_item_new_with_label (_("Provide PPD File...")); g_object_set_data_full (G_OBJECT (item), "purpose", g_strdup ("ppdfile-select"), g_free); g_signal_connect (item, "activate", G_CALLBACK (select_ppd_manually), self); gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), item); gtk_widget_show_all (priv->popup_menu); gtk_menu_popup (GTK_MENU (priv->popup_menu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time()); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { if (priv->preferred_drivers && g_hash_table_lookup_extended (priv->preferred_drivers, priv->dests[priv->current_dest].name, NULL, NULL)) { get_ppd_names_cb (NULL, priv->dests[priv->current_dest].name, FALSE, user_data); } else { priv->get_ppd_name_cancellable = g_cancellable_new (); priv->getting_ppd_names = TRUE; get_ppd_names_async (priv->dests[priv->current_dest].name, 3, priv->get_ppd_name_cancellable, get_ppd_names_cb, user_data); update_sensitivity (self); } } } static void pp_maintenance_command_execute_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { PpMaintenanceCommand *command = (PpMaintenanceCommand *) source_object; GError *error = NULL; pp_maintenance_command_execute_finish (command, res, &error); g_object_unref (command); } static void test_page_cb (GtkButton *button, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; cups_ptype_t type = 0; const gchar *printer_type = NULL; gchar *printer_name = NULL; gint i; priv = PRINTERS_PANEL_PRIVATE (self); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { printer_name = priv->dests[priv->current_dest].name; printer_type = cupsGetOption ("printer-type", priv->dests[priv->current_dest].num_options, priv->dests[priv->current_dest].options); if (printer_type) type = atoi (printer_type); } if (printer_name) { const gchar *const dirs[] = { "/usr/share/cups", "/usr/local/share/cups", NULL }; const gchar *testprint[] = { "%s/data/testprint", "%s/data/testprint.ps", NULL }; const gchar **pattern; const gchar *datadir = NULL; http_t *http = NULL; gchar *printer_uri = NULL; gchar *filename = NULL; gchar *resource = NULL; ipp_t *response = NULL; ipp_t *request; if ((datadir = getenv ("CUPS_DATADIR")) != NULL) { for (pattern = testprint; *pattern != NULL; pattern++) { filename = g_strdup_printf (*pattern, datadir); if (g_access (filename, R_OK) == 0) break; else { g_free (filename); filename = NULL; } } } else { for (i = 0; (datadir = dirs[i]) != NULL && filename == NULL; i++) { for (pattern = testprint; *pattern != NULL; pattern++) { filename = g_strdup_printf (*pattern, datadir); if (g_access (filename, R_OK) == 0) break; else { g_free (filename); filename = NULL; } } } } if (filename) { if (type & CUPS_PRINTER_CLASS) { printer_uri = g_strdup_printf ("ipp://localhost/classes/%s", printer_name); resource = g_strdup_printf ("/classes/%s", printer_name); } else { printer_uri = g_strdup_printf ("ipp://localhost/printers/%s", printer_name); resource = g_strdup_printf ("/printers/%s", printer_name); } http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ()); if (http) { request = ippNewRequest (IPP_PRINT_JOB); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, /* Translators: Name of job which makes printer to print test page */ "job-name", NULL, _("Test page")); response = cupsDoFileRequest (http, request, resource, filename); httpClose (http); } if (response) { if (ippGetState (response) == IPP_ERROR) g_warning ("An error has occured during printing of test page."); ippDelete (response); } g_free (filename); g_free (printer_uri); g_free (resource); } else { PpMaintenanceCommand *command; command = pp_maintenance_command_new (printer_name, "PrintSelfTestPage", /* Translators: Name of job which makes printer to print test page */ _("Test page")); pp_maintenance_command_execute_async (command, NULL, pp_maintenance_command_execute_cb, self); } } } static void update_sensitivity (gpointer user_data) { CcPrintersPanelPrivate *priv; GtkTreeSelection *selection; CcPrintersPanel *self = (CcPrintersPanel*) user_data; cups_ptype_t type = 0; GtkTreeModel *model; GtkTreeView *treeview; GtkTreeIter tree_iter; const char *cups_server = NULL; GtkWidget *widget; gboolean is_authorized; gboolean is_discovered = FALSE; gboolean is_class = FALSE; gboolean is_changing_driver = FALSE; gboolean printer_selected; gboolean local_server = TRUE; gboolean no_cups = FALSE; gboolean is_new = FALSE; gboolean already_present_local; GList *iter; gchar *current_printer_name = NULL; gint i; priv = PRINTERS_PANEL_PRIVATE (self); is_authorized = priv->permission && g_permission_get_allowed (G_PERMISSION (priv->permission)) && priv->lockdown_settings && !g_settings_get_boolean (priv->lockdown_settings, "disable-print-setup"); printer_selected = priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL; if (printer_selected) { for (i = 0; i < priv->dests[priv->current_dest].num_options; i++) { if (g_strcmp0 (priv->dests[priv->current_dest].options[i].name, "printer-type") == 0) { type = atoi (priv->dests[priv->current_dest].options[i].value); is_discovered = type & CUPS_PRINTER_DISCOVERED; is_class = type & CUPS_PRINTER_CLASS; break; } } for (iter = priv->driver_change_list; iter; iter = iter->next) { SetPPDItem *item = (SetPPDItem *) iter->data; if (g_strcmp0 (item->printer_name, priv->dests[priv->current_dest].name) == 0) { is_changing_driver = TRUE; } } } treeview = (GtkTreeView*) gtk_builder_get_object (priv->builder, "printers-treeview"); selection = gtk_tree_view_get_selection (treeview); if (selection && gtk_tree_selection_get_selected (selection, &model, &tree_iter)) { gtk_tree_model_get (model, &tree_iter, PRINTER_NAME_COLUMN, &current_printer_name, -1); } if (priv->new_printer_name && g_strcmp0 (priv->new_printer_name, current_printer_name) == 0) { printer_selected = TRUE; is_discovered = FALSE; is_class = FALSE; is_new = TRUE; } g_free (current_printer_name); cups_server = cupsServer (); if (cups_server && g_ascii_strncasecmp (cups_server, "localhost", 9) != 0 && g_ascii_strncasecmp (cups_server, "127.0.0.1", 9) != 0 && g_ascii_strncasecmp (cups_server, "::1", 3) != 0 && cups_server[0] != '/') local_server = FALSE; widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "notebook"); if (gtk_notebook_get_current_page (GTK_NOTEBOOK (widget)) == NOTEBOOK_NO_CUPS_PAGE) no_cups = TRUE; already_present_local = local_server && !is_discovered && is_authorized && !is_new; widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-add-button"); gtk_widget_set_sensitive (widget, local_server && is_authorized && !no_cups && !priv->new_printer_name); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-add-button2"); gtk_widget_set_sensitive (widget, local_server && is_authorized && !no_cups && !priv->new_printer_name); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-remove-button"); gtk_widget_set_sensitive (widget, already_present_local && printer_selected && !no_cups); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-disable-switch"); gtk_widget_set_sensitive (widget, already_present_local); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-default-check-button"); gtk_widget_set_sensitive (widget, is_authorized && !is_new); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "print-test-page-button"); gtk_widget_set_sensitive (widget, printer_selected && !is_new); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-options-button"); gtk_widget_set_sensitive (widget, printer_selected && local_server && !is_discovered && !priv->pp_options_dialog && !is_new); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-jobs-button"); gtk_widget_set_sensitive (widget, printer_selected && !is_new); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-icon"); gtk_widget_set_sensitive (widget, printer_selected); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-name-label"); cc_editable_entry_set_editable (CC_EDITABLE_ENTRY (widget), already_present_local); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-location-label"); cc_editable_entry_set_editable (CC_EDITABLE_ENTRY (widget), already_present_local); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-notebook"); if (is_changing_driver) { gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 2); } else { if (already_present_local && !is_class && !priv->getting_ppd_names) gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 0); else gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 1); } } static void on_permission_changed (GPermission *permission, GParamSpec *pspec, gpointer data) { update_sensitivity (data); } static void on_lockdown_settings_changed (GSettings *settings, const char *key, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; if (g_str_equal (key, "disable-print-setup") == FALSE) return; priv = PRINTERS_PANEL_PRIVATE (self); #if 0 /* FIXME */ gtk_widget_set_sensitive (priv->lock_button, !g_settings_get_boolean (priv->lockdown_settings, "disable-print-setup")); #endif on_permission_changed (priv->permission, NULL, user_data); } static void printer_options_response_cb (GtkDialog *dialog, gint response_id, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; priv = PRINTERS_PANEL_PRIVATE (self); pp_options_dialog_free (priv->pp_options_dialog); priv->pp_options_dialog = NULL; update_sensitivity (self); if (response_id == GTK_RESPONSE_OK) actualize_printers_list (self); } static void printer_options_cb (GtkToolButton *toolbutton, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkWidget *widget; gboolean is_authorized; priv = PRINTERS_PANEL_PRIVATE (self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "main-vbox"); is_authorized = priv->permission && g_permission_get_allowed (G_PERMISSION (priv->permission)) && priv->lockdown_settings && !g_settings_get_boolean (priv->lockdown_settings, "disable-print-setup"); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) { priv->pp_options_dialog = pp_options_dialog_new ( GTK_WINDOW (gtk_widget_get_toplevel (widget)), printer_options_response_cb, self, priv->dests[priv->current_dest].name, is_authorized); update_sensitivity (self); } } static gboolean cups_status_check (gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; gboolean result = TRUE; http_t *http; priv = self->priv = PRINTERS_PANEL_PRIVATE (self); http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ()); if (http) { httpClose (http); actualize_printers_list (self); attach_to_cups_notifier (self); priv->cups_status_check_id = 0; result = FALSE; } return result; } static void get_all_ppds_async_cb (PPDList *ppds, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; priv = self->priv = PRINTERS_PANEL_PRIVATE (self); priv->all_ppds_list = ppds; if (priv->pp_ppd_selection_dialog) pp_ppd_selection_dialog_set_ppd_list (priv->pp_ppd_selection_dialog, priv->all_ppds_list); g_object_unref (priv->get_all_ppds_cancellable); priv->get_all_ppds_cancellable = NULL; } static void update_label_padding (GtkWidget *widget, GtkAllocation *allocation, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkAllocation allocation1, allocation2; GtkWidget *label; GtkWidget *sublabel; gint offset; gint pad; priv = PRINTERS_PANEL_PRIVATE (self); sublabel = gtk_bin_get_child (GTK_BIN (widget)); if (sublabel) { gtk_widget_get_allocation (widget, &allocation1); gtk_widget_get_allocation (sublabel, &allocation2); offset = allocation2.x - allocation1.x; label = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-label"); gtk_misc_get_padding (GTK_MISC (label), &pad, NULL); if (offset != pad) gtk_misc_set_padding (GTK_MISC (label), offset, 0); } } static void jobs_dialog_response_cb (GtkDialog *dialog, gint response_id, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; priv = PRINTERS_PANEL_PRIVATE (self); pp_jobs_dialog_free (priv->pp_jobs_dialog); priv->pp_jobs_dialog = NULL; } static void printer_jobs_cb (GtkToolButton *toolbutton, gpointer user_data) { CcPrintersPanelPrivate *priv; CcPrintersPanel *self = (CcPrintersPanel*) user_data; GtkWidget *widget; priv = PRINTERS_PANEL_PRIVATE (self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "main-vbox"); if (priv->current_dest >= 0 && priv->current_dest < priv->num_dests && priv->dests != NULL) priv->pp_jobs_dialog = pp_jobs_dialog_new ( GTK_WINDOW (gtk_widget_get_toplevel (widget)), jobs_dialog_response_cb, self, priv->dests[priv->current_dest].name); } static void cc_printers_panel_init (CcPrintersPanel *self) { CcPrintersPanelPrivate *priv; GtkWidget *top_widget; GtkWidget *widget; GError *error = NULL; http_t *http; gchar *objects[] = { "main-vbox", NULL }; GtkStyleContext *context; guint builder_result; priv = self->priv = PRINTERS_PANEL_PRIVATE (self); /* initialize main data structure */ priv->builder = gtk_builder_new (); priv->dests = NULL; priv->dest_model_names = NULL; priv->ppd_file_names = NULL; priv->num_dests = 0; priv->current_dest = -1; priv->num_jobs = 0; priv->pp_new_printer_dialog = NULL; priv->pp_options_dialog = NULL; priv->subscription_id = 0; priv->cups_status_check_id = 0; priv->subscription_renewal_id = 0; priv->cups_proxy = NULL; priv->cups_bus_connection = NULL; priv->dbus_subscription_id = 0; priv->new_printer_name = NULL; priv->new_printer_location = NULL; priv->new_printer_make_and_model = NULL; priv->new_printer_on_network = FALSE; priv->select_new_printer = FALSE; priv->permission = NULL; priv->lockdown_settings = NULL; priv->getting_ppd_names = FALSE; priv->all_ppds_list = NULL; priv->get_all_ppds_cancellable = NULL; priv->preferred_drivers = NULL; GtkWidget *dummy = cc_editable_entry_new (); /* Needed before UI file is loaded, or else * the custom widget fails to load. */ g_object_ref_sink (dummy); builder_result = gtk_builder_add_objects_from_file (priv->builder, DATADIR"/printers.ui", objects, &error); if (builder_result == 0) { /* Translators: The XML file containing user interface can not be loaded */ g_warning (_("Could not load ui: %s"), error->message); g_error_free (error); return; } /* add the top level widget */ top_widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "main-vbox"); /* connect signals */ widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-add-button"); g_signal_connect (widget, "clicked", G_CALLBACK (printer_add_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-add-button2"); g_signal_connect (widget, "clicked", G_CALLBACK (printer_add_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-remove-button"); g_signal_connect (widget, "clicked", G_CALLBACK (printer_remove_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-disable-switch"); g_signal_connect (widget, "notify::active", G_CALLBACK (printer_disable_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "supply-drawing-area"); g_signal_connect (widget, "draw", G_CALLBACK (supply_levels_draw_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-default-check-button"); g_signal_connect (widget, "toggled", G_CALLBACK (printer_set_default_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "print-test-page-button"); g_signal_connect (widget, "clicked", G_CALLBACK (test_page_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-jobs-button"); g_signal_connect (widget, "clicked", G_CALLBACK (printer_jobs_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-options-button"); g_signal_connect (widget, "clicked", G_CALLBACK (printer_options_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-name-label"); g_signal_connect (widget, "editing-done", G_CALLBACK (printer_name_edit_cb), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-location-label"); g_signal_connect (widget, "editing-done", G_CALLBACK (printer_location_edit_cb), self); priv->lockdown_settings = g_settings_new ("org.gnome.desktop.lockdown"); if (priv->lockdown_settings) g_signal_connect (priv->lockdown_settings, "changed", G_CALLBACK (on_lockdown_settings_changed), self); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-model-button"); g_signal_connect (widget, "clicked", G_CALLBACK (popup_model_menu_cb), self); g_signal_connect (widget, "size-allocate", G_CALLBACK (update_label_padding), self); /* Set junctions */ widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printers-scrolledwindow"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printers-toolbar"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); /* Make model label and ip-address label selectable */ widget = (GtkWidget*) gtk_builder_get_object (priv->builder, "printer-ip-address-label"); cc_editable_entry_set_selectable (CC_EDITABLE_ENTRY (widget), TRUE); /* Add unlock button */ priv->permission = (GPermission *)polkit_permission_new_sync ( "org.opensuse.cupspkhelper.mechanism.all-edit", NULL, NULL, NULL); if (priv->permission != NULL) { g_signal_connect (priv->permission, "notify", G_CALLBACK (on_permission_changed), self); on_permission_changed (priv->permission, NULL, self); } else g_warning ("Your system does not have the cups-pk-helper's policy \ \"org.opensuse.cupspkhelper.mechanism.all-edit\" installed. \ Please check your installation"); gtk_style_context_get_background_color (gtk_widget_get_style_context (top_widget), GTK_STATE_FLAG_NORMAL, &priv->background_color); populate_printers_list (self); attach_to_cups_notifier (self); priv->get_all_ppds_cancellable = g_cancellable_new (); get_all_ppds_async (priv->get_all_ppds_cancellable, get_all_ppds_async_cb, self); http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ()); if (!http) { priv->cups_status_check_id = g_timeout_add_seconds (CUPS_STATUS_CHECK_INTERVAL, cups_status_check, self); } else httpClose (http); gtk_container_add (GTK_CONTAINER (self), top_widget); gtk_widget_show_all (GTK_WIDGET (self)); g_object_unref (dummy); } void cc_printers_panel_register (GIOModule *module) { cc_printers_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_PRINTERS_PANEL, "printers", 0); }
437
./cinnamon-control-center/panels/unused/printers/pp-host.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2012 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Marek Kasik <mkasik@redhat.com> */ #include "pp-host.h" struct _PpHostPrivate { gchar *hostname; gint port; }; G_DEFINE_TYPE (PpHost, pp_host, G_TYPE_OBJECT); enum { PROP_0 = 0, PROP_HOSTNAME, PROP_PORT, }; static void char_clear_pointer (gchar *pointer) { if (pointer) { g_free (pointer); pointer = NULL; } } static void pp_host_finalize (GObject *object) { PpHostPrivate *priv; priv = PP_HOST (object)->priv; char_clear_pointer (priv->hostname); G_OBJECT_CLASS (pp_host_parent_class)->finalize (object); } static void pp_host_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *param_spec) { PpHost *self; self = PP_HOST (object); switch (prop_id) { case PROP_HOSTNAME: g_value_set_string (value, self->priv->hostname); break; case PROP_PORT: g_value_set_int (value, self->priv->port); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, param_spec); break; } } static void pp_host_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *param_spec) { PpHost *self = PP_HOST (object); switch (prop_id) { case PROP_HOSTNAME: g_free (self->priv->hostname); self->priv->hostname = g_value_dup_string (value); break; case PROP_PORT: self->priv->port = g_value_get_int (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, param_spec); break; } } static void pp_host_class_init (PpHostClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (PpHostPrivate)); gobject_class->set_property = pp_host_set_property; gobject_class->get_property = pp_host_get_property; gobject_class->finalize = pp_host_finalize; g_object_class_install_property (gobject_class, PROP_HOSTNAME, g_param_spec_string ("hostname", "Hostname", "The hostname", NULL, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_PORT, g_param_spec_int ("port", "Port", "The port", 0, G_MAXINT32, 631, G_PARAM_READWRITE)); } static void pp_host_init (PpHost *host) { host->priv = G_TYPE_INSTANCE_GET_PRIVATE (host, PP_TYPE_HOST, PpHostPrivate); } PpHost * pp_host_new (const gchar *hostname, gint port) { return g_object_new (PP_TYPE_HOST, "hostname", hostname, "port", port, NULL); } typedef struct { PpDevicesList *devices; } GSDData; static gchar ** line_split (gchar *line) { gboolean escaped = FALSE; gboolean quoted = FALSE; gboolean in_word = FALSE; gchar **words = NULL; gchar **result = NULL; gchar *buffer = NULL; gchar ch; gint n = 0; gint i, j = 0, k = 0; if (line) { n = strlen (line); words = g_new0 (gchar *, n + 1); buffer = g_new0 (gchar, n + 1); for (i = 0; i < n; i++) { ch = line[i]; if (escaped) { buffer[k++] = ch; escaped = FALSE; continue; } if (ch == '\\') { in_word = TRUE; escaped = TRUE; continue; } if (in_word) { if (quoted) { if (ch == '"') quoted = FALSE; else buffer[k++] = ch; } else if (g_ascii_isspace (ch)) { words[j++] = g_strdup (buffer); memset (buffer, 0, n + 1); k = 0; in_word = FALSE; } else if (ch == '"') quoted = TRUE; else buffer[k++] = ch; } else { if (ch == '"') { in_word = TRUE; quoted = TRUE; } else if (!g_ascii_isspace (ch)) { in_word = TRUE; buffer[k++] = ch; } } } } if (buffer && buffer[0] != '\0') words[j++] = g_strdup (buffer); result = g_strdupv (words); g_strfreev (words); g_free (buffer); return result; } static void _pp_host_get_snmp_devices_thread (GSimpleAsyncResult *res, GObject *object, GCancellable *cancellable) { PpHost *host = (PpHost *) object; PpHostPrivate *priv = host->priv; PpPrintDevice *device; GSDData *data; GError *error; gchar **argv; gchar *stdout_string = NULL; gchar *stderr_string = NULL; gint exit_status; data = g_simple_async_result_get_op_res_gpointer (res); data->devices = g_new0 (PpDevicesList, 1); data->devices->devices = NULL; argv = g_new0 (gchar *, 3); argv[0] = g_strdup ("/usr/lib/cups/backend/snmp"); argv[1] = g_strdup (priv->hostname); /* Use SNMP to get printer's informations */ g_spawn_sync (NULL, argv, NULL, 0, NULL, NULL, &stdout_string, &stderr_string, &exit_status, &error); g_free (argv[1]); g_free (argv[0]); g_free (argv); if (exit_status == 0 && stdout_string) { gchar **printer_informations = NULL; gint length; printer_informations = line_split (stdout_string); length = g_strv_length (printer_informations); if (length >= 4) { device = g_new0 (PpPrintDevice, 1); device->device_class = g_strdup (printer_informations[0]); device->device_uri = g_strdup (printer_informations[1]); device->device_make_and_model = g_strdup (printer_informations[2]); device->device_info = g_strdup (printer_informations[3]); device->device_name = g_strdup (printer_informations[3]); device->device_name = g_strcanon (device->device_name, ALLOWED_CHARACTERS, '-'); device->acquisition_method = ACQUISITION_METHOD_SNMP; if (length >= 5 && printer_informations[4][0] != '\0') device->device_id = g_strdup (printer_informations[4]); if (length >= 6 && printer_informations[5][0] != '\0') device->device_location = g_strdup (printer_informations[5]); data->devices->devices = g_list_append (data->devices->devices, device); } g_strfreev (printer_informations); g_free (stdout_string); } } static void gsd_data_free (GSDData *data) { GList *iter; if (data) { if (data->devices) { if (data->devices->devices) { for (iter = data->devices->devices; iter; iter = iter->next) pp_print_device_free ((PpPrintDevice *) iter->data); g_list_free (data->devices->devices); } g_free (data->devices); } g_free (data); } } void pp_host_get_snmp_devices_async (PpHost *host, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *res; GSDData *data; res = g_simple_async_result_new (G_OBJECT (host), callback, user_data, pp_host_get_snmp_devices_async); data = g_new0 (GSDData, 1); data->devices = NULL; g_simple_async_result_set_check_cancellable (res, cancellable); g_simple_async_result_set_op_res_gpointer (res, data, (GDestroyNotify) gsd_data_free); g_simple_async_result_run_in_thread (res, _pp_host_get_snmp_devices_thread, 0, cancellable); g_object_unref (res); } PpDevicesList * pp_host_get_snmp_devices_finish (PpHost *host, GAsyncResult *res, GError **error) { GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res); GSDData *data; PpDevicesList *result; g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == pp_host_get_snmp_devices_async); if (g_simple_async_result_propagate_error (simple, error)) return NULL; data = g_simple_async_result_get_op_res_gpointer (simple); result = data->devices; data->devices = NULL; return result; } static void _pp_host_get_remote_cups_devices_thread (GSimpleAsyncResult *res, GObject *object, GCancellable *cancellable) { cups_dest_t *dests = NULL; GSDData *data; PpHost *host = (PpHost *) object; PpHostPrivate *priv = host->priv; PpPrintDevice *device; http_t *http; gint num_of_devices = 0; gint i; data = g_simple_async_result_get_op_res_gpointer (res); data->devices = g_new0 (PpDevicesList, 1); data->devices->devices = NULL; /* Connect to remote CUPS server and get its devices */ http = httpConnect (priv->hostname, priv->port); if (http) { num_of_devices = cupsGetDests2 (http, &dests); if (num_of_devices > 0) { for (i = 0; i < num_of_devices; i++) { device = g_new0 (PpPrintDevice, 1); device->device_class = g_strdup ("network"); device->device_uri = g_strdup_printf ("ipp://%s:%d/printers/%s", priv->hostname, priv->port, dests[i].name); device->device_name = g_strdup (dests[i].name); device->device_location = g_strdup (cupsGetOption ("printer-location", dests[i].num_options, dests[i].options)); device->host_name = g_strdup (priv->hostname); device->host_port = priv->port; device->acquisition_method = ACQUISITION_METHOD_REMOTE_CUPS_SERVER; data->devices->devices = g_list_append (data->devices->devices, device); } } httpClose (http); } } void pp_host_get_remote_cups_devices_async (PpHost *host, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { GSimpleAsyncResult *res; GSDData *data; res = g_simple_async_result_new (G_OBJECT (host), callback, user_data, pp_host_get_remote_cups_devices_async); data = g_new0 (GSDData, 1); data->devices = NULL; g_simple_async_result_set_check_cancellable (res, cancellable); g_simple_async_result_set_op_res_gpointer (res, data, (GDestroyNotify) gsd_data_free); g_simple_async_result_run_in_thread (res, _pp_host_get_remote_cups_devices_thread, 0, cancellable); g_object_unref (res); } PpDevicesList * pp_host_get_remote_cups_devices_finish (PpHost *host, GAsyncResult *res, GError **error) { GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res); GSDData *data; PpDevicesList *result; g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == pp_host_get_remote_cups_devices_async); if (g_simple_async_result_propagate_error (simple, error)) return NULL; data = g_simple_async_result_get_op_res_gpointer (simple); result = data->devices; data->devices = NULL; return result; }
438
./cinnamon-control-center/panels/network/panel-cell-renderer-security.c
/* -*- Security: C; tab-width: 8; indent-tabs-security: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011 Red Hat, Inc * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "panel-cell-renderer-security.h" enum { PROP_0, PROP_SECURITY, PROP_LAST }; G_DEFINE_TYPE (PanelCellRendererSecurity, panel_cell_renderer_security, GTK_TYPE_CELL_RENDERER_PIXBUF) static gpointer parent_class = NULL; /** * panel_cell_renderer_security_get_property: **/ static void panel_cell_renderer_security_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec) { PanelCellRendererSecurity *renderer = PANEL_CELL_RENDERER_SECURITY (object); switch (param_id) { case PROP_SECURITY: g_value_set_uint (value, renderer->security); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /** * panel_cell_renderer_set_name: **/ static void panel_cell_renderer_set_name (PanelCellRendererSecurity *renderer) { const gchar *icon_name = NULL; if (renderer->security != NM_AP_SEC_UNKNOWN && renderer->security != NM_AP_SEC_NONE) icon_name = "network-wireless-encrypted-symbolic"; if (icon_name != NULL) { g_object_set (renderer, "icon-name", icon_name, NULL); } else { g_object_set (renderer, "icon-name", "", NULL); } } /** * panel_cell_renderer_security_set_property: **/ static void panel_cell_renderer_security_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { PanelCellRendererSecurity *renderer = PANEL_CELL_RENDERER_SECURITY (object); switch (param_id) { case PROP_SECURITY: renderer->security = g_value_get_uint (value); panel_cell_renderer_set_name (renderer); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /** * panel_cell_renderer_finalize: **/ static void panel_cell_renderer_finalize (GObject *object) { PanelCellRendererSecurity *renderer; renderer = PANEL_CELL_RENDERER_SECURITY (object); g_free (renderer->icon_name); G_OBJECT_CLASS (parent_class)->finalize (object); } /** * panel_cell_renderer_security_class_init: **/ static void panel_cell_renderer_security_class_init (PanelCellRendererSecurityClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); object_class->finalize = panel_cell_renderer_finalize; parent_class = g_type_class_peek_parent (class); object_class->get_property = panel_cell_renderer_security_get_property; object_class->set_property = panel_cell_renderer_security_set_property; g_object_class_install_property (object_class, PROP_SECURITY, g_param_spec_uint ("security", NULL, NULL, 0, G_MAXUINT, 0, G_PARAM_READWRITE)); } /** * panel_cell_renderer_security_init: **/ static void panel_cell_renderer_security_init (PanelCellRendererSecurity *renderer) { renderer->security = 0; renderer->icon_name = NULL; } /** * panel_cell_renderer_security_new: **/ GtkCellRenderer * panel_cell_renderer_security_new (void) { return g_object_new (PANEL_TYPE_CELL_RENDERER_SECURITY, NULL); }
439
./cinnamon-control-center/panels/network/net-device.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> #include <arpa/inet.h> #include <netinet/ether.h> #include <nm-device-ethernet.h> #include <nm-device-modem.h> #include <nm-device-wifi.h> #include <nm-device-wimax.h> #include <nm-device-infiniband.h> #include <nm-utils.h> #include "net-device.h" #define NET_DEVICE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_DEVICE, NetDevicePrivate)) struct _NetDevicePrivate { NMDevice *nm_device; guint changed_id; }; enum { PROP_0, PROP_DEVICE, PROP_LAST }; G_DEFINE_TYPE (NetDevice, net_device, NET_TYPE_OBJECT) /* return value must be freed by caller with g_free() */ static gchar * get_mac_address_of_connection (NMConnection *connection) { if (!connection) return NULL; const GByteArray *mac = NULL; /* check the connection type */ if (nm_connection_is_type (connection, NM_SETTING_WIRELESS_SETTING_NAME)) { /* check wireless settings */ NMSettingWireless *s_wireless = nm_connection_get_setting_wireless (connection); if (!s_wireless) return NULL; mac = nm_setting_wireless_get_mac_address (s_wireless); if (mac) return nm_utils_hwaddr_ntoa (mac->data, ARPHRD_ETHER); } else if (nm_connection_is_type (connection, NM_SETTING_WIRED_SETTING_NAME)) { /* check wired settings */ NMSettingWired *s_wired = nm_connection_get_setting_wired (connection); if (!s_wired) return NULL; mac = nm_setting_wired_get_mac_address (s_wired); if (mac) return nm_utils_hwaddr_ntoa (mac->data, ARPHRD_ETHER); } else if (nm_connection_is_type (connection, NM_SETTING_WIMAX_SETTING_NAME)) { /* check wimax settings */ NMSettingWimax *s_wimax = nm_connection_get_setting_wimax (connection); if (!s_wimax) return NULL; mac = nm_setting_wimax_get_mac_address (s_wimax); if (mac) return nm_utils_hwaddr_ntoa (mac->data, ARPHRD_ETHER); } else if (nm_connection_is_type (connection, NM_SETTING_INFINIBAND_SETTING_NAME)) { /* check infiniband settings */ NMSettingInfiniband *s_infiniband = \ nm_connection_get_setting_infiniband (connection); if (!s_infiniband) return NULL; mac = nm_setting_infiniband_get_mac_address (s_infiniband); if (mac) return nm_utils_hwaddr_ntoa (mac->data, ARPHRD_INFINIBAND); } /* no MAC address found */ return NULL; } /* return value must not be freed! */ static const gchar * get_mac_address_of_device (NMDevice *device) { const gchar *mac = NULL; switch (nm_device_get_device_type (device)) { case NM_DEVICE_TYPE_WIFI: { NMDeviceWifi *device_wifi = NM_DEVICE_WIFI (device); mac = nm_device_wifi_get_hw_address (device_wifi); break; } case NM_DEVICE_TYPE_ETHERNET: { NMDeviceEthernet *device_ethernet = NM_DEVICE_ETHERNET (device); mac = nm_device_ethernet_get_hw_address (device_ethernet); break; } case NM_DEVICE_TYPE_WIMAX: { NMDeviceWimax *device_wimax = NM_DEVICE_WIMAX (device); mac = nm_device_wimax_get_hw_address (device_wimax); break; } case NM_DEVICE_TYPE_INFINIBAND: { NMDeviceInfiniband *device_infiniband = \ NM_DEVICE_INFINIBAND (device); mac = nm_device_infiniband_get_hw_address (device_infiniband); break; } default: break; } /* no MAC address found */ return mac; } /* returns TRUE if both MACs are equal */ static gboolean compare_mac_device_with_mac_connection (NMDevice *device, NMConnection *connection) { const gchar *mac_dev = NULL; gchar *mac_conn = NULL; mac_dev = get_mac_address_of_device (device); if (mac_dev != NULL) { mac_conn = get_mac_address_of_connection (connection); if (mac_conn) { /* compare both MACs */ if (g_strcmp0 (mac_dev, mac_conn) == 0) { g_free (mac_conn); return TRUE; } g_free (mac_conn); } } return FALSE; } static GSList * valid_connections_for_device (NMRemoteSettings *remote_settings, NetDevice *device) { GSList *all, *filtered, *iterator, *valid; NMConnection *connection; NMSettingConnection *s_con; all = nm_remote_settings_list_connections (remote_settings); filtered = nm_device_filter_connections (device->priv->nm_device, all); g_slist_free (all); valid = NULL; for (iterator = filtered; iterator; iterator = iterator->next) { connection = iterator->data; s_con = nm_connection_get_setting_connection (connection); if (!s_con) continue; if (nm_setting_connection_get_master (s_con)) continue; valid = g_slist_prepend (valid, connection); } g_slist_free (filtered); return g_slist_reverse (valid); } NMConnection * net_device_get_find_connection (NetDevice *device) { GSList *list, *iterator; NMConnection *connection = NULL; NMActiveConnection *ac; NMRemoteSettings *remote_settings; /* is the device available in a active connection? */ remote_settings = net_object_get_remote_settings (NET_OBJECT (device)); ac = nm_device_get_active_connection (device->priv->nm_device); if (ac) { return (NMConnection*)nm_remote_settings_get_connection_by_path (remote_settings, nm_active_connection_get_connection (ac)); } /* not found in active connections - check all available connections */ list = valid_connections_for_device (remote_settings, device); if (list != NULL) { /* if list has only one connection, use this connection */ if (g_slist_length (list) == 1) { connection = list->data; goto out; } /* is there connection with the MAC address of the device? */ for (iterator = list; iterator; iterator = iterator->next) { connection = iterator->data; if (compare_mac_device_with_mac_connection (device->priv->nm_device, connection)) { goto out; } } } /* no connection found for the given device */ connection = NULL; out: g_slist_free (list); return connection; } static void state_changed_cb (NMDevice *device, NMDeviceState new_state, NMDeviceState old_state, NMDeviceStateReason reason, NetDevice *net_device) { net_object_emit_changed (NET_OBJECT (net_device)); net_object_refresh (NET_OBJECT (net_device)); } NMDevice * net_device_get_nm_device (NetDevice *device) { return device->priv->nm_device; } static void net_device_edit (NetObject *object) { const gchar *uuid; gchar *cmdline; GError *error = NULL; NetDevice *device = NET_DEVICE (object); NMConnection *connection; connection = net_device_get_find_connection (device); uuid = nm_connection_get_uuid (connection); cmdline = g_strdup_printf ("nm-connection-editor --edit %s", uuid); g_debug ("Launching '%s'\n", cmdline); if (!g_spawn_command_line_async (cmdline, &error)) { g_warning ("Failed to launch nm-connection-editor: %s", error->message); g_error_free (error); } g_free (cmdline); } /** * net_device_get_property: **/ static void net_device_get_property (GObject *device_, guint prop_id, GValue *value, GParamSpec *pspec) { NetDevice *net_device = NET_DEVICE (device_); NetDevicePrivate *priv = net_device->priv; switch (prop_id) { case PROP_DEVICE: g_value_set_object (value, priv->nm_device); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (net_device, prop_id, pspec); break; } } /** * net_device_set_property: **/ static void net_device_set_property (GObject *device_, guint prop_id, const GValue *value, GParamSpec *pspec) { NetDevice *net_device = NET_DEVICE (device_); NetDevicePrivate *priv = net_device->priv; switch (prop_id) { case PROP_DEVICE: if (priv->changed_id != 0) { g_signal_handler_disconnect (priv->nm_device, priv->changed_id); } priv->nm_device = g_value_dup_object (value); priv->changed_id = g_signal_connect (priv->nm_device, "state-changed", G_CALLBACK (state_changed_cb), net_device); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (net_device, prop_id, pspec); break; } } static void net_device_finalize (GObject *object) { NetDevice *device = NET_DEVICE (object); NetDevicePrivate *priv = device->priv; if (priv->changed_id != 0) { g_signal_handler_disconnect (priv->nm_device, priv->changed_id); } if (priv->nm_device != NULL) g_object_unref (priv->nm_device); G_OBJECT_CLASS (net_device_parent_class)->finalize (object); } static void net_device_class_init (NetDeviceClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); NetObjectClass *parent_class = NET_OBJECT_CLASS (klass); object_class->finalize = net_device_finalize; object_class->get_property = net_device_get_property; object_class->set_property = net_device_set_property; parent_class->edit = net_device_edit; pspec = g_param_spec_object ("nm-device", NULL, NULL, NM_TYPE_DEVICE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_DEVICE, pspec); g_type_class_add_private (klass, sizeof (NetDevicePrivate)); } static void net_device_init (NetDevice *device) { device->priv = NET_DEVICE_GET_PRIVATE (device); } NetDevice * net_device_new (void) { NetDevice *device; device = g_object_new (NET_TYPE_DEVICE, "removable", FALSE, NULL); return NET_DEVICE (device); }
440
./cinnamon-control-center/panels/network/panel-cell-renderer-signal.c
/* -*- Mode: C; tab-width: 8; indent-tabs-signal: nil; c-basic-offset: 8 -*- * * Copyright (C) 2010 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "panel-cell-renderer-signal.h" enum { PROP_0, PROP_SIGNAL, PROP_LAST }; G_DEFINE_TYPE (PanelCellRendererSignal, panel_cell_renderer_signal, GTK_TYPE_CELL_RENDERER_PIXBUF) static gpointer parent_class = NULL; /** * panel_cell_renderer_signal_get_property: **/ static void panel_cell_renderer_signal_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec) { PanelCellRendererSignal *renderer = PANEL_CELL_RENDERER_SIGNAL (object); switch (param_id) { case PROP_SIGNAL: g_value_set_uint (value, renderer->signal); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /** * panel_cell_renderer_set_name: **/ static void panel_cell_renderer_set_name (PanelCellRendererSignal *renderer) { const gchar *icon_name = NULL; GIcon *icon; /* the 'Other...' entry */ if (renderer->signal <= 0) { g_object_set (renderer, "gicon", NULL, NULL); return; } if (renderer->signal < 20) icon_name = "network-wireless-signal-none-symbolic"; else if (renderer->signal < 40) icon_name = "network-wireless-signal-weak-symbolic"; else if (renderer->signal < 50) icon_name = "network-wireless-signal-ok-symbolic"; else if (renderer->signal < 80) icon_name = "network-wireless-signal-good-symbolic"; else icon_name = "network-wireless-signal-excellent-symbolic"; icon = g_themed_icon_new_with_default_fallbacks (icon_name); g_object_set (renderer, "gicon", icon, NULL); g_object_unref (icon); } /** * panel_cell_renderer_signal_set_property: **/ static void panel_cell_renderer_signal_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { PanelCellRendererSignal *renderer = PANEL_CELL_RENDERER_SIGNAL (object); switch (param_id) { case PROP_SIGNAL: renderer->signal = g_value_get_uint (value); panel_cell_renderer_set_name (renderer); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /** * panel_cell_renderer_finalize: **/ static void panel_cell_renderer_finalize (GObject *object) { PanelCellRendererSignal *renderer; renderer = PANEL_CELL_RENDERER_SIGNAL (object); g_free (renderer->icon_name); G_OBJECT_CLASS (parent_class)->finalize (object); } /** * panel_cell_renderer_signal_class_init: **/ static void panel_cell_renderer_signal_class_init (PanelCellRendererSignalClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); object_class->finalize = panel_cell_renderer_finalize; parent_class = g_type_class_peek_parent (class); object_class->get_property = panel_cell_renderer_signal_get_property; object_class->set_property = panel_cell_renderer_signal_set_property; g_object_class_install_property (object_class, PROP_SIGNAL, g_param_spec_uint ("signal", NULL, NULL, 0, G_MAXUINT, 0, G_PARAM_READWRITE)); } /** * panel_cell_renderer_signal_init: **/ static void panel_cell_renderer_signal_init (PanelCellRendererSignal *renderer) { renderer->signal = 0; renderer->icon_name = NULL; } /** * panel_cell_renderer_signal_new: **/ GtkCellRenderer * panel_cell_renderer_signal_new (void) { return g_object_new (PANEL_TYPE_CELL_RENDERER_SIGNAL, NULL); }
441
./cinnamon-control-center/panels/network/net-device-wired.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011-2012 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> #include <nm-client.h> #include <nm-device.h> #include <nm-device-ethernet.h> #include <nm-remote-connection.h> #include "panel-common.h" #include "net-device-wired.h" #define NET_DEVICE_WIRED_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_DEVICE_WIRED, NetDeviceWiredPrivate)) struct _NetDeviceWiredPrivate { GtkBuilder *builder; gboolean updating_device; }; G_DEFINE_TYPE (NetDeviceWired, net_device_wired, NET_TYPE_DEVICE) static GtkWidget * device_wired_proxy_add_to_notebook (NetObject *object, GtkNotebook *notebook, GtkSizeGroup *heading_size_group) { GtkWidget *widget; GtkWindow *window; NetDeviceWired *device_wired = NET_DEVICE_WIRED (object); /* add widgets to size group */ widget = GTK_WIDGET (gtk_builder_get_object (device_wired->priv->builder, "heading_ipv4")); gtk_size_group_add_widget (heading_size_group, widget); /* reparent */ window = GTK_WINDOW (gtk_builder_get_object (device_wired->priv->builder, "window_tmp")); widget = GTK_WIDGET (gtk_builder_get_object (device_wired->priv->builder, "vbox6")); g_object_ref (widget); gtk_container_remove (GTK_CONTAINER (window), widget); gtk_notebook_append_page (notebook, widget, NULL); g_object_unref (widget); return widget; } static void update_off_switch_from_device_state (GtkSwitch *sw, NMDeviceState state, NetDeviceWired *device_wired) { device_wired->priv->updating_device = TRUE; switch (state) { case NM_DEVICE_STATE_UNMANAGED: case NM_DEVICE_STATE_UNAVAILABLE: case NM_DEVICE_STATE_DISCONNECTED: case NM_DEVICE_STATE_DEACTIVATING: case NM_DEVICE_STATE_FAILED: gtk_switch_set_active (sw, FALSE); break; default: gtk_switch_set_active (sw, TRUE); break; } device_wired->priv->updating_device = FALSE; } static void nm_device_wired_refresh_ui (NetDeviceWired *device_wired) { const char *str; GString *status; GtkWidget *widget; guint speed = 0; NMDevice *nm_device; NMDeviceState state; NetDeviceWiredPrivate *priv = device_wired->priv; /* set device kind */ nm_device = net_device_get_nm_device (NET_DEVICE (device_wired)); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_device")); gtk_label_set_label (GTK_LABEL (widget), panel_device_to_localized_string (nm_device)); /* set up the device on/off switch */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "device_off_switch")); state = nm_device_get_state (nm_device); gtk_widget_set_visible (widget, state != NM_DEVICE_STATE_UNAVAILABLE && state != NM_DEVICE_STATE_UNMANAGED); update_off_switch_from_device_state (GTK_SWITCH (widget), state, device_wired); /* set device state, with status and optionally speed */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_status")); status = g_string_new (panel_device_state_to_localized_string (nm_device)); if (state != NM_DEVICE_STATE_UNAVAILABLE) speed = nm_device_ethernet_get_speed (NM_DEVICE_ETHERNET (nm_device)); if (speed > 0) { g_string_append (status, " - "); /* Translators: network device speed */ g_string_append_printf (status, _("%d Mb/s"), speed); } gtk_label_set_label (GTK_LABEL (widget), status->str); g_string_free (status, TRUE); gtk_widget_set_tooltip_text (widget, panel_device_state_reason_to_localized_string (nm_device)); /* device MAC */ str = nm_device_ethernet_get_hw_address (NM_DEVICE_ETHERNET (nm_device)); panel_set_device_widget_details (priv->builder, "mac", str); /* set IP entries */ panel_set_device_widgets (priv->builder, nm_device); } static void device_wired_refresh (NetObject *object) { NetDeviceWired *device_wired = NET_DEVICE_WIRED (object); nm_device_wired_refresh_ui (device_wired); } static void device_off_toggled (GtkSwitch *sw, GParamSpec *pspec, NetDeviceWired *device_wired) { const gchar *path; const GPtrArray *acs; gboolean active; gint i; NMActiveConnection *a; NMConnection *connection; NMClient *client; if (device_wired->priv->updating_device) return; active = gtk_switch_get_active (sw); if (active) { client = net_object_get_client (NET_OBJECT (device_wired)); connection = net_device_get_find_connection (NET_DEVICE (device_wired)); if (connection == NULL) return; nm_client_activate_connection (client, connection, net_device_get_nm_device (NET_DEVICE (device_wired)), NULL, NULL, NULL); } else { connection = net_device_get_find_connection (NET_DEVICE (device_wired)); if (connection == NULL) return; path = nm_connection_get_path (connection); client = net_object_get_client (NET_OBJECT (device_wired)); acs = nm_client_get_active_connections (client); for (i = 0; i < acs->len; i++) { a = (NMActiveConnection*)acs->pdata[i]; if (strcmp (nm_active_connection_get_connection (a), path) == 0) { nm_client_deactivate_connection (client, a); break; } } } } static void edit_connection (GtkButton *button, NetDeviceWired *device_wired) { net_object_edit (NET_OBJECT (device_wired)); } static void net_device_wired_constructed (GObject *object) { NetDeviceWired *device_wired = NET_DEVICE_WIRED (object); G_OBJECT_CLASS (net_device_wired_parent_class)->constructed (object); nm_device_wired_refresh_ui (device_wired); } static void net_device_wired_finalize (GObject *object) { NetDeviceWired *device_wired = NET_DEVICE_WIRED (object); NetDeviceWiredPrivate *priv = device_wired->priv; g_object_unref (priv->builder); G_OBJECT_CLASS (net_device_wired_parent_class)->finalize (object); } static void net_device_wired_class_init (NetDeviceWiredClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); NetObjectClass *parent_class = NET_OBJECT_CLASS (klass); object_class->finalize = net_device_wired_finalize; object_class->constructed = net_device_wired_constructed; parent_class->add_to_notebook = device_wired_proxy_add_to_notebook; parent_class->refresh = device_wired_refresh; g_type_class_add_private (klass, sizeof (NetDeviceWiredPrivate)); } static void net_device_wired_init (NetDeviceWired *device_wired) { GError *error = NULL; GtkWidget *widget; device_wired->priv = NET_DEVICE_WIRED_GET_PRIVATE (device_wired); device_wired->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (device_wired->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (device_wired->priv->builder, CINNAMONCC_UI_DIR "/network-wired.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } /* setup wired combobox model */ widget = GTK_WIDGET (gtk_builder_get_object (device_wired->priv->builder, "device_off_switch")); g_signal_connect (widget, "notify::active", G_CALLBACK (device_off_toggled), device_wired); widget = GTK_WIDGET (gtk_builder_get_object (device_wired->priv->builder, "button_options")); g_signal_connect (widget, "clicked", G_CALLBACK (edit_connection), device_wired); }
442
./cinnamon-control-center/panels/network/panel-cell-renderer-separator.c
/* -*- Separator: C; tab-width: 8; indent-tabs-separator: nil; c-basic-offset: 8 -*- * * Copyright (C) 2012 Red Hat, Inc. * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Written by Matthias Clasen */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "panel-cell-renderer-separator.h" enum { PROP_0, PROP_DRAW, PROP_LAST }; G_DEFINE_TYPE (PanelCellRendererSeparator, panel_cell_renderer_separator, GTK_TYPE_CELL_RENDERER) static void panel_cell_renderer_separator_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec) { PanelCellRendererSeparator *renderer = PANEL_CELL_RENDERER_SEPARATOR (object); switch (param_id) { case PROP_DRAW: g_value_set_boolean (value, renderer->draw); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } static void panel_cell_renderer_separator_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { PanelCellRendererSeparator *renderer = PANEL_CELL_RENDERER_SEPARATOR (object); switch (param_id) { case PROP_DRAW: renderer->draw = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } static void render (GtkCellRenderer *cell, cairo_t *cr, GtkWidget *widget, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags) { PanelCellRendererSeparator *renderer = PANEL_CELL_RENDERER_SEPARATOR (cell); GtkStyleContext *context; gint x, y, w, h, xpad, ypad; if (!renderer->draw) return; context = gtk_widget_get_style_context (widget); gtk_cell_renderer_get_padding (cell, &xpad, &ypad); x = cell_area->x + xpad; y = cell_area->y + ypad; w = cell_area->width - xpad * 2; h = cell_area->height - ypad * 2; gtk_render_line (context, cr, x + w / 2, y, x + w / 2, y + h - 1); } static void panel_cell_renderer_separator_class_init (PanelCellRendererSeparatorClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); GtkCellRendererClass *cell_renderer_class = GTK_CELL_RENDERER_CLASS (class); object_class->get_property = panel_cell_renderer_separator_get_property; object_class->set_property = panel_cell_renderer_separator_set_property; cell_renderer_class->render = render; g_object_class_install_property (object_class, PROP_DRAW, g_param_spec_boolean ("draw", "draw", "draw", TRUE, G_PARAM_READWRITE)); } static void panel_cell_renderer_separator_init (PanelCellRendererSeparator *renderer) { renderer->draw = TRUE; } GtkCellRenderer * panel_cell_renderer_separator_new (void) { return g_object_new (PANEL_TYPE_CELL_RENDERER_SEPARATOR, NULL); }
443
./cinnamon-control-center/panels/network/panel-common.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2010 Richard Hughes <richard@hughsie.com> * Copyright (C) 2012 Thomas Bechtold <thomasbechtold@jpberlin.de> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include <nm-device-ethernet.h> #include <nm-device-modem.h> #include <nm-utils.h> #include "panel-common.h" /** * panel_device_to_icon_name: **/ const gchar * panel_device_to_icon_name (NMDevice *device) { const gchar *value = NULL; NMDeviceState state; NMDeviceModemCapabilities caps; switch (nm_device_get_device_type (device)) { case NM_DEVICE_TYPE_ETHERNET: state = nm_device_get_state (device); if (state == NM_DEVICE_STATE_UNAVAILABLE) { value = "network-wired-disconnected"; } else { value = "network-wired"; } break; case NM_DEVICE_TYPE_WIFI: case NM_DEVICE_TYPE_BT: case NM_DEVICE_TYPE_OLPC_MESH: value = "network-wireless"; break; case NM_DEVICE_TYPE_MODEM: caps = nm_device_modem_get_current_capabilities (NM_DEVICE_MODEM (device)); if ((caps & NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS) || (caps & NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO)) { value = "network-wireless"; } break; default: break; } return value; } /** * panel_device_to_localized_string: **/ const gchar * panel_device_to_localized_string (NMDevice *device) { const gchar *value = NULL; NMDeviceModemCapabilities caps; switch (nm_device_get_device_type (device)) { case NM_DEVICE_TYPE_UNKNOWN: /* TRANSLATORS: device type */ value = _("Unknown"); break; case NM_DEVICE_TYPE_ETHERNET: /* TRANSLATORS: device type */ value = _("Wired"); break; case NM_DEVICE_TYPE_WIFI: /* TRANSLATORS: device type */ value = _("Wireless"); break; case NM_DEVICE_TYPE_MODEM: caps = nm_device_modem_get_current_capabilities (NM_DEVICE_MODEM (device)); if ((caps & NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS) || (caps & NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO)) { /* TRANSLATORS: device type */ value = _("Mobile broadband"); } break; case NM_DEVICE_TYPE_BT: /* TRANSLATORS: device type */ value = _("Bluetooth"); break; case NM_DEVICE_TYPE_OLPC_MESH: /* TRANSLATORS: device type */ value = _("Mesh"); break; default: break; } return value; } /** * panel_device_to_sortable_string: * * Try to return order of approximate connection speed. * But sort wifi first, since thats the common case. **/ const gchar * panel_device_to_sortable_string (NMDevice *device) { const gchar *value = NULL; NMDeviceModemCapabilities caps; switch (nm_device_get_device_type (device)) { case NM_DEVICE_TYPE_ETHERNET: value = "2"; break; case NM_DEVICE_TYPE_WIFI: value = "1"; break; case NM_DEVICE_TYPE_MODEM: caps = nm_device_modem_get_current_capabilities (NM_DEVICE_MODEM (device)); if ((caps & NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS) || (caps & NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO)) { value = "3"; } break; case NM_DEVICE_TYPE_BT: value = "4"; break; case NM_DEVICE_TYPE_OLPC_MESH: value = "5"; break; default: value = "6"; break; } return value; } /** * panel_ap_mode_to_localized_string: **/ const gchar * panel_ap_mode_to_localized_string (NM80211Mode mode) { const gchar *value = NULL; switch (mode) { case NM_802_11_MODE_UNKNOWN: /* TRANSLATORS: AP type */ value = _("Unknown"); break; case NM_802_11_MODE_ADHOC: /* TRANSLATORS: AP type */ value = _("Ad-hoc"); break; case NM_802_11_MODE_INFRA: /* TRANSLATORS: AP type */ value = _("Infrastructure"); break; default: break; } return value; } /** * panel_device_state_to_localized_string: **/ const gchar * panel_device_state_to_localized_string (NMDevice *device) { NMDeviceType type; NMDeviceState state; type = nm_device_get_device_type (device); state = nm_device_get_state (device); const gchar *value = NULL; switch (state) { case NM_DEVICE_STATE_UNKNOWN: /* TRANSLATORS: device status */ value = _("Status unknown"); break; case NM_DEVICE_STATE_UNMANAGED: /* TRANSLATORS: device status */ value = _("Unmanaged"); break; case NM_DEVICE_STATE_UNAVAILABLE: /* TRANSLATORS: device status */ if (nm_device_get_firmware_missing (device)) value = _("Firmware missing"); else if (type == NM_DEVICE_TYPE_ETHERNET && !nm_device_ethernet_get_carrier (NM_DEVICE_ETHERNET (device))) value = _("Cable unplugged"); else value = _("Unavailable"); break; case NM_DEVICE_STATE_DISCONNECTED: /* TRANSLATORS: device status */ value = _("Disconnected"); break; case NM_DEVICE_STATE_PREPARE: case NM_DEVICE_STATE_CONFIG: case NM_DEVICE_STATE_IP_CONFIG: case NM_DEVICE_STATE_IP_CHECK: /* TRANSLATORS: device status */ value = _("Connecting"); break; case NM_DEVICE_STATE_NEED_AUTH: /* TRANSLATORS: device status */ value = _("Authentication required"); break; case NM_DEVICE_STATE_ACTIVATED: /* TRANSLATORS: device status */ value = _("Connected"); break; case NM_DEVICE_STATE_DEACTIVATING: /* TRANSLATORS: device status */ value = _("Disconnecting"); break; case NM_DEVICE_STATE_FAILED: /* TRANSLATORS: device status */ value = _("Connection failed"); break; default: /* TRANSLATORS: device status */ value = _("Status unknown (missing)"); break; } return value; } /** * panel_vpn_state_to_localized_string: **/ const gchar * panel_vpn_state_to_localized_string (NMVPNConnectionState type) { const gchar *value = NULL; switch (type) { case NM_DEVICE_STATE_UNKNOWN: /* TRANSLATORS: VPN status */ value = _("Status unknown"); break; case NM_VPN_CONNECTION_STATE_PREPARE: case NM_VPN_CONNECTION_STATE_CONNECT: case NM_VPN_CONNECTION_STATE_IP_CONFIG_GET: /* TRANSLATORS: VPN status */ value = _("Connecting"); break; case NM_VPN_CONNECTION_STATE_NEED_AUTH: /* TRANSLATORS: VPN status */ value = _("Authentication required"); break; case NM_VPN_CONNECTION_STATE_ACTIVATED: /* TRANSLATORS: VPN status */ value = _("Connected"); break; case NM_VPN_CONNECTION_STATE_FAILED: /* TRANSLATORS: VPN status */ value = _("Connection failed"); break; case NM_VPN_CONNECTION_STATE_DISCONNECTED: /* TRANSLATORS: VPN status */ value = _("Not connected"); break; default: /* TRANSLATORS: VPN status */ value = _("Status unknown (missing)"); break; } return value; } /** * panel_device_state_reason_to_localized_string: **/ const gchar * panel_device_state_reason_to_localized_string (NMDevice *device) { const gchar *value = NULL; NMDeviceStateReason state_reason; /* we only want the StateReason's we care about */ nm_device_get_state_reason (device, &state_reason); switch (state_reason) { case NM_DEVICE_STATE_REASON_CONFIG_FAILED: /* TRANSLATORS: device status reason */ value = _("Configuration failed"); break; case NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE: /* TRANSLATORS: device status reason */ value = _("IP configuration failed"); break; case NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED: /* TRANSLATORS: device status reason */ value = _("IP configuration expired"); break; case NM_DEVICE_STATE_REASON_NO_SECRETS: /* TRANSLATORS: device status reason */ value = _("Secrets were required, but not provided"); break; case NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT: /* TRANSLATORS: device status reason */ value = _("802.1x supplicant disconnected"); break; case NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED: /* TRANSLATORS: device status reason */ value = _("802.1x supplicant configuration failed"); break; case NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED: /* TRANSLATORS: device status reason */ value = _("802.1x supplicant failed"); break; case NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT: /* TRANSLATORS: device status reason */ value = _("802.1x supplicant took too long to authenticate"); break; case NM_DEVICE_STATE_REASON_PPP_START_FAILED: /* TRANSLATORS: device status reason */ value = _("PPP service failed to start"); break; case NM_DEVICE_STATE_REASON_PPP_DISCONNECT: /* TRANSLATORS: device status reason */ value = _("PPP service disconnected"); break; case NM_DEVICE_STATE_REASON_PPP_FAILED: /* TRANSLATORS: device status reason */ value = _("PPP failed"); break; case NM_DEVICE_STATE_REASON_DHCP_START_FAILED: /* TRANSLATORS: device status reason */ value = _("DHCP client failed to start"); break; case NM_DEVICE_STATE_REASON_DHCP_ERROR: /* TRANSLATORS: device status reason */ value = _("DHCP client error"); break; case NM_DEVICE_STATE_REASON_DHCP_FAILED: /* TRANSLATORS: device status reason */ value = _("DHCP client failed"); break; case NM_DEVICE_STATE_REASON_SHARED_START_FAILED: /* TRANSLATORS: device status reason */ value = _("Shared connection service failed to start"); break; case NM_DEVICE_STATE_REASON_SHARED_FAILED: /* TRANSLATORS: device status reason */ value = _("Shared connection service failed"); break; case NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED: /* TRANSLATORS: device status reason */ value = _("AutoIP service failed to start"); break; case NM_DEVICE_STATE_REASON_AUTOIP_ERROR: /* TRANSLATORS: device status reason */ value = _("AutoIP service error"); break; case NM_DEVICE_STATE_REASON_AUTOIP_FAILED: /* TRANSLATORS: device status reason */ value = _("AutoIP service failed"); break; case NM_DEVICE_STATE_REASON_MODEM_BUSY: /* TRANSLATORS: device status reason */ value = _("Line busy"); break; case NM_DEVICE_STATE_REASON_MODEM_NO_DIAL_TONE: /* TRANSLATORS: device status reason */ value = _("No dial tone"); break; case NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER: /* TRANSLATORS: device status reason */ value = _("No carrier could be established"); break; case NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT: /* TRANSLATORS: device status reason */ value = _("Dialing request timed out"); break; case NM_DEVICE_STATE_REASON_MODEM_DIAL_FAILED: /* TRANSLATORS: device status reason */ value = _("Dialing attempt failed"); break; case NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED: /* TRANSLATORS: device status reason */ value = _("Modem initialization failed"); break; case NM_DEVICE_STATE_REASON_GSM_APN_FAILED: /* TRANSLATORS: device status reason */ value = _("Failed to select the specified APN"); break; case NM_DEVICE_STATE_REASON_GSM_REGISTRATION_NOT_SEARCHING: /* TRANSLATORS: device status reason */ value = _("Not searching for networks"); break; case NM_DEVICE_STATE_REASON_GSM_REGISTRATION_DENIED: /* TRANSLATORS: device status reason */ value = _("Network registration denied"); break; case NM_DEVICE_STATE_REASON_GSM_REGISTRATION_TIMEOUT: /* TRANSLATORS: device status reason */ value = _("Network registration timed out"); break; case NM_DEVICE_STATE_REASON_GSM_REGISTRATION_FAILED: /* TRANSLATORS: device status reason */ value = _("Failed to register with the requested network"); break; case NM_DEVICE_STATE_REASON_GSM_PIN_CHECK_FAILED: /* TRANSLATORS: device status reason */ value = _("PIN check failed"); break; case NM_DEVICE_STATE_REASON_FIRMWARE_MISSING: /* TRANSLATORS: device status reason */ value = _("Firmware for the device may be missing"); break; case NM_DEVICE_STATE_REASON_CONNECTION_REMOVED: /* TRANSLATORS: device status reason */ value = _("Connection disappeared"); break; case NM_DEVICE_STATE_REASON_CARRIER: /* TRANSLATORS: device status reason */ value = _("Carrier/link changed"); break; case NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED: /* TRANSLATORS: device status reason */ value = _("Existing connection was assumed"); break; case NM_DEVICE_STATE_REASON_MODEM_NOT_FOUND: /* TRANSLATORS: device status reason */ value = _("Modem not found"); break; case NM_DEVICE_STATE_REASON_BT_FAILED: /* TRANSLATORS: device status reason */ value = _("Bluetooth connection failed"); break; case NM_DEVICE_STATE_REASON_GSM_SIM_NOT_INSERTED: /* TRANSLATORS: device status reason */ value = _("SIM Card not inserted"); break; case NM_DEVICE_STATE_REASON_GSM_SIM_PIN_REQUIRED: /* TRANSLATORS: device status reason */ value = _("SIM Pin required"); break; case NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED: /* TRANSLATORS: device status reason */ value = _("SIM Puk required"); break; case NM_DEVICE_STATE_REASON_GSM_SIM_WRONG: /* TRANSLATORS: device status reason */ value = _("SIM wrong"); break; case NM_DEVICE_STATE_REASON_INFINIBAND_MODE: /* TRANSLATORS: device status reason */ value = _("InfiniBand device does not support connected mode"); break; case NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED: /* TRANSLATORS: device status reason */ value = _("Connection dependency failed"); break; default: /* no StateReason to show */ value = ""; break; } return value; } gboolean panel_set_device_widget_details (GtkBuilder *builder, const gchar *widget_suffix, const gchar *value) { gchar *heading_id; gchar *label_id; GtkWidget *heading; GtkWidget *widget; /* hide the row if there is no value */ heading_id = g_strdup_printf ("heading_%s", widget_suffix); label_id = g_strdup_printf ("label_%s", widget_suffix); heading = GTK_WIDGET (gtk_builder_get_object (builder, heading_id)); widget = GTK_WIDGET (gtk_builder_get_object (builder, label_id)); if (heading == NULL || widget == NULL) { g_critical ("no widgets %s, %s found", heading_id, label_id); return FALSE; } g_free (heading_id); g_free (label_id); if (value == NULL) { gtk_widget_hide (heading); gtk_widget_hide (widget); } else { /* there exists a value */ gtk_widget_show (heading); gtk_widget_show (widget); gtk_label_set_label (GTK_LABEL (widget), value); } return TRUE; } gboolean panel_set_device_widget_header (GtkBuilder *builder, const gchar *widget_suffix, const gchar *heading) { gchar *label_id = NULL; GtkWidget *widget; label_id = g_strdup_printf ("heading_%s", widget_suffix); widget = GTK_WIDGET (gtk_builder_get_object (builder, label_id)); if (widget == NULL) { g_critical ("no widget %s found", label_id); return FALSE; } gtk_label_set_label (GTK_LABEL (widget), heading); g_free (label_id); return TRUE; } static gchar * get_ipv4_config_address_as_string (NMIP4Config *ip4_config, const char *what) { const GSList *list; struct in_addr addr; gchar *str = NULL; gchar tmp[INET_ADDRSTRLEN]; NMIP4Address *address; /* get address */ list = nm_ip4_config_get_addresses (ip4_config); if (list == NULL) goto out; /* we only care about one address */ address = list->data; if (!strcmp (what, "address")) addr.s_addr = nm_ip4_address_get_address (address); else if (!strcmp (what, "gateway")) addr.s_addr = nm_ip4_address_get_gateway (address); else if (!strcmp (what, "netmask")) addr.s_addr = nm_utils_ip4_prefix_to_netmask (nm_ip4_address_get_prefix (address)); else goto out; if (!inet_ntop (AF_INET, &addr, tmp, sizeof(tmp))) goto out; if (g_strcmp0 (tmp, "0.0.0.0") == 0) goto out; str = g_strdup (tmp); out: return str; } static gchar * get_ipv4_config_name_servers_as_string (NMIP4Config *ip4_config) { const GArray *array; GString *dns; struct in_addr addr; gchar tmp[INET_ADDRSTRLEN]; int i; gchar *str = NULL; array = nm_ip4_config_get_nameservers (ip4_config); if (array == NULL || array->len == 0) goto out; dns = g_string_new (NULL); for (i = 0; i < array->len; i++) { addr.s_addr = g_array_index (array, guint32, i); if (inet_ntop (AF_INET, &addr, tmp, sizeof(tmp))) g_string_append_printf (dns, "%s ", tmp); } str = g_string_free (dns, FALSE); out: return str; } static gchar * get_ipv6_config_address_as_string (NMIP6Config *ip6_config) { const GSList *list; const struct in6_addr *addr; gchar *str = NULL; gchar tmp[INET6_ADDRSTRLEN]; NMIP6Address *address; /* get address */ list = nm_ip6_config_get_addresses (ip6_config); if (list == NULL) goto out; /* we only care about one address */ address = list->data; addr = nm_ip6_address_get_address (address); if (addr == NULL) goto out; inet_ntop (AF_INET6, addr, tmp, sizeof(tmp)); str = g_strdup (tmp); out: return str; } void panel_set_device_widgets (GtkBuilder *builder, NMDevice *device) { NMIP4Config *ip4_config = NULL; NMIP6Config *ip6_config = NULL; gboolean has_ip4; gboolean has_ip6; gchar *str_tmp; /* get IPv4 parameters */ ip4_config = nm_device_get_ip4_config (device); if (ip4_config != NULL) { /* IPv4 address */ str_tmp = get_ipv4_config_address_as_string (ip4_config, "address"); panel_set_device_widget_details (builder, "ipv4", str_tmp); has_ip4 = str_tmp != NULL; g_free (str_tmp); /* IPv4 DNS */ str_tmp = get_ipv4_config_name_servers_as_string (ip4_config); panel_set_device_widget_details (builder, "dns", str_tmp); g_free (str_tmp); /* IPv4 route */ str_tmp = get_ipv4_config_address_as_string (ip4_config, "gateway"); panel_set_device_widget_details (builder, "route", str_tmp); g_free (str_tmp); } else { /* IPv4 address */ panel_set_device_widget_details (builder, "ipv4", NULL); has_ip4 = FALSE; /* IPv4 DNS */ panel_set_device_widget_details (builder, "dns", NULL); /* IPv4 route */ panel_set_device_widget_details (builder, "route", NULL); } /* get IPv6 parameters */ ip6_config = nm_device_get_ip6_config (device); if (ip6_config != NULL) { str_tmp = get_ipv6_config_address_as_string (ip6_config); panel_set_device_widget_details (builder, "ipv6", str_tmp); has_ip6 = str_tmp != NULL; g_free (str_tmp); } else { panel_set_device_widget_details (builder, "ipv6", NULL); has_ip6 = FALSE; } if (has_ip4 && has_ip6) { panel_set_device_widget_header (builder, "ipv4", _("IPv4 Address")); panel_set_device_widget_header (builder, "ipv6", _("IPv6 Address")); } else if (has_ip4) { panel_set_device_widget_header (builder, "ipv4", _("IP Address")); } else if (has_ip6) { panel_set_device_widget_header (builder, "ipv6", _("IP Address")); } } void panel_unset_device_widgets (GtkBuilder *builder) { panel_set_device_widget_details (builder, "ipv4", NULL); panel_set_device_widget_details (builder, "ipv6", NULL); panel_set_device_widget_details (builder, "dns", NULL); panel_set_device_widget_details (builder, "route", NULL); }
444
./cinnamon-control-center/panels/network/panel-cell-renderer-mode.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2010 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "panel-cell-renderer-mode.h" enum { PROP_0, PROP_AP_MODE, PROP_LAST }; G_DEFINE_TYPE (PanelCellRendererMode, panel_cell_renderer_mode, GTK_TYPE_CELL_RENDERER_PIXBUF) static gpointer parent_class = NULL; /** * panel_cell_renderer_mode_get_property: **/ static void panel_cell_renderer_mode_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec) { PanelCellRendererMode *renderer = PANEL_CELL_RENDERER_MODE (object); switch (param_id) { case PROP_AP_MODE: g_value_set_uint (value, renderer->mode); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /** * panel_cell_renderer_set_name: **/ static void panel_cell_renderer_set_name (PanelCellRendererMode *renderer) { const gchar *icon_name = NULL; if (renderer->mode == NM_802_11_MODE_ADHOC) icon_name = "network-workgroup-symbolic"; g_object_set (renderer, "icon-name", icon_name, NULL); } /** * panel_cell_renderer_mode_set_property: **/ static void panel_cell_renderer_mode_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { PanelCellRendererMode *renderer = PANEL_CELL_RENDERER_MODE (object); switch (param_id) { case PROP_AP_MODE: renderer->mode = g_value_get_uint (value); panel_cell_renderer_set_name (renderer); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /** * panel_cell_renderer_finalize: **/ static void panel_cell_renderer_finalize (GObject *object) { PanelCellRendererMode *renderer; renderer = PANEL_CELL_RENDERER_MODE (object); g_free (renderer->icon_name); G_OBJECT_CLASS (parent_class)->finalize (object); } /** * panel_cell_renderer_mode_class_init: **/ static void panel_cell_renderer_mode_class_init (PanelCellRendererModeClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); object_class->finalize = panel_cell_renderer_finalize; parent_class = g_type_class_peek_parent (class); object_class->get_property = panel_cell_renderer_mode_get_property; object_class->set_property = panel_cell_renderer_mode_set_property; g_object_class_install_property (object_class, PROP_AP_MODE, g_param_spec_uint ("ap-mode", NULL, NULL, 0, G_MAXUINT, 0, G_PARAM_READWRITE)); } /** * panel_cell_renderer_mode_init: **/ static void panel_cell_renderer_mode_init (PanelCellRendererMode *renderer) { renderer->mode = 0; renderer->icon_name = NULL; } /** * panel_cell_renderer_mode_new: **/ GtkCellRenderer * panel_cell_renderer_mode_new (void) { return g_object_new (PANEL_TYPE_CELL_RENDERER_MODE, NULL); }
445
./cinnamon-control-center/panels/network/net-device-mobile.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011-2012 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> #include <nm-client.h> #include <nm-device.h> #include <nm-device-modem.h> #include <nm-remote-connection.h> #include "panel-common.h" #include "network-dialogs.h" #include "net-device-mobile.h" #define NET_DEVICE_MOBILE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_DEVICE_MOBILE, NetDeviceMobilePrivate)) static void nm_device_mobile_refresh_ui (NetDeviceMobile *device_mobile); struct _NetDeviceMobilePrivate { GtkBuilder *builder; gboolean updating_device; }; enum { COLUMN_ID, COLUMN_TITLE, COLUMN_LAST }; G_DEFINE_TYPE (NetDeviceMobile, net_device_mobile, NET_TYPE_DEVICE) static GtkWidget * device_mobile_proxy_add_to_notebook (NetObject *object, GtkNotebook *notebook, GtkSizeGroup *heading_size_group) { GtkWidget *widget; GtkWindow *window; NetDeviceMobile *device_mobile = NET_DEVICE_MOBILE (object); /* add widgets to size group */ widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "heading_imei")); gtk_size_group_add_widget (heading_size_group, widget); widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "heading_network")); gtk_size_group_add_widget (heading_size_group, widget); /* reparent */ window = GTK_WINDOW (gtk_builder_get_object (device_mobile->priv->builder, "window_tmp")); widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "vbox7")); g_object_ref (widget); gtk_container_remove (GTK_CONTAINER (window), widget); gtk_notebook_append_page (notebook, widget, NULL); g_object_unref (widget); return widget; } static void connection_activate_cb (NMClient *client, NMActiveConnection *connection, GError *error, gpointer user_data) { NetDeviceMobile *device_mobile = NET_DEVICE_MOBILE (user_data); if (connection == NULL) { /* failed to activate */ nm_device_mobile_refresh_ui (device_mobile); } } static void mobile_connection_changed_cb (GtkComboBox *combo_box, NetDeviceMobile *device_mobile) { gboolean ret; gchar *object_path = NULL; GtkTreeIter iter; GtkTreeModel *model; NMConnection *connection; NMDevice *device; NMClient *client; NMRemoteSettings *remote_settings; CcNetworkPanel *panel; if (device_mobile->priv->updating_device) goto out; ret = gtk_combo_box_get_active_iter (combo_box, &iter); if (!ret) goto out; device = net_device_get_nm_device (NET_DEVICE (device_mobile)); if (device == NULL) goto out; client = net_object_get_client (NET_OBJECT (device_mobile)); remote_settings = net_object_get_remote_settings (NET_OBJECT (device_mobile)); /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX (combo_box)); gtk_tree_model_get (model, &iter, COLUMN_ID, &object_path, -1); if (g_strcmp0 (object_path, NULL) == 0) { panel = net_object_get_panel (NET_OBJECT (device_mobile)); cc_network_panel_connect_to_3g_network (panel, client, remote_settings, device); goto out; } /* activate the connection */ g_debug ("try to switch to connection %s", object_path); connection = (NMConnection*) nm_remote_settings_get_connection_by_path (remote_settings, object_path); if (connection != NULL) { nm_device_disconnect (device, NULL, NULL); nm_client_activate_connection (client, connection, device, NULL, connection_activate_cb, device_mobile); goto out; } out: g_free (object_path); } static void mobilebb_enabled_toggled (NMClient *client, GParamSpec *pspec, NetDeviceMobile *device_mobile) { gboolean enabled; GtkSwitch *sw; NMDevice *device; device = net_device_get_nm_device (NET_DEVICE (device_mobile)); if (nm_device_get_device_type (device) != NM_DEVICE_TYPE_MODEM) return; enabled = nm_client_wwan_get_enabled (client); sw = GTK_SWITCH (gtk_builder_get_object (device_mobile->priv->builder, "device_off_switch")); device_mobile->priv->updating_device = TRUE; gtk_switch_set_active (sw, enabled); device_mobile->priv->updating_device = FALSE; } static void device_add_device_connections (NetDeviceMobile *device_mobile, NMDevice *nm_device, GtkListStore *liststore, GtkComboBox *combobox) { NetDeviceMobilePrivate *priv = device_mobile->priv; GSList *filtered; GSList *list, *l; GtkTreeIter treeiter; NMActiveConnection *active_connection; NMConnection *connection; NMRemoteSettings *remote_settings; /* get the list of available connections for this device */ remote_settings = net_object_get_remote_settings (NET_OBJECT (device_mobile)); g_assert (remote_settings != NULL); list = nm_remote_settings_list_connections (remote_settings); filtered = nm_device_filter_connections (nm_device, list); gtk_list_store_clear (liststore); active_connection = nm_device_get_active_connection (nm_device); for (l = filtered; l; l = g_slist_next (l)) { connection = NM_CONNECTION (l->data); gtk_list_store_append (liststore, &treeiter); gtk_list_store_set (liststore, &treeiter, COLUMN_ID, nm_connection_get_uuid (connection), COLUMN_TITLE, nm_connection_get_id (connection), -1); /* is this already activated? */ if (active_connection != NULL && g_strcmp0 (nm_connection_get_path (connection), nm_active_connection_get_connection (active_connection)) == 0) { priv->updating_device = TRUE; gtk_combo_box_set_active_iter (combobox, &treeiter); priv->updating_device = FALSE; } } /* add new connection entry */ gtk_list_store_append (liststore, &treeiter); gtk_list_store_set (liststore, &treeiter, COLUMN_ID, NULL, COLUMN_TITLE, _("Add new connection"), -1); g_slist_free (list); g_slist_free (filtered); } static void nm_device_mobile_refresh_ui (NetDeviceMobile *device_mobile) { const char *str; gboolean is_connected; GString *status; GtkListStore *liststore; GtkWidget *widget; guint speed = 0; NetDeviceMobilePrivate *priv = device_mobile->priv; NMClient *client; NMDeviceModemCapabilities caps; NMDevice *nm_device; /* set device kind */ nm_device = net_device_get_nm_device (NET_DEVICE (device_mobile)); widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "label_device")); gtk_label_set_label (GTK_LABEL (widget), panel_device_to_localized_string (nm_device)); /* set up the device on/off switch */ widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "device_off_switch")); gtk_widget_show (widget); client = net_object_get_client (NET_OBJECT (device_mobile)); mobilebb_enabled_toggled (client, NULL, device_mobile); /* set device state, with status and optionally speed */ widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "label_status")); status = g_string_new (panel_device_state_to_localized_string (nm_device)); if (speed > 0) { g_string_append (status, " - "); /* Translators: network device speed */ g_string_append_printf (status, _("%d Mb/s"), speed); } gtk_label_set_label (GTK_LABEL (widget), status->str); g_string_free (status, TRUE); gtk_widget_set_tooltip_text (widget, panel_device_state_reason_to_localized_string (nm_device)); /* sensitive for other connection types if the device is currently connected */ widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "button_options")); is_connected = net_device_get_find_connection (NET_DEVICE (device_mobile)) != NULL; gtk_widget_set_sensitive (widget, is_connected); caps = nm_device_modem_get_current_capabilities (NM_DEVICE_MODEM (nm_device)); if ((caps & NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS) || (caps & NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO)) { /* IMEI */ str = g_object_get_data (G_OBJECT (nm_device), "ControlCenter::EquipmentIdentifier"); panel_set_device_widget_details (device_mobile->priv->builder, "imei", str); /* operator name */ str = g_object_get_data (G_OBJECT (nm_device), "ControlCenter::OperatorName"); panel_set_device_widget_details (device_mobile->priv->builder, "provider", str); } /* add possible connections to device */ liststore = GTK_LIST_STORE (gtk_builder_get_object (priv->builder, "liststore_mobile_connections")); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_network")); device_add_device_connections (device_mobile, nm_device, liststore, GTK_COMBO_BOX (widget)); /* set IP entries */ panel_set_device_widgets (priv->builder, nm_device); } static void device_mobile_refresh (NetObject *object) { NetDeviceMobile *device_mobile = NET_DEVICE_MOBILE (object); nm_device_mobile_refresh_ui (device_mobile); } static void device_off_toggled (GtkSwitch *sw, GParamSpec *pspec, NetDeviceMobile *device_mobile) { const gchar *path; const GPtrArray *acs; gboolean active; gint i; NMActiveConnection *a; NMConnection *connection; NMClient *client; if (device_mobile->priv->updating_device) return; active = gtk_switch_get_active (sw); if (active) { client = net_object_get_client (NET_OBJECT (device_mobile)); connection = net_device_get_find_connection (NET_DEVICE (device_mobile)); if (connection == NULL) return; nm_client_activate_connection (client, connection, net_device_get_nm_device (NET_DEVICE (device_mobile)), NULL, NULL, NULL); } else { connection = net_device_get_find_connection (NET_DEVICE (device_mobile)); if (connection == NULL) return; path = nm_connection_get_path (connection); client = net_object_get_client (NET_OBJECT (device_mobile)); acs = nm_client_get_active_connections (client); for (i = 0; i < acs->len; i++) { a = (NMActiveConnection*)acs->pdata[i]; if (strcmp (nm_active_connection_get_connection (a), path) == 0) { nm_client_deactivate_connection (client, a); break; } } } } static void edit_connection (GtkButton *button, NetDeviceMobile *device_mobile) { net_object_edit (NET_OBJECT (device_mobile)); } static void device_mobile_device_got_modem_manager_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; GVariant *result = NULL; GDBusProxy *proxy; NMDevice *device = (NMDevice *) user_data; proxy = g_dbus_proxy_new_for_bus_finish (res, &error); if (proxy == NULL) { g_warning ("Error creating ModemManager proxy: %s", error->message); g_error_free (error); goto out; } /* get the IMEI */ result = g_dbus_proxy_get_cached_property (proxy, "EquipmentIdentifier"); /* save */ g_object_set_data_full (G_OBJECT (device), "ControlCenter::EquipmentIdentifier", g_variant_dup_string (result, NULL), g_free); out: if (result != NULL) g_variant_unref (result); if (proxy != NULL) g_object_unref (proxy); } static void device_mobile_get_registration_info_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { gchar *operator_code = NULL; GError *error = NULL; guint registration_status; GVariant *result = NULL; gchar *operator_name = NULL; gchar *operator_name_safe = NULL; NMDevice *device = (NMDevice *) user_data; result = g_dbus_proxy_call_finish (G_DBUS_PROXY (source_object), res, &error); if (result == NULL) { g_warning ("Error getting registration info: %s\n", error->message); g_error_free (error); return; } /* get values */ g_variant_get (result, "((uss))", &registration_status, &operator_code, &operator_name); if (operator_name != NULL && operator_name[0] != '\0') operator_name_safe = g_strescape (operator_name, NULL); /* save */ g_object_set_data_full (G_OBJECT (device), "ControlCenter::OperatorName", operator_name_safe, g_free); g_free (operator_name); g_free (operator_code); g_variant_unref (result); } static void device_mobile_device_got_modem_manager_gsm_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; GDBusProxy *proxy; NMDevice *device = (NMDevice *) user_data; proxy = g_dbus_proxy_new_for_bus_finish (res, &error); if (proxy == NULL) { g_warning ("Error creating ModemManager GSM proxy: %s\n", error->message); g_error_free (error); goto out; } g_dbus_proxy_call (proxy, "GetRegistrationInfo", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, device_mobile_get_registration_info_cb, device); out: if (proxy != NULL) g_object_unref (proxy); } static void net_device_mobile_constructed (GObject *object) { GCancellable *cancellable; NetDeviceMobile *device_mobile = NET_DEVICE_MOBILE (object); NMClient *client; NMDevice *device; G_OBJECT_CLASS (net_device_mobile_parent_class)->constructed (object); device = net_device_get_nm_device (NET_DEVICE (device_mobile)); cancellable = net_object_get_cancellable (NET_OBJECT (device_mobile)); g_dbus_proxy_new_for_bus (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.ModemManager", nm_device_get_udi (device), "org.freedesktop.ModemManager.Modem", cancellable, device_mobile_device_got_modem_manager_cb, device); g_dbus_proxy_new_for_bus (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.ModemManager", nm_device_get_udi (device), "org.freedesktop.ModemManager.Modem.Gsm.Network", cancellable, device_mobile_device_got_modem_manager_gsm_cb, device); client = net_object_get_client (NET_OBJECT (device_mobile)); g_signal_connect (client, "notify::wwan-enabled", G_CALLBACK (mobilebb_enabled_toggled), device_mobile); nm_device_mobile_refresh_ui (device_mobile); } static void net_device_mobile_finalize (GObject *object) { NetDeviceMobile *device_mobile = NET_DEVICE_MOBILE (object); NetDeviceMobilePrivate *priv = device_mobile->priv; g_object_unref (priv->builder); G_OBJECT_CLASS (net_device_mobile_parent_class)->finalize (object); } static void net_device_mobile_class_init (NetDeviceMobileClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); NetObjectClass *parent_class = NET_OBJECT_CLASS (klass); object_class->finalize = net_device_mobile_finalize; object_class->constructed = net_device_mobile_constructed; parent_class->add_to_notebook = device_mobile_proxy_add_to_notebook; parent_class->refresh = device_mobile_refresh; g_type_class_add_private (klass, sizeof (NetDeviceMobilePrivate)); } static void net_device_mobile_init (NetDeviceMobile *device_mobile) { GError *error = NULL; GtkWidget *widget; GtkCellRenderer *renderer; GtkComboBox *combobox; device_mobile->priv = NET_DEVICE_MOBILE_GET_PRIVATE (device_mobile); device_mobile->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (device_mobile->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (device_mobile->priv->builder, CINNAMONCC_UI_DIR "/network-mobile.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } /* setup mobile combobox model */ combobox = GTK_COMBO_BOX (gtk_builder_get_object (device_mobile->priv->builder, "combobox_network")); g_signal_connect (combobox, "changed", G_CALLBACK (mobile_connection_changed_cb), device_mobile); renderer = gtk_cell_renderer_text_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combobox), renderer, FALSE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combobox), renderer, "text", COLUMN_TITLE, NULL); widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "device_off_switch")); g_signal_connect (widget, "notify::active", G_CALLBACK (device_off_toggled), device_mobile); widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "button_options")); g_signal_connect (widget, "clicked", G_CALLBACK (edit_connection), device_mobile); widget = GTK_WIDGET (gtk_builder_get_object (device_mobile->priv->builder, "device_off_switch")); g_signal_connect (widget, "notify::active", G_CALLBACK (device_off_toggled), device_mobile); }
446
./cinnamon-control-center/panels/network/net-device-wifi.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011-2012 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> //#include <arpa/inet.h> #include <netinet/ether.h> #include <nm-client.h> #include <nm-utils.h> #include <nm-device.h> #include <nm-device-wifi.h> #include <nm-device-ethernet.h> #include <nm-setting-wireless-security.h> #include <nm-remote-connection.h> #include <nm-setting-wireless.h> #include "network-dialogs.h" #include "panel-common.h" #include "panel-cell-renderer-mode.h" #include "panel-cell-renderer-signal.h" #include "panel-cell-renderer-security.h" #include "panel-cell-renderer-separator.h" #include "panel-cell-renderer-text.h" #include "panel-cell-renderer-pixbuf.h" #include "net-device-wifi.h" #define NET_DEVICE_WIFI_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_DEVICE_WIFI, NetDeviceWifiPrivate)) static void nm_device_wifi_refresh_ui (NetDeviceWifi *device_wifi); static void show_wifi_list (NetDeviceWifi *device_wifi); struct _NetDeviceWifiPrivate { GtkBuilder *builder; gboolean updating_device; gchar *selected_ssid_title; gchar *selected_connection_id; gchar *selected_ap_id; }; G_DEFINE_TYPE (NetDeviceWifi, net_device_wifi, NET_TYPE_DEVICE) enum { COLUMN_CONNECTION_ID, COLUMN_ACCESS_POINT_ID, COLUMN_TITLE, COLUMN_SORT, COLUMN_STRENGTH, COLUMN_MODE, COLUMN_SECURITY, COLUMN_ACTIVE, COLUMN_AP_IN_RANGE, COLUMN_AP_OUT_OF_RANGE, COLUMN_AP_IS_SAVED, COLUMN_LAST }; static GtkWidget * device_wifi_proxy_add_to_notebook (NetObject *object, GtkNotebook *notebook, GtkSizeGroup *heading_size_group) { GtkWidget *widget; GtkWindow *window; NetDeviceWifi *device_wifi = NET_DEVICE_WIFI (object); /* add widgets to size group */ widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "heading_ipv4")); gtk_size_group_add_widget (heading_size_group, widget); /* reparent */ window = GTK_WINDOW (gtk_builder_get_object (device_wifi->priv->builder, "window_tmp")); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "notebook_view")); g_object_ref (widget); gtk_container_remove (GTK_CONTAINER (window), widget); gtk_notebook_append_page (notebook, widget, NULL); g_object_unref (widget); return widget; } static guint get_access_point_security (NMAccessPoint *ap) { NM80211ApFlags flags; NM80211ApSecurityFlags wpa_flags; NM80211ApSecurityFlags rsn_flags; guint type; flags = nm_access_point_get_flags (ap); wpa_flags = nm_access_point_get_wpa_flags (ap); rsn_flags = nm_access_point_get_rsn_flags (ap); if (!(flags & NM_802_11_AP_FLAGS_PRIVACY) && wpa_flags == NM_802_11_AP_SEC_NONE && rsn_flags == NM_802_11_AP_SEC_NONE) type = NM_AP_SEC_NONE; else if ((flags & NM_802_11_AP_FLAGS_PRIVACY) && wpa_flags == NM_802_11_AP_SEC_NONE && rsn_flags == NM_802_11_AP_SEC_NONE) type = NM_AP_SEC_WEP; else if (!(flags & NM_802_11_AP_FLAGS_PRIVACY) && wpa_flags != NM_802_11_AP_SEC_NONE && rsn_flags != NM_802_11_AP_SEC_NONE) type = NM_AP_SEC_WPA; else type = NM_AP_SEC_WPA2; return type; } static void add_access_point (NetDeviceWifi *device_wifi, NMAccessPoint *ap, NMAccessPoint *active, NMDevice *device) { const GByteArray *ssid; const gchar *object_path; const gchar *ssid_text; gboolean is_active_ap; gchar *title; GtkListStore *liststore_network; GtkTreeIter treeiter; NetDeviceWifiPrivate *priv = device_wifi->priv; ssid = nm_access_point_get_ssid (ap); if (ssid == NULL) return; ssid_text = nm_utils_escape_ssid (ssid->data, ssid->len); title = g_markup_escape_text (ssid_text, -1); is_active_ap = active && nm_utils_same_ssid (ssid, nm_access_point_get_ssid (active), TRUE); liststore_network = GTK_LIST_STORE (gtk_builder_get_object (priv->builder, "liststore_network")); object_path = nm_object_get_path (NM_OBJECT (ap)); gtk_list_store_insert_with_values (liststore_network, &treeiter, -1, COLUMN_ACCESS_POINT_ID, object_path, COLUMN_TITLE, title, COLUMN_SORT, ssid_text, COLUMN_STRENGTH, nm_access_point_get_strength (ap), COLUMN_MODE, nm_access_point_get_mode (ap), COLUMN_SECURITY, get_access_point_security (ap), COLUMN_ACTIVE, is_active_ap, COLUMN_AP_IN_RANGE, TRUE, COLUMN_AP_OUT_OF_RANGE, FALSE, COLUMN_AP_IS_SAVED, FALSE, -1); g_free (title); } static GPtrArray * panel_get_strongest_unique_aps (const GPtrArray *aps) { const GByteArray *ssid; const GByteArray *ssid_tmp; GPtrArray *aps_unique = NULL; gboolean add_ap; guint i; guint j; NMAccessPoint *ap; NMAccessPoint *ap_tmp; /* we will have multiple entries for typical hotspots, just * filter to the one with the strongest signal */ aps_unique = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref); if (aps != NULL) for (i = 0; i < aps->len; i++) { ap = NM_ACCESS_POINT (g_ptr_array_index (aps, i)); /* Hidden SSIDs don't get shown in the list */ ssid = nm_access_point_get_ssid (ap); if (!ssid) continue; add_ap = TRUE; /* get already added list */ for (j=0; j<aps_unique->len; j++) { ap_tmp = NM_ACCESS_POINT (g_ptr_array_index (aps_unique, j)); ssid_tmp = nm_access_point_get_ssid (ap_tmp); g_assert (ssid_tmp); /* is this the same type and data? */ if (nm_utils_same_ssid (ssid, ssid_tmp, TRUE)) { g_debug ("found duplicate: %s", nm_utils_escape_ssid (ssid_tmp->data, ssid_tmp->len)); /* the new access point is stronger */ if (nm_access_point_get_strength (ap) > nm_access_point_get_strength (ap_tmp)) { g_debug ("removing %s", nm_utils_escape_ssid (ssid_tmp->data, ssid_tmp->len)); g_ptr_array_remove (aps_unique, ap_tmp); add_ap = TRUE; } else { add_ap = FALSE; } break; } } if (add_ap) { g_debug ("adding %s", nm_utils_escape_ssid (ssid->data, ssid->len)); g_ptr_array_add (aps_unique, g_object_ref (ap)); } } return aps_unique; } static gchar * get_ap_security_string (NMAccessPoint *ap) { NM80211ApSecurityFlags wpa_flags, rsn_flags; NM80211ApFlags flags; GString *str; flags = nm_access_point_get_flags (ap); wpa_flags = nm_access_point_get_wpa_flags (ap); rsn_flags = nm_access_point_get_rsn_flags (ap); str = g_string_new (""); if ((flags & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_flags == NM_802_11_AP_SEC_NONE) && (rsn_flags == NM_802_11_AP_SEC_NONE)) { /* TRANSLATORS: this WEP WiFi security */ g_string_append_printf (str, "%s, ", _("WEP")); } if (wpa_flags != NM_802_11_AP_SEC_NONE) { /* TRANSLATORS: this WPA WiFi security */ g_string_append_printf (str, "%s, ", _("WPA")); } if (rsn_flags != NM_802_11_AP_SEC_NONE) { /* TRANSLATORS: this WPA WiFi security */ g_string_append_printf (str, "%s, ", _("WPA2")); } if ((wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { /* TRANSLATORS: this Enterprise WiFi security */ g_string_append_printf (str, "%s, ", _("Enterprise")); } if (str->len > 0) g_string_set_size (str, str->len - 2); else { g_string_append (str, C_("Wifi security", "None")); } return g_string_free (str, FALSE); } static void wireless_enabled_toggled (NMClient *client, GParamSpec *pspec, NetDeviceWifi *device_wifi) { gboolean enabled; GtkSwitch *sw; NMDevice *device; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); if (nm_device_get_device_type (device) != NM_DEVICE_TYPE_WIFI) return; enabled = nm_client_wireless_get_enabled (client); sw = GTK_SWITCH (gtk_builder_get_object (device_wifi->priv->builder, "device_off_switch")); device_wifi->priv->updating_device = TRUE; gtk_switch_set_active (sw, enabled); device_wifi->priv->updating_device = FALSE; } #if 0 static void update_off_switch_from_device_state (GtkSwitch *sw, NMDeviceState state, NetDeviceWifi *device_wifi) { device_wifi->priv->updating_device = TRUE; switch (state) { case NM_DEVICE_STATE_UNMANAGED: case NM_DEVICE_STATE_UNAVAILABLE: case NM_DEVICE_STATE_DISCONNECTED: case NM_DEVICE_STATE_DEACTIVATING: case NM_DEVICE_STATE_FAILED: gtk_switch_set_active (sw, FALSE); break; default: gtk_switch_set_active (sw, TRUE); break; } device_wifi->priv->updating_device = FALSE; } #endif static NMConnection * find_connection_for_device (NetDeviceWifi *device_wifi, NMDevice *device) { NetDevice *tmp; NMConnection *connection; NMRemoteSettings *remote_settings; NMClient *client; client = net_object_get_client (NET_OBJECT (device_wifi)); remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); tmp = g_object_new (NET_TYPE_DEVICE, "client", client, "remote-settings", remote_settings, "nm-device", device, NULL); connection = net_device_get_find_connection (tmp); g_object_unref (tmp); return connection; } static gboolean connection_is_shared (NMConnection *c) { NMSettingIP4Config *s_ip4; s_ip4 = nm_connection_get_setting_ip4_config (c); if (g_strcmp0 (nm_setting_ip4_config_get_method (s_ip4), NM_SETTING_IP4_CONFIG_METHOD_SHARED) != 0) { return FALSE; } return TRUE; } static gboolean device_is_hotspot (NetDeviceWifi *device_wifi) { NMConnection *c; NMDevice *device; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); c = find_connection_for_device (device_wifi, device); if (c == NULL) return FALSE; return connection_is_shared (c); } static const GByteArray * device_get_hotspot_ssid (NetDeviceWifi *device_wifi, NMDevice *device) { NMConnection *c; NMSettingWireless *sw; c = find_connection_for_device (device_wifi, device); if (c == NULL) { return FALSE; } sw = nm_connection_get_setting_wireless (c); return nm_setting_wireless_get_ssid (sw); } static void get_secrets_cb (NMRemoteConnection *c, GHashTable *secrets, GError *error, gpointer data) { NetDeviceWifi *device_wifi = data; NMSettingWireless *sw; sw = nm_connection_get_setting_wireless (NM_CONNECTION (c)); nm_connection_update_secrets (NM_CONNECTION (c), nm_setting_wireless_get_security (sw), secrets, NULL); nm_device_wifi_refresh_ui (device_wifi); } static void device_get_hotspot_security_details (NetDeviceWifi *device_wifi, NMDevice *device, gchar **secret, gchar **security) { NMConnection *c; NMSettingWireless *sw; NMSettingWirelessSecurity *sws; const gchar *key_mgmt; const gchar *tmp_secret; const gchar *tmp_security; c = find_connection_for_device (device_wifi, device); if (c == NULL) return; sw = nm_connection_get_setting_wireless (c); sws = nm_connection_get_setting_wireless_security (c); if (sw == NULL || sws == NULL) return; tmp_secret = NULL; tmp_security = C_("Wifi security", "None"); key_mgmt = nm_setting_wireless_security_get_key_mgmt (sws); if (strcmp (key_mgmt, "none") == 0) { tmp_secret = nm_setting_wireless_security_get_wep_key (sws, 0); tmp_security = _("WEP"); } else if (strcmp (key_mgmt, "wpa-none") == 0) { tmp_secret = nm_setting_wireless_security_get_psk (sws); tmp_security = _("WPA"); } else { g_warning ("unhandled security key-mgmt: %s", key_mgmt); } /* If we don't have secrets, request them from NM and bail. * We'll refresh the UI when secrets arrive. */ if (tmp_secret == NULL) { nm_remote_connection_get_secrets ((NMRemoteConnection*)c, nm_setting_wireless_get_security (sw), get_secrets_cb, device_wifi); return; } if (secret) *secret = g_strdup (tmp_secret); if (security) *security = g_strdup (tmp_security); } static void device_wifi_refresh_aps (NetDeviceWifi *device_wifi) { const GPtrArray *aps; GPtrArray *aps_unique = NULL; GtkListStore *liststore_network; guint i; NMAccessPoint *active_ap; NMAccessPoint *ap; NMDevice *nm_device; /* populate access points */ liststore_network = GTK_LIST_STORE (gtk_builder_get_object (device_wifi->priv->builder, "liststore_network")); device_wifi->priv->updating_device = TRUE; gtk_list_store_clear (liststore_network); nm_device = net_device_get_nm_device (NET_DEVICE (device_wifi)); aps = nm_device_wifi_get_access_points (NM_DEVICE_WIFI (nm_device)); aps_unique = panel_get_strongest_unique_aps (aps); active_ap = nm_device_wifi_get_active_access_point (NM_DEVICE_WIFI (nm_device)); for (i = 0; i < aps_unique->len; i++) { ap = NM_ACCESS_POINT (g_ptr_array_index (aps_unique, i)); add_access_point (device_wifi, ap, active_ap, nm_device); } device_wifi->priv->updating_device = FALSE; g_ptr_array_unref (aps_unique); } static gboolean find_ssid_in_store (GtkTreeModel *model, GtkTreeIter *iter, const gchar *ssid) { gboolean found; gchar *sort; found = gtk_tree_model_get_iter_first (model, iter); while (found) { gtk_tree_model_get (model, iter, COLUMN_SORT, &sort, -1); if (g_strcmp0 (ssid, sort) == 0) { g_free (sort); return TRUE; } g_free (sort); found = gtk_tree_model_iter_next (model, iter); } return FALSE; } static void add_saved_connection (NetDeviceWifi *device_wifi, NMConnection *connection, NMDevice *nm_device) { const GByteArray *ssid; const gchar *id; const gchar *ssid_text; gchar *title; GtkListStore *store; GtkTreeIter iter; NMSetting *setting; setting = nm_connection_get_setting_by_name (connection, NM_SETTING_WIRELESS_SETTING_NAME); if (setting == NULL) return; ssid = nm_setting_wireless_get_ssid (NM_SETTING_WIRELESS (setting)); ssid_text = nm_utils_escape_ssid (ssid->data, ssid->len); title = g_markup_escape_text (ssid_text, -1); g_debug ("got saved %s", title); id = nm_connection_get_path (connection); store = GTK_LIST_STORE (gtk_builder_get_object (device_wifi->priv->builder, "liststore_network")); if (find_ssid_in_store (GTK_TREE_MODEL (store), &iter, ssid_text)) gtk_list_store_set (store, &iter, COLUMN_CONNECTION_ID, id, COLUMN_AP_IS_SAVED, TRUE, -1); else gtk_list_store_insert_with_values (store, &iter, -1, COLUMN_CONNECTION_ID, id, COLUMN_TITLE, title, COLUMN_SORT, ssid_text, COLUMN_STRENGTH, 0, COLUMN_MODE, 0, COLUMN_SECURITY, 0, COLUMN_ACTIVE, FALSE, COLUMN_AP_IN_RANGE, FALSE, COLUMN_AP_OUT_OF_RANGE, TRUE, COLUMN_AP_IS_SAVED, TRUE, -1); g_free (title); } static void device_wifi_refresh_saved_connections (NetDeviceWifi *device_wifi) { GSList *connections; GSList *filtered; GSList *l; NMDevice *nm_device; NMRemoteSettings *remote_settings; /* add stored connections */ device_wifi->priv->updating_device = TRUE; remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); connections = nm_remote_settings_list_connections (remote_settings); nm_device = net_device_get_nm_device (NET_DEVICE (device_wifi)); filtered = nm_device_filter_connections (nm_device, connections); for (l = filtered; l; l = l->next) { NMConnection *connection = l->data; if (!connection_is_shared (connection)) add_saved_connection (device_wifi, connection, nm_device); } device_wifi->priv->updating_device = FALSE; g_slist_free (connections); g_slist_free (filtered); } static void nm_device_wifi_refresh_hotspot (NetDeviceWifi *device_wifi) { const GByteArray *ssid; gchar *hotspot_secret = NULL; gchar *hotspot_security = NULL; gchar *hotspot_ssid = NULL; NMDevice *nm_device; /* refresh hotspot ui */ nm_device = net_device_get_nm_device (NET_DEVICE (device_wifi)); ssid = device_get_hotspot_ssid (device_wifi, nm_device); if (ssid) hotspot_ssid = nm_utils_ssid_to_utf8 (ssid); device_get_hotspot_security_details (device_wifi, nm_device, &hotspot_secret, &hotspot_security); panel_set_device_widget_details (device_wifi->priv->builder, "hotspot_network_name", hotspot_ssid); panel_set_device_widget_details (device_wifi->priv->builder, "hotspot_security_key", hotspot_secret); panel_set_device_widget_details (device_wifi->priv->builder, "hotspot_security", hotspot_security); panel_set_device_widget_details (device_wifi->priv->builder, "hotspot_connected", NULL); g_free (hotspot_secret); g_free (hotspot_security); g_free (hotspot_ssid); } static void update_last_used (NetDeviceWifi *device_wifi) { NetDeviceWifiPrivate *priv = device_wifi->priv; gchar *last_used = NULL; GDateTime *now = NULL; GDateTime *then = NULL; gint days; GTimeSpan diff; guint64 timestamp; NMRemoteConnection *connection; NMRemoteSettings *settings; NMSettingConnection *s_con; if (priv->selected_connection_id == NULL) goto out; settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); connection = nm_remote_settings_get_connection_by_path (settings, priv->selected_connection_id); s_con = nm_connection_get_setting_connection (NM_CONNECTION (connection)); if (s_con == NULL) goto out; timestamp = nm_setting_connection_get_timestamp (s_con); if (timestamp == 0) { last_used = g_strdup (_("never")); goto out; } /* calculate the amount of time that has elapsed */ now = g_date_time_new_now_utc (); then = g_date_time_new_from_unix_utc (timestamp); diff = g_date_time_difference (now, then); days = diff / G_TIME_SPAN_DAY; if (days == 0) last_used = g_strdup (_("today")); else if (days == 1) last_used = g_strdup (_("yesterday")); else last_used = g_strdup_printf (ngettext ("%i day ago", "%i days ago", days), days); out: panel_set_device_widget_details (device_wifi->priv->builder, "last_used", last_used); if (now != NULL) g_date_time_unref (now); if (then != NULL) g_date_time_unref (then); g_free (last_used); } static void nm_device_wifi_refresh_ui (NetDeviceWifi *device_wifi) { const gchar *str; gboolean is_hotspot; gchar *str_tmp = NULL; GtkWidget *widget; gint strength = 0; guint speed = 0; NMAccessPoint *active_ap; NMDevice *nm_device; NMDeviceState state; NMClient *client; NMAccessPoint *ap; NetDeviceWifiPrivate *priv = device_wifi->priv; is_hotspot = device_is_hotspot (device_wifi); if (is_hotspot) { nm_device_wifi_refresh_hotspot (device_wifi); return; } nm_device = net_device_get_nm_device (NET_DEVICE (device_wifi)); if (priv->selected_ap_id) { ap = nm_device_wifi_get_access_point_by_path (NM_DEVICE_WIFI (nm_device), priv->selected_ap_id); } else { ap = NULL; } active_ap = nm_device_wifi_get_active_access_point (NM_DEVICE_WIFI (nm_device)); state = nm_device_get_state (nm_device); /* keep this in sync with the signal handler setup in cc_network_panel_init */ client = net_object_get_client (NET_OBJECT (device_wifi)); wireless_enabled_toggled (client, NULL, device_wifi); if (ap != active_ap) speed = 0; else if (state != NM_DEVICE_STATE_UNAVAILABLE) speed = nm_device_wifi_get_bitrate (NM_DEVICE_WIFI (nm_device)); speed /= 1000; if (speed > 0) { /* Translators: network device speed */ str_tmp = g_strdup_printf (_("%d Mb/s"), speed); } panel_set_device_widget_details (device_wifi->priv->builder, "speed", str_tmp); /* set device state, with status and optionally speed */ widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "label_status")); if (ap != active_ap) { if (ap) gtk_label_set_label (GTK_LABEL (widget), _("Not connected")); else gtk_label_set_label (GTK_LABEL (widget), _("Out of range")); gtk_widget_set_tooltip_text (widget, ""); } else { gtk_label_set_label (GTK_LABEL (widget), panel_device_state_to_localized_string (nm_device)); gtk_widget_set_tooltip_text (widget, panel_device_state_reason_to_localized_string (nm_device)); } /* device MAC */ str = nm_device_wifi_get_hw_address (NM_DEVICE_WIFI (nm_device)); panel_set_device_widget_details (device_wifi->priv->builder, "mac", str); /* security */ if (ap != active_ap) str_tmp = NULL; else if (active_ap != NULL) str_tmp = get_ap_security_string (active_ap); panel_set_device_widget_details (device_wifi->priv->builder, "security", str_tmp); g_free (str_tmp); /* signal strength */ if (ap != NULL) strength = nm_access_point_get_strength (ap); else strength = 0; if (strength <= 0) str = NULL; else if (strength < 20) str = C_("Signal strength", "None"); else if (strength < 40) str = C_("Signal strength", "Weak"); else if (strength < 50) str = C_("Signal strength", "Ok"); else if (strength < 80) str = C_("Signal strength", "Good"); else str = C_("Signal strength", "Excellent"); panel_set_device_widget_details (device_wifi->priv->builder, "strength", str); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "label_device")); gtk_label_set_label (GTK_LABEL (widget), priv->selected_ssid_title ? priv->selected_ssid_title : panel_device_to_localized_string (nm_device)); /* only disconnect when connection active */ if (ap == active_ap) { widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_disconnect1")); gtk_widget_set_sensitive (widget, state == NM_DEVICE_STATE_ACTIVATED); gtk_widget_show (widget); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_connect1")); gtk_widget_hide (widget); } else { widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_disconnect1")); gtk_widget_hide (widget); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_connect1")); gtk_widget_show (widget); gtk_widget_set_sensitive (widget, ap != NULL); } /* device MAC */ if (ap != active_ap) str = NULL; else str = nm_device_wifi_get_hw_address (NM_DEVICE_WIFI (nm_device)); panel_set_device_widget_details (priv->builder, "mac", str); /* set IP entries */ if (ap != active_ap) panel_unset_device_widgets (priv->builder); else panel_set_device_widgets (priv->builder, nm_device); if (ap != active_ap) update_last_used (device_wifi); else panel_set_device_widget_details (priv->builder, "last_used", NULL); /* update list of APs */ device_wifi_refresh_aps (device_wifi); device_wifi_refresh_saved_connections (device_wifi); } static void device_wifi_refresh (NetObject *object) { NetDeviceWifi *device_wifi = NET_DEVICE_WIFI (object); nm_device_wifi_refresh_ui (device_wifi); } static void device_off_toggled (GtkSwitch *sw, GParamSpec *pspec, NetDeviceWifi *device_wifi) { NMClient *client; gboolean active; if (device_wifi->priv->updating_device) return; client = net_object_get_client (NET_OBJECT (device_wifi)); active = gtk_switch_get_active (sw); nm_client_wireless_set_enabled (client, active); } static gboolean find_connection_id_in_store (GtkTreeModel *model, GtkTreeIter *iter, const gchar *connection_id) { gboolean found; gchar *id; found = gtk_tree_model_get_iter_first (model, iter); while (found) { gtk_tree_model_get (model, iter, COLUMN_CONNECTION_ID, &id, -1); if (g_strcmp0 (connection_id, id) == 0) { g_free (id); return TRUE; } g_free (id); found = gtk_tree_model_iter_next (model, iter); } return FALSE; } static void forget_network_connection_delete_cb (NMRemoteConnection *connection, GError *error, gpointer user_data) { gboolean ret; GtkTreeIter iter; GtkTreeModel *model; GtkTreeView *treeview; NetDeviceWifi *device_wifi = NET_DEVICE_WIFI (user_data); if (error != NULL) { g_warning ("failed to delete connection %s: %s", nm_object_get_path (NM_OBJECT (connection)), error->message); return; } /* remove the entry from the list */ treeview = GTK_TREE_VIEW (gtk_builder_get_object (device_wifi->priv->builder, "treeview_list")); model = gtk_tree_view_get_model (treeview); ret = find_connection_id_in_store (model, &iter, device_wifi->priv->selected_connection_id); if (ret) gtk_list_store_remove (GTK_LIST_STORE (model), &iter); show_wifi_list (device_wifi); } static void forget_network_response_cb (GtkWidget *dialog, gint response, NetDeviceWifi *device_wifi) { NMRemoteConnection *connection; NMRemoteSettings *remote_settings; if (response != GTK_RESPONSE_OK) goto out; remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); connection = nm_remote_settings_get_connection_by_path (remote_settings, device_wifi->priv->selected_connection_id); if (connection == NULL) { g_warning ("failed to get remote connection"); goto out; } /* delete the connection */ g_debug ("deleting %s", device_wifi->priv->selected_connection_id); nm_remote_connection_delete (connection, forget_network_connection_delete_cb, device_wifi); out: gtk_widget_destroy (dialog); } static void disconnect_button_clicked_cb (GtkButton *button, NetDeviceWifi *device_wifi) { NMDevice *device; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); if (device == NULL) return; nm_device_disconnect (device, NULL, NULL); } static void activate_connection (NetDeviceWifi *device, const gchar *id); static void connect_button_clicked_cb (GtkButton *button, NetDeviceWifi *device_wifi) { if (device_wifi->priv->selected_connection_id) activate_connection (device_wifi, device_wifi->priv->selected_connection_id); } static void forget_button_clicked_cb (GtkButton *button, NetDeviceWifi *device_wifi) { gchar *ssid_pretty = NULL; gchar *warning = NULL; GtkWidget *dialog; GtkWidget *window; CcNetworkPanel *panel; ssid_pretty = g_strdup_printf ("<b>%s</b>", device_wifi->priv->selected_ssid_title); warning = g_strdup_printf (_("Network details for %s including password and any custom configuration will be lost."), ssid_pretty); panel = net_object_get_panel (NET_OBJECT (device_wifi)); window = gtk_widget_get_toplevel (GTK_WIDGET (panel)); dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, NULL); gtk_message_dialog_set_markup (GTK_MESSAGE_DIALOG (dialog), warning); gtk_dialog_add_buttons (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, _("Forget"), GTK_RESPONSE_OK, NULL); g_signal_connect (dialog, "response", G_CALLBACK (forget_network_response_cb), device_wifi); gtk_window_present (GTK_WINDOW (dialog)); g_free (ssid_pretty); g_free (warning); } static void connect_to_hidden_network (NetDeviceWifi *device_wifi) { NMRemoteSettings *remote_settings; NMClient *client; CcNetworkPanel *panel; remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); client = net_object_get_client (NET_OBJECT (device_wifi)); panel = net_object_get_panel (NET_OBJECT (device_wifi)); cc_network_panel_connect_to_hidden_network (panel, client, remote_settings); } static void connection_add_activate_cb (NMClient *client, NMActiveConnection *connection, const char *path, GError *error, gpointer user_data) { NetDeviceWifi *device_wifi = user_data; if (connection == NULL) { /* failed to activate */ g_debug ("Failed to add and activate connection '%d': %s", error->code, error->message); nm_device_wifi_refresh_ui (device_wifi); } } static void connection_activate_cb (NMClient *client, NMActiveConnection *connection, GError *error, gpointer user_data) { NetDeviceWifi *device_wifi = user_data; if (connection == NULL) { /* failed to activate */ g_debug ("Failed to activate connection '%d': %s", error->code, error->message); nm_device_wifi_refresh_ui (device_wifi); } } static void activate_connection (NetDeviceWifi *device_wifi, const gchar *connection_id) { NMDevice *device; NMClient *client; NMRemoteSettings *settings; NMRemoteConnection *connection; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); client = net_object_get_client (NET_OBJECT (device_wifi)); settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); connection = nm_remote_settings_get_connection_by_path (settings, connection_id); nm_client_activate_connection (client, NM_CONNECTION (connection), device, NULL, connection_activate_cb, device_wifi); } static gboolean is_8021x (NMDevice *device, const char *ap_object_path) { NM80211ApSecurityFlags wpa_flags, rsn_flags; NMAccessPoint *ap; ap = nm_device_wifi_get_access_point_by_path (NM_DEVICE_WIFI (device), ap_object_path); if (!ap) return FALSE; rsn_flags = nm_access_point_get_rsn_flags (ap); if (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) return TRUE; wpa_flags = nm_access_point_get_wpa_flags (ap); if (wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) return TRUE; return FALSE; } static void wireless_try_to_connect (NetDeviceWifi *device_wifi, const gchar *ssid_target, const gchar *ap_object_path) { const GByteArray *ssid; const gchar *ssid_tmp; GSList *list, *l; GSList *filtered; NMConnection *connection_activate = NULL; NMDevice *device; NMSettingWireless *setting_wireless; NMRemoteSettings *remote_settings; NMClient *client; if (device_wifi->priv->updating_device) goto out; if (ap_object_path == NULL || ap_object_path[0] == 0) goto out; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); if (device == NULL) goto out; g_debug ("try to connect to WIFI network %s [%s]", ssid_target, ap_object_path); /* look for an existing connection we can use */ remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); list = nm_remote_settings_list_connections (remote_settings); g_debug ("%i existing remote connections available", g_slist_length (list)); filtered = nm_device_filter_connections (device, list); g_debug ("%i suitable remote connections to check", g_slist_length (filtered)); for (l = filtered; l; l = g_slist_next (l)) { NMConnection *connection; connection = NM_CONNECTION (l->data); setting_wireless = nm_connection_get_setting_wireless (connection); if (!NM_IS_SETTING_WIRELESS (setting_wireless)) continue; ssid = nm_setting_wireless_get_ssid (setting_wireless); if (ssid == NULL) continue; ssid_tmp = nm_utils_escape_ssid (ssid->data, ssid->len); if (g_strcmp0 (ssid_target, ssid_tmp) == 0) { g_debug ("we found an existing connection %s to activate!", nm_connection_get_id (connection)); connection_activate = connection; break; } } g_slist_free (list); g_slist_free (filtered); /* activate the connection */ client = net_object_get_client (NET_OBJECT (device_wifi)); if (connection_activate != NULL) { nm_client_activate_connection (client, connection_activate, device, NULL, connection_activate_cb, device_wifi); goto out; } /* create one, as it's missing */ g_debug ("no existing connection found for %s, creating", ssid_target); if (!is_8021x (device, ap_object_path)) { g_debug ("no existing connection found for %s, creating and activating one", ssid_target); nm_client_add_and_activate_connection (client, NULL, device, ap_object_path, connection_add_activate_cb, device_wifi); } else { CcNetworkPanel *panel; GPtrArray *array; g_debug ("no existing connection found for %s, creating", ssid_target); array = g_ptr_array_new (); g_ptr_array_add (array, "connect-8021x-wifi"); g_ptr_array_add (array, (gpointer) nm_object_get_path (NM_OBJECT (device))); g_ptr_array_add (array, (gpointer) ap_object_path); g_ptr_array_add (array, NULL); panel = net_object_get_panel (NET_OBJECT (device_wifi)); g_object_set (G_OBJECT (panel), "argv", array->pdata, NULL); g_ptr_array_free (array, FALSE); } out: return; } static gint wireless_ap_model_sort_cb (GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer user_data) { gboolean active_a; gboolean active_b; gboolean ap_a; gboolean ap_b; gchar *str_a; gchar *str_b; gint retval; gint strength_a; gint strength_b; gtk_tree_model_get (model, a, COLUMN_SORT, &str_a, COLUMN_STRENGTH, &strength_a, COLUMN_ACTIVE, &active_a, COLUMN_AP_IN_RANGE, &ap_a, -1); gtk_tree_model_get (model, b, COLUMN_SORT, &str_b, COLUMN_STRENGTH, &strength_b, COLUMN_ACTIVE, &active_b, COLUMN_AP_IN_RANGE, &ap_b, -1); /* active entry first */ if (active_a) { retval = -1; goto out; } if (active_b) { retval = 1; goto out; } /* aps before connections */ if (ap_a && !ap_b) { retval = -1; goto out; } if (!ap_a && ap_b) { retval = 1; goto out; } /* case sensitive search like before */ retval = strength_b - strength_a; out: g_free (str_a); g_free (str_b); return retval; } static GByteArray * ssid_to_byte_array (const gchar *ssid) { guint32 len; GByteArray *ba; len = strlen (ssid); ba = g_byte_array_sized_new (len); g_byte_array_append (ba, (guchar *)ssid, len); return ba; } static gchar * get_hostname (void) { GDBusConnection *bus; GVariant *res; GVariant *inner; gchar *str; GError *error; error = NULL; bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error); if (error != NULL) { g_warning ("Failed to get system bus connection: %s", error->message); g_error_free (error); return NULL; } res = g_dbus_connection_call_sync (bus, "org.freedesktop.hostname1", "/org/freedesktop/hostname1", "org.freedesktop.DBus.Properties", "Get", g_variant_new ("(ss)", "org.freedesktop.hostname1", "PrettyHostname"), (GVariantType*)"(v)", G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_object_unref (bus); if (error != NULL) { g_warning ("Getting pretty hostname failed: %s", error->message); g_error_free (error); } str = NULL; if (res != NULL) { g_variant_get (res, "(v)", &inner); str = g_variant_dup_string (inner, NULL); g_variant_unref (res); } if (str == NULL || *str == '\0') { str = g_strdup (g_get_host_name ()); } if (str == NULL || *str == '\0') { str = g_strdup ("GNOME"); } return str; } static GByteArray * generate_ssid_for_hotspot (NetDeviceWifi *device_wifi) { GByteArray *ssid_array; gchar *ssid; ssid = get_hostname (); ssid_array = ssid_to_byte_array (ssid); g_free (ssid); return ssid_array; } static gchar * generate_wep_key (NetDeviceWifi *device_wifi) { gchar key[11]; gint i; const gchar *hexdigits = "0123456789abcdef"; /* generate a 10-digit hex WEP key */ for (i = 0; i < 10; i++) { gint digit; digit = g_random_int_range (0, 16); key[i] = hexdigits[digit]; } key[10] = 0; return g_strdup (key); } static gboolean is_hotspot_connection (NMConnection *connection) { NMSettingConnection *sc; NMSettingWireless *sw; NMSettingIP4Config *sip; sc = nm_connection_get_setting_connection (connection); if (g_strcmp0 (nm_setting_connection_get_connection_type (sc), "802-11-wireless") != 0) { return FALSE; } sw = nm_connection_get_setting_wireless (connection); if (g_strcmp0 (nm_setting_wireless_get_mode (sw), "adhoc") != 0) { return FALSE; } if (g_strcmp0 (nm_setting_wireless_get_security (sw), "802-11-wireless-security") != 0) { return FALSE; } sip = nm_connection_get_setting_ip4_config (connection); if (g_strcmp0 (nm_setting_ip4_config_get_method (sip), "shared") != 0) { return FALSE; } return TRUE; } static void show_hotspot_ui (NetDeviceWifi *device_wifi) { GtkWidget *widget; GtkSwitch *sw; /* show hotspot tab */ widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "notebook_view")); gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 3); /* force switch to on as this succeeded */ sw = GTK_SWITCH (gtk_builder_get_object (device_wifi->priv->builder, "switch_hotspot_off")); device_wifi->priv->updating_device = TRUE; gtk_switch_set_active (sw, TRUE); device_wifi->priv->updating_device = FALSE; } static void activate_cb (NMClient *client, NMActiveConnection *connection, GError *error, NetDeviceWifi *device_wifi) { if (error != NULL) { g_warning ("Failed to add new connection: (%d) %s", error->code, error->message); return; } /* show hotspot tab */ nm_device_wifi_refresh_ui (device_wifi); show_hotspot_ui (device_wifi); } static void activate_new_cb (NMClient *client, NMActiveConnection *connection, const gchar *path, GError *error, NetDeviceWifi *device_wifi) { activate_cb (client, connection, error, device_wifi); } static void start_shared_connection (NetDeviceWifi *device_wifi) { NMConnection *c; NMConnection *tmp; NMSettingConnection *sc; NMSettingWireless *sw; NMSettingIP4Config *sip; NMSettingWirelessSecurity *sws; NMDevice *device; GByteArray *ssid_array; gchar *wep_key; const gchar *str_mac; struct ether_addr *bin_mac; GSList *connections; GSList *filtered; GSList *l; NMClient *client; NMRemoteSettings *remote_settings; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); g_assert (nm_device_get_device_type (device) == NM_DEVICE_TYPE_WIFI); remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); connections = nm_remote_settings_list_connections (remote_settings); filtered = nm_device_filter_connections (device, connections); g_slist_free (connections); c = NULL; for (l = filtered; l; l = l->next) { tmp = l->data; if (is_hotspot_connection (tmp)) { c = tmp; break; } } g_slist_free (filtered); client = net_object_get_client (NET_OBJECT (device_wifi)); if (c != NULL) { g_debug ("activate existing hotspot connection\n"); nm_client_activate_connection (client, c, device, NULL, (NMClientActivateFn)activate_cb, device_wifi); return; } g_debug ("create new hotspot connection\n"); c = nm_connection_new (); sc = (NMSettingConnection *)nm_setting_connection_new (); g_object_set (sc, "type", "802-11-wireless", "id", "Hotspot", "autoconnect", FALSE, NULL); nm_connection_add_setting (c, (NMSetting *)sc); sw = (NMSettingWireless *)nm_setting_wireless_new (); g_object_set (sw, "mode", "adhoc", "security", "802-11-wireless-security", NULL); str_mac = nm_device_wifi_get_permanent_hw_address (NM_DEVICE_WIFI (device)); bin_mac = ether_aton (str_mac); if (bin_mac) { GByteArray *hw_address; hw_address = g_byte_array_sized_new (ETH_ALEN); g_byte_array_append (hw_address, bin_mac->ether_addr_octet, ETH_ALEN); g_object_set (sw, "mac-address", hw_address, NULL); g_byte_array_unref (hw_address); } nm_connection_add_setting (c, (NMSetting *)sw); sip = (NMSettingIP4Config*) nm_setting_ip4_config_new (); g_object_set (sip, "method", "shared", NULL); nm_connection_add_setting (c, (NMSetting *)sip); ssid_array = generate_ssid_for_hotspot (device_wifi); g_object_set (sw, "ssid", ssid_array, NULL); g_byte_array_unref (ssid_array); sws = (NMSettingWirelessSecurity*) nm_setting_wireless_security_new (); wep_key = generate_wep_key (device_wifi); g_object_set (sws, "key-mgmt", "none", "wep-key0", wep_key, "wep-key-type", NM_WEP_KEY_TYPE_KEY, NULL); g_free (wep_key); nm_connection_add_setting (c, (NMSetting *)sws); nm_client_add_and_activate_connection (client, c, device, NULL, (NMClientAddActivateFn)activate_new_cb, device_wifi); g_object_unref (c); } static void start_hotspot_response_cb (GtkWidget *dialog, gint response, NetDeviceWifi *device_wifi) { if (response == GTK_RESPONSE_OK) { start_shared_connection (device_wifi); } gtk_widget_hide (dialog); } static void start_hotspot (GtkButton *button, NetDeviceWifi *device_wifi) { NMDevice *device; const GPtrArray *connections; gchar *active_ssid; NMClient *client; GtkWidget *dialog; GtkWidget *window; GtkWidget *widget; GString *str; active_ssid = NULL; client = net_object_get_client (NET_OBJECT (device_wifi)); device = net_device_get_nm_device (NET_DEVICE (device_wifi)); connections = nm_client_get_active_connections (client); if (connections) { gint i; for (i = 0; i < connections->len; i++) { NMActiveConnection *c; const GPtrArray *devices; c = (NMActiveConnection *)connections->pdata[i]; devices = nm_active_connection_get_devices (c); if (devices && devices->pdata[0] == device) { NMAccessPoint *ap; ap = nm_device_wifi_get_active_access_point (NM_DEVICE_WIFI (device)); active_ssid = nm_utils_ssid_to_utf8 (nm_access_point_get_ssid (ap)); break; } } } window = gtk_widget_get_toplevel (GTK_WIDGET (button)); dialog = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "hotspot-dialog")); gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (window)); str = g_string_new (_("If you have a connection to the Internet other than wireless, you can use it to share your internet connection with others.")); g_string_append (str, "\n\n"); if (active_ssid) { g_string_append_printf (str, _("Switching on the wireless hotspot will disconnect you from <b>%s</b>."), active_ssid); g_string_append (str, " "); } g_string_append (str, _("It is not possible to access the internet through your wireless while the hotspot is active.")); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "hotspot-dialog-content")); gtk_label_set_markup (GTK_LABEL (widget), str->str); g_string_free (str, TRUE); g_signal_connect (dialog, "response", G_CALLBACK (start_hotspot_response_cb), device_wifi); gtk_window_present (GTK_WINDOW (dialog)); g_free (active_ssid); } static void stop_shared_connection (NetDeviceWifi *device_wifi) { const GPtrArray *connections; const GPtrArray *devices; NMDevice *device; gint i; NMActiveConnection *c; NMClient *client; device = net_device_get_nm_device (NET_DEVICE (device_wifi)); client = net_object_get_client (NET_OBJECT (device_wifi)); connections = nm_client_get_active_connections (client); for (i = 0; i < connections->len; i++) { c = (NMActiveConnection *)connections->pdata[i]; devices = nm_active_connection_get_devices (c); if (devices && devices->pdata[0] == device) { nm_client_deactivate_connection (client, c); break; } } nm_device_wifi_refresh_ui (device_wifi); show_wifi_list (device_wifi); } static void stop_hotspot_response_cb (GtkWidget *dialog, gint response, NetDeviceWifi *device_wifi) { if (response == GTK_RESPONSE_OK) { stop_shared_connection (device_wifi); } gtk_widget_destroy (dialog); } static void switch_hotspot_changed_cb (GtkSwitch *sw, GParamSpec *pspec, NetDeviceWifi *device_wifi) { GtkWidget *dialog; GtkWidget *window; CcNetworkPanel *panel; if (device_wifi->priv->updating_device) return; panel = net_object_get_panel (NET_OBJECT (device_wifi)); window = gtk_widget_get_toplevel (GTK_WIDGET (panel)); dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Stop hotspot and disconnect any users?")); gtk_dialog_add_buttons (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, _("_Stop Hotspot"), GTK_RESPONSE_OK, NULL); g_signal_connect (dialog, "response", G_CALLBACK (stop_hotspot_response_cb), device_wifi); gtk_window_present (GTK_WINDOW (dialog)); } static void connect_wifi_network (NetDeviceWifi *device_wifi, GtkTreeView *tv, GtkTreePath *path) { gboolean ap_in_range; gchar *ap_object_path; gchar *ssid; gchar *connection_id; GtkTreeIter iter; GtkTreeModel *model; NM80211Mode mode; model = gtk_tree_view_get_model (tv); gtk_tree_model_get_iter (model, &iter, path); gtk_tree_model_get (model, &iter, COLUMN_ACCESS_POINT_ID, &ap_object_path, COLUMN_CONNECTION_ID, &connection_id, COLUMN_TITLE, &ssid, COLUMN_AP_IN_RANGE, &ap_in_range, COLUMN_MODE, &mode, -1); if (ap_in_range) { if (connection_id) activate_connection (device_wifi, connection_id); else wireless_try_to_connect (device_wifi, ssid, ap_object_path); } else { g_warning ("can't connect"); } g_free (ap_object_path); g_free (connection_id); g_free (ssid); } static void show_wifi_details (NetDeviceWifi *device_wifi, GtkTreeView *tv, GtkTreePath *path) { GtkWidget *widget; gboolean ret; gboolean in_range; GtkTreeModel *model; GtkTreeIter iter; gchar *path_str; model = gtk_tree_view_get_model (tv); path_str = gtk_tree_path_to_string (path); ret = gtk_tree_model_get_iter_from_string (model, &iter, path_str); if (!ret) goto out; /* get parameters about the selected connection */ g_free (device_wifi->priv->selected_connection_id); g_free (device_wifi->priv->selected_ssid_title); gtk_tree_model_get (model, &iter, COLUMN_ACCESS_POINT_ID, &device_wifi->priv->selected_ap_id, COLUMN_CONNECTION_ID, &device_wifi->priv->selected_connection_id, COLUMN_TITLE, &device_wifi->priv->selected_ssid_title, COLUMN_AP_IN_RANGE, &in_range, -1); g_debug ("ssid = %s, in-range = %i", device_wifi->priv->selected_ssid_title, in_range); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "notebook_view")); nm_device_wifi_refresh_ui (device_wifi); gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 1); out: g_free (path_str); } static void show_wifi_list (NetDeviceWifi *device_wifi) { GtkWidget *widget; widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "notebook_view")); gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 0); } static gboolean arrow_visible (GtkTreeModel *model, GtkTreeIter *iter) { gboolean active; gboolean ap_is_saved; gboolean ret; gchar *sort; gtk_tree_model_get (model, iter, COLUMN_ACTIVE, &active, COLUMN_AP_IS_SAVED, &ap_is_saved, COLUMN_SORT, &sort, -1); if (active || ap_is_saved) ret = TRUE; else ret = FALSE; g_free (sort); return ret; } static void set_arrow_image (GtkCellLayout *layout, GtkCellRenderer *cell, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { NetDeviceWifi *device = user_data; const gchar *icon; if (arrow_visible (model, iter)) { GtkWidget *widget; widget = GTK_WIDGET (gtk_builder_get_object (device->priv->builder, "treeview_list")); if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) icon = "go-previous"; else icon = "go-next"; } else { icon = ""; } g_object_set (cell, "icon-name", icon, NULL); } static void edit_connection (GtkButton *button, NetDeviceWifi *device_wifi) { net_object_edit (NET_OBJECT (device_wifi)); } static void remote_settings_read_cb (NMRemoteSettings *remote_settings, NetDeviceWifi *device_wifi) { gboolean is_hotspot; device_wifi_refresh_saved_connections (device_wifi); /* go straight to the hotspot UI */ is_hotspot = device_is_hotspot (device_wifi); if (is_hotspot) { nm_device_wifi_refresh_hotspot (device_wifi); show_hotspot_ui (device_wifi); } } static gboolean separator_visible (GtkTreeModel *model, GtkTreeIter *iter) { gboolean active; gboolean ap_is_saved; gboolean ap_in_range; gchar *sort; gboolean ret; gtk_tree_model_get (model, iter, COLUMN_ACTIVE, &active, COLUMN_AP_IS_SAVED, &ap_is_saved, COLUMN_AP_IN_RANGE, &ap_in_range, COLUMN_SORT, &sort, -1); if (!active && ap_is_saved && ap_in_range) ret = TRUE; else ret = FALSE; g_free (sort); return ret; } static void set_draw_separator (GtkCellLayout *layout, GtkCellRenderer *cell, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { gboolean draw; draw = separator_visible (model, iter); g_object_set (cell, "draw", draw, NULL); } static void switch_page_cb (GtkNotebook *notebook, GtkWidget *page, guint page_num, NetDeviceWifi *device_wifi) { GtkWidget *widget; if (page_num == 1) { widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_back1")); gtk_widget_grab_focus (widget); } } static void net_device_wifi_constructed (GObject *object) { NetDeviceWifi *device_wifi = NET_DEVICE_WIFI (object); NMClient *client; NMRemoteSettings *remote_settings; NMClientPermissionResult perm; GtkWidget *widget; G_OBJECT_CLASS (net_device_wifi_parent_class)->constructed (object); client = net_object_get_client (NET_OBJECT (device_wifi)); g_signal_connect (client, "notify::wireless-enabled", G_CALLBACK (wireless_enabled_toggled), device_wifi); /* only show the button if the user can create a hotspot */ perm = nm_client_get_permission_result (client, NM_CLIENT_PERMISSION_WIFI_SHARE_OPEN); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "start_hotspot_button")); gtk_widget_set_sensitive (widget, perm == NM_CLIENT_PERMISSION_RESULT_YES || perm == NM_CLIENT_PERMISSION_RESULT_AUTH); remote_settings = net_object_get_remote_settings (NET_OBJECT (device_wifi)); g_signal_connect (remote_settings, "connections-read", G_CALLBACK (remote_settings_read_cb), device_wifi); nm_device_wifi_refresh_ui (device_wifi); } static void net_device_wifi_finalize (GObject *object) { NetDeviceWifi *device_wifi = NET_DEVICE_WIFI (object); NetDeviceWifiPrivate *priv = device_wifi->priv; g_object_unref (priv->builder); g_free (priv->selected_ssid_title); g_free (priv->selected_connection_id); g_free (priv->selected_ap_id); G_OBJECT_CLASS (net_device_wifi_parent_class)->finalize (object); } static void device_wifi_edit (NetObject *object) { const gchar *uuid; gchar *cmdline; GError *error = NULL; NetDeviceWifi *device = NET_DEVICE_WIFI (object); NMRemoteSettings *settings; NMRemoteConnection *connection; settings = net_object_get_remote_settings (object); connection = nm_remote_settings_get_connection_by_path (settings, device->priv->selected_connection_id); if (connection == NULL) { g_warning ("failed to get remote connection"); return; } uuid = nm_connection_get_uuid (NM_CONNECTION (connection)); cmdline = g_strdup_printf ("nm-connection-editor --edit %s", uuid); g_debug ("Launching '%s'\n", cmdline); if (!g_spawn_command_line_async (cmdline, &error)) { g_warning ("Failed to launch nm-connection-editor: %s", error->message); g_error_free (error); } g_free (cmdline); } static void net_device_wifi_class_init (NetDeviceWifiClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); NetObjectClass *parent_class = NET_OBJECT_CLASS (klass); object_class->finalize = net_device_wifi_finalize; object_class->constructed = net_device_wifi_constructed; parent_class->add_to_notebook = device_wifi_proxy_add_to_notebook; parent_class->refresh = device_wifi_refresh; parent_class->edit = device_wifi_edit; g_type_class_add_private (klass, sizeof (NetDeviceWifiPrivate)); } static void activate_ssid_cb (PanelCellRendererText *cell, const gchar *path, NetDeviceWifi *device_wifi) { GtkTreeView *tv; GtkTreePath *tpath; g_debug ("activate ssid!\n"); tv = GTK_TREE_VIEW (gtk_builder_get_object (device_wifi->priv->builder, "treeview_list")); tpath = gtk_tree_path_new_from_string (path); connect_wifi_network (device_wifi, tv, tpath); gtk_tree_path_free (tpath); } static void activate_arrow_cb (PanelCellRendererText *cell, const gchar *path, NetDeviceWifi *device_wifi) { GtkTreeView *tv; GtkTreeModel *model; GtkTreePath *tpath; GtkTreeIter iter; g_debug ("activate arrow!\n"); tv = GTK_TREE_VIEW (gtk_builder_get_object (device_wifi->priv->builder, "treeview_list")); model = gtk_tree_view_get_model (tv); tpath = gtk_tree_path_new_from_string (path); gtk_tree_model_get_iter (model, &iter, tpath); if (arrow_visible (model, &iter)) show_wifi_details (device_wifi, tv, tpath); gtk_tree_path_free (tpath); } static void net_device_wifi_init (NetDeviceWifi *device_wifi) { GError *error = NULL; GtkWidget *widget; GtkCellRenderer *renderer1; GtkCellRenderer *renderer2; GtkCellRenderer *renderer3; GtkCellRenderer *renderer4; GtkCellRenderer *renderer5; GtkCellRenderer *renderer6; GtkCellRenderer *renderer7; GtkCellRenderer *renderer8; GtkTreeSortable *sortable; GtkTreeViewColumn *column; GtkCellArea *area; device_wifi->priv = NET_DEVICE_WIFI_GET_PRIVATE (device_wifi); device_wifi->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (device_wifi->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (device_wifi->priv->builder, CINNAMONCC_UI_DIR "/network-wifi.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } /* setup wifi views */ widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "device_off_switch")); g_signal_connect (widget, "notify::active", G_CALLBACK (device_off_toggled), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_options1")); g_signal_connect (widget, "clicked", G_CALLBACK (edit_connection), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_forget1")); g_signal_connect (widget, "clicked", G_CALLBACK (forget_button_clicked_cb), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_disconnect1")); g_signal_connect (widget, "clicked", G_CALLBACK (disconnect_button_clicked_cb), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_connect1")); g_signal_connect (widget, "clicked", G_CALLBACK (connect_button_clicked_cb), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "treeview_list")); /* sort networks in drop down */ sortable = GTK_TREE_SORTABLE (gtk_builder_get_object (device_wifi->priv->builder, "liststore_network")); gtk_tree_sortable_set_sort_column_id (sortable, COLUMN_SORT, GTK_SORT_ASCENDING); gtk_tree_sortable_set_sort_func (sortable, COLUMN_SORT, wireless_ap_model_sort_cb, device_wifi, NULL); column = GTK_TREE_VIEW_COLUMN (gtk_builder_get_object (device_wifi->priv->builder, "treeview_list_column")); area = gtk_cell_layout_get_area (GTK_CELL_LAYOUT (column)); renderer1 = gtk_cell_renderer_pixbuf_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer1, FALSE); g_object_set (renderer1, "follow-state", TRUE, "icon-name", "object-select-symbolic", "xpad", 6, "ypad", 6, NULL); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (column), renderer1, "visible", COLUMN_ACTIVE, NULL); gtk_cell_area_cell_set (area, renderer1, "align", TRUE, NULL); renderer2 = panel_cell_renderer_text_new (); g_object_set (renderer2, "mode", GTK_CELL_RENDERER_MODE_ACTIVATABLE, "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer2, TRUE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (column), renderer2, "markup", COLUMN_TITLE, NULL); gtk_cell_area_cell_set (area, renderer2, "align", TRUE, "expand", TRUE, NULL); g_signal_connect (renderer2, "activate", G_CALLBACK (activate_ssid_cb), device_wifi); renderer3 = panel_cell_renderer_mode_new (); gtk_cell_renderer_set_padding (renderer3, 4, 0); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer3, FALSE); g_object_set (renderer3, "follow-state", TRUE, NULL); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (column), renderer3, "ap-mode", COLUMN_MODE, NULL); renderer4 = gtk_cell_renderer_text_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer4, FALSE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (column), renderer4, "visible", COLUMN_AP_OUT_OF_RANGE, NULL); g_object_set (renderer4, "text", _("Out of range"), "mode", GTK_CELL_RENDERER_MODE_INERT, "xalign", 1.0, NULL); renderer5 = panel_cell_renderer_signal_new (); gtk_cell_renderer_set_padding (renderer5, 4, 0); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer5, FALSE); g_object_set (renderer5, "follow-state", TRUE, NULL); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (column), renderer5, "signal", COLUMN_STRENGTH, "visible", COLUMN_AP_IN_RANGE, NULL); renderer6 = panel_cell_renderer_security_new (); gtk_cell_renderer_set_padding (renderer6, 4, 0); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer6, FALSE); g_object_set (renderer6, "follow-state", TRUE, NULL); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (column), renderer6, "security", COLUMN_SECURITY, "visible", COLUMN_AP_IN_RANGE, NULL); renderer7 = panel_cell_renderer_separator_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer7, FALSE); g_object_set (renderer7, "visible", TRUE, "sensitive", FALSE, "draw", TRUE, NULL); gtk_cell_renderer_set_fixed_size (renderer7, 1, -1); gtk_cell_layout_set_cell_data_func (GTK_CELL_LAYOUT (column), renderer7, set_draw_separator, device_wifi, NULL); renderer8 = panel_cell_renderer_pixbuf_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), renderer8, FALSE); g_object_set (renderer8, "mode", GTK_CELL_RENDERER_MODE_ACTIVATABLE, "follow-state", TRUE, "visible", TRUE, "xpad", 6, "ypad", 6, NULL); gtk_cell_layout_set_cell_data_func (GTK_CELL_LAYOUT (column), renderer8, set_arrow_image, device_wifi, NULL); g_signal_connect (renderer8, "activate", G_CALLBACK (activate_arrow_cb), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "button_back1")); g_signal_connect_swapped (widget, "clicked", G_CALLBACK (show_wifi_list), device_wifi); /* draw focus around everything but the arrow */ gtk_cell_area_add_focus_sibling (area, renderer2, renderer1); gtk_cell_area_add_focus_sibling (area, renderer2, renderer3); gtk_cell_area_add_focus_sibling (area, renderer2, renderer4); gtk_cell_area_add_focus_sibling (area, renderer2, renderer5); gtk_cell_area_add_focus_sibling (area, renderer2, renderer6); gtk_cell_area_add_focus_sibling (area, renderer2, renderer7); /* setup view */ widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "notebook_view")); gtk_notebook_set_show_tabs (GTK_NOTEBOOK (widget), FALSE); gtk_notebook_set_current_page (GTK_NOTEBOOK (widget), 0); g_signal_connect_after (widget, "switch-page", G_CALLBACK (switch_page_cb), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "start_hotspot_button")); g_signal_connect (widget, "clicked", G_CALLBACK (start_hotspot), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "connect_hidden_button")); g_signal_connect_swapped (widget, "clicked", G_CALLBACK (connect_to_hidden_network), device_wifi); widget = GTK_WIDGET (gtk_builder_get_object (device_wifi->priv->builder, "switch_hotspot_off")); g_signal_connect (widget, "notify::active", G_CALLBACK (switch_hotspot_changed_cb), device_wifi); }
447
./cinnamon-control-center/panels/network/net-vpn.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011-2012 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> #include "panel-common.h" #include "net-vpn.h" #include "nm-client.h" #include "nm-remote-connection.h" #include "nm-setting-vpn.h" #define NET_VPN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_VPN, NetVpnPrivate)) struct _NetVpnPrivate { GtkBuilder *builder; NMConnection *connection; gchar *service_type; gboolean valid; gboolean updating_device; }; enum { PROP_0, PROP_CONNECTION, PROP_LAST }; G_DEFINE_TYPE (NetVpn, net_vpn, NET_TYPE_OBJECT) static void connection_vpn_state_changed_cb (NMVPNConnection *connection, NMVPNConnectionState state, NMVPNConnectionStateReason reason, NetVpn *vpn) { net_object_emit_changed (NET_OBJECT (vpn)); } static void connection_changed_cb (NMConnection *connection, NetVpn *vpn) { net_object_emit_changed (NET_OBJECT (vpn)); } static void connection_removed_cb (NMConnection *connection, NetVpn *vpn) { net_object_emit_removed (NET_OBJECT (vpn)); } static char * net_vpn_connection_to_type (NMConnection *connection) { const gchar *type, *p; type = nm_setting_vpn_get_service_type (nm_connection_get_setting_vpn (connection)); /* Go from "org.freedesktop.NetworkManager.vpnc" to "vpnc" for example */ p = strrchr (type, '.'); return g_strdup (p ? p + 1 : type); } static void net_vpn_set_connection (NetVpn *vpn, NMConnection *connection) { NetVpnPrivate *priv = vpn->priv; /* * vpnc config exmaple: * key=IKE DH Group, value=dh2 * key=xauth-password-type, value=ask * key=ipsec-secret-type, value=save * key=IPSec gateway, value=66.187.233.252 * key=NAT Traversal Mode, value=natt * key=IPSec ID, value=rh-vpn * key=Xauth username, value=rhughes */ priv->connection = g_object_ref (connection); g_signal_connect (priv->connection, NM_REMOTE_CONNECTION_REMOVED, G_CALLBACK (connection_removed_cb), vpn); g_signal_connect (priv->connection, NM_REMOTE_CONNECTION_UPDATED, G_CALLBACK (connection_changed_cb), vpn); if (NM_IS_VPN_CONNECTION (priv->connection)) { g_signal_connect (priv->connection, NM_VPN_CONNECTION_VPN_STATE, G_CALLBACK (connection_vpn_state_changed_cb), vpn); } priv->service_type = net_vpn_connection_to_type (priv->connection); } static NMVPNConnectionState net_vpn_get_state (NetVpn *vpn) { NetVpnPrivate *priv = vpn->priv; if (!NM_IS_VPN_CONNECTION (priv->connection)) return NM_VPN_CONNECTION_STATE_DISCONNECTED; return nm_vpn_connection_get_vpn_state (NM_VPN_CONNECTION (priv->connection)); } /* VPN parameters can be found at: * http://git.gnome.org/browse/network-manager-openvpn/tree/src/nm-openvpn-service.h * http://git.gnome.org/browse/network-manager-vpnc/tree/src/nm-vpnc-service.h * http://git.gnome.org/browse/network-manager-pptp/tree/src/nm-pptp-service.h * http://git.gnome.org/browse/network-manager-openconnect/tree/src/nm-openconnect-service.h * http://git.gnome.org/browse/network-manager-openswan/tree/src/nm-openswan-service.h * See also 'properties' directory in these plugins. */ static const gchar * get_vpn_key_gateway (const char *vpn_type) { if (g_strcmp0 (vpn_type, "openvpn") == 0) return "remote"; if (g_strcmp0 (vpn_type, "vpnc") == 0) return "IPSec gateway"; if (g_strcmp0 (vpn_type, "pptp") == 0) return "gateway"; if (g_strcmp0 (vpn_type, "openconnect") == 0) return "gateway"; if (g_strcmp0 (vpn_type, "openswan") == 0) return "right"; return ""; } static const gchar * get_vpn_key_group (const char *vpn_type) { if (g_strcmp0 (vpn_type, "openvpn") == 0) return ""; if (g_strcmp0 (vpn_type, "vpnc") == 0) return "IPSec ID"; if (g_strcmp0 (vpn_type, "pptp") == 0) return ""; if (g_strcmp0 (vpn_type, "openconnect") == 0) return ""; if (g_strcmp0 (vpn_type, "openswan") == 0) return ""; return ""; } static const gchar * get_vpn_key_username (const char *vpn_type) { if (g_strcmp0 (vpn_type, "openvpn") == 0) return "username"; if (g_strcmp0 (vpn_type, "vpnc") == 0) return "Xauth username"; if (g_strcmp0 (vpn_type, "pptp") == 0) return "user"; if (g_strcmp0 (vpn_type, "openconnect") == 0) return "username"; if (g_strcmp0 (vpn_type, "openswan") == 0) return "leftxauthusername"; return ""; } static const gchar * get_vpn_key_group_password (const char *vpn_type) { if (g_strcmp0 (vpn_type, "openvpn") == 0) return ""; if (g_strcmp0 (vpn_type, "vpnc") == 0) return "Xauth password"; if (g_strcmp0 (vpn_type, "pptp") == 0) return ""; if (g_strcmp0 (vpn_type, "openconnect") == 0) return ""; if (g_strcmp0 (vpn_type, "openswan") == 0) return ""; return ""; } static const gchar * net_vpn_get_gateway (NetVpn *vpn) { NetVpnPrivate *priv = vpn->priv; const gchar *key; key = get_vpn_key_gateway (priv->service_type); return nm_setting_vpn_get_data_item (nm_connection_get_setting_vpn (priv->connection), key); } static const gchar * net_vpn_get_id (NetVpn *vpn) { NetVpnPrivate *priv = vpn->priv; const gchar *key; key = get_vpn_key_group (priv->service_type); return nm_setting_vpn_get_data_item (nm_connection_get_setting_vpn (priv->connection), key); } static const gchar * net_vpn_get_username (NetVpn *vpn) { NetVpnPrivate *priv = vpn->priv; const gchar *key; key = get_vpn_key_username (priv->service_type); return nm_setting_vpn_get_data_item (nm_connection_get_setting_vpn (priv->connection), key); } static const gchar * net_vpn_get_password (NetVpn *vpn) { NetVpnPrivate *priv = vpn->priv; const gchar *key; key = get_vpn_key_group_password (priv->service_type); return nm_setting_vpn_get_data_item (nm_connection_get_setting_vpn (priv->connection), key); } static void vpn_proxy_delete (NetObject *object) { NetVpn *vpn = NET_VPN (object); nm_remote_connection_delete (NM_REMOTE_CONNECTION (vpn->priv->connection), NULL, vpn); } static GtkWidget * vpn_proxy_add_to_notebook (NetObject *object, GtkNotebook *notebook, GtkSizeGroup *heading_size_group) { GtkWidget *widget; GtkWindow *window; NetVpn *vpn = NET_VPN (object); /* add widgets to size group */ widget = GTK_WIDGET (gtk_builder_get_object (vpn->priv->builder, "heading_group_password")); gtk_size_group_add_widget (heading_size_group, widget); /* reparent */ window = GTK_WINDOW (gtk_builder_get_object (vpn->priv->builder, "window_tmp")); widget = GTK_WIDGET (gtk_builder_get_object (vpn->priv->builder, "vbox9")); g_object_ref (widget); gtk_container_remove (GTK_CONTAINER (window), widget); gtk_notebook_append_page (notebook, widget, NULL); g_object_unref (widget); return widget; } static void nm_device_refresh_vpn_ui (NetVpn *vpn) { GtkWidget *widget; GtkWidget *sw; const gchar *status; NetVpnPrivate *priv = vpn->priv; const GPtrArray *acs; NMActiveConnection *a; gint i; const gchar *path; const gchar *apath; NMVPNConnectionState state; gchar *title; NMClient *client; sw = GTK_WIDGET (gtk_builder_get_object (priv->builder, "device_off_switch")); gtk_widget_set_visible (sw, TRUE); /* update title */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_device")); title = g_strdup_printf (_("%s VPN"), nm_connection_get_id (vpn->priv->connection)); net_object_set_title (NET_OBJECT (vpn), title); gtk_label_set_label (GTK_LABEL (widget), title); g_free (title); /* use status */ state = net_vpn_get_state (vpn); client = net_object_get_client (NET_OBJECT (vpn)); acs = nm_client_get_active_connections (client); if (acs != NULL) { path = nm_connection_get_path (vpn->priv->connection); for (i = 0; i < acs->len; i++) { a = (NMActiveConnection*)acs->pdata[i]; apath = nm_active_connection_get_connection (a); if (NM_IS_VPN_CONNECTION (a) && strcmp (apath, path) == 0) { state = nm_vpn_connection_get_vpn_state (NM_VPN_CONNECTION (a)); break; } } } widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_status")); status = panel_vpn_state_to_localized_string (state); gtk_label_set_label (GTK_LABEL (widget), status); priv->updating_device = TRUE; gtk_switch_set_active (GTK_SWITCH (sw), state != NM_VPN_CONNECTION_STATE_FAILED && state != NM_VPN_CONNECTION_STATE_DISCONNECTED); priv->updating_device = FALSE; /* service type */ panel_set_device_widget_details (vpn->priv->builder, "service_type", vpn->priv->service_type); /* gateway */ panel_set_device_widget_details (vpn->priv->builder, "gateway", net_vpn_get_gateway (vpn)); /* groupname */ panel_set_device_widget_details (vpn->priv->builder, "group_name", net_vpn_get_id (vpn)); /* username */ panel_set_device_widget_details (vpn->priv->builder, "username", net_vpn_get_username (vpn)); /* password */ panel_set_device_widget_details (vpn->priv->builder, "group_password", net_vpn_get_password (vpn)); } static void vpn_proxy_refresh (NetObject *object) { NetVpn *vpn = NET_VPN (object); nm_device_refresh_vpn_ui (vpn); } static void device_off_toggled (GtkSwitch *sw, GParamSpec *pspec, NetVpn *vpn) { const gchar *path; const GPtrArray *acs; gboolean active; gint i; NMActiveConnection *a; NMClient *client; if (vpn->priv->updating_device) return; active = gtk_switch_get_active (sw); if (active) { client = net_object_get_client (NET_OBJECT (vpn)); nm_client_activate_connection (client, vpn->priv->connection, NULL, NULL, NULL, NULL); } else { path = nm_connection_get_path (vpn->priv->connection); client = net_object_get_client (NET_OBJECT (vpn)); acs = nm_client_get_active_connections (client); for (i = 0; i < acs->len; i++) { a = (NMActiveConnection*)acs->pdata[i]; if (strcmp (nm_active_connection_get_connection (a), path) == 0) { nm_client_deactivate_connection (client, a); break; } } } } static void edit_connection (GtkButton *button, NetVpn *vpn) { net_object_edit (NET_OBJECT (vpn)); } static void vpn_proxy_edit (NetObject *object) { const gchar *uuid; gchar *cmdline; GError *error = NULL; NetVpn *vpn = NET_VPN (object); uuid = nm_connection_get_uuid (vpn->priv->connection); cmdline = g_strdup_printf ("nm-connection-editor --edit %s", uuid); g_debug ("Launching '%s'\n", cmdline); if (!g_spawn_command_line_async (cmdline, &error)) { g_warning ("Failed to launch nm-connection-editor: %s", error->message); g_error_free (error); } g_free (cmdline); } /** * net_vpn_get_property: **/ static void net_vpn_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { NetVpn *vpn = NET_VPN (object); NetVpnPrivate *priv = vpn->priv; switch (prop_id) { case PROP_CONNECTION: g_value_set_object (value, priv->connection); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (vpn, prop_id, pspec); break; } } /** * net_vpn_set_property: **/ static void net_vpn_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { NetVpn *vpn = NET_VPN (object); switch (prop_id) { case PROP_CONNECTION: net_vpn_set_connection (vpn, g_value_get_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (vpn, prop_id, pspec); break; } } static void net_vpn_constructed (GObject *object) { NetVpn *vpn = NET_VPN (object); G_OBJECT_CLASS (net_vpn_parent_class)->constructed (object); nm_device_refresh_vpn_ui (vpn); } static void net_vpn_finalize (GObject *object) { NetVpn *vpn = NET_VPN (object); NetVpnPrivate *priv = vpn->priv; g_object_unref (priv->connection); g_free (priv->service_type); G_OBJECT_CLASS (net_vpn_parent_class)->finalize (object); } static void net_vpn_class_init (NetVpnClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); NetObjectClass *parent_class = NET_OBJECT_CLASS (klass); object_class->get_property = net_vpn_get_property; object_class->set_property = net_vpn_set_property; object_class->constructed = net_vpn_constructed; object_class->finalize = net_vpn_finalize; parent_class->add_to_notebook = vpn_proxy_add_to_notebook; parent_class->delete = vpn_proxy_delete; parent_class->refresh = vpn_proxy_refresh; parent_class->edit = vpn_proxy_edit; pspec = g_param_spec_object ("connection", NULL, NULL, NM_TYPE_CONNECTION, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_CONNECTION, pspec); g_type_class_add_private (klass, sizeof (NetVpnPrivate)); } static void net_vpn_init (NetVpn *vpn) { GError *error = NULL; GtkWidget *widget; vpn->priv = NET_VPN_GET_PRIVATE (vpn); vpn->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (vpn->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (vpn->priv->builder, CINNAMONCC_UI_DIR "/network-vpn.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } widget = GTK_WIDGET (gtk_builder_get_object (vpn->priv->builder, "device_off_switch")); g_signal_connect (widget, "notify::active", G_CALLBACK (device_off_toggled), vpn); widget = GTK_WIDGET (gtk_builder_get_object (vpn->priv->builder, "button_options")); g_signal_connect (widget, "clicked", G_CALLBACK (edit_connection), vpn); }
448
./cinnamon-control-center/panels/network/network-module.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Richard Hughes <richard@hughsie.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * */ #include <config.h> #include "cc-network-panel.h" #include <glib/gi18n-lib.h> void g_io_module_load (GIOModule *module) { /* register the panel */ cc_network_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
449
./cinnamon-control-center/panels/network/net-proxy.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011-2012 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> #include <gio/gio.h> #include "net-proxy.h" #define NET_PROXY_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_PROXY, NetProxyPrivate)) struct _NetProxyPrivate { GSettings *settings; GtkBuilder *builder; }; G_DEFINE_TYPE (NetProxy, net_proxy, NET_TYPE_OBJECT) static void check_wpad_warning (NetProxy *proxy) { GtkWidget *widget; gchar *autoconfig_url = NULL; GString *string = NULL; gboolean ret = FALSE; guint mode; string = g_string_new (""); /* check we're using 'Automatic' */ mode = g_settings_get_enum (proxy->priv->settings, "mode"); if (mode != 2) goto out; /* see if the PAC is blank */ autoconfig_url = g_settings_get_string (proxy->priv->settings, "autoconfig-url"); ret = autoconfig_url == NULL || autoconfig_url[0] == '\0'; if (!ret) goto out; g_string_append (string, "<small>"); /* TRANSLATORS: this is when the use leaves the PAC textbox blank */ g_string_append (string, _("Web Proxy Autodiscovery is used when a Configuration URL is not provided.")); g_string_append (string, "\n"); /* TRANSLATORS: WPAD is bad: if you enable it on an untrusted * network, then anyone else on that network can tell your * machine that it should proxy all of your web traffic * through them. */ g_string_append (string, _("This is not recommended for untrusted public networks.")); g_string_append (string, "</small>"); out: widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "label_proxy_warning")); gtk_label_set_markup (GTK_LABEL (widget), string->str); g_free (autoconfig_url); g_string_free (string, TRUE); } static void settings_changed_cb (GSettings *settings, const gchar *key, NetProxy *proxy) { check_wpad_warning (proxy); } static void panel_proxy_mode_combo_setup_widgets (NetProxy *proxy, guint value) { GtkWidget *widget; /* hide or show the PAC text box */ widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "heading_proxy_url")); gtk_widget_set_visible (widget, value == 2); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_url")); gtk_widget_set_visible (widget, value == 2); /* hide or show the manual entry text boxes */ widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "heading_proxy_http")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_http")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "spinbutton_proxy_http")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "heading_proxy_https")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_https")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "spinbutton_proxy_https")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "heading_proxy_ftp")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_ftp")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "spinbutton_proxy_ftp")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "heading_proxy_socks")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_socks")); gtk_widget_set_visible (widget, value == 1); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "spinbutton_proxy_socks")); gtk_widget_set_visible (widget, value == 1); /* perhaps show the wpad warning */ check_wpad_warning (proxy); } static void panel_set_value_for_combo (NetProxy *proxy, GtkComboBox *combo_box, gint value) { gboolean ret; gint value_tmp; GtkTreeIter iter; GtkTreeModel *model; /* get entry */ model = gtk_combo_box_get_model (combo_box); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* try to make the UI match the setting */ do { gtk_tree_model_get (model, &iter, 1, &value_tmp, -1); if (value == value_tmp) { gtk_combo_box_set_active_iter (combo_box, &iter); break; } } while (gtk_tree_model_iter_next (model, &iter)); /* hide or show the correct widgets */ panel_proxy_mode_combo_setup_widgets (proxy, value); } static void panel_proxy_mode_combo_changed_cb (GtkWidget *widget, NetProxy *proxy) { gboolean ret; gint value; GtkTreeIter iter; GtkTreeModel *model; /* no selection */ ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX (widget), &iter); if (!ret) return; /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget)); gtk_tree_model_get (model, &iter, 1, &value, -1); /* set */ g_settings_set_enum (proxy->priv->settings, "mode", value); /* hide or show the correct widgets */ panel_proxy_mode_combo_setup_widgets (proxy, value); } static GtkWidget * net_proxy_add_to_notebook (NetObject *object, GtkNotebook *notebook, GtkSizeGroup *heading_size_group) { GtkWidget *widget; GtkWindow *window; NetProxy *proxy = NET_PROXY (object); /* add widgets to size group */ widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "heading_proxy_method")); gtk_size_group_add_widget (heading_size_group, widget); /* reparent */ window = GTK_WINDOW (gtk_builder_get_object (proxy->priv->builder, "window_tmp")); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "grid5")); g_object_ref (widget); gtk_container_remove (GTK_CONTAINER (window), widget); gtk_notebook_append_page (notebook, widget, NULL); g_object_unref (widget); return widget; } static void net_proxy_finalize (GObject *object) { NetProxy *proxy = NET_PROXY (object); NetProxyPrivate *priv = proxy->priv; g_clear_object (&priv->settings); g_clear_object (&priv->builder); G_OBJECT_CLASS (net_proxy_parent_class)->finalize (object); } static void net_proxy_class_init (NetProxyClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); NetObjectClass *parent_class = NET_OBJECT_CLASS (klass); object_class->finalize = net_proxy_finalize; parent_class->add_to_notebook = net_proxy_add_to_notebook; g_type_class_add_private (klass, sizeof (NetProxyPrivate)); } static void net_proxy_init (NetProxy *proxy) { GError *error = NULL; gint value; GSettings *settings_tmp; GtkAdjustment *adjustment; GtkWidget *widget; proxy->priv = NET_PROXY_GET_PRIVATE (proxy); proxy->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (proxy->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (proxy->priv->builder, CINNAMONCC_UI_DIR "/network-proxy.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } proxy->priv->settings = g_settings_new ("org.gnome.system.proxy"); g_signal_connect (proxy->priv->settings, "changed", G_CALLBACK (settings_changed_cb), proxy); /* explicitly set this to false as the panel has no way of * linking the http and https proxies them together */ g_settings_set_boolean (proxy->priv->settings, "use-same-proxy", FALSE); /* actions */ value = g_settings_get_enum (proxy->priv->settings, "mode"); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "combobox_proxy_mode")); panel_set_value_for_combo (proxy, GTK_COMBO_BOX (widget), value); g_signal_connect (widget, "changed", G_CALLBACK (panel_proxy_mode_combo_changed_cb), proxy); /* bind the proxy values */ widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_url")); g_settings_bind (proxy->priv->settings, "autoconfig-url", widget, "text", G_SETTINGS_BIND_DEFAULT); /* bind the HTTP proxy values */ settings_tmp = g_settings_get_child (proxy->priv->settings, "http"); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_http")); g_settings_bind (settings_tmp, "host", widget, "text", G_SETTINGS_BIND_DEFAULT); adjustment = GTK_ADJUSTMENT (gtk_builder_get_object (proxy->priv->builder, "adjustment_proxy_port_http")); g_settings_bind (settings_tmp, "port", adjustment, "value", G_SETTINGS_BIND_DEFAULT); g_object_unref (settings_tmp); /* bind the HTTPS proxy values */ settings_tmp = g_settings_get_child (proxy->priv->settings, "https"); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_https")); g_settings_bind (settings_tmp, "host", widget, "text", G_SETTINGS_BIND_DEFAULT); adjustment = GTK_ADJUSTMENT (gtk_builder_get_object (proxy->priv->builder, "adjustment_proxy_port_https")); g_settings_bind (settings_tmp, "port", adjustment, "value", G_SETTINGS_BIND_DEFAULT); g_object_unref (settings_tmp); /* bind the FTP proxy values */ settings_tmp = g_settings_get_child (proxy->priv->settings, "ftp"); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_ftp")); g_settings_bind (settings_tmp, "host", widget, "text", G_SETTINGS_BIND_DEFAULT); adjustment = GTK_ADJUSTMENT (gtk_builder_get_object (proxy->priv->builder, "adjustment_proxy_port_ftp")); g_settings_bind (settings_tmp, "port", adjustment, "value", G_SETTINGS_BIND_DEFAULT); g_object_unref (settings_tmp); /* bind the SOCKS proxy values */ settings_tmp = g_settings_get_child (proxy->priv->settings, "socks"); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "entry_proxy_socks")); g_settings_bind (settings_tmp, "host", widget, "text", G_SETTINGS_BIND_DEFAULT); adjustment = GTK_ADJUSTMENT (gtk_builder_get_object (proxy->priv->builder, "adjustment_proxy_port_socks")); g_settings_bind (settings_tmp, "port", adjustment, "value", G_SETTINGS_BIND_DEFAULT); g_object_unref (settings_tmp); /* set header to something sane */ widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "image_proxy_device")); gtk_image_set_from_icon_name (GTK_IMAGE (widget), "preferences-system-network", GTK_ICON_SIZE_DIALOG); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "label_proxy_device")); gtk_label_set_label (GTK_LABEL (widget), _("Proxy")); widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "label_proxy_status")); gtk_label_set_label (GTK_LABEL (widget), ""); /* hide the switch until we get some more detail in the mockup */ widget = GTK_WIDGET (gtk_builder_get_object (proxy->priv->builder, "device_proxy_off_switch")); if (widget != NULL) gtk_widget_hide (widget); } NetProxy * net_proxy_new (void) { NetProxy *proxy; proxy = g_object_new (NET_TYPE_PROXY, "removable", FALSE, "id", "proxy", NULL); return NET_PROXY (proxy); }
450
./cinnamon-control-center/panels/network/network-dialogs.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011 Giovanni Campagna <scampa.giovanni@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Portions of this code were taken from network-manager-applet. * Copyright 2008 - 2011 Red Hat, Inc. */ #include <shell/cc-shell.h> #include <nm-utils.h> #include <nm-connection.h> #include <nm-setting-gsm.h> #include <nm-setting-cdma.h> #include <nm-setting-serial.h> #include <nm-device-modem.h> #include <nm-device-wifi.h> #include "network-dialogs.h" #include "nm-wireless-dialog.h" #include "nm-mobile-wizard.h" typedef struct { NMClient *client; NMRemoteSettings *settings; } WirelessDialogClosure; typedef struct { NMClient *client; NMRemoteSettings *settings; NMDevice *device; } MobileDialogClosure; static void wireless_dialog_closure_closure_notify (gpointer data, GClosure *gclosure) { WirelessDialogClosure *closure = data; g_object_unref (closure->client); g_object_unref (closure->settings); g_slice_free (WirelessDialogClosure, data); } static void mobile_dialog_closure_free (gpointer data) { MobileDialogClosure *closure = data; g_object_unref (closure->client); g_object_unref (closure->settings); g_object_unref (closure->device); g_slice_free (MobileDialogClosure, data); } static gboolean wifi_can_create_wifi_network (NMClient *client) { NMClientPermissionResult perm; /* FIXME: check WIFI_SHARE_PROTECTED too, and make the wireless dialog * handle the permissions as well so that admins can restrict open network * creation separately from protected network creation. */ perm = nm_client_get_permission_result (client, NM_CLIENT_PERMISSION_WIFI_SHARE_OPEN); if (perm == NM_CLIENT_PERMISSION_RESULT_YES || perm == NM_CLIENT_PERMISSION_RESULT_AUTH) return TRUE; return FALSE; } static void activate_existing_cb (NMClient *client, NMActiveConnection *active, GError *error, gpointer user_data) { if (error) g_warning ("Failed to activate connection: (%d) %s", error->code, error->message); } static void activate_new_cb (NMClient *client, NMActiveConnection *active, const char *connection_path, GError *error, gpointer user_data) { if (error) g_warning ("Failed to add new connection: (%d) %s", error->code, error->message); } static void nag_dialog_response_cb (GtkDialog *nag_dialog, gint response, gpointer user_data) { NMAWirelessDialog *wireless_dialog = NMA_WIRELESS_DIALOG (user_data); if (response == GTK_RESPONSE_NO) { /* user opted not to correct the warning */ nma_wireless_dialog_set_nag_ignored (wireless_dialog, TRUE); gtk_dialog_response (GTK_DIALOG (wireless_dialog), GTK_RESPONSE_OK); } } static void wireless_dialog_response_cb (GtkDialog *foo, gint response, gpointer user_data) { NMAWirelessDialog *dialog = NMA_WIRELESS_DIALOG (foo); WirelessDialogClosure *closure = user_data; NMConnection *connection, *fuzzy_match = NULL; NMDevice *device; NMAccessPoint *ap; GSList *all, *iter; if (response != GTK_RESPONSE_OK) goto done; if (!nma_wireless_dialog_get_nag_ignored (dialog)) { GtkWidget *nag_dialog; /* Nag the user about certificates or whatever. Only destroy the dialog * if no nagging was done. */ nag_dialog = nma_wireless_dialog_nag_user (dialog); if (nag_dialog) { gtk_window_set_transient_for (GTK_WINDOW (nag_dialog), GTK_WINDOW (dialog)); g_signal_connect (nag_dialog, "response", G_CALLBACK (nag_dialog_response_cb), dialog); return; } } /* nma_wireless_dialog_get_connection() returns a connection with the * refcount incremented, so the caller must remember to unref it. */ connection = nma_wireless_dialog_get_connection (dialog, &device, &ap); g_assert (connection); g_assert (device); /* Find a similar connection and use that instead */ all = nm_remote_settings_list_connections (closure->settings); for (iter = all; iter; iter = g_slist_next (iter)) { if (nm_connection_compare (connection, NM_CONNECTION (iter->data), (NM_SETTING_COMPARE_FLAG_FUZZY | NM_SETTING_COMPARE_FLAG_IGNORE_ID))) { fuzzy_match = NM_CONNECTION (iter->data); break; } } g_slist_free (all); if (fuzzy_match) { nm_client_activate_connection (closure->client, fuzzy_match, device, ap ? nm_object_get_path (NM_OBJECT (ap)) : NULL, activate_existing_cb, NULL); } else { NMSetting *s_con; NMSettingWireless *s_wifi; const char *mode = NULL; /* Entirely new connection */ /* Don't autoconnect adhoc networks by default for now */ s_wifi = (NMSettingWireless *) nm_connection_get_setting (connection, NM_TYPE_SETTING_WIRELESS); if (s_wifi) mode = nm_setting_wireless_get_mode (s_wifi); if (g_strcmp0 (mode, "adhoc") == 0) { s_con = nm_connection_get_setting (connection, NM_TYPE_SETTING_CONNECTION); if (!s_con) { s_con = nm_setting_connection_new (); nm_connection_add_setting (connection, s_con); } g_object_set (G_OBJECT (s_con), NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NULL); } nm_client_add_and_activate_connection (closure->client, connection, device, ap ? nm_object_get_path (NM_OBJECT (ap)) : NULL, activate_new_cb, NULL); } /* Balance nma_wireless_dialog_get_connection() */ g_object_unref (connection); done: gtk_widget_hide (GTK_WIDGET (dialog)); gtk_widget_destroy (GTK_WIDGET (dialog)); } static void show_wireless_dialog (CcNetworkPanel *panel, NMClient *client, NMRemoteSettings *settings, GtkWidget *dialog) { WirelessDialogClosure *closure; g_object_set (G_OBJECT (dialog), "modal", TRUE, NULL); closure = g_slice_new (WirelessDialogClosure); closure->client = g_object_ref (client); closure->settings = g_object_ref (settings); g_signal_connect_data (dialog, "response", G_CALLBACK (wireless_dialog_response_cb), closure, wireless_dialog_closure_closure_notify, 0); gtk_widget_show (dialog); } void cc_network_panel_create_wifi_network (CcNetworkPanel *panel, NMClient *client, NMRemoteSettings *settings) { if (wifi_can_create_wifi_network (client)) { show_wireless_dialog (panel, client, settings, nma_wireless_dialog_new_for_create (client, settings)); } } void cc_network_panel_connect_to_hidden_network (CcNetworkPanel *panel, NMClient *client, NMRemoteSettings *settings) { g_debug ("connect to hidden wifi"); show_wireless_dialog (panel, client, settings, nma_wireless_dialog_new_for_other (client, settings)); } void cc_network_panel_connect_to_8021x_network (CcNetworkPanel *panel, NMClient *client, NMRemoteSettings *settings, NMDevice *device, const gchar *arg_access_point) { NMConnection *connection; NMSettingConnection *s_con; NMSettingWireless *s_wifi; NMSettingWirelessSecurity *s_wsec; NMSetting8021x *s_8021x; NM80211ApSecurityFlags wpa_flags, rsn_flags; GtkWidget *dialog; char *uuid; NMAccessPoint *ap; g_debug ("connect to 8021x wifi"); ap = nm_device_wifi_get_access_point_by_path (NM_DEVICE_WIFI (device), arg_access_point); if (ap == NULL) { g_warning ("didn't find access point with path %s", arg_access_point); return; } /* If the AP is WPA[2]-Enterprise then we need to set up a minimal 802.1x * setting and ask the user for more information. */ rsn_flags = nm_access_point_get_rsn_flags (ap); wpa_flags = nm_access_point_get_wpa_flags (ap); if (!(rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) && !(wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { g_warning ("Network panel loaded with connect-8021x-wifi but the " "access point does not support 802.1x"); return; } connection = nm_connection_new (); /* Need a UUID for the "always ask" stuff in the Dialog of Doom */ s_con = (NMSettingConnection *) nm_setting_connection_new (); uuid = nm_utils_uuid_generate (); g_object_set (s_con, NM_SETTING_CONNECTION_UUID, uuid, NULL); g_free (uuid); nm_connection_add_setting (connection, NM_SETTING (s_con)); s_wifi = (NMSettingWireless *) nm_setting_wireless_new (); nm_connection_add_setting (connection, NM_SETTING (s_wifi)); g_object_set (s_wifi, NM_SETTING_WIRELESS_SSID, nm_access_point_get_ssid (ap), NM_SETTING_WIRELESS_SEC, NM_SETTING_WIRELESS_SECURITY_SETTING_NAME, NULL); s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new (); g_object_set (s_wsec, NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-eap", NULL); nm_connection_add_setting (connection, NM_SETTING (s_wsec)); s_8021x = (NMSetting8021x *) nm_setting_802_1x_new (); nm_setting_802_1x_add_eap_method (s_8021x, "ttls"); g_object_set (s_8021x, NM_SETTING_802_1X_PHASE2_AUTH, "mschapv2", NULL); nm_connection_add_setting (connection, NM_SETTING (s_8021x)); dialog = nma_wireless_dialog_new (client, settings, connection, device, ap, FALSE); show_wireless_dialog (panel, client, settings, dialog); } static void connect_3g (NMConnection *connection, gboolean canceled, gpointer user_data) { MobileDialogClosure *closure = user_data; if (canceled == FALSE) { g_return_if_fail (connection != NULL); /* Ask NM to add the new connection and activate it; NM will fill in the * missing details based on the specific object and the device. */ nm_client_add_and_activate_connection (closure->client, connection, closure->device, "/", activate_new_cb, NULL); } mobile_dialog_closure_free (closure); } static void cdma_mobile_wizard_done (NMAMobileWizard *wizard, gboolean canceled, NMAMobileWizardAccessMethod *method, gpointer user_data) { NMConnection *connection = NULL; if (!canceled && method) { NMSetting *setting; char *uuid, *id; if (method->devtype != NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO) { g_warning ("Unexpected device type (not CDMA)."); canceled = TRUE; goto done; } connection = nm_connection_new (); setting = nm_setting_cdma_new (); g_object_set (setting, NM_SETTING_CDMA_NUMBER, "#777", NM_SETTING_CDMA_USERNAME, method->username, NM_SETTING_CDMA_PASSWORD, method->password, NULL); nm_connection_add_setting (connection, setting); /* Serial setting */ setting = nm_setting_serial_new (); g_object_set (setting, NM_SETTING_SERIAL_BAUD, 115200, NM_SETTING_SERIAL_BITS, 8, NM_SETTING_SERIAL_PARITY, 'n', NM_SETTING_SERIAL_STOPBITS, 1, NULL); nm_connection_add_setting (connection, setting); nm_connection_add_setting (connection, nm_setting_ppp_new ()); setting = nm_setting_connection_new (); if (method->plan_name) id = g_strdup_printf ("%s %s", method->provider_name, method->plan_name); else id = g_strdup_printf ("%s connection", method->provider_name); uuid = nm_utils_uuid_generate (); g_object_set (setting, NM_SETTING_CONNECTION_ID, id, NM_SETTING_CONNECTION_TYPE, NM_SETTING_CDMA_SETTING_NAME, NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NM_SETTING_CONNECTION_UUID, uuid, NULL); g_free (uuid); g_free (id); nm_connection_add_setting (connection, setting); } done: connect_3g (connection, canceled, user_data); nma_mobile_wizard_destroy (wizard); } static void gsm_mobile_wizard_done (NMAMobileWizard *wizard, gboolean canceled, NMAMobileWizardAccessMethod *method, gpointer user_data) { NMConnection *connection = NULL; if (!canceled && method) { NMSetting *setting; char *uuid, *id; if (method->devtype != NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS) { g_warning ("Unexpected device type (not GSM)."); canceled = TRUE; goto done; } connection = nm_connection_new (); setting = nm_setting_gsm_new (); g_object_set (setting, NM_SETTING_GSM_NUMBER, "*99#", NM_SETTING_GSM_USERNAME, method->username, NM_SETTING_GSM_PASSWORD, method->password, NM_SETTING_GSM_APN, method->gsm_apn, NULL); nm_connection_add_setting (connection, setting); /* Serial setting */ setting = nm_setting_serial_new (); g_object_set (setting, NM_SETTING_SERIAL_BAUD, 115200, NM_SETTING_SERIAL_BITS, 8, NM_SETTING_SERIAL_PARITY, 'n', NM_SETTING_SERIAL_STOPBITS, 1, NULL); nm_connection_add_setting (connection, setting); nm_connection_add_setting (connection, nm_setting_ppp_new ()); setting = nm_setting_connection_new (); if (method->plan_name) id = g_strdup_printf ("%s %s", method->provider_name, method->plan_name); else id = g_strdup_printf ("%s connection", method->provider_name); uuid = nm_utils_uuid_generate (); g_object_set (setting, NM_SETTING_CONNECTION_ID, id, NM_SETTING_CONNECTION_TYPE, NM_SETTING_GSM_SETTING_NAME, NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NM_SETTING_CONNECTION_UUID, uuid, NULL); g_free (uuid); g_free (id); nm_connection_add_setting (connection, setting); } done: connect_3g (connection, canceled, user_data); nma_mobile_wizard_destroy (wizard); } static void toplevel_shown (GtkWindow *toplevel, GParamSpec *pspec, NMAMobileWizard *wizard) { gboolean visible = FALSE; g_object_get (G_OBJECT (toplevel), "visible", &visible, NULL); if (visible) nma_mobile_wizard_present (wizard); } static gboolean show_wizard_idle_cb (NMAMobileWizard *wizard) { nma_mobile_wizard_present (wizard); return FALSE; } void cc_network_panel_connect_to_3g_network (CcNetworkPanel *panel, NMClient *client, NMRemoteSettings *settings, NMDevice *device) { GtkWidget *toplevel = cc_shell_get_toplevel (cc_panel_get_shell (CC_PANEL (panel))); if (toplevel == NULL) { toplevel = GTK_WIDGET (panel); } MobileDialogClosure *closure; NMAMobileWizard *wizard; NMDeviceModemCapabilities caps; gboolean visible = FALSE; g_debug ("connect to 3g"); if (!NM_IS_DEVICE_MODEM (device)) { g_warning ("Network panel loaded with connect-3g but the selected device" " is not a modem"); return; } closure = g_slice_new (MobileDialogClosure); closure->client = g_object_ref (client); closure->settings = g_object_ref (settings); closure->device = g_object_ref (device); caps = nm_device_modem_get_current_capabilities (NM_DEVICE_MODEM (device)); if (caps & NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS) { wizard = nma_mobile_wizard_new (GTK_WINDOW (toplevel), NULL, NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS, FALSE, gsm_mobile_wizard_done, closure); if (wizard == NULL) { g_warning ("failed to construct GSM wizard"); return; } } else if (caps & NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO) { wizard = nma_mobile_wizard_new (GTK_WINDOW (toplevel), NULL, NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO, FALSE, cdma_mobile_wizard_done, closure); if (wizard == NULL) { g_warning ("failed to construct CDMA wizard"); return; } } else { g_warning ("Network panel loaded with connect-3g but the selected device" " does not support GSM or CDMA"); mobile_dialog_closure_free (closure); return; } g_object_get (G_OBJECT (toplevel), "visible", &visible, NULL); if (visible) { g_debug ("Scheduling showing the Mobile wizard"); g_idle_add ((GSourceFunc) show_wizard_idle_cb, wizard); } else { g_debug ("Will show wizard a bit later, toplevel is not visible"); g_signal_connect (G_OBJECT (toplevel), "notify::visible", G_CALLBACK (toplevel_shown), wizard); } }
451
./cinnamon-control-center/panels/network/cc-network-panel.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2010-2012 Richard Hughes <richard@hughsie.com> * Copyright (C) 2012 Thomas Bechtold <thomasbechtold@jpberlin.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <config.h> #include <glib/gi18n-lib.h> #include <stdlib.h> #include "cc-network-panel.h" #include "nm-remote-settings.h" #include "nm-client.h" #include "nm-device.h" #include "nm-device-modem.h" #include "net-device.h" #include "net-device-mobile.h" #include "net-device-wifi.h" #include "net-device-wired.h" #include "net-object.h" #include "net-proxy.h" #include "net-vpn.h" #include "rfkill-glib.h" #include "panel-common.h" #include "network-dialogs.h" CC_PANEL_REGISTER (CcNetworkPanel, cc_network_panel) #define NETWORK_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_NETWORK_PANEL, CcNetworkPanelPrivate)) typedef enum { OPERATION_NULL, OPERATION_SHOW_DEVICE, OPERATION_CREATE_WIFI, OPERATION_CONNECT_HIDDEN, OPERATION_CONNECT_8021X, OPERATION_CONNECT_MOBILE } CmdlineOperation; struct _CcNetworkPanelPrivate { GCancellable *cancellable; GtkBuilder *builder; GtkWidget *treeview; NMClient *client; NMRemoteSettings *remote_settings; gboolean updating_device; guint add_header_widgets_idle; guint nm_warning_idle; guint refresh_idle; /* Killswitch stuff */ GtkWidget *kill_switch_header; CcRfkillGlib *rfkill; GtkSwitch *rfkill_switch; GHashTable *killswitches; /* wireless dialog stuff */ CmdlineOperation arg_operation; gchar *arg_device; gchar *arg_access_point; gboolean operation_done; }; enum { PANEL_DEVICES_COLUMN_ICON, PANEL_DEVICES_COLUMN_TITLE, PANEL_DEVICES_COLUMN_SORT, PANEL_DEVICES_COLUMN_OBJECT, PANEL_DEVICES_COLUMN_LAST }; enum { PROP_0, PROP_ARGV }; static NetObject *find_in_model_by_id (CcNetworkPanel *panel, const gchar *id); static void handle_argv (CcNetworkPanel *panel); static void cc_network_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static CmdlineOperation cmdline_operation_from_string (const gchar *string) { if (g_strcmp0 (string, "create-wifi") == 0) return OPERATION_CREATE_WIFI; if (g_strcmp0 (string, "connect-hidden-wifi") == 0) return OPERATION_CONNECT_HIDDEN; if (g_strcmp0 (string, "connect-8021x-wifi") == 0) return OPERATION_CONNECT_8021X; if (g_strcmp0 (string, "connect-3g") == 0) return OPERATION_CONNECT_MOBILE; if (g_strcmp0 (string, "show-device") == 0) return OPERATION_SHOW_DEVICE; g_warning ("Invalid additional argument %s", string); return OPERATION_NULL; } static void char_clear_pointer (gchar *pointer) { if (pointer) { g_free (pointer); pointer = NULL; } } static void reset_command_line_args (CcNetworkPanel *self) { self->priv->arg_operation = OPERATION_NULL; char_clear_pointer (self->priv->arg_device); char_clear_pointer (self->priv->arg_access_point); } static gboolean verify_argv (CcNetworkPanel *self, const char **args) { switch (self->priv->arg_operation) { case OPERATION_CONNECT_MOBILE: case OPERATION_CONNECT_8021X: case OPERATION_SHOW_DEVICE: if (self->priv->arg_device == NULL) { g_warning ("Operation %s requires an object path", args[0]); return FALSE; } default: return TRUE; } } static void cc_network_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { CcNetworkPanel *self = CC_NETWORK_PANEL (object); CcNetworkPanelPrivate *priv = self->priv; switch (property_id) { case PROP_ARGV: { gchar **args; reset_command_line_args (self); args = g_value_get_boxed (value); if (args) { g_debug ("Invoked with operation %s", args[0]); if (args[0]) priv->arg_operation = cmdline_operation_from_string (args[0]); if (args[0] && args[1]) priv->arg_device = g_strdup (args[1]); if (args[0] && args[1] && args[2]) priv->arg_access_point = g_strdup (args[2]); if (verify_argv (self, (const char **) args) == FALSE) { reset_command_line_args (self); return; } g_debug ("Calling handle_argv() after setting property"); handle_argv (self); } break; } default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_network_panel_dispose (GObject *object) { CcNetworkPanelPrivate *priv = CC_NETWORK_PANEL (object)->priv; if (priv->cancellable != NULL) g_cancellable_cancel (priv->cancellable); g_clear_object (&priv->cancellable); g_clear_object (&priv->builder); g_clear_object (&priv->client); g_clear_object (&priv->remote_settings); g_clear_object (&priv->kill_switch_header); g_clear_object (&priv->rfkill); if (priv->killswitches) { g_hash_table_destroy (priv->killswitches); priv->killswitches = NULL; } priv->rfkill_switch = NULL; if (priv->refresh_idle != 0) { g_source_remove (priv->refresh_idle); priv->refresh_idle = 0; } if (priv->nm_warning_idle != 0) { g_source_remove (priv->nm_warning_idle); priv->nm_warning_idle = 0; } if (priv->add_header_widgets_idle != 0) { g_source_remove (priv->add_header_widgets_idle); priv->add_header_widgets_idle = 0; } G_OBJECT_CLASS (cc_network_panel_parent_class)->dispose (object); } static void cc_network_panel_finalize (GObject *object) { CcNetworkPanel *panel = CC_NETWORK_PANEL (object); reset_command_line_args (panel); G_OBJECT_CLASS (cc_network_panel_parent_class)->finalize (object); } static const char * cc_network_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/net"; else return "help:gnome-help/net"; } static void cc_network_panel_class_init (CcNetworkPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcNetworkPanelPrivate)); panel_class->get_help_uri = cc_network_panel_get_help_uri; object_class->get_property = cc_network_panel_get_property; object_class->set_property = cc_network_panel_set_property; object_class->dispose = cc_network_panel_dispose; object_class->finalize = cc_network_panel_finalize; g_object_class_override_property (object_class, PROP_ARGV, "argv"); } static NetObject * get_selected_object (CcNetworkPanel *panel) { GtkTreeSelection *selection; GtkTreeModel *model; GtkTreeIter iter; NetObject *object = NULL; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->priv->treeview)); if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { return NULL; } gtk_tree_model_get (model, &iter, PANEL_DEVICES_COLUMN_OBJECT, &object, -1); return object; } static void select_first_device (CcNetworkPanel *panel) { GtkTreePath *path; GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->priv->treeview)); /* select the first device */ path = gtk_tree_path_new_from_string ("0"); gtk_tree_selection_select_path (selection, path); gtk_tree_path_free (path); } static void select_tree_iter (CcNetworkPanel *panel, GtkTreeIter *iter) { GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->priv->treeview)); gtk_tree_selection_select_iter (selection, iter); } static void object_removed_cb (NetObject *object, CcNetworkPanel *panel) { gboolean ret; NetObject *object_tmp; GtkTreeIter iter; GtkTreeModel *model; GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->priv->treeview)); /* remove device from model */ model = GTK_TREE_MODEL (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* get the other elements */ do { gtk_tree_model_get (model, &iter, PANEL_DEVICES_COLUMN_OBJECT, &object_tmp, -1); if (g_strcmp0 (net_object_get_id (object), net_object_get_id (object_tmp)) == 0) { g_object_unref (object_tmp); if (!gtk_list_store_remove (GTK_LIST_STORE (model), &iter)) gtk_tree_model_get_iter_first (model, &iter); gtk_tree_selection_select_iter (selection, &iter); break; } g_object_unref (object_tmp); } while (gtk_tree_model_iter_next (model, &iter)); } static gboolean handle_argv_for_device (CcNetworkPanel *panel, NMDevice *device, GtkTreeIter *iter) { CcNetworkPanelPrivate *priv = panel->priv; NMDeviceType type; if (priv->arg_operation == OPERATION_NULL) return TRUE; type = nm_device_get_device_type (device); if (type == NM_DEVICE_TYPE_WIFI && (priv->arg_operation == OPERATION_CREATE_WIFI || priv->arg_operation == OPERATION_CONNECT_HIDDEN)) { g_debug ("Selecting wifi device"); select_tree_iter (panel, iter); if (priv->arg_operation == OPERATION_CREATE_WIFI) cc_network_panel_create_wifi_network (panel, priv->client, priv->remote_settings); else cc_network_panel_connect_to_hidden_network (panel, priv->client, priv->remote_settings); reset_command_line_args (panel); /* done */ return TRUE; } else if (g_strcmp0 (nm_object_get_path (NM_OBJECT (device)), priv->arg_device) == 0) { if (priv->arg_operation == OPERATION_CONNECT_MOBILE) { cc_network_panel_connect_to_3g_network (panel, priv->client, priv->remote_settings, device); reset_command_line_args (panel); /* done */ select_tree_iter (panel, iter); return TRUE; } else if (priv->arg_operation == OPERATION_CONNECT_8021X) { cc_network_panel_connect_to_8021x_network (panel, priv->client, priv->remote_settings, device, priv->arg_access_point); reset_command_line_args (panel); /* done */ select_tree_iter (panel, iter); return TRUE; } else if (priv->arg_operation == OPERATION_SHOW_DEVICE) { select_tree_iter (panel, iter); reset_command_line_args (panel); /* done */ return TRUE; } } return FALSE; } static void handle_argv (CcNetworkPanel *panel) { GtkTreeModel *model; GtkTreeIter iter; gboolean ret; if (panel->priv->arg_operation == OPERATION_NULL) return; model = GTK_TREE_MODEL (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); ret = gtk_tree_model_get_iter_first (model, &iter); while (ret) { GObject *object_tmp; NMDevice *device; gboolean done = FALSE; gtk_tree_model_get (model, &iter, PANEL_DEVICES_COLUMN_OBJECT, &object_tmp, -1); if (g_object_class_find_property (G_OBJECT_GET_CLASS (object_tmp), "nm-device") != NULL) { g_object_get (object_tmp, "nm-device", &device, NULL); done = handle_argv_for_device (panel, device, &iter); g_object_unref (device); } g_object_unref (object_tmp); if (done) return; ret = gtk_tree_model_iter_next (model, &iter); } g_debug ("Could not handle argv operation, no matching device yet?"); } static gboolean panel_add_device (CcNetworkPanel *panel, NMDevice *device) { const gchar *title; GtkListStore *liststore_devices; GtkTreeIter iter; NMDeviceType type; NetDevice *net_device; CcNetworkPanelPrivate *priv = panel->priv; GtkNotebook *notebook; GtkSizeGroup *size_group; GType device_g_type; /* do we have an existing object with this id? */ if (find_in_model_by_id (panel, nm_device_get_udi (device)) != NULL) goto out; type = nm_device_get_device_type (device); g_debug ("device %s type %i path %s", nm_device_get_udi (device), type, nm_object_get_path (NM_OBJECT (device))); /* map the NMDeviceType to the GType */ switch (type) { case NM_DEVICE_TYPE_ETHERNET: device_g_type = NET_TYPE_DEVICE_WIRED; break; case NM_DEVICE_TYPE_MODEM: device_g_type = NET_TYPE_DEVICE_MOBILE; break; case NM_DEVICE_TYPE_WIFI: device_g_type = NET_TYPE_DEVICE_WIFI; break; default: goto out; } /* create device */ title = panel_device_to_localized_string (device); net_device = g_object_new (device_g_type, "panel", panel, "removable", FALSE, "cancellable", panel->priv->cancellable, "client", panel->priv->client, "remote-settings", panel->priv->remote_settings, "nm-device", device, "id", nm_device_get_udi (device), "title", title, NULL); /* add as a panel */ if (device_g_type != NET_TYPE_DEVICE) { notebook = GTK_NOTEBOOK (gtk_builder_get_object (panel->priv->builder, "notebook_types")); size_group = GTK_SIZE_GROUP (gtk_builder_get_object (panel->priv->builder, "sizegroup1")); net_object_add_to_notebook (NET_OBJECT (net_device), notebook, size_group); } liststore_devices = GTK_LIST_STORE (gtk_builder_get_object (priv->builder, "liststore_devices")); g_signal_connect_object (net_device, "removed", G_CALLBACK (object_removed_cb), panel, 0); gtk_list_store_append (liststore_devices, &iter); gtk_list_store_set (liststore_devices, &iter, PANEL_DEVICES_COLUMN_ICON, panel_device_to_icon_name (device), PANEL_DEVICES_COLUMN_SORT, panel_device_to_sortable_string (device), PANEL_DEVICES_COLUMN_TITLE, title, PANEL_DEVICES_COLUMN_OBJECT, net_device, -1); out: return FALSE; } static void panel_remove_device (CcNetworkPanel *panel, NMDevice *device) { gboolean ret; NetObject *object_tmp; GtkTreeIter iter; GtkTreeModel *model; /* remove device from model */ model = GTK_TREE_MODEL (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* get the other elements */ do { gtk_tree_model_get (model, &iter, PANEL_DEVICES_COLUMN_OBJECT, &object_tmp, -1); if (g_strcmp0 (net_object_get_id (object_tmp), nm_device_get_udi (device)) == 0) { gtk_list_store_remove (GTK_LIST_STORE (model), &iter); g_object_unref (object_tmp); break; } g_object_unref (object_tmp); } while (gtk_tree_model_iter_next (model, &iter)); } static void panel_add_devices_columns (CcNetworkPanel *panel, GtkTreeView *treeview) { CcNetworkPanelPrivate *priv = panel->priv; GtkCellRenderer *renderer; GtkListStore *liststore_devices; GtkTreeViewColumn *column; /* image */ renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (renderer, "stock-size", gtk_icon_size_from_name ("cc-sidebar-list"), NULL); gtk_cell_renderer_set_padding (renderer, 4, 4); column = gtk_tree_view_column_new_with_attributes ("icon", renderer, "icon-name", PANEL_DEVICES_COLUMN_ICON, NULL); gtk_tree_view_append_column (treeview, column); /* column for text */ renderer = gtk_cell_renderer_text_new (); g_object_set (renderer, "wrap-mode", PANGO_WRAP_WORD, "ellipsize", PANGO_ELLIPSIZE_END, NULL); column = gtk_tree_view_column_new_with_attributes ("title", renderer, "markup", PANEL_DEVICES_COLUMN_TITLE, NULL); gtk_tree_view_column_set_sort_column_id (column, PANEL_DEVICES_COLUMN_SORT); liststore_devices = GTK_LIST_STORE (gtk_builder_get_object (priv->builder, "liststore_devices")); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (liststore_devices), PANEL_DEVICES_COLUMN_SORT, GTK_SORT_ASCENDING); gtk_tree_view_append_column (treeview, column); gtk_tree_view_column_set_expand (column, TRUE); } static void nm_devices_treeview_clicked_cb (GtkTreeSelection *selection, CcNetworkPanel *panel) { CcNetworkPanelPrivate *priv = panel->priv; const gchar *id_tmp; const gchar *needle; GList *l; GList *panels = NULL; GtkNotebook *notebook; GtkTreeIter iter; GtkTreeModel *model; GtkWidget *widget; guint i = 0; NetObject *object = NULL; if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { g_debug ("no row selected"); goto out; } /* find the widget in the notebook that matches the object ID */ object = get_selected_object (panel); needle = net_object_get_id (object); notebook = GTK_NOTEBOOK (gtk_builder_get_object (priv->builder, "notebook_types")); panels = gtk_container_get_children (GTK_CONTAINER (notebook)); for (l = panels; l != NULL; l = l->next) { widget = GTK_WIDGET (l->data); id_tmp = g_object_get_data (G_OBJECT (widget), "NetObject::id"); if (g_strcmp0 (needle, id_tmp) == 0) { gtk_notebook_set_current_page (notebook, i); /* object is deletable? */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "remove_toolbutton")); gtk_widget_set_sensitive (widget, net_object_get_removable (object)); break; } i++; } out: g_list_free (panels); } static void panel_add_proxy_device (CcNetworkPanel *panel) { gchar *title; GtkListStore *liststore_devices; GtkTreeIter iter; NetProxy *proxy; GtkNotebook *notebook; GtkSizeGroup *size_group; /* add proxy to notebook */ proxy = net_proxy_new (); notebook = GTK_NOTEBOOK (gtk_builder_get_object (panel->priv->builder, "notebook_types")); size_group = GTK_SIZE_GROUP (gtk_builder_get_object (panel->priv->builder, "sizegroup1")); net_object_add_to_notebook (NET_OBJECT (proxy), notebook, size_group); /* add proxy to device list */ liststore_devices = GTK_LIST_STORE (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); title = g_strdup_printf ("%s", _("Network proxy")); gtk_list_store_append (liststore_devices, &iter); gtk_list_store_set (liststore_devices, &iter, PANEL_DEVICES_COLUMN_ICON, "preferences-system-network", PANEL_DEVICES_COLUMN_TITLE, title, PANEL_DEVICES_COLUMN_SORT, "9", PANEL_DEVICES_COLUMN_OBJECT, proxy, -1); g_free (title); g_object_unref (proxy); } static void cc_network_panel_notify_enable_active_cb (GtkSwitch *sw, GParamSpec *pspec, CcNetworkPanel *panel) { gboolean enable; struct rfkill_event event; enable = gtk_switch_get_active (sw); g_debug ("Setting killswitch to %d", enable); memset (&event, 0, sizeof(event)); event.op = RFKILL_OP_CHANGE_ALL; event.type = RFKILL_TYPE_ALL; event.soft = enable ? 1 : 0; if (cc_rfkill_glib_send_event (panel->priv->rfkill, &event) < 0) g_warning ("Setting the killswitch %s failed", enable ? "on" : "off"); } static void connection_state_changed (NMActiveConnection *c, GParamSpec *pspec, CcNetworkPanel *panel) { } static void active_connections_changed (NMClient *client, GParamSpec *pspec, gpointer user_data) { CcNetworkPanel *panel = user_data; const GPtrArray *connections; int i, j; g_debug ("Active connections changed:"); connections = nm_client_get_active_connections (client); for (i = 0; connections && (i < connections->len); i++) { NMActiveConnection *connection; const GPtrArray *devices; connection = g_ptr_array_index (connections, i); g_debug (" %s", nm_object_get_path (NM_OBJECT (connection))); devices = nm_active_connection_get_devices (connection); for (j = 0; devices && j < devices->len; j++) g_debug (" %s", nm_device_get_udi (g_ptr_array_index (devices, j))); if (NM_IS_VPN_CONNECTION (connection)) g_debug (" VPN base connection: %s", nm_active_connection_get_specific_object (connection)); if (g_object_get_data (G_OBJECT (connection), "has-state-changed-handler") == NULL) { g_signal_connect_object (connection, "notify::state", G_CALLBACK (connection_state_changed), panel, 0); g_object_set_data (G_OBJECT (connection), "has-state-changed-handler", GINT_TO_POINTER (TRUE)); } } } static void device_added_cb (NMClient *client, NMDevice *device, CcNetworkPanel *panel) { g_debug ("New device added"); panel_add_device (panel, device); } static void device_removed_cb (NMClient *client, NMDevice *device, CcNetworkPanel *panel) { g_debug ("Device removed"); panel_remove_device (panel, device); } static void manager_running (NMClient *client, GParamSpec *pspec, gpointer user_data) { const GPtrArray *devices; int i; NMDevice *device_tmp; GtkListStore *liststore_devices; gboolean selected = FALSE; CcNetworkPanel *panel = CC_NETWORK_PANEL (user_data); /* clear all devices we added */ if (!nm_client_get_manager_running (client)) { g_debug ("NM disappeared"); liststore_devices = GTK_LIST_STORE (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); gtk_list_store_clear (liststore_devices); panel_add_proxy_device (panel); goto out; } g_debug ("coldplugging devices"); devices = nm_client_get_devices (client); if (devices == NULL) { g_debug ("No devices to add"); return; } for (i = 0; i < devices->len; i++) { device_tmp = g_ptr_array_index (devices, i); selected = panel_add_device (panel, device_tmp) || selected; } out: if (!selected) { /* select the first device */ select_first_device (panel); } g_debug ("Calling handle_argv() after cold-plugging devices"); handle_argv (panel); } static NetObject * find_in_model_by_id (CcNetworkPanel *panel, const gchar *id) { gboolean ret; NetObject *object_tmp; GtkTreeIter iter; GtkTreeModel *model; NetObject *object = NULL; /* find in model */ model = GTK_TREE_MODEL (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) goto out; /* get the other elements */ ret = FALSE; do { gtk_tree_model_get (model, &iter, PANEL_DEVICES_COLUMN_OBJECT, &object_tmp, -1); if (object_tmp != NULL) { g_debug ("got %s", net_object_get_id (object_tmp)); if (g_strcmp0 (net_object_get_id (object_tmp), id) == 0) object = object_tmp; g_object_unref (object_tmp); } } while (object == NULL && gtk_tree_model_iter_next (model, &iter)); out: return object; } static void panel_add_vpn_device (CcNetworkPanel *panel, NMConnection *connection) { gchar *title; gchar *title_markup; GtkListStore *liststore_devices; GtkTreeIter iter; NetVpn *net_vpn; const gchar *id; GtkNotebook *notebook; GtkSizeGroup *size_group; /* does already exist */ id = nm_connection_get_path (connection); if (find_in_model_by_id (panel, id) != NULL) return; /* add as a virtual object */ net_vpn = g_object_new (NET_TYPE_VPN, "panel", panel, "removable", TRUE, "id", id, "connection", connection, "client", panel->priv->client, NULL); g_signal_connect_object (net_vpn, "removed", G_CALLBACK (object_removed_cb), panel, 0); /* add as a panel */ notebook = GTK_NOTEBOOK (gtk_builder_get_object (panel->priv->builder, "notebook_types")); size_group = GTK_SIZE_GROUP (gtk_builder_get_object (panel->priv->builder, "sizegroup1")); net_object_add_to_notebook (NET_OBJECT (net_vpn), notebook, size_group); liststore_devices = GTK_LIST_STORE (gtk_builder_get_object (panel->priv->builder, "liststore_devices")); title = g_strdup_printf (_("%s VPN"), nm_connection_get_id (connection)); title_markup = g_strdup (title); net_object_set_title (NET_OBJECT (net_vpn), title); gtk_list_store_append (liststore_devices, &iter); gtk_list_store_set (liststore_devices, &iter, PANEL_DEVICES_COLUMN_ICON, "network-vpn", PANEL_DEVICES_COLUMN_TITLE, title_markup, PANEL_DEVICES_COLUMN_SORT, "5", PANEL_DEVICES_COLUMN_OBJECT, net_vpn, -1); g_free (title); g_free (title_markup); } static void add_connection (CcNetworkPanel *panel, NMConnection *connection) { NMSettingConnection *s_con; const gchar *type; s_con = NM_SETTING_CONNECTION (nm_connection_get_setting (connection, NM_TYPE_SETTING_CONNECTION)); type = nm_setting_connection_get_connection_type (s_con); if (g_strcmp0 (type, "vpn") != 0) return; g_debug ("add %s/%s remote connection: %s", type, g_type_name_from_instance ((GTypeInstance*)connection), nm_connection_get_path (connection)); panel_add_vpn_device (panel, connection); } static void notify_new_connection_cb (NMRemoteSettings *settings, NMRemoteConnection *connection, CcNetworkPanel *panel) { add_connection (panel, NM_CONNECTION (connection)); } static void notify_connections_read_cb (NMRemoteSettings *settings, CcNetworkPanel *panel) { GSList *list, *iter; NMConnection *connection; list = nm_remote_settings_list_connections (settings); g_debug ("%p has %i remote connections", panel, g_slist_length (list)); for (iter = list; iter; iter = g_slist_next (iter)) { connection = NM_CONNECTION (iter->data); add_connection (panel, connection); } } static gboolean display_version_warning_idle (CcNetworkPanel *panel) { GtkWidget *dialog; GtkWidget *image; GtkWindow *window; const char *message; /* TRANSLATORS: the user is running a NM that is not API compatible */ message = _("The system network services are not compatible with this version."); window = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (panel))); dialog = gtk_message_dialog_new (window, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", message); image = gtk_image_new_from_icon_name ("computer-fail", GTK_ICON_SIZE_DIALOG); gtk_widget_show (image); gtk_message_dialog_set_image (GTK_MESSAGE_DIALOG (dialog), image); gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); return FALSE; } static gboolean panel_check_network_manager_version (CcNetworkPanel *panel) { const gchar *version; gchar **split = NULL; guint major = 0; guint micro = 0; guint minor = 0; gboolean ret = TRUE; /* parse running version */ version = nm_client_get_version (panel->priv->client); if (version != NULL) { split = g_strsplit (version, ".", -1); major = atoi (split[0]); minor = atoi (split[1]); micro = atoi (split[2]); } /* is it too new or old */ if (major > 0 || major > 9 || (minor <= 8 && micro < 992)) { ret = FALSE; /* do modal dialog in idle so we don't block startup */ panel->priv->nm_warning_idle = g_idle_add ((GSourceFunc)display_version_warning_idle, panel); } g_strfreev (split); return ret; } static void add_connection_cb (GtkToolButton *button, CcNetworkPanel *panel) { GtkWidget *dialog; gint response; dialog = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "connection_type_dialog")); gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (panel)))); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_hide (dialog); if (response == GTK_RESPONSE_OK) { GtkComboBox *combo; GtkTreeModel *model; GtkTreeIter iter; gchar *type; gchar *cmdline; GError *error; combo = GTK_COMBO_BOX (gtk_builder_get_object (panel->priv->builder, "connection_type_combo")); model = gtk_combo_box_get_model (combo); gtk_combo_box_get_active_iter (combo, &iter); type = NULL; gtk_tree_model_get (model, &iter, 1, &type, -1); cmdline = g_strdup_printf ("nm-connection-editor --create --type %s", type); g_debug ("Launching '%s'\n", cmdline); error = NULL; if (!g_spawn_command_line_async (cmdline, &error)) { g_warning ("Failed to launch nm-connection-editor: %s", error->message); g_error_free (error); } g_free (cmdline); g_free (type); } } static void remove_connection (GtkToolButton *button, CcNetworkPanel *panel) { NetObject *object; /* get current device */ object = get_selected_object (panel); if (object == NULL) return; /* delete the object */ net_object_delete (object); } static void on_toplevel_map (GtkWidget *widget, CcNetworkPanel *panel) { gboolean ret; /* is the user compiling against a new version, but running an * old daemon version? */ ret = panel_check_network_manager_version (panel); if (ret) { manager_running (panel->priv->client, NULL, panel); } else { /* just select the proxy settings */ select_first_device (panel); } } static void rfkill_changed (CcRfkillGlib *rfkill, GList *events, CcNetworkPanel *panel) { gboolean enabled; GList *l; GHashTableIter iter; gpointer key, value; enabled = TRUE; for (l = events; l != NULL; l = l->next) { struct rfkill_event *event = l->data; if (event->op == RFKILL_OP_ADD) g_hash_table_insert (panel->priv->killswitches, GINT_TO_POINTER (event->idx), GINT_TO_POINTER (event->soft || event->hard)); else if (event->op == RFKILL_OP_CHANGE) g_hash_table_insert (panel->priv->killswitches, GINT_TO_POINTER (event->idx), GINT_TO_POINTER (event->soft || event->hard)); else if (event->op == RFKILL_OP_DEL) g_hash_table_remove (panel->priv->killswitches, GINT_TO_POINTER (event->idx)); } g_hash_table_iter_init (&iter, panel->priv->killswitches); while (g_hash_table_iter_next (&iter, &key, &value)) { int idx, state; idx = GPOINTER_TO_INT (key); state = GPOINTER_TO_INT (value); g_debug ("Killswitch %d is %s", idx, state ? "enabled" : "disabled"); /* A single device that's enabled? airplane mode is off */ if (state == FALSE) { enabled = FALSE; break; } } if (enabled != gtk_switch_get_active (panel->priv->rfkill_switch)) { g_signal_handlers_block_by_func (panel->priv->rfkill_switch, cc_network_panel_notify_enable_active_cb, panel); gtk_switch_set_active (panel->priv->rfkill_switch, enabled); g_signal_handlers_unblock_by_func (panel->priv->rfkill_switch, cc_network_panel_notify_enable_active_cb, panel); } } static gboolean network_add_shell_header_widgets_cb (gpointer user_data) { CcNetworkPanel *panel = CC_NETWORK_PANEL (user_data); GtkWidget *box; GtkWidget *label; GtkWidget *widget; box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 3); /* TRANSLATORS: this is to disable the radio hardware in the * network panel */ label = gtk_label_new_with_mnemonic (_("Air_plane Mode")); gtk_box_pack_start (GTK_BOX (box), label, TRUE, FALSE, 2); gtk_widget_set_visible (label, TRUE); widget = gtk_switch_new (); gtk_label_set_mnemonic_widget (GTK_LABEL (label), widget); gtk_box_pack_start (GTK_BOX (box), widget, TRUE, FALSE, 2); gtk_widget_show_all (box); panel->priv->rfkill_switch = GTK_SWITCH (widget); CcShell *shell = cc_panel_get_shell (CC_PANEL (panel)); if (shell == NULL) { GtkWidget *widget = widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "vbox10")); gtk_box_pack_start (GTK_BOX (widget), box, FALSE, FALSE, 6); gtk_box_reorder_child (GTK_BOX (widget), box, 0); } else { cc_shell_embed_widget_in_header (shell, box); } panel->priv->kill_switch_header = g_object_ref (box); panel->priv->killswitches = g_hash_table_new (g_direct_hash, g_direct_equal); panel->priv->rfkill = cc_rfkill_glib_new (); g_signal_connect (G_OBJECT (panel->priv->rfkill), "changed", G_CALLBACK (rfkill_changed), panel); if (cc_rfkill_glib_open (panel->priv->rfkill) < 0) gtk_widget_hide (box); g_signal_connect (panel->priv->rfkill_switch, "notify::active", G_CALLBACK (cc_network_panel_notify_enable_active_cb), panel); return FALSE; } static void cc_network_panel_init (CcNetworkPanel *panel) { DBusGConnection *bus = NULL; GError *error = NULL; GtkStyleContext *context; GtkTreeSelection *selection; GtkWidget *widget; GtkWidget *toplevel; if (!gtk_icon_size_from_name ("cc-sidebar-list")) gtk_icon_size_register ("cc-sidebar-list", 24, 24); panel->priv = NETWORK_PANEL_PRIVATE (panel); panel->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (panel->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (panel->priv->builder, CINNAMONCC_UI_DIR "/network.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } panel->priv->cancellable = g_cancellable_new (); panel->priv->treeview = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "treeview_devices")); panel_add_devices_columns (panel, GTK_TREE_VIEW (panel->priv->treeview)); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->priv->treeview)); gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE); g_signal_connect (selection, "changed", G_CALLBACK (nm_devices_treeview_clicked_cb), panel); widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "devices_scrolledwindow")); gtk_widget_set_size_request (widget, 200, -1); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "devices_toolbar")); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); /* add the virtual proxy device */ panel_add_proxy_device (panel); /* use NetworkManager client */ panel->priv->client = nm_client_new (); g_signal_connect (panel->priv->client, "notify::" NM_CLIENT_MANAGER_RUNNING, G_CALLBACK (manager_running), panel); g_signal_connect (panel->priv->client, "notify::" NM_CLIENT_ACTIVE_CONNECTIONS, G_CALLBACK (active_connections_changed), panel); g_signal_connect (panel->priv->client, "device-added", G_CALLBACK (device_added_cb), panel); g_signal_connect (panel->priv->client, "device-removed", G_CALLBACK (device_removed_cb), panel); widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "add_toolbutton")); g_signal_connect (widget, "clicked", G_CALLBACK (add_connection_cb), panel); /* disable for now, until we actually show removable connections */ widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "remove_toolbutton")); g_signal_connect (widget, "clicked", G_CALLBACK (remove_connection), panel); /* add remote settings such as VPN settings as virtual devices */ bus = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error); if (bus == NULL) { g_warning ("Error connecting to system D-Bus: %s", error->message); g_error_free (error); } panel->priv->remote_settings = nm_remote_settings_new (bus); g_signal_connect (panel->priv->remote_settings, NM_REMOTE_SETTINGS_CONNECTIONS_READ, G_CALLBACK (notify_connections_read_cb), panel); g_signal_connect (panel->priv->remote_settings, NM_REMOTE_SETTINGS_NEW_CONNECTION, G_CALLBACK (notify_new_connection_cb), panel); toplevel = gtk_widget_get_toplevel (GTK_WIDGET (panel)); g_signal_connect_after (toplevel, "map", G_CALLBACK (on_toplevel_map), panel); /* hide implementation details */ widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "notebook_types")); gtk_notebook_set_show_tabs (GTK_NOTEBOOK (widget), FALSE); widget = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "vbox1")); gtk_widget_reparent (widget, (GtkWidget *) panel); gtk_widget_show_all (GTK_WIDGET (panel)); /* add kill switch widgets when dialog activated */ panel->priv->add_header_widgets_idle = g_idle_add (network_add_shell_header_widgets_cb, panel); } void cc_network_panel_register (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); cc_network_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_NETWORK_PANEL, "network", 0); }
452
./cinnamon-control-center/panels/network/rfkill-glib.c
/* * * gnome-bluetooth - Bluetooth integration for GNOME * * Copyright (C) 2012 Bastien Nocera <hadess@hadess.net> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <glib.h> #include "rfkill-glib.h" enum { CHANGED, LAST_SIGNAL }; static int signals[LAST_SIGNAL] = { 0 }; #define CC_RFKILL_GLIB_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), \ CC_RFKILL_TYPE_GLIB, CcRfkillGlibPrivate)) struct CcRfkillGlibPrivate { int fd; GIOChannel *channel; guint watch_id; }; G_DEFINE_TYPE(CcRfkillGlib, cc_rfkill_glib, G_TYPE_OBJECT) int cc_rfkill_glib_send_event (CcRfkillGlib *rfkill, struct rfkill_event *event) { g_return_val_if_fail (RFKILL_IS_GLIB (rfkill), -1); g_return_val_if_fail (rfkill->priv->fd > 0, -1); return write (rfkill->priv->fd, event, sizeof(struct rfkill_event)); } static const char * type_to_string (unsigned int type) { switch (type) { case RFKILL_TYPE_ALL: return "ALL"; case RFKILL_TYPE_WLAN: return "WLAN"; case RFKILL_TYPE_BLUETOOTH: return "RFKILL"; case RFKILL_TYPE_UWB: return "UWB"; case RFKILL_TYPE_WIMAX: return "WIMAX"; case RFKILL_TYPE_WWAN: return "WWAN"; default: g_assert_not_reached (); } } static const char * op_to_string (unsigned int op) { switch (op) { case RFKILL_OP_ADD: return "ADD"; case RFKILL_OP_DEL: return "DEL"; case RFKILL_OP_CHANGE: return "CHANGE"; case RFKILL_OP_CHANGE_ALL: return "CHANGE_ALL"; default: g_assert_not_reached (); } } static void print_event (struct rfkill_event *event) { g_debug ("RFKILL event: idx %u type %u (%s) op %u (%s) soft %u hard %u", event->idx, event->type, type_to_string (event->type), event->op, op_to_string (event->op), event->soft, event->hard); } static void emit_changed_signal_and_free (CcRfkillGlib *rfkill, GList *events) { if (events == NULL) return; g_signal_emit (G_OBJECT (rfkill), signals[CHANGED], 0, events); g_list_free_full (events, g_free); } static gboolean event_cb (GIOChannel *source, GIOCondition condition, CcRfkillGlib *rfkill) { GList *events; events = NULL; if (condition & G_IO_IN) { GIOStatus status; struct rfkill_event event; gsize read; status = g_io_channel_read_chars (source, (char *) &event, sizeof(event), &read, NULL); while (status == G_IO_STATUS_NORMAL && read == sizeof(event)) { struct rfkill_event *event_ptr; print_event (&event); event_ptr = g_memdup (&event, sizeof(event)); events = g_list_prepend (events, event_ptr); status = g_io_channel_read_chars (source, (char *) &event, sizeof(event), &read, NULL); } events = g_list_reverse (events); } else { g_debug ("something else happened"); return FALSE; } emit_changed_signal_and_free (rfkill, events); return TRUE; } static void cc_rfkill_glib_init (CcRfkillGlib *rfkill) { CcRfkillGlibPrivate *priv; priv = CC_RFKILL_GLIB_GET_PRIVATE (rfkill); rfkill->priv = priv; rfkill->priv->fd = -1; } int cc_rfkill_glib_open (CcRfkillGlib *rfkill) { CcRfkillGlibPrivate *priv; int fd; int ret; GList *events; g_return_val_if_fail (RFKILL_IS_GLIB (rfkill), -1); g_return_val_if_fail (rfkill->priv->fd == -1, -1); priv = rfkill->priv; fd = open("/dev/rfkill", O_RDWR); if (fd < 0) { if (errno == EACCES) g_warning ("Could not open RFKILL control device, please verify your installation"); return fd; } ret = fcntl(fd, F_SETFL, O_NONBLOCK); if (ret < 0) { g_debug ("Can't set RFKILL control device to non-blocking"); close(fd); return ret; } events = NULL; while (1) { struct rfkill_event event; struct rfkill_event *event_ptr; ssize_t len; len = read(fd, &event, sizeof(event)); if (len < 0) { if (errno == EAGAIN) break; g_debug ("Reading of RFKILL events failed"); break; } if (len != RFKILL_EVENT_SIZE_V1) { g_warning ("Wrong size of RFKILL event\n"); continue; } if (event.op != RFKILL_OP_ADD) continue; g_debug ("Read killswitch of type '%s' (idx=%d): soft %d hard %d", type_to_string (event.type), event.idx, event.soft, event.hard); event_ptr = g_memdup (&event, sizeof(event)); events = g_list_prepend (events, event_ptr); } /* Setup monitoring */ priv->fd = fd; priv->channel = g_io_channel_unix_new (priv->fd); priv->watch_id = g_io_add_watch (priv->channel, G_IO_IN | G_IO_HUP | G_IO_ERR, (GIOFunc) event_cb, rfkill); events = g_list_reverse (events); emit_changed_signal_and_free (rfkill, events); return fd; } static void cc_rfkill_glib_finalize (GObject *object) { CcRfkillGlib *rfkill; CcRfkillGlibPrivate *priv; rfkill = CC_RFKILL_GLIB (object); priv = rfkill->priv; /* cleanup monitoring */ if (priv->watch_id > 0) { g_source_remove (priv->watch_id); priv->watch_id = 0; g_io_channel_shutdown (priv->channel, FALSE, NULL); g_io_channel_unref (priv->channel); } close(priv->fd); priv->fd = -1; G_OBJECT_CLASS(cc_rfkill_glib_parent_class)->finalize(object); } static void cc_rfkill_glib_class_init(CcRfkillGlibClass *klass) { GObjectClass *object_class = (GObjectClass *) klass; g_type_class_add_private(klass, sizeof(CcRfkillGlibPrivate)); object_class->finalize = cc_rfkill_glib_finalize; signals[CHANGED] = g_signal_new ("changed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (CcRfkillGlibClass, changed), NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_POINTER); } CcRfkillGlib * cc_rfkill_glib_new (void) { return CC_RFKILL_GLIB (g_object_new (CC_RFKILL_TYPE_GLIB, NULL)); }
453
./cinnamon-control-center/panels/network/net-object.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2011 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib-object.h> #include <glib/gi18n-lib.h> #include "net-object.h" #define NET_OBJECT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_OBJECT, NetObjectPrivate)) struct _NetObjectPrivate { gchar *id; gchar *title; gboolean removable; GCancellable *cancellable; NMClient *client; NMRemoteSettings *remote_settings; CcNetworkPanel *panel; }; enum { PROP_0, PROP_ID, PROP_TITLE, PROP_REMOVABLE, PROP_CLIENT, PROP_REMOTE_SETTINGS, PROP_CANCELLABLE, PROP_PANEL, PROP_LAST }; enum { SIGNAL_CHANGED, SIGNAL_REMOVED, SIGNAL_LAST }; static guint signals[SIGNAL_LAST] = { 0 }; G_DEFINE_TYPE (NetObject, net_object, G_TYPE_OBJECT) void net_object_emit_changed (NetObject *object) { g_return_if_fail (NET_IS_OBJECT (object)); g_debug ("NetObject: %s emit 'changed'", object->priv->id); g_signal_emit (object, signals[SIGNAL_CHANGED], 0); } void net_object_emit_removed (NetObject *object) { g_return_if_fail (NET_IS_OBJECT (object)); g_debug ("NetObject: %s emit 'removed'", object->priv->id); g_signal_emit (object, signals[SIGNAL_REMOVED], 0); } const gchar * net_object_get_id (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), NULL); return object->priv->id; } void net_object_set_id (NetObject *object, const gchar *id) { g_return_if_fail (NET_IS_OBJECT (object)); object->priv->id = g_strdup (id); } gboolean net_object_get_removable (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), FALSE); return object->priv->removable; } const gchar * net_object_get_title (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), NULL); return object->priv->title; } void net_object_set_title (NetObject *object, const gchar *title) { g_return_if_fail (NET_IS_OBJECT (object)); object->priv->title = g_strdup (title); } NMClient * net_object_get_client (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), NULL); return object->priv->client; } NMRemoteSettings * net_object_get_remote_settings (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), NULL); return object->priv->remote_settings; } GCancellable * net_object_get_cancellable (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), NULL); return object->priv->cancellable; } CcNetworkPanel * net_object_get_panel (NetObject *object) { g_return_val_if_fail (NET_IS_OBJECT (object), NULL); return object->priv->panel; } GtkWidget * net_object_add_to_notebook (NetObject *object, GtkNotebook *notebook, GtkSizeGroup *heading_size_group) { GtkWidget *widget; NetObjectClass *klass = NET_OBJECT_GET_CLASS (object); if (klass->add_to_notebook != NULL) { widget = klass->add_to_notebook (object, notebook, heading_size_group); g_object_set_data_full (G_OBJECT (widget), "NetObject::id", g_strdup (object->priv->id), g_free); return widget; } g_debug ("no klass->add_to_notebook for %s", object->priv->id); return NULL; } void net_object_delete (NetObject *object) { NetObjectClass *klass = NET_OBJECT_GET_CLASS (object); if (klass->delete != NULL) klass->delete (object); } void net_object_refresh (NetObject *object) { NetObjectClass *klass = NET_OBJECT_GET_CLASS (object); if (klass->refresh != NULL) klass->refresh (object); } void net_object_edit (NetObject *object) { NetObjectClass *klass = NET_OBJECT_GET_CLASS (object); if (klass->edit != NULL) klass->edit (object); } /** * net_object_get_property: **/ static void net_object_get_property (GObject *object_, guint prop_id, GValue *value, GParamSpec *pspec) { NetObject *object = NET_OBJECT (object_); NetObjectPrivate *priv = object->priv; switch (prop_id) { case PROP_ID: g_value_set_string (value, priv->id); break; case PROP_TITLE: g_value_set_string (value, priv->title); break; case PROP_REMOVABLE: g_value_set_boolean (value, priv->removable); break; case PROP_CLIENT: g_value_set_object (value, priv->client); break; case PROP_REMOTE_SETTINGS: g_value_set_object (value, priv->remote_settings); break; case PROP_CANCELLABLE: g_value_set_object (value, priv->cancellable); break; case PROP_PANEL: g_value_set_object (value, priv->panel); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } /** * net_object_set_property: **/ static void net_object_set_property (GObject *object_, guint prop_id, const GValue *value, GParamSpec *pspec) { NetObject *object = NET_OBJECT (object_); NetObjectPrivate *priv = object->priv; switch (prop_id) { case PROP_ID: g_free (priv->id); priv->id = g_strdup (g_value_get_string (value)); break; case PROP_TITLE: g_free (priv->title); priv->title = g_strdup (g_value_get_string (value)); break; case PROP_REMOVABLE: priv->removable = g_value_get_boolean (value); break; case PROP_CLIENT: priv->client = g_value_dup_object (value); break; case PROP_REMOTE_SETTINGS: priv->remote_settings = g_value_dup_object (value); break; case PROP_CANCELLABLE: priv->cancellable = g_value_dup_object (value); break; case PROP_PANEL: priv->panel = g_value_dup_object (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void net_object_finalize (GObject *object) { NetObject *nm_object = NET_OBJECT (object); NetObjectPrivate *priv = nm_object->priv; g_free (priv->id); g_free (priv->title); if (priv->client != NULL) g_object_unref (priv->client); if (priv->remote_settings != NULL) g_object_unref (priv->remote_settings); if (priv->cancellable != NULL) g_object_unref (priv->cancellable); if (priv->panel != NULL) g_object_unref (priv->panel); G_OBJECT_CLASS (net_object_parent_class)->finalize (object); } static void net_object_class_init (NetObjectClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = net_object_finalize; object_class->get_property = net_object_get_property; object_class->set_property = net_object_set_property; pspec = g_param_spec_string ("id", NULL, NULL, NULL, G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_ID, pspec); pspec = g_param_spec_string ("title", NULL, NULL, NULL, G_PARAM_READWRITE); g_object_class_install_property (object_class, PROP_TITLE, pspec); pspec = g_param_spec_boolean ("removable", NULL, NULL, TRUE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_REMOVABLE, pspec); pspec = g_param_spec_object ("client", NULL, NULL, NM_TYPE_CLIENT, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_CLIENT, pspec); pspec = g_param_spec_object ("remote-settings", NULL, NULL, NM_TYPE_REMOTE_SETTINGS, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_REMOTE_SETTINGS, pspec); pspec = g_param_spec_object ("cancellable", NULL, NULL, G_TYPE_CANCELLABLE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_CANCELLABLE, pspec); pspec = g_param_spec_object ("panel", NULL, NULL, CC_TYPE_NETWORK_PANEL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT); g_object_class_install_property (object_class, PROP_PANEL, pspec); signals[SIGNAL_CHANGED] = g_signal_new ("changed", G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (NetObjectClass, changed), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[SIGNAL_REMOVED] = g_signal_new ("removed", G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (NetObjectClass, changed), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); g_type_class_add_private (klass, sizeof (NetObjectPrivate)); } static void net_object_init (NetObject *object) { object->priv = NET_OBJECT_GET_PRIVATE (object); }
454
./cinnamon-control-center/panels/network/panel-cell-renderer-text.c
/* -*- Text: C; tab-width: 8; indent-tabs-text: nil; c-basic-offset: 8 -*- * * Copyright (C) 2012 Red Hat, Inc. * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Written by Matthias Clasen */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "panel-cell-renderer-text.h" enum { ACTIVATE, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE (PanelCellRendererText, panel_cell_renderer_text, GTK_TYPE_CELL_RENDERER_TEXT) static gint activate (GtkCellRenderer *cell, GdkEvent *event, GtkWidget *widget, const gchar *path, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags) { g_signal_emit (cell, signals[ACTIVATE], 0, path); return TRUE; } static void panel_cell_renderer_text_class_init (PanelCellRendererTextClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); GtkCellRendererClass *cell_renderer_class = GTK_CELL_RENDERER_CLASS (class); cell_renderer_class->activate = activate; signals[ACTIVATE] = g_signal_new ("activate", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (PanelCellRendererTextClass, activate), NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); } static void panel_cell_renderer_text_init (PanelCellRendererText *renderer) { } GtkCellRenderer * panel_cell_renderer_text_new (void) { return g_object_new (PANEL_TYPE_CELL_RENDERER_TEXT, NULL); }
455
./cinnamon-control-center/panels/network/panel-cell-renderer-pixbuf.c
/* -*- Pixbuf: C; tab-width: 8; indent-tabs-pixbuf: nil; c-basic-offset: 8 -*- * * Copyright (C) 2012 Red Hat, Inc. * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Written by Matthias Clasen */ #include "config.h" #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include "panel-cell-renderer-pixbuf.h" enum { ACTIVATE, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE (PanelCellRendererPixbuf, panel_cell_renderer_pixbuf, GTK_TYPE_CELL_RENDERER_PIXBUF) static gint activate (GtkCellRenderer *cell, GdkEvent *event, GtkWidget *widget, const gchar *path, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags) { g_signal_emit (cell, signals[ACTIVATE], 0, path); return TRUE; } static void panel_cell_renderer_pixbuf_class_init (PanelCellRendererPixbufClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); GtkCellRendererClass *cell_renderer_class = GTK_CELL_RENDERER_CLASS (class); cell_renderer_class->activate = activate; signals[ACTIVATE] = g_signal_new ("activate", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (PanelCellRendererPixbufClass, activate), NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); } static void panel_cell_renderer_pixbuf_init (PanelCellRendererPixbuf *renderer) { } GtkCellRenderer * panel_cell_renderer_pixbuf_new (void) { return g_object_new (PANEL_TYPE_CELL_RENDERER_PIXBUF, NULL); }
456
./cinnamon-control-center/panels/bluetooth/cc-bluetooth-panel.c
/* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2006-2010 Bastien Nocera <hadess@hadess.net> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <glib/gi18n-lib.h> #include <shell/cc-shell.h> #include "cc-bluetooth-panel.h" #include <bluetooth-client.h> #include <bluetooth-utils.h> #include <bluetooth-killswitch.h> #include <bluetooth-chooser.h> #include <bluetooth-plugin-manager.h> CC_PANEL_REGISTER (CcBluetoothPanel, cc_bluetooth_panel) #define BLUETOOTH_PANEL_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_BLUETOOTH_PANEL, CcBluetoothPanelPrivate)) #define WID(s) GTK_WIDGET (gtk_builder_get_object (self->priv->builder, s)) #define KEYBOARD_PREFS "keyboard" #define MOUSE_PREFS "mouse" #define SOUND_PREFS "sound" #define WIZARD "bluetooth-wizard" struct CcBluetoothPanelPrivate { GtkBuilder *builder; GtkWidget *chooser; char *selected_bdaddr; BluetoothClient *client; BluetoothKillswitch *killswitch; gboolean debug; GHashTable *connecting_devices; }; static void cc_bluetooth_panel_finalize (GObject *object); static void launch_command (const char *command) { GError *error = NULL; if (!g_spawn_command_line_async(command, &error)) { g_warning ("Couldn't execute command '%s': %s\n", command, error->message); g_error_free (error); } } static const char * cc_bluetooth_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/bluetooth"; else return "help:gnome-help/bluetooth"; } static void cc_bluetooth_panel_class_init (CcBluetoothPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); object_class->finalize = cc_bluetooth_panel_finalize; panel_class->get_help_uri = cc_bluetooth_panel_get_help_uri; g_type_class_add_private (klass, sizeof (CcBluetoothPanelPrivate)); } static void char_clear_pointer (gchar *pointer) { if (pointer) { g_free (pointer); pointer = NULL; } } static void cc_bluetooth_panel_finalize (GObject *object) { CcBluetoothPanel *self; bluetooth_plugin_manager_cleanup (); self = CC_BLUETOOTH_PANEL (object); g_clear_object (&self->priv->builder); g_clear_object (&self->priv->killswitch); g_clear_object (&self->priv->client); if (self->priv->connecting_devices != NULL) { g_hash_table_destroy (self->priv->connecting_devices); self->priv->connecting_devices = NULL; } char_clear_pointer (self->priv->selected_bdaddr); G_OBJECT_CLASS (cc_bluetooth_panel_parent_class)->finalize (object); } enum { CONNECTING_NOTEBOOK_PAGE_SWITCH = 0, CONNECTING_NOTEBOOK_PAGE_SPINNER = 1 }; static void set_connecting_page (CcBluetoothPanel *self, int page) { if (page == CONNECTING_NOTEBOOK_PAGE_SPINNER) gtk_spinner_start (GTK_SPINNER (WID ("connecting_spinner"))); gtk_notebook_set_current_page (GTK_NOTEBOOK (WID ("connecting_notebook")), page); if (page == CONNECTING_NOTEBOOK_PAGE_SWITCH) gtk_spinner_start (GTK_SPINNER (WID ("connecting_spinner"))); } static void remove_connecting (CcBluetoothPanel *self, const char *bdaddr) { g_hash_table_remove (self->priv->connecting_devices, bdaddr); } static void add_connecting (CcBluetoothPanel *self, const char *bdaddr) { g_hash_table_insert (self->priv->connecting_devices, g_strdup (bdaddr), GINT_TO_POINTER (1)); } static gboolean is_connecting (CcBluetoothPanel *self, const char *bdaddr) { return GPOINTER_TO_INT (g_hash_table_lookup (self->priv->connecting_devices, bdaddr)); } typedef struct { char *bdaddr; CcBluetoothPanel *self; } ConnectData; static void connect_done (GObject *source_object, GAsyncResult *res, gpointer user_data) { CcBluetoothPanel *self; char *bdaddr; gboolean success; ConnectData *data = (ConnectData *) user_data; success = bluetooth_client_connect_service_finish (BLUETOOTH_CLIENT (source_object), res, NULL); self = data->self; /* Check whether the same device is now selected, and update the UI */ bdaddr = bluetooth_chooser_get_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); if (g_strcmp0 (bdaddr, data->bdaddr) == 0) { GtkSwitch *button; button = GTK_SWITCH (WID ("switch_connection")); /* Reset the switch if it failed */ if (success == FALSE) gtk_switch_set_active (button, !gtk_switch_get_active (button)); set_connecting_page (self, CONNECTING_NOTEBOOK_PAGE_SWITCH); } remove_connecting (self, data->bdaddr); g_free (bdaddr); g_object_unref (data->self); g_free (data->bdaddr); g_free (data); } static void switch_connected_active_changed (GtkSwitch *button, GParamSpec *spec, CcBluetoothPanel *self) { char *proxy; GValue value = { 0, }; ConnectData *data; char *bdaddr; bdaddr = bluetooth_chooser_get_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); if (is_connecting (self, bdaddr)) { g_free (bdaddr); return; } if (bluetooth_chooser_get_selected_device_info (BLUETOOTH_CHOOSER (self->priv->chooser), "proxy", &value) == FALSE) { g_warning ("Could not get D-Bus proxy for selected device"); return; } proxy = g_strdup (g_dbus_proxy_get_object_path (g_value_get_object (&value))); g_value_unset (&value); if (proxy == NULL) return; data = g_new0 (ConnectData, 1); data->bdaddr = bdaddr; data->self = g_object_ref (self); bluetooth_client_connect_service (self->priv->client, proxy, gtk_switch_get_active (button), NULL, connect_done, data); add_connecting (self, data->bdaddr); set_connecting_page (self, CONNECTING_NOTEBOOK_PAGE_SPINNER); g_free (proxy); } enum { NOTEBOOK_PAGE_EMPTY = 0, NOTEBOOK_PAGE_PROPS = 1 }; static void set_notebook_page (CcBluetoothPanel *self, int page) { gtk_notebook_set_current_page (GTK_NOTEBOOK (WID ("props_notebook")), page); } static void add_extra_setup_widgets (CcBluetoothPanel *self, const char *bdaddr) { GValue value = { 0 }; char **uuids; GList *list, *l; GtkWidget *container; if (bluetooth_chooser_get_selected_device_info (BLUETOOTH_CHOOSER (self->priv->chooser), "uuids", &value) == FALSE) return; uuids = (char **) g_value_get_boxed (&value); list = bluetooth_plugin_manager_get_widgets (bdaddr, (const char **) uuids); if (list == NULL) { g_value_unset (&value); return; } container = WID ("additional_setup_box"); for (l = list; l != NULL; l = l->next) { GtkWidget *widget = l->data; gtk_box_pack_start (GTK_BOX (container), widget, FALSE, FALSE, 0); gtk_widget_show_all (widget); } gtk_widget_show (container); g_value_unset (&value); } static void remove_extra_setup_widgets (CcBluetoothPanel *self) { GtkWidget *box; box = WID ("additional_setup_box"); gtk_container_forall (GTK_CONTAINER (box), (GtkCallback) gtk_widget_destroy, NULL); gtk_widget_hide (WID ("additional_setup_box")); } static void cc_bluetooth_panel_update_properties (CcBluetoothPanel *self) { char *bdaddr; GtkSwitch *button; button = GTK_SWITCH (WID ("switch_connection")); g_signal_handlers_block_by_func (button, switch_connected_active_changed, self); /* Hide all the buttons now, and show them again if we need to */ gtk_widget_hide (WID ("keyboard_box")); gtk_widget_hide (WID ("sound_box")); gtk_widget_hide (WID ("mouse_box")); gtk_widget_hide (WID ("browse_box")); gtk_widget_hide (WID ("send_box")); bdaddr = bluetooth_chooser_get_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); /* Remove the extra setup widgets */ if (g_strcmp0 (self->priv->selected_bdaddr, bdaddr) != 0) remove_extra_setup_widgets (self); if (bdaddr == NULL) { gtk_widget_set_sensitive (WID ("properties_vbox"), FALSE); gtk_switch_set_active (button, FALSE); gtk_widget_set_sensitive (WID ("button_delete"), FALSE); set_notebook_page (self, NOTEBOOK_PAGE_EMPTY); } else { BluetoothType type; gboolean connected; GValue value = { 0 }; GHashTable *services; if (self->priv->debug) bluetooth_chooser_dump_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); gtk_widget_set_sensitive (WID ("properties_vbox"), TRUE); if (is_connecting (self, bdaddr)) { gtk_switch_set_active (button, TRUE); set_connecting_page (self, CONNECTING_NOTEBOOK_PAGE_SPINNER); } else { connected = bluetooth_chooser_get_selected_device_is_connected (BLUETOOTH_CHOOSER (self->priv->chooser)); gtk_switch_set_active (button, connected); set_connecting_page (self, CONNECTING_NOTEBOOK_PAGE_SWITCH); } /* Paired */ bluetooth_chooser_get_selected_device_info (BLUETOOTH_CHOOSER (self->priv->chooser), "paired", &value); gtk_label_set_text (GTK_LABEL (WID ("paired_label")), g_value_get_boolean (&value) ? _("Yes") : _("No")); g_value_unset (&value); /* Connection */ bluetooth_chooser_get_selected_device_info (BLUETOOTH_CHOOSER (self->priv->chooser), "services", &value); services = g_value_get_boxed (&value); gtk_widget_set_sensitive (GTK_WIDGET (button), (services != NULL)); g_value_unset (&value); /* UUIDs */ if (bluetooth_chooser_get_selected_device_info (BLUETOOTH_CHOOSER (self->priv->chooser), "uuids", &value)) { const char **uuids; guint i; uuids = (const char **) g_value_get_boxed (&value); for (i = 0; uuids && uuids[i] != NULL; i++) { if (g_str_equal (uuids[i], "OBEXObjectPush")) gtk_widget_show (WID ("send_box")); else if (g_str_equal (uuids[i], "OBEXFileTransfer")) gtk_widget_show (WID ("browse_box")); } g_value_unset (&value); } /* Type */ type = bluetooth_chooser_get_selected_device_type (BLUETOOTH_CHOOSER (self->priv->chooser)); gtk_label_set_text (GTK_LABEL (WID ("type_label")), bluetooth_type_to_string (type)); switch (type) { case BLUETOOTH_TYPE_KEYBOARD: gtk_widget_show (WID ("keyboard_box")); break; case BLUETOOTH_TYPE_MOUSE: case BLUETOOTH_TYPE_TABLET: gtk_widget_show (WID ("mouse_box")); break; case BLUETOOTH_TYPE_HEADSET: case BLUETOOTH_TYPE_HEADPHONES: case BLUETOOTH_TYPE_OTHER_AUDIO: gtk_widget_show (WID ("sound_box")); default: /* others? */ ; } /* Extra widgets */ if (g_strcmp0 (self->priv->selected_bdaddr, bdaddr) != 0) add_extra_setup_widgets (self, bdaddr); gtk_label_set_text (GTK_LABEL (WID ("address_label")), bdaddr); gtk_widget_set_sensitive (WID ("button_delete"), TRUE); set_notebook_page (self, NOTEBOOK_PAGE_PROPS); } g_free (self->priv->selected_bdaddr); self->priv->selected_bdaddr = bdaddr; g_signal_handlers_unblock_by_func (button, switch_connected_active_changed, self); } static void power_callback (GObject *object, GParamSpec *spec, CcBluetoothPanel *self) { gboolean state; state = gtk_switch_get_active (GTK_SWITCH (WID ("switch_bluetooth"))); g_debug ("Power switched to %s", state ? "off" : "on"); bluetooth_killswitch_set_state (self->priv->killswitch, state ? 1 : 0); } static void cc_bluetooth_panel_update_treeview_message (CcBluetoothPanel *self, const char *message) { if (message != NULL) { gtk_widget_hide (self->priv->chooser); gtk_widget_show (WID ("message_scrolledwindow")); gtk_label_set_text (GTK_LABEL (WID ("message_label")), message); } else { gtk_widget_hide (WID ("message_scrolledwindow")); gtk_widget_show (self->priv->chooser); } } static void cc_bluetooth_panel_update_power (CcBluetoothPanel *self) { gint state; char *path; gboolean powered, sensitive; g_object_get (G_OBJECT (self->priv->client), "default-adapter", &path, "default-adapter-powered", &powered, NULL); state = bluetooth_killswitch_get_state (self->priv->killswitch); g_debug ("Updating power, default adapter: %s (powered: %s), killswitch: %s", path ? path : "(none)", powered ? "on" : "off", bluetooth_killswitch_state_to_string (state)); if (path == NULL && bluetooth_killswitch_has_killswitches (self->priv->killswitch) && state != 2) { g_debug ("Default adapter is unpowered, but should be available"); sensitive = TRUE; cc_bluetooth_panel_update_treeview_message (self, _("Bluetooth is disabled")); } else if (path == NULL && state == 2) { g_debug ("Bluetooth is Hard blocked"); sensitive = FALSE; cc_bluetooth_panel_update_treeview_message (self, _("Bluetooth is disabled by hardware switch")); } else if (path == NULL) { sensitive = FALSE; g_debug ("No Bluetooth available"); cc_bluetooth_panel_update_treeview_message (self, _("No Bluetooth adapters found")); } else { sensitive = TRUE; g_debug ("Bluetooth is available and powered"); cc_bluetooth_panel_update_treeview_message (self, NULL); } g_free (path); gtk_widget_set_sensitive (WID ("box_power") , sensitive); gtk_widget_set_sensitive (WID ("box_vis") , sensitive); } static void switch_panel (CcBluetoothPanel *self, const char *panel) { CcShell *shell; GError *error = NULL; shell = cc_panel_get_shell (CC_PANEL (self)); if (cc_shell_set_active_panel_from_id (shell, panel, NULL, &error) == FALSE) { g_warning ("Failed to activate '%s' panel: %s", panel, error->message); g_error_free (error); } } static gboolean keyboard_callback (GtkButton *button, CcBluetoothPanel *self) { switch_panel (self, KEYBOARD_PREFS); return TRUE; } static gboolean mouse_callback (GtkButton *button, CcBluetoothPanel *self) { switch_panel (self, MOUSE_PREFS); return TRUE; } static gboolean sound_callback (GtkButton *button, CcBluetoothPanel *self) { switch_panel (self, SOUND_PREFS); return TRUE; } static void send_callback (GtkButton *button, CcBluetoothPanel *self) { char *bdaddr, *alias; bdaddr = bluetooth_chooser_get_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); alias = bluetooth_chooser_get_selected_device_name (BLUETOOTH_CHOOSER (self->priv->chooser)); bluetooth_send_to_address (bdaddr, alias); g_free (bdaddr); g_free (alias); } static void mount_finish_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; if (bluetooth_browse_address_finish (source_object, res, &error) == FALSE) { g_printerr ("Failed to mount OBEX volume: %s", error->message); g_error_free (error); return; } } static void browse_callback (GtkButton *button, CcBluetoothPanel *self) { char *bdaddr; bdaddr = bluetooth_chooser_get_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); bluetooth_browse_address (G_OBJECT (self), bdaddr, GDK_CURRENT_TIME, mount_finish_cb, NULL); g_free (bdaddr); } /* Visibility/Discoverable */ static void discoverable_changed (BluetoothClient *client, GParamSpec *spec, CcBluetoothPanel *self); static void switch_discoverable_active_changed (GtkSwitch *button, GParamSpec *spec, CcBluetoothPanel *self) { g_signal_handlers_block_by_func (self->priv->client, discoverable_changed, self); g_object_set (G_OBJECT (self->priv->client), "default-adapter-discoverable", gtk_switch_get_active (button), NULL); g_signal_handlers_unblock_by_func (self->priv->client, discoverable_changed, self); } static void cc_bluetooth_panel_update_visibility (CcBluetoothPanel *self) { gboolean discoverable; GtkSwitch *button; char *name; button = GTK_SWITCH (WID ("switch_discoverable")); g_object_get (G_OBJECT (self->priv->client), "default-adapter-discoverable", &discoverable, NULL); g_signal_handlers_block_by_func (button, switch_discoverable_active_changed, self); gtk_switch_set_active (button, discoverable); g_signal_handlers_unblock_by_func (button, switch_discoverable_active_changed, self); g_object_get (G_OBJECT (self->priv->client), "default-adapter-name", &name, NULL); if (name == NULL) { gtk_widget_set_sensitive (WID ("switch_discoverable"), FALSE); gtk_widget_set_sensitive (WID ("visible_label"), FALSE); gtk_label_set_text (GTK_LABEL (WID ("visible_label")), _("Visibility")); } else { char *label; label = g_strdup_printf (_("Visibility of ΓÇ£%sΓÇ¥"), name); g_free (name); gtk_label_set_text (GTK_LABEL (WID ("visible_label")), label); g_free (label); gtk_widget_set_sensitive (WID ("switch_discoverable"), TRUE); gtk_widget_set_sensitive (WID ("visible_label"), TRUE); } } static void discoverable_changed (BluetoothClient *client, GParamSpec *spec, CcBluetoothPanel *self) { cc_bluetooth_panel_update_visibility (self); } static void name_changed (BluetoothClient *client, GParamSpec *spec, CcBluetoothPanel *self) { cc_bluetooth_panel_update_visibility (self); } static void device_selected_changed (BluetoothChooser *chooser, GParamSpec *spec, CcBluetoothPanel *self) { cc_bluetooth_panel_update_properties (self); } static gboolean show_confirm_dialog (CcBluetoothPanel *self, const char *name) { GtkWidget *dialog, *parent; gint response; parent = gtk_widget_get_toplevel (GTK_WIDGET (self)); dialog = gtk_message_dialog_new (GTK_WINDOW (parent), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Remove '%s' from the list of devices?"), name); g_object_set (G_OBJECT (dialog), "secondary-text", _("If you remove the device, you will have to set it up again before next use."), NULL); gtk_dialog_add_button (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL); gtk_dialog_add_button (GTK_DIALOG (dialog), GTK_STOCK_REMOVE, GTK_RESPONSE_ACCEPT); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); if (response == GTK_RESPONSE_ACCEPT) return TRUE; return FALSE; } static gboolean remove_selected_device (CcBluetoothPanel *self) { GValue value = { 0, }; char *device, *adapter; GDBusProxy *adapter_proxy; GError *error = NULL; GVariant *ret; if (bluetooth_chooser_get_selected_device_info (BLUETOOTH_CHOOSER (self->priv->chooser), "proxy", &value) == FALSE) { return FALSE; } device = g_strdup (g_dbus_proxy_get_object_path (g_value_get_object (&value))); g_value_unset (&value); g_object_get (G_OBJECT (self->priv->client), "default-adapter", &adapter, NULL); adapter_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START, NULL, "org.bluez", adapter, "org.bluez.Adapter", NULL, &error); g_free (adapter); if (adapter_proxy == NULL) { g_warning ("Failed to create a GDBusProxy for the default adapter: %s", error->message); g_error_free (error); g_free (device); return FALSE; } ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (adapter_proxy), "RemoveDevice", g_variant_new ("(o)", device), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (ret == NULL) { g_warning ("Failed to remove device '%s': %s", device, error->message); g_error_free (error); } else { g_variant_unref (ret); } g_object_unref (adapter_proxy); g_free (device); return (ret != NULL); } /* Treeview buttons */ static void delete_clicked (GtkToolButton *button, CcBluetoothPanel *self) { char *address, *name; address = bluetooth_chooser_get_selected_device (BLUETOOTH_CHOOSER (self->priv->chooser)); g_assert (address); name = bluetooth_chooser_get_selected_device_name (BLUETOOTH_CHOOSER (self->priv->chooser)); if (show_confirm_dialog (self, name) != FALSE) { if (remove_selected_device (self)) bluetooth_plugin_manager_device_deleted (address); } g_free (address); g_free (name); } static void setup_clicked (GtkToolButton *button, CcBluetoothPanel *self) { launch_command (WIZARD); } /* Overall device state */ static void cc_bluetooth_panel_update_state (CcBluetoothPanel *self) { char *bdaddr; g_object_get (G_OBJECT (self->priv->client), "default-adapter", &bdaddr, NULL); gtk_widget_set_sensitive (WID ("toolbar"), (bdaddr != NULL)); g_free (bdaddr); } static void cc_bluetooth_panel_update_powered_state (CcBluetoothPanel *self) { gboolean powered; g_object_get (G_OBJECT (self->priv->client), "default-adapter-powered", &powered, NULL); gtk_switch_set_active (GTK_SWITCH (WID ("switch_bluetooth")), powered); } static void default_adapter_power_changed (BluetoothClient *client, GParamSpec *spec, CcBluetoothPanel *self) { g_debug ("Default adapter power changed"); cc_bluetooth_panel_update_powered_state (self); } static void default_adapter_changed (BluetoothClient *client, GParamSpec *spec, CcBluetoothPanel *self) { g_debug ("Default adapter changed"); cc_bluetooth_panel_update_state (self); cc_bluetooth_panel_update_power (self); cc_bluetooth_panel_update_powered_state (self); } static void killswitch_changed (BluetoothKillswitch *killswitch, int state, CcBluetoothPanel *self) { g_debug ("Killswitch changed to state '%s' (%d)", bluetooth_killswitch_state_to_string (state) , state); cc_bluetooth_panel_update_state (self); cc_bluetooth_panel_update_power (self); } static void cc_bluetooth_panel_init (CcBluetoothPanel *self) { GtkWidget *widget; GError *error = NULL; GtkStyleContext *context; self->priv = BLUETOOTH_PANEL_PRIVATE (self); bluetooth_plugin_manager_init (); self->priv->killswitch = bluetooth_killswitch_new (); self->priv->client = bluetooth_client_new (); self->priv->connecting_devices = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, NULL); self->priv->debug = g_getenv ("BLUETOOTH_DEBUG") != NULL; self->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (self->priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (self->priv->builder, PKGDATADIR "/bluetooth.ui", &error); if (error != NULL) { g_warning ("Failed to load '%s': %s", PKGDATADIR "/bluetooth.ui", error->message); g_error_free (error); return; } widget = WID ("grid"); gtk_widget_reparent (widget, GTK_WIDGET (self)); /* Overall device state */ cc_bluetooth_panel_update_state (self); g_signal_connect (G_OBJECT (self->priv->client), "notify::default-adapter", G_CALLBACK (default_adapter_changed), self); g_signal_connect (G_OBJECT (self->priv->client), "notify::default-adapter-powered", G_CALLBACK (default_adapter_power_changed), self); /* The discoverable button */ cc_bluetooth_panel_update_visibility (self); g_signal_connect (G_OBJECT (self->priv->client), "notify::default-adapter-discoverable", G_CALLBACK (discoverable_changed), self); g_signal_connect (G_OBJECT (self->priv->client), "notify::default-adapter-name", G_CALLBACK (name_changed), self); g_signal_connect (G_OBJECT (WID ("switch_discoverable")), "notify::active", G_CALLBACK (switch_discoverable_active_changed), self); /* The known devices */ widget = WID ("devices_table"); context = gtk_widget_get_style_context (WID ("message_scrolledwindow")); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); /* Note that this will only ever show the devices on the default * adapter, this is on purpose */ self->priv->chooser = bluetooth_chooser_new (); gtk_box_pack_start (GTK_BOX (WID ("box_devices")), self->priv->chooser, TRUE, TRUE, 0); g_object_set (self->priv->chooser, "show-searching", FALSE, "show-device-type", FALSE, "show-device-type-column", FALSE, "show-device-category", FALSE, "show-pairing", FALSE, "show-connected", FALSE, "device-category-filter", BLUETOOTH_CATEGORY_PAIRED_OR_TRUSTED, "no-show-all", TRUE, NULL); /* Join treeview and buttons */ widget = bluetooth_chooser_get_scrolled_window (BLUETOOTH_CHOOSER (self->priv->chooser)); gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (widget), 250); gtk_scrolled_window_set_min_content_width (GTK_SCROLLED_WINDOW (widget), 200); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = WID ("toolbar"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); g_signal_connect (G_OBJECT (self->priv->chooser), "notify::device-selected", G_CALLBACK (device_selected_changed), self); g_signal_connect (G_OBJECT (WID ("button_delete")), "clicked", G_CALLBACK (delete_clicked), self); g_signal_connect (G_OBJECT (WID ("button_setup")), "clicked", G_CALLBACK (setup_clicked), self); /* Set the initial state of the properties */ cc_bluetooth_panel_update_properties (self); g_signal_connect (G_OBJECT (WID ("mouse_link")), "activate-link", G_CALLBACK (mouse_callback), self); g_signal_connect (G_OBJECT (WID ("keyboard_link")), "activate-link", G_CALLBACK (keyboard_callback), self); g_signal_connect (G_OBJECT (WID ("sound_link")), "activate-link", G_CALLBACK (sound_callback), self); g_signal_connect (G_OBJECT (WID ("browse_button")), "clicked", G_CALLBACK (browse_callback), self); g_signal_connect (G_OBJECT (WID ("send_button")), "clicked", G_CALLBACK (send_callback), self); g_signal_connect (G_OBJECT (WID ("switch_connection")), "notify::active", G_CALLBACK (switch_connected_active_changed), self); /* Set the initial state of power */ g_signal_connect (G_OBJECT (WID ("switch_bluetooth")), "notify::active", G_CALLBACK (power_callback), self); g_signal_connect (G_OBJECT (self->priv->killswitch), "state-changed", G_CALLBACK (killswitch_changed), self); cc_bluetooth_panel_update_power (self); gtk_widget_show_all (GTK_WIDGET (self)); } void cc_bluetooth_panel_register (GIOModule *module) { cc_bluetooth_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_BLUETOOTH_PANEL, "bluetooth", 0); } /* GIO extension stuff */ void g_io_module_load (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); /* register the panel */ cc_bluetooth_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
457
./cinnamon-control-center/panels/display/cc-rr-labeler.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- * * cc-rr-labeler.c - Utility to label monitors to identify them * while they are being configured. * * Copyright 2008, Novell, Inc. * * This file is part of the Gnome Library. * * The Gnome Library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * The Gnome Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with the Gnome Library; see the file COPYING.LIB. If not, * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * * Author: Federico Mena-Quintero <federico@novell.com> */ #include <config.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include <X11/Xproto.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <gdk/gdkx.h> #include "cc-rr-labeler.h" struct _CcRRLabelerPrivate { GnomeRRConfig *config; int num_outputs; GdkRGBA *palette; GtkWidget **windows; GdkScreen *screen; Atom workarea_atom; }; enum { PROP_0, PROP_CONFIG, PROP_LAST }; G_DEFINE_TYPE (CcRRLabeler, cc_rr_labeler, G_TYPE_OBJECT); static void cc_rr_labeler_finalize (GObject *object); static void setup_from_config (CcRRLabeler *labeler); static GdkFilterReturn screen_xevent_filter (GdkXEvent *xevent, GdkEvent *event, CcRRLabeler *labeler) { XEvent *xev; xev = (XEvent *) xevent; if (xev->type == PropertyNotify && xev->xproperty.atom == labeler->priv->workarea_atom) { /* update label positions */ if (labeler->priv->windows != NULL) { cc_rr_labeler_hide (labeler); cc_rr_labeler_show (labeler); } } return GDK_FILTER_CONTINUE; } static void cc_rr_labeler_init (CcRRLabeler *labeler) { GdkWindow *gdkwindow; labeler->priv = G_TYPE_INSTANCE_GET_PRIVATE (labeler, GNOME_TYPE_RR_LABELER, CcRRLabelerPrivate); labeler->priv->workarea_atom = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "_NET_WORKAREA", True); labeler->priv->screen = gdk_screen_get_default (); /* code is not really designed to handle multiple screens so *shrug* */ gdkwindow = gdk_screen_get_root_window (labeler->priv->screen); gdk_window_add_filter (gdkwindow, (GdkFilterFunc) screen_xevent_filter, labeler); gdk_window_set_events (gdkwindow, gdk_window_get_events (gdkwindow) | GDK_PROPERTY_CHANGE_MASK); } static void cc_rr_labeler_set_property (GObject *gobject, guint property_id, const GValue *value, GParamSpec *param_spec) { CcRRLabeler *self = CC_RR_LABELER (gobject); switch (property_id) { case PROP_CONFIG: self->priv->config = GNOME_RR_CONFIG (g_value_dup_object (value)); return; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, property_id, param_spec); } } static GObject * cc_rr_labeler_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_properties) { CcRRLabeler *self = (CcRRLabeler*) G_OBJECT_CLASS (cc_rr_labeler_parent_class)->constructor (type, n_construct_properties, construct_properties); setup_from_config (self); return (GObject*) self; } static void cc_rr_labeler_class_init (CcRRLabelerClass *klass) { GObjectClass *object_class; g_type_class_add_private (klass, sizeof (CcRRLabelerPrivate)); object_class = (GObjectClass *) klass; object_class->set_property = cc_rr_labeler_set_property; object_class->finalize = cc_rr_labeler_finalize; object_class->constructor = cc_rr_labeler_constructor; g_object_class_install_property (object_class, PROP_CONFIG, g_param_spec_object ("config", "Configuration", "RandR configuration to label", GNOME_TYPE_RR_CONFIG, G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)); } static void cc_rr_labeler_finalize (GObject *object) { CcRRLabeler *labeler; GdkWindow *gdkwindow; labeler = CC_RR_LABELER (object); gdkwindow = gdk_screen_get_root_window (labeler->priv->screen); gdk_window_remove_filter (gdkwindow, (GdkFilterFunc) screen_xevent_filter, labeler); if (labeler->priv->config != NULL) { g_object_unref (labeler->priv->config); } if (labeler->priv->windows != NULL) { cc_rr_labeler_hide (labeler); g_free (labeler->priv->windows); } g_free (labeler->priv->palette); G_OBJECT_CLASS (cc_rr_labeler_parent_class)->finalize (object); } static int count_outputs (GnomeRRConfig *config) { int i; GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (config); for (i = 0; outputs[i] != NULL; i++) ; return i; } static void make_palette (CcRRLabeler *labeler) { /* The idea is that we go around an hue color wheel. We want to start * at red, go around to green/etc. and stop at blue --- because magenta * is evil. Eeeeek, no magenta, please! * * Purple would be nice, though. Remember that we are watered down * (i.e. low saturation), so that would be like Like berries with cream. * Mmmmm, berries. */ double start_hue; double end_hue; int i; g_assert (labeler->priv->num_outputs > 0); labeler->priv->palette = g_new (GdkRGBA, labeler->priv->num_outputs); start_hue = 0.0; /* red */ end_hue = 2.0/3; /* blue */ for (i = 0; i < labeler->priv->num_outputs; i++) { double h, s, v; double r, g, b; h = start_hue + (end_hue - start_hue) / labeler->priv->num_outputs * i; s = 1.0 / 3; v = 1.0; gtk_hsv_to_rgb (h, s, v, &r, &g, &b); labeler->priv->palette[i].red = r; labeler->priv->palette[i].green = g; labeler->priv->palette[i].blue = b; labeler->priv->palette[i].alpha = 1.0; } } static void rounded_rectangle (cairo_t *cr, gint x, gint y, gint width, gint height, gint x_radius, gint y_radius) { gint x1, x2; gint y1, y2; gint xr1, xr2; gint yr1, yr2; x1 = x; x2 = x1 + width; y1 = y; y2 = y1 + height; x_radius = MIN (x_radius, width / 2.0); y_radius = MIN (y_radius, width / 2.0); xr1 = x_radius; xr2 = x_radius / 2.0; yr1 = y_radius; yr2 = y_radius / 2.0; cairo_move_to (cr, x1 + xr1, y1); cairo_line_to (cr, x2 - xr1, y1); cairo_curve_to (cr, x2 - xr2, y1, x2, y1 + yr2, x2, y1 + yr1); cairo_line_to (cr, x2, y2 - yr1); cairo_curve_to (cr, x2, y2 - yr2, x2 - xr2, y2, x2 - xr1, y2); cairo_line_to (cr, x1 + xr1, y2); cairo_curve_to (cr, x1 + xr2, y2, x1, y2 - yr2, x1, y2 - yr1); cairo_line_to (cr, x1, y1 + yr1); cairo_curve_to (cr, x1, y1 + yr2, x1 + xr2, y1, x1 + xr1, y1); cairo_close_path (cr); } #define LABEL_WINDOW_EDGE_THICKNESS 2 #define LABEL_WINDOW_PADDING 12 /* Look for panel-corner in: * http://git.gnome.org/browse/gnome-shell/tree/data/theme/gnome-shell.css * to match the corner radius */ #define LABEL_CORNER_RADIUS 6 + LABEL_WINDOW_EDGE_THICKNESS static void label_draw_background_and_frame (GtkWidget *widget, cairo_t *cr, gboolean for_shape) { GdkRGBA shape_color = { 0, 0, 0, 1 }; GdkRGBA *rgba; GtkAllocation allocation; rgba = g_object_get_data (G_OBJECT (widget), "rgba"); gtk_widget_get_allocation (widget, &allocation); cairo_save (cr); cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE); /* edge outline */ if (for_shape) gdk_cairo_set_source_rgba (cr, &shape_color); else cairo_set_source_rgba (cr, 0, 0, 0, 0.5); rounded_rectangle (cr, LABEL_WINDOW_EDGE_THICKNESS / 2.0, LABEL_WINDOW_EDGE_THICKNESS / 2.0, allocation.width - LABEL_WINDOW_EDGE_THICKNESS, allocation.height - LABEL_WINDOW_EDGE_THICKNESS, LABEL_CORNER_RADIUS, LABEL_CORNER_RADIUS); cairo_set_line_width (cr, LABEL_WINDOW_EDGE_THICKNESS); cairo_stroke (cr); /* fill */ if (for_shape) { gdk_cairo_set_source_rgba (cr, &shape_color); } else { rgba->alpha = 0.75; gdk_cairo_set_source_rgba (cr, rgba); } rounded_rectangle (cr, LABEL_WINDOW_EDGE_THICKNESS, LABEL_WINDOW_EDGE_THICKNESS, allocation.width - LABEL_WINDOW_EDGE_THICKNESS * 2, allocation.height - LABEL_WINDOW_EDGE_THICKNESS * 2, LABEL_CORNER_RADIUS - LABEL_WINDOW_EDGE_THICKNESS / 2.0, LABEL_CORNER_RADIUS - LABEL_WINDOW_EDGE_THICKNESS / 2.0); cairo_fill (cr); cairo_restore (cr); } static void maybe_update_shape (GtkWidget *widget) { cairo_t *cr; cairo_surface_t *surface; cairo_region_t *region; /* fallback to XShape only for non-composited clients */ if (gtk_widget_is_composited (widget)) { gtk_widget_shape_combine_region (widget, NULL); return; } surface = gdk_window_create_similar_surface (gtk_widget_get_window (widget), CAIRO_CONTENT_COLOR_ALPHA, gtk_widget_get_allocated_width (widget), gtk_widget_get_allocated_height (widget)); cr = cairo_create (surface); label_draw_background_and_frame (widget, cr, TRUE); cairo_destroy (cr); region = gdk_cairo_region_create_from_surface (surface); gtk_widget_shape_combine_region (widget, region); cairo_surface_destroy (surface); cairo_region_destroy (region); } static gboolean label_window_draw_event_cb (GtkWidget *widget, cairo_t *cr, gpointer data) { if (gtk_widget_is_composited (widget)) { /* clear any content */ cairo_save (cr); cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE); cairo_set_source_rgba (cr, 0, 0, 0, 0); cairo_paint (cr); cairo_restore (cr); } maybe_update_shape (widget); label_draw_background_and_frame (widget, cr, FALSE); return FALSE; } static void position_window (CcRRLabeler *labeler, GtkWidget *window, int x, int y) { GdkRectangle workarea; GdkRectangle monitor; int monitor_num; monitor_num = gdk_screen_get_monitor_at_point (labeler->priv->screen, x, y); gdk_screen_get_monitor_workarea (labeler->priv->screen, monitor_num, &workarea); gdk_screen_get_monitor_geometry (labeler->priv->screen, monitor_num, &monitor); gdk_rectangle_intersect (&monitor, &workarea, &workarea); gtk_window_move (GTK_WINDOW (window), workarea.x, workarea.y); } static void label_window_realize_cb (GtkWidget *widget) { cairo_region_t *region; /* make the whole window ignore events */ region = cairo_region_create (); gtk_widget_input_shape_combine_region (widget, region); cairo_region_destroy (region); maybe_update_shape (widget); } static void label_window_composited_changed_cb (GtkWidget *widget, CcRRLabeler *labeler) { if (gtk_widget_get_realized (widget)) maybe_update_shape (widget); } static GtkWidget * create_label_window (CcRRLabeler *labeler, GnomeRROutputInfo *output, GdkRGBA *rgba) { GtkWidget *window; GtkWidget *widget; char *str; const char *display_name; GdkRGBA black = { 0, 0, 0, 1.0 }; int x, y; GdkScreen *screen; GdkVisual *visual; window = gtk_window_new (GTK_WINDOW_POPUP); gtk_window_set_type_hint (GTK_WINDOW (window), GDK_WINDOW_TYPE_HINT_TOOLTIP); gtk_window_set_resizable (GTK_WINDOW (window), FALSE); gtk_widget_set_app_paintable (window, TRUE); screen = gtk_widget_get_screen (window); visual = gdk_screen_get_rgba_visual (screen); if (visual != NULL) gtk_widget_set_visual (window, visual); gtk_container_set_border_width (GTK_CONTAINER (window), LABEL_WINDOW_PADDING + LABEL_WINDOW_EDGE_THICKNESS); /* This is semi-dangerous. The color is part of the labeler->palette * array. Note that in cc_rr_labeler_finalize(), we are careful to * free the palette only after we free the windows. */ g_object_set_data (G_OBJECT (window), "rgba", rgba); g_signal_connect (window, "draw", G_CALLBACK (label_window_draw_event_cb), labeler); g_signal_connect (window, "realize", G_CALLBACK (label_window_realize_cb), labeler); g_signal_connect (window, "composited-changed", G_CALLBACK (label_window_composited_changed_cb), labeler); if (gnome_rr_config_get_clone (labeler->priv->config)) { /* Keep this string in sync with gnome-control-center/capplets/display/xrandr-capplet.c:get_display_name() */ /* Translators: this is the feature where what you see on your * laptop's screen is the same as your external projector. * Here, "Mirrored" is being used as an adjective. For example, * the Spanish translation could be "Pantallas en Espejo". */ display_name = _("Mirrored Displays"); } else display_name = gnome_rr_output_info_get_display_name (output); str = g_strdup_printf ("<b>%s</b>", display_name); widget = gtk_label_new (NULL); gtk_label_set_markup (GTK_LABEL (widget), str); g_free (str); /* Make the label explicitly black. We don't want it to follow the * theme's colors, since the label is always shown against a light * pastel background. See bgo#556050 */ gtk_widget_override_color (widget, gtk_widget_get_state_flags (widget), &black); gtk_container_add (GTK_CONTAINER (window), widget); /* Should we center this at the top edge of the monitor, instead of using the upper-left corner? */ gnome_rr_output_info_get_geometry (output, &x, &y, NULL, NULL); position_window (labeler, window, x, y); gtk_widget_show_all (window); return window; } static void setup_from_config (CcRRLabeler *labeler) { labeler->priv->num_outputs = count_outputs (labeler->priv->config); make_palette (labeler); cc_rr_labeler_show (labeler); } /** * cc_rr_labeler_new: * @config: Configuration of the screens to label * * Create a GUI element that will display colored labels on each connected monitor. * This is useful when users are required to identify which monitor is which, e.g. for * for configuring multiple monitors. * The labels will be shown by default, use cc_rr_labeler_hide to hide them. * * Returns: A new #CcRRLabeler */ CcRRLabeler * cc_rr_labeler_new (GnomeRRConfig *config) { g_return_val_if_fail (GNOME_IS_RR_CONFIG (config), NULL); return g_object_new (GNOME_TYPE_RR_LABELER, "config", config, NULL); } /** * cc_rr_labeler_show: * @labeler: A #CcRRLabeler * * Show the labels. */ void cc_rr_labeler_show (CcRRLabeler *labeler) { int i; gboolean created_window_for_clone; GnomeRROutputInfo **outputs; g_return_if_fail (GNOME_IS_RR_LABELER (labeler)); if (labeler->priv->windows != NULL) return; labeler->priv->windows = g_new (GtkWidget *, labeler->priv->num_outputs); created_window_for_clone = FALSE; outputs = gnome_rr_config_get_outputs (labeler->priv->config); for (i = 0; i < labeler->priv->num_outputs; i++) { if (!created_window_for_clone && gnome_rr_output_info_is_active (outputs[i])) { labeler->priv->windows[i] = create_label_window (labeler, outputs[i], labeler->priv->palette + i); if (gnome_rr_config_get_clone (labeler->priv->config)) created_window_for_clone = TRUE; } else labeler->priv->windows[i] = NULL; } } /** * cc_rr_labeler_hide: * @labeler: A #CcRRLabeler * * Hide ouput labels. */ void cc_rr_labeler_hide (CcRRLabeler *labeler) { int i; CcRRLabelerPrivate *priv; g_return_if_fail (GNOME_IS_RR_LABELER (labeler)); priv = labeler->priv; if (priv->windows == NULL) return; for (i = 0; i < priv->num_outputs; i++) if (priv->windows[i] != NULL) { gtk_widget_destroy (priv->windows[i]); priv->windows[i] = NULL; } g_free (priv->windows); priv->windows = NULL; } /** * cc_rr_labeler_get_rgba_for_output: * @labeler: A #CcRRLabeler * @output: Output device (i.e. monitor) to query * @rgba_out: (out): Color of selected monitor. * * Get the color used for the label on a given output (monitor). */ void cc_rr_labeler_get_rgba_for_output (CcRRLabeler *labeler, GnomeRROutputInfo *output, GdkRGBA *rgba_out) { int i; GnomeRROutputInfo **outputs; g_return_if_fail (GNOME_IS_RR_LABELER (labeler)); g_return_if_fail (GNOME_IS_RR_OUTPUT_INFO (output)); g_return_if_fail (rgba_out != NULL); outputs = gnome_rr_config_get_outputs (labeler->priv->config); for (i = 0; i < labeler->priv->num_outputs; i++) if (outputs[i] == output) { *rgba_out = labeler->priv->palette[i]; return; } g_warning ("trying to get the color for unknown GnomeOutputInfo %p; returning magenta!", output); rgba_out->red = 1.0; rgba_out->green = 0; rgba_out->blue = 1.0; rgba_out->alpha = 1.0; }
458
./cinnamon-control-center/panels/display/cc-display-panel.c
/* * Copyright (C) 2007, 2008 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Soren Sandmann <sandmann@redhat.com> * */ #include <config.h> #include <string.h> #include <stdlib.h> #include <sys/wait.h> #include "cc-display-panel.h" #include <gtk/gtk.h> #include "scrollarea.h" #define GNOME_DESKTOP_USE_UNSTABLE_API #include <libgnome-desktop/gnome-rr.h> #include <libgnome-desktop/gnome-rr-config.h> #include <gdk/gdkx.h> #include <X11/Xlib.h> #include <glib/gi18n-lib.h> #include <gdesktop-enums.h> #include "cc-rr-labeler.h" CC_PANEL_REGISTER (CcDisplayPanel, cc_display_panel) #define DISPLAY_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_DISPLAY_PANEL, CcDisplayPanelPrivate)) #define WID(s) GTK_WIDGET (gtk_builder_get_object (self->priv->builder, s)) #define TOP_BAR_HEIGHT 10 #define CLOCK_SCHEMA "org.gnome.desktop.interface" #define CLOCK_FORMAT_KEY "clock-format" /* The minimum supported size for the panel, see: * http://live.gnome.org/Design/SystemSettings */ #define MINIMUM_WIDTH 675 #define MINIMUM_HEIGHT 530 #define UNITY_GSETTINGS_SCHEMA "org.compiz.unityshell" #define UNITY_GSETTINGS_PATH "/org/compiz/profiles/unity/plugins/unityshell/" #define UNITY_LAUNCHER_ALL_MONITORS_KEY "num-launchers" #define UNITY_STICKY_EDGE_KEY "launcher-capture-mouse" #define UNITY2D_GSETTINGS_MAIN "com.canonical.Unity2d" #define UNITY2D_GSETTINGS_LAUNCHER "com.canonical.Unity2d.Launcher" enum { TEXT_COL, WIDTH_COL, HEIGHT_COL, RATE_COL, SORT_COL, ROTATION_COL, NUM_COLS }; struct _CcDisplayPanelPrivate { GnomeRRScreen *screen; GnomeRRConfig *current_configuration; CcRRLabeler *labeler; GnomeRROutputInfo *current_output; GSettings *clock_settings; GSettings *unity_settings; GSettings *unity2d_settings_main; GSettings *unity2d_settings_launcher; GtkBuilder *builder; guint focus_id; guint focus_id_hide; GtkWidget *panel; GtkWidget *current_monitor_event_box; GtkWidget *current_monitor_label; GtkWidget *monitor_switch; GtkListStore *resolution_store; GtkWidget *resolution_combo; GtkWidget *rotation_combo; GtkWidget *clone_checkbox; GtkWidget *clone_label; GtkWidget *show_icon_checkbox; /* We store the event timestamp when the Apply button is clicked */ guint32 apply_button_clicked_timestamp; GtkWidget *area; gboolean ignore_gui_changes; gboolean dragging_top_bar; /* These are used while we are waiting for the ApplyConfiguration method to be executed over D-bus */ GDBusProxy *proxy; }; typedef struct { int grab_x; int grab_y; int output_x; int output_y; } GrabInfo; static void rebuild_gui (CcDisplayPanel *self); static void on_clone_changed (GtkWidget *box, gpointer data); static gboolean output_overlaps (GnomeRROutputInfo *output, GnomeRRConfig *config); static void select_current_output_from_dialog_position (CcDisplayPanel *self); static void monitor_switch_active_cb (GObject *object, GParamSpec *pspec, gpointer data); static void get_geometry (GnomeRROutputInfo *output, int *w, int *h); static void apply_configuration_returned_cb (GObject *proxy, GAsyncResult *res, gpointer data); static gboolean get_clone_size (GnomeRRScreen *screen, int *width, int *height); static gboolean output_info_supports_mode (CcDisplayPanel *self, GnomeRROutputInfo *info, int width, int height); static char *make_resolution_string (int width, int height); static GObject *cc_display_panel_constructor (GType gtype, guint n_properties, GObjectConstructParam *properties); static void on_screen_changed (GnomeRRScreen *scr, gpointer data); static void refresh_unity_launcher_placement (CcDisplayPanel *self); static gboolean unity_launcher_on_all_monitors (GSettings *settings); static void cc_display_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_display_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_display_panel_dispose (GObject *object) { G_OBJECT_CLASS (cc_display_panel_parent_class)->dispose (object); } static void cc_display_panel_finalize (GObject *object) { CcDisplayPanel *self; CcShell *shell; GtkWidget *toplevel; self = CC_DISPLAY_PANEL (object); g_signal_handlers_disconnect_by_func (self->priv->screen, on_screen_changed, self); g_object_unref (self->priv->screen); g_object_unref (self->priv->builder); if (self->priv->clock_settings != NULL) g_object_unref (self->priv->clock_settings); if (self->priv->unity2d_settings_main != NULL) g_object_unref (self->priv->unity2d_settings_main); if (self->priv->unity2d_settings_launcher != NULL) g_object_unref (self->priv->unity2d_settings_launcher); if (self->priv->unity_settings != NULL) g_object_unref (self->priv->unity_settings); shell = cc_panel_get_shell (CC_PANEL (self)); if (shell != NULL) { toplevel = cc_shell_get_toplevel (shell); if (toplevel != NULL) g_signal_handler_disconnect (G_OBJECT (toplevel), self->priv->focus_id); } else { g_signal_handler_disconnect (GTK_WIDGET (self), self->priv->focus_id); g_signal_handler_disconnect (GTK_WIDGET (self), self->priv->focus_id_hide); } cc_rr_labeler_hide (self->priv->labeler); g_object_unref (self->priv->labeler); G_OBJECT_CLASS (cc_display_panel_parent_class)->finalize (object); } static const char * cc_display_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/prefs-display"; else return "help:gnome-help/prefs-display"; } static void cc_display_panel_class_init (CcDisplayPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcDisplayPanelPrivate)); panel_class->get_help_uri = cc_display_panel_get_help_uri; object_class->constructor = cc_display_panel_constructor; object_class->get_property = cc_display_panel_get_property; object_class->set_property = cc_display_panel_set_property; object_class->dispose = cc_display_panel_dispose; object_class->finalize = cc_display_panel_finalize; } static void error_message (CcDisplayPanel *self, const char *primary_text, const char *secondary_text) { GtkWidget *toplevel; GtkWidget *dialog; if (self && self->priv->panel) toplevel = gtk_widget_get_toplevel (self->priv->panel); else toplevel = NULL; dialog = gtk_message_dialog_new (GTK_WINDOW (toplevel), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", primary_text); if (secondary_text) gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), "%s", secondary_text); gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); } static gboolean is_unity_session (void) { return (g_strcmp0 (g_getenv("XDG_CURRENT_DESKTOP"), "Unity") == 0); } static gboolean should_show_resolution (gint output_width, gint output_height, gint width, gint height) { if (width >= MIN (output_width, MINIMUM_WIDTH) && height >= MIN (output_height, MINIMUM_HEIGHT)) { return TRUE; } return FALSE; } static void on_screen_changed (GnomeRRScreen *scr, gpointer data) { GnomeRRConfig *current; CcDisplayPanel *self = data; current = gnome_rr_config_new_current (self->priv->screen, NULL); gnome_rr_config_ensure_primary (current); if (self->priv->current_configuration) g_object_unref (self->priv->current_configuration); self->priv->current_configuration = current; self->priv->current_output = NULL; if (self->priv->labeler) { cc_rr_labeler_hide (self->priv->labeler); g_object_unref (self->priv->labeler); } self->priv->labeler = cc_rr_labeler_new (self->priv->current_configuration); if (cc_panel_get_shell (CC_PANEL (self)) == NULL) cc_rr_labeler_hide (self->priv->labeler); else cc_rr_labeler_show (self->priv->labeler); select_current_output_from_dialog_position (self); if (is_unity_session ()) refresh_unity_launcher_placement (self); } static void on_viewport_changed (FooScrollArea *scroll_area, GdkRectangle *old_viewport, GdkRectangle *new_viewport) { foo_scroll_area_set_size (scroll_area, new_viewport->width, new_viewport->height); foo_scroll_area_invalidate (scroll_area); } static void layout_set_font (PangoLayout *layout, const char *font) { PangoFontDescription *desc = pango_font_description_from_string (font); if (desc) { pango_layout_set_font_description (layout, desc); pango_font_description_free (desc); } } static void clear_combo (GtkWidget *widget) { GtkComboBox *box = GTK_COMBO_BOX (widget); GtkTreeModel *model = gtk_combo_box_get_model (box); GtkListStore *store = GTK_LIST_STORE (model); gtk_list_store_clear (store); } typedef struct { const char *text; gboolean found; GtkTreeIter iter; } ForeachInfo; static gboolean foreach (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data) { ForeachInfo *info = data; char *text = NULL; gtk_tree_model_get (model, iter, TEXT_COL, &text, -1); g_assert (text != NULL); if (strcmp (info->text, text) == 0) { info->found = TRUE; info->iter = *iter; return TRUE; } return FALSE; } static void add_key (GtkTreeModel *model, const char *text, gboolean preferred, int width, int height, int rate, GnomeRRRotation rotation) { ForeachInfo info; info.text = text; info.found = FALSE; gtk_tree_model_foreach (model, foreach, &info); if (!info.found) { GtkTreeIter iter; g_debug ("adding %s with rate %d Hz", text, rate); gtk_list_store_insert_with_values (GTK_LIST_STORE (model), &iter, -1, TEXT_COL, text, WIDTH_COL, width, HEIGHT_COL, height, RATE_COL, rate, SORT_COL, width * 10000 + height, ROTATION_COL, rotation, -1); return; } /* Look, the preferred output, replace the old one */ if (preferred) { g_debug ("replacing %s with rate %d Hz (preferred mode)", text, rate); gtk_list_store_set (GTK_LIST_STORE (model), &info.iter, RATE_COL, rate, -1); return; } { int old_rate; gtk_tree_model_get (model, &info.iter, RATE_COL, &old_rate, -1); /* Higher refresh rate */ if (rate > old_rate) { g_debug ("replacing %s with rate %d Hz (old rate: %d)", text, rate, old_rate); gtk_list_store_set (GTK_LIST_STORE (model), &info.iter, RATE_COL, rate, -1); return; } } g_debug ("not adding %s with rate %d Hz (higher rate already there)", text, rate); } static void add_mode (CcDisplayPanel *self, GnomeRRMode *mode, gint output_width, gint output_height, guint preferred_id) { int width, height, rate; width = gnome_rr_mode_get_width (mode); height = gnome_rr_mode_get_height (mode); rate = gnome_rr_mode_get_freq (mode); if (should_show_resolution (output_width, output_height, width, height)) { char *text; gboolean preferred; preferred = (gnome_rr_mode_get_id (mode) == preferred_id); text = make_resolution_string (width, height); add_key (gtk_combo_box_get_model (GTK_COMBO_BOX (self->priv->resolution_combo)), text, preferred, width, height, rate, -1); g_free (text); } } static gboolean combo_select (GtkWidget *widget, const char *text) { GtkComboBox *box = GTK_COMBO_BOX (widget); GtkTreeModel *model = gtk_combo_box_get_model (box); ForeachInfo info; info.text = text; info.found = FALSE; gtk_tree_model_foreach (model, foreach, &info); if (!info.found) return FALSE; gtk_combo_box_set_active_iter (box, &info.iter); return TRUE; } static GnomeRRMode ** get_current_modes (CcDisplayPanel *self) { GnomeRROutput *output; if (gnome_rr_config_get_clone (self->priv->current_configuration)) { return gnome_rr_screen_list_clone_modes (self->priv->screen); } else { if (!self->priv->current_output) return NULL; output = gnome_rr_screen_get_output_by_name (self->priv->screen, gnome_rr_output_info_get_name (self->priv->current_output)); if (!output) return NULL; return gnome_rr_output_list_modes (output); } } static void rebuild_rotation_combo (CcDisplayPanel *self) { typedef struct { GnomeRRRotation rotation; const char * name; } RotationInfo; static const RotationInfo rotations[] = { { GNOME_RR_ROTATION_0, NC_("display panel, rotation", "Normal") }, { GNOME_RR_ROTATION_90, NC_("display panel, rotation", "Counterclockwise") }, { GNOME_RR_ROTATION_270, NC_("display panel, rotation", "Clockwise") }, { GNOME_RR_ROTATION_180, NC_("display panel, rotation", "180 Degrees") }, }; const char *selection; GnomeRRRotation current; int i; clear_combo (self->priv->rotation_combo); gtk_widget_set_sensitive (self->priv->rotation_combo, self->priv->current_output && gnome_rr_output_info_is_active (self->priv->current_output)); if (!self->priv->current_output) return; current = gnome_rr_output_info_get_rotation (self->priv->current_output); selection = NULL; for (i = 0; i < G_N_ELEMENTS (rotations); ++i) { const RotationInfo *info = &(rotations[i]); gnome_rr_output_info_set_rotation (self->priv->current_output, info->rotation); /* NULL-GError --- FIXME: we should say why this rotation is not available! */ if (gnome_rr_config_applicable (self->priv->current_configuration, self->priv->screen, NULL)) { add_key (gtk_combo_box_get_model (GTK_COMBO_BOX (self->priv->rotation_combo)), g_dpgettext2 (GETTEXT_PACKAGE, "display panel, rotation", info->name), FALSE, 0, 0, 0, info->rotation); if (info->rotation == current) selection = g_dpgettext2 (GETTEXT_PACKAGE, "display panel, rotation", info->name); } } gnome_rr_output_info_set_rotation (self->priv->current_output, current); if (!(selection && combo_select (self->priv->rotation_combo, selection))) gtk_combo_box_set_active (GTK_COMBO_BOX (self->priv->rotation_combo), 0); } static int count_active_outputs (CcDisplayPanel *self) { int i, count = 0; GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i] != NULL; ++i) { if (gnome_rr_output_info_is_active (outputs[i])) count++; } return count; } #if 0 static int count_all_outputs (GnomeRRConfig *config) { int i; GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (config); for (i = 0; outputs[i] != NULL; i++) ; return i; } #endif /* Computes whether "Mirror displays" (clone mode) is supported based on these criteria: * * 1. There is an available size for cloning. * * 2. There are 2 or more connected outputs that support that size. */ static gboolean mirror_screens_is_supported (CcDisplayPanel *self) { int clone_width, clone_height; gboolean have_clone_size; gboolean mirror_is_supported; mirror_is_supported = FALSE; have_clone_size = get_clone_size (self->priv->screen, &clone_width, &clone_height); if (have_clone_size) { int i; int num_outputs_with_clone_size; GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); num_outputs_with_clone_size = 0; for (i = 0; outputs[i] != NULL; i++) { /* We count the connected outputs that support the clone size. It * doesn't matter if those outputs aren't actually On currently; we * will turn them on in on_clone_changed(). */ if (gnome_rr_output_info_is_connected (outputs[i]) && output_info_supports_mode (self, outputs[i], clone_width, clone_height)) num_outputs_with_clone_size++; } if (num_outputs_with_clone_size >= 2) mirror_is_supported = TRUE; } return mirror_is_supported; } static void rebuild_mirror_screens (CcDisplayPanel *self) { gboolean mirror_is_active; gboolean mirror_is_supported; g_signal_handlers_block_by_func (self->priv->clone_checkbox, G_CALLBACK (on_clone_changed), self); mirror_is_active = self->priv->current_configuration && gnome_rr_config_get_clone (self->priv->current_configuration); /* If mirror_is_active, then it *must* be possible to turn mirroring off */ mirror_is_supported = mirror_is_active || mirror_screens_is_supported (self); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (self->priv->clone_checkbox), mirror_is_active); gtk_widget_set_sensitive (self->priv->clone_checkbox, mirror_is_supported); gtk_widget_set_sensitive (self->priv->clone_label, mirror_is_supported); /* set inactive the launcher placement choice */ gtk_widget_set_sensitive (WID ("launcher_placement_combo"), !mirror_is_active); gtk_widget_set_sensitive (WID ("stickyedge_switch"), !mirror_is_active); g_signal_handlers_unblock_by_func (self->priv->clone_checkbox, G_CALLBACK (on_clone_changed), self); } static char * mirror_monitor_name (void) { /* Keep this string in sync with gnome-desktop/libgnome-desktop/gnome-rr-labeler.c */ /* Translators: this is the feature where what you see on your laptop's * screen is the same as your external projector. Here, "Mirrored" is being * used as an adjective. For example, the Spanish translation could be * "Pantallas en Espejo". */ return g_strdup (_("Mirrored Displays")); } static void rebuild_current_monitor_label (CcDisplayPanel *self) { char *str, *tmp; GdkColor color; gboolean use_color; if (self->priv->current_output) { if (gnome_rr_config_get_clone (self->priv->current_configuration)) tmp = mirror_monitor_name (); else tmp = g_strdup (gnome_rr_output_info_get_display_name (self->priv->current_output)); str = g_strdup_printf ("<b>%s</b>", tmp); gdk_color_parse ("#FFAAAA", &color); use_color = TRUE; g_free (tmp); } else { str = g_strdup_printf ("<b>%s</b>", _("Monitor")); use_color = FALSE; } gtk_label_set_markup (GTK_LABEL (self->priv->current_monitor_label), str); g_free (str); if (use_color) { GdkRGBA black = { 0, 0, 0, 1.0 }; GdkRGBA light; light.red = color.red / 65535.0; light.green = color.green / 65535.0; light.blue = color.blue / 65535.0; light.alpha = 1.0; gtk_widget_override_background_color (self->priv->current_monitor_event_box, gtk_widget_get_state_flags (self->priv->current_monitor_event_box), &light); /* Make the label explicitly black. We don't want it to follow the * theme's colors, since the label is always shown against a light * pastel background. See bgo#556050 */ gtk_widget_override_color (self->priv->current_monitor_label, gtk_widget_get_state_flags (self->priv->current_monitor_label), &black); } else { /* Remove any modifications we did on the label's color */ gtk_widget_override_color (self->priv->current_monitor_label, gtk_widget_get_state_flags (self->priv->current_monitor_label), NULL); } gtk_event_box_set_visible_window (GTK_EVENT_BOX (self->priv->current_monitor_event_box), use_color); } static void rebuild_on_off_radios (CcDisplayPanel *self) { gboolean sensitive; gboolean on_active; g_signal_handlers_block_by_func (self->priv->monitor_switch, G_CALLBACK (monitor_switch_active_cb), self); sensitive = FALSE; on_active = FALSE; if (!gnome_rr_config_get_clone (self->priv->current_configuration) && self->priv->current_output) { if (count_active_outputs (self) > 1 || !gnome_rr_output_info_is_active (self->priv->current_output)) sensitive = TRUE; else sensitive = FALSE; on_active = gnome_rr_output_info_is_active (self->priv->current_output); } gtk_widget_set_sensitive (self->priv->monitor_switch, sensitive); gtk_switch_set_active (GTK_SWITCH (self->priv->monitor_switch), on_active); g_signal_handlers_unblock_by_func (self->priv->monitor_switch, G_CALLBACK (monitor_switch_active_cb), self); } static char * make_resolution_string (int width, int height) { int ratio; const char *aspect = NULL; if (width && height) { if (width > height) ratio = width * 10 / height; else ratio = height * 10 / width; switch (ratio) { case 13: aspect = "4:3"; break; case 16: aspect = "16:10"; break; case 17: aspect = "16:9"; break; case 23: aspect = "21:9"; break; case 12: aspect = "5:4"; break; /* This catches 1.5625 as well (1600x1024) when maybe it shouldn't. */ case 15: aspect = "3:2"; break; case 18: aspect = "9:5"; break; case 10: aspect = "1:1"; break; } } if (aspect != NULL) return g_strdup_printf (_("%d x %d (%s)"), width, height, aspect); else return g_strdup_printf (_("%d x %d"), width, height); } static void find_best_mode (GnomeRRMode **modes, int *out_width, int *out_height) { int i; *out_width = 0; *out_height = 0; for (i = 0; modes[i] != NULL; i++) { int w, h; w = gnome_rr_mode_get_width (modes[i]); h = gnome_rr_mode_get_height (modes[i]); if (w * h > *out_width * *out_height) { *out_width = w; *out_height = h; } } } static void rebuild_resolution_combo (CcDisplayPanel *self) { int i; GnomeRRMode **modes; GnomeRRMode *mode; char *current; int output_width, output_height; guint32 preferred_id; GnomeRROutput *output; clear_combo (self->priv->resolution_combo); if (!(modes = get_current_modes (self)) || !self->priv->current_output || !gnome_rr_output_info_is_active (self->priv->current_output)) { gtk_widget_set_sensitive (self->priv->resolution_combo, FALSE); return; } g_assert (self->priv->current_output != NULL); gnome_rr_output_info_get_geometry (self->priv->current_output, NULL, NULL, &output_width, &output_height); g_assert (output_width != 0 && output_height != 0); gtk_widget_set_sensitive (self->priv->resolution_combo, TRUE); output = gnome_rr_screen_get_output_by_name (self->priv->screen, gnome_rr_output_info_get_name (self->priv->current_output)); mode = gnome_rr_output_get_preferred_mode (output); preferred_id = gnome_rr_mode_get_id (mode); for (i = 0; modes[i] != NULL; ++i) add_mode (self, modes[i], output_width, output_height, preferred_id); /* And force the preferred mode in the drop-down (when not in clone mode) * https://bugzilla.gnome.org/show_bug.cgi?id=680969 */ if (!gnome_rr_config_get_clone (self->priv->current_configuration)) add_mode (self, mode, output_width, output_height, preferred_id); current = make_resolution_string (output_width, output_height); if (!combo_select (self->priv->resolution_combo, current)) { int best_w, best_h; char *str; find_best_mode (modes, &best_w, &best_h); str = make_resolution_string (best_w, best_h); combo_select (self->priv->resolution_combo, str); g_free (str); } g_free (current); } static void rebuild_gui (CcDisplayPanel *self) { /* We would break spectacularly if we recursed, so * just assert if that happens */ g_assert (self->priv->ignore_gui_changes == FALSE); self->priv->ignore_gui_changes = TRUE; rebuild_mirror_screens (self); rebuild_current_monitor_label (self); rebuild_on_off_radios (self); rebuild_resolution_combo (self); rebuild_rotation_combo (self); refresh_unity_launcher_placement (self); self->priv->ignore_gui_changes = FALSE; } static gboolean get_mode (GtkWidget *widget, int *width, int *height, int *rate, GnomeRRRotation *rot) { GtkTreeIter iter; GtkTreeModel *model; GtkComboBox *box = GTK_COMBO_BOX (widget); int dummy; if (!gtk_combo_box_get_active_iter (box, &iter)) return FALSE; if (!width) width = &dummy; if (!height) height = &dummy; if (!rate) rate = &dummy; if (!rot) rot = (GnomeRRRotation *)&dummy; model = gtk_combo_box_get_model (box); gtk_tree_model_get (model, &iter, WIDTH_COL, width, HEIGHT_COL, height, RATE_COL, rate, ROTATION_COL, rot, -1); return TRUE; } static void on_rotation_changed (GtkComboBox *box, gpointer data) { CcDisplayPanel *self = data; GnomeRRRotation rotation; if (!self->priv->current_output) return; if (get_mode (self->priv->rotation_combo, NULL, NULL, NULL, &rotation)) gnome_rr_output_info_set_rotation (self->priv->current_output, rotation); foo_scroll_area_invalidate (FOO_SCROLL_AREA (self->priv->area)); } static void select_resolution_for_current_output (CcDisplayPanel *self) { GnomeRRMode **modes; int width, height; int x,y; gnome_rr_output_info_get_geometry (self->priv->current_output, &x, &y, NULL, NULL); width = gnome_rr_output_info_get_preferred_width (self->priv->current_output); height = gnome_rr_output_info_get_preferred_height (self->priv->current_output); if (width != 0 && height != 0) { gnome_rr_output_info_set_geometry (self->priv->current_output, x, y, width, height); return; } modes = get_current_modes (self); if (!modes) return; find_best_mode (modes, &width, &height); gnome_rr_output_info_set_geometry (self->priv->current_output, x, y, width, height); } static void monitor_switch_active_cb (GObject *object, GParamSpec *pspec, gpointer data) { CcDisplayPanel *self = data; gboolean value; if (!self->priv->current_output) return; value = gtk_switch_get_active (GTK_SWITCH (object)); if (value) { gnome_rr_output_info_set_active (self->priv->current_output, TRUE); select_resolution_for_current_output (self); } else { gnome_rr_output_info_set_active (self->priv->current_output, FALSE); gnome_rr_config_ensure_primary (self->priv->current_configuration); } rebuild_gui (self); foo_scroll_area_invalidate (FOO_SCROLL_AREA (self->priv->area)); } static void realign_outputs_after_resolution_change (CcDisplayPanel *self, GnomeRROutputInfo *output_that_changed, int old_width, int old_height) { /* We find the outputs that were below or to the right of the output that * changed, and realign them; we also do that for outputs that shared the * right/bottom edges with the output that changed. The outputs that are * above or to the left of that output don't need to change. */ int i; int old_right_edge, old_bottom_edge; int dx, dy; int x, y, width, height; GnomeRROutputInfo **outputs; g_assert (self->priv->current_configuration != NULL); gnome_rr_output_info_get_geometry (output_that_changed, &x, &y, &width, &height); if (width == old_width && height == old_height) return; old_right_edge = x + old_width; old_bottom_edge = y + old_height; dx = width - old_width; dy = height - old_height; outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i] != NULL; i++) { int output_x, output_y; int output_width, output_height; if (outputs[i] == output_that_changed || !gnome_rr_output_info_is_connected (outputs[i])) continue; gnome_rr_output_info_get_geometry (outputs[i], &output_x, &output_y, &output_width, &output_height); if (output_x >= old_right_edge) output_x += dx; else if (output_x + output_width == old_right_edge) output_x = x + width - output_width; if (output_y >= old_bottom_edge) output_y += dy; else if (output_y + output_height == old_bottom_edge) output_y = y + height - output_height; gnome_rr_output_info_set_geometry (outputs[i], output_x, output_y, output_width, output_height); } } static void on_resolution_changed (GtkComboBox *box, gpointer data) { CcDisplayPanel *self = data; int old_width, old_height; int x,y; int width; int height; if (!self->priv->current_output) return; gnome_rr_output_info_get_geometry (self->priv->current_output, &x, &y, &old_width, &old_height); if (get_mode (self->priv->resolution_combo, &width, &height, NULL, NULL)) { gnome_rr_output_info_set_geometry (self->priv->current_output, x, y, width, height); if (width == 0 || height == 0) gnome_rr_output_info_set_active (self->priv->current_output, FALSE); else gnome_rr_output_info_set_active (self->priv->current_output, TRUE); } realign_outputs_after_resolution_change (self, self->priv->current_output, old_width, old_height); rebuild_rotation_combo (self); foo_scroll_area_invalidate (FOO_SCROLL_AREA (self->priv->area)); } static void lay_out_outputs_horizontally (CcDisplayPanel *self) { int i; int x; GnomeRROutputInfo **outputs; /* Lay out all the monitors horizontally when "mirror screens" is turned * off, to avoid having all of them overlapped initially. We put the * outputs turned off on the right-hand side. */ x = 0; /* First pass, all "on" outputs */ outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i]; ++i) { int width, height; if (gnome_rr_output_info_is_connected (outputs[i]) && gnome_rr_output_info_is_active (outputs[i])) { gnome_rr_output_info_get_geometry (outputs[i], NULL, NULL, &width, &height); gnome_rr_output_info_set_geometry (outputs[i], x, 0, width, height); x += width; } } /* Second pass, all the black screens */ for (i = 0; outputs[i]; ++i) { int width, height; if (!(gnome_rr_output_info_is_connected (outputs[i]) && gnome_rr_output_info_is_active (outputs[i]))) { gnome_rr_output_info_get_geometry (outputs[i], NULL, NULL, &width, &height); gnome_rr_output_info_set_geometry (outputs[i], x, 0, width, height); x += width; } } } /* FIXME: this function is copied from gnome-settings-daemon/plugins/xrandr/csd-xrandr-manager.c. * Do we need to put this function in gnome-desktop for public use? */ static gboolean get_clone_size (GnomeRRScreen *screen, int *width, int *height) { GnomeRRMode **modes = gnome_rr_screen_list_clone_modes (screen); int best_w, best_h; int i; best_w = 0; best_h = 0; for (i = 0; modes[i] != NULL; ++i) { GnomeRRMode *mode = modes[i]; int w, h; w = gnome_rr_mode_get_width (mode); h = gnome_rr_mode_get_height (mode); if (w * h > best_w * best_h) { best_w = w; best_h = h; } } if (best_w > 0 && best_h > 0) { if (width) *width = best_w; if (height) *height = best_h; return TRUE; } return FALSE; } static gboolean output_info_supports_mode (CcDisplayPanel *self, GnomeRROutputInfo *info, int width, int height) { GnomeRROutput *output; GnomeRRMode **modes; int i; if (!gnome_rr_output_info_is_connected (info)) return FALSE; output = gnome_rr_screen_get_output_by_name (self->priv->screen, gnome_rr_output_info_get_name (info)); if (!output) return FALSE; modes = gnome_rr_output_list_modes (output); for (i = 0; modes[i]; i++) { if (gnome_rr_mode_get_width (modes[i]) == width && gnome_rr_mode_get_height (modes[i]) == height) return TRUE; } return FALSE; } static void on_clone_changed (GtkWidget *box, gpointer data) { CcDisplayPanel *self = data; gnome_rr_config_set_clone (self->priv->current_configuration, gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (self->priv->clone_checkbox))); if (gnome_rr_config_get_clone (self->priv->current_configuration)) { int i; int width, height; GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i]; ++i) { if (gnome_rr_output_info_is_connected (outputs[i])) { self->priv->current_output = outputs[i]; break; } } /* Turn on all the connected screens that support the best clone mode. * The user may hit "Mirror displays", but he shouldn't have to turn on * all the required outputs as well. */ get_clone_size (self->priv->screen, &width, &height); for (i = 0; outputs[i]; i++) { int x, y; if (output_info_supports_mode (self, outputs[i], width, height)) { gnome_rr_output_info_set_active (outputs[i], TRUE); gnome_rr_output_info_get_geometry (outputs[i], &x, &y, NULL, NULL); gnome_rr_output_info_set_geometry (outputs[i], x, y, width, height); } } } else { if (output_overlaps (self->priv->current_output, self->priv->current_configuration)) lay_out_outputs_horizontally (self); } rebuild_gui (self); } static void apply_rotation_to_geometry (GnomeRROutputInfo *output, int *w, int *h) { GnomeRRRotation rotation; rotation = gnome_rr_output_info_get_rotation (output); if ((rotation & GNOME_RR_ROTATION_90) || (rotation & GNOME_RR_ROTATION_270)) { int tmp; tmp = *h; *h = *w; *w = tmp; } } static void get_geometry (GnomeRROutputInfo *output, int *w, int *h) { if (gnome_rr_output_info_is_active (output)) { gnome_rr_output_info_get_geometry (output, NULL, NULL, w, h); } else { *h = gnome_rr_output_info_get_preferred_height (output); *w = gnome_rr_output_info_get_preferred_width (output); } apply_rotation_to_geometry (output, w, h); } #define SPACE 15 #define MARGIN 15 static GList * list_connected_outputs (CcDisplayPanel *self, int *total_w, int *total_h) { int i, dummy; GList *result = NULL; GnomeRROutputInfo **outputs; if (!total_w) total_w = &dummy; if (!total_h) total_h = &dummy; *total_w = 0; *total_h = 0; outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i] != NULL; ++i) { if (gnome_rr_output_info_is_connected (outputs[i])) { int w, h; result = g_list_prepend (result, outputs[i]); get_geometry (outputs[i], &w, &h); *total_w += w; *total_h += h; } } return g_list_reverse (result); } static int get_n_connected (CcDisplayPanel *self) { GList *connected_outputs = list_connected_outputs (self, NULL, NULL); int n = g_list_length (connected_outputs); g_list_free (connected_outputs); return n; } static double compute_scale (CcDisplayPanel *self) { int available_w, available_h; int total_w, total_h; int n_monitors; GdkRectangle viewport; GList *connected_outputs; foo_scroll_area_get_viewport (FOO_SCROLL_AREA (self->priv->area), &viewport); connected_outputs = list_connected_outputs (self, &total_w, &total_h); n_monitors = g_list_length (connected_outputs); g_list_free (connected_outputs); available_w = viewport.width - 2 * MARGIN - (n_monitors - 1) * SPACE; available_h = viewport.height - 2 * MARGIN - (n_monitors - 1) * SPACE; return MIN ((double)available_w / total_w, (double)available_h / total_h); } typedef struct Edge { GnomeRROutputInfo *output; int x1, y1; int x2, y2; } Edge; typedef struct Snap { Edge *snapper; /* Edge that should be snapped */ Edge *snappee; int dy, dx; } Snap; static void add_edge (GnomeRROutputInfo *output, int x1, int y1, int x2, int y2, GArray *edges) { Edge e; e.x1 = x1; e.x2 = x2; e.y1 = y1; e.y2 = y2; e.output = output; g_array_append_val (edges, e); } static void list_edges_for_output (GnomeRROutputInfo *output, GArray *edges) { int x, y, w, h; gnome_rr_output_info_get_geometry (output, &x, &y, &w, &h); apply_rotation_to_geometry (output, &w, &h); /* Top, Bottom, Left, Right */ add_edge (output, x, y, x + w, y, edges); add_edge (output, x, y + h, x + w, y + h, edges); add_edge (output, x, y, x, y + h, edges); add_edge (output, x + w, y, x + w, y + h, edges); } static void list_edges (GnomeRRConfig *config, GArray *edges) { int i; GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (config); for (i = 0; outputs[i]; ++i) { if (gnome_rr_output_info_is_connected (outputs[i])) list_edges_for_output (outputs[i], edges); } } static gboolean overlap (int s1, int e1, int s2, int e2) { return (!(e1 < s2 || s1 >= e2)); } static gboolean horizontal_overlap (Edge *snapper, Edge *snappee) { if (snapper->y1 != snapper->y2 || snappee->y1 != snappee->y2) return FALSE; return overlap (snapper->x1, snapper->x2, snappee->x1, snappee->x2); } static gboolean vertical_overlap (Edge *snapper, Edge *snappee) { if (snapper->x1 != snapper->x2 || snappee->x1 != snappee->x2) return FALSE; return overlap (snapper->y1, snapper->y2, snappee->y1, snappee->y2); } static void add_snap (GArray *snaps, Snap snap) { if (ABS (snap.dx) <= 200 || ABS (snap.dy) <= 200) g_array_append_val (snaps, snap); } static void add_edge_snaps (Edge *snapper, Edge *snappee, GArray *snaps) { Snap snap; snap.snapper = snapper; snap.snappee = snappee; if (horizontal_overlap (snapper, snappee)) { snap.dx = 0; snap.dy = snappee->y1 - snapper->y1; add_snap (snaps, snap); } else if (vertical_overlap (snapper, snappee)) { snap.dy = 0; snap.dx = snappee->x1 - snapper->x1; add_snap (snaps, snap); } /* Corner snaps */ /* 1->1 */ snap.dx = snappee->x1 - snapper->x1; snap.dy = snappee->y1 - snapper->y1; add_snap (snaps, snap); /* 1->2 */ snap.dx = snappee->x2 - snapper->x1; snap.dy = snappee->y2 - snapper->y1; add_snap (snaps, snap); /* 2->2 */ snap.dx = snappee->x2 - snapper->x2; snap.dy = snappee->y2 - snapper->y2; add_snap (snaps, snap); /* 2->1 */ snap.dx = snappee->x1 - snapper->x2; snap.dy = snappee->y1 - snapper->y2; add_snap (snaps, snap); } static void list_snaps (GnomeRROutputInfo *output, GArray *edges, GArray *snaps) { int i; for (i = 0; i < edges->len; ++i) { Edge *output_edge = &(g_array_index (edges, Edge, i)); if (output_edge->output == output) { int j; for (j = 0; j < edges->len; ++j) { Edge *edge = &(g_array_index (edges, Edge, j)); if (edge->output != output) add_edge_snaps (output_edge, edge, snaps); } } } } #if 0 static void print_edge (Edge *edge) { g_debug ("(%d %d %d %d)", edge->x1, edge->y1, edge->x2, edge->y2); } #endif static gboolean corner_on_edge (int x, int y, Edge *e) { if (x == e->x1 && x == e->x2 && y >= e->y1 && y <= e->y2) return TRUE; if (y == e->y1 && y == e->y2 && x >= e->x1 && x <= e->x2) return TRUE; return FALSE; } static gboolean edges_align (Edge *e1, Edge *e2) { if (corner_on_edge (e1->x1, e1->y1, e2)) return TRUE; if (corner_on_edge (e2->x1, e2->y1, e1)) return TRUE; return FALSE; } static gboolean output_is_aligned (GnomeRROutputInfo *output, GArray *edges) { gboolean result = FALSE; int i; for (i = 0; i < edges->len; ++i) { Edge *output_edge = &(g_array_index (edges, Edge, i)); if (output_edge->output == output) { int j; for (j = 0; j < edges->len; ++j) { Edge *edge = &(g_array_index (edges, Edge, j)); /* We are aligned if an output edge matches * an edge of another output */ if (edge->output != output_edge->output) { if (edges_align (output_edge, edge)) { result = TRUE; goto done; } } } } } done: return result; } static void get_output_rect (GnomeRROutputInfo *output, GdkRectangle *rect) { gnome_rr_output_info_get_geometry (output, &rect->x, &rect->y, &rect->width, &rect->height); apply_rotation_to_geometry (output, &rect->width, &rect->height); } static gboolean output_overlaps (GnomeRROutputInfo *output, GnomeRRConfig *config) { int i; GdkRectangle output_rect; GnomeRROutputInfo **outputs; g_assert (output != NULL); get_output_rect (output, &output_rect); outputs = gnome_rr_config_get_outputs (config); for (i = 0; outputs[i]; ++i) { if (outputs[i] != output && gnome_rr_output_info_is_connected (outputs[i])) { GdkRectangle other_rect; get_output_rect (outputs[i], &other_rect); if (gdk_rectangle_intersect (&output_rect, &other_rect, NULL)) return TRUE; } } return FALSE; } static gboolean gnome_rr_config_is_aligned (GnomeRRConfig *config, GArray *edges) { int i; gboolean result = TRUE; GnomeRROutputInfo **outputs; outputs = gnome_rr_config_get_outputs (config); for (i = 0; outputs[i]; ++i) { if (gnome_rr_output_info_is_connected (outputs[i])) { if (!output_is_aligned (outputs[i], edges)) return FALSE; if (output_overlaps (outputs[i], config)) return FALSE; } } return result; } static gboolean is_corner_snap (const Snap *s) { return s->dx != 0 && s->dy != 0; } static int compare_snaps (gconstpointer v1, gconstpointer v2) { const Snap *s1 = v1; const Snap *s2 = v2; int sv1 = MAX (ABS (s1->dx), ABS (s1->dy)); int sv2 = MAX (ABS (s2->dx), ABS (s2->dy)); int d; d = sv1 - sv2; /* This snapping algorithm is good enough for rock'n'roll, but * this is probably a better: * * First do a horizontal/vertical snap, then * with the new coordinates from that snap, * do a corner snap. * * Right now, it's confusing that corner snapping * depends on the distance in an axis that you can't actually see. * */ if (d == 0) { if (is_corner_snap (s1) && !is_corner_snap (s2)) return -1; else if (is_corner_snap (s2) && !is_corner_snap (s1)) return 1; else return 0; } else { return d; } } /* Sets a mouse cursor for a widget's window. As a hack, you can pass * GDK_BLANK_CURSOR to mean "set the cursor to NULL" (i.e. reset the widget's * window's cursor to its default). */ static void set_cursor (GtkWidget *widget, GdkCursorType type) { GdkCursor *cursor; GdkWindow *window; if (type == GDK_BLANK_CURSOR) cursor = NULL; else cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), type); window = gtk_widget_get_window (widget); if (window) gdk_window_set_cursor (window, cursor); if (cursor) g_object_unref (cursor); } static void set_top_bar_tooltip (CcDisplayPanel *self, gboolean is_dragging) { const char *text; if (is_dragging) text = NULL; else text = _("Drag to change primary display."); gtk_widget_set_tooltip_text (self->priv->area, text); } static void on_top_bar_event (FooScrollArea *area, FooScrollAreaEvent *event, CcDisplayPanel *self) { /* Ignore drops */ if (event->type == FOO_DROP) return; /* If the mouse is inside the top bar, set the cursor to "you can move me". See * on_canvas_event() for where we reset the cursor to the default if it * exits the outputs' area. */ if (!gnome_rr_config_get_clone (self->priv->current_configuration) && get_n_connected (self) > 1) set_cursor (GTK_WIDGET (area), GDK_HAND1); if (event->type == FOO_BUTTON_PRESS) { rebuild_gui (self); set_top_bar_tooltip (self, TRUE); if (!gnome_rr_config_get_clone (self->priv->current_configuration) && get_n_connected (self) > 1) { self->priv->dragging_top_bar = TRUE; foo_scroll_area_begin_grab (area, (FooScrollAreaEventFunc) on_top_bar_event, self); } foo_scroll_area_invalidate (area); } else { if (foo_scroll_area_is_grabbed (area)) { if (event->type == FOO_BUTTON_RELEASE) { foo_scroll_area_end_grab (area, event); self->priv->dragging_top_bar = FALSE; set_top_bar_tooltip (self, FALSE); } foo_scroll_area_invalidate (area); } } } static void set_monitors_tooltip (CcDisplayPanel *self, gboolean is_dragging) { const char *text; if (is_dragging) text = NULL; else text = _("Select a monitor to change its properties; drag it to rearrange its placement."); gtk_widget_set_tooltip_text (self->priv->area, text); } static void set_primary_output (CcDisplayPanel *self, GnomeRROutputInfo *output) { int i; GnomeRROutputInfo **outputs; outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i] != NULL; ++i) gnome_rr_output_info_set_primary (outputs[i], outputs[i] == output); gtk_widget_queue_draw (WID ("self->priv->area")); /* refresh the combobox */ refresh_unity_launcher_placement (self); } static void on_output_event (FooScrollArea *area, FooScrollAreaEvent *event, gpointer data) { GnomeRROutputInfo *output = data; CcDisplayPanel *self = g_object_get_data (G_OBJECT (area), "panel"); if (event->type == FOO_DRAG_HOVER) { if (gnome_rr_output_info_is_active (output) && self->priv->dragging_top_bar) set_primary_output (self, output); return; } if (event->type == FOO_DROP) { /* Activate new primary? */ return; } /* If the mouse is inside the outputs, set the cursor to "you can move me". See * on_canvas_event() for where we reset the cursor to the default if it * exits the outputs' area. */ if (!gnome_rr_config_get_clone (self->priv->current_configuration) && get_n_connected (self) > 1) set_cursor (GTK_WIDGET (area), GDK_FLEUR); if (event->type == FOO_BUTTON_PRESS) { GrabInfo *info; self->priv->current_output = output; rebuild_gui (self); set_monitors_tooltip (self, TRUE); if (!gnome_rr_config_get_clone (self->priv->current_configuration) && get_n_connected (self) > 1) { int output_x, output_y; gnome_rr_output_info_get_geometry (output, &output_x, &output_y, NULL, NULL); foo_scroll_area_begin_grab (area, on_output_event, data); info = g_new0 (GrabInfo, 1); info->grab_x = event->x; info->grab_y = event->y; info->output_x = output_x; info->output_y = output_y; g_object_set_data (G_OBJECT (output), "grab-info", info); } foo_scroll_area_invalidate (area); } else { if (foo_scroll_area_is_grabbed (area)) { GrabInfo *info = g_object_get_data (G_OBJECT (output), "grab-info"); double scale = compute_scale (self); int old_x, old_y; int width, height; int new_x, new_y; int i; GArray *edges, *snaps, *new_edges; gnome_rr_output_info_get_geometry (output, &old_x, &old_y, &width, &height); new_x = info->output_x + (event->x - info->grab_x) / scale; new_y = info->output_y + (event->y - info->grab_y) / scale; gnome_rr_output_info_set_geometry (output, new_x, new_y, width, height); edges = g_array_new (TRUE, TRUE, sizeof (Edge)); snaps = g_array_new (TRUE, TRUE, sizeof (Snap)); new_edges = g_array_new (TRUE, TRUE, sizeof (Edge)); list_edges (self->priv->current_configuration, edges); list_snaps (output, edges, snaps); g_array_sort (snaps, compare_snaps); gnome_rr_output_info_set_geometry (output, new_x, new_y, width, height); for (i = 0; i < snaps->len; ++i) { Snap *snap = &(g_array_index (snaps, Snap, i)); GArray *new_edges = g_array_new (TRUE, TRUE, sizeof (Edge)); gnome_rr_output_info_set_geometry (output, new_x + snap->dx, new_y + snap->dy, width, height); g_array_set_size (new_edges, 0); list_edges (self->priv->current_configuration, new_edges); if (gnome_rr_config_is_aligned (self->priv->current_configuration, new_edges)) { g_array_free (new_edges, TRUE); break; } else { gnome_rr_output_info_set_geometry (output, info->output_x, info->output_y, width, height); } } g_array_free (new_edges, TRUE); g_array_free (snaps, TRUE); g_array_free (edges, TRUE); if (event->type == FOO_BUTTON_RELEASE) { foo_scroll_area_end_grab (area, event); set_monitors_tooltip (self, FALSE); g_free (g_object_get_data (G_OBJECT (output), "grab-info")); g_object_set_data (G_OBJECT (output), "grab-info", NULL); #if 0 g_debug ("new position: %d %d %d %d", output->x, output->y, output->width, output->height); #endif } foo_scroll_area_invalidate (area); } } } static void on_canvas_event (FooScrollArea *area, FooScrollAreaEvent *event, gpointer data) { /* If the mouse exits the outputs, reset the cursor to the default. See * on_output_event() for where we set the cursor to the movement cursor if * it is over one of the outputs. */ set_cursor (GTK_WIDGET (area), GDK_BLANK_CURSOR); } static PangoLayout * get_display_name (CcDisplayPanel *self, GnomeRROutputInfo *output) { PangoLayout *layout; char *text; if (gnome_rr_config_get_clone (self->priv->current_configuration)) text = mirror_monitor_name (); else text = g_strdup (gnome_rr_output_info_get_display_name (output)); layout = gtk_widget_create_pango_layout (GTK_WIDGET (self->priv->area), text); g_free (text); pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER); return layout; } static void paint_background (FooScrollArea *area, cairo_t *cr) { GdkRectangle viewport; GtkWidget *widget; GtkStyleContext *context; GdkRGBA fg, bg; widget = GTK_WIDGET (area); foo_scroll_area_get_viewport (area, &viewport); context = gtk_widget_get_style_context (widget); gtk_style_context_get_color (context, GTK_STATE_FLAG_NORMAL, &fg); gtk_style_context_get_background_color (context, GTK_STATE_FLAG_NORMAL, &bg); cairo_set_source_rgba (cr, (fg.red + bg.red) / 2, (fg.green + bg.green) / 2, (fg.blue + bg.blue) / 2, (fg.alpha + bg.alpha) / 2); cairo_rectangle (cr, viewport.x, viewport.y, viewport.width, viewport.height); cairo_fill_preserve (cr); foo_scroll_area_add_input_from_fill (area, cr, on_canvas_event, NULL); cairo_set_source_rgba (cr, 0.7 * bg.red, 0.7 * bg.green, 0.7 * bg.blue, 0.7 * bg.alpha); cairo_stroke (cr); } static void color_shade (double *r, double *g, double *b, double k) { double h, s, v; gtk_rgb_to_hsv (*r, *g, *b, &h, &s, &v); s *= k; if (s > 1.0) s = 1.0; else if (s < 0.0) s = 0.0; v *= k; if (v > 1.0) v = 1.0; else if (v < 0.0) v = 0.0; gtk_hsv_to_rgb (h, s, v, r, g, b); } static void paint_output (CcDisplayPanel *self, cairo_t *cr, int i) { int w, h; double scale = compute_scale (self); double x, y; int output_x, output_y; GnomeRRRotation rotation; int total_w, total_h; GList *connected_outputs = list_connected_outputs (self, &total_w, &total_h); GnomeRROutputInfo *output = g_list_nth (connected_outputs, i)->data; PangoLayout *layout = get_display_name (self, output); PangoRectangle ink_extent, log_extent; GdkRectangle viewport; GdkColor output_color; double r, g, b; double available_w; double factor; cairo_save (cr); foo_scroll_area_get_viewport (FOO_SCROLL_AREA (self->priv->area), &viewport); get_geometry (output, &w, &h); #if 0 g_debug ("%s (%p) geometry %d %d %d primary=%d", output->name, output->name, w, h, output->rate, output->primary); #endif viewport.height -= 2 * MARGIN; viewport.width -= 2 * MARGIN; gnome_rr_output_info_get_geometry (output, &output_x, &output_y, NULL, NULL); x = output_x * scale + MARGIN + (viewport.width - total_w * scale) / 2.0; y = output_y * scale + MARGIN + (viewport.height - total_h * scale) / 2.0; #if 0 g_debug ("scaled: %f %f", x, y); g_debug ("scale: %f", scale); g_debug ("%f %f %f %f", x, y, w * scale + 0.5, h * scale + 0.5); #endif cairo_translate (cr, x + (w * scale + 0.5) / 2, y + (h * scale + 0.5) / 2); /* rotation is already applied in get_geometry */ rotation = gnome_rr_output_info_get_rotation (output); if (rotation & GNOME_RR_REFLECT_X) cairo_scale (cr, -1, 1); if (rotation & GNOME_RR_REFLECT_Y) cairo_scale (cr, 1, -1); cairo_translate (cr, - x - (w * scale + 0.5) / 2, - y - (h * scale + 0.5) / 2); if (output == self->priv->current_output) { GtkStyleContext *context; GdkRGBA color; context = gtk_widget_get_style_context (self->priv->area); gtk_style_context_get_background_color (context, GTK_STATE_FLAG_SELECTED, &color); cairo_rectangle (cr, x - 2, y - 2, w * scale + 0.5 + 4, h * scale + 0.5 + 4); cairo_set_line_width (cr, 4); cairo_set_source_rgba (cr, color.red, color.green, color.blue, 0.5); cairo_stroke (cr); } cairo_rectangle (cr, x, y, w * scale + 0.5, h * scale + 0.5); cairo_clip_preserve (cr); gdk_color_parse ("#FFAAAA", &output_color); r = output_color.red / 65535.0; g = output_color.green / 65535.0; b = output_color.blue / 65535.0; if (!gnome_rr_output_info_is_active (output)) { /* If the output is turned off, just darken the selected color */ color_shade (&r, &g, &b, 0.4); } cairo_set_source_rgba (cr, r, g, b, 1.0); foo_scroll_area_add_input_from_fill (FOO_SCROLL_AREA (self->priv->area), cr, on_output_event, output); cairo_fill (cr); cairo_rectangle (cr, x + 0.5, y + 0.5, w * scale + 0.5 - 1, h * scale + 0.5 - 1); cairo_set_line_width (cr, 1); cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, 1.0); cairo_stroke (cr); cairo_set_line_width (cr, 2); cairo_save (cr); layout_set_font (layout, "Sans 10"); pango_layout_get_pixel_extents (layout, &ink_extent, &log_extent); available_w = w * scale + 0.5 - 6; /* Same as the inner rectangle's width, minus 1 pixel of padding on each side */ if (available_w < ink_extent.width) factor = available_w / ink_extent.width; else factor = 1.0; cairo_move_to (cr, x + ((w * scale + 0.5) - factor * log_extent.width) / 2, y + ((h * scale + 0.5) - factor * log_extent.height) / 2); cairo_scale (cr, factor, factor); if (gnome_rr_output_info_is_active (output)) cairo_set_source_rgb (cr, 0.0, 0.0, 0.0); else cairo_set_source_rgb (cr, 1.0, 1.0, 1.0); pango_cairo_show_layout (cr, layout); g_object_unref (layout); cairo_restore (cr); /* Only display a launcher on all or primary monitor */ if (is_unity_session ()) { if (gnome_rr_output_info_is_active (output) && (unity_launcher_on_all_monitors (self->priv->unity_settings) || gnome_rr_output_info_get_primary (output))) { cairo_rectangle (cr, x, y, 10, h * scale + 0.5); cairo_set_source_rgb (cr, 0, 0, 0); foo_scroll_area_add_input_from_fill (FOO_SCROLL_AREA (self->priv->area), cr, (FooScrollAreaEventFunc) on_top_bar_event, self); cairo_fill (cr); cairo_set_source_rgb (cr, 0.25, 0.25, 0.25); cairo_rectangle (cr, x + 1, y + 6, 8, 8); cairo_rectangle (cr, x + 1, y + 16, 8, 8); cairo_rectangle (cr, x + 1, y + 26, 8, 8); cairo_rectangle (cr, x + 1, y + 36, 8, 8); cairo_rectangle (cr, x + 1, y + h * scale + 0.5 - 10, 8, 8); cairo_fill (cr); } } if (gnome_rr_output_info_get_primary (output) && !is_unity_session ()) { const char *clock_format; char *text; gboolean use_24; GDateTime *dt; GDesktopClockFormat value; /* top bar */ cairo_rectangle (cr, x, y, w * scale + 0.5, TOP_BAR_HEIGHT); cairo_set_source_rgb (cr, 0, 0, 0); foo_scroll_area_add_input_from_fill (FOO_SCROLL_AREA (self->priv->area), cr, (FooScrollAreaEventFunc) on_top_bar_event, self); cairo_fill (cr); /* clock */ value = g_settings_get_enum (self->priv->clock_settings, CLOCK_FORMAT_KEY); use_24 = value == G_DESKTOP_CLOCK_FORMAT_24H; if (use_24) clock_format = _("%a %R"); else clock_format = _("%a %l:%M %p"); dt = g_date_time_new_now_local (); text = g_date_time_format (dt, clock_format); g_date_time_unref (dt); layout = gtk_widget_create_pango_layout (GTK_WIDGET (self->priv->area), text); g_free (text); pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER); layout_set_font (layout, "Sans 4"); pango_layout_get_pixel_extents (layout, &ink_extent, &log_extent); if (available_w < ink_extent.width) factor = available_w / ink_extent.width; else factor = 1.0; cairo_move_to (cr, x + ((w * scale + 0.5) - factor * log_extent.width) / 2, y + (TOP_BAR_HEIGHT - factor * log_extent.height) / 2); cairo_scale (cr, factor, factor); cairo_set_source_rgb (cr, 1.0, 1.0, 1.0); pango_cairo_show_layout (cr, layout); g_object_unref (layout); } cairo_restore (cr); } static void on_area_paint (FooScrollArea *area, cairo_t *cr, gpointer data) { CcDisplayPanel *self = data; GList *connected_outputs = NULL; GList *list; paint_background (area, cr); if (!self->priv->current_configuration) return; connected_outputs = list_connected_outputs (self, NULL, NULL); for (list = connected_outputs; list != NULL; list = list->next) { paint_output (self, cr, g_list_position (connected_outputs, list)); if (gnome_rr_config_get_clone (self->priv->current_configuration)) break; } } static void make_text_combo (GtkWidget *widget, int sort_column) { GtkComboBox *box = GTK_COMBO_BOX (widget); GtkListStore *store = gtk_list_store_new ( NUM_COLS, G_TYPE_STRING, /* Text */ G_TYPE_INT, /* Width */ G_TYPE_INT, /* Height */ G_TYPE_INT, /* Frequency */ G_TYPE_INT, /* Width * Height */ G_TYPE_INT); /* Rotation */ GtkCellRenderer *cell; gtk_cell_layout_clear (GTK_CELL_LAYOUT (widget)); gtk_combo_box_set_model (box, GTK_TREE_MODEL (store)); cell = gtk_cell_renderer_text_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (box), cell, TRUE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (box), cell, "text", 0, NULL); if (sort_column != -1) { gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (store), sort_column, GTK_SORT_DESCENDING); } } static void compute_virtual_size_for_configuration (GnomeRRConfig *config, int *ret_width, int *ret_height) { int i; int width, height; int output_x, output_y, output_width, output_height; GnomeRROutputInfo **outputs; width = height = 0; outputs = gnome_rr_config_get_outputs (config); for (i = 0; outputs[i] != NULL; i++) { if (gnome_rr_output_info_is_active (outputs[i])) { gnome_rr_output_info_get_geometry (outputs[i], &output_x, &output_y, &output_width, &output_height); width = MAX (width, output_x + output_width); height = MAX (height, output_y + output_height); } } *ret_width = width; *ret_height = height; } static void check_required_virtual_size (CcDisplayPanel *self) { int req_width, req_height; int min_width, max_width; int min_height, max_height; compute_virtual_size_for_configuration (self->priv->current_configuration, &req_width, &req_height); gnome_rr_screen_get_ranges (self->priv->screen, &min_width, &max_width, &min_height, &max_height); #if 0 g_debug ("X Server supports:"); g_debug ("min_width = %d, max_width = %d", min_width, max_width); g_debug ("min_height = %d, max_height = %d", min_height, max_height); g_debug ("Requesting size of %dx%d", req_width, req_height); #endif if (!(min_width <= req_width && req_width <= max_width && min_height <= req_height && req_height <= max_height)) { /* FIXME: present a useful dialog, maybe even before the user tries to Apply */ #if 0 g_debug ("Your X server needs a larger Virtual size!"); #endif } } static void begin_version2_apply_configuration (CcDisplayPanel *self, GdkWindow *parent_window, guint32 timestamp) { XID parent_window_xid; GError *error = NULL; parent_window_xid = GDK_WINDOW_XID (parent_window); self->priv->proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.cinnamon.SettingsDaemon", "/org/cinnamon/SettingsDaemon/XRANDR", "org.cinnamon.SettingsDaemon.XRANDR_2", NULL, &error); if (self->priv->proxy == NULL) { error_message (self, _("Failed to apply configuration: %s"), error->message); g_error_free (error); return; } g_dbus_proxy_call (self->priv->proxy, "ApplyConfiguration", g_variant_new ("(xx)", (gint64) parent_window_xid, (gint64) timestamp), G_DBUS_CALL_FLAGS_NONE, -1, NULL, apply_configuration_returned_cb, self); } static void ensure_current_configuration_is_saved (void) { GnomeRRScreen *rr_screen; GnomeRRConfig *rr_config; /* Normally, gnome_rr_config_save() creates a backup file based on the * old monitors.xml. However, if *that* file didn't exist, there is * nothing from which to create a backup. So, here we'll save the * current/unchanged configuration and then let our caller call * gnome_rr_config_save() again with the new/changed configuration, so * that there *will* be a backup file in the end. */ rr_screen = gnome_rr_screen_new (gdk_screen_get_default (), NULL); /* NULL-GError */ if (!rr_screen) return; rr_config = gnome_rr_config_new_current (rr_screen, NULL); gnome_rr_config_ensure_primary (rr_config); gnome_rr_config_save (rr_config, NULL); /* NULL-GError */ g_object_unref (rr_config); g_object_unref (rr_screen); } static void apply_configuration_returned_cb (GObject *proxy, GAsyncResult *res, gpointer data) { CcDisplayPanel *self = data; GVariant *result; GError *error = NULL; result = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, &error); if (error) error_message (self, _("Failed to apply configuration: %s"), error->message); g_clear_error (&error); if (result) g_variant_unref (result); g_object_unref (self->priv->proxy); self->priv->proxy = NULL; gtk_widget_set_sensitive (self->priv->panel, TRUE); } static gboolean sanitize_and_save_configuration (CcDisplayPanel *self) { GError *error; gnome_rr_config_sanitize (self->priv->current_configuration); gnome_rr_config_ensure_primary (self->priv->current_configuration); check_required_virtual_size (self); foo_scroll_area_invalidate (FOO_SCROLL_AREA (self->priv->area)); ensure_current_configuration_is_saved (); error = NULL; if (!gnome_rr_config_save (self->priv->current_configuration, &error)) { error_message (self, _("Could not save the monitor configuration"), error->message); g_error_free (error); return FALSE; } return TRUE; } static void apply (CcDisplayPanel *self) { GdkWindow *window; self->priv->apply_button_clicked_timestamp = gtk_get_current_event_time (); if (!sanitize_and_save_configuration (self)) return; g_assert (self->priv->proxy == NULL); gtk_widget_set_sensitive (self->priv->panel, FALSE); window = gtk_widget_get_window (gtk_widget_get_toplevel (self->priv->panel)); begin_version2_apply_configuration (self, window, self->priv->apply_button_clicked_timestamp); } #if 0 /* Returns whether the graphics driver doesn't advertise RANDR 1.2 features, and just 1.0 */ static gboolean driver_is_randr_10 (GnomeRRConfig *config) { /* In the Xorg code, see xserver/randr/rrinfo.c:RRScanOldConfig(). It gets * called when the graphics driver doesn't support RANDR 1.2 yet, just 1.0. * In that case, the X server's base code (which supports RANDR 1.2) will * simulate having a single output called "default". For drivers that *do* * support RANDR 1.2, the separate outputs will be named differently, we * hope. * * This heuristic is courtesy of Dirk Mueller <dmueller@suse.de> * * FIXME: however, we don't even check for XRRQueryVersion() returning 1.2, neither * here nor in gnome-desktop/libgnomedesktop*.c. Do we need to check for that, * or is gnome_rr_screen_new()'s return value sufficient? */ return (count_all_outputs (config) == 1 && strcmp (gnome_rr_output_info_get_name (gnome_rr_config_get_outputs (config)[0]), "default") == 0); } #endif static void on_detect_displays (GtkWidget *widget, gpointer data) { CcDisplayPanel *self = data; GError *error; error = NULL; if (!gnome_rr_screen_refresh (self->priv->screen, &error)) { if (error) { error_message (self, _("Could not detect displays"), error->message); g_error_free (error); } } } static GnomeRROutputInfo * get_nearest_output (GnomeRRConfig *configuration, int x, int y) { int i; int nearest_index; int nearest_dist; GnomeRROutputInfo **outputs; nearest_index = -1; nearest_dist = G_MAXINT; outputs = gnome_rr_config_get_outputs (configuration); for (i = 0; outputs[i] != NULL; i++) { int dist_x, dist_y; int output_x, output_y, output_width, output_height; if (!(gnome_rr_output_info_is_connected (outputs[i]) && gnome_rr_output_info_is_active (outputs[i]))) continue; gnome_rr_output_info_get_geometry (outputs[i], &output_x, &output_y, &output_width, &output_height); if (x < output_x) dist_x = output_x - x; else if (x >= output_x + output_width) dist_x = x - (output_x + output_width) + 1; else dist_x = 0; if (y < output_y) dist_y = output_y - y; else if (y >= output_y + output_height) dist_y = y - (output_y + output_height) + 1; else dist_y = 0; if (MIN (dist_x, dist_y) < nearest_dist) { nearest_dist = MIN (dist_x, dist_y); nearest_index = i; } } if (nearest_index != -1) return outputs[nearest_index]; else return NULL; } /* Gets the output that contains the largest intersection with the window. * Logic stolen from gdk_screen_get_monitor_at_window(). */ static GnomeRROutputInfo * get_output_for_window (GnomeRRConfig *configuration, GdkWindow *window) { GdkRectangle win_rect; int i; int largest_area; int largest_index; GnomeRROutputInfo **outputs; gdk_window_get_geometry (window, &win_rect.x, &win_rect.y, &win_rect.width, &win_rect.height); gdk_window_get_origin (window, &win_rect.x, &win_rect.y); largest_area = 0; largest_index = -1; outputs = gnome_rr_config_get_outputs (configuration); for (i = 0; outputs[i] != NULL; i++) { GdkRectangle output_rect, intersection; gnome_rr_output_info_get_geometry (outputs[i], &output_rect.x, &output_rect.y, &output_rect.width, &output_rect.height); if (gnome_rr_output_info_is_connected (outputs[i]) && gdk_rectangle_intersect (&win_rect, &output_rect, &intersection)) { int area; area = intersection.width * intersection.height; if (area > largest_area) { largest_area = area; largest_index = i; } } } if (largest_index != -1) return outputs[largest_index]; else return get_nearest_output (configuration, win_rect.x + win_rect.width / 2, win_rect.y + win_rect.height / 2); } static void dialog_toplevel_focus_changed (GtkWindow *window, GParamSpec *pspec, CcDisplayPanel *self) { if (self->priv->labeler == NULL) return; if (gtk_window_has_toplevel_focus (window)) cc_rr_labeler_show (self->priv->labeler); else cc_rr_labeler_hide (self->priv->labeler); } static void widget_visible_changed (GtkWidget *widget, gpointer user_data) { if (CC_DISPLAY_PANEL(widget)->priv->labeler == NULL) return; if (gtk_widget_get_visible (widget)) { cc_rr_labeler_show (CC_DISPLAY_PANEL (widget)->priv->labeler); } else { cc_rr_labeler_hide (CC_DISPLAY_PANEL (widget)->priv->labeler); } } static void on_toplevel_realized (GtkWidget *widget, CcDisplayPanel *self) { self->priv->current_output = get_output_for_window (self->priv->current_configuration, gtk_widget_get_window (widget)); rebuild_gui (self); } /* We select the current output, i.e. select the one being edited, based on * which output is showing the configuration dialog. */ static void select_current_output_from_dialog_position (CcDisplayPanel *self) { GtkWidget *toplevel; toplevel = gtk_widget_get_toplevel (self->priv->panel); if (gtk_widget_get_realized (toplevel)) { self->priv->current_output = get_output_for_window (self->priv->current_configuration, gtk_widget_get_window (toplevel)); rebuild_gui (self); } else { g_signal_connect (toplevel, "realize", G_CALLBACK (on_toplevel_realized), self); self->priv->current_output = NULL; } } /* This is a GtkWidget::map-event handler. We wait for the display-properties * dialog to be mapped, and then we select the output which corresponds to the * monitor on which the dialog is being shown. */ static gboolean dialog_map_event_cb (GtkWidget *widget, GdkEventAny *event, gpointer data) { CcDisplayPanel *self = data; select_current_output_from_dialog_position (self); return FALSE; } static void stickyedge_widget_refresh (GtkSwitch *switcher, GSettings *settings) { gboolean stickyedge_enabled = g_settings_get_boolean (settings, UNITY_STICKY_EDGE_KEY); gtk_switch_set_active (switcher, stickyedge_enabled); } static void ext_stickyedge_changed_callback (GSettings* settings, guint key, gpointer user_data) { stickyedge_widget_refresh (GTK_SWITCH (user_data), settings); } static void on_stickyedge_changed (GtkSwitch *switcher, GParamSpec *pspec, gpointer user_data) { CcDisplayPanel *self = CC_DISPLAY_PANEL (user_data); gboolean enabled = gtk_switch_get_active (GTK_SWITCH (switcher)); /* 3d */ g_settings_set_boolean (self->priv->unity_settings, UNITY_STICKY_EDGE_KEY, enabled); /* 2d */ if (self->priv->unity2d_settings_main) g_settings_set_boolean (self->priv->unity2d_settings_main, "sticky-edges", enabled); } static gboolean unity_launcher_on_all_monitors (GSettings *settings) { gint value = g_settings_get_int (settings, UNITY_LAUNCHER_ALL_MONITORS_KEY); return (value == 0); } static GdkPixbuf* get_monitor_pixbuf (CcDisplayPanel *self, GnomeRROutputInfo *output) { GdkColor color; cairo_surface_t *cairo_surface; cairo_t *cr; int monitor_width = 30; int monitor_height = 15; gdk_color_parse ("#FFAAAA", &color); cairo_surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, monitor_width, monitor_height); cr = cairo_create (cairo_surface); cairo_surface_destroy (cairo_surface); cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR); cairo_paint (cr); cairo_set_operator (cr, CAIRO_OPERATOR_OVER); cairo_set_source_rgb (cr, color.red / 65535.0, color.green / 65535.0, color.blue / 65535.0); cairo_rectangle (cr, 0.5, 0.5, monitor_width - 1, monitor_height - 1); cairo_fill (cr); cairo_set_line_width (cr, 1); cairo_set_source_rgba (cr, 0, 0, 0, 1.0); cairo_rectangle (cr, 0.5, 0.5, monitor_width - 1, monitor_height - 1); cairo_stroke (cr); return gdk_pixbuf_get_from_surface (cairo_get_target (cr), 0, 0, monitor_width, monitor_height); } static void refresh_unity_launcher_placement (CcDisplayPanel *self) { GtkWidget *launcher_placement_combo = WID ("launcher_placement_combo"); GtkListStore *liststore; GtkTreeIter iter; GList *connected_outputs = NULL; GList *list; gboolean launcher_on_all_monitors = FALSE; //unity_launcher_on_all_monitors (self->priv->unity_settings); gint index_of_primary_screen = 0; gint i; liststore = (GtkListStore *) gtk_builder_get_object (self->priv->builder, "available_launcher_placement_store"); gtk_list_store_clear (liststore); connected_outputs = list_connected_outputs (self, NULL, NULL); for (list = connected_outputs, i = 0; list != NULL; list = list->next) { char *monitor_name; GdkPixbuf *monitor_pixbuf; GnomeRROutputInfo *output = list->data; if (!gnome_rr_output_info_is_active (output)) continue; gtk_list_store_append (liststore, &iter); monitor_name = g_strdup (gnome_rr_output_info_get_display_name (output)); monitor_pixbuf = get_monitor_pixbuf (self, output); gtk_list_store_set (liststore, &iter, 0, monitor_pixbuf, 1, monitor_name, -1); /* select it if primary and only one launcher */ if (gnome_rr_output_info_get_primary (output) && (!launcher_on_all_monitors)) index_of_primary_screen = i; i++; g_object_unref (monitor_pixbuf); g_free (monitor_name); } // FIXME: check autosort? gtk_list_store_append (liststore, &iter); gtk_list_store_set (liststore, &iter, 0, NULL, 1, _("All displays"), -1); if (launcher_on_all_monitors) index_of_primary_screen = i; gtk_combo_box_set_active (GTK_COMBO_BOX (launcher_placement_combo), index_of_primary_screen); } static gboolean switcher_set_to_launcher_on_all_monitors (CcDisplayPanel *self) { GtkComboBox *combo = GTK_COMBO_BOX (WID ("launcher_placement_combo")); gint active = gtk_combo_box_get_active (combo); gint number_items = gtk_tree_model_iter_n_children (gtk_combo_box_get_model (combo), NULL); return (active == number_items - 1); } static void ext_launcher_placement_changed_callback (GSettings* settings, guint key, gpointer user_data) { // add some crazyness as 2d/3d are not using the same keys CcDisplayPanel *self = CC_DISPLAY_PANEL (user_data); gint launcher_unity_value = 0; // two options support: all monitors (0)i or just primary desktop (hence set to 1, not any other number) if (! switcher_set_to_launcher_on_all_monitors (self)) launcher_unity_value = 1; if (g_settings_get_int (settings, UNITY_LAUNCHER_ALL_MONITORS_KEY) != launcher_unity_value) refresh_unity_launcher_placement (self); } static void on_launcher_placement_combo_changed (GtkComboBox *combo, CcDisplayPanel *self) { gint active = gtk_combo_box_get_active (combo); gint i; gint index_on_combo = 0; if (active < 0) return; gint value = 0; gboolean on_all_monitors = switcher_set_to_launcher_on_all_monitors (self); if (!on_all_monitors) { value = 1; // set the primary output if needed GnomeRROutputInfo **outputs = gnome_rr_config_get_outputs (self->priv->current_configuration); for (i = 0; outputs[i] != NULL; ++i) { GnomeRROutputInfo *output = outputs[i]; if (!gnome_rr_output_info_is_active (output)) continue; if ((active == index_on_combo) && !gnome_rr_output_info_get_primary (output)) { set_primary_output (self, output); break; } index_on_combo++; } } /* 3d */ if (self->priv->unity_settings) g_settings_set_int (self->priv->unity_settings, UNITY_LAUNCHER_ALL_MONITORS_KEY, value); /* 2d */ if (self->priv->unity2d_settings_launcher) g_settings_set_boolean (self->priv->unity2d_settings_launcher, "only-one-launcher", !on_all_monitors); } static void setup_unity_settings (CcDisplayPanel *self) { const gchar * const *schemas; /* Only use the unity-2d schema if it's installed */ schemas = g_settings_list_schemas (); while (*schemas != NULL) { if (g_strcmp0 (*schemas, UNITY2D_GSETTINGS_LAUNCHER) == 0) { self->priv->unity2d_settings_main = g_settings_new (UNITY2D_GSETTINGS_MAIN); self->priv->unity2d_settings_launcher = g_settings_new (UNITY2D_GSETTINGS_LAUNCHER); break; } schemas++; } schemas = g_settings_list_relocatable_schemas (); while (*schemas != NULL) { if (g_strcmp0 (*schemas, UNITY_GSETTINGS_SCHEMA) == 0) { self->priv->unity_settings = g_settings_new_with_path (UNITY_GSETTINGS_SCHEMA, UNITY_GSETTINGS_PATH); break; } schemas++; } if (!self->priv->unity_settings) return; GtkWidget *sticky_edge_switch = WID ("stickyedge_switch"); g_signal_connect (sticky_edge_switch, "notify::active", G_CALLBACK (on_stickyedge_changed), self); g_signal_connect (self->priv->unity_settings, "changed::" UNITY_STICKY_EDGE_KEY, G_CALLBACK (ext_stickyedge_changed_callback), sticky_edge_switch); stickyedge_widget_refresh (GTK_SWITCH (sticky_edge_switch), self->priv->unity_settings); g_signal_connect (G_OBJECT (WID ("launcher_placement_combo")), "changed", G_CALLBACK (on_launcher_placement_combo_changed), self); g_signal_connect (self->priv->unity_settings, "changed::" UNITY_LAUNCHER_ALL_MONITORS_KEY, G_CALLBACK (ext_launcher_placement_changed_callback), self); } static void cc_display_panel_init (CcDisplayPanel *self) { } static GObject * cc_display_panel_constructor (GType gtype, guint n_properties, GObjectConstructParam *properties) { GtkBuilder *builder; GtkWidget *align; GError *error; GObject *obj; CcDisplayPanel *self; CcShell *shell; GtkWidget *toplevel; gchar *objects[] = {"display-panel", "available_launcher_placement_store", NULL}; obj = G_OBJECT_CLASS (cc_display_panel_parent_class)->constructor (gtype, n_properties, properties); self = CC_DISPLAY_PANEL (obj); self->priv = DISPLAY_PANEL_PRIVATE (self); error = NULL; self->priv->builder = builder = gtk_builder_new (); gtk_builder_set_translation_domain (self->priv->builder, GETTEXT_PACKAGE); if (!gtk_builder_add_objects_from_file (builder, UIDIR "/display-capplet.ui", objects, &error)) { g_warning ("Could not parse UI definition: %s", error->message); g_error_free (error); g_object_unref (builder); return obj; } self->priv->screen = gnome_rr_screen_new (gdk_screen_get_default (), &error); g_signal_connect (self->priv->screen, "changed", G_CALLBACK (on_screen_changed), self); if (!self->priv->screen) { error_message (NULL, _("Could not get screen information"), error->message); g_error_free (error); g_object_unref (builder); return obj; } self->priv->clock_settings = g_settings_new (CLOCK_SCHEMA); shell = cc_panel_get_shell (CC_PANEL (self)); if (shell != NULL) { toplevel = cc_shell_get_toplevel (shell); self->priv->focus_id = g_signal_connect (toplevel, "notify::has-toplevel-focus", G_CALLBACK (dialog_toplevel_focus_changed), self); } else { self->priv->focus_id = g_signal_connect (GTK_WIDGET (self), "show", G_CALLBACK (widget_visible_changed), NULL); self->priv->focus_id_hide = g_signal_connect (GTK_WIDGET (self), "hide", G_CALLBACK (widget_visible_changed), NULL); } self->priv->panel = WID ("display-panel"); g_signal_connect_after (self->priv->panel, "show", G_CALLBACK (dialog_map_event_cb), self); self->priv->current_monitor_event_box = WID ("current_monitor_event_box"); self->priv->current_monitor_label = WID ("current_monitor_label"); self->priv->monitor_switch = WID ("monitor_switch"); g_signal_connect (self->priv->monitor_switch, "notify::active", G_CALLBACK (monitor_switch_active_cb), self); self->priv->resolution_combo = WID ("resolution_combo"); g_signal_connect (self->priv->resolution_combo, "changed", G_CALLBACK (on_resolution_changed), self); self->priv->rotation_combo = WID ("rotation_combo"); g_signal_connect (self->priv->rotation_combo, "changed", G_CALLBACK (on_rotation_changed), self); self->priv->clone_checkbox = WID ("clone_checkbox"); g_signal_connect (self->priv->clone_checkbox, "toggled", G_CALLBACK (on_clone_changed), self); self->priv->clone_label = WID ("clone_resolution_warning_label"); g_signal_connect (WID ("detect_displays_button"), "clicked", G_CALLBACK (on_detect_displays), self); make_text_combo (self->priv->resolution_combo, 4); make_text_combo (self->priv->rotation_combo, -1); /* Scroll Area */ self->priv->area = (GtkWidget *)foo_scroll_area_new (); g_object_set_data (G_OBJECT (self->priv->area), "panel", self); set_monitors_tooltip (self, FALSE); /* FIXME: this should be computed dynamically */ foo_scroll_area_set_min_size (FOO_SCROLL_AREA (self->priv->area), 0, 200); gtk_widget_show (self->priv->area); g_signal_connect (self->priv->area, "paint", G_CALLBACK (on_area_paint), self); g_signal_connect (self->priv->area, "viewport_changed", G_CALLBACK (on_viewport_changed), self); align = WID ("align"); gtk_container_add (GTK_CONTAINER (align), self->priv->area); on_screen_changed (self->priv->screen, self); g_signal_connect_swapped (WID ("apply_button"), "clicked", G_CALLBACK (apply), self); /* Unity settings */ if (is_unity_session ()) setup_unity_settings (self); else { gtk_widget_hide (WID ("unity_launcher_placement_sep")); gtk_widget_hide (WID ("launcher_placement_label")); gtk_widget_hide (WID ("sticky_edge_label")); gtk_widget_hide (WID ("launcher_placement_combo")); gtk_widget_hide (WID ("stickyedge_switch")); } gtk_widget_show (self->priv->panel); gtk_container_add (GTK_CONTAINER (self), self->priv->panel); return obj; } void cc_display_panel_register (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); cc_display_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_DISPLAY_PANEL, "display", 0); }
459
./cinnamon-control-center/panels/display/display-module.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Thomas Wood <thomas.wood@intel.com> * */ #include <config.h> #include "cc-display-panel.h" #include <glib/gi18n-lib.h> void g_io_module_load (GIOModule *module) { /* register the panel */ cc_display_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
460
./cinnamon-control-center/panels/display/scrollarea.c
/* Copyright 2006, 2007, 2008, Soren Sandmann <sandmann@daimi.au.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "scrollarea.h" #include <gdk/gdk.h> #include "foo-marshal.h" G_DEFINE_TYPE_WITH_CODE (FooScrollArea, foo_scroll_area, GTK_TYPE_CONTAINER, G_IMPLEMENT_INTERFACE (GTK_TYPE_SCROLLABLE, NULL)); static GtkWidgetClass *parent_class; typedef struct BackingStore BackingStore; typedef struct InputPath InputPath; typedef struct InputRegion InputRegion; typedef struct AutoScrollInfo AutoScrollInfo; struct InputPath { gboolean is_stroke; cairo_fill_rule_t fill_rule; double line_width; cairo_path_t *path; /* In canvas coordinates */ FooScrollAreaEventFunc func; gpointer data; InputPath *next; }; /* InputRegions are mutually disjoint */ struct InputRegion { /* the boundary of this area in canvas coordinates */ cairo_region_t *region; InputPath *paths; }; struct AutoScrollInfo { int dx; int dy; int timeout_id; int begin_x; int begin_y; double res_x; double res_y; GTimer *timer; }; struct FooScrollAreaPrivate { GdkWindow *input_window; int width; int height; GtkAdjustment *hadj; GtkAdjustment *vadj; GtkScrollablePolicy hscroll_policy; GtkScrollablePolicy vscroll_policy; int x_offset; int y_offset; int min_width; int min_height; GPtrArray *input_regions; AutoScrollInfo *auto_scroll_info; /* During expose, this region is set to the region * being exposed. At other times, it is NULL * * It is used for clipping of input areas */ InputRegion *current_input; gboolean grabbed; FooScrollAreaEventFunc grab_func; gpointer grab_data; cairo_surface_t *surface; cairo_region_t *update_region; /* In canvas coordinates */ }; enum { VIEWPORT_CHANGED, PAINT, INPUT, LAST_SIGNAL, }; enum { PROP_0, PROP_VADJUSTMENT, PROP_HADJUSTMENT, PROP_HSCROLL_POLICY, PROP_VSCROLL_POLICY }; static guint signals [LAST_SIGNAL] = { 0 }; static gboolean foo_scroll_area_draw (GtkWidget *widget, cairo_t *cr); static void foo_scroll_area_get_preferred_width (GtkWidget *widget, gint *minimum, gint *natural); static void foo_scroll_area_get_preferred_height (GtkWidget *widget, gint *minimum, gint *natural); static void foo_scroll_area_size_allocate (GtkWidget *widget, GtkAllocation *allocation); static void foo_scroll_area_set_hadjustment (FooScrollArea *scroll_area, GtkAdjustment *hadjustment); static void foo_scroll_area_set_vadjustment (FooScrollArea *scroll_area, GtkAdjustment *vadjustment); static void foo_scroll_area_realize (GtkWidget *widget); static void foo_scroll_area_unrealize (GtkWidget *widget); static void foo_scroll_area_map (GtkWidget *widget); static void foo_scroll_area_unmap (GtkWidget *widget); static gboolean foo_scroll_area_button_press (GtkWidget *widget, GdkEventButton *event); static gboolean foo_scroll_area_button_release (GtkWidget *widget, GdkEventButton *event); static gboolean foo_scroll_area_motion (GtkWidget *widget, GdkEventMotion *event); static void foo_scroll_area_map (GtkWidget *widget) { FooScrollArea *area = FOO_SCROLL_AREA (widget); GTK_WIDGET_CLASS (parent_class)->map (widget); if (area->priv->input_window) gdk_window_show (area->priv->input_window); } static void foo_scroll_area_unmap (GtkWidget *widget) { FooScrollArea *area = FOO_SCROLL_AREA (widget); if (area->priv->input_window) gdk_window_hide (area->priv->input_window); GTK_WIDGET_CLASS (parent_class)->unmap (widget); } static void foo_scroll_area_finalize (GObject *object) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (object); g_object_unref (scroll_area->priv->hadj); g_object_unref (scroll_area->priv->vadj); g_ptr_array_free (scroll_area->priv->input_regions, TRUE); g_free (scroll_area->priv); G_OBJECT_CLASS (foo_scroll_area_parent_class)->finalize (object); } static void foo_scroll_area_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (object); switch (property_id) { case PROP_VADJUSTMENT: g_value_set_object (value, &scroll_area->priv->vadj); break; case PROP_HADJUSTMENT: g_value_set_object (value, &scroll_area->priv->hadj); break; case PROP_HSCROLL_POLICY: g_value_set_enum (value, scroll_area->priv->hscroll_policy); break; case PROP_VSCROLL_POLICY: g_value_set_enum (value, scroll_area->priv->vscroll_policy); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void foo_scroll_area_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (object); switch (property_id) { case PROP_VADJUSTMENT: foo_scroll_area_set_vadjustment (FOO_SCROLL_AREA (object), g_value_get_object (value)); break; case PROP_HADJUSTMENT: foo_scroll_area_set_hadjustment (FOO_SCROLL_AREA (object), g_value_get_object (value)); break; case PROP_HSCROLL_POLICY: scroll_area->priv->hscroll_policy = g_value_get_enum (value); break; case PROP_VSCROLL_POLICY: scroll_area->priv->vscroll_policy = g_value_get_enum (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void foo_scroll_area_class_init (FooScrollAreaClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class); object_class->finalize = foo_scroll_area_finalize; object_class->set_property = foo_scroll_area_set_property; object_class->get_property = foo_scroll_area_get_property; widget_class->get_preferred_width = foo_scroll_area_get_preferred_width; widget_class->get_preferred_height = foo_scroll_area_get_preferred_height; widget_class->draw = foo_scroll_area_draw; widget_class->size_allocate = foo_scroll_area_size_allocate; widget_class->realize = foo_scroll_area_realize; widget_class->unrealize = foo_scroll_area_unrealize; widget_class->button_press_event = foo_scroll_area_button_press; widget_class->button_release_event = foo_scroll_area_button_release; widget_class->motion_notify_event = foo_scroll_area_motion; widget_class->map = foo_scroll_area_map; widget_class->unmap = foo_scroll_area_unmap; parent_class = g_type_class_peek_parent (class); /* Scrollable interface properties */ g_object_class_override_property (object_class, PROP_HADJUSTMENT, "hadjustment"); g_object_class_override_property (object_class, PROP_VADJUSTMENT, "vadjustment"); g_object_class_override_property (object_class, PROP_HSCROLL_POLICY, "hscroll-policy"); g_object_class_override_property (object_class, PROP_VSCROLL_POLICY, "vscroll-policy"); signals[VIEWPORT_CHANGED] = g_signal_new ("viewport_changed", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (FooScrollAreaClass, viewport_changed), NULL, NULL, foo_marshal_VOID__BOXED_BOXED, G_TYPE_NONE, 2, GDK_TYPE_RECTANGLE, GDK_TYPE_RECTANGLE); signals[PAINT] = g_signal_new ("paint", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (FooScrollAreaClass, paint), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); } static GtkAdjustment * new_adjustment (void) { return GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); } static void foo_scroll_area_init (FooScrollArea *scroll_area) { GtkWidget *widget; widget = GTK_WIDGET (scroll_area); gtk_widget_set_has_window (widget, FALSE); gtk_widget_set_redraw_on_allocate (widget, FALSE); scroll_area->priv = g_new0 (FooScrollAreaPrivate, 1); scroll_area->priv->width = 0; scroll_area->priv->height = 0; scroll_area->priv->hadj = g_object_ref_sink (new_adjustment()); scroll_area->priv->vadj = g_object_ref_sink (new_adjustment()); scroll_area->priv->x_offset = 0.0; scroll_area->priv->y_offset = 0.0; scroll_area->priv->min_width = 0; scroll_area->priv->min_height = 0; scroll_area->priv->auto_scroll_info = NULL; scroll_area->priv->input_regions = g_ptr_array_new (); scroll_area->priv->surface = NULL; scroll_area->priv->update_region = cairo_region_create (); } typedef void (* PathForeachFunc) (double *x, double *y, gpointer data); static void path_foreach_point (cairo_path_t *path, PathForeachFunc func, gpointer user_data) { int i; for (i = 0; i < path->num_data; i += path->data[i].header.length) { cairo_path_data_t *data = &(path->data[i]); switch (data->header.type) { case CAIRO_PATH_MOVE_TO: case CAIRO_PATH_LINE_TO: func (&(data[1].point.x), &(data[1].point.y), user_data); break; case CAIRO_PATH_CURVE_TO: func (&(data[1].point.x), &(data[1].point.y), user_data); func (&(data[2].point.x), &(data[2].point.y), user_data); func (&(data[3].point.x), &(data[3].point.y), user_data); break; case CAIRO_PATH_CLOSE_PATH: break; } } } typedef struct { double x1, y1, x2, y2; } Box; static void input_path_free_list (InputPath *paths) { if (!paths) return; input_path_free_list (paths->next); cairo_path_destroy (paths->path); g_free (paths); } static void input_region_free (InputRegion *region) { input_path_free_list (region->paths); cairo_region_destroy (region->region); g_free (region); } static void get_viewport (FooScrollArea *scroll_area, GdkRectangle *viewport) { GtkAllocation allocation; GtkWidget *widget = GTK_WIDGET (scroll_area); gtk_widget_get_allocation (widget, &allocation); viewport->x = scroll_area->priv->x_offset; viewport->y = scroll_area->priv->y_offset; viewport->width = allocation.width; viewport->height = allocation.height; } static void allocation_to_canvas (FooScrollArea *area, int *x, int *y) { *x += area->priv->x_offset; *y += area->priv->y_offset; } static void clear_exposed_input_region (FooScrollArea *area, cairo_region_t *exposed) /* in canvas coordinates */ { int i; cairo_region_t *viewport; GdkRectangle allocation; gtk_widget_get_allocation (GTK_WIDGET (area), &allocation); allocation.x = 0; allocation.y = 0; allocation_to_canvas (area, &allocation.x, &allocation.y); viewport = cairo_region_create_rectangle (&allocation); cairo_region_subtract (viewport, exposed); for (i = 0; i < area->priv->input_regions->len; ++i) { InputRegion *region = area->priv->input_regions->pdata[i]; cairo_region_intersect (region->region, viewport); if (cairo_region_is_empty (region->region)) { input_region_free (region); g_ptr_array_remove_index_fast (area->priv->input_regions, i--); } } cairo_region_destroy (viewport); } /* taken from mutter */ static void setup_background_cr (GdkWindow *window, cairo_t *cr, int x_offset, int y_offset) { GdkWindow *parent = gdk_window_get_parent (window); cairo_pattern_t *bg_pattern; bg_pattern = gdk_window_get_background_pattern (window); if (bg_pattern == NULL && parent) { gint window_x, window_y; gdk_window_get_position (window, &window_x, &window_y); setup_background_cr (parent, cr, x_offset + window_x, y_offset + window_y); } else if (bg_pattern) { cairo_translate (cr, - x_offset, - y_offset); cairo_set_source (cr, bg_pattern); cairo_translate (cr, x_offset, y_offset); } } static void initialize_background (GtkWidget *widget, cairo_t *cr) { setup_background_cr (gtk_widget_get_window (widget), cr, 0, 0); cairo_paint (cr); } static gboolean foo_scroll_area_draw (GtkWidget *widget, cairo_t *cr) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (widget); cairo_region_t *region; GtkAllocation widget_allocation; /* Note that this function can be called at a time * where the adj->value is different from x_offset. * Ie., the GtkScrolledWindow changed the adj->value * without emitting the value_changed signal. * * Hence we must always use the value we got * the last time the signal was emitted, ie., * priv->{x,y}_offset. */ /* Setup input areas */ clear_exposed_input_region (scroll_area, scroll_area->priv->update_region); scroll_area->priv->current_input = g_new0 (InputRegion, 1); scroll_area->priv->current_input->region = cairo_region_copy (scroll_area->priv->update_region); scroll_area->priv->current_input->paths = NULL; g_ptr_array_add (scroll_area->priv->input_regions, scroll_area->priv->current_input); region = scroll_area->priv->update_region; scroll_area->priv->update_region = cairo_region_create (); initialize_background (widget, cr); g_signal_emit (widget, signals[PAINT], 0, cr); scroll_area->priv->current_input = NULL; gtk_widget_get_allocation (widget, &widget_allocation); /* Finally draw the backing surface */ cairo_set_source_surface (cr, scroll_area->priv->surface, widget_allocation.x, widget_allocation.y); cairo_fill (cr); cairo_region_destroy (region); return TRUE; } void foo_scroll_area_get_viewport (FooScrollArea *scroll_area, GdkRectangle *viewport) { g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); if (!viewport) return; get_viewport (scroll_area, viewport); } static void process_event (FooScrollArea *scroll_area, FooScrollAreaEventType input_type, int x, int y); static void emit_viewport_changed (FooScrollArea *scroll_area, GdkRectangle *new_viewport, GdkRectangle *old_viewport) { int px, py; g_signal_emit (scroll_area, signals[VIEWPORT_CHANGED], 0, new_viewport, old_viewport); if (scroll_area->priv->input_window == NULL) return; gdk_window_get_pointer (scroll_area->priv->input_window, &px, &py, NULL); #if 0 g_print ("procc\n"); #endif process_event (scroll_area, FOO_MOTION, px, py); } static void clamp_adjustment (GtkAdjustment *adj) { if (gtk_adjustment_get_upper (adj) >= gtk_adjustment_get_page_size (adj)) gtk_adjustment_set_value (adj, CLAMP (gtk_adjustment_get_value (adj), 0.0, gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj))); else gtk_adjustment_set_value (adj, 0.0); gtk_adjustment_changed (adj); } static gboolean set_adjustment_values (FooScrollArea *scroll_area) { GtkAllocation allocation; GtkAdjustment *hadj = scroll_area->priv->hadj; GtkAdjustment *vadj = scroll_area->priv->vadj; /* Horizontal */ gtk_widget_get_allocation (GTK_WIDGET (scroll_area), &allocation); g_object_freeze_notify (G_OBJECT (hadj)); gtk_adjustment_set_page_size (hadj, allocation.width); gtk_adjustment_set_step_increment (hadj, 0.1 * allocation.width); gtk_adjustment_set_page_increment (hadj, 0.9 * allocation.width); gtk_adjustment_set_lower (hadj, 0.0); gtk_adjustment_set_upper (hadj, scroll_area->priv->width); g_object_thaw_notify (G_OBJECT (hadj)); /* Vertical */ g_object_freeze_notify (G_OBJECT (vadj)); gtk_adjustment_set_page_size (vadj, allocation.height); gtk_adjustment_set_step_increment (vadj, 0.1 * allocation.height); gtk_adjustment_set_page_increment (vadj, 0.9 * allocation.height); gtk_adjustment_set_lower (vadj, 0.0); gtk_adjustment_set_upper (vadj, scroll_area->priv->height); g_object_thaw_notify (G_OBJECT (vadj)); clamp_adjustment (hadj); clamp_adjustment (vadj); return TRUE; } static void foo_scroll_area_realize (GtkWidget *widget) { FooScrollArea *area = FOO_SCROLL_AREA (widget); GdkWindowAttr attributes; GtkAllocation widget_allocation; GdkWindow *window; gint attributes_mask; cairo_t *cr; gtk_widget_get_allocation (widget, &widget_allocation); gtk_widget_set_realized (widget, TRUE); attributes.window_type = GDK_WINDOW_CHILD; attributes.x = widget_allocation.x; attributes.y = widget_allocation.y; attributes.width = widget_allocation.width; attributes.height = widget_allocation.height; attributes.wclass = GDK_INPUT_ONLY; attributes.event_mask = gtk_widget_get_events (widget); attributes.event_mask |= (GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON1_MOTION_MASK | GDK_BUTTON2_MOTION_MASK | GDK_BUTTON3_MOTION_MASK | GDK_POINTER_MOTION_MASK | GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK); attributes_mask = GDK_WA_X | GDK_WA_Y; window = gtk_widget_get_parent_window (widget); gtk_widget_set_window (widget, window); g_object_ref (window); area->priv->input_window = gdk_window_new (window, &attributes, attributes_mask); cr = gdk_cairo_create (gtk_widget_get_window (widget)); area->priv->surface = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, widget_allocation.width, widget_allocation.height); cairo_destroy (cr); gdk_window_set_user_data (area->priv->input_window, area); } static void foo_scroll_area_unrealize (GtkWidget *widget) { FooScrollArea *area = FOO_SCROLL_AREA (widget); if (area->priv->input_window) { gdk_window_set_user_data (area->priv->input_window, NULL); gdk_window_destroy (area->priv->input_window); area->priv->input_window = NULL; } GTK_WIDGET_CLASS (parent_class)->unrealize (widget); } static cairo_surface_t * create_new_surface (GtkWidget *widget, cairo_surface_t *old) { GtkAllocation widget_allocation; cairo_surface_t *new; cairo_t *cr; gtk_widget_get_allocation (widget, &widget_allocation); cr = gdk_cairo_create (gtk_widget_get_window (widget)); new = cairo_surface_create_similar (cairo_get_target (cr), CAIRO_CONTENT_COLOR, widget_allocation.width, widget_allocation.height); cairo_destroy (cr); /* Unfortunately we don't know in which direction we were resized, * so we just assume we were dragged from the south-east corner. * * Although, maybe we could get the root coordinates of the input-window? * That might just work, actually. We need to make sure metacity uses * static gravity for the window before this will be useful. */ cr = cairo_create (new); cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE); cairo_set_source_surface (cr, old, 0, 0); cairo_paint (cr); cairo_destroy (cr); return new; } static void allocation_to_canvas_region (FooScrollArea *area, cairo_region_t *region) { cairo_region_translate (region, area->priv->x_offset, area->priv->y_offset); } static void _cairo_region_xor (cairo_region_t *dst, const cairo_region_t *src) { cairo_region_t *trb; trb = cairo_region_copy (src); cairo_region_subtract (trb, dst); cairo_region_subtract (dst, src); cairo_region_union (dst, trb); cairo_region_destroy (trb); } static void foo_scroll_area_size_allocate (GtkWidget *widget, GtkAllocation *allocation) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (widget); GdkRectangle new_viewport; GdkRectangle old_viewport; cairo_region_t *old_allocation; cairo_region_t *invalid; GtkAllocation widget_allocation; get_viewport (scroll_area, &old_viewport); gtk_widget_get_allocation (widget, &widget_allocation); old_allocation = cairo_region_create_rectangle (&widget_allocation); cairo_region_translate (old_allocation, -widget_allocation.x, -widget_allocation.y); invalid = cairo_region_create_rectangle (allocation); cairo_region_translate (invalid, -allocation->x, -allocation->y); _cairo_region_xor (invalid, old_allocation); allocation_to_canvas_region (scroll_area, invalid); foo_scroll_area_invalidate_region (scroll_area, invalid); cairo_region_destroy (old_allocation); cairo_region_destroy (invalid); gtk_widget_set_allocation (widget, allocation); if (scroll_area->priv->input_window) { cairo_surface_t *new_surface; gdk_window_move_resize (scroll_area->priv->input_window, allocation->x, allocation->y, allocation->width, allocation->height); new_surface = create_new_surface (widget, scroll_area->priv->surface); cairo_surface_destroy (scroll_area->priv->surface); scroll_area->priv->surface = new_surface; } get_viewport (scroll_area, &new_viewport); emit_viewport_changed (scroll_area, &new_viewport, &old_viewport); } static void emit_input (FooScrollArea *scroll_area, FooScrollAreaEventType type, int x, int y, FooScrollAreaEventFunc func, gpointer data) { FooScrollAreaEvent event; if (!func) return; event.type = type; event.x = x; event.y = y; func (scroll_area, &event, data); } static void process_event (FooScrollArea *scroll_area, FooScrollAreaEventType input_type, int x, int y) { GtkWidget *widget = GTK_WIDGET (scroll_area); int i; allocation_to_canvas (scroll_area, &x, &y); if (scroll_area->priv->grabbed) { emit_input (scroll_area, input_type, x, y, scroll_area->priv->grab_func, scroll_area->priv->grab_data); } #if 0 g_print ("number of input regions: %d\n", scroll_area->priv->input_regions->len); #endif for (i = 0; i < scroll_area->priv->input_regions->len; ++i) { InputRegion *region = scroll_area->priv->input_regions->pdata[i]; #if 0 g_print ("region %d (looking for %d,%d) ", i, x, y); #endif if (cairo_region_contains_point (region->region, x, y)) { InputPath *path; path = region->paths; while (path) { cairo_t *cr; gboolean inside; cr = gdk_cairo_create (gtk_widget_get_window (widget)); cairo_set_fill_rule (cr, path->fill_rule); cairo_set_line_width (cr, path->line_width); cairo_append_path (cr, path->path); if (path->is_stroke) inside = cairo_in_stroke (cr, x, y); else inside = cairo_in_fill (cr, x, y); cairo_destroy (cr); if (inside) { if (scroll_area->priv->grabbed) { emit_input (scroll_area, FOO_DRAG_HOVER, x, y, path->func, path->data); } else { emit_input (scroll_area, input_type, x, y, path->func, path->data); } return; } path = path->next; } /* Since the regions are all disjoint, no other region * can match. Of course we could be clever and try and * sort the regions, but so far I have been unable to * make this loop show up on a profile. */ return; } } } static void process_gdk_event (FooScrollArea *scroll_area, int x, int y, GdkEvent *event) { FooScrollAreaEventType input_type; if (event->type == GDK_BUTTON_PRESS) input_type = FOO_BUTTON_PRESS; else if (event->type == GDK_BUTTON_RELEASE) input_type = FOO_BUTTON_RELEASE; else if (event->type == GDK_MOTION_NOTIFY) input_type = FOO_MOTION; else return; process_event (scroll_area, input_type, x, y); } static gboolean foo_scroll_area_button_press (GtkWidget *widget, GdkEventButton *event) { FooScrollArea *area = FOO_SCROLL_AREA (widget); process_gdk_event (area, event->x, event->y, (GdkEvent *)event); return TRUE; } static gboolean foo_scroll_area_button_release (GtkWidget *widget, GdkEventButton *event) { FooScrollArea *area = FOO_SCROLL_AREA (widget); process_gdk_event (area, event->x, event->y, (GdkEvent *)event); return FALSE; } static gboolean foo_scroll_area_motion (GtkWidget *widget, GdkEventMotion *event) { FooScrollArea *area = FOO_SCROLL_AREA (widget); process_gdk_event (area, event->x, event->y, (GdkEvent *)event); return TRUE; } void foo_scroll_area_set_size_fixed_y (FooScrollArea *scroll_area, int width, int height, int old_y, int new_y) { scroll_area->priv->width = width; scroll_area->priv->height = height; #if 0 g_print ("diff: %d\n", new_y - old_y); #endif g_object_thaw_notify (G_OBJECT (scroll_area->priv->vadj)); gtk_adjustment_set_value (scroll_area->priv->vadj, new_y); set_adjustment_values (scroll_area); g_object_thaw_notify (G_OBJECT (scroll_area->priv->vadj)); } void foo_scroll_area_set_size (FooScrollArea *scroll_area, int width, int height) { g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); /* FIXME: Default scroll algorithm should probably be to * keep the same *area* outside the screen as before. * * For wrapper widgets that will do something roughly * right. For widgets that don't change size, it * will do the right thing. Except for idle-layouting * widgets. * * Maybe there should be some generic support for those * widgets. Can that even be done? * * Should we have a version of this function using * fixed points? */ scroll_area->priv->width = width; scroll_area->priv->height = height; set_adjustment_values (scroll_area); } static void foo_scroll_area_get_preferred_width (GtkWidget *widget, gint *minimum, gint *natural) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (widget); if (minimum != NULL) { *minimum = scroll_area->priv->min_width; } if (natural != NULL) { *natural = scroll_area->priv->min_width; } } static void foo_scroll_area_get_preferred_height (GtkWidget *widget, gint *minimum, gint *natural) { FooScrollArea *scroll_area = FOO_SCROLL_AREA (widget); if (minimum != NULL) { *minimum = scroll_area->priv->min_height; } if (natural != NULL) { *natural = scroll_area->priv->min_height; } } static void foo_scroll_area_scroll (FooScrollArea *area, gint dx, gint dy) { GdkRectangle allocation; GdkRectangle src_area; GdkRectangle move_area; cairo_region_t *invalid_region; gtk_widget_get_allocation (GTK_WIDGET (area), &allocation); allocation.x = 0; allocation.y = 0; src_area = allocation; src_area.x -= dx; src_area.y -= dy; invalid_region = cairo_region_create_rectangle (&allocation); if (gdk_rectangle_intersect (&allocation, &src_area, &move_area)) { cairo_region_t *move_region; cairo_t *cr; #if 0 g_print ("scrolling %d %d %d %d (%d %d)\n", move_area.x, move_area.y, move_area.width, move_area.height, dx, dy); #endif cr = cairo_create (area->priv->surface); /* Cairo doesn't allow self-copies, so we do this little trick instead: * 1) Clip so the group size is small. * 2) Call push_group() which creates a temporary pixmap as a workaround */ gdk_cairo_rectangle (cr, &move_area); cairo_clip (cr); cairo_push_group (cr); cairo_set_source_surface (cr, area->priv->surface, dx, dy); gdk_cairo_rectangle (cr, &move_area); cairo_fill (cr); cairo_pop_group_to_source (cr); cairo_paint (cr); cairo_destroy (cr); gtk_widget_queue_draw (GTK_WIDGET (area)); move_region = cairo_region_create_rectangle (&move_area); cairo_region_translate (move_region, dx, dy); cairo_region_subtract (invalid_region, move_region); cairo_region_destroy (move_region); } allocation_to_canvas_region (area, invalid_region); foo_scroll_area_invalidate_region (area, invalid_region); cairo_region_destroy (invalid_region); } static void foo_scrollbar_adjustment_changed (GtkAdjustment *adj, FooScrollArea *scroll_area) { GtkWidget *widget = GTK_WIDGET (scroll_area); gint dx = 0; gint dy = 0; GdkRectangle old_viewport, new_viewport; get_viewport (scroll_area, &old_viewport); if (adj == scroll_area->priv->hadj) { /* FIXME: do we treat the offset as int or double, and, * if int, how do we round? */ dx = (int)gtk_adjustment_get_value (adj) - scroll_area->priv->x_offset; scroll_area->priv->x_offset = gtk_adjustment_get_value (adj); } else if (adj == scroll_area->priv->vadj) { dy = (int)gtk_adjustment_get_value (adj) - scroll_area->priv->y_offset; scroll_area->priv->y_offset = gtk_adjustment_get_value (adj); } else { g_assert_not_reached (); } if (gtk_widget_get_realized (widget)) { foo_scroll_area_scroll (scroll_area, -dx, -dy); //translate_input_regions (scroll_area, -dx, -dy); } get_viewport (scroll_area, &new_viewport); emit_viewport_changed (scroll_area, &new_viewport, &old_viewport); } static void set_one_adjustment (FooScrollArea *scroll_area, GtkAdjustment *adjustment, GtkAdjustment **location) { g_return_if_fail (location != NULL); if (adjustment == *location) return; if (!adjustment) adjustment = new_adjustment (); g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment)); if (*location) { g_signal_handlers_disconnect_by_func ( *location, foo_scrollbar_adjustment_changed, scroll_area); g_object_unref (*location); } *location = adjustment; g_object_ref_sink (*location); g_signal_connect (*location, "value_changed", G_CALLBACK (foo_scrollbar_adjustment_changed), scroll_area); } static void foo_scroll_area_set_hadjustment (FooScrollArea *scroll_area, GtkAdjustment *hadjustment) { set_one_adjustment (scroll_area, hadjustment, &scroll_area->priv->hadj); set_adjustment_values (scroll_area); } static void foo_scroll_area_set_vadjustment (FooScrollArea *scroll_area, GtkAdjustment *vadjustment) { set_one_adjustment (scroll_area, vadjustment, &scroll_area->priv->vadj); set_adjustment_values (scroll_area); } FooScrollArea * foo_scroll_area_new (void) { return g_object_new (FOO_TYPE_SCROLL_AREA, NULL); } void foo_scroll_area_set_min_size (FooScrollArea *scroll_area, int min_width, int min_height) { scroll_area->priv->min_width = min_width; scroll_area->priv->min_height = min_height; /* FIXME: think through invalidation. * * Goals: - no repainting everything on size_allocate(), * - make sure input boxes are invalidated when * needed */ gtk_widget_queue_resize (GTK_WIDGET (scroll_area)); } typedef struct { cairo_t *cr; GtkAllocation allocation; } user_to_device_data; static void user_to_device (double *x, double *y, gpointer user_data) { gdouble ox, oy; user_to_device_data* data = user_data; /* The translations by the user */ cairo_user_to_device (data->cr, x, y); /* The position of the widget on the window. */ *x -= data->allocation.x; *y -= data->allocation.y; } static InputPath * make_path (FooScrollArea *area, cairo_t *cr, gboolean is_stroke, FooScrollAreaEventFunc func, gpointer data) { user_to_device_data conversion_data; InputPath *path = g_new0 (InputPath, 1); conversion_data.cr = cr; gtk_widget_get_allocation(GTK_WIDGET (area), &conversion_data.allocation); path->is_stroke = is_stroke; path->fill_rule = cairo_get_fill_rule (cr); path->line_width = cairo_get_line_width (cr); path->path = cairo_copy_path (cr); path_foreach_point (path->path, user_to_device, &conversion_data); path->func = func; path->data = data; path->next = area->priv->current_input->paths; area->priv->current_input->paths = path; return path; } /* FIXME: we probably really want a * * foo_scroll_area_add_input_from_fill (area, cr, ...); * and * foo_scroll_area_add_input_from_stroke (area, cr, ...); * as well. */ void foo_scroll_area_add_input_from_fill (FooScrollArea *scroll_area, cairo_t *cr, FooScrollAreaEventFunc func, gpointer data) { g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); g_return_if_fail (cr != NULL); g_return_if_fail (scroll_area->priv->current_input); make_path (scroll_area, cr, FALSE, func, data); } void foo_scroll_area_add_input_from_stroke (FooScrollArea *scroll_area, cairo_t *cr, FooScrollAreaEventFunc func, gpointer data) { g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); g_return_if_fail (cr != NULL); g_return_if_fail (scroll_area->priv->current_input); make_path (scroll_area, cr, TRUE, func, data); } void foo_scroll_area_invalidate (FooScrollArea *scroll_area) { GtkAllocation allocation; GtkWidget *widget = GTK_WIDGET (scroll_area); gtk_widget_get_allocation (widget, &allocation); foo_scroll_area_invalidate_rect (scroll_area, scroll_area->priv->x_offset, scroll_area->priv->y_offset, allocation.width, allocation.height); } static void canvas_to_window (FooScrollArea *area, cairo_region_t *region) { GtkAllocation allocation; GtkWidget *widget = GTK_WIDGET (area); gtk_widget_get_allocation (widget, &allocation); cairo_region_translate (region, -area->priv->x_offset + allocation.x, -area->priv->y_offset + allocation.y); } static void window_to_canvas (FooScrollArea *area, cairo_region_t *region) { GtkAllocation allocation; GtkWidget *widget = GTK_WIDGET (area); gtk_widget_get_allocation (widget, &allocation); cairo_region_translate (region, area->priv->x_offset - allocation.x, area->priv->y_offset - allocation.y); } void foo_scroll_area_invalidate_region (FooScrollArea *area, cairo_region_t *region) { GtkWidget *widget; g_return_if_fail (FOO_IS_SCROLL_AREA (area)); widget = GTK_WIDGET (area); cairo_region_union (area->priv->update_region, region); if (gtk_widget_get_realized (widget)) { canvas_to_window (area, region); gdk_window_invalidate_region (gtk_widget_get_window (widget), region, TRUE); window_to_canvas (area, region); } } void foo_scroll_area_invalidate_rect (FooScrollArea *scroll_area, int x, int y, int width, int height) { cairo_rectangle_int_t rect = { x, y, width, height }; cairo_region_t *region; g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); region = cairo_region_create_rectangle (&rect); foo_scroll_area_invalidate_region (scroll_area, region); cairo_region_destroy (region); } void foo_scroll_area_begin_grab (FooScrollArea *scroll_area, FooScrollAreaEventFunc func, gpointer input_data) { g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); g_return_if_fail (!scroll_area->priv->grabbed); scroll_area->priv->grabbed = TRUE; scroll_area->priv->grab_func = func; scroll_area->priv->grab_data = input_data; /* FIXME: we should probably take a server grab */ /* Also, maybe there should be support for setting the grab cursor */ } void foo_scroll_area_end_grab (FooScrollArea *scroll_area, FooScrollAreaEvent *event) { g_return_if_fail (FOO_IS_SCROLL_AREA (scroll_area)); scroll_area->priv->grabbed = FALSE; scroll_area->priv->grab_func = NULL; scroll_area->priv->grab_data = NULL; if (event != NULL) process_event (scroll_area, FOO_DROP, event->x, event->y); } gboolean foo_scroll_area_is_grabbed (FooScrollArea *scroll_area) { return scroll_area->priv->grabbed; } void foo_scroll_area_set_viewport_pos (FooScrollArea *scroll_area, int x, int y) { g_object_freeze_notify (G_OBJECT (scroll_area->priv->hadj)); g_object_freeze_notify (G_OBJECT (scroll_area->priv->vadj)); gtk_adjustment_set_value (scroll_area->priv->hadj, x); gtk_adjustment_set_value (scroll_area->priv->vadj, y); set_adjustment_values (scroll_area); g_object_thaw_notify (G_OBJECT (scroll_area->priv->hadj)); g_object_thaw_notify (G_OBJECT (scroll_area->priv->vadj)); } static gboolean rect_contains (const GdkRectangle *rect, int x, int y) { return (x >= rect->x && y >= rect->y && x < rect->x + rect->width && y < rect->y + rect->height); } static void stop_scrolling (FooScrollArea *area) { #if 0 g_print ("stop scrolling\n"); #endif if (area->priv->auto_scroll_info) { g_source_remove (area->priv->auto_scroll_info->timeout_id); g_timer_destroy (area->priv->auto_scroll_info->timer); g_free (area->priv->auto_scroll_info); area->priv->auto_scroll_info = NULL; } } static gboolean scroll_idle (gpointer data) { GdkRectangle viewport, new_viewport; FooScrollArea *area = data; AutoScrollInfo *info = area->priv->auto_scroll_info; int new_x, new_y; double elapsed; get_viewport (area, &viewport); #if 0 g_print ("old info: %d %d\n", info->dx, info->dy); g_print ("timeout (%d %d)\n", dx, dy); #endif #if 0 g_print ("new info %d %d\n", info->dx, info->dy); #endif elapsed = g_timer_elapsed (info->timer, NULL); info->res_x = elapsed * info->dx / 0.2; info->res_y = elapsed * info->dy / 0.2; #if 0 g_print ("%f %f\n", info->res_x, info->res_y); #endif new_x = viewport.x + info->res_x; new_y = viewport.y + info->res_y; #if 0 g_print ("%f\n", elapsed * (info->dx / 0.2)); #endif #if 0 g_print ("new_x, new_y\n: %d %d\n", new_x, new_y); #endif foo_scroll_area_set_viewport_pos (area, new_x, new_y); #if 0 viewport.x + info->dx, viewport.y + info->dy); #endif get_viewport (area, &new_viewport); if (viewport.x == new_viewport.x && viewport.y == new_viewport.y && (info->res_x > 1.0 || info->res_y > 1.0 || info->res_x < -1.0 || info->res_y < -1.0)) { stop_scrolling (area); /* stop scrolling if it didn't have an effect */ return FALSE; } return TRUE; } static void ensure_scrolling (FooScrollArea *area, int dx, int dy) { if (!area->priv->auto_scroll_info) { #if 0 g_print ("start scrolling\n"); #endif area->priv->auto_scroll_info = g_new0 (AutoScrollInfo, 1); area->priv->auto_scroll_info->timeout_id = g_idle_add (scroll_idle, area); area->priv->auto_scroll_info->timer = g_timer_new (); } #if 0 g_print ("setting scrolling to %d %d\n", dx, dy); #endif #if 0 g_print ("dx, dy: %d %d\n", dx, dy); #endif area->priv->auto_scroll_info->dx = dx; area->priv->auto_scroll_info->dy = dy; } void foo_scroll_area_auto_scroll (FooScrollArea *scroll_area, FooScrollAreaEvent *event) { GdkRectangle viewport; get_viewport (scroll_area, &viewport); if (rect_contains (&viewport, event->x, event->y)) { stop_scrolling (scroll_area); } else { int dx, dy; dx = dy = 0; if (event->y < viewport.y) { dy = event->y - viewport.y; dy = MIN (dy + 2, 0); } else if (event->y >= viewport.y + viewport.height) { dy = event->y - (viewport.y + viewport.height - 1); dy = MAX (dy - 2, 0); } if (event->x < viewport.x) { dx = event->x - viewport.x; dx = MIN (dx + 2, 0); } else if (event->x >= viewport.x + viewport.width) { dx = event->x - (viewport.x + viewport.width - 1); dx = MAX (dx - 2, 0); } #if 0 g_print ("dx, dy: %d %d\n", dx, dy); #endif ensure_scrolling (scroll_area, dx, dy); } } void foo_scroll_area_begin_auto_scroll (FooScrollArea *scroll_area) { /* noop for now */ } void foo_scroll_area_end_auto_scroll (FooScrollArea *scroll_area) { stop_scrolling (scroll_area); }
461
./cinnamon-control-center/panels/display/foo-marshal.c
#ifndef __foo_marshal_MARSHAL_H__ #define __foo_marshal_MARSHAL_H__ #include <glib-object.h> G_BEGIN_DECLS #ifdef G_ENABLE_DEBUG #define g_marshal_value_peek_boolean(v) g_value_get_boolean (v) #define g_marshal_value_peek_char(v) g_value_get_char (v) #define g_marshal_value_peek_uchar(v) g_value_get_uchar (v) #define g_marshal_value_peek_int(v) g_value_get_int (v) #define g_marshal_value_peek_uint(v) g_value_get_uint (v) #define g_marshal_value_peek_long(v) g_value_get_long (v) #define g_marshal_value_peek_ulong(v) g_value_get_ulong (v) #define g_marshal_value_peek_int64(v) g_value_get_int64 (v) #define g_marshal_value_peek_uint64(v) g_value_get_uint64 (v) #define g_marshal_value_peek_enum(v) g_value_get_enum (v) #define g_marshal_value_peek_flags(v) g_value_get_flags (v) #define g_marshal_value_peek_float(v) g_value_get_float (v) #define g_marshal_value_peek_double(v) g_value_get_double (v) #define g_marshal_value_peek_string(v) (char*) g_value_get_string (v) #define g_marshal_value_peek_param(v) g_value_get_param (v) #define g_marshal_value_peek_boxed(v) g_value_get_boxed (v) #define g_marshal_value_peek_pointer(v) g_value_get_pointer (v) #define g_marshal_value_peek_object(v) g_value_get_object (v) #define g_marshal_value_peek_variant(v) g_value_get_variant (v) #else /* !G_ENABLE_DEBUG */ /* WARNING: This code accesses GValues directly, which is UNSUPPORTED API. * Do not access GValues directly in your code. Instead, use the * g_value_get_*() functions */ #define g_marshal_value_peek_boolean(v) (v)->data[0].v_int #define g_marshal_value_peek_char(v) (v)->data[0].v_int #define g_marshal_value_peek_uchar(v) (v)->data[0].v_uint #define g_marshal_value_peek_int(v) (v)->data[0].v_int #define g_marshal_value_peek_uint(v) (v)->data[0].v_uint #define g_marshal_value_peek_long(v) (v)->data[0].v_long #define g_marshal_value_peek_ulong(v) (v)->data[0].v_ulong #define g_marshal_value_peek_int64(v) (v)->data[0].v_int64 #define g_marshal_value_peek_uint64(v) (v)->data[0].v_uint64 #define g_marshal_value_peek_enum(v) (v)->data[0].v_long #define g_marshal_value_peek_flags(v) (v)->data[0].v_ulong #define g_marshal_value_peek_float(v) (v)->data[0].v_float #define g_marshal_value_peek_double(v) (v)->data[0].v_double #define g_marshal_value_peek_string(v) (v)->data[0].v_pointer #define g_marshal_value_peek_param(v) (v)->data[0].v_pointer #define g_marshal_value_peek_boxed(v) (v)->data[0].v_pointer #define g_marshal_value_peek_pointer(v) (v)->data[0].v_pointer #define g_marshal_value_peek_object(v) (v)->data[0].v_pointer #define g_marshal_value_peek_variant(v) (v)->data[0].v_pointer #endif /* !G_ENABLE_DEBUG */ /* VOID:OBJECT,OBJECT (./foo-marshal.list:1) */ extern void foo_marshal_VOID__OBJECT_OBJECT (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void foo_marshal_VOID__OBJECT_OBJECT (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__OBJECT_OBJECT) (gpointer data1, gpointer arg_1, gpointer arg_2, gpointer data2); register GMarshalFunc_VOID__OBJECT_OBJECT callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 3); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__OBJECT_OBJECT) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_object (param_values + 1), g_marshal_value_peek_object (param_values + 2), data2); } /* VOID:UINT,UINT,UINT,UINT (./foo-marshal.list:2) */ extern void foo_marshal_VOID__UINT_UINT_UINT_UINT (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void foo_marshal_VOID__UINT_UINT_UINT_UINT (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__UINT_UINT_UINT_UINT) (gpointer data1, guint arg_1, guint arg_2, guint arg_3, guint arg_4, gpointer data2); register GMarshalFunc_VOID__UINT_UINT_UINT_UINT callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 5); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__UINT_UINT_UINT_UINT) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_uint (param_values + 1), g_marshal_value_peek_uint (param_values + 2), g_marshal_value_peek_uint (param_values + 3), g_marshal_value_peek_uint (param_values + 4), data2); } /* VOID:UINT,UINT (./foo-marshal.list:3) */ extern void foo_marshal_VOID__UINT_UINT (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void foo_marshal_VOID__UINT_UINT (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__UINT_UINT) (gpointer data1, guint arg_1, guint arg_2, gpointer data2); register GMarshalFunc_VOID__UINT_UINT callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 3); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__UINT_UINT) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_uint (param_values + 1), g_marshal_value_peek_uint (param_values + 2), data2); } /* VOID:BOXED,BOXED (./foo-marshal.list:4) */ extern void foo_marshal_VOID__BOXED_BOXED (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void foo_marshal_VOID__BOXED_BOXED (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__BOXED_BOXED) (gpointer data1, gpointer arg_1, gpointer arg_2, gpointer data2); register GMarshalFunc_VOID__BOXED_BOXED callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 3); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__BOXED_BOXED) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_boxed (param_values + 1), g_marshal_value_peek_boxed (param_values + 2), data2); } /* VOID:POINTER,BOXED,POINTER (./foo-marshal.list:5) */ extern void foo_marshal_VOID__POINTER_BOXED_POINTER (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void foo_marshal_VOID__POINTER_BOXED_POINTER (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__POINTER_BOXED_POINTER) (gpointer data1, gpointer arg_1, gpointer arg_2, gpointer arg_3, gpointer data2); register GMarshalFunc_VOID__POINTER_BOXED_POINTER callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 4); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__POINTER_BOXED_POINTER) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_pointer (param_values + 1), g_marshal_value_peek_boxed (param_values + 2), g_marshal_value_peek_pointer (param_values + 3), data2); } /* VOID:POINTER,POINTER (./foo-marshal.list:6) */ extern void foo_marshal_VOID__POINTER_POINTER (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void foo_marshal_VOID__POINTER_POINTER (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__POINTER_POINTER) (gpointer data1, gpointer arg_1, gpointer arg_2, gpointer data2); register GMarshalFunc_VOID__POINTER_POINTER callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 3); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__POINTER_POINTER) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_pointer (param_values + 1), g_marshal_value_peek_pointer (param_values + 2), data2); } G_END_DECLS #endif /* __foo_marshal_MARSHAL_H__ */
462
./cinnamon-control-center/panels/power/power-module.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * */ #include <config.h> #include "cc-power-panel.h" #include <glib/gi18n-lib.h> void g_io_module_load (GIOModule *module) { /* register the panel */ cc_power_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
463
./cinnamon-control-center/panels/power/cc-power-panel.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc * Copyright (C) 2008 William Jon McCann <jmccann@redhat.com> * Copyright (C) 2010 Richard Hughes <richard@hughsie.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <config.h> #include <libupower-glib/upower.h> #include <glib/gi18n-lib.h> #include <cinnamon-settings-daemon/csd-enums.h> #include "cc-power-panel.h" #define WID(b, w) (GtkWidget *) gtk_builder_get_object (b, w) CC_PANEL_REGISTER (CcPowerPanel, cc_power_panel) #define POWER_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_POWER_PANEL, CcPowerPanelPrivate)) struct _CcPowerPanelPrivate { GSettings *lock_settings; GSettings *csd_settings; GSettings *power_settings; GCancellable *cancellable; GtkBuilder *builder; GDBusProxy *proxy; UpClient *up_client; GtkWidget *levelbar_primary; }; enum { ACTION_MODEL_TEXT, ACTION_MODEL_VALUE, ACTION_MODEL_SENSITIVE }; static void cc_power_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_power_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_power_panel_dispose (GObject *object) { CcPowerPanelPrivate *priv = CC_POWER_PANEL (object)->priv; if (priv->csd_settings) { g_object_unref (priv->csd_settings); priv->csd_settings = NULL; } if (priv->power_settings) { g_object_unref (priv->power_settings); priv->power_settings = NULL; } if (priv->cancellable != NULL) { g_cancellable_cancel (priv->cancellable); g_object_unref (priv->cancellable); priv->cancellable = NULL; } if (priv->builder != NULL) { g_object_unref (priv->builder); priv->builder = NULL; } if (priv->proxy != NULL) { g_object_unref (priv->proxy); priv->proxy = NULL; } if (priv->up_client != NULL) { g_object_unref (priv->up_client); priv->up_client = NULL; } G_OBJECT_CLASS (cc_power_panel_parent_class)->dispose (object); } static void on_lock_settings_changed (GSettings *settings, const char *key, CcPowerPanel *panel) { } static const char * cc_power_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/power"; else return "help:gnome-help/power"; } static void cc_power_panel_class_init (CcPowerPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcPowerPanelPrivate)); object_class->get_property = cc_power_panel_get_property; object_class->set_property = cc_power_panel_set_property; object_class->dispose = cc_power_panel_dispose; panel_class->get_help_uri = cc_power_panel_get_help_uri; } static gchar * get_timestring (guint64 time_secs) { gchar* timestring = NULL; gint hours; gint minutes; /* Add 0.5 to do rounding */ minutes = (int) ( ( time_secs / 60.0 ) + 0.5 ); if (minutes == 0) { timestring = g_strdup (_("Unknown time")); return timestring; } if (minutes < 60) { timestring = g_strdup_printf (ngettext ("%i minute", "%i minutes", minutes), minutes); return timestring; } hours = minutes / 60; minutes = minutes % 60; if (minutes == 0) { timestring = g_strdup_printf (ngettext ( "%i hour", "%i hours", hours), hours); return timestring; } /* TRANSLATOR: "%i %s %i %s" are "%i hours %i minutes" * Swap order with "%2$s %2$i %1$s %1$i if needed */ timestring = g_strdup_printf (_("%i %s %i %s"), hours, ngettext ("hour", "hours", hours), minutes, ngettext ("minute", "minutes", minutes)); return timestring; } static void set_device_battery_primary (CcPowerPanel *panel, GVariant *device) { CcPowerPanelPrivate *priv = panel->priv; gchar *details = NULL; gchar *time_string = NULL; gdouble percentage; GtkWidget *widget; guint64 time; UpDeviceState state; /* set the device */ g_variant_get (device, "(susdut)", NULL, /* object_path */ NULL, /* kind */ NULL, /* icon_name */ &percentage, &state, &time); /* set the percentage */ gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (priv->levelbar_primary), percentage / 100.0f); /* clear the warning */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "image_primary_warning")); gtk_widget_hide (widget); /* set the description */ if (time > 0) { time_string = get_timestring (time); switch (state) { case UP_DEVICE_STATE_CHARGING: case UP_DEVICE_STATE_PENDING_CHARGE: /* TRANSLATORS: %1 is a time string, e.g. "1 hour 5 minutes" */ details = g_strdup_printf(_("Charging - %s until fully charged"), time_string); break; case UP_DEVICE_STATE_DISCHARGING: case UP_DEVICE_STATE_PENDING_DISCHARGE: if (percentage < 20) { /* TRANSLATORS: %1 is a time string, e.g. "1 hour 5 minutes" */ details = g_strdup_printf(_("Caution low battery, %s remaining"), time_string); /* show the warning */ gtk_widget_show (widget); } else { /* TRANSLATORS: %1 is a time string, e.g. "1 hour 5 minutes" */ details = g_strdup_printf(_("Using battery power - %s remaining"), time_string); } break; default: details = g_strdup_printf ("error: %s", up_device_state_to_string (state)); break; } } else { switch (state) { case UP_DEVICE_STATE_CHARGING: case UP_DEVICE_STATE_PENDING_CHARGE: /* TRANSLATORS: primary battery */ details = g_strdup(_("Charging")); break; case UP_DEVICE_STATE_DISCHARGING: case UP_DEVICE_STATE_PENDING_DISCHARGE: /* TRANSLATORS: primary battery */ details = g_strdup(_("Using battery power")); break; case UP_DEVICE_STATE_FULLY_CHARGED: /* TRANSLATORS: primary battery */ details = g_strdup(_("Charging - fully charged")); break; case UP_DEVICE_STATE_EMPTY: /* TRANSLATORS: primary battery */ details = g_strdup(_("Empty")); break; default: details = g_strdup_printf ("error: %s", up_device_state_to_string (state)); break; } } if (details == NULL) goto out; widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_battery_primary")); gtk_label_set_label (GTK_LABEL (widget), details); /* show the primary device */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_primary")); gtk_widget_show (widget); /* hide the addon device until we stumble upon the device */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_battery_addon")); gtk_widget_hide (widget); out: g_free (time_string); g_free (details); } static void set_device_ups_primary (CcPowerPanel *panel, GVariant *device) { CcPowerPanelPrivate *priv = panel->priv; gchar *details = NULL; gchar *time_string = NULL; gdouble percentage; GtkWidget *widget; guint64 time; UpDeviceState state; /* set the device */ g_variant_get (device, "(susdut)", NULL, /* object_path */ NULL, /* kind */ NULL, /* icon_name */ &percentage, &state, &time); /* set the percentage */ gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (priv->levelbar_primary), percentage / 100.0f); /* always show the warning */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "image_primary_warning")); gtk_widget_show (widget); /* set the description */ if (time > 0) { time_string = get_timestring (time); switch (state) { case UP_DEVICE_STATE_DISCHARGING: if (percentage < 20) { /* TRANSLATORS: %1 is a time string, e.g. "1 hour 5 minutes" */ details = g_strdup_printf(_("Caution low UPS, %s remaining"), time_string); } else { /* TRANSLATORS: %1 is a time string, e.g. "1 hour 5 minutes" */ details = g_strdup_printf(_("Using UPS power - %s remaining"), time_string); } break; default: details = g_strdup_printf ("error: %s", up_device_state_to_string (state)); break; } } else { switch (state) { case UP_DEVICE_STATE_DISCHARGING: if (percentage < 20) { /* TRANSLATORS: UPS battery */ details = g_strdup(_("Caution low UPS")); } else { /* TRANSLATORS: UPS battery */ details = g_strdup(_("Using UPS power")); } break; default: details = g_strdup_printf ("error: %s", up_device_state_to_string (state)); break; } } if (details == NULL) goto out; widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_battery_primary")); gtk_label_set_label (GTK_LABEL (widget), details); /* show the primary device */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_primary")); gtk_widget_show (widget); /* hide the addon device as extra UPS devices are not possible */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_battery_addon")); gtk_widget_hide (widget); out: g_free (time_string); g_free (details); } static void set_device_battery_additional (CcPowerPanel *panel, GVariant *device) { CcPowerPanelPrivate *priv = panel->priv; gchar *details = NULL; GtkWidget *widget; UpDeviceState state; /* set the device */ g_variant_get (device, "(susdut)", NULL, /* object_path */ NULL, /* kind */ NULL, /* icon_name */ NULL, /* percentage */ &state, NULL /* time */); /* set the description */ switch (state) { case UP_DEVICE_STATE_FULLY_CHARGED: /* TRANSLATORS: secondary battery is normally in the media bay */ details = g_strdup(_("Your secondary battery is fully charged")); break; case UP_DEVICE_STATE_EMPTY: /* TRANSLATORS: secondary battery is normally in the media bay */ details = g_strdup(_("Your secondary battery is empty")); break; default: break; } if (details == NULL) goto out; widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_battery_addon")); gtk_label_set_label (GTK_LABEL (widget), details); /* show the addon device */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_battery_addon")); gtk_widget_show (widget); out: g_free (details); } static void add_device_secondary (CcPowerPanel *panel, GVariant *device, guint *secondary_devices_cnt) { CcPowerPanelPrivate *priv = panel->priv; const gchar *icon_name = NULL; gdouble percentage; guint64 time; UpDeviceKind kind; UpDeviceState state; GtkWidget *vbox; GtkWidget *hbox; GtkWidget *widget; GString *status; GString *description; gboolean show_caution = FALSE; g_variant_get (device, "(susdut)", NULL, &kind, NULL, &percentage, &state, &time); switch (kind) { case UP_DEVICE_KIND_UPS: icon_name = "uninterruptible-power-supply"; show_caution = TRUE; break; case UP_DEVICE_KIND_MOUSE: icon_name = "input-mouse"; break; case UP_DEVICE_KIND_KEYBOARD: icon_name = "input-keyboard"; break; case UP_DEVICE_KIND_TABLET: icon_name = "input-tablet"; break; case UP_DEVICE_KIND_PDA: icon_name = "pda"; break; case UP_DEVICE_KIND_PHONE: icon_name = "phone"; break; case UP_DEVICE_KIND_MEDIA_PLAYER: icon_name = "multimedia-player"; break; case UP_DEVICE_KIND_COMPUTER: icon_name = "computer"; show_caution = TRUE; break; default: icon_name = "battery"; break; } switch (kind) { case UP_DEVICE_KIND_MOUSE: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Wireless mouse")); break; case UP_DEVICE_KIND_KEYBOARD: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Wireless keyboard")); break; case UP_DEVICE_KIND_UPS: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Uninterruptible power supply")); break; case UP_DEVICE_KIND_PDA: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Personal digital assistant")); break; case UP_DEVICE_KIND_PHONE: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Cellphone")); break; case UP_DEVICE_KIND_MEDIA_PLAYER: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Media player")); break; case UP_DEVICE_KIND_TABLET: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Tablet")); break; case UP_DEVICE_KIND_COMPUTER: /* TRANSLATORS: secondary battery */ description = g_string_new (_("Computer")); break; default: /* TRANSLATORS: secondary battery, misc */ description = g_string_new (_("Battery")); break; } g_string_prepend (description, "<b>"); g_string_append (description, "</b>"); switch (state) { case UP_DEVICE_STATE_CHARGING: case UP_DEVICE_STATE_PENDING_CHARGE: /* TRANSLATORS: secondary battery */ status = g_string_new(C_("Battery power", "Charging")); break; case UP_DEVICE_STATE_DISCHARGING: case UP_DEVICE_STATE_PENDING_DISCHARGE: if (percentage < 10 && show_caution) { /* TRANSLATORS: secondary battery */ status = g_string_new (C_("Battery power", "Caution")); } else if (percentage < 30) { /* TRANSLATORS: secondary battery */ status = g_string_new (C_("Battery power", "Low")); } else { /* TRANSLATORS: secondary battery */ status = g_string_new (C_("Battery power", "Good")); } break; case UP_DEVICE_STATE_FULLY_CHARGED: /* TRANSLATORS: primary battery */ status = g_string_new(C_("Battery power", "Charging - fully charged")); break; case UP_DEVICE_STATE_EMPTY: /* TRANSLATORS: primary battery */ status = g_string_new(C_("Battery power", "Empty")); break; default: status = g_string_new (up_device_state_to_string (state)); break; } g_string_prepend (status, "<small>"); g_string_append (status, "</small>"); /* create the new widget */ hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12); gtk_widget_set_hexpand (hbox, TRUE); widget = gtk_image_new (); gtk_misc_set_alignment (GTK_MISC (widget), 0.5f, 0.0f); gtk_image_set_from_icon_name (GTK_IMAGE (widget), icon_name, GTK_ICON_SIZE_DND); gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0); vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); widget = gtk_label_new (""); gtk_misc_set_alignment (GTK_MISC (widget), 0.0f, 0.5f); gtk_label_set_markup (GTK_LABEL (widget), description->str); gtk_box_pack_start (GTK_BOX (vbox), widget, FALSE, FALSE, 0); widget = gtk_label_new (""); gtk_misc_set_alignment (GTK_MISC (widget), 0.0f, 0.5f); gtk_label_set_markup (GTK_LABEL (widget), status->str); gtk_box_pack_start (GTK_BOX (vbox), widget, FALSE, FALSE, 0); widget = gtk_progress_bar_new (); gtk_widget_set_margin_right (widget, 32); gtk_widget_set_margin_top (widget, 3); gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (widget), percentage / 100.0f); gtk_box_pack_start (GTK_BOX (vbox), widget, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (hbox), vbox, TRUE, TRUE, 0); /* add to the grid */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "grid_secondary")); /* two devices wide */ gtk_grid_attach (GTK_GRID (widget), hbox, *secondary_devices_cnt % 2, (*secondary_devices_cnt / 2) - 1, 1, 1); (*secondary_devices_cnt)++; /* show panel */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_secondary")); gtk_widget_show_all (widget); g_string_free (description, TRUE); g_string_free (status, TRUE); } static void get_devices_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { CcPowerPanel *panel; CcPowerPanelPrivate *priv; gboolean got_primary = FALSE; gboolean ups_as_primary_device = FALSE; GError *error = NULL; gsize n_devices; GList *children; GList *l; GtkWidget *widget; guint i; guint secondary_devices_cnt = 0; GVariant *child; GVariant *result; GVariant *untuple; UpDeviceKind kind; UpDeviceState state; result = g_dbus_proxy_call_finish (G_DBUS_PROXY (source_object), res, &error); if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { g_error_free (error); return; /* Must exit before accessing freed memory */ } panel = CC_POWER_PANEL (user_data); priv = panel->priv; /* empty the secondary box */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "grid_secondary")); children = gtk_container_get_children (GTK_CONTAINER (widget)); for (l = children; l != NULL; l = l->next) gtk_container_remove (GTK_CONTAINER (widget), l->data); g_list_free (children); /* hide both panels initially */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_primary")); gtk_widget_hide (widget); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "box_secondary")); gtk_widget_hide (widget); if (result == NULL) { g_printerr ("Error getting devices: %s\n", error->message); g_error_free (error); return; } untuple = g_variant_get_child_value (result, 0); n_devices = g_variant_n_children (untuple); /* first we look for a discharging UPS, which is promoted to the * primary device if it's discharging. Otherwise we use the first * listed laptop battery as the primary device */ for (i = 0; i < n_devices; i++) { child = g_variant_get_child_value (untuple, i); g_variant_get (child, "(susdut)", NULL, &kind, NULL, NULL, &state, NULL); if (kind == UP_DEVICE_KIND_UPS && state == UP_DEVICE_STATE_DISCHARGING) { ups_as_primary_device = TRUE; } g_variant_unref (child); } /* add the devices now we know the state-of-play */ for (i = 0; i < n_devices; i++) { child = g_variant_get_child_value (untuple, i); g_variant_get (child, "(susdut)", NULL, &kind, NULL, NULL, NULL, NULL); if (kind == UP_DEVICE_KIND_LINE_POWER) { /* do nothing */ } else if (kind == UP_DEVICE_KIND_UPS && ups_as_primary_device) { set_device_ups_primary (panel, child); } else if (kind == UP_DEVICE_KIND_BATTERY && !ups_as_primary_device) { if (!got_primary) { set_device_battery_primary (panel, child); got_primary = TRUE; } else { set_device_battery_additional (panel, child); } } else { add_device_secondary (panel, child, &secondary_devices_cnt); } g_variant_unref (child); } g_variant_unref (untuple); g_variant_unref (result); } static void on_properties_changed (GDBusProxy *proxy, GVariant *changed_properties, GStrv invalidated_properties, gpointer user_data) { CcPowerPanelPrivate *priv = CC_POWER_PANEL (user_data)->priv; /* get the new state */ g_dbus_proxy_call (priv->proxy, "GetDevices", NULL, G_DBUS_CALL_FLAGS_NONE, -1, priv->cancellable, get_devices_cb, user_data); } static void got_power_proxy_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; GDBusProxy *proxy; CcPowerPanelPrivate *priv; proxy = g_dbus_proxy_new_for_bus_finish (res, &error); if (proxy == NULL) { g_printerr ("Error creating proxy: %s\n", error->message); g_error_free (error); return; } /* Access user_data after checking for error because user_data might be disposed already. */ priv = CC_POWER_PANEL (user_data)->priv; priv->proxy = proxy; /* we want to change the primary device changes */ g_signal_connect (priv->proxy, "g-properties-changed", G_CALLBACK (on_properties_changed), user_data); /* get the initial state */ g_dbus_proxy_call (priv->proxy, "GetDevices", NULL, G_DBUS_CALL_FLAGS_NONE, 200, /* we don't want to randomly expand the dialog */ priv->cancellable, get_devices_cb, user_data); } static void combo_time_changed_cb (GtkWidget *widget, CcPowerPanel *self) { GtkTreeIter iter; GtkTreeModel *model; gint value; gboolean ret; const gchar *key = (const gchar *)g_object_get_data (G_OBJECT(widget), "_gsettings_key"); /* no selection */ ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); if (!ret) return; /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_tree_model_get (model, &iter, 1, &value, -1); /* set both keys */ g_settings_set_int (self->priv->csd_settings, key, value); } static void combo_enum_changed_cb (GtkWidget *widget, CcPowerPanel *self) { GtkTreeIter iter; GtkTreeModel *model; gint value; gboolean ret; const gchar *key = (const gchar *)g_object_get_data (G_OBJECT(widget), "_gsettings_key"); /* no selection */ ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); if (!ret) return; /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_tree_model_get (model, &iter, 1, &value, -1); /* set both battery and ac keys */ g_settings_set_enum (self->priv->csd_settings, key, value); } static void disable_unavailable_combo_items (CcPowerPanel *self, GtkComboBox *combo_box) { gboolean enabled; gboolean ret; gint value_tmp; GtkCellRenderer *renderer; GtkTreeIter iter; GtkTreeModel *model; /* setup the renderer */ renderer = gtk_cell_renderer_text_new (); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, TRUE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer, "text", ACTION_MODEL_TEXT, "sensitive", ACTION_MODEL_SENSITIVE, NULL); /* get entry */ model = gtk_combo_box_get_model (combo_box); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* disable any actions we cannot do */ do { gtk_tree_model_get (model, &iter, ACTION_MODEL_VALUE, &value_tmp, -1); switch (value_tmp) { case CSD_POWER_ACTION_SUSPEND: enabled = up_client_get_can_suspend (self->priv->up_client); break; case CSD_POWER_ACTION_HIBERNATE: enabled = up_client_get_can_hibernate (self->priv->up_client); break; default: enabled = TRUE; } gtk_list_store_set (GTK_LIST_STORE (model), &iter, ACTION_MODEL_SENSITIVE, enabled, -1); } while (gtk_tree_model_iter_next (model, &iter)); } static void set_value_for_combo (GtkComboBox *combo_box, gint value) { GtkTreeIter iter; GtkTreeModel *model; gint value_tmp; gboolean ret; /* get entry */ model = gtk_combo_box_get_model (combo_box); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* try to make the UI match the setting */ do { gtk_tree_model_get (model, &iter, 1, &value_tmp, -1); if (value == value_tmp) { gtk_combo_box_set_active_iter (combo_box, &iter); break; } } while (gtk_tree_model_iter_next (model, &iter)); } static void set_ac_battery_ui_mode (CcPowerPanel *self) { gboolean has_batteries = FALSE; gboolean has_lid = FALSE; gboolean ret; GError *error = NULL; GPtrArray *devices; guint i; UpDevice *device; UpDeviceKind kind; CcPowerPanelPrivate *priv = self->priv; /* this is sync, but it's cached in the daemon and so quick */ ret = up_client_enumerate_devices_sync (self->priv->up_client, NULL, &error); if (!ret) { g_warning ("failed to get device list: %s", error->message); g_error_free (error); goto out; } devices = up_client_get_devices (self->priv->up_client); for (i=0; i<devices->len; i++) { device = g_ptr_array_index (devices, i); g_object_get (device, "kind", &kind, NULL); if (kind == UP_DEVICE_KIND_BATTERY || kind == UP_DEVICE_KIND_UPS) { has_batteries = TRUE; break; } } g_ptr_array_unref (devices); has_lid = up_client_get_lid_is_present (self->priv->up_client); out: gtk_widget_set_visible (WID (priv->builder, "combobox_lid_ac"), has_lid); gtk_widget_set_visible (WID (priv->builder, "label_lid_action"), has_lid); gtk_widget_set_visible (WID (priv->builder, "combobox_lid_battery"), has_batteries && has_lid); gtk_widget_set_visible (WID (priv->builder, "label_header_battery"), has_batteries); gtk_widget_set_visible (WID (priv->builder, "label_header_ac"), has_batteries); gtk_widget_set_visible (WID (priv->builder, "combobox_sleep_battery"), has_batteries); gtk_widget_set_visible (WID (priv->builder, "label_critical"), has_batteries); gtk_widget_set_visible (WID (priv->builder, "combobox_critical"), has_batteries); } static void cc_power_panel_init (CcPowerPanel *self) { GError *error; GtkWidget *widget; gint value; char *text; self->priv = POWER_PANEL_PRIVATE (self); self->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (self->priv->builder, GETTEXT_PACKAGE); error = NULL; gtk_builder_add_from_file (self->priv->builder, CINNAMONCC_UI_DIR "/power.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } /* add levelbar */ self->priv->levelbar_primary = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "levelbar_primary")); self->priv->cancellable = g_cancellable_new (); /* get initial icon state */ g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.cinnamon.SettingsDaemon", "/org/cinnamon/SettingsDaemon/Power", "org.cinnamon.SettingsDaemon.Power", self->priv->cancellable, got_power_proxy_cb, self); /* find out if there are any battery or UPS devices attached * and setup UI accordingly */ self->priv->up_client = up_client_new (); set_ac_battery_ui_mode (self); self->priv->csd_settings = g_settings_new ("org.cinnamon.settings-daemon.plugins.power"); g_signal_connect (self->priv->csd_settings, "changed", G_CALLBACK (on_lock_settings_changed), self); /* auto-sleep time */ value = g_settings_get_int (self->priv->csd_settings, "sleep-inactive-ac-timeout"); widget = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "combobox_sleep_ac")); set_value_for_combo (GTK_COMBO_BOX (widget), value); g_object_set_data (G_OBJECT(widget), "_gsettings_key", "sleep-inactive-ac-timeout"); g_signal_connect (widget, "changed", G_CALLBACK (combo_time_changed_cb), self); value = g_settings_get_int (self->priv->csd_settings, "sleep-inactive-battery-timeout"); widget = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "combobox_sleep_battery")); set_value_for_combo (GTK_COMBO_BOX (widget), value); g_object_set_data (G_OBJECT(widget), "_gsettings_key", "sleep-inactive-battery-timeout"); g_signal_connect (widget, "changed", G_CALLBACK (combo_time_changed_cb), self); /* actions */ value = g_settings_get_enum (self->priv->csd_settings, "critical-battery-action"); widget = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "combobox_critical")); disable_unavailable_combo_items (self, GTK_COMBO_BOX (widget)); set_value_for_combo (GTK_COMBO_BOX (widget), value); g_object_set_data (G_OBJECT(widget), "_gsettings_key", "critical-battery-action"); g_signal_connect (widget, "changed", G_CALLBACK (combo_enum_changed_cb), self); value = g_settings_get_enum (self->priv->csd_settings, "lid-close-ac-action"); widget = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "combobox_lid_ac")); disable_unavailable_combo_items (self, GTK_COMBO_BOX (widget)); set_value_for_combo (GTK_COMBO_BOX (widget), value); g_object_set_data (G_OBJECT(widget), "_gsettings_key", "lid-close-ac-action"); g_signal_connect (widget, "changed", G_CALLBACK (combo_enum_changed_cb), self); value = g_settings_get_enum (self->priv->csd_settings, "lid-close-battery-action"); widget = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "combobox_lid_battery")); disable_unavailable_combo_items (self, GTK_COMBO_BOX (widget)); set_value_for_combo (GTK_COMBO_BOX (widget), value); g_object_set_data (G_OBJECT(widget), "_gsettings_key", "lid-close-battery-action"); g_signal_connect (widget, "changed", G_CALLBACK (combo_enum_changed_cb), self); widget = WID (self->priv->builder, "vbox_power"); gtk_widget_reparent (widget, (GtkWidget *) self); gtk_widget_hide (GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "label_indicator"))); gtk_widget_hide (GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "combobox_indicator"))); value = g_settings_get_enum (self->priv->csd_settings, "button-power"); widget = WID (self->priv->builder, "combobox_power_button"); disable_unavailable_combo_items (self, GTK_COMBO_BOX (widget)); set_value_for_combo (GTK_COMBO_BOX (widget), value); g_object_set_data (G_OBJECT (widget), "_gsettings_key", "button-power"); g_signal_connect (widget, "changed", G_CALLBACK (combo_enum_changed_cb), self); } void cc_power_panel_register (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); cc_power_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_POWER_PANEL, "power", 0); }
464
./cinnamon-control-center/panels/region/cinnamon-region-panel-xkbot.c
/* cinnamon-region-panel-xkbot.c * Copyright (C) 2003-2007 Sergey V. Udaltsov * * Written by: Sergey V. Udaltsov <svu@gnome.org> * John Spray <spray_john@users.sourceforge.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <glib/gi18n-lib.h> #include <string.h> #include "cinnamon-region-panel-xkb.h" static GtkBuilder *chooser_dialog = NULL; static const char *current1st_level_id = NULL; static GSList *option_checks_list = NULL; static GtkWidget *current_none_radio = NULL; static GtkWidget *current_expander = NULL; static gboolean current_multi_select = FALSE; static GSList *current_radio_group = NULL; #define OPTION_ID_PROP "optionID" #define SELCOUNTER_PROP "selectionCounter" #define GCONFSTATE_PROP "gconfState" #define EXPANDERS_PROP "expandersList" gchar ** xkb_options_get_selected_list (void) { gchar **retval; retval = g_settings_get_strv (xkb_keyboard_settings, GKBD_KEYBOARD_CONFIG_KEY_OPTIONS); if (retval == NULL) { retval = g_strdupv (initial_config.options); } return retval; } /* Returns the selection counter of the expander (static current_expander) */ static int xkb_options_expander_selcounter_get (void) { return GPOINTER_TO_INT (g_object_get_data (G_OBJECT (current_expander), SELCOUNTER_PROP)); } /* Increments the selection counter in the expander (static current_expander) using the value (can be 0)*/ static void xkb_options_expander_selcounter_add (int value) { g_object_set_data (G_OBJECT (current_expander), SELCOUNTER_PROP, GINT_TO_POINTER (xkb_options_expander_selcounter_get () + value)); } /* Resets the seletion counter in the expander (static current_expander) */ static void xkb_options_expander_selcounter_reset (void) { g_object_set_data (G_OBJECT (current_expander), SELCOUNTER_PROP, GINT_TO_POINTER (0)); } /* Formats the expander (static current_expander), based on the selection counter */ static void xkb_options_expander_highlight (void) { char *utf_group_name = g_object_get_data (G_OBJECT (current_expander), "utfGroupName"); int counter = xkb_options_expander_selcounter_get (); if (utf_group_name != NULL) { gchar *titlemarkup = g_strconcat (counter > 0 ? "<span weight=\"bold\">" : "<span>", utf_group_name, "</span>", NULL); gtk_expander_set_label (GTK_EXPANDER (current_expander), titlemarkup); g_free (titlemarkup); } } /* Add optionname from the backend's selection list if it's not already in there. */ static void xkb_options_select (gchar * optionname) { gboolean already_selected = FALSE; gchar **options_list; guint i; options_list = xkb_options_get_selected_list (); for (i = 0; options_list != NULL && options_list[i] != NULL; i++) { gchar *option = options_list[i]; if (!strcmp (option, optionname)) { already_selected = TRUE; break; } } if (!already_selected) { options_list = gkbd_strv_append (options_list, g_strdup (optionname)); xkb_options_set_selected_list (options_list); } g_strfreev (options_list); } /* Remove all occurences of optionname from the backend's selection list */ static void xkb_options_deselect (gchar * optionname) { gchar **options_list = xkb_options_get_selected_list (); if (options_list != NULL) { gchar **option = options_list; while (*option != NULL) { gchar *id = *option; if (!strcmp (id, optionname)) { gkbd_strv_behead (option); } else option++; } xkb_options_set_selected_list (options_list); } g_strfreev (options_list); } /* Return true if optionname describes a string already in the backend's list of selected options */ static gboolean xkb_options_is_selected (gchar * optionname) { gboolean retval = FALSE; gchar **options_list = xkb_options_get_selected_list (); if (options_list != NULL) { gchar **option = options_list; while (*option != NULL) { if (!strcmp (*option, optionname)) { retval = TRUE; break; } option++; } } g_strfreev (options_list); return retval; } /* Make sure selected options stay visible when navigating with the keyboard */ static gboolean option_focused_cb (GtkWidget * widget, GdkEventFocus * event, gpointer data) { GtkScrolledWindow *win = GTK_SCROLLED_WINDOW (data); GtkAllocation alloc; GtkAdjustment *adj; gtk_widget_get_allocation (widget, &alloc); adj = gtk_scrolled_window_get_vadjustment (win); gtk_adjustment_clamp_page (adj, alloc.y, alloc.y + alloc.height); return FALSE; } /* Update xkb backend to reflect the new UI state */ static void option_toggled_cb (GtkWidget * checkbutton, gpointer data) { gpointer optionID = g_object_get_data (G_OBJECT (checkbutton), OPTION_ID_PROP); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (checkbutton))) xkb_options_select (optionID); else xkb_options_deselect (optionID); } /* Add a check_button or radio_button to control a particular option This function makes particular use of the current... variables at the top of this file. */ static void xkb_options_add_option (XklConfigRegistry * config_registry, XklConfigItem * config_item, GtkBuilder * dialog) { GtkWidget *option_check; gchar *utf_option_name = xci_desc_to_utf8 (config_item); /* Copy this out because we'll load it into the widget with set_data */ gchar *full_option_name = g_strdup (gkbd_keyboard_config_merge_items (current1st_level_id, config_item->name)); gboolean initial_state; if (current_multi_select) option_check = gtk_check_button_new_with_label (utf_option_name); else { if (current_radio_group == NULL) { /* The first radio in a group is to be "Default", meaning none of the below options are to be included in the selected list. This is a HIG-compliant alternative to allowing no selection in the group. */ option_check = gtk_radio_button_new_with_label (current_radio_group, _("Default")); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (option_check), TRUE); /* Make option name underscore - to enforce its first position in the list */ g_object_set_data_full (G_OBJECT (option_check), "utfOptionName", g_strdup (" "), g_free); option_checks_list = g_slist_append (option_checks_list, option_check); current_radio_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (option_check)); current_none_radio = option_check; g_signal_connect (option_check, "focus-in-event", G_CALLBACK (option_focused_cb), WID ("options_scroll")); } option_check = gtk_radio_button_new_with_label (current_radio_group, utf_option_name); current_radio_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (option_check)); g_object_set_data (G_OBJECT (option_check), "NoneRadio", current_none_radio); } initial_state = xkb_options_is_selected (full_option_name); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (option_check), initial_state); g_object_set_data_full (G_OBJECT (option_check), OPTION_ID_PROP, full_option_name, g_free); g_object_set_data_full (G_OBJECT (option_check), "utfOptionName", utf_option_name, g_free); g_signal_connect (option_check, "toggled", G_CALLBACK (option_toggled_cb), NULL); option_checks_list = g_slist_append (option_checks_list, option_check); g_signal_connect (option_check, "focus-in-event", G_CALLBACK (option_focused_cb), WID ("options_scroll")); xkb_options_expander_selcounter_add (initial_state); g_object_set_data (G_OBJECT (option_check), GCONFSTATE_PROP, GINT_TO_POINTER (initial_state)); } static gint xkb_option_checks_compare (GtkWidget * chk1, GtkWidget * chk2) { const gchar *t1 = g_object_get_data (G_OBJECT (chk1), "utfOptionName"); const gchar *t2 = g_object_get_data (G_OBJECT (chk2), "utfOptionName"); return g_utf8_collate (t1, t2); } /* Add a group of options: create title and layout widgets and then add widgets for all the options in the group. */ static void xkb_options_add_group (XklConfigRegistry * config_registry, XklConfigItem * config_item, GtkBuilder * dialog) { GtkWidget *align, *vbox, *option_check; gboolean allow_multiple_selection = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (config_item), XCI_PROP_ALLOW_MULTIPLE_SELECTION)); GSList *expanders_list = g_object_get_data (G_OBJECT (dialog), EXPANDERS_PROP); gchar *utf_group_name = xci_desc_to_utf8 (config_item); gchar *titlemarkup = g_strconcat ("<span>", utf_group_name, "</span>", NULL); current_expander = gtk_expander_new (titlemarkup); gtk_expander_set_use_markup (GTK_EXPANDER (current_expander), TRUE); g_object_set_data_full (G_OBJECT (current_expander), "utfGroupName", utf_group_name, g_free); g_object_set_data_full (G_OBJECT (current_expander), "groupId", g_strdup (config_item->name), g_free); g_free (titlemarkup); align = gtk_alignment_new (0, 0, 1, 1); gtk_alignment_set_padding (GTK_ALIGNMENT (align), 6, 12, 12, 0); vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6); gtk_box_set_homogeneous (GTK_BOX (vbox), TRUE); gtk_container_add (GTK_CONTAINER (align), vbox); gtk_container_add (GTK_CONTAINER (current_expander), align); current_multi_select = (gboolean) allow_multiple_selection; current_radio_group = NULL; current1st_level_id = config_item->name; option_checks_list = NULL; xkl_config_registry_foreach_option (config_registry, config_item->name, (ConfigItemProcessFunc) xkb_options_add_option, dialog); /* sort it */ option_checks_list = g_slist_sort (option_checks_list, (GCompareFunc) xkb_option_checks_compare); while (option_checks_list) { option_check = GTK_WIDGET (option_checks_list->data); gtk_box_pack_start (GTK_BOX (vbox), option_check, TRUE, TRUE, 0); option_checks_list = option_checks_list->next; } /* free it */ g_slist_free (option_checks_list); option_checks_list = NULL; xkb_options_expander_highlight (); expanders_list = g_slist_append (expanders_list, current_expander); g_object_set_data (G_OBJECT (dialog), EXPANDERS_PROP, expanders_list); g_signal_connect (current_expander, "focus-in-event", G_CALLBACK (option_focused_cb), WID ("options_scroll")); } static gint xkb_options_expanders_compare (GtkWidget * expander1, GtkWidget * expander2) { const gchar *t1 = g_object_get_data (G_OBJECT (expander1), "utfGroupName"); const gchar *t2 = g_object_get_data (G_OBJECT (expander2), "utfGroupName"); return g_utf8_collate (t1, t2); } /* Create widgets to represent the options made available by the backend */ void xkb_options_load_options (GtkBuilder * dialog) { GtkWidget *opts_vbox = WID ("options_vbox"); GtkWidget *dialog_vbox = WID ("dialog_vbox"); GtkWidget *options_scroll = WID ("options_scroll"); GtkWidget *expander; GSList *expanders_list; current1st_level_id = NULL; current_none_radio = NULL; current_multi_select = FALSE; current_radio_group = NULL; /* fill the list */ xkl_config_registry_foreach_option_group (config_registry, (ConfigItemProcessFunc) xkb_options_add_group, dialog); /* sort it */ expanders_list = g_object_get_data (G_OBJECT (dialog), EXPANDERS_PROP); expanders_list = g_slist_sort (expanders_list, (GCompareFunc) xkb_options_expanders_compare); g_object_set_data (G_OBJECT (dialog), EXPANDERS_PROP, expanders_list); while (expanders_list) { expander = GTK_WIDGET (expanders_list->data); gtk_box_pack_start (GTK_BOX (opts_vbox), expander, FALSE, FALSE, 0); expanders_list = expanders_list->next; } /* Somewhere in gtk3 the top vbox in dialog is made non-expandable */ gtk_box_set_child_packing (GTK_BOX (dialog_vbox), options_scroll, TRUE, TRUE, 0, GTK_PACK_START); gtk_widget_show_all (dialog_vbox); } static void chooser_response_cb (GtkDialog * dialog, gint response, gpointer data) { switch (response) { case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_CLOSE: { /* just cleanup */ GSList *expanders_list = g_object_get_data (G_OBJECT (dialog), EXPANDERS_PROP); g_object_set_data (G_OBJECT (dialog), EXPANDERS_PROP, NULL); g_slist_free (expanders_list); gtk_widget_destroy (GTK_WIDGET (dialog)); chooser_dialog = NULL; } break; } } /* Create popup dialog */ void xkb_options_popup_dialog (GtkBuilder * dialog) { GtkWidget *chooser; chooser_dialog = gtk_builder_new (); gtk_builder_set_translation_domain (chooser_dialog, GETTEXT_PACKAGE); gtk_builder_add_from_file (chooser_dialog, CINNAMONCC_UI_DIR "/cinnamon-region-panel-options-dialog.ui", NULL); chooser = CWID ("xkb_options_dialog"); gtk_window_set_transient_for (GTK_WINDOW (chooser), GTK_WINDOW (gtk_widget_get_toplevel (WID ("region_notebook")))); gtk_window_set_modal (GTK_WINDOW (chooser), TRUE); xkb_options_load_options (chooser_dialog); g_signal_connect (chooser, "response", G_CALLBACK (chooser_response_cb), dialog); gtk_widget_show (chooser); } /* Update selected option counters for a group-bound expander */ static void xkb_options_update_option_counters (XklConfigRegistry * config_registry, XklConfigItem * config_item) { gchar *full_option_name = g_strdup (gkbd_keyboard_config_merge_items (current1st_level_id, config_item->name)); gboolean current_state = xkb_options_is_selected (full_option_name); g_free (full_option_name); xkb_options_expander_selcounter_add (current_state); } /* Respond to a change in the xkb gconf settings */ static void xkb_options_update (GSettings * settings, gchar * key, GtkBuilder * dialog) { if (!strcmp (key, GKBD_KEYBOARD_CONFIG_KEY_OPTIONS)) { /* Updating options is handled by gconf notifies for each widget This is here to avoid calling it N_OPTIONS times for each gconf change. */ enable_disable_restoring (dialog); if (chooser_dialog != NULL) { GSList *expanders_list = g_object_get_data (G_OBJECT (chooser_dialog), EXPANDERS_PROP); while (expanders_list) { current_expander = GTK_WIDGET (expanders_list->data); gchar *group_id = g_object_get_data (G_OBJECT (current_expander), "groupId"); current1st_level_id = group_id; xkb_options_expander_selcounter_reset (); xkl_config_registry_foreach_option (config_registry, group_id, (ConfigItemProcessFunc) xkb_options_update_option_counters, current_expander); xkb_options_expander_highlight (); expanders_list = expanders_list->next; } } } } void xkb_options_register_conf_listener (GtkBuilder * dialog) { g_signal_connect (xkb_keyboard_settings, "changed", G_CALLBACK (xkb_options_update), dialog); }
465
./cinnamon-control-center/panels/region/cinnamon-region-panel-system.c
/* * Copyright (C) 2011 Rodrigo Moya * * Written by: Rodrigo Moya <rodrigo@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <string.h> #include <polkit/polkit.h> #include <glib/gi18n-lib.h> #include <libgnomekbd/gkbd-keyboard-config.h> #include "cc-common-language.h" #include "gdm-languages.h" #include "cinnamon-region-panel-system.h" #include "cinnamon-region-panel-xkb.h" static GSettings *locale_settings, *xkb_settings; static GDBusProxy *localed_proxy; static GPermission *localed_permission; static void update_copy_button (GtkBuilder *dialog) { GtkWidget *label; GtkWidget *button; const gchar *user_lang, *system_lang; const gchar *user_region, *system_region; const gchar *user_input_source, *system_input_source; const gchar *user_input_variants, *system_input_variants; gboolean layouts_differ; label = WID ("user_display_language"); user_lang = g_object_get_data (G_OBJECT (label), "language"); label = WID ("system_display_language"); system_lang = g_object_get_data (G_OBJECT (label), "language"); label = WID ("user_format"); user_region = g_object_get_data (G_OBJECT (label), "region"); label = WID ("system_format"); system_region = g_object_get_data (G_OBJECT (label), "region"); label = WID ("user_input_source"); user_input_source = g_object_get_data (G_OBJECT (label), "input_source"); user_input_variants = g_object_get_data (G_OBJECT (label), "input_variants"); label = WID ("system_input_source"); system_input_source = g_object_get_data (G_OBJECT (label), "input_source"); system_input_variants = g_object_get_data (G_OBJECT (label), "input_variants"); button = WID ("copy_settings_button"); /* If the version of localed doesn't include layouts... */ if (system_input_source) { layouts_differ = (g_strcmp0 (user_input_source, system_input_source) != 0); if (layouts_differ == FALSE) layouts_differ = (g_strcmp0 (user_input_variants, system_input_variants) != 0); } else layouts_differ = FALSE; if (g_strcmp0 (user_lang, system_lang) == 0 && g_strcmp0 (user_region, system_region) == 0 && !layouts_differ) gtk_widget_set_sensitive (button, FALSE); else gtk_widget_set_sensitive (button, TRUE); } static void locale_settings_changed (GSettings *settings, const gchar *key, GtkBuilder *dialog) { GtkWidget *label; gchar *region, *display_region; region = g_settings_get_string (locale_settings, "region"); if (!region || !region[0]) { label = WID ("user_display_language"); region = g_strdup ((gchar*)g_object_get_data (G_OBJECT (label), "language")); } display_region = gdm_get_region_from_name (region, NULL); label = WID ("user_format"); gtk_label_set_text (GTK_LABEL (label), display_region); g_object_set_data_full (G_OBJECT (label), "region", g_strdup (region), g_free); g_free (region); g_free (display_region); update_copy_button (dialog); } void system_update_language (GtkBuilder *dialog, const gchar *language) { gchar *display_language; GtkWidget *label; display_language = gdm_get_language_from_name (language, NULL); label = WID ("user_display_language"); gtk_label_set_text (GTK_LABEL (label), display_language); g_object_set_data_full (G_OBJECT (label), "language", g_strdup (language), g_free); g_free (display_language); /* need to update the region display in case the setting is '' */ locale_settings_changed (locale_settings, "region", dialog); update_copy_button (dialog); } static void xkb_settings_changed (GSettings *settings, const gchar *key, GtkBuilder *dialog) { guint i; GString *disp, *list, *variants; GtkWidget *label; gchar **layouts; layouts = g_settings_get_strv (settings, "layouts"); if (layouts == NULL) return; label = WID ("user_input_source"); disp = g_string_new (""); list = g_string_new (""); variants = g_string_new (""); for (i = 0; layouts[i]; i++) { gchar *utf_visible; char **split; gchar *layout, *variant; utf_visible = xkb_layout_description_utf8 (layouts[i]); if (disp->str[0] != '\0') g_string_append (disp, ", "); g_string_append (disp, utf_visible ? utf_visible : layouts[i]); g_free (utf_visible); split = g_strsplit_set (layouts[i], " \t", 2); if (split == NULL || split[0] == NULL) continue; layout = split[0]; variant = split[1]; if (list->str[0] != '\0') g_string_append (list, ","); g_string_append (list, layout); if (variants->str[0] != '\0') g_string_append (variants, ","); g_string_append (variants, variant ? variant : ""); g_strfreev (split); } g_strfreev (layouts); g_object_set_data_full (G_OBJECT (label), "input_source", g_string_free (list, FALSE), g_free); g_object_set_data_full (G_OBJECT (label), "input_variants", g_string_free (variants, FALSE), g_free); gtk_label_set_text (GTK_LABEL (label), disp->str); g_string_free (disp, TRUE); update_copy_button (dialog); } static void update_property (GDBusProxy *proxy, const char *property) { GError *error = NULL; GVariant *variant; /* Work around systemd-localed not sending us back * the property value when changing values */ variant = g_dbus_proxy_call_sync (proxy, "org.freedesktop.DBus.Properties.Get", g_variant_new ("(ss)", "org.freedesktop.locale1", property), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (variant == NULL) { g_warning ("Failed to get property '%s': %s", property, error->message); g_error_free (error); } else { GVariant *v; g_variant_get (variant, "(v)", &v); g_dbus_proxy_set_cached_property (proxy, property, v); g_variant_unref (variant); } } static void on_localed_properties_changed (GDBusProxy *proxy, GVariant *changed_properties, const gchar **invalidated_properties, GtkBuilder *dialog) { GVariant *v; GtkWidget *label; const char *layout; char **layouts; GString *disp; guint i; if (invalidated_properties != NULL) { guint i; for (i = 0; invalidated_properties[i] != NULL; i++) { if (g_str_equal (invalidated_properties[i], "Locale")) update_property (proxy, "Locale"); else if (g_str_equal (invalidated_properties[i], "X11Layout")) update_property (proxy, "X11Layout"); } } v = g_dbus_proxy_get_cached_property (proxy, "Locale"); if (v) { const gchar **strv; gsize len; gint i; const gchar *lang, *messages, *time; gchar *name; GtkWidget *label; strv = g_variant_get_strv (v, &len); lang = messages = time = NULL; for (i = 0; strv[i]; i++) { if (g_str_has_prefix (strv[i], "LANG=")) { lang = strv[i] + strlen ("LANG="); } else if (g_str_has_prefix (strv[i], "LC_MESSAGES=")) { messages = strv[i] + strlen ("LC_MESSAGES="); } else if (g_str_has_prefix (strv[i], "LC_TIME=")) { time = strv[i] + strlen ("LC_TIME="); } } if (!messages) { messages = lang; } if (!time) { time = lang; } if (messages) { name = gdm_get_language_from_name (messages, NULL); label = WID ("system_display_language"); gtk_label_set_text (GTK_LABEL (label), name); g_free (name); g_object_set_data_full (G_OBJECT (label), "language", g_strdup (lang), g_free); } if (time) { name = gdm_get_region_from_name (time, NULL); label = WID ("system_format"); gtk_label_set_text (GTK_LABEL (label), name); g_free (name); g_object_set_data_full (G_OBJECT (label), "region", g_strdup (time), g_free); } g_variant_unref (v); } label = WID ("system_input_source"); v = g_dbus_proxy_get_cached_property (proxy, "X11Layout"); if (v) { layout = g_variant_get_string (v, NULL); g_object_set_data_full (G_OBJECT (label), "input_source", g_strdup (layout), g_free); } else { g_object_set_data_full (G_OBJECT (label), "input_source", NULL, g_free); update_copy_button (dialog); return; } disp = g_string_new (""); layouts = g_strsplit (layout, ",", -1); for (i = 0; layouts[i]; i++) { gchar *utf_visible; utf_visible = xkb_layout_description_utf8 (layouts[i]); if (disp->str[0] != '\0') disp = g_string_append (disp, ", "); disp = g_string_append (disp, utf_visible ? utf_visible : layouts[i]); g_free (utf_visible); } gtk_label_set_text (GTK_LABEL (label), disp->str); g_string_free (disp, TRUE); g_variant_unref (v); update_copy_button (dialog); } static void localed_proxy_ready (GObject *source, GAsyncResult *res, GtkBuilder *dialog) { GError *error = NULL; localed_proxy = g_dbus_proxy_new_finish (res, &error); if (!localed_proxy) { g_warning ("Failed to contact localed: %s\n", error->message); g_error_free (error); return; } g_object_weak_ref (G_OBJECT (dialog), (GWeakNotify) g_object_unref, localed_proxy); g_signal_connect (localed_proxy, "g-properties-changed", G_CALLBACK (on_localed_properties_changed), dialog); on_localed_properties_changed (localed_proxy, NULL, NULL, dialog); } static void copy_settings (GtkButton *button, GtkBuilder *dialog) { const gchar *language; const gchar *region; const gchar *layout; const gchar *variants; GtkWidget *label; GVariantBuilder *b; gchar *s; label = WID ("user_display_language"); language = g_object_get_data (G_OBJECT (label), "language"); label = WID ("user_format"); region = g_object_get_data (G_OBJECT (label), "region"); b = g_variant_builder_new (G_VARIANT_TYPE ("as")); s = g_strconcat ("LANG=", language, NULL); g_variant_builder_add (b, "s", s); g_free (s); if (g_strcmp0 (language, region) != 0) { s = g_strconcat ("LC_TIME=", region, NULL); g_variant_builder_add (b, "s", s); g_free (s); s = g_strconcat ("LC_NUMERIC=", region, NULL); g_variant_builder_add (b, "s", s); g_free (s); s = g_strconcat ("LC_MONETARY=", region, NULL); g_variant_builder_add (b, "s", s); g_free (s); s = g_strconcat ("LC_MEASUREMENT=", region, NULL); g_variant_builder_add (b, "s", s); g_free (s); } g_dbus_proxy_call (localed_proxy, "SetLocale", g_variant_new ("(asb)", b, TRUE), G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL); g_variant_builder_unref (b); label = WID ("user_input_source"); layout = g_object_get_data (G_OBJECT (label), "input_source"); variants = g_object_get_data (G_OBJECT (label), "input_variants"); g_dbus_proxy_call (localed_proxy, "SetX11Keyboard", g_variant_new ("(ssssbb)", layout, "", variants ? variants : "", "", TRUE, TRUE), G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL); } static void on_permission_changed (GPermission *permission, GParamSpec *pspec, GtkBuilder *dialog) { GtkWidget *button; GtkWidget *label; gboolean can_acquire; gboolean allowed; if (permission) { can_acquire = g_permission_get_can_acquire (permission); allowed = g_permission_get_allowed (permission); } else { can_acquire = FALSE; allowed = FALSE; } button = WID ("copy_settings_button"); label = WID ("system-title"); if (!allowed && !can_acquire) { gtk_label_set_text (GTK_LABEL (label), _("The login screen, system accounts and new user accounts use the system-wide Region and Language settings.")); gtk_widget_hide (button); } else { gtk_label_set_text (GTK_LABEL (label), _("The login screen, system accounts and new user accounts use the system-wide Region and Language settings. You may change the system settings to match yours.")); gtk_widget_show (button); if (allowed) { gtk_button_set_label (GTK_BUTTON (button), _("Copy Settings")); } else { gtk_button_set_label (GTK_BUTTON (button), _("Copy Settings...")); } } } void setup_system (GtkBuilder *dialog) { gchar *language; GDBusConnection *bus; GtkWidget *button; localed_permission = polkit_permission_new_sync ("org.freedesktop.locale1.set-locale", NULL, NULL, NULL); if (localed_permission == NULL) { GtkWidget *tab_widget, *notebook; int num; tab_widget = WID ("table3"); notebook = WID ("region_notebook"); num = gtk_notebook_page_num (GTK_NOTEBOOK (notebook), tab_widget); gtk_notebook_remove_page (GTK_NOTEBOOK (notebook), num); return; } g_object_weak_ref (G_OBJECT (dialog), (GWeakNotify) g_object_unref, localed_permission); g_signal_connect (localed_permission, "notify", G_CALLBACK (on_permission_changed), dialog); on_permission_changed (localed_permission, NULL, dialog); button = WID ("copy_settings_button"); g_signal_connect (button, "clicked", G_CALLBACK (copy_settings), dialog); locale_settings = g_settings_new ("org.gnome.system.locale"); g_signal_connect (locale_settings, "changed::region", G_CALLBACK (locale_settings_changed), dialog); g_object_weak_ref (G_OBJECT (dialog), (GWeakNotify) g_object_unref, locale_settings); xkb_settings = g_settings_new (GKBD_KEYBOARD_SCHEMA); g_signal_connect (xkb_settings, "changed::layouts", G_CALLBACK (xkb_settings_changed), dialog); g_object_weak_ref (G_OBJECT (dialog), (GWeakNotify) g_object_unref, xkb_settings); /* Display user settings */ language = cc_common_language_get_current_language (); system_update_language (dialog, language); g_free (language); locale_settings_changed (locale_settings, "region", dialog); xkb_settings_changed (xkb_settings, "layouts", dialog); bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL); g_dbus_proxy_new (bus, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.locale1", "/org/freedesktop/locale1", "org.freedesktop.locale1", NULL, (GAsyncReadyCallback) localed_proxy_ready, dialog); g_object_unref (bus); }
466
./cinnamon-control-center/panels/region/cinnamon-region-panel-xkbltadd.c
/* cinnamon-region-panel-xkbltadd.c * Copyright (C) 2007 Sergey V. Udaltsov * * Written by: Sergey V. Udaltsov <svu@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <string.h> #include <libgnomekbd/gkbd-keyboard-drawing.h> #include <libgnomekbd/gkbd-util.h> #include "cinnamon-region-panel-xkb.h" enum { COMBO_BOX_MODEL_COL_SORT, COMBO_BOX_MODEL_COL_VISIBLE, COMBO_BOX_MODEL_COL_XKB_ID, COMBO_BOX_MODEL_COL_COUNTRY_DESC, COMBO_BOX_MODEL_COL_LANGUAGE_DESC }; static gchar **search_pattern_list = NULL; static GtkWidget *preview_dialog = NULL; static GRegex *left_bracket_regex = NULL; #define RESPONSE_PREVIEW 1 static void xkb_preview_destroy_callback (GtkWidget * widget) { preview_dialog = NULL; } static gboolean xkb_layout_chooser_selection_dupe (GtkDialog * dialog) { gchar *selected_id = (gchar *) xkb_layout_chooser_get_selected_id (dialog); gchar **layouts_list, **pl; gboolean rv = FALSE; if (selected_id == NULL) return rv; layouts_list = pl = xkb_layouts_get_selected_list (); while (pl && *pl) { if (!g_ascii_strcasecmp (*pl++, selected_id)) { rv = TRUE; break; } } g_strfreev (layouts_list); return rv; } void xkb_layout_chooser_response (GtkDialog * dialog, gint response) { switch (response) case GTK_RESPONSE_OK:{ /* Handled by the main code */ break; case RESPONSE_PREVIEW:{ gchar *selected_id = (gchar *) xkb_layout_chooser_get_selected_id (dialog); if (selected_id != NULL) { if (preview_dialog == NULL) { preview_dialog = gkbd_keyboard_drawing_dialog_new (); g_signal_connect (G_OBJECT (preview_dialog), "destroy", G_CALLBACK (xkb_preview_destroy_callback), NULL); /* Put into the separate group to avoid conflict with modal parent */ gtk_window_group_add_window (gtk_window_group_new (), GTK_WINDOW (preview_dialog)); }; gkbd_keyboard_drawing_dialog_set_layout (preview_dialog, config_registry, selected_id); gtk_widget_show_all (preview_dialog); } } return; } if (preview_dialog != NULL) { gtk_widget_destroy (preview_dialog); } if (search_pattern_list != NULL) { g_strfreev (search_pattern_list); search_pattern_list = NULL; } gtk_widget_destroy (GTK_WIDGET (dialog)); } static gchar * xkl_create_description_from_list (const XklConfigItem * item, const XklConfigItem * subitem, const gchar * prop_name, const gchar * (*desc_getter) (const gchar * code)) { gchar *rv = NULL, *code = NULL; gchar **list = NULL; const gchar *desc; if (subitem != NULL) list = (gchar **) (g_object_get_data (G_OBJECT (subitem), prop_name)); if (list == NULL || *list == 0) list = (gchar **) (g_object_get_data (G_OBJECT (item), prop_name)); /* First try the parent id as such */ desc = desc_getter (item->name); if (desc != NULL) { rv = g_utf8_strup (desc, -1); } else { code = g_utf8_strup (item->name, -1); desc = desc_getter (code); if (desc != NULL) { rv = g_utf8_strup (desc, -1); } g_free (code); } if (list == NULL || *list == 0) return rv; while (*list != 0) { code = *list++; desc = desc_getter (code); if (desc != NULL) { gchar *udesc = g_utf8_strup (desc, -1); if (rv == NULL) { rv = udesc; } else { gchar *orv = rv; rv = g_strdup_printf ("%s %s", rv, udesc); g_free (orv); g_free (udesc); } } } return rv; } static void xkl_layout_add_to_list (XklConfigRegistry * config, const XklConfigItem * item, const XklConfigItem * subitem, GtkBuilder * chooser_dialog) { GtkListStore *list_store = GTK_LIST_STORE (gtk_builder_get_object (chooser_dialog, "layout_list_model")); GtkTreeIter iter; gchar *utf_variant_name = subitem ? xkb_layout_description_utf8 (gkbd_keyboard_config_merge_items (item->name, subitem->name)) : xci_desc_to_utf8 (item); const gchar *xkb_id = subitem ? gkbd_keyboard_config_merge_items (item->name, subitem->name) : item->name; gchar *country_desc = xkl_create_description_from_list (item, subitem, XCI_PROP_COUNTRY_LIST, xkl_get_country_name); gchar *language_desc = xkl_create_description_from_list (item, subitem, XCI_PROP_LANGUAGE_LIST, xkl_get_language_name); gchar *tmp = utf_variant_name; utf_variant_name = g_regex_replace_literal (left_bracket_regex, tmp, -1, 0, "&lt;", 0, NULL); g_free (tmp); if (subitem && g_object_get_data (G_OBJECT (subitem), XCI_PROP_EXTRA_ITEM)) { gchar *buf = g_strdup_printf ("<i>%s</i>", utf_variant_name); gtk_list_store_insert_with_values (list_store, &iter, -1, COMBO_BOX_MODEL_COL_SORT, utf_variant_name, COMBO_BOX_MODEL_COL_VISIBLE, buf, COMBO_BOX_MODEL_COL_XKB_ID, xkb_id, COMBO_BOX_MODEL_COL_COUNTRY_DESC, country_desc, COMBO_BOX_MODEL_COL_LANGUAGE_DESC, language_desc, -1); g_free (buf); } else gtk_list_store_insert_with_values (list_store, &iter, -1, COMBO_BOX_MODEL_COL_SORT, utf_variant_name, COMBO_BOX_MODEL_COL_VISIBLE, utf_variant_name, COMBO_BOX_MODEL_COL_XKB_ID, xkb_id, COMBO_BOX_MODEL_COL_COUNTRY_DESC, country_desc, COMBO_BOX_MODEL_COL_LANGUAGE_DESC, language_desc, -1); g_free (utf_variant_name); g_free (country_desc); g_free (language_desc); } static void xkb_layout_filter_clear (GtkEntry * entry, GtkEntryIconPosition icon_pos, GdkEvent * event, gpointer user_data) { gtk_entry_set_text (entry, ""); } static void xkb_layout_filter_changed (GtkBuilder * chooser_dialog) { GtkTreeModelFilter *filtered_model = GTK_TREE_MODEL_FILTER (gtk_builder_get_object (chooser_dialog, "filtered_layout_list_model")); GtkWidget *xkb_layout_filter = CWID ("xkb_layout_filter"); const gchar *pattern = gtk_entry_get_text (GTK_ENTRY (xkb_layout_filter)); gchar *upattern = g_utf8_strup (pattern, -1); if (!g_strcmp0 (pattern, "")) { g_object_set (G_OBJECT (xkb_layout_filter), "secondary-icon-name", "edit-find-symbolic", "secondary-icon-activatable", FALSE, "secondary-icon-sensitive", FALSE, NULL); } else { g_object_set (G_OBJECT (xkb_layout_filter), "secondary-icon-name", "edit-clear-symbolic", "secondary-icon-activatable", TRUE, "secondary-icon-sensitive", TRUE, NULL); } if (search_pattern_list != NULL) g_strfreev (search_pattern_list); search_pattern_list = g_strsplit (upattern, " ", -1); g_free (upattern); gtk_tree_model_filter_refilter (filtered_model); } static void xkb_layout_chooser_selection_changed (GtkTreeSelection * selection, GtkBuilder * chooser_dialog) { GList *selected_layouts = gtk_tree_selection_get_selected_rows (selection, NULL); GtkWidget *add_button = CWID ("btnOk"); GtkWidget *preview_button = CWID ("btnPreview"); gboolean anything_selected = g_list_length (selected_layouts) == 1; gboolean dupe = xkb_layout_chooser_selection_dupe (GTK_DIALOG (CWID ("xkb_layout_chooser"))); gtk_widget_set_sensitive (add_button, anything_selected && !dupe); gtk_widget_set_sensitive (preview_button, anything_selected); } static void xkb_layout_chooser_row_activated (GtkTreeView * tree_view, GtkTreePath * path, GtkTreeViewColumn * column, GtkBuilder * chooser_dialog) { GtkWidget *add_button = CWID ("btnOk"); GtkWidget *dialog = CWID ("xkb_layout_chooser"); if (gtk_widget_is_sensitive (add_button)) gtk_dialog_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK); } static gboolean xkb_filter_layouts (GtkTreeModel * model, GtkTreeIter * iter, gpointer data) { gchar *desc = NULL, *country_desc = NULL, *language_desc = NULL, **pattern; gboolean rv = TRUE; if (search_pattern_list == NULL || search_pattern_list[0] == NULL) return TRUE; gtk_tree_model_get (model, iter, COMBO_BOX_MODEL_COL_SORT, &desc, COMBO_BOX_MODEL_COL_COUNTRY_DESC, &country_desc, COMBO_BOX_MODEL_COL_LANGUAGE_DESC, &language_desc, -1); pattern = search_pattern_list; do { gboolean is_pattern_found = FALSE; gchar *udesc = g_utf8_strup (desc, -1); if (udesc != NULL && g_strstr_len (udesc, -1, *pattern)) { is_pattern_found = TRUE; } else if (country_desc != NULL && g_strstr_len (country_desc, -1, *pattern)) { is_pattern_found = TRUE; } else if (language_desc != NULL && g_strstr_len (language_desc, -1, *pattern)) { is_pattern_found = TRUE; } g_free (udesc); if (!is_pattern_found) { rv = FALSE; break; } } while (*++pattern != NULL); g_free (desc); g_free (country_desc); g_free (language_desc); return rv; } GtkWidget * xkb_layout_choose (GtkBuilder * dialog) { GtkBuilder *chooser_dialog = gtk_builder_new (); GtkWidget *chooser, *xkb_filtered_layouts_list, *xkb_layout_filter; GtkTreeViewColumn *visible_column; GtkTreeSelection *selection; GtkListStore *model; GtkTreeModelFilter *filtered_model; gtk_builder_set_translation_domain (chooser_dialog, GETTEXT_PACKAGE); gtk_builder_add_from_file (chooser_dialog, CINNAMONCC_UI_DIR "/cinnamon-region-panel-layout-chooser.ui", NULL); chooser = CWID ("xkb_layout_chooser"); xkb_filtered_layouts_list = CWID ("xkb_filtered_layouts_list"); xkb_layout_filter = CWID ("xkb_layout_filter"); g_object_set_data (G_OBJECT (chooser), "xkb_filtered_layouts_list", xkb_filtered_layouts_list); visible_column = gtk_tree_view_column_new_with_attributes ("Layout", gtk_cell_renderer_text_new (), "markup", COMBO_BOX_MODEL_COL_VISIBLE, NULL); gtk_window_set_transient_for (GTK_WINDOW (chooser), GTK_WINDOW (gtk_widget_get_toplevel (WID ("region_notebook")))); gtk_tree_view_append_column (GTK_TREE_VIEW (xkb_filtered_layouts_list), visible_column); g_signal_connect_swapped (G_OBJECT (xkb_layout_filter), "notify::text", G_CALLBACK (xkb_layout_filter_changed), chooser_dialog); g_signal_connect (G_OBJECT (xkb_layout_filter), "icon-release", G_CALLBACK (xkb_layout_filter_clear), NULL); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (xkb_filtered_layouts_list)); g_signal_connect (G_OBJECT (selection), "changed", G_CALLBACK (xkb_layout_chooser_selection_changed), chooser_dialog); xkb_layout_chooser_selection_changed (selection, chooser_dialog); g_signal_connect (G_OBJECT (xkb_filtered_layouts_list), "row-activated", G_CALLBACK (xkb_layout_chooser_row_activated), chooser_dialog); filtered_model = GTK_TREE_MODEL_FILTER (gtk_builder_get_object (chooser_dialog, "filtered_layout_list_model")); model = GTK_LIST_STORE (gtk_builder_get_object (chooser_dialog, "layout_list_model")); left_bracket_regex = g_regex_new ("<", 0, 0, NULL); xkl_config_registry_search_by_pattern (config_registry, NULL, (TwoConfigItemsProcessFunc) (xkl_layout_add_to_list), chooser_dialog); g_regex_unref (left_bracket_regex); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (model), COMBO_BOX_MODEL_COL_SORT, GTK_SORT_ASCENDING); gtk_tree_model_filter_set_visible_func (filtered_model, xkb_filter_layouts, NULL, NULL); gtk_widget_grab_focus (xkb_layout_filter); gtk_widget_show (chooser); return chooser; } gchar * xkb_layout_chooser_get_selected_id (GtkDialog * dialog) { GtkTreeModel *filtered_list_model; GtkWidget *xkb_filtered_layouts_list = g_object_get_data (G_OBJECT (dialog), "xkb_filtered_layouts_list"); GtkTreeIter viter; gchar *v_id; GtkTreeSelection *selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (xkb_filtered_layouts_list)); GList *selected_layouts = gtk_tree_selection_get_selected_rows (selection, &filtered_list_model); if (g_list_length (selected_layouts) != 1) return NULL; gtk_tree_model_get_iter (filtered_list_model, &viter, (GtkTreePath *) (selected_layouts->data)); g_list_foreach (selected_layouts, (GFunc) gtk_tree_path_free, NULL); g_list_free (selected_layouts); gtk_tree_model_get (filtered_list_model, &viter, COMBO_BOX_MODEL_COL_XKB_ID, &v_id, -1); return v_id; }
467
./cinnamon-control-center/panels/region/cinnamon-region-panel-formats.c
/* * Copyright (C) 2011 Rodrigo Moya * * Written by: Rodrigo Moya <rodrigo@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <glib/gi18n-lib.h> #include <locale.h> #include <langinfo.h> #include <stdlib.h> #include "cc-common-language.h" #include "cc-language-chooser.h" #include "gdm-languages.h" #include "cinnamon-region-panel-formats.h" static void display_date (GtkLabel *label, GDateTime *dt, const gchar *format) { gchar *s; s = g_date_time_format (dt, format); s = g_strstrip (s); gtk_label_set_text (label, s); g_free (s); } static void select_region (GtkTreeView *treeview, const gchar *lang) { GtkTreeModel *model; GtkTreeSelection *selection; GtkTreeIter iter; GtkTreePath *path; gboolean cont; model = gtk_tree_view_get_model (treeview); selection = gtk_tree_view_get_selection (treeview); cont = gtk_tree_model_get_iter_first (model, &iter); while (cont) { gchar *locale; gtk_tree_model_get (model, &iter, 0, &locale, -1); if (g_strcmp0 (locale, lang) == 0) { gtk_tree_selection_select_iter (selection, &iter); path = gtk_tree_model_get_path (model, &iter); gtk_tree_view_scroll_to_cell (treeview, path, NULL, FALSE, 0.0, 0.0); gtk_tree_path_free (path); g_free (locale); break; } g_free (locale); cont = gtk_tree_model_iter_next (model, &iter); } } static void update_examples_cb (GtkTreeSelection *selection, gpointer user_data) { GtkBuilder *builder = GTK_BUILDER (user_data); GtkTreeModel *model; GtkTreeIter iter; gchar *active_id; gchar *locale; GDateTime *dt; gchar *s; struct lconv *num_info; const char *fmt; if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { return; } gtk_tree_model_get (model, &iter, 0, &active_id, -1); locale = g_strdup (setlocale (LC_TIME, NULL)); setlocale (LC_TIME, active_id); dt = g_date_time_new_now_local (); /* Display dates */ display_date (GTK_LABEL (gtk_builder_get_object (builder, "full_date_format")), dt, "%A %e %B %Y"); display_date (GTK_LABEL (gtk_builder_get_object (builder, "full_day_format")), dt, "%e %B %Y"); display_date (GTK_LABEL (gtk_builder_get_object (builder, "short_day_format")), dt, "%e %b %Y"); display_date (GTK_LABEL (gtk_builder_get_object (builder, "shortest_day_format")), dt, "%x"); /* Display times */ display_date (GTK_LABEL (gtk_builder_get_object (builder, "full_time_format")), dt, "%r %Z"); display_date (GTK_LABEL (gtk_builder_get_object (builder, "short_time_format")), dt, "%X"); setlocale (LC_TIME, locale); g_free (locale); /* Display numbers */ locale = g_strdup (setlocale (LC_NUMERIC, NULL)); setlocale (LC_NUMERIC, active_id); s = g_strdup_printf ("%'.2f", 123456789.00); gtk_label_set_text (GTK_LABEL (gtk_builder_get_object (builder, "numbers_format")), s); g_free (s); setlocale (LC_NUMERIC, locale); g_free (locale); /* Display currency */ locale = g_strdup (setlocale (LC_MONETARY, NULL)); setlocale (LC_MONETARY, active_id); num_info = localeconv (); if (num_info != NULL) { gtk_label_set_text (GTK_LABEL (gtk_builder_get_object (builder, "currency_format")), num_info->currency_symbol); } setlocale (LC_MONETARY, locale); g_free (locale); /* Display measurement */ #ifdef LC_MEASUREMENT locale = g_strdup (setlocale (LC_MEASUREMENT, NULL)); setlocale (LC_MEASUREMENT, active_id); fmt = nl_langinfo (_NL_MEASUREMENT_MEASUREMENT); if (fmt && *fmt == 2) gtk_label_set_text (GTK_LABEL (gtk_builder_get_object (builder, "measurement_format")), _("Imperial")); else gtk_label_set_text (GTK_LABEL (gtk_builder_get_object (builder, "measurement_format")), _("Metric")); setlocale (LC_MEASUREMENT, locale); g_free (locale); #endif g_free (active_id); } static void update_settings_cb (GtkTreeSelection *selection, gpointer user_data) { GtkBuilder *builder = GTK_BUILDER (user_data); GtkTreeModel *model; GtkTreeIter iter; gchar *active_id; GtkWidget *treeview; GSettings *locale_settings; gchar *current_setting; if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { return; } gtk_tree_model_get (model, &iter, 0, &active_id, -1); treeview = GTK_WIDGET (gtk_builder_get_object (builder, "region_selector")); locale_settings = g_object_get_data (G_OBJECT (treeview), "settings"); current_setting = g_settings_get_string (locale_settings, "region"); if (g_strcmp0 (active_id, current_setting) != 0) { g_settings_set_string (locale_settings, "region", active_id); } g_free (current_setting); g_free (active_id); } static void setting_changed_cb (GSettings *locale_settings, gchar *key, GtkTreeView *treeview) { gchar *current_setting; current_setting = g_settings_get_string (locale_settings, "region"); select_region (treeview, current_setting); g_free (current_setting); } static gint sort_regions (GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer data) { gchar *la, *lb; gint result; gtk_tree_model_get (model, a, 1, &la, -1); gtk_tree_model_get (model, b, 1, &lb, -1); result = strcmp (la, lb); g_free (la); g_free (lb); return result; } static void populate_regions (GtkBuilder *builder, const gchar *current_lang) { gchar *current_region; GSettings *locale_settings; GHashTable *ht; GHashTableIter htiter; GtkTreeModel *model; gchar *name, *language; GtkWidget *treeview; GtkTreeIter iter; GtkTreeSelection *selection; treeview = GTK_WIDGET (gtk_builder_get_object (builder, "region_selector")); /* don't update the setting just because the list is repopulated */ selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); g_signal_handlers_block_by_func (selection, update_settings_cb, builder); model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview)); locale_settings = g_object_get_data (G_OBJECT (treeview), "settings"); ht = cc_common_language_get_initial_regions (current_lang); current_region = g_settings_get_string (locale_settings, "region"); if (!current_region || !current_region[0]) { current_region = g_strdup (current_lang); } else if (!g_hash_table_lookup (ht, current_region)) { name = gdm_get_region_from_name (current_region, NULL); g_hash_table_insert (ht, g_strdup (current_region), name); } gtk_list_store_clear (GTK_LIST_STORE (model)); g_hash_table_iter_init (&htiter, ht); while (g_hash_table_iter_next (&htiter, (gpointer *)&name, (gpointer *)&language)) { gtk_list_store_append (GTK_LIST_STORE (model), &iter); gtk_list_store_set (GTK_LIST_STORE (model), &iter, 0, name, 1, language, -1); } g_hash_table_unref (ht); select_region (GTK_TREE_VIEW (treeview), current_region); g_free (current_region); g_signal_handlers_unblock_by_func (selection, update_settings_cb, builder); } static void region_response (GtkDialog *dialog, gint response_id, GtkWidget *treeview) { gchar *lang; GtkTreeModel *model; GtkTreeSelection *selection; GtkTreeIter iter; gtk_widget_hide (GTK_WIDGET (dialog)); if (response_id != GTK_RESPONSE_OK) { return; } lang = cc_language_chooser_get_language (GTK_WIDGET (dialog)); if (lang == NULL) { return; } model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview)); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); if (cc_common_language_get_iter_for_region (model, lang, &iter)) { gtk_tree_selection_select_iter (selection, &iter); } gtk_widget_grab_focus (treeview); g_free (lang); } static void add_region (GtkWidget *button, GtkWidget *treeview) { GtkWidget *toplevel; GtkWidget *chooser; toplevel = gtk_widget_get_toplevel (button); chooser = g_object_get_data (G_OBJECT (button), "chooser"); if (chooser == NULL) { chooser = cc_language_chooser_new (toplevel, TRUE); g_signal_connect (chooser, "response", G_CALLBACK (region_response), treeview); g_signal_connect (chooser, "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL); g_object_set_data_full (G_OBJECT (button), "chooser", chooser, (GDestroyNotify)gtk_widget_destroy); } else { cc_language_chooser_clear_filter (chooser); } gdk_window_set_cursor (gtk_widget_get_window (toplevel), NULL); gtk_window_present (GTK_WINDOW (chooser)); } void setup_formats (GtkBuilder *builder) { GtkWidget *treeview; gchar *current_lang; GtkTreeModel *model; GtkCellRenderer *cell; GtkTreeViewColumn *column; GtkWidget *widget; GtkStyleContext *context; GSettings *locale_settings; GtkTreeSelection *selection; locale_settings = g_settings_new ("org.gnome.system.locale"); /* Setup junction between toolbar and treeview */ widget = (GtkWidget *)gtk_builder_get_object (builder, "region-swindow"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = (GtkWidget *)gtk_builder_get_object (builder, "region-toolbar"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); /* Setup formats selector */ treeview = GTK_WIDGET (gtk_builder_get_object (builder, "region_selector")); cell = gtk_cell_renderer_text_new (); g_object_set (cell, "width-chars", 40, "ellipsize", PANGO_ELLIPSIZE_END, NULL); column = gtk_tree_view_column_new_with_attributes (NULL, cell, "text", 1, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); model = (GtkTreeModel*)gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_STRING); gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (model), sort_regions, NULL, NULL); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (model), GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, GTK_SORT_ASCENDING); gtk_tree_view_set_model (GTK_TREE_VIEW (treeview), model); g_object_set_data_full (G_OBJECT (treeview), "settings", locale_settings, g_object_unref); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); g_signal_connect (selection, "changed", G_CALLBACK (update_settings_cb), builder); g_signal_connect (selection, "changed", G_CALLBACK (update_examples_cb), builder); /* Connect buttons */ widget = (GtkWidget *)gtk_builder_get_object (builder, "region_add"); g_signal_connect (widget, "clicked", G_CALLBACK (add_region), treeview); current_lang = cc_common_language_get_current_language (); populate_regions (builder, current_lang); g_free (current_lang); g_signal_connect (locale_settings, "changed::region", G_CALLBACK (setting_changed_cb), treeview); } void formats_update_language (GtkBuilder *builder, const gchar *language) { populate_regions (builder, language); }
468
./cinnamon-control-center/panels/region/cinnamon-region-panel-xkb.c
/* cinnamon-region-panel-xkb.c * Copyright (C) 2003-2007 Sergey V. Udaltsov * * Written by: Sergey V. Udaltsov <svu@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <string.h> #include <gdk/gdkx.h> #include <glib/gi18n-lib.h> #include "cinnamon-region-panel-xkb.h" #include <libgnomekbd/gkbd-desktop-config.h> XklEngine *engine; XklConfigRegistry *config_registry; GkbdKeyboardConfig initial_config; GkbdDesktopConfig desktop_config; GSettings *xkb_keyboard_settings; GSettings *xkb_desktop_settings; char * xci_desc_to_utf8 (const XklConfigItem * ci) { gchar *dd = g_strdup (ci->description); gchar *sd = g_strstrip (dd); gchar *rv = g_strdup (sd[0] == 0 ? ci->name : sd); g_free (dd); return rv; } static void cleanup_xkb_tabs (GtkBuilder * dialog, GObject *where_the_object_wa) { gkbd_desktop_config_term (&desktop_config); gkbd_keyboard_config_term (&initial_config); g_object_unref (G_OBJECT (config_registry)); config_registry = NULL; /* Don't unref it here, or we'll crash if open the panel again */ engine = NULL; g_object_unref (G_OBJECT (xkb_keyboard_settings)); g_object_unref (G_OBJECT (xkb_desktop_settings)); xkb_keyboard_settings = NULL; xkb_desktop_settings = NULL; } static void reset_to_defaults (GtkWidget * button, GtkBuilder * dialog) { GkbdKeyboardConfig empty_kbd_config; gkbd_keyboard_config_init (&empty_kbd_config, engine); gkbd_keyboard_config_save (&empty_kbd_config); gkbd_keyboard_config_term (&empty_kbd_config); g_settings_reset (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_DEFAULT_GROUP); /* all the rest is g-s-d's business */ } static void chk_new_windows_inherit_layout_toggled (GtkWidget * chk_new_windows_inherit_layout, GtkBuilder * dialog) { xkb_save_default_group (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (chk_new_windows_inherit_layout)) ? -1 : 0); } void setup_xkb_tabs (GtkBuilder * dialog) { GtkWidget *widget; GtkStyleContext *context; GtkWidget *chk_new_windows_inherit_layout; chk_new_windows_inherit_layout = WID ("chk_new_windows_inherit_layout"); xkb_desktop_settings = g_settings_new (GKBD_DESKTOP_SCHEMA); xkb_keyboard_settings = g_settings_new (GKBD_KEYBOARD_SCHEMA); engine = xkl_engine_get_instance (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ())); config_registry = xkl_config_registry_get_instance (engine); gkbd_desktop_config_init (&desktop_config, engine); gkbd_desktop_config_load (&desktop_config); xkl_config_registry_load (config_registry, desktop_config.load_extra_items); gkbd_keyboard_config_init (&initial_config, engine); gkbd_keyboard_config_load_from_x_initial (&initial_config, NULL); /* Set initial state */ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (WID ("chk_separate_group_per_window")), g_settings_get_boolean (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_GROUP_PER_WINDOW)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (chk_new_windows_inherit_layout), xkb_get_default_group () < 0); g_settings_bind (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_GROUP_PER_WINDOW, WID ("chk_separate_group_per_window"), "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_GROUP_PER_WINDOW, WID ("chk_new_windows_inherit_layout"), "sensitive", G_SETTINGS_BIND_DEFAULT); g_settings_bind (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_GROUP_PER_WINDOW, WID ("chk_new_windows_default_layout"), "sensitive", G_SETTINGS_BIND_DEFAULT); xkb_layouts_prepare_selected_tree (dialog); xkb_layouts_fill_selected_tree (dialog); xkb_layouts_register_buttons_handlers (dialog); g_signal_connect (G_OBJECT (WID ("xkb_reset_to_defaults")), "clicked", G_CALLBACK (reset_to_defaults), dialog); g_signal_connect (G_OBJECT (chk_new_windows_inherit_layout), "toggled", G_CALLBACK (chk_new_windows_inherit_layout_toggled), dialog); g_signal_connect_swapped (G_OBJECT (WID ("xkb_layout_options")), "clicked", G_CALLBACK (xkb_options_popup_dialog), dialog); xkb_layouts_register_conf_listener (dialog); xkb_options_register_conf_listener (dialog); g_object_weak_ref (G_OBJECT (WID ("region_notebook")), (GWeakNotify) cleanup_xkb_tabs, dialog); enable_disable_restoring (dialog); /* Setup junction between toolbar and treeview */ widget = WID ("xkb_layouts_swindow"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = WID ("layouts-toolbar"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); } void enable_disable_restoring (GtkBuilder * dialog) { GkbdKeyboardConfig gswic; gboolean enable; gkbd_keyboard_config_init (&gswic, engine); gkbd_keyboard_config_load (&gswic, NULL); enable = !gkbd_keyboard_config_equals (&gswic, &initial_config); gkbd_keyboard_config_term (&gswic); gtk_widget_set_sensitive (WID ("xkb_reset_to_defaults"), enable); }
469
./cinnamon-control-center/panels/region/cinnamon-region-panel-xkbpv.c
/* cinnamon-region-panel-xkbpv.c * Copyright (C) 2003-2007 Sergey V. Udaltsov * * Written by: Sergey V. Udaltsov <svu@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <libgnomekbd/gkbd-keyboard-drawing.h> #include "cinnamon-region-panel-xkb.h" #ifdef HAVE_X11_EXTENSIONS_XKB_H #include "X11/XKBlib.h" /** * BAD STYLE: Taken from xklavier_private_xkb.h * Any ideas on architectural improvements are WELCOME */ extern gboolean xkl_xkb_config_native_prepare (XklEngine * engine, const XklConfigRec * data, XkbComponentNamesPtr component_names); extern void xkl_xkb_config_native_cleanup (XklEngine * engine, XkbComponentNamesPtr component_names); /* */ #endif static GkbdKeyboardDrawingGroupLevel groupsLevels[] = { {0, 1}, {0, 3}, {0, 0}, {0, 2} }; static GkbdKeyboardDrawingGroupLevel *pGroupsLevels[] = { groupsLevels, groupsLevels + 1, groupsLevels + 2, groupsLevels + 3 }; GtkWidget * xkb_layout_preview_create_widget (GtkBuilder * chooserDialog) { GtkWidget *kbdraw = gkbd_keyboard_drawing_new (); gkbd_keyboard_drawing_set_groups_levels (GKBD_KEYBOARD_DRAWING (kbdraw), pGroupsLevels); return kbdraw; } void xkb_layout_preview_set_drawing_layout (GtkWidget * kbdraw, const gchar * id) { #ifdef HAVE_X11_EXTENSIONS_XKB_H if (kbdraw != NULL) { if (id != NULL) { XklConfigRec *data; char **p, *layout, *variant; XkbComponentNamesRec component_names; data = xkl_config_rec_new (); if (xkl_config_rec_get_from_server (data, engine)) { if ((p = data->layouts) != NULL) g_strfreev (data->layouts); if ((p = data->variants) != NULL) g_strfreev (data->variants); data->layouts = g_new0 (char *, 2); data->variants = g_new0 (char *, 2); if (gkbd_keyboard_config_split_items (id, &layout, &variant) && variant != NULL) { data->layouts[0] = (layout == NULL) ? NULL : g_strdup (layout); data->variants[0] = (variant == NULL) ? NULL : g_strdup (variant); } else { data->layouts[0] = (id == NULL) ? NULL : g_strdup (id); data->variants[0] = NULL; } if (xkl_xkb_config_native_prepare (engine, data, &component_names)) { gkbd_keyboard_drawing_set_keyboard (GKBD_KEYBOARD_DRAWING (kbdraw), &component_names); xkl_xkb_config_native_cleanup (engine, &component_names); } } g_object_unref (G_OBJECT (data)); } else gkbd_keyboard_drawing_set_keyboard (GKBD_KEYBOARD_DRAWING (kbdraw), NULL); } #endif }
470
./cinnamon-control-center/panels/region/region-module.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Sergey Udaltsov <svu@gnome.org> * */ #include <config.h> #include "cc-region-panel.h" #include <glib/gi18n-lib.h> void g_io_module_load (GIOModule * module) { /* register the panel */ cc_region_panel_register (module); } void g_io_module_unload (GIOModule * module) { }
471
./cinnamon-control-center/panels/region/cc-region-panel.c
/* * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Author: Sergey Udaltsov <svu@gnome.org> * */ #include "config.h" #include "cc-region-panel.h" #include <gtk/gtk.h> #include <glib/gi18n-lib.h> #include "cinnamon-region-panel-xkb.h" #include "cinnamon-region-panel-lang.h" #include "cinnamon-region-panel-formats.h" #include "cinnamon-region-panel-system.h" G_DEFINE_DYNAMIC_TYPE (CcRegionPanel, cc_region_panel, CC_TYPE_PANEL) #define REGION_PANEL_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_REGION_PANEL, CcRegionPanelPrivate)) struct _CcRegionPanelPrivate { GtkBuilder *builder; }; enum { PROP_0, PROP_ARGV }; enum { LANGUAGE_PAGE, FORMATS_PAGE, LAYOUTS_PAGE, SYSTEM_PAGE }; static gboolean languages_link_cb (GtkButton *button, gpointer user_data) { g_spawn_command_line_async ("gnome-language-selector", NULL); return TRUE; } static void cc_region_panel_set_page (CcRegionPanel *panel, const char *page) { GtkWidget *notebook; int page_num; if (g_strcmp0 (page, "formats") == 0) page_num = FORMATS_PAGE; else if (g_strcmp0 (page, "layouts") == 0) page_num = LAYOUTS_PAGE; else if (g_strcmp0 (page, "system") == 0) page_num = SYSTEM_PAGE; else page_num = LANGUAGE_PAGE; notebook = GTK_WIDGET (gtk_builder_get_object (panel->priv->builder, "region_notebook")); gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), page_num); } static void cc_region_panel_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec) { CcRegionPanel *self; self = CC_REGION_PANEL (object); switch (property_id) { case PROP_ARGV: { gchar **args; args = g_value_get_boxed (value); if (args && args[0]) { cc_region_panel_set_page (self, args[0]); } break; } default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_region_panel_finalize (GObject * object) { CcRegionPanel *panel; panel = CC_REGION_PANEL (object); if (panel->priv && panel->priv->builder) g_object_unref (panel->priv->builder); G_OBJECT_CLASS (cc_region_panel_parent_class)->finalize (object); } static void cc_region_panel_class_init (CcRegionPanelClass * klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (CcRegionPanelPrivate)); object_class->set_property = cc_region_panel_set_property; object_class->finalize = cc_region_panel_finalize; g_object_class_override_property (object_class, PROP_ARGV, "argv"); } static void cc_region_panel_class_finalize (CcRegionPanelClass * klass) { } static void cc_region_panel_init (CcRegionPanel * self) { CcRegionPanelPrivate *priv; GtkWidget *prefs_widget; const char *desktop; GError *error = NULL; priv = self->priv = REGION_PANEL_PRIVATE (self); desktop = g_getenv ("XDG_CURRENT_DESKTOP"); priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (priv->builder, CINNAMONCC_UI_DIR "/cinnamon-region-panel.ui", &error); if (error != NULL) { g_warning ("Error loading UI file: %s", error->message); g_error_free (error); return; } prefs_widget = (GtkWidget *) gtk_builder_get_object (priv->builder, "region_notebook"); gtk_widget_set_size_request (GTK_WIDGET (prefs_widget), -1, 400); gtk_widget_reparent (prefs_widget, GTK_WIDGET (self)); setup_xkb_tabs (priv->builder); setup_language (priv->builder); setup_formats (priv->builder); setup_system (priv->builder); /* set screen link */ GtkWidget *widget = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "get_languages_button")); gtk_button_set_label (GTK_BUTTON (widget), _("Get more languages...")); g_signal_connect (widget, "clicked", G_CALLBACK (languages_link_cb), self); } void cc_region_panel_register (GIOModule * module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); cc_region_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_REGION_PANEL, "region", 0); }
472
./cinnamon-control-center/panels/region/cinnamon-region-panel-lang.c
/* * Copyright (C) 2010 Bastien Nocera * * Written by: Bastien Nocera <hadess@hadess.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <string.h> #include <glib/gi18n-lib.h> #include "cinnamon-region-panel-lang.h" #include "cinnamon-region-panel-formats.h" #include "cinnamon-region-panel-system.h" #include "cc-common-language.h" #include "cc-language-chooser.h" #include "gdm-languages.h" static GDBusProxy *proxy = NULL; static void selection_changed (GtkTreeSelection *selection, GtkBuilder *builder) { GtkTreeModel *model; GtkTreeIter iter; char *locale; GDBusProxy *user; GVariant *variant; GError *error = NULL; char *object_path; if (gtk_tree_selection_get_selected (selection, &model, &iter) == FALSE) { g_warning ("No selected languages, this shouldn't happen"); return; } user = NULL; variant = NULL; gtk_tree_model_get (model, &iter, LOCALE_COL, &locale, -1); if (proxy == NULL) { g_warning ("Would change the language to '%s', but no D-Bus connection available", locale); goto bail; } variant = g_dbus_proxy_call_sync (proxy, "FindUserByName", g_variant_new ("(s)", g_get_user_name ()), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (variant == NULL) { g_warning ("Could not contact accounts service to look up '%s': %s", g_get_user_name (), error->message); g_error_free (error); goto bail; } g_variant_get (variant, "(o)", &object_path); user = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.Accounts", object_path, "org.freedesktop.Accounts.User", NULL, &error); g_free (object_path); if (user == NULL) { g_warning ("Could not create proxy for user '%s': %s", g_variant_get_string (variant, NULL), error->message); g_error_free (error); goto bail; } g_variant_unref (variant); variant = g_dbus_proxy_call_sync (user, "SetLanguage", g_variant_new ("(s)", locale), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (variant == NULL) { g_warning ("Failed to set the language '%s': %s", locale, error->message); g_error_free (error); goto bail; } /* Update the other tabs */ formats_update_language (builder, locale); system_update_language (builder, locale); /* And done */ bail: if (variant != NULL) g_variant_unref (variant); if (user != NULL) g_object_unref (user); g_free (locale); } static void language_response (GtkDialog *dialog, gint response_id, GtkWidget *treeview) { gchar *lang; GtkTreeModel *model; GtkTreeSelection *selection; GtkTreeIter iter; gtk_widget_hide (GTK_WIDGET (dialog)); if (response_id != GTK_RESPONSE_OK) { return; } lang = cc_language_chooser_get_language (GTK_WIDGET (dialog)); if (lang == NULL) { return; } model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview)); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); if (cc_common_language_get_iter_for_language (model, lang, &iter)) { gtk_tree_selection_select_iter (selection, &iter); } gtk_widget_grab_focus (treeview); g_free (lang); } static void add_language (GtkWidget *button, GtkWidget *treeview) { GtkWidget *toplevel; GtkWidget *chooser; toplevel = gtk_widget_get_toplevel (button); chooser = g_object_get_data (G_OBJECT (button), "chooser"); if (chooser == NULL) { chooser = cc_language_chooser_new (toplevel, FALSE); g_signal_connect (chooser, "response", G_CALLBACK (language_response), treeview); g_signal_connect (chooser, "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL); g_object_set_data_full (G_OBJECT (button), "chooser", chooser, (GDestroyNotify)gtk_widget_destroy); } else { cc_language_chooser_clear_filter (chooser); } gdk_window_set_cursor (gtk_widget_get_window (toplevel), NULL); gtk_window_present (GTK_WINDOW (chooser)); } void setup_language (GtkBuilder *builder) { GtkWidget *treeview; GHashTable *user_langs; GError *error = NULL; GtkWidget *widget; GtkStyleContext *context; GtkTreeSelection *selection; /* Setup junction between toolbar and treeview */ widget = (GtkWidget *)gtk_builder_get_object (builder, "language-swindow"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = (GtkWidget *)gtk_builder_get_object (builder, "language-toolbar"); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); treeview = GTK_WIDGET (gtk_builder_get_object (builder, "display_language_treeview")); /* Connect buttons */ widget = (GtkWidget *)gtk_builder_get_object (builder, "language_add"); g_signal_connect (widget, "clicked", G_CALLBACK (add_language), treeview); /* Setup accounts service */ proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.Accounts", "/org/freedesktop/Accounts", "org.freedesktop.Accounts", NULL, &error); if (proxy == NULL) { g_warning ("Failed to contact accounts service: %s", error->message); g_error_free (error); } else { g_object_weak_ref (G_OBJECT (treeview), (GWeakNotify) g_object_unref, proxy); } /* Add user languages */ user_langs = cc_common_language_get_initial_languages (); cc_common_language_setup_list (treeview, user_langs); /* And select the current language */ cc_common_language_select_current_language (GTK_TREE_VIEW (treeview)); /* And now listen for changes */ selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); g_signal_connect (G_OBJECT (selection), "changed", G_CALLBACK (selection_changed), builder); gtk_widget_grab_focus (treeview); }
473
./cinnamon-control-center/panels/region/cinnamon-region-panel-xkblt.c
/* cinnamon-region-panel-xkblt.c * Copyright (C) 2003-2007 Sergey V. Udaltsov * * Written by: Sergey V. Udaltsov <svu@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gdk/gdkx.h> #include <glib/gi18n-lib.h> #include <libgnomekbd/gkbd-desktop-config.h> #include <libgnomekbd/gkbd-keyboard-drawing.h> #include "cinnamon-region-panel-xkb.h" enum { SEL_LAYOUT_TREE_COL_DESCRIPTION, SEL_LAYOUT_TREE_COL_ID, SEL_LAYOUT_TREE_COL_ENABLED, SEL_LAYOUT_N_COLS }; static int idx2select = -1; static int max_selected_layouts = -1; static GtkCellRenderer *text_renderer; static gboolean disable_buttons_sensibility_update = FALSE; static gboolean get_selected_iter (GtkBuilder *dialog, GtkTreeModel **model, GtkTreeIter *iter) { GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (WID ("xkb_layouts_selected"))); return gtk_tree_selection_get_selected (selection, model, iter); } static void set_selected_path (GtkBuilder *dialog, GtkTreePath *path) { GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (WID ("xkb_layouts_selected"))); gtk_tree_selection_select_path (selection, path); } static gint find_selected_layout_idx (GtkBuilder *dialog) { GtkTreeIter selected_iter; GtkTreeModel *model; GtkTreePath *path; gint *indices; gint rv; if (!get_selected_iter (dialog, &model, &selected_iter)) return -1; path = gtk_tree_model_get_path (model, &selected_iter); if (path == NULL) return -1; indices = gtk_tree_path_get_indices (path); rv = indices[0]; gtk_tree_path_free (path); return rv; } gchar ** xkb_layouts_get_selected_list (void) { gchar **retval; retval = g_settings_get_strv (xkb_keyboard_settings, GKBD_KEYBOARD_CONFIG_KEY_LAYOUTS); if (retval == NULL || retval[0] == NULL) { g_strfreev (retval); retval = g_strdupv (initial_config.layouts_variants); } return retval; } gint xkb_get_default_group () { return g_settings_get_int (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_DEFAULT_GROUP); } void xkb_save_default_group (gint default_group) { g_settings_set_int (xkb_desktop_settings, GKBD_DESKTOP_CONFIG_KEY_DEFAULT_GROUP, default_group); } static void xkb_layouts_enable_disable_buttons (GtkBuilder * dialog) { GtkWidget *add_layout_btn = WID ("xkb_layouts_add"); GtkWidget *show_layout_btn = WID ("xkb_layouts_show"); GtkWidget *del_layout_btn = WID ("xkb_layouts_remove"); GtkWidget *selected_layouts_tree = WID ("xkb_layouts_selected"); GtkWidget *move_up_layout_btn = WID ("xkb_layouts_move_up"); GtkWidget *move_down_layout_btn = WID ("xkb_layouts_move_down"); GtkTreeSelection *s_selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (selected_layouts_tree)); const int n_selected_selected_layouts = gtk_tree_selection_count_selected_rows (s_selection); GtkTreeModel *selected_layouts_model = gtk_tree_view_get_model (GTK_TREE_VIEW (selected_layouts_tree)); const int n_selected_layouts = gtk_tree_model_iter_n_children (selected_layouts_model, NULL); gint sidx = find_selected_layout_idx (dialog); if (disable_buttons_sensibility_update) return; gtk_widget_set_sensitive (add_layout_btn, (n_selected_layouts < max_selected_layouts || max_selected_layouts == 0)); gtk_widget_set_sensitive (del_layout_btn, (n_selected_layouts > 1) && (n_selected_selected_layouts > 0)); gtk_widget_set_sensitive (show_layout_btn, (n_selected_selected_layouts > 0)); gtk_widget_set_sensitive (move_up_layout_btn, sidx > 0); gtk_widget_set_sensitive (move_down_layout_btn, sidx >= 0 && sidx < (n_selected_layouts - 1)); } static void update_layouts_list (GtkTreeModel *model, GtkBuilder *dialog) { gboolean cont; GtkTreeIter iter; GPtrArray *array; array = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free); cont = gtk_tree_model_get_iter_first (model, &iter); while (cont) { char *id; gtk_tree_model_get (model, &iter, SEL_LAYOUT_TREE_COL_ID, &id, -1); g_ptr_array_add (array, id); cont = gtk_tree_model_iter_next (model, &iter); } g_ptr_array_add (array, NULL); xkb_layouts_set_selected_list (array->pdata); g_ptr_array_free (array, TRUE); xkb_layouts_enable_disable_buttons (dialog); } static void xkb_layouts_drag_end (GtkWidget *widget, GdkDragContext *drag_context, gpointer user_data) { update_layouts_list (gtk_tree_view_get_model (GTK_TREE_VIEW (widget)), GTK_BUILDER (user_data)); } void xkb_layouts_prepare_selected_tree (GtkBuilder * dialog) { GtkListStore *list_store; GtkWidget *tree_view = WID ("xkb_layouts_selected"); GtkTreeSelection *selection; GtkTreeViewColumn *desc_column; list_store = gtk_list_store_new (SEL_LAYOUT_N_COLS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN); text_renderer = GTK_CELL_RENDERER (gtk_cell_renderer_text_new ()); desc_column = gtk_tree_view_column_new_with_attributes (_("Layout"), text_renderer, "text", SEL_LAYOUT_TREE_COL_DESCRIPTION, "sensitive", SEL_LAYOUT_TREE_COL_ENABLED, NULL); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree_view)); gtk_tree_view_set_model (GTK_TREE_VIEW (tree_view), GTK_TREE_MODEL (list_store)); gtk_tree_view_column_set_sizing (desc_column, GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable (desc_column, TRUE); gtk_tree_view_column_set_expand (desc_column, TRUE); gtk_tree_view_append_column (GTK_TREE_VIEW (tree_view), desc_column); g_signal_connect_swapped (G_OBJECT (selection), "changed", G_CALLBACK (xkb_layouts_enable_disable_buttons), dialog); max_selected_layouts = xkl_engine_get_max_num_groups (engine); /* Setting up DnD */ gtk_tree_view_set_reorderable (GTK_TREE_VIEW (tree_view), TRUE); g_signal_connect (G_OBJECT (tree_view), "drag-end", G_CALLBACK (xkb_layouts_drag_end), dialog); } gchar * xkb_layout_description_utf8 (const gchar * visible) { char *l, *sl, *v, *sv; if (gkbd_keyboard_config_get_descriptions (config_registry, visible, &sl, &l, &sv, &v)) visible = gkbd_keyboard_config_format_full_description (l, v); return g_strstrip (g_strdup (visible)); } void xkb_layouts_fill_selected_tree (GtkBuilder * dialog) { gchar **layouts = xkb_layouts_get_selected_list (); guint i; GtkListStore *list_store = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (WID ("xkb_layouts_selected")))); /* temporarily disable the buttons' status update */ disable_buttons_sensibility_update = TRUE; gtk_list_store_clear (list_store); for (i = 0; layouts != NULL && layouts[i] != NULL; i++) { char *cur_layout = layouts[i]; gchar *utf_visible = xkb_layout_description_utf8 (cur_layout); gtk_list_store_insert_with_values (list_store, NULL, G_MAXINT, SEL_LAYOUT_TREE_COL_DESCRIPTION, utf_visible, SEL_LAYOUT_TREE_COL_ID, cur_layout, SEL_LAYOUT_TREE_COL_ENABLED, i < max_selected_layouts, -1); g_free (utf_visible); } g_strfreev (layouts); /* enable the buttons' status update */ disable_buttons_sensibility_update = FALSE; if (idx2select != -1) { GtkTreeSelection *selection = gtk_tree_view_get_selection ((GTK_TREE_VIEW (WID ("xkb_layouts_selected")))); GtkTreePath *path = gtk_tree_path_new_from_indices (idx2select, -1); gtk_tree_selection_select_path (selection, path); gtk_tree_path_free (path); idx2select = -1; } else { /* if there is nothing to select - just enable/disable the buttons, otherwise it would be done by the selection change */ xkb_layouts_enable_disable_buttons (dialog); } } static void add_default_switcher_if_necessary () { gchar **layouts_list = xkb_layouts_get_selected_list(); gchar **options_list = xkb_options_get_selected_list (); gboolean was_appended; options_list = gkbd_keyboard_config_add_default_switch_option_if_necessary (layouts_list, options_list, &was_appended); if (was_appended) xkb_options_set_selected_list (options_list); g_strfreev (options_list); } static void chooser_response (GtkDialog *chooser, int response_id, GtkBuilder *dialog) { if (response_id == GTK_RESPONSE_OK) { char *id, *name; GtkListStore *list_store; list_store = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (WID ("xkb_layouts_selected")))); id = xkb_layout_chooser_get_selected_id (chooser); name = xkb_layout_description_utf8 (id); gtk_list_store_insert_with_values (list_store, NULL, G_MAXINT, SEL_LAYOUT_TREE_COL_DESCRIPTION, name, SEL_LAYOUT_TREE_COL_ID, id, SEL_LAYOUT_TREE_COL_ENABLED, TRUE, -1); g_free (name); add_default_switcher_if_necessary (); update_layouts_list (GTK_TREE_MODEL (list_store), dialog); } xkb_layout_chooser_response (chooser, response_id); } static void add_selected_layout (GtkWidget * button, GtkBuilder * dialog) { GtkWidget *chooser; chooser = xkb_layout_choose (dialog); g_signal_connect (G_OBJECT (chooser), "response", G_CALLBACK (chooser_response), dialog); } static void show_selected_layout (GtkWidget * button, GtkBuilder * dialog) { gint idx = find_selected_layout_idx (dialog); if (idx != -1) { GtkWidget *parent = WID ("region_notebook"); GtkWidget *popup = gkbd_keyboard_drawing_dialog_new (); gkbd_keyboard_drawing_dialog_set_group (popup, config_registry, idx); gtk_window_set_transient_for (GTK_WINDOW (popup), GTK_WINDOW (gtk_widget_get_toplevel (parent))); gtk_widget_show_all (popup); } } static void remove_selected_layout (GtkWidget * button, GtkBuilder * dialog) { GtkTreeModel *model; GtkTreeIter iter; if (get_selected_iter (dialog, &model, &iter) == FALSE) return; gtk_list_store_remove (GTK_LIST_STORE (model), &iter); update_layouts_list (model, dialog); } static void move_up_selected_layout (GtkWidget * button, GtkBuilder * dialog) { GtkTreeModel *model; GtkTreeIter iter, prev; GtkTreePath *path; if (get_selected_iter (dialog, &model, &iter) == FALSE) return; prev = iter; if (!gtk_tree_model_iter_previous (model, &prev)) return; path = gtk_tree_model_get_path (model, &prev); gtk_list_store_swap (GTK_LIST_STORE (model), &iter, &prev); update_layouts_list (model, dialog); set_selected_path (dialog, path); gtk_tree_path_free (path); } static void move_down_selected_layout (GtkWidget * button, GtkBuilder * dialog) { GtkTreeModel *model; GtkTreeIter iter, next; GtkTreePath *path; if (get_selected_iter (dialog, &model, &iter) == FALSE) return; next = iter; if (!gtk_tree_model_iter_next (model, &next)) return; path = gtk_tree_model_get_path (model, &next); gtk_list_store_swap (GTK_LIST_STORE (model), &iter, &next); update_layouts_list (model, dialog); set_selected_path (dialog, path); gtk_tree_path_free (path); } void xkb_layouts_register_buttons_handlers (GtkBuilder * dialog) { g_signal_connect (G_OBJECT (WID ("xkb_layouts_add")), "clicked", G_CALLBACK (add_selected_layout), dialog); g_signal_connect (G_OBJECT (WID ("xkb_layouts_show")), "clicked", G_CALLBACK (show_selected_layout), dialog); g_signal_connect (G_OBJECT (WID ("xkb_layouts_remove")), "clicked", G_CALLBACK (remove_selected_layout), dialog); g_signal_connect (G_OBJECT (WID ("xkb_layouts_move_up")), "clicked", G_CALLBACK (move_up_selected_layout), dialog); g_signal_connect (G_OBJECT (WID ("xkb_layouts_move_down")), "clicked", G_CALLBACK (move_down_selected_layout), dialog); } static void xkb_layouts_update_list (GSettings * settings, gchar * key, GtkBuilder * dialog) { if (strcmp (key, GKBD_KEYBOARD_CONFIG_KEY_LAYOUTS) == 0) { xkb_layouts_fill_selected_tree (dialog); enable_disable_restoring (dialog); } } void xkb_layouts_register_conf_listener (GtkBuilder * dialog) { g_signal_connect (xkb_keyboard_settings, "changed", G_CALLBACK (xkb_layouts_update_list), dialog); }
474
./cinnamon-control-center/panels/sound-nua/cc-sound-panel.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2008 Red Hat, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "config.h" #include <libintl.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <glib/gi18n-lib.h> #include <glib.h> #include <gtk/gtk.h> #include <pulse/pulseaudio.h> #include "cc-sound-panel.h" #include "gvc-mixer-dialog.h" G_DEFINE_DYNAMIC_TYPE (CcSoundNuaPanel, cc_sound_panel, CC_TYPE_PANEL) enum { PROP_0, PROP_ARGV }; static void cc_sound_panel_finalize (GObject *object); static void cc_sound_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { CcSoundNuaPanel *self = CC_SOUND_PANEL (object); switch (property_id) { case PROP_ARGV: { gchar **args; args = g_value_get_boxed (value); if (args && args[0]) { gvc_mixer_dialog_set_page (self->dialog, args[0]); } break; } default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_sound_panel_class_init (CcSoundNuaPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = cc_sound_panel_finalize; object_class->set_property = cc_sound_panel_set_property; g_object_class_override_property (object_class, PROP_ARGV, "argv"); } static void cc_sound_panel_class_finalize (CcSoundNuaPanelClass *klass) { } static void cc_sound_panel_finalize (GObject *object) { CcSoundNuaPanel *panel = CC_SOUND_PANEL (object); if (panel->dialog != NULL) panel->dialog = NULL; if (panel->connecting_label != NULL) panel->connecting_label = NULL; if (panel->control != NULL) { g_object_unref (panel->control); panel->control = NULL; } G_OBJECT_CLASS (cc_sound_panel_parent_class)->finalize (object); } static void cc_sound_panel_init (CcSoundNuaPanel *self) { gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (), ICON_DATA_DIR); gtk_window_set_default_icon_name ("multimedia-volume-control"); self->control = gvc_mixer_control_new ("Cinnamon Volume Control Dialog"); gvc_mixer_control_open (self->control); self->dialog = gvc_mixer_dialog_new (self->control); gtk_container_add (GTK_CONTAINER (self), GTK_WIDGET (self->dialog)); gtk_widget_show (GTK_WIDGET (self->dialog)); } void cc_sound_panel_register (GIOModule *module) { cc_sound_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_SOUND_PANEL, "sound", 0); } /* GIO extension stuff */ void g_io_module_load (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); /* register the panel */ cc_sound_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
475
./cinnamon-control-center/panels/sound-nua/gvc-balance-bar.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2008 William Jon McCann * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <glib.h> #include <glib/gi18n-lib.h> #include <gtk/gtk.h> #include <canberra-gtk.h> #include <pulse/pulseaudio.h> #include "gvc-balance-bar.h" #include "gvc-channel-map-private.h" #define SCALE_SIZE 220 #define ADJUSTMENT_MAX_NORMAL 65536.0 /* PA_VOLUME_NORM */ #define GVC_BALANCE_BAR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_BALANCE_BAR, GvcBalanceBarPrivate)) struct GvcBalanceBarPrivate { GvcChannelMap *channel_map; GvcBalanceType btype; GtkWidget *scale_box; GtkWidget *start_box; GtkWidget *end_box; GtkWidget *label; GtkWidget *scale; GtkAdjustment *adjustment; GtkSizeGroup *size_group; gboolean symmetric; gboolean click_lock; }; enum { PROP_0, PROP_CHANNEL_MAP, PROP_BALANCE_TYPE, }; static void gvc_balance_bar_class_init (GvcBalanceBarClass *klass); static void gvc_balance_bar_init (GvcBalanceBar *balance_bar); static void gvc_balance_bar_finalize (GObject *object); static gboolean on_scale_button_press_event (GtkWidget *widget, GdkEventButton *event, GvcBalanceBar *bar); static gboolean on_scale_button_release_event (GtkWidget *widget, GdkEventButton *event, GvcBalanceBar *bar); static gboolean on_scale_scroll_event (GtkWidget *widget, GdkEventScroll *event, GvcBalanceBar *bar); static void on_adjustment_value_changed (GtkAdjustment *adjustment, GvcBalanceBar *bar); G_DEFINE_TYPE (GvcBalanceBar, gvc_balance_bar, GTK_TYPE_HBOX) static GtkWidget * _scale_box_new (GvcBalanceBar *bar) { GvcBalanceBarPrivate *priv = bar->priv; GtkWidget *box; GtkWidget *sbox; GtkWidget *ebox; GtkAdjustment *adjustment = bar->priv->adjustment; char *str_lower, *str_upper; gdouble lower, upper; bar->priv->scale_box = box = gtk_box_new (FALSE, 6); priv->scale = gtk_hscale_new (priv->adjustment); gtk_widget_set_size_request (priv->scale, SCALE_SIZE, -1); gtk_scale_set_has_origin (GTK_SCALE (priv->scale), FALSE); gtk_widget_set_name (priv->scale, "balance-bar-scale"); gtk_rc_parse_string ("style \"balance-bar-scale-style\" {\n" " GtkScale::trough-side-details = 0\n" "}\n" "widget \"*.balance-bar-scale\" style : rc \"balance-bar-scale-style\"\n"); bar->priv->start_box = sbox = gtk_box_new (FALSE, 6); gtk_box_pack_start (GTK_BOX (box), sbox, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (sbox), priv->label, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (box), priv->scale, TRUE, TRUE, 0); switch (bar->priv->btype) { case BALANCE_TYPE_RL: str_lower = g_strdup_printf ("<small>%s</small>", C_("balance", "Left")); str_upper = g_strdup_printf ("<small>%s</small>", C_("balance", "Right")); break; case BALANCE_TYPE_FR: str_lower = g_strdup_printf ("<small>%s</small>", C_("balance", "Rear")); str_upper = g_strdup_printf ("<small>%s</small>", C_("balance", "Front")); break; case BALANCE_TYPE_LFE: str_lower = g_strdup_printf ("<small>%s</small>", C_("balance", "Minimum")); str_upper = g_strdup_printf ("<small>%s</small>", C_("balance", "Maximum")); break; default: g_assert_not_reached (); } lower = gtk_adjustment_get_lower (adjustment); gtk_scale_add_mark (GTK_SCALE (priv->scale), lower, GTK_POS_BOTTOM, str_lower); g_free (str_lower); upper = gtk_adjustment_get_upper (adjustment); gtk_scale_add_mark (GTK_SCALE (priv->scale), upper, GTK_POS_BOTTOM, str_upper); g_free (str_upper); if (bar->priv->btype != BALANCE_TYPE_LFE) { gtk_scale_add_mark (GTK_SCALE (priv->scale), (upper - lower)/2 + lower, GTK_POS_BOTTOM, NULL); } bar->priv->end_box = ebox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6); gtk_box_pack_start (GTK_BOX (box), ebox, FALSE, FALSE, 0); ca_gtk_widget_disable_sounds (bar->priv->scale, FALSE); gtk_widget_add_events (bar->priv->scale, GDK_SCROLL_MASK); g_signal_connect (G_OBJECT (bar->priv->scale), "button-press-event", G_CALLBACK (on_scale_button_press_event), bar); g_signal_connect (G_OBJECT (bar->priv->scale), "button-release-event", G_CALLBACK (on_scale_button_release_event), bar); g_signal_connect (G_OBJECT (bar->priv->scale), "scroll-event", G_CALLBACK (on_scale_scroll_event), bar); if (bar->priv->size_group != NULL) { gtk_size_group_add_widget (bar->priv->size_group, sbox); if (bar->priv->symmetric) { gtk_size_group_add_widget (bar->priv->size_group, ebox); } } gtk_scale_set_draw_value (GTK_SCALE (priv->scale), FALSE); return box; } void gvc_balance_bar_set_size_group (GvcBalanceBar *bar, GtkSizeGroup *group, gboolean symmetric) { g_return_if_fail (GVC_IS_BALANCE_BAR (bar)); bar->priv->size_group = group; bar->priv->symmetric = symmetric; if (bar->priv->size_group != NULL) { gtk_size_group_add_widget (bar->priv->size_group, bar->priv->start_box); if (bar->priv->symmetric) { gtk_size_group_add_widget (bar->priv->size_group, bar->priv->end_box); } } gtk_widget_queue_draw (GTK_WIDGET (bar)); } static const char * btype_to_string (guint btype) { switch (btype) { case BALANCE_TYPE_RL: return "Balance"; case BALANCE_TYPE_FR: return "Fade"; break; case BALANCE_TYPE_LFE: return "LFE"; default: g_assert_not_reached (); } return NULL; } static void update_level_from_map (GvcBalanceBar *bar, GvcChannelMap *map) { const gdouble *volumes; gdouble val; g_debug ("Volume changed (for %s bar)", btype_to_string (bar->priv->btype)); volumes = gvc_channel_map_get_volume (map); switch (bar->priv->btype) { case BALANCE_TYPE_RL: val = volumes[BALANCE]; break; case BALANCE_TYPE_FR: val = volumes[FADE]; break; case BALANCE_TYPE_LFE: val = volumes[LFE]; break; default: g_assert_not_reached (); } gtk_adjustment_set_value (bar->priv->adjustment, val); } static void on_channel_map_volume_changed (GvcChannelMap *map, gboolean set, GvcBalanceBar *bar) { update_level_from_map (bar, map); } static void gvc_balance_bar_set_channel_map (GvcBalanceBar *bar, GvcChannelMap *map) { g_return_if_fail (GVC_BALANCE_BAR (bar)); if (bar->priv->channel_map != NULL) { g_signal_handlers_disconnect_by_func (G_OBJECT (bar->priv->channel_map), on_channel_map_volume_changed, bar); g_object_unref (bar->priv->channel_map); } bar->priv->channel_map = g_object_ref (map); update_level_from_map (bar, map); g_signal_connect (G_OBJECT (map), "volume-changed", G_CALLBACK (on_channel_map_volume_changed), bar); g_object_notify (G_OBJECT (bar), "channel-map"); } static void gvc_balance_bar_set_balance_type (GvcBalanceBar *bar, GvcBalanceType btype) { GtkWidget *frame; g_return_if_fail (GVC_BALANCE_BAR (bar)); bar->priv->btype = btype; if (bar->priv->btype != BALANCE_TYPE_LFE) { bar->priv->adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, -1.0, 1.0, 0.5, 0.5, 0.0)); } else { bar->priv->adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, ADJUSTMENT_MAX_NORMAL, ADJUSTMENT_MAX_NORMAL/100.0, ADJUSTMENT_MAX_NORMAL/10.0, 0.0)); } g_object_ref_sink (bar->priv->adjustment); g_signal_connect (bar->priv->adjustment, "value-changed", G_CALLBACK (on_adjustment_value_changed), bar); switch (btype) { case BALANCE_TYPE_RL: bar->priv->label = gtk_label_new_with_mnemonic (_("_Balance:")); break; case BALANCE_TYPE_FR: bar->priv->label = gtk_label_new_with_mnemonic (_("_Fade:")); break; case BALANCE_TYPE_LFE: bar->priv->label = gtk_label_new_with_mnemonic (_("_Subwoofer:")); break; default: g_assert_not_reached (); } gtk_misc_set_alignment (GTK_MISC (bar->priv->label), 0.0, 0.0); /* frame */ frame = gtk_frame_new (NULL); gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE); gtk_container_add (GTK_CONTAINER (bar), frame); /* box with scale */ bar->priv->scale_box = _scale_box_new (bar); gtk_container_add (GTK_CONTAINER (frame), bar->priv->scale_box); gtk_widget_show_all (frame); gtk_widget_set_direction (bar->priv->scale, GTK_TEXT_DIR_LTR); gtk_label_set_mnemonic_widget (GTK_LABEL (bar->priv->label), bar->priv->scale); g_object_notify (G_OBJECT (bar), "balance-type"); } static void gvc_balance_bar_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GvcBalanceBar *self = GVC_BALANCE_BAR (object); switch (prop_id) { case PROP_CHANNEL_MAP: gvc_balance_bar_set_channel_map (self, g_value_get_object (value)); break; case PROP_BALANCE_TYPE: gvc_balance_bar_set_balance_type (self, g_value_get_int (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gvc_balance_bar_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GvcBalanceBar *self = GVC_BALANCE_BAR (object); switch (prop_id) { case PROP_CHANNEL_MAP: g_value_set_object (value, self->priv->channel_map); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GObject * gvc_balance_bar_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_params) { return G_OBJECT_CLASS (gvc_balance_bar_parent_class)->constructor (type, n_construct_properties, construct_params); } static void gvc_balance_bar_class_init (GvcBalanceBarClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->constructor = gvc_balance_bar_constructor; object_class->finalize = gvc_balance_bar_finalize; object_class->set_property = gvc_balance_bar_set_property; object_class->get_property = gvc_balance_bar_get_property; g_object_class_install_property (object_class, PROP_CHANNEL_MAP, g_param_spec_object ("channel-map", "channel map", "The channel map", GVC_TYPE_CHANNEL_MAP, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_BALANCE_TYPE, g_param_spec_int ("balance-type", "balance type", "Whether the balance is right-left or front-rear", BALANCE_TYPE_RL, NUM_BALANCE_TYPES - 1, BALANCE_TYPE_RL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY)); g_type_class_add_private (klass, sizeof (GvcBalanceBarPrivate)); } static gboolean on_scale_button_press_event (GtkWidget *widget, GdkEventButton *event, GvcBalanceBar *bar) { bar->priv->click_lock = TRUE; return FALSE; } static gboolean on_scale_button_release_event (GtkWidget *widget, GdkEventButton *event, GvcBalanceBar *bar) { bar->priv->click_lock = FALSE; return FALSE; } static gboolean on_scale_scroll_event (GtkWidget *widget, GdkEventScroll *event, GvcBalanceBar *bar) { gdouble value; gdouble dx, dy; value = gtk_adjustment_get_value (bar->priv->adjustment); if (!gdk_event_get_scroll_deltas ((GdkEvent*)event, &dx, &dy)) { dx = 0.0; dy = 0.0; switch (event->direction) { case GDK_SCROLL_UP: case GDK_SCROLL_RIGHT: dy = 1.0; break; case GDK_SCROLL_DOWN: case GDK_SCROLL_LEFT: dy = -1.0; break; default: ; } } if (bar->priv->btype == BALANCE_TYPE_LFE) { if (dy > 0) { if (value + dy * ADJUSTMENT_MAX_NORMAL/100.0 > ADJUSTMENT_MAX_NORMAL) value = ADJUSTMENT_MAX_NORMAL; else value = value + dy * ADJUSTMENT_MAX_NORMAL/100.0; } else if (dy < 0) { if (value + dy * ADJUSTMENT_MAX_NORMAL/100.0 < 0) value = 0.0; else value = value + dy * ADJUSTMENT_MAX_NORMAL/100.0; } } else { if (dy > 0) { if (value + dy * 0.01 > 1.0) value = 1.0; else value = value + dy * 0.01; } else if (dy < 0) { if (value + dy * 0.01 < -1.0) value = -1.0; else value = value + dy * 0.01; } } gtk_adjustment_set_value (bar->priv->adjustment, value); return TRUE; } /* FIXME remove when we depend on a newer PA */ static pa_cvolume * gvc_pa_cvolume_set_position (pa_cvolume *cv, const pa_channel_map *map, pa_channel_position_t t, pa_volume_t v) { unsigned c; gboolean good = FALSE; g_assert(cv); g_assert(map); g_return_val_if_fail(pa_cvolume_compatible_with_channel_map(cv, map), NULL); g_return_val_if_fail(t < PA_CHANNEL_POSITION_MAX, NULL); for (c = 0; c < map->channels; c++) if (map->map[c] == t) { cv->values[c] = v; good = TRUE; } return good ? cv : NULL; } static void on_adjustment_value_changed (GtkAdjustment *adjustment, GvcBalanceBar *bar) { gdouble val; pa_cvolume cv; const pa_channel_map *pa_map; if (bar->priv->channel_map == NULL) return; cv = *gvc_channel_map_get_cvolume (bar->priv->channel_map); val = gtk_adjustment_get_value (adjustment); pa_map = gvc_channel_map_get_pa_channel_map (bar->priv->channel_map); switch (bar->priv->btype) { case BALANCE_TYPE_RL: pa_cvolume_set_balance (&cv, pa_map, val); break; case BALANCE_TYPE_FR: pa_cvolume_set_fade (&cv, pa_map, val); break; case BALANCE_TYPE_LFE: gvc_pa_cvolume_set_position (&cv, pa_map, PA_CHANNEL_POSITION_LFE, val); break; } gvc_channel_map_volume_changed (bar->priv->channel_map, &cv, TRUE); } static void gvc_balance_bar_init (GvcBalanceBar *bar) { bar->priv = GVC_BALANCE_BAR_GET_PRIVATE (bar); } static void gvc_balance_bar_finalize (GObject *object) { GvcBalanceBar *bar; g_return_if_fail (object != NULL); g_return_if_fail (GVC_IS_BALANCE_BAR (object)); bar = GVC_BALANCE_BAR (object); g_return_if_fail (bar->priv != NULL); if (bar->priv->channel_map != NULL) { g_signal_handlers_disconnect_by_func (G_OBJECT (bar->priv->channel_map), on_channel_map_volume_changed, bar); g_object_unref (bar->priv->channel_map); } G_OBJECT_CLASS (gvc_balance_bar_parent_class)->finalize (object); } void gvc_balance_bar_set_map (GvcBalanceBar* self, const GvcChannelMap *channel_map) { g_object_set (G_OBJECT (self), "channel-map", channel_map, NULL); } GtkWidget * gvc_balance_bar_new (GvcBalanceType btype) { GObject *bar; bar = g_object_new (GVC_TYPE_BALANCE_BAR, "balance-type", btype, NULL); return GTK_WIDGET (bar); }
476
./cinnamon-control-center/panels/sound-nua/gvc-mixer-dialog.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2008 William Jon McCann * Copyright (C) 2012 Conor Curran * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <glib.h> #include <glib/gi18n-lib.h> #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> #include <pulse/pulseaudio.h> #include "gvc-channel-bar.h" #include "gvc-balance-bar.h" #include "gvc-combo-box.h" #include "gvc-mixer-control.h" #include "gvc-mixer-card.h" #include "gvc-mixer-ui-device.h" #include "gvc-mixer-sink.h" #include "gvc-mixer-source.h" #include "gvc-mixer-source-output.h" #include "gvc-mixer-dialog.h" #include "gvc-sound-theme-chooser.h" #include "gvc-level-bar.h" #include "gvc-speaker-test.h" #include "gvc-mixer-control-private.h" #define SCALE_SIZE 128 #define GVC_MIXER_DIALOG_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_DIALOG, GvcMixerDialogPrivate)) struct GvcMixerDialogPrivate { GvcMixerControl *mixer_control; GHashTable *bars; GtkWidget *notebook; GtkWidget *output_bar; GtkWidget *input_bar; GtkWidget *input_level_bar; GtkWidget *effects_bar; GtkWidget *output_stream_box; GtkWidget *sound_effects_box; GtkWidget *hw_box; GtkWidget *hw_treeview; GtkWidget *hw_settings_box; GtkWidget *hw_profile_combo; GtkWidget *input_box; GtkWidget *output_box; GtkWidget *applications_box; GtkWidget *no_apps_label; GtkWidget *output_treeview; GtkWidget *output_settings_box; GtkWidget *output_balance_bar; GtkWidget *output_fade_bar; GtkWidget *output_lfe_bar; GtkWidget *output_profile_combo; GtkWidget *input_profile_combo; GtkWidget *input_treeview; GtkWidget *input_settings_box; GtkWidget *sound_theme_chooser; GtkWidget *click_feedback_button; GtkWidget *audible_bell_button; GtkSizeGroup *size_group; GtkWidget *selected_output_label; GtkWidget *selected_input_label; GtkWidget *test_output_button; GSettings *indicator_settings; gdouble last_input_peak; guint num_apps; }; enum { NAME_COLUMN, DEVICE_COLUMN, ACTIVE_COLUMN, ID_COLUMN, SPEAKERS_COLUMN, ICON_COLUMN, NUM_COLUMNS }; enum { HW_ID_COLUMN, HW_ICON_COLUMN, HW_NAME_COLUMN, HW_STATUS_COLUMN, HW_PROFILE_COLUMN, HW_PROFILE_HUMAN_COLUMN, HW_SENSITIVE_COLUMN, HW_NUM_COLUMNS }; enum { PROP_0, PROP_MIXER_CONTROL }; static void gvc_mixer_dialog_class_init (GvcMixerDialogClass *klass); static void gvc_mixer_dialog_init (GvcMixerDialog *mixer_dialog); static void gvc_mixer_dialog_finalize (GObject *object); static void bar_set_stream (GvcMixerDialog *dialog, GtkWidget *bar, GvcMixerStream *stream); static void on_adjustment_value_changed (GtkAdjustment *adjustment, GvcMixerDialog *dialog); static void on_control_output_added (GvcMixerControl *control, guint id, GvcMixerDialog *dialog); static void on_control_active_output_update (GvcMixerControl *control, guint id, GvcMixerDialog *dialog); static void on_control_active_input_update (GvcMixerControl *control, guint id, GvcMixerDialog *dialog); G_DEFINE_TYPE (GvcMixerDialog, gvc_mixer_dialog, GTK_TYPE_VBOX) static void update_description (GvcMixerDialog *dialog, guint column, const char *value, GvcMixerStream *stream) { GtkTreeModel *model; GtkTreeIter iter; guint id; if (GVC_IS_MIXER_SOURCE (stream)) model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview)); else if (GVC_IS_MIXER_SINK (stream)) model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview)); else g_assert_not_reached (); if (gtk_tree_model_get_iter_first (model, &iter) == FALSE){ g_warning ("The tree is empty => Cannot update the description"); return; } id = gvc_mixer_stream_get_id (stream); do { guint current_id; gtk_tree_model_get (model, &iter, ID_COLUMN, &current_id, -1); if (id != current_id) continue; gtk_list_store_set (GTK_LIST_STORE (model), &iter, column, value, -1); break; } while (gtk_tree_model_iter_next (model, &iter)); } static void profile_selection_changed (GvcComboBox *combo_box, const char *profile, GvcMixerDialog *dialog) { g_debug ("profile_selection_changed - %s", profile); GvcMixerUIDevice *out; out = g_object_get_data (G_OBJECT (combo_box), "uidevice"); if (out == NULL) { g_warning ("Could not find Output for profile combo box"); return; } g_debug (" \n on profile selection changed on output with \n description %s \n origin %s \n id %i \n \n", gvc_mixer_ui_device_get_description (out), gvc_mixer_ui_device_get_origin (out), gvc_mixer_ui_device_get_id (out)); if (gvc_mixer_control_change_profile_on_selected_device (dialog->priv->mixer_control, out, profile) == FALSE) { g_warning ("Could not change profile on device %s", gvc_mixer_ui_device_get_description (out)); } } #define DECAY_STEP .15 static void update_input_peak (GvcMixerDialog *dialog, gdouble v) { GtkAdjustment *adj; if (dialog->priv->last_input_peak >= DECAY_STEP) { if (v < dialog->priv->last_input_peak - DECAY_STEP) { v = dialog->priv->last_input_peak - DECAY_STEP; } } dialog->priv->last_input_peak = v; adj = gvc_level_bar_get_peak_adjustment (GVC_LEVEL_BAR (dialog->priv->input_level_bar)); if (v >= 0) { gtk_adjustment_set_value (adj, v); } else { gtk_adjustment_set_value (adj, 0.0); } } static void update_input_meter (GvcMixerDialog *dialog, uint32_t source_index, uint32_t sink_input_idx, double v) { update_input_peak (dialog, v); } static void on_monitor_suspended_callback (pa_stream *s, void *userdata) { GvcMixerDialog *dialog; dialog = userdata; if (pa_stream_is_suspended (s)) { g_debug ("Stream suspended"); update_input_meter (dialog, pa_stream_get_device_index (s), PA_INVALID_INDEX, -1); } } static void on_monitor_read_callback (pa_stream *s, size_t length, void *userdata) { GvcMixerDialog *dialog; const void *data; double v; dialog = userdata; if (pa_stream_peek (s, &data, &length) < 0) { g_warning ("Failed to read data from stream"); return; } assert (length > 0); assert (length % sizeof (float) == 0); v = ((const float *) data)[length / sizeof (float) -1]; pa_stream_drop (s); if (v < 0) { v = 0; } if (v > 1) { v = 1; } update_input_meter (dialog, pa_stream_get_device_index (s), pa_stream_get_monitor_stream (s), v); } static void create_monitor_stream_for_source (GvcMixerDialog *dialog, GvcMixerStream *stream) { pa_stream *s; char t[16]; pa_buffer_attr attr; pa_sample_spec ss; pa_context *context; int res; pa_proplist *proplist; gboolean has_monitor; if (stream == NULL) { g_debug ("\n create_monitor_stream_for_source - stream is null - returning\n"); return; } has_monitor = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (stream), "has-monitor")); if (has_monitor != FALSE) { g_debug ("\n create_monitor_stream_for_source, has monitor is not false - returning \n"); return; } g_debug ("Create monitor for %u", gvc_mixer_stream_get_index (stream)); context = gvc_mixer_control_get_pa_context (dialog->priv->mixer_control); if (pa_context_get_server_protocol_version (context) < 13) { g_debug ("\n create_monitor_stream_for_source - protocol version is less 13 \n"); return; } ss.channels = 1; ss.format = PA_SAMPLE_FLOAT32; ss.rate = 25; memset (&attr, 0, sizeof (attr)); attr.fragsize = sizeof (float); attr.maxlength = (uint32_t) -1; snprintf (t, sizeof (t), "%u", gvc_mixer_stream_get_index (stream)); proplist = pa_proplist_new (); pa_proplist_sets (proplist, PA_PROP_APPLICATION_ID, "org.gnome.VolumeControl"); s = pa_stream_new_with_proplist (context, _("Peak detect"), &ss, NULL, proplist); pa_proplist_free (proplist); if (s == NULL) { g_warning ("Failed to create monitoring stream"); return; } pa_stream_set_read_callback (s, on_monitor_read_callback, dialog); pa_stream_set_suspended_callback (s, on_monitor_suspended_callback, dialog); res = pa_stream_connect_record (s, t, &attr, (pa_stream_flags_t) (PA_STREAM_DONT_MOVE |PA_STREAM_PEAK_DETECT |PA_STREAM_ADJUST_LATENCY)); if (res < 0) { g_warning ("Failed to connect monitoring stream"); pa_stream_unref (s); } else { g_object_set_data (G_OBJECT (stream), "has-monitor", GINT_TO_POINTER (TRUE)); g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "pa_stream", s); g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "stream", stream); } } static void stop_monitor_stream_for_source (GvcMixerDialog *dialog) { pa_stream *s; pa_context *context; int res = 0; GvcMixerStream *stream; stream = g_object_get_data (G_OBJECT (dialog->priv->input_level_bar), "stream"); if (stream == NULL){ g_debug ("\n stop_monitor_stream_for_source - gvcstream is null - returning \n"); return; } else{ g_debug ("\n stop_monitor_stream_for_source - gvcstream is not null - continue \n"); } s = g_object_get_data (G_OBJECT (dialog->priv->input_level_bar), "pa_stream"); if (s != NULL){ res = pa_stream_disconnect (s); if (res == 0) { g_debug("stream has been disconnected"); pa_stream_unref (s); } g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "pa_stream", NULL); } context = gvc_mixer_control_get_pa_context (dialog->priv->mixer_control); if (pa_context_get_server_protocol_version (context) < 13) { return; } if (res == 0) { g_object_set_data (G_OBJECT (stream), "has-monitor", GINT_TO_POINTER (FALSE)); } g_debug ("Stopping monitor for %u", pa_stream_get_index (s)); g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "stream", NULL); } static void gvc_mixer_dialog_set_mixer_control (GvcMixerDialog *dialog, GvcMixerControl *control) { g_return_if_fail (GVC_MIXER_DIALOG (dialog)); g_return_if_fail (GVC_IS_MIXER_CONTROL (control)); g_object_ref (control); if (dialog->priv->mixer_control != NULL) { g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, G_CALLBACK (on_control_active_output_update), dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, G_CALLBACK (on_control_active_input_update), dialog); g_object_unref (dialog->priv->mixer_control); } dialog->priv->mixer_control = control; g_signal_connect (dialog->priv->mixer_control, "active-output-update", G_CALLBACK (on_control_active_output_update), dialog); g_signal_connect (dialog->priv->mixer_control, "active-input-update", G_CALLBACK (on_control_active_input_update), dialog); g_object_notify (G_OBJECT (dialog), "mixer-control"); } static GvcMixerControl * gvc_mixer_dialog_get_mixer_control (GvcMixerDialog *dialog) { g_return_val_if_fail (GVC_IS_MIXER_DIALOG (dialog), NULL); return dialog->priv->mixer_control; } static void gvc_mixer_dialog_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GvcMixerDialog *self = GVC_MIXER_DIALOG (object); switch (prop_id) { case PROP_MIXER_CONTROL: gvc_mixer_dialog_set_mixer_control (self, g_value_get_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gvc_mixer_dialog_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GvcMixerDialog *self = GVC_MIXER_DIALOG (object); switch (prop_id) { case PROP_MIXER_CONTROL: g_value_set_object (value, gvc_mixer_dialog_get_mixer_control (self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void on_adjustment_value_changed (GtkAdjustment *adjustment, GvcMixerDialog *dialog) { GvcMixerStream *stream; stream = g_object_get_data (G_OBJECT (adjustment), "gvc-mixer-dialog-stream"); if (stream != NULL) { GObject *bar; gdouble volume, rounded; char *name; volume = gtk_adjustment_get_value (adjustment); rounded = round (volume); bar = g_object_get_data (G_OBJECT (adjustment), "gvc-mixer-dialog-bar"); g_object_get (bar, "name", &name, NULL); g_debug ("Setting stream volume %lf (rounded: %lf) for bar '%s'", volume, rounded, name); g_free (name); /* FIXME would need to do that in the balance bar really... */ /* Make sure we do not unmute muted streams, there's a button for that */ if (volume == 0.0) gvc_mixer_stream_set_is_muted (stream, TRUE); /* Only push the volume if it's actually changed */ if (gvc_mixer_stream_set_volume(stream, (pa_volume_t) rounded) != FALSE) gvc_mixer_stream_push_volume (stream); } } static void on_bar_is_muted_notify (GObject *object, GParamSpec *pspec, GvcMixerDialog *dialog) { gboolean is_muted; GvcMixerStream *stream; is_muted = gvc_channel_bar_get_is_muted (GVC_CHANNEL_BAR (object)); stream = g_object_get_data (object, "gvc-mixer-dialog-stream"); if (stream != NULL) { gvc_mixer_stream_change_is_muted (stream, is_muted); } else { char *name; g_object_get (object, "name", &name, NULL); g_warning ("Unable to find stream for bar '%s'", name); g_free (name); } } static GtkWidget * lookup_bar_for_stream (GvcMixerDialog *dialog, GvcMixerStream *stream) { GtkWidget *bar; bar = g_hash_table_lookup (dialog->priv->bars, GUINT_TO_POINTER (gvc_mixer_stream_get_id (stream))); return bar; } // TODO // Do we need this ? // UI devices now pull description material mainly for the card ports. // Therefore the need for stream description dynamic changes more than ever seems unneccessary. static void on_stream_description_notify (GvcMixerStream *stream, GParamSpec *pspec, GvcMixerDialog *dialog) { update_description (dialog, NAME_COLUMN, gvc_mixer_stream_get_description (stream), stream); } static void on_stream_volume_notify (GObject *object, GParamSpec *pspec, GvcMixerDialog *dialog) { GvcMixerStream *stream; GtkWidget *bar; GtkAdjustment *adj; stream = GVC_MIXER_STREAM (object); bar = lookup_bar_for_stream (dialog, stream); if (bar == NULL) { if (stream == gvc_mixer_control_get_default_sink(dialog->priv->mixer_control)) { bar = dialog->priv->output_bar; } else if(stream == gvc_mixer_control_get_default_source(dialog->priv->mixer_control)) { bar = dialog->priv->input_bar; } else{ g_warning ("Unable to find bar for stream %s in on_stream_volume_notify()", gvc_mixer_stream_get_name (stream)); return; } } adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (bar))); g_signal_handlers_block_by_func (adj, on_adjustment_value_changed, dialog); gtk_adjustment_set_value (adj, gvc_mixer_stream_get_volume (stream)); g_signal_handlers_unblock_by_func (adj, on_adjustment_value_changed, dialog); } static void on_stream_is_muted_notify (GObject *object, GParamSpec *pspec, GvcMixerDialog *dialog) { GvcMixerStream *stream; GtkWidget *bar; gboolean is_muted; stream = GVC_MIXER_STREAM (object); bar = lookup_bar_for_stream (dialog, stream); if (bar == NULL) { if (stream == gvc_mixer_control_get_default_sink(dialog->priv->mixer_control)) { bar = dialog->priv->output_bar; } else if(stream == gvc_mixer_control_get_default_source(dialog->priv->mixer_control)) { bar = dialog->priv->input_bar; } else{ g_warning ("Unable to find bar for stream %s in on_stream_muted_notify()", gvc_mixer_stream_get_name (stream)); return; } } is_muted = gvc_mixer_stream_get_is_muted (stream); gvc_channel_bar_set_is_muted (GVC_CHANNEL_BAR (bar), is_muted); if (stream == gvc_mixer_control_get_default_sink (dialog->priv->mixer_control)) { gtk_widget_set_sensitive (dialog->priv->applications_box, !is_muted); } } static void save_bar_for_stream (GvcMixerDialog *dialog, GvcMixerStream *stream, GtkWidget *bar) { g_debug ("\n saving bar for stream %s", gvc_mixer_stream_get_name (stream)); g_hash_table_insert (dialog->priv->bars, GUINT_TO_POINTER (gvc_mixer_stream_get_id (stream)), bar); } static GtkWidget * create_bar (GvcMixerDialog *dialog, gboolean add_to_size_group, gboolean symmetric) { GtkWidget *bar; bar = gvc_channel_bar_new (); gtk_widget_set_sensitive (bar, FALSE); if (add_to_size_group && dialog->priv->size_group != NULL) { gvc_channel_bar_set_size_group (GVC_CHANNEL_BAR (bar), dialog->priv->size_group, symmetric); } gvc_channel_bar_set_orientation (GVC_CHANNEL_BAR (bar), GTK_ORIENTATION_HORIZONTAL); gvc_channel_bar_set_show_mute (GVC_CHANNEL_BAR (bar), TRUE); g_signal_connect (bar, "notify::is-muted", G_CALLBACK (on_bar_is_muted_notify), dialog); return bar; } static GtkWidget * create_app_bar (GvcMixerDialog *dialog, const char *name, const char *icon_name) { GtkWidget *bar; bar = create_bar (dialog, FALSE, FALSE); gvc_channel_bar_set_ellipsize (GVC_CHANNEL_BAR (bar), TRUE); gvc_channel_bar_set_icon_name (GVC_CHANNEL_BAR (bar), icon_name); if (name == NULL || strchr (name, '_') == NULL) { gvc_channel_bar_set_name (GVC_CHANNEL_BAR (bar), name); } else { char **tokens, *escaped; tokens = g_strsplit (name, "_", -1); escaped = g_strjoinv ("__", tokens); g_strfreev (tokens); gvc_channel_bar_set_name (GVC_CHANNEL_BAR (bar), escaped); g_free (escaped); } return bar; } static gint test_it = 0; /* active_input_update * Handle input update change from the backend (control). * Trust the backend whole-heartedly to deliver the correct input * i.e. keep it MVC. */ static void active_input_update (GvcMixerDialog *dialog, GvcMixerUIDevice *active_input) { g_debug ("\n active_input_update %s \n", gvc_mixer_ui_device_get_description (active_input)); // First make sure the correct UI device is selected. GtkTreeModel *model; GtkTreeIter iter; model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview)); if (gtk_tree_model_get_iter_first (model, &iter) == FALSE){ g_warning ("The tree is empty => we have no devices so cannot set the active input"); return; } do { gboolean is_selected = FALSE; gint id; gtk_tree_model_get (model, &iter, ID_COLUMN, &id, -1); is_selected = id == gvc_mixer_ui_device_get_id (active_input); gtk_list_store_set (GTK_LIST_STORE (model), &iter, ACTIVE_COLUMN, is_selected, -1); if (is_selected) { GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (dialog->priv->input_treeview)); gtk_tree_selection_select_iter (selection, &iter); } }while (gtk_tree_model_iter_next (model, &iter)); // Not ideal but for now destroy the combo and recreate below. if (dialog->priv->input_profile_combo != NULL) { gtk_container_remove (GTK_CONTAINER (dialog->priv->input_settings_box), dialog->priv->input_profile_combo); dialog->priv->input_profile_combo = NULL; } GvcMixerStream *stream; GtkAdjustment *adj; stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control, active_input); if (stream == NULL) { g_warning ("active_input_update - couldn't find a stream from the supposed active input"); gtk_widget_set_sensitive (dialog->priv->input_bar, FALSE); return; } // Set the label accordingly adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (dialog->priv->input_bar))); g_signal_handlers_disconnect_by_func(adj, on_adjustment_value_changed, dialog); gtk_label_set_label (GTK_LABEL(dialog->priv->selected_input_label), g_strdup_printf(_("Settings for %s"), gvc_mixer_ui_device_get_description (active_input))); gvc_channel_bar_set_base_volume (GVC_CHANNEL_BAR (dialog->priv->input_bar), gvc_mixer_stream_get_base_volume (stream)); gvc_channel_bar_set_is_amplified (GVC_CHANNEL_BAR (dialog->priv->input_bar), gvc_mixer_stream_get_can_decibel (stream)); /* Update the adjustment in case the previous bar wasn't decibel * capable, and we clipped it */ adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (dialog->priv->input_bar))); gtk_adjustment_set_value (adj, gvc_mixer_stream_get_volume (stream)); stop_monitor_stream_for_source (dialog); //if (test_it < 6){ create_monitor_stream_for_source (dialog, stream); test_it += 1; //} bar_set_stream (dialog, dialog->priv->input_bar, stream); // remove any previous stream that might have been pointed at // the static input bar and connect new signals from new stream. const GList* profiles = gvc_mixer_ui_device_get_profiles (active_input); if (profiles != NULL && !gvc_mixer_ui_device_should_profiles_be_hidden (active_input)){ const gchar *active_profile; dialog->priv->input_profile_combo = gvc_combo_box_new (_("Mode:")); gvc_combo_box_set_profiles (GVC_COMBO_BOX (dialog->priv->input_profile_combo), profiles); active_profile = gvc_mixer_ui_device_get_active_profile (active_input); if (active_profile) gvc_combo_box_set_active (GVC_COMBO_BOX (dialog->priv->input_profile_combo), active_profile); g_object_set_data (G_OBJECT (dialog->priv->input_profile_combo), "uidevice", active_input); g_signal_connect (G_OBJECT (dialog->priv->input_profile_combo), "changed", G_CALLBACK (profile_selection_changed), dialog); gtk_box_pack_start (GTK_BOX (dialog->priv->input_settings_box), dialog->priv->input_profile_combo, TRUE, FALSE, 0); if (dialog->priv->size_group != NULL) { gvc_combo_box_set_size_group (GVC_COMBO_BOX (dialog->priv->input_profile_combo), dialog->priv->size_group, FALSE); } gtk_widget_show (dialog->priv->input_profile_combo); } } /* active_output_update * Handle output update change from the backend (control). * Trust the backend whole heartedly to deliver the correct output * i.e. keep it MVC. */ static void active_output_update (GvcMixerDialog *dialog, GvcMixerUIDevice *active_output) { // First make sure the correct UI device is selected. GtkTreeModel *model; GtkTreeIter iter; g_debug ("\n\n active output update - device id = %i \n\n", gvc_mixer_ui_device_get_id (active_output)); model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview)); if (gtk_tree_model_get_iter_first (model, &iter) == FALSE){ g_warning ("The tree is empty => we have no devices in the tree => cannot set the active output"); return; } do { gboolean is_selected; gint id; gtk_tree_model_get (model, &iter, ID_COLUMN, &id, ACTIVE_COLUMN, &is_selected, -1); if (is_selected && id == gvc_mixer_ui_device_get_id (active_output)) { g_debug ("\n\n unneccessary active output update unless it was a profile change on the same device ? \n\n"); } is_selected = id == gvc_mixer_ui_device_get_id (active_output); gtk_list_store_set (GTK_LIST_STORE (model), &iter, ACTIVE_COLUMN, is_selected, -1); if (is_selected) { GtkTreeSelection *selection; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (dialog->priv->output_treeview)); gtk_tree_selection_select_iter (selection, &iter); } }while (gtk_tree_model_iter_next (model, &iter)); // Not ideal but for now destroy the combo and recreate below. if (dialog->priv->output_profile_combo != NULL) { gtk_container_remove (GTK_CONTAINER (dialog->priv->output_settings_box), dialog->priv->output_profile_combo); dialog->priv->output_profile_combo = NULL; } GvcMixerStream *stream; const GvcChannelMap *map; GtkAdjustment *adj; stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control, active_output); if (stream == NULL) { g_warning ("active_output_update - couldn't find a stream from the supposed active output"); return; } gboolean is_muted = gvc_mixer_stream_get_is_muted (stream); gtk_widget_set_sensitive (dialog->priv->applications_box, !is_muted); adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (dialog->priv->output_bar))); g_signal_handlers_disconnect_by_func(adj, on_adjustment_value_changed, dialog); bar_set_stream (dialog, dialog->priv->output_bar, stream); gvc_channel_bar_set_base_volume (GVC_CHANNEL_BAR (dialog->priv->output_bar), gvc_mixer_stream_get_base_volume (stream)); gvc_channel_bar_set_is_amplified (GVC_CHANNEL_BAR (dialog->priv->output_bar), gvc_mixer_stream_get_can_decibel (stream)); /* Update the adjustment in case the previous bar wasn't decibel * capable, and we clipped it */ adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (dialog->priv->output_bar))); gtk_adjustment_set_value (adj, gvc_mixer_stream_get_volume (stream)); map = gvc_mixer_stream_get_channel_map (stream); if (map == NULL) { g_warning ("Active output stream has no channel map"); gtk_widget_set_sensitive (dialog->priv->output_bar, FALSE); gtk_widget_set_sensitive (dialog->priv->output_balance_bar, FALSE); gtk_widget_set_sensitive (dialog->priv->output_lfe_bar, FALSE); gtk_widget_set_sensitive (dialog->priv->output_fade_bar, FALSE); return; } // Swap bars to the active map gvc_balance_bar_set_map (GVC_BALANCE_BAR (dialog->priv->output_balance_bar), map); gvc_balance_bar_set_map (GVC_BALANCE_BAR (dialog->priv->output_fade_bar), map); gvc_balance_bar_set_map (GVC_BALANCE_BAR (dialog->priv->output_lfe_bar), map); // Set sensitivities accordingly. gtk_widget_set_sensitive (dialog->priv->output_balance_bar, gvc_channel_map_can_balance (map)); gtk_widget_set_sensitive (dialog->priv->output_fade_bar, gvc_channel_map_can_fade (map)); gtk_widget_set_sensitive (dialog->priv->output_lfe_bar, gvc_channel_map_has_lfe (map)); gtk_widget_set_sensitive (dialog->priv->output_bar, TRUE); // Set the label accordingly gtk_label_set_label (GTK_LABEL(dialog->priv->selected_output_label), g_strdup_printf(_("Settings for %s"), gvc_mixer_ui_device_get_description (active_output))); g_debug ("\n active_output_update %s \n", gvc_mixer_ui_device_get_description (active_output)); GList* profiles = gvc_mixer_ui_device_get_profiles (active_output); if (profiles != NULL && !gvc_mixer_ui_device_should_profiles_be_hidden (active_output)) { const gchar *active_profile; dialog->priv->output_profile_combo = gvc_combo_box_new (_("Mode:")); gvc_combo_box_set_profiles (GVC_COMBO_BOX (dialog->priv->output_profile_combo), profiles); gtk_box_pack_start (GTK_BOX (dialog->priv->output_settings_box), dialog->priv->output_profile_combo, FALSE, FALSE, 3); if (dialog->priv->size_group != NULL) { gvc_combo_box_set_size_group (GVC_COMBO_BOX (dialog->priv->output_profile_combo), dialog->priv->size_group, FALSE); } active_profile = gvc_mixer_ui_device_get_active_profile (active_output); if (active_profile) gvc_combo_box_set_active (GVC_COMBO_BOX (dialog->priv->output_profile_combo), active_profile); g_object_set_data (G_OBJECT (dialog->priv->output_profile_combo), "uidevice", active_output); g_signal_connect (G_OBJECT (dialog->priv->output_profile_combo), "changed", G_CALLBACK (profile_selection_changed), dialog); gtk_widget_show (dialog->priv->output_profile_combo); } } static void bar_set_stream (GvcMixerDialog *dialog, GtkWidget *bar, GvcMixerStream *stream) { GtkAdjustment *adj; g_assert (bar != NULL); gtk_widget_set_sensitive (bar, (stream != NULL)); adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (bar))); g_signal_handlers_disconnect_by_func (adj, on_adjustment_value_changed, dialog); g_object_set_data (G_OBJECT (bar), "gvc-mixer-dialog-stream", stream); g_object_set_data (G_OBJECT (adj), "gvc-mixer-dialog-stream", stream); g_object_set_data (G_OBJECT (adj), "gvc-mixer-dialog-bar", bar); if (stream != NULL) { gboolean is_muted; is_muted = gvc_mixer_stream_get_is_muted (stream); gvc_channel_bar_set_is_muted (GVC_CHANNEL_BAR (bar), is_muted); gtk_adjustment_set_value (adj, gvc_mixer_stream_get_volume (stream)); g_signal_connect (stream, "notify::is-muted", G_CALLBACK (on_stream_is_muted_notify), dialog); g_signal_connect (stream, "notify::volume", G_CALLBACK (on_stream_volume_notify), dialog); g_signal_connect (adj, "value-changed", G_CALLBACK (on_adjustment_value_changed), dialog); } } /** * This method handles all streams that are not an input or output * i.e. effects streams and application streams * TODO rename to truly reflect its usage. **/ static void add_stream (GvcMixerDialog *dialog, GvcMixerStream *stream) { GtkWidget *bar; bar = NULL; if (stream == gvc_mixer_control_get_event_sink_input (dialog->priv->mixer_control)) { bar = dialog->priv->effects_bar; g_debug ("Adding effects stream"); } else { // Must be a sink/source input/output const char *name; name = gvc_mixer_stream_get_name (stream); g_debug ("\n Add bar for application stream : %s", name); bar = create_app_bar (dialog, name, gvc_mixer_stream_get_icon_name (stream)); gtk_box_pack_start (GTK_BOX (dialog->priv->applications_box), bar, FALSE, FALSE, 12); dialog->priv->num_apps++; gtk_widget_hide (dialog->priv->no_apps_label); } // We should have a bar by now. g_assert (bar != NULL); GvcMixerStream *old_stream; if (bar != NULL) { old_stream = g_object_get_data (G_OBJECT (bar), "gvc-mixer-dialog-stream"); if (old_stream != NULL) { char *name; g_object_get (bar, "name", &name, NULL); g_debug ("Disconnecting old stream '%s' from bar '%s'", gvc_mixer_stream_get_name (old_stream), name); g_free (name); g_signal_handlers_disconnect_by_func (old_stream, on_stream_is_muted_notify, dialog); g_signal_handlers_disconnect_by_func (old_stream, on_stream_volume_notify, dialog); g_print ("\n in add stream \n"); g_hash_table_remove (dialog->priv->bars, GUINT_TO_POINTER (gvc_mixer_stream_get_id (old_stream))); } save_bar_for_stream (dialog, stream, bar); bar_set_stream (dialog, bar, stream); gtk_widget_show (bar); } } static void remove_stream (GvcMixerDialog *dialog, guint id) { GtkWidget *bar; bar = g_hash_table_lookup (dialog->priv->bars, GUINT_TO_POINTER (id)); if (bar != NULL) { g_hash_table_remove (dialog->priv->bars, GUINT_TO_POINTER (id)); gtk_container_remove (GTK_CONTAINER (gtk_widget_get_parent (bar)), bar); dialog->priv->num_apps--; if (dialog->priv->num_apps == 0) { gtk_widget_show (dialog->priv->no_apps_label); } } } static void on_control_stream_added (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GvcMixerStream *stream; stream = gvc_mixer_control_lookup_stream_id (control, id); if (stream == NULL) return; const char *app_id; app_id = gvc_mixer_stream_get_application_id (stream); if (stream == gvc_mixer_control_get_event_sink_input (dialog->priv->mixer_control) || (!GVC_IS_MIXER_SOURCE (stream) && !GVC_IS_MIXER_SINK (stream) && !gvc_mixer_stream_is_virtual (stream) && g_strcmp0 (app_id, "org.gnome.VolumeControl") != 0 && g_strcmp0 (app_id, "org.PulseAudio.pavucontrol") != 0)) { GtkWidget *bar; bar = g_hash_table_lookup (dialog->priv->bars, GUINT_TO_POINTER (id)); if (bar != NULL) { g_debug ("GvcMixerDialog: Stream %u already added", id); return; } add_stream (dialog, stream); } } static void on_control_stream_removed (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { remove_stream (dialog, id); } static gboolean find_item_by_id (GtkTreeModel *model, guint id, guint column, GtkTreeIter *iter) { gboolean found_item; found_item = FALSE; if (!gtk_tree_model_get_iter_first (model, iter)) { return FALSE; } do { guint t_id; gtk_tree_model_get (model, iter, column, &t_id, -1); if (id == t_id) { found_item = TRUE; } } while (!found_item && gtk_tree_model_iter_next (model, iter)); return found_item; } static void add_input_ui_entry (GvcMixerDialog *dialog, GvcMixerUIDevice *input) { g_debug ("\n Add input ui entry with id : %u \n", gvc_mixer_ui_device_get_id (input)); gchar *port_name; gchar *origin; gchar *description; gboolean active; gboolean available; gint stream_id; GvcMixerCard *card; g_object_get (G_OBJECT (input), "stream-id", &stream_id, "card", &card, "origin", &origin, "description", &description, "port-name", &port_name, "port-available", &available, NULL); GtkTreeModel *model; GtkTreeIter iter; const GvcChannelMap *map; GIcon *icon; if (card == NULL) { GvcMixerStream *stream; g_debug ("just detected a network source"); stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control, input); if (stream == NULL) { g_warning ("tried to add the network source but the stream was null - fail ?!"); g_free (port_name); g_free (origin); g_free (description); return; } icon = gvc_mixer_stream_get_gicon (stream); } else icon = gvc_mixer_card_get_gicon (card); model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview)); gtk_list_store_append (GTK_LIST_STORE (model), &iter); gtk_list_store_set (GTK_LIST_STORE (model), &iter, NAME_COLUMN, description, DEVICE_COLUMN, origin, ACTIVE_COLUMN, FALSE, ICON_COLUMN, icon, ID_COLUMN, gvc_mixer_ui_device_get_id (input), SPEAKERS_COLUMN,origin, -1); if (icon != NULL) g_object_unref (icon); // TODO check this. /*g_signal_connect (output, "notify::description", G_CALLBACK (on_output_description_notify), dialog);*/ g_free (port_name); g_free (origin); g_free (description); } static void add_output_ui_entry (GvcMixerDialog *dialog, GvcMixerUIDevice *output) { g_debug ("\n Add output ui entry with id : %u \n", gvc_mixer_ui_device_get_id (output)); gchar *sink_port_name; gchar *origin; gchar *description; gboolean active; gboolean available; gint sink_stream_id; GvcMixerCard *card; g_object_get (G_OBJECT (output), "stream-id", &sink_stream_id, "card", &card, "origin", &origin, "description", &description, "port-name", &sink_port_name, "port-available", &available, NULL); GtkTreeModel *model; GtkTreeIter iter; const GvcChannelMap *map; GIcon *icon; if (card == NULL) { g_debug ("just detected a network sink"); GvcMixerStream *stream; stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control, output); if (stream == NULL) { g_warning ("tried to add the network sink but the stream was null - fail ?!"); g_free (sink_port_name); g_free (origin); g_free (description); return; } icon = gvc_mixer_stream_get_gicon (stream); } else icon = gvc_mixer_card_get_gicon (card); model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview)); gtk_list_store_append (GTK_LIST_STORE (model), &iter); gtk_list_store_set (GTK_LIST_STORE (model), &iter, NAME_COLUMN, description, DEVICE_COLUMN, origin, ACTIVE_COLUMN, FALSE, ICON_COLUMN, icon, ID_COLUMN, gvc_mixer_ui_device_get_id (output), SPEAKERS_COLUMN,origin, -1); if (icon != NULL) g_object_unref (icon); // TODO check this. /*g_signal_connect (output, "notify::description", G_CALLBACK (on_output_description_notify), dialog);*/ g_free (sink_port_name); g_free (origin); g_free (description); } static void on_control_output_added (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GvcMixerUIDevice* out = NULL; out = gvc_mixer_control_lookup_output_id (control, id); if (out == NULL) { g_warning ("on_control_output_added - tried to fetch an output of id %u but got nothing", id); return; } add_output_ui_entry (dialog, out); } static void on_control_active_output_update (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GvcMixerUIDevice* out = NULL; out = gvc_mixer_control_lookup_output_id (control, id); if (out == NULL) { g_warning ("\n on_control_active_output_update - tried to fetch an output of id %u but got nothing", id); return; } active_output_update (dialog, out); } static void on_control_active_input_update (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GvcMixerUIDevice* in = NULL; in = gvc_mixer_control_lookup_input_id (control, id); if (in == NULL) { g_warning ("on_control_active_input_update - tried to fetch an input of id %u but got nothing", id); return; } active_input_update (dialog, in); } static void on_control_input_added (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GvcMixerUIDevice* in = NULL; in = gvc_mixer_control_lookup_input_id (control, id); if (in == NULL) { g_warning ("on_control_input_added - tried to fetch an input of id %u but got nothing", id); return; } add_input_ui_entry (dialog, in); } static void on_control_output_removed (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GtkWidget *bar; gboolean found; GtkTreeIter iter; GtkTreeModel *model; GvcMixerUIDevice* out = NULL; out = gvc_mixer_control_lookup_output_id (control, id); gint sink_stream_id; g_object_get (G_OBJECT (out), "stream-id", &sink_stream_id, NULL); g_debug ("Remove output from dialog \n id : %u \n sink stream id : %i \n", id, sink_stream_id); /* remove from any models */ model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview)); found = find_item_by_id (GTK_TREE_MODEL (model), id, ID_COLUMN, &iter); if (found) { gtk_list_store_remove (GTK_LIST_STORE (model), &iter); } } static void on_control_input_removed (GvcMixerControl *control, guint id, GvcMixerDialog *dialog) { GtkWidget *bar; gboolean found; GtkTreeIter iter; GtkTreeModel *model; GvcMixerUIDevice* in = NULL; in = gvc_mixer_control_lookup_input_id (control, id); gint stream_id; g_object_get (G_OBJECT (in), "stream-id", &stream_id, NULL); g_debug ("Remove input from dialog \n id : %u \n stream id : %i \n", id, stream_id); /* remove from any models */ model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview)); found = find_item_by_id (GTK_TREE_MODEL (model), id, ID_COLUMN, &iter); if (found) { gtk_list_store_remove (GTK_LIST_STORE (model), &iter); } } static void _gtk_label_make_bold (GtkLabel *label) { PangoFontDescription *font_desc; font_desc = pango_font_description_new (); pango_font_description_set_weight (font_desc, PANGO_WEIGHT_BOLD); /* This will only affect the weight of the font, the rest is * from the current state of the widget, which comes from the * theme or user prefs, since the font desc only has the * weight flag turned on. */ gtk_widget_modify_font (GTK_WIDGET (label), font_desc); pango_font_description_free (font_desc); } static void on_input_selection_changed (GtkTreeSelection *selection, GvcMixerDialog *dialog) { GtkTreeModel *model; GtkTreeIter iter; gboolean toggled; guint id; if (gtk_tree_selection_get_selected (selection, &model, &iter) == FALSE) { g_debug ("Could not get default input from selection"); return; } gtk_tree_model_get (model, &iter, ID_COLUMN, &id, ACTIVE_COLUMN, &toggled, -1); toggled ^= 1; GvcMixerUIDevice *input; //g_debug ("on_input_selection_changed - try swap to input with id %u", id); input = gvc_mixer_control_lookup_input_id (dialog->priv->mixer_control, id); if (input == NULL) { g_warning ("on_input_selection_changed - Unable to find input with id: %u", id); return; } gvc_mixer_control_change_input (dialog->priv->mixer_control, input); } static void on_output_selection_changed (GtkTreeSelection *selection, GvcMixerDialog *dialog) { GtkTreeModel *model; GtkTreeIter iter; gboolean active; guint id; if (gtk_tree_selection_get_selected (selection, &model, &iter) == FALSE) { g_debug ("Could not get default output from selection"); return; } gtk_tree_model_get (model, &iter, ID_COLUMN, &id, ACTIVE_COLUMN, &active, -1); g_debug ("\n\n on_output_selection_changed - active %i \n\n", active); if (active){ return; } GvcMixerUIDevice *output; g_debug ("\n on_output_selection_changed - try swap to output with id %u", id); output = gvc_mixer_control_lookup_output_id (dialog->priv->mixer_control, id); if (output == NULL) { g_warning ("on_output_selection_changed - Unable to find output with id: %u", id); return; } gvc_mixer_control_change_output (dialog->priv->mixer_control, output); } static void name_to_text (GtkTreeViewColumn *column, GtkCellRenderer *cell, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { char *name, *mapping; gtk_tree_model_get(model, iter, NAME_COLUMN, &name, SPEAKERS_COLUMN, &mapping, -1); if (mapping == NULL) { g_object_set (cell, "text", name, NULL); } else { char *str; str = g_strdup_printf ("%s\n<i>%s</i>", name, mapping); g_object_set (cell, "markup", str, NULL); g_free (str); } g_free (name); g_free (mapping); } static GtkWidget * create_stream_treeview (GvcMixerDialog *dialog, GCallback on_selection_changed) { GtkWidget *treeview; GtkListStore *store; GtkCellRenderer *renderer; GtkTreeViewColumn *column; GtkTreeSelection *selection; treeview = gtk_tree_view_new (); gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (treeview), FALSE); store = gtk_list_store_new (NUM_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_UINT, G_TYPE_STRING, G_TYPE_ICON); gtk_tree_view_set_model (GTK_TREE_VIEW (treeview), GTK_TREE_MODEL (store)); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE); column = gtk_tree_view_column_new (); gtk_tree_view_column_set_title (column, _("Name")); renderer = gtk_cell_renderer_pixbuf_new (); gtk_tree_view_column_pack_start (column, renderer, FALSE); g_object_set (G_OBJECT (renderer), "stock-size", GTK_ICON_SIZE_LARGE_TOOLBAR, NULL); gtk_tree_view_column_set_attributes (column, renderer, "gicon", ICON_COLUMN, NULL); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_column_pack_start (column, renderer, TRUE); gtk_tree_view_column_set_cell_data_func (column, renderer, name_to_text, NULL, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); g_signal_connect ( selection, "changed", on_selection_changed, dialog); #if 0 renderer = gtk_cell_renderer_text_new (); column = gtk_tree_view_column_new_with_attributes (_("Device"), renderer, "text", DEVICE_COLUMN, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); #endif return treeview; } static void on_profile_changed (GvcComboBox *widget, const char *profile, gpointer user_data) { GvcMixerCard *card; card = g_object_get_data (G_OBJECT (widget), "card"); if (card == NULL) { g_warning ("Could not find card for combobox"); return; } g_debug ("Profile changed to %s for card %s", profile, gvc_mixer_card_get_name (card)); gvc_mixer_card_change_profile (card, profile); } static void on_test_speakers_clicked (GtkButton *widget, gpointer user_data) { GvcMixerDialog *dialog = GVC_MIXER_DIALOG (user_data); GtkTreeModel *model; GtkTreeIter iter; gint active_output = GVC_MIXER_UI_DEVICE_INVALID; model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview)); if (gtk_tree_model_get_iter_first (model, &iter) == FALSE){ g_warning ("The tree is empty => we have no device to test speakers with return"); return; } do { gboolean is_selected = FALSE ; gint id; gtk_tree_model_get (model, &iter, ID_COLUMN, &id, ACTIVE_COLUMN, &is_selected, -1); if (is_selected) { active_output = id; break; } }while (gtk_tree_model_iter_next (model, &iter)); if (active_output == GVC_MIXER_UI_DEVICE_INVALID) { g_warning ("Cant find the active output from the UI"); return; } GvcMixerUIDevice *output; output = gvc_mixer_control_lookup_output_id (dialog->priv->mixer_control, (guint)active_output); gint stream_id = gvc_mixer_ui_device_get_stream_id(output); if (stream_id == GVC_MIXER_UI_DEVICE_INVALID) return; g_debug ("Test the speakers on the %s", gvc_mixer_ui_device_get_description (output)); GvcMixerStream *stream; GvcMixerCardProfile *profile; GtkWidget *d, *speaker_test, *container; char *title; stream = gvc_mixer_control_lookup_stream_id (dialog->priv->mixer_control, stream_id); if (stream == NULL) { g_debug ("Stream/sink not found"); return; } title = g_strdup_printf (_("Speaker Testing for %s"), gvc_mixer_ui_device_get_description (output)); d = gtk_dialog_new_with_buttons (title, GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (widget))), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, NULL); gtk_window_set_has_resize_grip (GTK_WINDOW (d), FALSE); g_free (title); speaker_test = gvc_speaker_test_new (dialog->priv->mixer_control, stream); gtk_widget_show (speaker_test); container = gtk_dialog_get_content_area (GTK_DIALOG (d)); gtk_container_add (GTK_CONTAINER (container), speaker_test); gtk_dialog_run (GTK_DIALOG (d)); gtk_widget_destroy (d); } static GObject * gvc_mixer_dialog_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_params) { GObject *object; GvcMixerDialog *self; GtkWidget *main_vbox; GtkWidget *label; GtkWidget *alignment; GtkWidget *alignment_settings_box; GtkWidget *settings_box; GtkWidget *box; GtkWidget *sbox; GtkWidget *ebox; GtkWidget *test_sound_box; GSList *streams; GSList *cards; GSList *l; GvcMixerStream *stream; GvcMixerCard *card; GtkTreeSelection *selection; object = G_OBJECT_CLASS (gvc_mixer_dialog_parent_class)->constructor (type, n_construct_properties, construct_params); self = GVC_MIXER_DIALOG (object); main_vbox = GTK_WIDGET (self); gtk_box_set_spacing (GTK_BOX (main_vbox), 2); gtk_container_set_border_width (GTK_CONTAINER (self), 3); self->priv->output_stream_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12); alignment = gtk_alignment_new (0, 0, 1, 1); gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 0, 0, 0, 0); gtk_container_add (GTK_CONTAINER (alignment), self->priv->output_stream_box); gtk_box_pack_start (GTK_BOX (main_vbox), alignment, FALSE, FALSE, 0); self->priv->notebook = gtk_notebook_new (); gtk_box_pack_start (GTK_BOX (main_vbox), self->priv->notebook, TRUE, TRUE, 0); gtk_container_set_border_width (GTK_CONTAINER (self->priv->notebook), 5); /* Output page */ self->priv->output_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12); gtk_container_set_border_width (GTK_CONTAINER (self->priv->output_box), 12); label = gtk_label_new (_("Output")); gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook), self->priv->output_box, label); box = gtk_frame_new (_("Play sound through")); gtk_widget_set_size_request (GTK_WIDGET (box), 310, -1); label = gtk_frame_get_label_widget (GTK_FRAME (box)); _gtk_label_make_bold (GTK_LABEL (label)); gtk_label_set_use_underline (GTK_LABEL (label), TRUE); gtk_frame_set_shadow_type (GTK_FRAME (box), GTK_SHADOW_NONE); gtk_box_pack_start (GTK_BOX (self->priv->output_box), box, FALSE, TRUE, 0); alignment = gtk_alignment_new (0, 0, 1, 1); gtk_container_add (GTK_CONTAINER (box), alignment); gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 10, 5, 0, 15); self->priv->output_treeview = create_stream_treeview (self, G_CALLBACK (on_output_selection_changed)); gtk_label_set_mnemonic_widget (GTK_LABEL (label), self->priv->output_treeview); box = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (box), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (box), GTK_SHADOW_IN); gtk_container_add (GTK_CONTAINER (box), self->priv->output_treeview); gtk_container_add (GTK_CONTAINER (alignment), box); self->priv->selected_output_label = gtk_label_new (_("Settings for the selected device")); gtk_widget_set_halign (self->priv->selected_output_label, GTK_ALIGN_START); gtk_widget_set_valign (self->priv->selected_output_label, GTK_ALIGN_START); gtk_misc_set_padding (GTK_MISC (self->priv->selected_output_label), 0, 0); _gtk_label_make_bold (GTK_LABEL (self->priv->selected_output_label)); settings_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); alignment_settings_box = gtk_alignment_new (0, 0, 1, 1); gtk_alignment_set_padding (GTK_ALIGNMENT (alignment_settings_box), 7, 0, 0, 0); self->priv->output_settings_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); gtk_container_add (GTK_CONTAINER (alignment_settings_box), self->priv->output_settings_box); gtk_box_pack_start (GTK_BOX (self->priv->output_box), settings_box, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (settings_box), self->priv->selected_output_label, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (settings_box), alignment_settings_box, FALSE, FALSE, 0); self->priv->output_balance_bar = gvc_balance_bar_new (BALANCE_TYPE_RL); if (self->priv->size_group != NULL) { gvc_balance_bar_set_size_group (GVC_BALANCE_BAR (self->priv->output_balance_bar), self->priv->size_group, FALSE); } gtk_box_pack_start (GTK_BOX (self->priv->output_settings_box), self->priv->output_balance_bar, FALSE, FALSE, 3); gtk_widget_show (self->priv->output_balance_bar); self->priv->output_fade_bar = gvc_balance_bar_new (BALANCE_TYPE_FR); if (self->priv->size_group != NULL) { gvc_balance_bar_set_size_group (GVC_BALANCE_BAR (self->priv->output_fade_bar), self->priv->size_group, FALSE); } gtk_box_pack_start (GTK_BOX (self->priv->output_settings_box), self->priv->output_fade_bar, FALSE, FALSE, 3); gtk_widget_show (self->priv->output_fade_bar); self->priv->output_lfe_bar = gvc_balance_bar_new (BALANCE_TYPE_LFE); if (self->priv->size_group != NULL) { gvc_balance_bar_set_size_group (GVC_BALANCE_BAR (self->priv->output_lfe_bar), self->priv->size_group, FALSE); } gtk_box_pack_start (GTK_BOX (self->priv->output_settings_box), self->priv->output_lfe_bar, FALSE, FALSE, 3); gtk_widget_show (self->priv->output_lfe_bar); /* Creating a box and try to deal using the same size group. */ test_sound_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_end (GTK_BOX (self->priv->output_settings_box), test_sound_box, FALSE, FALSE, 5); sbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_start (GTK_BOX (test_sound_box), sbox, FALSE, FALSE, 0); label = gtk_label_new (_("Test:")); gtk_box_pack_start (GTK_BOX (sbox), label, FALSE, FALSE, 0); if (self->priv->size_group != NULL) gtk_size_group_add_widget (self->priv->size_group, sbox); self->priv->test_output_button = gtk_button_new_with_label (_("Test Sound")); /* FIXME: I am getting mental with all these hardcoded padding values, * Here 8 works fine, not sure why. */ gtk_box_pack_start (GTK_BOX (test_sound_box), self->priv->test_output_button, TRUE, TRUE, 8); /* Is this needed */ if (self->priv->size_group != NULL) gtk_size_group_add_widget (self->priv->size_group, self->priv->test_output_button); gtk_widget_show (test_sound_box); //gtk_container_add (GTK_CONTAINER (box), self->priv->output_settings_box); g_signal_connect (self->priv->test_output_button, "released", G_CALLBACK (on_test_speakers_clicked), self); /* Input page */ self->priv->input_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12); gtk_container_set_border_width (GTK_CONTAINER (self->priv->input_box), 12); label = gtk_label_new (_("Input")); gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook), self->priv->input_box, label); box = gtk_frame_new (_("Record sound from")); gtk_widget_set_size_request (GTK_WIDGET (box), 310, -1); label = gtk_frame_get_label_widget (GTK_FRAME (box)); _gtk_label_make_bold (GTK_LABEL (label)); gtk_label_set_use_underline (GTK_LABEL (label), TRUE); gtk_frame_set_shadow_type (GTK_FRAME (box), GTK_SHADOW_NONE); gtk_box_pack_start (GTK_BOX (self->priv->input_box), box, FALSE, TRUE, 0); alignment = gtk_alignment_new (0, 0, 1, 1); gtk_container_add (GTK_CONTAINER (box), alignment); gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 10, 5, 0, 15); self->priv->input_treeview = create_stream_treeview (self, G_CALLBACK (on_input_selection_changed)); gtk_label_set_mnemonic_widget (GTK_LABEL (label), self->priv->input_treeview); box = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (box), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (box), GTK_SHADOW_IN); gtk_container_add (GTK_CONTAINER (box), self->priv->input_treeview); gtk_container_add (GTK_CONTAINER (alignment), box); self->priv->selected_input_label = gtk_label_new (_("Settings for the selected device")); gtk_widget_set_halign (self->priv->selected_input_label, GTK_ALIGN_START); _gtk_label_make_bold (GTK_LABEL (self->priv->selected_input_label)); self->priv->input_settings_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); gtk_box_pack_start (GTK_BOX (self->priv->input_box), self->priv->input_settings_box, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (self->priv->input_settings_box), self->priv->selected_input_label, FALSE, FALSE, 0); self->priv->input_bar = create_bar (self, FALSE, TRUE); gvc_channel_bar_set_name (GVC_CHANNEL_BAR (self->priv->input_bar), _("_Input volume:")); gvc_channel_bar_set_low_icon_name (GVC_CHANNEL_BAR (self->priv->input_bar), "cin-audio-input-microphone-low-symbolic"); gvc_channel_bar_set_high_icon_name (GVC_CHANNEL_BAR (self->priv->input_bar), "cin-audio-input-microphone-high-symbolic"); gtk_widget_set_sensitive (self->priv->input_bar, FALSE); if (self->priv->size_group != NULL) { gvc_channel_bar_set_size_group (GVC_CHANNEL_BAR (self->priv->input_bar), self->priv->size_group, FALSE); } gtk_box_pack_start (GTK_BOX (self->priv->input_settings_box), self->priv->input_bar, FALSE, FALSE, 15); gtk_widget_show (self->priv->input_bar); /* Creating a box and try to deal using the same size group. */ GtkWidget *input_level_box; input_level_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_start (GTK_BOX (self->priv->input_settings_box), input_level_box, FALSE, FALSE, 5); sbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_start (GTK_BOX (input_level_box), sbox, FALSE, FALSE, 0); label = gtk_label_new (_("Input level:")); gtk_box_pack_start (GTK_BOX (sbox), label, FALSE, FALSE, 0); if (self->priv->size_group != NULL) gtk_size_group_add_widget (self->priv->size_group, sbox); self->priv->input_level_bar = gvc_level_bar_new (); gvc_level_bar_set_orientation (GVC_LEVEL_BAR (self->priv->input_level_bar), GTK_ORIENTATION_HORIZONTAL); gvc_level_bar_set_scale (GVC_LEVEL_BAR (self->priv->input_level_bar), GVC_LEVEL_SCALE_LINEAR); gtk_box_pack_start (GTK_BOX (input_level_box), self->priv->input_level_bar, TRUE, TRUE, 0); /* Effects page */ self->priv->sound_effects_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6); gtk_container_set_border_width (GTK_CONTAINER (self->priv->sound_effects_box), 12); label = gtk_label_new (_("Sound Effects")); gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook), self->priv->sound_effects_box, label); self->priv->effects_bar = create_bar (self, FALSE, TRUE); gvc_channel_bar_set_name (GVC_CHANNEL_BAR (self->priv->effects_bar), _("_Alert volume:")); gtk_widget_set_sensitive (self->priv->effects_bar, FALSE); gtk_box_pack_start (GTK_BOX (self->priv->sound_effects_box), self->priv->effects_bar, FALSE, FALSE, 0); self->priv->sound_theme_chooser = gvc_sound_theme_chooser_new (); gtk_box_pack_start (GTK_BOX (self->priv->sound_effects_box), self->priv->sound_theme_chooser, TRUE, TRUE, 6); /* Applications */ self->priv->applications_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12); gtk_container_set_border_width (GTK_CONTAINER (self->priv->applications_box), 12); label = gtk_label_new (_("Applications")); gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook), self->priv->applications_box, label); self->priv->no_apps_label = gtk_label_new (_("No application is currently playing or recording audio.")); gtk_box_pack_start (GTK_BOX (self->priv->applications_box), self->priv->no_apps_label, TRUE, TRUE, 0); self->priv->output_stream_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12); alignment = gtk_alignment_new (0, 0, 1, 1); gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 12, 0, 0, 0); gtk_container_add (GTK_CONTAINER (alignment), self->priv->output_stream_box); gtk_box_pack_start (GTK_BOX (main_vbox), alignment, FALSE, FALSE, 0); // Output volume self->priv->output_bar = create_bar (self, FALSE, TRUE); gvc_channel_bar_set_name (GVC_CHANNEL_BAR (self->priv->output_bar), _("_Output volume:")); gtk_widget_set_sensitive (self->priv->output_bar, FALSE); gtk_widget_set_size_request (self->priv->output_bar, 460, -1); gtk_box_pack_start (GTK_BOX (self->priv->output_stream_box), self->priv->output_bar, TRUE, FALSE, 12); gtk_widget_show_all (main_vbox); g_signal_connect (self->priv->mixer_control, "stream-added", G_CALLBACK (on_control_stream_added), self); g_signal_connect (self->priv->mixer_control, "stream-removed", G_CALLBACK (on_control_stream_removed), self); g_signal_connect (self->priv->mixer_control, "output-added", G_CALLBACK (on_control_output_added), self); g_signal_connect (self->priv->mixer_control, "output-removed", G_CALLBACK (on_control_output_removed), self); g_signal_connect (self->priv->mixer_control, "input-added", G_CALLBACK (on_control_input_added), self); g_signal_connect (self->priv->mixer_control, "input-removed", G_CALLBACK (on_control_input_removed), self); return object; } static void gvc_mixer_dialog_dispose (GObject *object) { GvcMixerDialog *dialog = GVC_MIXER_DIALOG (object); g_clear_object (&dialog->priv->indicator_settings); if (dialog->priv->mixer_control != NULL) { g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_output_added, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_output_removed, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_active_input_update, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_active_output_update, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_input_added, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_input_removed, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_stream_added, dialog); g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control, on_control_stream_removed, dialog); g_object_unref (dialog->priv->mixer_control); dialog->priv->mixer_control = NULL; } if (dialog->priv->bars != NULL) { g_hash_table_destroy (dialog->priv->bars); dialog->priv->bars = NULL; } G_OBJECT_CLASS (gvc_mixer_dialog_parent_class)->dispose (object); } static void gvc_mixer_dialog_class_init (GvcMixerDialogClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->constructor = gvc_mixer_dialog_constructor; object_class->dispose = gvc_mixer_dialog_dispose; object_class->finalize = gvc_mixer_dialog_finalize; object_class->set_property = gvc_mixer_dialog_set_property; object_class->get_property = gvc_mixer_dialog_get_property; g_object_class_install_property (object_class, PROP_MIXER_CONTROL, g_param_spec_object ("mixer-control", "mixer control", "mixer control", GVC_TYPE_MIXER_CONTROL, G_PARAM_READWRITE|G_PARAM_CONSTRUCT)); g_type_class_add_private (klass, sizeof (GvcMixerDialogPrivate)); } static void gvc_mixer_dialog_init (GvcMixerDialog *dialog) { dialog->priv = GVC_MIXER_DIALOG_GET_PRIVATE (dialog); dialog->priv->bars = g_hash_table_new (NULL, NULL); dialog->priv->size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL); } static void gvc_mixer_dialog_finalize (GObject *object) { GvcMixerDialog *mixer_dialog; g_return_if_fail (object != NULL); g_return_if_fail (GVC_IS_MIXER_DIALOG (object)); mixer_dialog = GVC_MIXER_DIALOG (object); g_return_if_fail (mixer_dialog->priv != NULL); G_OBJECT_CLASS (gvc_mixer_dialog_parent_class)->finalize (object); } GvcMixerDialog * gvc_mixer_dialog_new (GvcMixerControl *control) { GObject *dialog; dialog = g_object_new (GVC_TYPE_MIXER_DIALOG, "mixer-control", control, NULL); return GVC_MIXER_DIALOG (dialog); } enum { PAGE_OUTPUT, PAGE_INPUT, PAGE_EVENTS, PAGE_APPLICATIONS }; gboolean gvc_mixer_dialog_set_page (GvcMixerDialog *self, const char *page) { guint num; g_return_val_if_fail (self != NULL, FALSE); num = PAGE_OUTPUT; if (g_str_equal (page, "effects")) num = PAGE_EVENTS; else if (g_str_equal (page, "input")) num = PAGE_INPUT; else if (g_str_equal (page, "output")) num = PAGE_OUTPUT; else if (g_str_equal (page, "applications")) num = PAGE_APPLICATIONS; gtk_notebook_set_current_page (GTK_NOTEBOOK (self->priv->notebook), num); return TRUE; }
477
./cinnamon-control-center/panels/color/cc-color-panel.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc * Copyright (C) 2011 Richard Hughes <richard@hughsie.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <config.h> #include <colord.h> #include <gtk/gtk.h> #include <gdk/gdkx.h> #include <gio/gio.h> #include <glib/gi18n-lib.h> #include "cc-color-panel.h" #define WID(b, w) (GtkWidget *) gtk_builder_get_object (b, w) CC_PANEL_REGISTER (CcColorPanel, cc_color_panel) #define COLOR_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_COLOR_PANEL, CcColorPanelPrivate)) struct _CcColorPanelPrivate { CdClient *client; CdDevice *current_device; CdSensor *sensor; GCancellable *cancellable; GDBusProxy *proxy; GSettings *settings; GtkBuilder *builder; GtkTreeStore *list_store_devices; GtkWidget *main_window; }; enum { GCM_PREFS_COLUMN_DEVICE_PATH, GCM_PREFS_COLUMN_SORT, GCM_PREFS_COLUMN_ICON, GCM_PREFS_COLUMN_TITLE, GCM_PREFS_COLUMN_DEVICE, GCM_PREFS_COLUMN_PROFILE, GCM_PREFS_COLUMN_STATUS, GCM_PREFS_COLUMN_STATUS_IMAGE, GCM_PREFS_COLUMN_TOOLTIP, GCM_PREFS_COLUMN_RADIO_ACTIVE, GCM_PREFS_COLUMN_RADIO_VISIBLE, GCM_PREFS_COLUMN_NUM_COLUMNS }; enum { GCM_PREFS_COMBO_COLUMN_TEXT, GCM_PREFS_COMBO_COLUMN_PROFILE, GCM_PREFS_COMBO_COLUMN_TYPE, GCM_PREFS_COMBO_COLUMN_NUM_COLUMNS }; typedef enum { GCM_PREFS_ENTRY_TYPE_PROFILE, GCM_PREFS_ENTRY_TYPE_IMPORT } GcmPrefsEntryType; #define GCM_SETTINGS_SCHEMA "org.cinnamon.settings-daemon.plugins.color" #define GCM_SETTINGS_RECALIBRATE_PRINTER_THRESHOLD "recalibrate-printer-threshold" #define GCM_SETTINGS_RECALIBRATE_DISPLAY_THRESHOLD "recalibrate-display-threshold" /* max number of devices and profiles to cause auto-expand at startup */ #define GCM_PREFS_MAX_DEVICES_PROFILES_EXPANDED 5 static void gcm_prefs_device_add_cb (GtkWidget *widget, CcColorPanel *prefs); static void gcm_prefs_combobox_add_profile (GtkWidget *widget, CdProfile *profile, GcmPrefsEntryType entry_type, GtkTreeIter *iter) { const gchar *id; GtkTreeModel *model; GtkTreeIter iter_tmp; GString *string; /* iter is optional */ if (iter == NULL) iter = &iter_tmp; /* use description */ if (entry_type == GCM_PREFS_ENTRY_TYPE_IMPORT) { /* TRANSLATORS: this is where the user can click and import a profile */ string = g_string_new (_("Other profile…")); } else { string = g_string_new (cd_profile_get_title (profile)); /* any source prefix? */ id = cd_profile_get_metadata_item (profile, CD_PROFILE_METADATA_DATA_SOURCE); if (g_strcmp0 (id, CD_PROFILE_METADATA_DATA_SOURCE_EDID) == 0) { /* TRANSLATORS: this is a profile prefix to signify the * profile has been auto-generated for this hardware */ g_string_prepend (string, _("Default: ")); } #if CD_CHECK_VERSION(0,1,14) if (g_strcmp0 (id, CD_PROFILE_METADATA_DATA_SOURCE_STANDARD) == 0) { /* TRANSLATORS: this is a profile prefix to signify the * profile his a standard space like AdobeRGB */ g_string_prepend (string, _("Colorspace: ")); } if (g_strcmp0 (id, CD_PROFILE_METADATA_DATA_SOURCE_TEST) == 0) { /* TRANSLATORS: this is a profile prefix to signify the * profile is a test profile */ g_string_prepend (string, _("Test profile: ")); } #endif } /* also add profile */ model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_list_store_append (GTK_LIST_STORE(model), iter); gtk_list_store_set (GTK_LIST_STORE(model), iter, GCM_PREFS_COMBO_COLUMN_TEXT, string->str, GCM_PREFS_COMBO_COLUMN_PROFILE, profile, GCM_PREFS_COMBO_COLUMN_TYPE, entry_type, -1); g_string_free (string, TRUE); } static void gcm_prefs_default_cb (GtkWidget *widget, CcColorPanel *prefs) { CdProfile *profile; gboolean ret; GError *error = NULL; CcColorPanelPrivate *priv = prefs->priv; /* TODO: check if the profile is already systemwide */ profile = cd_device_get_default_profile (priv->current_device); if (profile == NULL) goto out; /* install somewhere out of $HOME */ ret = cd_profile_install_system_wide_sync (profile, priv->cancellable, &error); if (!ret) { g_warning ("failed to set profile system-wide: %s", error->message); g_error_free (error); goto out; } out: if (profile != NULL) g_object_unref (profile); } static void gcm_prefs_treeview_popup_menu (CcColorPanel *prefs, GtkWidget *treeview) { GtkWidget *menu, *menuitem; menu = gtk_menu_new (); /* TRANSLATORS: this is when the profile should be set for all users */ menuitem = gtk_menu_item_new_with_label (_("Set for all users")); g_signal_connect (menuitem, "activate", G_CALLBACK (gcm_prefs_default_cb), prefs); gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem); /* TRANSLATORS: this is when the profile should be set for all users */ menuitem = gtk_menu_item_new_with_label (_("Create virtual device")); g_signal_connect (menuitem, "activate", G_CALLBACK (gcm_prefs_device_add_cb), prefs); gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem); gtk_widget_show_all (menu); /* Note: gdk_event_get_time() accepts a NULL argument */ gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL, NULL, 0, gdk_event_get_time (NULL)); } static gboolean gcm_prefs_treeview_popup_menu_cb (GtkWidget *treeview, CcColorPanel *prefs) { if (prefs->priv->current_device == NULL) return FALSE; gcm_prefs_treeview_popup_menu (prefs, treeview); return TRUE; /* we handled this */ } static GFile * gcm_prefs_file_chooser_get_icc_profile (CcColorPanel *prefs) { GtkWindow *window; GtkWidget *dialog; GFile *file = NULL; GtkFileFilter *filter; CcColorPanelPrivate *priv = prefs->priv; /* create new dialog */ window = GTK_WINDOW(gtk_builder_get_object (priv->builder, "dialog_assign")); /* TRANSLATORS: an ICC profile is a file containing colorspace data */ dialog = gtk_file_chooser_dialog_new (_("Select ICC Profile File"), window, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, _("_Import"), GTK_RESPONSE_ACCEPT, NULL); gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER(dialog), g_get_home_dir ()); gtk_file_chooser_set_create_folders (GTK_FILE_CHOOSER(dialog), FALSE); gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER(dialog), FALSE); /* setup the filter */ filter = gtk_file_filter_new (); gtk_file_filter_add_mime_type (filter, "application/vnd.iccprofile"); /* TRANSLATORS: filter name on the file->open dialog */ gtk_file_filter_set_name (filter, _("Supported ICC profiles")); gtk_file_chooser_add_filter (GTK_FILE_CHOOSER(dialog), filter); /* setup the all files filter */ filter = gtk_file_filter_new (); gtk_file_filter_add_pattern (filter, "*"); /* TRANSLATORS: filter name on the file->open dialog */ gtk_file_filter_set_name (filter, _("All files")); gtk_file_chooser_add_filter (GTK_FILE_CHOOSER(dialog), filter); /* did user choose file */ if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER(dialog)); /* we're done */ gtk_widget_destroy (dialog); /* or NULL for missing */ return file; } static void gcm_packagekit_finished_cb (GObject *source, GAsyncResult *res, gpointer user_data) { GPtrArray *argv = (GPtrArray *)user_data; GVariant *reply; GError *error = NULL; gboolean ret; reply = g_dbus_proxy_call_finish (G_DBUS_PROXY (source), res, &error); g_variant_unref (reply); if (error != NULL) { g_warning ("failed to install required component: %s", error->message); g_ptr_array_unref (argv); g_error_free (error); return; } ret = g_spawn_async (NULL, (gchar**) argv->pdata, NULL, 0, NULL, NULL, NULL, &error); g_ptr_array_unref (argv); if (!ret) { g_warning ("failed to run command: %s", error->message); g_error_free (error); } } struct gcm_packagekit_closure_data { GPtrArray *argv; guint xid; }; static void gcm_packagekit_proxy_ready_cb (GObject *source, GAsyncResult *res, gpointer user_data) { struct gcm_packagekit_closure_data *data = (struct gcm_packagekit_closure_data *)user_data; GDBusProxy *session_installer; GVariantBuilder *builder; GError *error = NULL; session_installer = g_dbus_proxy_new_for_bus_finish (res, &error); if (error != NULL) { g_warning ("failed to connect to PackageKit interface: %s", error->message); g_ptr_array_unref (data->argv); g_free (data); g_error_free (error); return; } builder = g_variant_builder_new (G_VARIANT_TYPE ("as")); g_variant_builder_add (builder, "s", g_ptr_array_index (data->argv, 0)); g_dbus_proxy_call (session_installer, "InstallProvideFiles", g_variant_new ("(uass)", data->xid, builder, "hide-finished" ), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &gcm_packagekit_finished_cb, data->argv); g_free (data); g_variant_builder_unref (builder); } static void gcm_prefs_install_component (guint xid, GPtrArray *argv) { struct gcm_packagekit_closure_data *data; data = g_malloc (sizeof (*data)); data->argv = argv; data->xid = xid; g_ptr_array_ref (data->argv); g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS, NULL, "org.freedesktop.PackageKit", "/org/freedesktop/PackageKit", "org.freedesktop.PackageKit.Modify", NULL, &gcm_packagekit_proxy_ready_cb, data); } static void gcm_prefs_run_maybe_install (guint xid, gchar *filename, GPtrArray *argv) { gboolean ret; GError *error = NULL; ret = g_spawn_async (NULL, (gchar**) argv->pdata, NULL, 0, NULL, NULL, NULL, &error); if (!ret) { if ((error->domain == g_spawn_error_quark ()) && (error->code == G_SPAWN_ERROR_NOENT)) { gcm_prefs_install_component (xid, argv); } else { g_warning ("failed to run command: %s", error->message); } g_error_free (error); } } static void gcm_prefs_calibrate_cb (GtkWidget *widget, CcColorPanel *prefs) { guint xid; GPtrArray *argv; gchar *calibrater_filename; CcColorPanelPrivate *priv = prefs->priv; /* get xid */ xid = gdk_x11_window_get_xid (gtk_widget_get_window (GTK_WIDGET (priv->main_window))); calibrater_filename = g_build_filename (BINDIR, "gcm-calibrate", NULL); /* run with modal set */ argv = g_ptr_array_new_with_free_func (g_free); g_ptr_array_add (argv, calibrater_filename); g_ptr_array_add (argv, g_strdup ("--device")); g_ptr_array_add (argv, g_strdup (cd_device_get_id (priv->current_device))); g_ptr_array_add (argv, g_strdup ("--parent-window")); g_ptr_array_add (argv, g_strdup_printf ("%i", xid)); g_ptr_array_add (argv, NULL); gcm_prefs_run_maybe_install (xid, calibrater_filename, argv); g_ptr_array_unref (argv); } static void gcm_prefs_device_add_cb (GtkWidget *widget, CcColorPanel *prefs) { CcColorPanelPrivate *priv = prefs->priv; /* show ui */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_virtual")); gtk_widget_show (widget); gtk_window_set_transient_for (GTK_WINDOW (widget), GTK_WINDOW (priv->main_window)); /* clear entries */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_virtual_type")); gtk_combo_box_set_active (GTK_COMBO_BOX(widget), 0); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "entry_virtual_model")); gtk_entry_set_text (GTK_ENTRY (widget), ""); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "entry_virtual_manufacturer")); gtk_entry_set_text (GTK_ENTRY (widget), ""); } static gboolean gcm_prefs_is_profile_suitable_for_device (CdProfile *profile, CdDevice *device) { #if CD_CHECK_VERSION(0,1,14) const gchar *data_source; #endif CdProfileKind profile_kind_tmp; CdProfileKind profile_kind; CdColorspace profile_colorspace; CdColorspace device_colorspace = 0; gboolean ret = FALSE; CdDeviceKind device_kind; /* not the right colorspace */ device_colorspace = cd_device_get_colorspace (device); profile_colorspace = cd_profile_get_colorspace (profile); if (device_colorspace != profile_colorspace) goto out; /* not the correct kind */ device_kind = cd_device_get_kind (device); profile_kind_tmp = cd_profile_get_kind (profile); profile_kind = cd_device_kind_to_profile_kind (device_kind); if (profile_kind_tmp != profile_kind) goto out; #if CD_CHECK_VERSION(0,1,14) /* ignore the colorspace profiles */ data_source = cd_profile_get_metadata_item (profile, CD_PROFILE_METADATA_DATA_SOURCE); if (g_strcmp0 (data_source, CD_PROFILE_METADATA_DATA_SOURCE_STANDARD) == 0) goto out; #endif /* success */ ret = TRUE; out: return ret; } static gint gcm_prefs_combo_sort_func_cb (GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer user_data) { gint type_a, type_b; gchar *text_a; gchar *text_b; gint retval; /* get data from model */ gtk_tree_model_get (model, a, GCM_PREFS_COMBO_COLUMN_TYPE, &type_a, GCM_PREFS_COMBO_COLUMN_TEXT, &text_a, -1); gtk_tree_model_get (model, b, GCM_PREFS_COMBO_COLUMN_TYPE, &type_b, GCM_PREFS_COMBO_COLUMN_TEXT, &text_b, -1); /* prefer normal type profiles over the 'Other Profile...' entry */ if (type_a < type_b) retval = -1; else if (type_a > type_b) retval = 1; else retval = g_strcmp0 (text_a, text_b); g_free (text_a); g_free (text_b); return retval; } static gboolean gcm_prefs_combo_set_default_cb (gpointer user_data) { GtkWidget *widget = GTK_WIDGET (user_data); gtk_combo_box_set_active (GTK_COMBO_BOX (widget), 0); return FALSE; } static gboolean gcm_prefs_profile_exists_in_array (GPtrArray *array, CdProfile *profile) { CdProfile *profile_tmp; guint i; for (i = 0; i < array->len; i++) { profile_tmp = g_ptr_array_index (array, i); if (cd_profile_equal (profile, profile_tmp)) return TRUE; } return FALSE; } static void gcm_prefs_add_profiles_suitable_for_devices (CcColorPanel *prefs, GtkWidget *widget, GPtrArray *profiles) { CdProfile *profile_tmp; gboolean ret; GError *error = NULL; GPtrArray *profile_array = NULL; GtkTreeIter iter; GtkTreeModel *model; guint i; CcColorPanelPrivate *priv = prefs->priv; /* clear existing entries */ model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget)); gtk_list_store_clear (GTK_LIST_STORE (model)); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (model), GCM_PREFS_COMBO_COLUMN_TEXT, GTK_SORT_ASCENDING); gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (model), GCM_PREFS_COMBO_COLUMN_TEXT, gcm_prefs_combo_sort_func_cb, model, NULL); /* get profiles */ profile_array = cd_client_get_profiles_sync (priv->client, priv->cancellable, &error); if (profile_array == NULL) { g_warning ("failed to get profiles: %s", error->message); g_error_free (error); goto out; } /* add profiles of the right kind */ for (i = 0; i < profile_array->len; i++) { profile_tmp = g_ptr_array_index (profile_array, i); /* get properties */ ret = cd_profile_connect_sync (profile_tmp, priv->cancellable, &error); if (!ret) { g_warning ("failed to get profile: %s", error->message); g_error_free (error); goto out; } /* don't add any of the already added profiles */ if (profiles != NULL) { if (gcm_prefs_profile_exists_in_array (profiles, profile_tmp)) continue; } /* only add correct types */ ret = gcm_prefs_is_profile_suitable_for_device (profile_tmp, priv->current_device); if (!ret) continue; #if CD_CHECK_VERSION(0,1,13) /* ignore profiles from other user accounts */ if (!cd_profile_has_access (profile_tmp)) continue; #endif /* add */ gcm_prefs_combobox_add_profile (widget, profile_tmp, GCM_PREFS_ENTRY_TYPE_PROFILE, &iter); } /* add a import entry */ #if CD_CHECK_VERSION(0,1,12) gcm_prefs_combobox_add_profile (widget, NULL, GCM_PREFS_ENTRY_TYPE_IMPORT, NULL); #endif g_idle_add (gcm_prefs_combo_set_default_cb, widget); out: if (profile_array != NULL) g_ptr_array_unref (profile_array); } static void gcm_prefs_profile_add_cb (GtkWidget *widget, CcColorPanel *prefs) { const gchar *title; GPtrArray *profiles; CcColorPanelPrivate *priv = prefs->priv; /* add profiles of the right kind */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_profile")); profiles = cd_device_get_profiles (priv->current_device); gcm_prefs_add_profiles_suitable_for_devices (prefs, widget, profiles); /* set the title */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "label_assign_title")); switch (cd_device_get_kind (priv->current_device)) { case CD_DEVICE_KIND_DISPLAY: /* TRANSLATORS: this is the dialog title in the 'Add profile' UI */ title = _("Available Profiles for Displays"); break; case CD_DEVICE_KIND_SCANNER: /* TRANSLATORS: this is the dialog title in the 'Add profile' UI */ title = _("Available Profiles for Scanners"); break; case CD_DEVICE_KIND_PRINTER: /* TRANSLATORS: this is the dialog title in the 'Add profile' UI */ title = _("Available Profiles for Printers"); break; case CD_DEVICE_KIND_CAMERA: /* TRANSLATORS: this is the dialog title in the 'Add profile' UI */ title = _("Available Profiles for Cameras"); break; case CD_DEVICE_KIND_WEBCAM: /* TRANSLATORS: this is the dialog title in the 'Add profile' UI */ title = _("Available Profiles for Webcams"); break; default: /* TRANSLATORS: this is the dialog title in the 'Add profile' UI * where the device type is not recognised */ title = _("Available Profiles"); break; } gtk_label_set_label (GTK_LABEL (widget), title); /* show the dialog */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_assign")); gtk_widget_show (widget); gtk_window_set_transient_for (GTK_WINDOW (widget), GTK_WINDOW (priv->main_window)); if (profiles != NULL) g_ptr_array_unref (profiles); } static void gcm_prefs_profile_remove_cb (GtkWidget *widget, CcColorPanel *prefs) { GtkTreeIter iter; GtkTreeSelection *selection; GtkTreeModel *model; gboolean ret = FALSE; CdProfile *profile = NULL; GError *error = NULL; CcColorPanelPrivate *priv = prefs->priv; /* get the selected row */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "treeview_devices")); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget)); if (!gtk_tree_selection_get_selected (selection, &model, &iter)) goto out; /* if the profile is default, then we'll have to make the first profile default */ gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_PROFILE, &profile, -1); /* just remove it, the list store will get ::changed */ ret = cd_device_remove_profile_sync (priv->current_device, profile, priv->cancellable, &error); if (!ret) { g_warning ("failed to remove profile: %s", error->message); g_error_free (error); goto out; } out: if (profile != NULL) g_object_unref (profile); return; } static void gcm_prefs_make_profile_default_cb (GObject *object, GAsyncResult *res, gpointer user_data) { CdDevice *device = CD_DEVICE (object); gboolean ret = FALSE; GError *error = NULL; ret = cd_device_make_profile_default_finish (device, res, &error); if (!ret) { g_warning ("failed to set default profile on %s: %s", cd_device_get_id (device), error->message); g_error_free (error); } } static void gcm_prefs_profile_make_default_internal (CcColorPanel *prefs, GtkTreeModel *model, GtkTreeIter *iter_selected) { CdDevice *device; CdProfile *profile; CcColorPanelPrivate *priv = prefs->priv; /* get currentlt selected item */ gtk_tree_model_get (model, iter_selected, GCM_PREFS_COLUMN_DEVICE, &device, GCM_PREFS_COLUMN_PROFILE, &profile, -1); if (profile == NULL || device == NULL) goto out; /* just set it default */ g_debug ("setting %s default on %s", cd_profile_get_id (profile), cd_device_get_id (device)); cd_device_make_profile_default (device, profile, priv->cancellable, gcm_prefs_make_profile_default_cb, prefs); out: if (profile != NULL) g_object_unref (profile); if (device != NULL) g_object_unref (device); } static void gcm_prefs_profile_view_cb (GtkWidget *widget, CcColorPanel *prefs) { CdProfile *profile = NULL; GtkTreeIter iter; GtkTreeModel *model; GtkTreeSelection *selection; gchar *options = NULL; gchar *viewer_filename; GPtrArray *argv = NULL; guint xid; CcColorPanelPrivate *priv = prefs->priv; /* get the selected row */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "treeview_devices")); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget)); if (!gtk_tree_selection_get_selected (selection, &model, &iter)) g_assert_not_reached (); /* get currentlt selected item */ gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_PROFILE, &profile, -1); /* get xid */ xid = gdk_x11_window_get_xid (gtk_widget_get_window (GTK_WIDGET (priv->main_window))); viewer_filename = g_build_filename (BINDIR, "gcm-viewer", NULL); /* open up gcm-viewer as a info pane */ argv = g_ptr_array_new_with_free_func (g_free); g_ptr_array_add (argv, viewer_filename); g_ptr_array_add (argv, g_strdup ("--profile")); g_ptr_array_add (argv, g_strdup (cd_profile_get_id (profile))); g_ptr_array_add (argv, g_strdup ("--parent-window")); g_ptr_array_add (argv, g_strdup_printf ("%i", xid)); g_ptr_array_add (argv, NULL); gcm_prefs_run_maybe_install (xid, viewer_filename, argv); g_ptr_array_unref (argv); g_free (options); if (profile != NULL) g_object_unref (profile); } static void gcm_prefs_button_assign_cancel_cb (GtkWidget *widget, CcColorPanel *prefs) { CcColorPanelPrivate *priv = prefs->priv; widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_assign")); gtk_widget_hide (widget); } static void gcm_prefs_button_assign_ok_cb (GtkWidget *widget, CcColorPanel *prefs) { GtkTreeIter iter; GtkTreeModel *model; CdProfile *profile = NULL; gboolean ret = FALSE; GError *error = NULL; CcColorPanelPrivate *priv = prefs->priv; /* hide window */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_assign")); gtk_widget_hide (widget); /* get entry */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_profile")); ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); if (!ret) goto out; model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_tree_model_get (model, &iter, GCM_PREFS_COMBO_COLUMN_PROFILE, &profile, -1); if (profile == NULL) { g_warning ("failed to get the active profile"); goto out; } /* just add it, the list store will get ::changed */ ret = cd_device_add_profile_sync (priv->current_device, CD_DEVICE_RELATION_HARD, profile, priv->cancellable, &error); if (!ret) { g_warning ("failed to add: %s", error->message); g_error_free (error); goto out; } /* make it default */ cd_device_make_profile_default (priv->current_device, profile, priv->cancellable, gcm_prefs_make_profile_default_cb, prefs); out: if (profile != NULL) g_object_unref (profile); } static gboolean gcm_prefs_profile_delete_event_cb (GtkWidget *widget, GdkEvent *event, CcColorPanel *prefs) { gcm_prefs_button_assign_cancel_cb (widget, prefs); return TRUE; } static void gcm_prefs_delete_cb (GtkWidget *widget, CcColorPanel *prefs) { gboolean ret = FALSE; GError *error = NULL; CcColorPanelPrivate *priv = prefs->priv; /* try to delete device */ ret = cd_client_delete_device_sync (priv->client, priv->current_device, priv->cancellable, &error); if (!ret) { g_warning ("failed to delete device: %s", error->message); g_error_free (error); } } static void gcm_prefs_treeview_renderer_toggled (GtkCellRendererToggle *cell, const gchar *path, CcColorPanel *prefs) { gboolean ret; GtkTreeModel *model; GtkTreeIter iter; CcColorPanelPrivate *priv = prefs->priv; model = GTK_TREE_MODEL (priv->list_store_devices); ret = gtk_tree_model_get_iter_from_string (model, &iter, path); if (!ret) return; gcm_prefs_profile_make_default_internal (prefs, model, &iter); } static void gcm_prefs_add_devices_columns (CcColorPanel *prefs, GtkTreeView *treeview) { GtkCellRenderer *renderer; GtkTreeViewColumn *column; CcColorPanelPrivate *priv = prefs->priv; gtk_tree_view_set_headers_visible (treeview, TRUE); /* --- column for device image and device title --- */ column = gtk_tree_view_column_new (); gtk_tree_view_column_set_expand (column, TRUE); /* TRANSLATORS: column for device list */ gtk_tree_view_column_set_title (column, _("Device")); /* image */ renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (renderer, "stock-size", GTK_ICON_SIZE_MENU, NULL); gtk_tree_view_column_pack_start (column, renderer, FALSE); gtk_tree_view_column_add_attribute (column, renderer, "icon-name", GCM_PREFS_COLUMN_ICON); /* option */ renderer = gtk_cell_renderer_toggle_new (); g_signal_connect (renderer, "toggled", G_CALLBACK (gcm_prefs_treeview_renderer_toggled), prefs); g_object_set (renderer, "radio", TRUE, NULL); gtk_tree_view_column_pack_start (column, renderer, FALSE); gtk_tree_view_column_add_attribute (column, renderer, "active", GCM_PREFS_COLUMN_RADIO_ACTIVE); gtk_tree_view_column_add_attribute (column, renderer, "visible", GCM_PREFS_COLUMN_RADIO_VISIBLE); /* text */ renderer = gtk_cell_renderer_text_new (); gtk_tree_view_column_pack_start (column, renderer, TRUE); gtk_tree_view_column_add_attribute (column, renderer, "markup", GCM_PREFS_COLUMN_TITLE); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (priv->list_store_devices), GCM_PREFS_COLUMN_SORT, GTK_SORT_DESCENDING); gtk_tree_view_append_column (treeview, GTK_TREE_VIEW_COLUMN(column)); /* --- column for device status --- */ column = gtk_tree_view_column_new (); gtk_tree_view_column_set_expand (column, TRUE); /* TRANSLATORS: column for device list */ gtk_tree_view_column_set_title (column, _("Calibration")); /* image */ renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (renderer, "stock-size", GTK_ICON_SIZE_MENU, NULL); gtk_tree_view_column_pack_start (column, renderer, FALSE); gtk_tree_view_column_add_attribute (column, renderer, "icon-name", GCM_PREFS_COLUMN_STATUS_IMAGE); /* text */ renderer = gtk_cell_renderer_text_new (); gtk_tree_view_column_pack_start (column, renderer, TRUE); gtk_tree_view_column_add_attribute (column, renderer, "markup", GCM_PREFS_COLUMN_STATUS); gtk_tree_view_column_set_expand (column, FALSE); gtk_tree_view_append_column (treeview, GTK_TREE_VIEW_COLUMN(column)); /* tooltip */ gtk_tree_view_set_tooltip_column (treeview, GCM_PREFS_COLUMN_TOOLTIP); } static void gcm_prefs_set_calibrate_button_sensitivity (CcColorPanel *prefs) { gboolean ret = FALSE; GtkWidget *widget; const gchar *tooltip; CdDeviceKind kind; CcColorPanelPrivate *priv = prefs->priv; /* TRANSLATORS: this is when the button is sensitive */ tooltip = _("Create a color profile for the selected device"); /* no device selected */ if (priv->current_device == NULL) goto out; /* are we a display */ kind = cd_device_get_kind (priv->current_device); if (kind == CD_DEVICE_KIND_DISPLAY) { /* find whether we have hardware installed */ if (priv->sensor == NULL) { /* TRANSLATORS: this is when the button is insensitive */ tooltip = _("The measuring instrument is not detected. Please check it is turned on and correctly connected."); goto out; } /* success */ ret = TRUE; } else if (kind == CD_DEVICE_KIND_SCANNER || kind == CD_DEVICE_KIND_CAMERA || kind == CD_DEVICE_KIND_WEBCAM) { /* TODO: find out if we can scan using gnome-scan */ ret = TRUE; } else if (kind == CD_DEVICE_KIND_PRINTER) { /* find whether we have hardware installed */ if (priv->sensor == NULL) { /* TRANSLATORS: this is when the button is insensitive */ tooltip = _("The measuring instrument is not detected. Please check it is turned on and correctly connected."); goto out; } /* find whether we have hardware installed */ ret = cd_sensor_has_cap (priv->sensor, CD_SENSOR_CAP_PRINTER); if (!ret) { /* TRANSLATORS: this is when the button is insensitive */ tooltip = _("The measuring instrument does not support printer profiling."); goto out; } /* success */ ret = TRUE; } else { /* TRANSLATORS: this is when the button is insensitive */ tooltip = _("The device type is not currently supported."); } out: /* control the tooltip and sensitivity of the button */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_calibrate")); gtk_widget_set_tooltip_text (widget, tooltip); gtk_widget_set_sensitive (widget, ret); } static void gcm_prefs_device_clicked (CcColorPanel *prefs, CdDevice *device) { GtkWidget *widget; CdDeviceMode device_mode; CcColorPanelPrivate *priv = prefs->priv; if (device == NULL) g_assert_not_reached (); /* get current device */ if (priv->current_device != NULL) g_object_unref (priv->current_device); priv->current_device = g_object_ref (device); /* we have a new device */ g_debug ("selected device is: %s", cd_device_get_id (device)); /* make sure selectable */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_profile")); gtk_widget_set_sensitive (widget, TRUE); /* can we delete this device? */ device_mode = cd_device_get_mode (priv->current_device); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_remove")); gtk_widget_set_visible (widget, device_mode == CD_DEVICE_MODE_VIRTUAL); /* can this device calibrate */ gcm_prefs_set_calibrate_button_sensitivity (prefs); } static void gcm_prefs_profile_clicked (CcColorPanel *prefs, CdProfile *profile, CdDevice *device) { GtkWidget *widget; CdDeviceRelation relation; CcColorPanelPrivate *priv = prefs->priv; /* get profile */ g_debug ("selected profile = %s", cd_profile_get_filename (profile)); /* find the profile relationship */ relation = cd_device_get_profile_relation_sync (device, profile, NULL, NULL); /* we can only remove hard relationships */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_remove")); if (relation == CD_DEVICE_RELATION_HARD) { gtk_widget_set_tooltip_text (widget, ""); gtk_widget_set_sensitive (widget, TRUE); } else { /* TRANSLATORS: this is when an auto-added profile cannot be removed */ gtk_widget_set_tooltip_text (widget, _("Cannot remove automatically added profile")); gtk_widget_set_sensitive (widget, FALSE); } /* allow getting profile info */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_view")); gtk_widget_set_sensitive (widget, TRUE); /* hide device specific stuff */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_remove")); gtk_widget_set_visible (widget, FALSE); } static void gcm_prefs_devices_treeview_clicked_cb (GtkTreeSelection *selection, CcColorPanel *prefs) { GtkTreeModel *model; GtkTreeIter iter; CdDevice *device = NULL; CdProfile *profile = NULL; GtkWidget *widget; CcColorPanelPrivate *priv = prefs->priv; /* get selection */ if (!gtk_tree_selection_get_selected (selection, &model, &iter)) return; gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_DEVICE, &device, GCM_PREFS_COLUMN_PROFILE, &profile, -1); /* device actions */ if (device != NULL) gcm_prefs_device_clicked (prefs, device); if (profile != NULL) gcm_prefs_profile_clicked (prefs, profile, device); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_default")); gtk_widget_set_visible (widget, profile != NULL); if (profile) gtk_widget_set_sensitive (widget, !cd_profile_get_is_system_wide (profile)); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_add")); gtk_widget_set_visible (widget, FALSE); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_calibrate")); gtk_widget_set_visible (widget, device != NULL); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_add")); gtk_widget_set_visible (widget, device != NULL); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_view")); gtk_widget_set_visible (widget, profile != NULL); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_remove")); gtk_widget_set_visible (widget, profile != NULL); /* if no buttons then hide toolbar */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbar_devices")); gtk_widget_set_visible (widget, profile != NULL || device != NULL); if (device != NULL) g_object_unref (device); if (profile != NULL) g_object_unref (profile); } static void gcm_prefs_treeview_row_activated_cb (GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, CcColorPanel *prefs) { GtkTreeModel *model; GtkTreeIter iter; gboolean ret; CcColorPanelPrivate *priv = prefs->priv; /* get the iter */ model = GTK_TREE_MODEL (priv->list_store_devices); ret = gtk_tree_model_get_iter (model, &iter, path); if (!ret) return; /* make this profile the default */ gcm_prefs_profile_make_default_internal (prefs, model, &iter); } static const gchar * gcm_prefs_device_kind_to_sort (CdDeviceKind kind) { if (kind == CD_DEVICE_KIND_DISPLAY) return "4"; if (kind == CD_DEVICE_KIND_SCANNER) return "3"; if (kind == CD_DEVICE_KIND_CAMERA) return "2"; if (kind == CD_DEVICE_KIND_PRINTER) return "1"; return "0"; } static gchar * gcm_device_get_title (CdDevice *device) { const gchar *model; const gchar *vendor; GString *string; /* try to get a nice string suitable for display */ vendor = cd_device_get_vendor (device); model = cd_device_get_model (device); string = g_string_new (""); if (vendor != NULL && model != NULL) { g_string_append_printf (string, "%s - %s", vendor, model); goto out; } /* just model */ if (model != NULL) { g_string_append (string, model); goto out; } /* just vendor */ if (vendor != NULL) { g_string_append (string, vendor); goto out; } /* fallback to id */ g_string_append (string, cd_device_get_id (device)); out: return g_string_free (string, FALSE); } static void gcm_prefs_set_combo_simple_text (GtkWidget *combo_box) { GtkCellRenderer *renderer; GtkListStore *store; store = gtk_list_store_new (GCM_PREFS_COMBO_COLUMN_NUM_COLUMNS, G_TYPE_STRING, CD_TYPE_PROFILE, G_TYPE_UINT); gtk_combo_box_set_model (GTK_COMBO_BOX (combo_box), GTK_TREE_MODEL (store)); g_object_unref (store); renderer = gtk_cell_renderer_text_new (); g_object_set (renderer, "ellipsize", PANGO_ELLIPSIZE_END, "wrap-mode", PANGO_WRAP_WORD_CHAR, NULL); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, TRUE); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer, "text", GCM_PREFS_COMBO_COLUMN_TEXT, NULL); } static void gcm_prefs_profile_combo_changed_cb (GtkWidget *widget, CcColorPanel *prefs) { GFile *file = NULL; GError *error = NULL; gboolean ret; CdProfile *profile = NULL; GtkTreeIter iter; GtkTreeModel *model; GcmPrefsEntryType entry_type; CcColorPanelPrivate *priv = prefs->priv; /* no devices */ if (priv->current_device == NULL) return; /* no selection */ ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); if (!ret) return; /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_tree_model_get (model, &iter, GCM_PREFS_COMBO_COLUMN_TYPE, &entry_type, -1); /* import */ if (entry_type == GCM_PREFS_ENTRY_TYPE_IMPORT) { file = gcm_prefs_file_chooser_get_icc_profile (prefs); if (file == NULL) { g_warning ("failed to get ICC file"); gtk_combo_box_set_active (GTK_COMBO_BOX (widget), 0); /* if we've got no other existing profiles to choose, then * just close the assign dialog */ gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); gtk_tree_model_get (model, &iter, GCM_PREFS_COMBO_COLUMN_TYPE, &entry_type, -1); if (entry_type == GCM_PREFS_ENTRY_TYPE_IMPORT) { widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_assign")); gtk_widget_hide (widget); } goto out; } #if CD_CHECK_VERSION(0,1,12) profile = cd_client_import_profile_sync (priv->client, file, priv->cancellable, &error); if (profile == NULL) { g_warning ("failed to get imported profile: %s", error->message); g_error_free (error); goto out; } #endif /* add to combobox */ gtk_list_store_append (GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, GCM_PREFS_COMBO_COLUMN_PROFILE, profile, -1); gtk_combo_box_set_active_iter (GTK_COMBO_BOX (widget), &iter); } out: if (file != NULL) g_object_unref (file); if (profile != NULL) g_object_unref (profile); } static void gcm_prefs_sensor_coldplug (CcColorPanel *prefs) { GPtrArray *sensors; GError *error = NULL; gboolean ret; CcColorPanelPrivate *priv = prefs->priv; /* unref old */ if (priv->sensor != NULL) { g_object_unref (priv->sensor); priv->sensor = NULL; } /* no present */ sensors = cd_client_get_sensors_sync (priv->client, NULL, &error); if (sensors == NULL) { g_warning ("%s", error->message); g_error_free (error); goto out; } if (sensors->len == 0) goto out; /* save a copy of the sensor */ priv->sensor = g_object_ref (g_ptr_array_index (sensors, 0)); /* connect to the sensor */ ret = cd_sensor_connect_sync (priv->sensor, NULL, &error); if (!ret) { g_warning ("%s", error->message); g_error_free (error); goto out; } out: if (sensors != NULL) g_ptr_array_unref (sensors); } static void gcm_prefs_client_sensor_changed_cb (CdClient *client, CdSensor *sensor, CcColorPanel *prefs) { gcm_prefs_sensor_coldplug (prefs); gcm_prefs_set_calibrate_button_sensitivity (prefs); } static const gchar * gcm_prefs_device_kind_to_icon_name (CdDeviceKind kind) { switch (kind) { case CD_DEVICE_KIND_DISPLAY: return "video-display"; case CD_DEVICE_KIND_SCANNER: return "scanner"; case CD_DEVICE_KIND_PRINTER: return "printer"; case CD_DEVICE_KIND_CAMERA: return "camera-photo"; case CD_DEVICE_KIND_WEBCAM: return "camera-web"; default: return "image-missing"; } } static GString * gcm_prefs_get_profile_age_as_string (CdProfile *profile) { const gchar *id; gint64 age; GString *string = NULL; if (profile == NULL) { /* TRANSLATORS: this is when there is no profile for the device */ string = g_string_new (_("No profile")); goto out; } /* don't show details for EDID, colorspace or test profiles */ id = cd_profile_get_metadata_item (profile, CD_PROFILE_METADATA_DATA_SOURCE); if (g_strcmp0 (id, CD_PROFILE_METADATA_DATA_SOURCE_EDID) == 0) goto out; #if CD_CHECK_VERSION(0,1,14) if (g_strcmp0 (id, CD_PROFILE_METADATA_DATA_SOURCE_STANDARD) == 0) goto out; if (g_strcmp0 (id, CD_PROFILE_METADATA_DATA_SOURCE_TEST) == 0) goto out; #endif /* days */ age = cd_profile_get_age (profile); if (age == 0) { string = g_string_new (NULL); goto out; } age /= 60 * 60 * 24; string = g_string_new (""); /* approximate years */ if (age > 365) { age /= 365; g_string_append_printf (string, ngettext ( "%i year", "%i years", age), (guint) age); goto out; } /* approximate months */ if (age > 30) { age /= 30; g_string_append_printf (string, ngettext ( "%i month", "%i months", age), (guint) age); goto out; } /* approximate weeks */ if (age > 7) { age /= 7; g_string_append_printf (string, ngettext ( "%i week", "%i weeks", age), (guint) age); goto out; } /* fallback */ g_string_append_printf (string, _("Less than 1 week")); out: return string; } static gchar * gcm_prefs_get_profile_created_for_sort (CdProfile *profile) { gint64 created; gchar *string = NULL; GDateTime *dt = NULL; /* get profile age */ created = cd_profile_get_created (profile); if (created == 0) goto out; dt = g_date_time_new_from_unix_utc (created); /* note: this is not shown in the UI, just used for sorting */ string = g_date_time_format (dt, "%Y%m%d"); out: if (dt != NULL) g_date_time_unref (dt); return string; } static gchar * gcm_prefs_get_profile_title (CcColorPanel *prefs, CdProfile *profile) { CdColorspace colorspace; const gchar *title; gchar *string; gboolean ret; GError *error = NULL; CcColorPanelPrivate *priv = prefs->priv; g_return_val_if_fail (profile != NULL, NULL); string = NULL; /* get properties */ ret = cd_profile_connect_sync (profile, priv->cancellable, &error); if (!ret) { g_warning ("failed to get profile: %s", error->message); g_error_free (error); goto out; } /* add profile description */ title = cd_profile_get_title (profile); if (title != NULL) { string = g_markup_escape_text (title, -1); goto out; } /* some meta profiles do not have ICC profiles */ colorspace = cd_profile_get_colorspace (profile); if (colorspace == CD_COLORSPACE_RGB) { string = g_strdup (C_("Colorspace fallback", "Default RGB")); goto out; } if (colorspace == CD_COLORSPACE_CMYK) { string = g_strdup (C_("Colorspace fallback", "Default CMYK")); goto out; } if (colorspace == CD_COLORSPACE_GRAY) { string = g_strdup (C_("Colorspace fallback", "Default Gray")); goto out; } /* fall back to ID, ick */ string = g_strdup (cd_profile_get_id (profile)); out: return string; } static void gcm_prefs_device_remove_profiles_phase1 (CcColorPanel *prefs, GtkTreeIter *parent) { GtkTreeIter iter; GtkTreeModel *model; gboolean ret; CcColorPanelPrivate *priv = prefs->priv; /* get first element */ model = GTK_TREE_MODEL (priv->list_store_devices); ret = gtk_tree_model_iter_children (model, &iter, parent); if (!ret) return; /* mark to be removed */ do { gtk_tree_store_set (priv->list_store_devices, &iter, GCM_PREFS_COLUMN_DEVICE_PATH, NULL, -1); } while (gtk_tree_model_iter_next (model, &iter)); } static void gcm_prefs_device_remove_profiles_phase2 (CcColorPanel *prefs, GtkTreeIter *parent) { GtkTreeIter iter; GtkTreeModel *model; gchar *id_tmp; gboolean ret; CcColorPanelPrivate *priv = prefs->priv; /* get first element */ model = GTK_TREE_MODEL (priv->list_store_devices); ret = gtk_tree_model_iter_children (model, &iter, parent); if (!ret) return; /* remove the other elements */ do { gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_DEVICE_PATH, &id_tmp, -1); if (id_tmp == NULL) ret = gtk_tree_store_remove (priv->list_store_devices, &iter); else ret = gtk_tree_model_iter_next (model, &iter); g_free (id_tmp); } while (ret); } static GtkTreeIter * get_iter_for_profile (GtkTreeModel *model, CdProfile *profile, GtkTreeIter *parent) { const gchar *id; gboolean ret; GtkTreeIter iter; CdProfile *profile_tmp; /* get first element */ ret = gtk_tree_model_iter_children (model, &iter, parent); if (!ret) return NULL; /* remove the other elements */ id = cd_profile_get_id (profile); while (ret) { gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_PROFILE, &profile_tmp, -1); if (g_strcmp0 (id, cd_profile_get_id (profile_tmp)) == 0) { g_object_unref (profile_tmp); return gtk_tree_iter_copy (&iter); } g_object_unref (profile_tmp); ret = gtk_tree_model_iter_next (model, &iter); } return NULL; } static void gcm_prefs_device_set_model_by_iter (CcColorPanel *prefs, CdDevice *device, GtkTreeIter *iter) { GString *status = NULL; const gchar *status_image = NULL; const gchar *tooltip = NULL; CdProfile *profile = NULL; gint age; GPtrArray *profiles = NULL; CdProfile *profile_tmp; guint i; gchar *title_tmp; GString *date_tmp; gchar *sort_tmp; GtkTreeIter iter_tmp; GtkTreeIter *iter_tmp_p; guint threshold = 0; gboolean ret; GError *error = NULL; CcColorPanelPrivate *priv = prefs->priv; /* set status */ profile = cd_device_get_default_profile (device); if (profile == NULL) { status = g_string_new (_("Uncalibrated")); g_string_prepend (status, "<span foreground='gray'><i>"); g_string_append (status, "</i></span>"); tooltip = _("This device is not color managed."); goto skip; } /* get properties */ ret = cd_profile_connect_sync (profile, priv->cancellable, &error); if (!ret) { g_warning ("failed to get profile: %s", error->message); g_error_free (error); goto out; } #if CD_CHECK_VERSION(0,1,13) /* ignore profiles from other user accounts */ if (!cd_profile_has_access (profile)) { /* only print the filename if it exists */ if (cd_profile_get_filename (profile) != NULL) { g_warning ("%s is not usable by this user", cd_profile_get_filename (profile)); } else { g_warning ("%s is not usable by this user", cd_profile_get_id (profile)); } goto out; } #endif /* autogenerated printer defaults */ if (cd_device_get_kind (device) == CD_DEVICE_KIND_PRINTER && cd_profile_get_filename (profile) == NULL) { status = g_string_new (_("Uncalibrated")); g_string_prepend (status, "<span foreground='gray'><i>"); g_string_append (status, "</i></span>"); tooltip = _("This device is using manufacturing calibrated data."); goto skip; } /* autogenerated profiles are crap */ if (cd_profile_get_kind (profile) == CD_PROFILE_KIND_DISPLAY_DEVICE && !cd_profile_get_has_vcgt (profile)) { status = g_string_new (_("Uncalibrated")); g_string_prepend (status, "<span foreground='gray'><i>"); g_string_append (status, "</i></span>"); tooltip = _("This device does not have a profile suitable for whole-screen color correction."); goto skip; } /* yay! */ status = gcm_prefs_get_profile_age_as_string (profile); if (status == NULL) { status = g_string_new (_("Uncalibrated")); g_string_prepend (status, "<span foreground='gray'><i>"); g_string_append (status, "</i></span>"); } /* greater than the calibration threshold for the device type */ age = cd_profile_get_age (profile); age /= 60 * 60 * 24; if (cd_device_get_kind (device) == CD_DEVICE_KIND_DISPLAY) { g_settings_get (priv->settings, GCM_SETTINGS_RECALIBRATE_DISPLAY_THRESHOLD, "u", &threshold); } else if (cd_device_get_kind (device) == CD_DEVICE_KIND_DISPLAY) { g_settings_get (priv->settings, GCM_SETTINGS_RECALIBRATE_PRINTER_THRESHOLD, "u", &threshold); } if (threshold > 0 && age > threshold) { status_image = "dialog-warning-symbolic"; tooltip = _("This device has an old profile that may no longer be accurate."); } skip: /* save to store */ gtk_tree_store_set (priv->list_store_devices, iter, GCM_PREFS_COLUMN_STATUS, status->str, GCM_PREFS_COLUMN_STATUS_IMAGE, status_image, GCM_PREFS_COLUMN_TOOLTIP, tooltip, -1); /* remove old profiles */ gcm_prefs_device_remove_profiles_phase1 (prefs, iter); /* add profiles */ profiles = cd_device_get_profiles (device); if (profiles == NULL) goto out; for (i = 0; i < profiles->len; i++) { profile_tmp = g_ptr_array_index (profiles, i); title_tmp = gcm_prefs_get_profile_title (prefs, profile_tmp); /* get profile age */ date_tmp = gcm_prefs_get_profile_age_as_string (profile_tmp); if (date_tmp == NULL) { /* TRANSLATORS: this is when the calibration profile age is not * specified as it has been autogenerated from the hardware */ date_tmp = g_string_new (_("Not specified")); g_string_prepend (date_tmp, "<span foreground='gray'><i>"); g_string_append (date_tmp, "</i></span>"); } sort_tmp = gcm_prefs_get_profile_created_for_sort (profile_tmp); /* get an existing profile, or create a new one */ iter_tmp_p = get_iter_for_profile (GTK_TREE_MODEL (priv->list_store_devices), profile_tmp, iter); if (iter_tmp_p == NULL) gtk_tree_store_append (priv->list_store_devices, &iter_tmp, iter); gtk_tree_store_set (priv->list_store_devices, iter_tmp_p ? iter_tmp_p : &iter_tmp, GCM_PREFS_COLUMN_DEVICE, device, GCM_PREFS_COLUMN_PROFILE, profile_tmp, GCM_PREFS_COLUMN_DEVICE_PATH, cd_device_get_object_path (device), GCM_PREFS_COLUMN_SORT, sort_tmp, GCM_PREFS_COLUMN_STATUS, date_tmp->str, GCM_PREFS_COLUMN_TITLE, title_tmp, GCM_PREFS_COLUMN_RADIO_VISIBLE, TRUE, GCM_PREFS_COLUMN_RADIO_ACTIVE, i==0, -1); if (iter_tmp_p != NULL) gtk_tree_iter_free (iter_tmp_p); g_free (title_tmp); g_free (sort_tmp); g_string_free (date_tmp, TRUE); } /* remove old profiles that no longer exist */ gcm_prefs_device_remove_profiles_phase2 (prefs, iter); out: if (status != NULL) g_string_free (status, TRUE); if (profiles != NULL) g_ptr_array_unref (profiles); if (profile != NULL) g_object_unref (profile); } static void gcm_prefs_device_changed_cb (CdDevice *device, CcColorPanel *prefs) { const gchar *id; gboolean ret; gchar *id_tmp; GtkTreeIter iter; GtkTreeModel *model; CcColorPanelPrivate *priv = prefs->priv; /* get first element */ model = GTK_TREE_MODEL (priv->list_store_devices); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* get the other elements */ id = cd_device_get_object_path (device); do { gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_DEVICE_PATH, &id_tmp, -1); if (g_strcmp0 (id_tmp, id) == 0) { /* populate device */ gcm_prefs_device_set_model_by_iter (prefs, device, &iter); } g_free (id_tmp); } while (gtk_tree_model_iter_next (model, &iter)); } static void gcm_prefs_add_device (CcColorPanel *prefs, CdDevice *device) { gboolean ret; GError *error = NULL; CdDeviceKind kind; const gchar *icon_name; const gchar *id; gchar *sort = NULL; gchar *title = NULL; GtkTreeIter parent; CcColorPanelPrivate *priv = prefs->priv; /* get device properties */ ret = cd_device_connect_sync (device, priv->cancellable, &error); if (!ret) { g_warning ("failed to connect to the device: %s", error->message); g_error_free (error); goto out; } /* get icon */ kind = cd_device_get_kind (device); icon_name = gcm_prefs_device_kind_to_icon_name (kind); /* italic for non-connected devices */ title = gcm_device_get_title (device); /* create sort order */ sort = g_strdup_printf ("%s%s", gcm_prefs_device_kind_to_sort (kind), title); /* watch for changes to update the status icons */ g_signal_connect (device, "changed", G_CALLBACK (gcm_prefs_device_changed_cb), prefs); /* add to list */ id = cd_device_get_object_path (device); g_debug ("add %s to device list", id); gtk_tree_store_append (priv->list_store_devices, &parent, NULL); gtk_tree_store_set (priv->list_store_devices, &parent, GCM_PREFS_COLUMN_DEVICE, device, GCM_PREFS_COLUMN_DEVICE_PATH, id, GCM_PREFS_COLUMN_SORT, sort, GCM_PREFS_COLUMN_TITLE, title, GCM_PREFS_COLUMN_ICON, icon_name, -1); gcm_prefs_device_set_model_by_iter (prefs, device, &parent); out: g_free (sort); g_free (title); } static void gcm_prefs_remove_device (CcColorPanel *prefs, CdDevice *cd_device) { GtkTreeIter iter; GtkTreeModel *model; const gchar *id; gchar *id_tmp; gboolean ret; CdDevice *device_tmp; CcColorPanelPrivate *priv = prefs->priv; /* remove */ id = cd_device_get_object_path (cd_device); /* get first element */ model = GTK_TREE_MODEL (priv->list_store_devices); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; /* get the other elements */ do { gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_DEVICE_PATH, &id_tmp, -1); if (g_strcmp0 (id_tmp, id) == 0) { gtk_tree_model_get (model, &iter, GCM_PREFS_COLUMN_DEVICE, &device_tmp, -1); g_signal_handlers_disconnect_by_func (device_tmp, G_CALLBACK (gcm_prefs_device_changed_cb), prefs); gtk_tree_store_remove (GTK_TREE_STORE (model), &iter); g_free (id_tmp); g_object_unref (device_tmp); break; } g_free (id_tmp); } while (gtk_tree_model_iter_next (model, &iter)); } static void gcm_prefs_update_device_list_extra_entry (CcColorPanel *prefs) { CcColorPanelPrivate *priv = prefs->priv; gboolean ret; gchar *id_tmp; gchar *title = NULL; GtkTreeIter iter; /* select the first device */ ret = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->list_store_devices), &iter); if (!ret) { /* add the 'No devices detected' entry */ title = g_strdup_printf ("<i>%s</i>", _("No devices supporting color management detected")); gtk_tree_store_append (priv->list_store_devices, &iter, NULL); gtk_tree_store_set (priv->list_store_devices, &iter, GCM_PREFS_COLUMN_RADIO_VISIBLE, FALSE, GCM_PREFS_COLUMN_TITLE, title, -1); g_free (title); return; } /* remove the 'No devices detected' entry */ do { gtk_tree_model_get (GTK_TREE_MODEL (priv->list_store_devices), &iter, GCM_PREFS_COLUMN_DEVICE_PATH, &id_tmp, -1); if (id_tmp == NULL) { gtk_tree_store_remove (priv->list_store_devices, &iter); break; } g_free (id_tmp); } while (gtk_tree_model_iter_next (GTK_TREE_MODEL (priv->list_store_devices), &iter)); } static void gcm_prefs_device_added_cb (CdClient *client, CdDevice *device, CcColorPanel *prefs) { /* add the device */ gcm_prefs_add_device (prefs, device); /* ensure we're not showing the 'No devices detected' entry */ gcm_prefs_update_device_list_extra_entry (prefs); } static void gcm_prefs_changed_cb (CdClient *client, CdDevice *device, CcColorPanel *prefs) { g_debug ("changed: %s (doing nothing)", cd_device_get_id (device)); } static void gcm_prefs_device_removed_cb (CdClient *client, CdDevice *device, CcColorPanel *prefs) { GtkTreeIter iter; GtkTreeSelection *selection; GtkWidget *widget; gboolean ret; CcColorPanelPrivate *priv = prefs->priv; /* remove from the UI */ gcm_prefs_remove_device (prefs, device); /* ensure we showing the 'No devices detected' entry if required */ gcm_prefs_update_device_list_extra_entry (prefs); /* select the first device */ ret = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->list_store_devices), &iter); if (!ret) return; /* click it */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "treeview_devices")); gtk_tree_view_set_model (GTK_TREE_VIEW (widget), GTK_TREE_MODEL (priv->list_store_devices)); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget)); gtk_tree_selection_select_iter (selection, &iter); } static gboolean gcm_prefs_tree_model_count_cb (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer user_data) { guint *i = (guint *) user_data; (*i)++; return FALSE; } static void gcm_prefs_get_devices_cb (GObject *object, GAsyncResult *res, gpointer user_data) { CcColorPanel *prefs = (CcColorPanel *) user_data; CdClient *client = CD_CLIENT (object); CdDevice *device; GError *error = NULL; GPtrArray *devices; GtkTreePath *path; GtkWidget *widget; guint i; guint devices_and_profiles = 0; CcColorPanelPrivate *priv = prefs->priv; /* get devices and add them */ devices = cd_client_get_devices_finish (client, res, &error); if (devices == NULL) { g_warning ("failed to add connected devices: %s", error->message); g_error_free (error); goto out; } for (i = 0; i < devices->len; i++) { device = g_ptr_array_index (devices, i); gcm_prefs_add_device (prefs, device); } /* ensure we show the 'No devices detected' entry if empty */ gcm_prefs_update_device_list_extra_entry (prefs); /* set the cursor on the first device */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "treeview_devices")); path = gtk_tree_path_new_from_string ("0"); gtk_tree_view_set_cursor (GTK_TREE_VIEW (widget), path, NULL, FALSE); gtk_tree_path_free (path); /* if we have only a few devices and profiles expand the treeview * devices so they can all be seen */ gtk_tree_model_foreach (GTK_TREE_MODEL (priv->list_store_devices), gcm_prefs_tree_model_count_cb, &devices_and_profiles); if (devices_and_profiles <= GCM_PREFS_MAX_DEVICES_PROFILES_EXPANDED) gtk_tree_view_expand_all (GTK_TREE_VIEW (widget)); out: if (devices != NULL) g_ptr_array_unref (devices); } static void gcm_prefs_button_virtual_add_cb (GtkWidget *widget, CcColorPanel *prefs) { CdDeviceKind device_kind; CdDevice *device; const gchar *model; const gchar *manufacturer; gchar *device_id; GError *error = NULL; GHashTable *device_props; CcColorPanelPrivate *priv = prefs->priv; /* get device details */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_virtual_type")); device_kind = gtk_combo_box_get_active (GTK_COMBO_BOX(widget)) + 2; widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "entry_virtual_model")); model = gtk_entry_get_text (GTK_ENTRY (widget)); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "entry_virtual_manufacturer")); manufacturer = gtk_entry_get_text (GTK_ENTRY (widget)); /* create device */ device_id = g_strdup_printf ("%s-%s-%s", cd_device_kind_to_string (device_kind), manufacturer, model); device_props = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); g_hash_table_insert (device_props, g_strdup ("Kind"), g_strdup (cd_device_kind_to_string (device_kind))); g_hash_table_insert (device_props, g_strdup ("Mode"), g_strdup (cd_device_mode_to_string (CD_DEVICE_MODE_VIRTUAL))); g_hash_table_insert (device_props, g_strdup ("Colorspace"), g_strdup (cd_colorspace_to_string (CD_COLORSPACE_RGB))); g_hash_table_insert (device_props, g_strdup ("Model"), g_strdup (model)); g_hash_table_insert (device_props, g_strdup ("Vendor"), g_strdup (manufacturer)); device = cd_client_create_device_sync (priv->client, device_id, CD_OBJECT_SCOPE_DISK, device_props, priv->cancellable, &error); if (device == NULL) { g_warning ("Failed to add create virtual device: %s", error->message); g_error_free (error); goto out; } out: g_hash_table_unref (device_props); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_virtual")); gtk_widget_hide (widget); g_free (device_id); } static void gcm_prefs_button_virtual_cancel_cb (GtkWidget *widget, CcColorPanel *prefs) { CcColorPanelPrivate *priv = prefs->priv; widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_virtual")); gtk_widget_hide (widget); } static gboolean gcm_prefs_virtual_delete_event_cb (GtkWidget *widget, GdkEvent *event, CcColorPanel *prefs) { gcm_prefs_button_virtual_cancel_cb (widget, prefs); return TRUE; } static const gchar * cd_device_kind_to_localised_string (CdDeviceKind device_kind) { if (device_kind == CD_DEVICE_KIND_DISPLAY) return C_("Device kind", "Display"); if (device_kind == CD_DEVICE_KIND_SCANNER) return C_("Device kind", "Scanner"); if (device_kind == CD_DEVICE_KIND_PRINTER) return C_("Device kind", "Printer"); if (device_kind == CD_DEVICE_KIND_CAMERA) return C_("Device kind", "Camera"); if (device_kind == CD_DEVICE_KIND_WEBCAM) return C_("Device kind", "Webcam"); return NULL; } static void gcm_prefs_setup_virtual_combobox (GtkWidget *widget) { guint i; const gchar *text; for (i=CD_DEVICE_KIND_SCANNER; i<CD_DEVICE_KIND_LAST; i++) { text = cd_device_kind_to_localised_string (i); if (text == NULL) continue; gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(widget), text); } gtk_combo_box_set_active (GTK_COMBO_BOX (widget), CD_DEVICE_KIND_PRINTER - 2); } static gboolean gcm_prefs_virtual_set_from_file (CcColorPanel *prefs, GFile *file) { /* TODO: use GCM to get the EXIF data */ return FALSE; } static void gcm_prefs_virtual_drag_data_received_cb (GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *data, guint info, guint _time, CcColorPanel *prefs) { const guchar *filename; gchar **filenames = NULL; GFile *file = NULL; guint i; gboolean ret; /* get filenames */ filename = gtk_selection_data_get_data (data); if (filename == NULL) { gtk_drag_finish (context, FALSE, FALSE, _time); goto out; } /* import this */ g_debug ("dropped: %p (%s)", data, filename); /* split, as multiple drag targets are accepted */ filenames = g_strsplit_set ((const gchar *)filename, "\r\n", -1); for (i = 0; filenames[i] != NULL; i++) { /* blank entry */ if (filenames[i][0] == '\0') continue; /* check this is a parsable file */ g_debug ("trying to set %s", filenames[i]); file = g_file_new_for_uri (filenames[i]); ret = gcm_prefs_virtual_set_from_file (prefs, file); if (!ret) { g_debug ("%s did not set from file correctly", filenames[i]); gtk_drag_finish (context, FALSE, FALSE, _time); goto out; } g_object_unref (file); file = NULL; } gtk_drag_finish (context, TRUE, FALSE, _time); out: if (file != NULL) g_object_unref (file); g_strfreev (filenames); } static void gcm_prefs_setup_drag_and_drop (GtkWidget *widget) { GtkTargetEntry entry; /* setup a dummy entry */ entry.target = g_strdup ("text/plain"); entry.flags = GTK_TARGET_OTHER_APP; entry.info = 0; gtk_drag_dest_set (widget, GTK_DEST_DEFAULT_ALL, &entry, 1, GDK_ACTION_MOVE | GDK_ACTION_COPY); g_free (entry.target); } static void gcm_prefs_connect_cb (GObject *object, GAsyncResult *res, gpointer user_data) { gboolean ret; GError *error = NULL; CcColorPanel *prefs = CC_COLOR_PANEL (user_data); CcColorPanelPrivate *priv = prefs->priv; ret = cd_client_connect_finish (priv->client, res, &error); if (!ret) { g_warning ("failed to connect to colord: %s", error->message); g_error_free (error); return; } /* set calibrate button sensitivity */ gcm_prefs_sensor_coldplug (prefs); /* get devices */ cd_client_get_devices (priv->client, priv->cancellable, gcm_prefs_get_devices_cb, prefs); } static void gcm_prefs_window_realize_cb (GtkWidget *widget, CcColorPanel *prefs) { prefs->priv->main_window = gtk_widget_get_toplevel (widget); } static const char * cc_color_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/color"; else return "help:gnome-help/color"; } static void cc_color_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_color_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_color_panel_dispose (GObject *object) { CcColorPanelPrivate *priv = CC_COLOR_PANEL (object)->priv; if (priv->settings) { g_object_unref (priv->settings); priv->settings = NULL; } if (priv->cancellable != NULL) { g_cancellable_cancel (priv->cancellable); g_object_unref (priv->cancellable); priv->cancellable = NULL; } if (priv->builder != NULL) { g_object_unref (priv->builder); priv->builder = NULL; } if (priv->client != NULL) { g_object_unref (priv->client); priv->client = NULL; } if (priv->current_device != NULL) { g_object_unref (priv->current_device); priv->current_device = NULL; } if (priv->sensor != NULL) { g_object_unref (priv->sensor); priv->sensor = NULL; } G_OBJECT_CLASS (cc_color_panel_parent_class)->dispose (object); } static void cc_color_panel_finalize (GObject *object) { G_OBJECT_CLASS (cc_color_panel_parent_class)->finalize (object); } static void cc_color_panel_class_init (CcColorPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcColorPanelPrivate)); panel_class->get_help_uri = cc_color_panel_get_help_uri; object_class->get_property = cc_color_panel_get_property; object_class->set_property = cc_color_panel_set_property; object_class->dispose = cc_color_panel_dispose; object_class->finalize = cc_color_panel_finalize; } static void cc_color_panel_init (CcColorPanel *prefs) { CcColorPanelPrivate *priv; GError *error = NULL; GtkStyleContext *context; GtkTreeSelection *selection; GtkWidget *widget; priv = prefs->priv = COLOR_PANEL_PRIVATE (prefs); priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (priv->builder, GETTEXT_PACKAGE); gtk_builder_add_from_file (priv->builder, CINNAMONCC_UI_DIR "/color.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } priv->cancellable = g_cancellable_new (); /* setup defaults */ priv->settings = g_settings_new (GCM_SETTINGS_SCHEMA); /* create list stores */ priv->list_store_devices = gtk_tree_store_new (GCM_PREFS_COLUMN_NUM_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, CD_TYPE_DEVICE, CD_TYPE_PROFILE, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); /* assign buttons */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_add")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_profile_add_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_remove")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_profile_remove_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_profile_view")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_profile_view_cb), prefs); /* create device tree view */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "treeview_devices")); gtk_tree_view_set_model (GTK_TREE_VIEW (widget), GTK_TREE_MODEL (priv->list_store_devices)); gtk_tree_view_set_enable_tree_lines (GTK_TREE_VIEW (widget), TRUE); gtk_tree_view_set_level_indentation (GTK_TREE_VIEW (widget), 0); selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget)); g_signal_connect (selection, "changed", G_CALLBACK (gcm_prefs_devices_treeview_clicked_cb), prefs); g_signal_connect (GTK_TREE_VIEW (widget), "row-activated", G_CALLBACK (gcm_prefs_treeview_row_activated_cb), prefs); g_signal_connect (GTK_TREE_VIEW (widget), "popup-menu", G_CALLBACK (gcm_prefs_treeview_popup_menu_cb), prefs); /* add columns to the tree view */ gcm_prefs_add_devices_columns (prefs, GTK_TREE_VIEW (widget)); /* force to be at least ~6 rows high */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "scrolledwindow_devices")); gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (widget), 200); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_default")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_default_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_remove")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_delete_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_add")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_device_add_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbutton_device_calibrate")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_calibrate_cb), prefs); /* make devices toolbar sexy */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "scrolledwindow_devices")); context = gtk_widget_get_style_context (widget); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "toolbar_devices")); context = gtk_widget_get_style_context (widget); gtk_style_context_add_class (context, GTK_STYLE_CLASS_INLINE_TOOLBAR); gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP); /* set up virtual dialog */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_virtual")); g_signal_connect (widget, "delete-event", G_CALLBACK (gcm_prefs_virtual_delete_event_cb), prefs); g_signal_connect (widget, "drag-data-received", G_CALLBACK (gcm_prefs_virtual_drag_data_received_cb), prefs); gcm_prefs_setup_drag_and_drop (widget); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "button_virtual_add")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_button_virtual_add_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "button_virtual_cancel")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_button_virtual_cancel_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_virtual_type")); gcm_prefs_setup_virtual_combobox (widget); /* set up assign dialog */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "dialog_assign")); g_signal_connect (widget, "delete-event", G_CALLBACK (gcm_prefs_profile_delete_event_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "button_assign_cancel")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_button_assign_cancel_cb), prefs); widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "button_assign_ok")); g_signal_connect (widget, "clicked", G_CALLBACK (gcm_prefs_button_assign_ok_cb), prefs); /* setup icc profiles list */ widget = GTK_WIDGET (gtk_builder_get_object (priv->builder, "combobox_profile")); gcm_prefs_set_combo_simple_text (widget); gtk_widget_set_sensitive (widget, FALSE); g_signal_connect (G_OBJECT (widget), "changed", G_CALLBACK (gcm_prefs_profile_combo_changed_cb), prefs); /* use a device client array */ priv->client = cd_client_new (); g_signal_connect (priv->client, "device-added", G_CALLBACK (gcm_prefs_device_added_cb), prefs); g_signal_connect (priv->client, "device-removed", G_CALLBACK (gcm_prefs_device_removed_cb), prefs); g_signal_connect (priv->client, "changed", G_CALLBACK (gcm_prefs_changed_cb), prefs); /* connect to colord */ cd_client_connect (priv->client, priv->cancellable, gcm_prefs_connect_cb, prefs); /* use the color sensor */ g_signal_connect (priv->client, "sensor-added", G_CALLBACK (gcm_prefs_client_sensor_changed_cb), prefs); g_signal_connect (priv->client, "sensor-removed", G_CALLBACK (gcm_prefs_client_sensor_changed_cb), prefs); /* set calibrate button sensitivity */ gcm_prefs_set_calibrate_button_sensitivity (prefs); widget = WID (priv->builder, "dialog-vbox1"); gtk_widget_reparent (widget, (GtkWidget *) prefs); g_signal_connect (widget, "realize", G_CALLBACK (gcm_prefs_window_realize_cb), prefs); widget = WID (priv->builder, "linkbutton_help"); if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) g_object_set (G_OBJECT (widget), "uri", "help:ubuntu-help/color-whyimportant", NULL); } void cc_color_panel_register (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); cc_color_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_COLOR_PANEL, "color", 0); }
478
./cinnamon-control-center/panels/color/color-module.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc * Copyright (C) 2011 Richard Hughes <richard@hughsie.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * */ #include <config.h> #include "cc-color-panel.h" #include <glib/gi18n-lib.h> void g_io_module_load (GIOModule *module) { /* register the panel */ cc_color_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
479
./cinnamon-control-center/panels/screen/cc-screen-panel.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc * Copyright (C) 2008 William Jon McCann <jmccann@redhat.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include "cc-screen-panel.h" #include <glib/gi18n-lib.h> CC_PANEL_REGISTER (CcScreenPanel, cc_screen_panel) #define SCREEN_PANEL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_SCREEN_PANEL, CcScreenPanelPrivate)) #define WID(s) GTK_WIDGET (gtk_builder_get_object (self->priv->builder, s)) #define LS(s) GTK_LIST_STORE (gtk_builder_get_object (self->priv->builder, s)) struct _CcScreenPanelPrivate { GSettings *lock_settings; GSettings *csd_settings; GSettings *session_settings; GSettings *lockdown_settings; GCancellable *cancellable; GtkBuilder *builder; GDBusProxy *proxy; gboolean setting_brightness; }; static void cc_screen_panel_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_screen_panel_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_screen_panel_dispose (GObject *object) { CcScreenPanelPrivate *priv = CC_SCREEN_PANEL (object)->priv; if (priv->lock_settings) { g_object_unref (priv->lock_settings); priv->lock_settings = NULL; } if (priv->csd_settings) { g_object_unref (priv->csd_settings); priv->csd_settings = NULL; } if (priv->session_settings) { g_object_unref (priv->session_settings); priv->session_settings = NULL; } if (priv->lockdown_settings) { g_object_unref (priv->lockdown_settings); priv->lockdown_settings = NULL; } if (priv->cancellable != NULL) { g_cancellable_cancel (priv->cancellable); g_object_unref (priv->cancellable); priv->cancellable = NULL; } if (priv->builder != NULL) { g_object_unref (priv->builder); priv->builder = NULL; } if (priv->proxy != NULL) { g_object_unref (priv->proxy); priv->proxy = NULL; } G_OBJECT_CLASS (cc_screen_panel_parent_class)->dispose (object); } static void on_lock_settings_changed (GSettings *settings, const char *key, CcScreenPanel *panel) { if (g_str_equal (key, "lock-delay") == FALSE) return; } static void update_lock_screen_sensitivity (CcScreenPanel *self) { GtkWidget *widget; gboolean locked; widget = WID ("screen_lock_main_box"); locked = g_settings_get_boolean (self->priv->lockdown_settings, "disable-lock-screen"); gtk_widget_set_sensitive (widget, !locked); } static void on_lockdown_settings_changed (GSettings *settings, const char *key, CcScreenPanel *panel) { if (g_str_equal (key, "disable-lock-screen") == FALSE) return; update_lock_screen_sensitivity (panel); } static const char * cc_screen_panel_get_help_uri (CcPanel *panel) { if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) return "help:ubuntu-help/prefs-display"; else return "help:cinnamon-help/prefs-display"; } static void cc_screen_panel_class_init (CcScreenPanelClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcPanelClass *panel_class = CC_PANEL_CLASS (klass); g_type_class_add_private (klass, sizeof (CcScreenPanelPrivate)); object_class->get_property = cc_screen_panel_get_property; object_class->set_property = cc_screen_panel_set_property; object_class->dispose = cc_screen_panel_dispose; panel_class->get_help_uri = cc_screen_panel_get_help_uri; } static void set_brightness_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; GVariant *result; CcScreenPanelPrivate *priv = CC_SCREEN_PANEL (user_data)->priv; /* not setting, so pay attention to changed signals */ priv->setting_brightness = FALSE; result = g_dbus_proxy_call_finish (G_DBUS_PROXY (source_object), res, &error); if (result == NULL) { g_printerr ("Error setting brightness: %s\n", error->message); g_error_free (error); return; } } static void brightness_slider_value_changed_cb (GtkRange *range, gpointer user_data) { guint percentage; CcScreenPanelPrivate *priv = CC_SCREEN_PANEL (user_data)->priv; /* do not loop */ if (priv->setting_brightness) return; priv->setting_brightness = TRUE; /* push this to g-p-m */ percentage = (guint) gtk_range_get_value (range); g_dbus_proxy_call (priv->proxy, "SetPercentage", g_variant_new ("(u)", percentage), G_DBUS_CALL_FLAGS_NONE, -1, priv->cancellable, set_brightness_cb, user_data); } static void get_brightness_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; GVariant *result; guint brightness; GtkRange *range; CcScreenPanel *self = CC_SCREEN_PANEL (user_data); result = g_dbus_proxy_call_finish (G_DBUS_PROXY (source_object), res, &error); if (result == NULL) { /* We got cancelled, so we're probably exiting */ if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { g_error_free (error); return; } gtk_widget_hide (WID ("screen_brightness_hscale")); gtk_widget_hide (WID ("screen_auto_reduce_checkbutton")); gtk_widget_hide (WID ("brightness-frame")); g_object_set (G_OBJECT (WID ("turn-off-alignment")), "left-padding", 0, NULL); if (error->message && strstr (error->message, "No backlight devices present") == NULL) { g_warning ("Error getting brightness: %s", error->message); } g_error_free (error); return; } /* set the slider */ g_variant_get (result, "(u)", &brightness); range = GTK_RANGE (WID ("screen_brightness_hscale")); gtk_range_set_range (range, 0, 100); gtk_range_set_increments (range, 1, 10); gtk_range_set_value (range, brightness); g_signal_connect (range, "value-changed", G_CALLBACK (brightness_slider_value_changed_cb), user_data); g_variant_unref (result); } static void on_signal (GDBusProxy *proxy, gchar *sender_name, gchar *signal_name, GVariant *parameters, gpointer user_data) { CcScreenPanel *self = CC_SCREEN_PANEL (user_data); if (g_strcmp0 (signal_name, "Changed") == 0) { /* changed, but ignoring */ if (self->priv->setting_brightness) return; /* retrieve the value again from g-s-d */ g_dbus_proxy_call (self->priv->proxy, "GetPercentage", NULL, G_DBUS_CALL_FLAGS_NONE, 200, /* we don't want to randomly move the bar */ self->priv->cancellable, get_brightness_cb, user_data); } } static void got_power_proxy_cb (GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = NULL; CcScreenPanelPrivate *priv = CC_SCREEN_PANEL (user_data)->priv; priv->proxy = g_dbus_proxy_new_for_bus_finish (res, &error); if (priv->proxy == NULL) { g_printerr ("Error creating proxy: %s\n", error->message); g_error_free (error); return; } /* we want to change the bar if the user presses brightness buttons */ g_signal_connect (priv->proxy, "g-signal", G_CALLBACK (on_signal), user_data); /* get the initial state */ g_dbus_proxy_call (priv->proxy, "GetPercentage", NULL, G_DBUS_CALL_FLAGS_NONE, 200, /* we don't want to randomly move the bar */ priv->cancellable, get_brightness_cb, user_data); } static void set_idle_delay_from_dpms (CcScreenPanel *self, int value) { guint off_delay; off_delay = 0; if (value > 0) off_delay = (guint) value; g_settings_set (self->priv->session_settings, "idle-delay", "u", off_delay); } static void dpms_combo_changed_cb (GtkWidget *widget, CcScreenPanel *self) { GtkTreeIter iter; GtkTreeModel *model; gint value; gboolean ret; /* no selection */ ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); if (!ret) return; /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_tree_model_get (model, &iter, 1, &value, -1); /* set both battery and ac keys */ g_settings_set_int (self->priv->csd_settings, "sleep-display-ac", value); g_settings_set_int (self->priv->csd_settings, "sleep-display-battery", value); set_idle_delay_from_dpms (self, value); } static void lock_combo_changed_cb (GtkWidget *widget, CcScreenPanel *self) { GtkTreeIter iter; GtkTreeModel *model; guint delay; gboolean ret; /* no selection */ ret = gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter); if (!ret) return; /* get entry */ model = gtk_combo_box_get_model (GTK_COMBO_BOX(widget)); gtk_tree_model_get (model, &iter, 1, &delay, -1); g_settings_set (self->priv->lock_settings, "lock-delay", "u", delay); } static void set_dpms_value_for_combo (GtkComboBox *combo_box, CcScreenPanel *self) { GtkTreeIter iter; GtkTreeModel *model; gint value; gint value_tmp, value_prev; gboolean ret; guint i; /* get entry */ model = gtk_combo_box_get_model (combo_box); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; value_prev = 0; i = 0; /* try to make the UI match the AC setting */ value = g_settings_get_int (self->priv->csd_settings, "sleep-display-ac"); do { gtk_tree_model_get (model, &iter, 1, &value_tmp, -1); if (value == value_tmp) { gtk_combo_box_set_active_iter (combo_box, &iter); return; } value_prev = value_tmp; i++; } while (gtk_tree_model_iter_next (model, &iter)); /* If we didn't find the setting in the list */ gtk_combo_box_set_active (combo_box, i - 1); } static void set_lock_value_for_combo (GtkComboBox *combo_box, CcScreenPanel *self) { GtkTreeIter iter; GtkTreeModel *model; guint value; gint value_tmp, value_prev; gboolean ret; guint i; /* get entry */ model = gtk_combo_box_get_model (combo_box); ret = gtk_tree_model_get_iter_first (model, &iter); if (!ret) return; value_prev = 0; i = 0; /* try to make the UI match the lock setting */ g_settings_get (self->priv->lock_settings, "lock-delay", "u", &value); do { gtk_tree_model_get (model, &iter, 1, &value_tmp, -1); if (value == value_tmp || (value_tmp > value_prev && value < value_tmp)) { gtk_combo_box_set_active_iter (combo_box, &iter); return; } value_prev = value_tmp; i++; } while (gtk_tree_model_iter_next (model, &iter)); /* If we didn't find the setting in the list */ gtk_combo_box_set_active (combo_box, i - 1); } static void cc_screen_panel_init (CcScreenPanel *self) { GError *error; GtkWidget *widget; self->priv = SCREEN_PANEL_PRIVATE (self); self->priv->builder = gtk_builder_new (); gtk_builder_set_translation_domain (self->priv->builder, GETTEXT_PACKAGE); error = NULL; gtk_builder_add_from_file (self->priv->builder, CINNAMONCC_UI_DIR "/screen.ui", &error); if (error != NULL) { g_warning ("Could not load interface file: %s", error->message); g_error_free (error); return; } self->priv->cancellable = g_cancellable_new (); /* get initial brightness version */ g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.cinnamon.SettingsDaemon", "/org/cinnamon/SettingsDaemon/Power", "org.cinnamon.SettingsDaemon.Power.Screen", self->priv->cancellable, got_power_proxy_cb, self); self->priv->lock_settings = g_settings_new ("org.gnome.desktop.screensaver"); g_signal_connect (self->priv->lock_settings, "changed", G_CALLBACK (on_lock_settings_changed), self); self->priv->csd_settings = g_settings_new ("org.cinnamon.settings-daemon.plugins.power"); self->priv->session_settings = g_settings_new ("org.gnome.desktop.session"); self->priv->lockdown_settings = g_settings_new ("org.gnome.desktop.lockdown"); g_signal_connect (self->priv->lockdown_settings, "changed", G_CALLBACK (on_lockdown_settings_changed), self); /* bind the auto dim checkbox */ widget = WID ("screen_auto_reduce_checkbutton"); g_settings_bind (self->priv->csd_settings, "idle-dim-battery", widget, "active", G_SETTINGS_BIND_DEFAULT); /* display off time */ widget = WID ("screen_brightness_combobox"); GtkListStore *store = LS ("screen_brightness_liststore"); gtk_combo_box_set_model (GTK_COMBO_BOX (widget), store); set_dpms_value_for_combo (GTK_COMBO_BOX (widget), self); g_signal_connect (widget, "changed", G_CALLBACK (dpms_combo_changed_cb), self); /* bind the screen lock checkbox */ widget = WID ("screen_lock_on_switch"); g_settings_bind (self->priv->lock_settings, "lock-enabled", widget, "active", G_SETTINGS_BIND_DEFAULT); /* lock time */ widget = WID ("screen_lock_combobox"); store = LS ("lock_liststore"); gtk_combo_box_set_model (GTK_COMBO_BOX (widget), store); set_lock_value_for_combo (GTK_COMBO_BOX (widget), self); g_signal_connect (widget, "changed", G_CALLBACK (lock_combo_changed_cb), self); widget = WID ("screen_lock_hbox"); g_settings_bind (self->priv->lock_settings, "lock-enabled", widget, "sensitive", G_SETTINGS_BIND_GET); update_lock_screen_sensitivity (self); /* bind the screen lock suspend checkbutton */ widget = WID ("screen_lock_suspend_checkbutton"); gchar **keys = g_settings_list_keys (self->priv->lock_settings); gboolean has_key = FALSE; int i; for (i = 0; i < g_strv_length(keys); i++) { if (g_strcmp0(keys[i], "ubuntu-lock-on-suspend") == 0) { has_key = TRUE; break; } } g_strfreev (keys); if (has_key) { g_settings_bind (self->priv->lock_settings, "ubuntu-lock-on-suspend", widget, "active", G_SETTINGS_BIND_DEFAULT); } else { gtk_widget_destroy (widget); } widget = WID ("screen_vbox"); gtk_widget_reparent (widget, (GtkWidget *) self); g_object_set (self, "valign", GTK_ALIGN_START, NULL); } void cc_screen_panel_register (GIOModule *module) { bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); cc_screen_panel_register_type (G_TYPE_MODULE (module)); g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT, CC_TYPE_SCREEN_PANEL, "screen", 0); }
480
./cinnamon-control-center/panels/screen/screen-module.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * */ #include <config.h> #include "cc-screen-panel.h" #include <glib/gi18n-lib.h> void g_io_module_load (GIOModule *module) { /* register the panel */ cc_screen_panel_register (module); } void g_io_module_unload (GIOModule *module) { }
481
./cinnamon-control-center/shell/cc-shell-nav-bar.c
/* * Copyright 2012 Canonical * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Aurélien Gâteau <aurelien.gateau@canonical.com> */ #include "cc-shell-nav-bar.h" #include "cc-shell-marshal.h" #include <glib/gi18n.h> G_DEFINE_TYPE (CcShellNavBar, cc_shell_nav_bar, GTK_TYPE_BOX) #define SHELL_NAV_BAR_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_SHELL_NAV_BAR, CcShellNavBarPrivate)) struct _CcShellNavBarPrivate { GtkWidget *home_button; GtkWidget *detail_button; }; enum { HOME_CLICKED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {0,}; static void cc_shell_nav_bar_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_nav_bar_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_nav_bar_dispose (GObject *object) { G_OBJECT_CLASS (cc_shell_nav_bar_parent_class)->dispose (object); } static void cc_shell_nav_bar_finalize (GObject *object) { G_OBJECT_CLASS (cc_shell_nav_bar_parent_class)->finalize (object); } static void home_button_clicked_cb (GtkButton *button, CcShellNavBar *bar) { g_signal_emit (bar, signals[HOME_CLICKED], 0); } static void cc_shell_nav_bar_class_init (CcShellNavBarClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (CcShellNavBarPrivate)); object_class->get_property = cc_shell_nav_bar_get_property; object_class->set_property = cc_shell_nav_bar_set_property; object_class->dispose = cc_shell_nav_bar_dispose; object_class->finalize = cc_shell_nav_bar_finalize; signals[HOME_CLICKED] = g_signal_new ("home-clicked", CC_TYPE_SHELL_NAV_BAR, G_SIGNAL_RUN_FIRST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); } static void cc_shell_nav_bar_init (CcShellNavBar *self) { self->priv = SHELL_NAV_BAR_PRIVATE (self); self->priv->home_button = gtk_button_new_with_mnemonic (_("_All Settings")); self->priv->detail_button = gtk_button_new(); gtk_box_pack_start (GTK_BOX(self), self->priv->home_button, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX(self), self->priv->detail_button, FALSE, FALSE, 0); gtk_widget_show (self->priv->home_button); g_signal_connect (self->priv->home_button, "clicked", G_CALLBACK (home_button_clicked_cb), self); GtkStyleContext *context = gtk_widget_get_style_context (GTK_WIDGET(self)); gtk_style_context_add_class (context, GTK_STYLE_CLASS_LINKED); gtk_style_context_add_class (context, "breadcrumbs"); } GtkWidget * cc_shell_nav_bar_new (void) { return g_object_new (CC_TYPE_SHELL_NAV_BAR, NULL); } void cc_shell_nav_bar_show_detail_button (CcShellNavBar *bar, const gchar *label) { gtk_widget_show (bar->priv->detail_button); gtk_button_set_label (GTK_BUTTON (bar->priv->detail_button), label); } void cc_shell_nav_bar_hide_detail_button (CcShellNavBar *bar) { gtk_widget_hide (bar->priv->detail_button); }
482
./cinnamon-control-center/shell/cc-shell.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (c) 2010 Intel, Inc. * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Thomas Wood <thos@gnome.org> */ /** * SECTION:cc-shell * @short_description: Abstract class representing the Control Center shell * * CcShell is an abstract class that represents an instance of a control * center shell. It provides access to some of the properties of the shell * that panels will need to read or change. When a panel is created it has an * instance of CcShell available that represents the current shell. */ #include "cc-shell.h" #include "cc-panel.h" G_DEFINE_ABSTRACT_TYPE (CcShell, cc_shell, G_TYPE_OBJECT) #define SHELL_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_SHELL, CcShellPrivate)) struct _CcShellPrivate { CcPanel *active_panel; }; enum { PROP_ACTIVE_PANEL = 1 }; static void cc_shell_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { CcShell *shell = CC_SHELL (object); switch (property_id) { case PROP_ACTIVE_PANEL: g_value_set_object (value, shell->priv->active_panel); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { CcShell *shell = CC_SHELL (object); switch (property_id) { case PROP_ACTIVE_PANEL: cc_shell_set_active_panel (shell, g_value_get_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_dispose (GObject *object) { /* remove and unref the active shell */ cc_shell_set_active_panel (CC_SHELL (object), NULL); G_OBJECT_CLASS (cc_shell_parent_class)->dispose (object); } static void cc_shell_class_init (CcShellClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GParamSpec *pspec; g_type_class_add_private (klass, sizeof (CcShellPrivate)); object_class->get_property = cc_shell_get_property; object_class->set_property = cc_shell_set_property; object_class->dispose = cc_shell_dispose; pspec = g_param_spec_object ("active-panel", "active panel", "The currently active Panel", CC_TYPE_PANEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_ACTIVE_PANEL, pspec); } static void cc_shell_init (CcShell *self) { self->priv = SHELL_PRIVATE (self); } /** * cc_shell_get_active_panel: * @shell: A #CcShell * * Get the current active panel * * Returns: a #CcPanel or NULL if no panel is active */ CcPanel* cc_shell_get_active_panel (CcShell *shell) { g_return_val_if_fail (CC_IS_SHELL (shell), NULL); return shell->priv->active_panel; } /** * cc_shell_set_active_panel: * @shell: A #CcShell * @panel: A #CcPanel * * Set the current active panel. If @panel is NULL, then the shell is returned * to a state where no panel is being displayed (for example, the list of panels * may be shown instead). * */ void cc_shell_set_active_panel (CcShell *shell, CcPanel *panel) { g_return_if_fail (CC_IS_SHELL (shell)); g_return_if_fail (panel == NULL || CC_IS_PANEL (panel)); if (panel != shell->priv->active_panel) { /* remove the old panel */ g_clear_object (&shell->priv->active_panel); /* set the new panel */ if (panel) { shell->priv->active_panel = g_object_ref (panel); } g_object_notify (G_OBJECT (shell), "active-panel"); } } /** * cc_shell_set_active_panel_from_id: * @shell: A #CcShell * @id: the ID of the panel to set as active * @error: A #GError * * Find a panel corresponding to the specified id and set it as active. * * Returns: #TRUE if the panel was found and set as the active panel */ gboolean cc_shell_set_active_panel_from_id (CcShell *shell, const gchar *id, const gchar **argv, GError **error) { CcShellClass *class; g_return_val_if_fail (CC_IS_SHELL (shell), FALSE); class = (CcShellClass *) G_OBJECT_GET_CLASS (shell); if (!class->set_active_panel_from_id) { g_warning ("Object of type \"%s\" does not implement required virtual" " function \"set_active_panel_from_id\",", G_OBJECT_TYPE_NAME (shell)); return FALSE; } else { return class->set_active_panel_from_id (shell, id, argv, error); } } /** * cc_shell_get_toplevel: * @shell: A #CcShell * * Gets the toplevel window of the shell. * * Returns: The #GtkWidget of the shell window, or #NULL on error. */ GtkWidget * cc_shell_get_toplevel (CcShell *shell) { CcShellClass *klass; g_return_val_if_fail (CC_IS_SHELL (shell), NULL); klass = CC_SHELL_GET_CLASS (shell); if (klass->get_toplevel) { return klass->get_toplevel (shell); } g_warning ("Object of type \"%s\" does not implement required virtual" " function \"get_toplevel\",", G_OBJECT_TYPE_NAME (shell)); return NULL; } void cc_shell_embed_widget_in_header (CcShell *shell, GtkWidget *widget) { CcShellClass *class; g_return_if_fail (CC_IS_SHELL (shell)); class = (CcShellClass *) G_OBJECT_GET_CLASS (shell); if (!class->embed_widget_in_header) { g_warning ("Object of type \"%s\" does not implement required virtual" " function \"embed_widget_in_header\",", G_OBJECT_TYPE_NAME (shell)); } else { class->embed_widget_in_header (shell, widget); } }
483
./cinnamon-control-center/shell/cc-shell-marshal.c
#ifndef __cc_shell_marshal_MARSHAL_H__ #define __cc_shell_marshal_MARSHAL_H__ #include <glib-object.h> G_BEGIN_DECLS #ifdef G_ENABLE_DEBUG #define g_marshal_value_peek_boolean(v) g_value_get_boolean (v) #define g_marshal_value_peek_char(v) g_value_get_schar (v) #define g_marshal_value_peek_uchar(v) g_value_get_uchar (v) #define g_marshal_value_peek_int(v) g_value_get_int (v) #define g_marshal_value_peek_uint(v) g_value_get_uint (v) #define g_marshal_value_peek_long(v) g_value_get_long (v) #define g_marshal_value_peek_ulong(v) g_value_get_ulong (v) #define g_marshal_value_peek_int64(v) g_value_get_int64 (v) #define g_marshal_value_peek_uint64(v) g_value_get_uint64 (v) #define g_marshal_value_peek_enum(v) g_value_get_enum (v) #define g_marshal_value_peek_flags(v) g_value_get_flags (v) #define g_marshal_value_peek_float(v) g_value_get_float (v) #define g_marshal_value_peek_double(v) g_value_get_double (v) #define g_marshal_value_peek_string(v) (char*) g_value_get_string (v) #define g_marshal_value_peek_param(v) g_value_get_param (v) #define g_marshal_value_peek_boxed(v) g_value_get_boxed (v) #define g_marshal_value_peek_pointer(v) g_value_get_pointer (v) #define g_marshal_value_peek_object(v) g_value_get_object (v) #define g_marshal_value_peek_variant(v) g_value_get_variant (v) #else /* !G_ENABLE_DEBUG */ /* WARNING: This code accesses GValues directly, which is UNSUPPORTED API. * Do not access GValues directly in your code. Instead, use the * g_value_get_*() functions */ #define g_marshal_value_peek_boolean(v) (v)->data[0].v_int #define g_marshal_value_peek_char(v) (v)->data[0].v_int #define g_marshal_value_peek_uchar(v) (v)->data[0].v_uint #define g_marshal_value_peek_int(v) (v)->data[0].v_int #define g_marshal_value_peek_uint(v) (v)->data[0].v_uint #define g_marshal_value_peek_long(v) (v)->data[0].v_long #define g_marshal_value_peek_ulong(v) (v)->data[0].v_ulong #define g_marshal_value_peek_int64(v) (v)->data[0].v_int64 #define g_marshal_value_peek_uint64(v) (v)->data[0].v_uint64 #define g_marshal_value_peek_enum(v) (v)->data[0].v_long #define g_marshal_value_peek_flags(v) (v)->data[0].v_ulong #define g_marshal_value_peek_float(v) (v)->data[0].v_float #define g_marshal_value_peek_double(v) (v)->data[0].v_double #define g_marshal_value_peek_string(v) (v)->data[0].v_pointer #define g_marshal_value_peek_param(v) (v)->data[0].v_pointer #define g_marshal_value_peek_boxed(v) (v)->data[0].v_pointer #define g_marshal_value_peek_pointer(v) (v)->data[0].v_pointer #define g_marshal_value_peek_object(v) (v)->data[0].v_pointer #define g_marshal_value_peek_variant(v) (v)->data[0].v_pointer #endif /* !G_ENABLE_DEBUG */ /* VOID:STRING,STRING,STRING (cc-shell-marshal.list:1) */ extern void cc_shell_marshal_VOID__STRING_STRING_STRING (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); void cc_shell_marshal_VOID__STRING_STRING_STRING (GClosure *closure, GValue *return_value G_GNUC_UNUSED, guint n_param_values, const GValue *param_values, gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data) { typedef void (*GMarshalFunc_VOID__STRING_STRING_STRING) (gpointer data1, gpointer arg_1, gpointer arg_2, gpointer arg_3, gpointer data2); register GMarshalFunc_VOID__STRING_STRING_STRING callback; register GCClosure *cc = (GCClosure*) closure; register gpointer data1, data2; g_return_if_fail (n_param_values == 4); if (G_CCLOSURE_SWAP_DATA (closure)) { data1 = closure->data; data2 = g_value_peek_pointer (param_values + 0); } else { data1 = g_value_peek_pointer (param_values + 0); data2 = closure->data; } callback = (GMarshalFunc_VOID__STRING_STRING_STRING) (marshal_data ? marshal_data : cc->callback); callback (data1, g_marshal_value_peek_string (param_values + 1), g_marshal_value_peek_string (param_values + 2), g_marshal_value_peek_string (param_values + 3), data2); } G_END_DECLS #endif /* __cc_shell_marshal_MARSHAL_H__ */
484
./cinnamon-control-center/shell/cc-editable-entry.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright 2009-2010 Red Hat, Inc, * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Written by: Matthias Clasen <mclasen@redhat.com> */ #include <gdk/gdkkeysyms.h> #include "cc-editable-entry.h" #define EMPTY_TEXT "\xe2\x80\x94" struct _CcEditableEntryPrivate { GtkNotebook *notebook; GtkLabel *label; GtkButton *button; GtkEntry *entry; gchar *text; gboolean editable; gboolean selectable; gint weight; gboolean weight_set; gdouble scale; gboolean scale_set; gboolean in_stop_editing; }; #define CC_EDITABLE_ENTRY_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), CC_TYPE_EDITABLE_ENTRY, CcEditableEntryPrivate)) enum { PROP_0, PROP_TEXT, PROP_EDITABLE, PROP_SELECTABLE, PROP_SCALE, PROP_SCALE_SET, PROP_WEIGHT, PROP_WEIGHT_SET }; enum { EDITING_DONE, LAST_SIGNAL }; enum { PAGE_LABEL, PAGE_BUTTON, PAGE_ENTRY }; static guint signals [LAST_SIGNAL] = { 0, }; G_DEFINE_TYPE (CcEditableEntry, cc_editable_entry, GTK_TYPE_ALIGNMENT); void cc_editable_entry_set_text (CcEditableEntry *e, const gchar *text) { CcEditableEntryPrivate *priv; gchar *tmp; GtkWidget *label; priv = e->priv; tmp = g_strdup (text); g_free (priv->text); priv->text = tmp; gtk_entry_set_text (priv->entry, tmp); if (tmp == NULL || tmp[0] == '\0') tmp = EMPTY_TEXT; gtk_label_set_text (priv->label, tmp); label = gtk_bin_get_child (GTK_BIN (priv->button)); gtk_label_set_text (GTK_LABEL (label), tmp); g_object_notify (G_OBJECT (e), "text"); } const gchar * cc_editable_entry_get_text (CcEditableEntry *e) { return e->priv->text; } void cc_editable_entry_set_editable (CcEditableEntry *e, gboolean editable) { CcEditableEntryPrivate *priv; priv = e->priv; if (priv->editable != editable) { priv->editable = editable; gtk_notebook_set_current_page (priv->notebook, editable ? PAGE_BUTTON : PAGE_LABEL); g_object_notify (G_OBJECT (e), "editable"); } } gboolean cc_editable_entry_get_editable (CcEditableEntry *e) { return e->priv->editable; } void cc_editable_entry_set_selectable (CcEditableEntry *e, gboolean selectable) { CcEditableEntryPrivate *priv; priv = e->priv; if (priv->selectable != selectable) { priv->selectable = selectable; gtk_label_set_selectable (priv->label, selectable); g_object_notify (G_OBJECT (e), "selectable"); } } gboolean cc_editable_entry_get_selectable (CcEditableEntry *e) { return e->priv->selectable; } static void update_fonts (CcEditableEntry *e) { PangoAttrList *attrs; PangoAttribute *attr; GtkWidget *label; CcEditableEntryPrivate *priv = e->priv; attrs = pango_attr_list_new (); if (priv->scale_set) { attr = pango_attr_scale_new (priv->scale); pango_attr_list_insert (attrs, attr); } if (priv->weight_set) { attr = pango_attr_weight_new (priv->weight); pango_attr_list_insert (attrs, attr); } gtk_label_set_attributes (priv->label, attrs); label = gtk_bin_get_child (GTK_BIN (priv->button)); gtk_label_set_attributes (GTK_LABEL (label), attrs); g_object_set(priv->entry, "attributes", attrs, NULL); pango_attr_list_unref (attrs); } void cc_editable_entry_set_weight (CcEditableEntry *e, gint weight) { CcEditableEntryPrivate *priv = e->priv; if (priv->weight == weight && priv->weight_set) return; priv->weight = weight; priv->weight_set = TRUE; update_fonts (e); g_object_notify (G_OBJECT (e), "weight"); g_object_notify (G_OBJECT (e), "weight-set"); } gint cc_editable_entry_get_weight (CcEditableEntry *e) { return e->priv->weight; } void cc_editable_entry_set_scale (CcEditableEntry *e, gdouble scale) { CcEditableEntryPrivate *priv = e->priv; if (priv->scale == scale && priv->scale_set) return; priv->scale = scale; priv->scale_set = TRUE; update_fonts (e); g_object_notify (G_OBJECT (e), "scale"); g_object_notify (G_OBJECT (e), "scale-set"); } gdouble cc_editable_entry_get_scale (CcEditableEntry *e) { return e->priv->scale; } static void cc_editable_entry_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { CcEditableEntry *e = CC_EDITABLE_ENTRY (object); switch (prop_id) { case PROP_TEXT: cc_editable_entry_set_text (e, g_value_get_string (value)); break; case PROP_EDITABLE: cc_editable_entry_set_editable (e, g_value_get_boolean (value)); break; case PROP_SELECTABLE: cc_editable_entry_set_selectable (e, g_value_get_boolean (value)); break; case PROP_WEIGHT: cc_editable_entry_set_weight (e, g_value_get_int (value)); break; case PROP_WEIGHT_SET: e->priv->weight_set = g_value_get_boolean (value); break; case PROP_SCALE: cc_editable_entry_set_scale (e, g_value_get_double (value)); break; case PROP_SCALE_SET: e->priv->scale_set = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void cc_editable_entry_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { CcEditableEntry *e = CC_EDITABLE_ENTRY (object); switch (prop_id) { case PROP_TEXT: g_value_set_string (value, cc_editable_entry_get_text (e)); break; case PROP_EDITABLE: g_value_set_boolean (value, cc_editable_entry_get_editable (e)); break; case PROP_SELECTABLE: g_value_set_boolean (value, cc_editable_entry_get_selectable (e)); break; case PROP_WEIGHT: g_value_set_int (value, cc_editable_entry_get_weight (e)); break; case PROP_WEIGHT_SET: g_value_set_boolean (value, e->priv->weight_set); break; case PROP_SCALE: g_value_set_double (value, cc_editable_entry_get_scale (e)); break; case PROP_SCALE_SET: g_value_set_boolean (value, e->priv->scale_set); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void cc_editable_entry_finalize (GObject *object) { CcEditableEntry *e = (CcEditableEntry*)object; g_free (e->priv->text); G_OBJECT_CLASS (cc_editable_entry_parent_class)->finalize (object); } static void cc_editable_entry_class_init (CcEditableEntryClass *class) { GObjectClass *object_class; object_class = G_OBJECT_CLASS (class); object_class->set_property = cc_editable_entry_set_property; object_class->get_property = cc_editable_entry_get_property; object_class->finalize = cc_editable_entry_finalize; signals[EDITING_DONE] = g_signal_new ("editing-done", G_TYPE_FROM_CLASS (class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (CcEditableEntryClass, editing_done), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); g_object_class_install_property (object_class, PROP_TEXT, g_param_spec_string ("text", "Text", "The text of the button", NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_EDITABLE, g_param_spec_boolean ("editable", "Editable", "Whether the text can be edited", FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SELECTABLE, g_param_spec_boolean ("selectable", "Selectable", "Whether the text can be selected by mouse", FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_WEIGHT, g_param_spec_int ("weight", "Font Weight", "The font weight to use", 0, G_MAXINT, PANGO_WEIGHT_NORMAL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_WEIGHT_SET, g_param_spec_boolean ("weight-set", "Font Weight Set", "Whether a font weight is set", FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SCALE, g_param_spec_double ("scale", "Font Scale", "The font scale to use", 0.0, G_MAXDOUBLE, 1.0, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SCALE_SET, g_param_spec_boolean ("scale-set", "Font Scale Set", "Whether a font scale is set", FALSE, G_PARAM_READWRITE)); g_type_class_add_private (class, sizeof (CcEditableEntryPrivate)); } static void start_editing (CcEditableEntry *e) { gtk_notebook_set_current_page (e->priv->notebook, PAGE_ENTRY); } static void stop_editing (CcEditableEntry *e) { /* Avoid launching another "editing-done" signal * caused by the notebook page change */ if (e->priv->in_stop_editing) return; e->priv->in_stop_editing = TRUE; gtk_notebook_set_current_page (e->priv->notebook, PAGE_BUTTON); cc_editable_entry_set_text (e, gtk_entry_get_text (e->priv->entry)); g_signal_emit (e, signals[EDITING_DONE], 0); e->priv->in_stop_editing = FALSE; } static void cancel_editing (CcEditableEntry *e) { gtk_entry_set_text (e->priv->entry, cc_editable_entry_get_text (e)); gtk_notebook_set_current_page (e->priv->notebook, PAGE_BUTTON); } static void button_clicked (GtkWidget *widget, CcEditableEntry *e) { start_editing (e); } static void entry_activated (GtkWidget *widget, CcEditableEntry *e) { stop_editing (e); } static gboolean entry_focus_out (GtkWidget *widget, GdkEventFocus *event, CcEditableEntry *e) { stop_editing (e); return FALSE; } static gboolean entry_key_press (GtkWidget *widget, GdkEventKey *event, CcEditableEntry *e) { if (event->keyval == GDK_KEY_Escape) { cancel_editing (e); } return FALSE; } static void update_button_padding (GtkWidget *widget, GtkAllocation *allocation, CcEditableEntry *e) { CcEditableEntryPrivate *priv = e->priv; GtkAllocation alloc; gint offset; gint pad; gtk_widget_get_allocation (gtk_widget_get_parent (widget), &alloc); offset = allocation->x - alloc.x; gtk_misc_get_padding (GTK_MISC (priv->label), &pad, NULL); if (offset != pad) gtk_misc_set_padding (GTK_MISC (priv->label), offset, 0); } static void cc_editable_entry_init (CcEditableEntry *e) { CcEditableEntryPrivate *priv; priv = e->priv = CC_EDITABLE_ENTRY_GET_PRIVATE (e); priv->weight = PANGO_WEIGHT_NORMAL; priv->weight_set = FALSE; priv->scale = 1.0; priv->scale_set = FALSE; priv->notebook = (GtkNotebook*)gtk_notebook_new (); gtk_notebook_set_show_tabs (priv->notebook, FALSE); gtk_notebook_set_show_border (priv->notebook, FALSE); /* Label */ priv->label = (GtkLabel*)gtk_label_new (EMPTY_TEXT); gtk_misc_set_alignment (GTK_MISC (priv->label), 0.0, 0.5); gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->label, NULL); /* Button */ priv->button = (GtkButton*)gtk_button_new_with_label (EMPTY_TEXT); gtk_widget_set_receives_default ((GtkWidget*)priv->button, TRUE); gtk_button_set_relief (priv->button, GTK_RELIEF_NONE); gtk_button_set_alignment (priv->button, 0.0, 0.5); gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->button, NULL); g_signal_connect (priv->button, "clicked", G_CALLBACK (button_clicked), e); /* Entry */ priv->entry = (GtkEntry*)gtk_entry_new (); gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->entry, NULL); g_signal_connect (priv->entry, "activate", G_CALLBACK (entry_activated), e); g_signal_connect (priv->entry, "focus-out-event", G_CALLBACK (entry_focus_out), e); g_signal_connect (priv->entry, "key-press-event", G_CALLBACK (entry_key_press), e); g_signal_connect (gtk_bin_get_child (GTK_BIN (priv->button)), "size-allocate", G_CALLBACK (update_button_padding), e); gtk_container_add (GTK_CONTAINER (e), (GtkWidget*)priv->notebook); gtk_widget_show ((GtkWidget*)priv->notebook); gtk_widget_show ((GtkWidget*)priv->label); gtk_widget_show ((GtkWidget*)priv->button); gtk_widget_show ((GtkWidget*)priv->entry); gtk_notebook_set_current_page (priv->notebook, PAGE_LABEL); } GtkWidget * cc_editable_entry_new (void) { return (GtkWidget *) g_object_new (CC_TYPE_EDITABLE_ENTRY, NULL); }
485
./cinnamon-control-center/shell/control-center.c
/* * Copyright (c) 2009, 2010 Intel, Inc. * Copyright (c) 2010 Red Hat, Inc. * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Thomas Wood <thos@gnome.org> */ #include "config.h" #include <glib/gi18n.h> #include <stdlib.h> #include "cinnamon-control-center.h" #include <gtk/gtk.h> #include <string.h> #include <libnotify/notify.h> #ifdef GDK_WINDOWING_X11 #include <X11/Xlib.h> #endif #include "cc-shell-log.h" G_GNUC_NORETURN static gboolean option_version_cb (const gchar *option_name, const gchar *value, gpointer data, GError **error) { g_print ("%s %s\n", PACKAGE, VERSION); exit (0); } static char **start_panels = NULL; static gboolean show_overview = FALSE; static gboolean verbose = FALSE; static gboolean show_help = FALSE; static gboolean show_help_gtk = FALSE; static gboolean show_help_all = FALSE; const GOptionEntry all_options[] = { { "version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, option_version_cb, NULL, NULL }, { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, N_("Enable verbose mode"), NULL }, { "overview", 'o', 0, G_OPTION_ARG_NONE, &show_overview, N_("Show the overview"), NULL }, { "help", 'h', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &show_help, N_("Show help options"), NULL }, { "help-all", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &show_help_all, N_("Show help options"), NULL }, { "help-gtk", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &show_help_gtk, N_("Show help options"), NULL }, { G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_FILENAME_ARRAY, &start_panels, N_("Panel to display"), NULL }, { NULL, 0, 0, 0, NULL, NULL, NULL } /* end the list */ }; static int application_command_line_cb (GApplication *application, GApplicationCommandLine *command_line, CinnamonControlCenter *shell) { int argc; char **argv; int retval = 0; GOptionContext *context; GError *error = NULL; verbose = FALSE; show_overview = FALSE; show_help = FALSE; start_panels = NULL; argv = g_application_command_line_get_arguments (command_line, &argc); context = g_option_context_new (N_("- System Settings")); g_option_context_add_main_entries (context, all_options, GETTEXT_PACKAGE); g_option_context_set_translation_domain(context, GETTEXT_PACKAGE); g_option_context_add_group (context, gtk_get_option_group (TRUE)); g_option_context_set_help_enabled (context, FALSE); if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) { g_print (_("%s\nRun '%s --help' to see a full list of available command line options.\n"), error->message, argv[0]); g_error_free (error); g_option_context_free (context); return 1; } if (show_help || show_help_all || show_help_gtk) { gchar *help; GOptionGroup *group; if (show_help || show_help_all) group = NULL; else group = gtk_get_option_group (FALSE); help = g_option_context_get_help (context, FALSE, group); g_print ("%s", help); g_free (help); g_option_context_free (context); return 0; } g_option_context_free (context); cc_shell_log_set_debug (verbose); cinnamon_control_center_show (shell, GTK_APPLICATION (application)); if (show_overview) { cinnamon_control_center_set_overview_page (shell); } else if (start_panels != NULL && start_panels[0] != NULL) { const char *start_id; GError *err = NULL; start_id = start_panels[0]; if (start_panels[1]) g_debug ("Extra argument: %s", start_panels[1]); else g_debug ("No extra argument"); if (!cc_shell_set_active_panel_from_id (CC_SHELL (shell), start_id, (const gchar**)start_panels+1, &err)) { g_warning ("Could not load setting panel \"%s\": %s", start_id, (err) ? err->message : "Unknown error"); retval = 1; if (err) { g_error_free (err); err = NULL; } } } cinnamon_control_center_present (shell); gdk_notify_startup_complete (); g_strfreev (argv); if (start_panels != NULL) { g_strfreev (start_panels); start_panels = NULL; } show_overview = FALSE; return retval; } static void help_activated (GSimpleAction *action, GVariant *parameter, gpointer user_data) { CinnamonControlCenter *shell = user_data; CcPanel *panel = cc_shell_get_active_panel (CC_SHELL (shell)); GtkWidget *window = cc_shell_get_toplevel (CC_SHELL (shell)); const char *uri = NULL; if (panel) uri = cc_panel_get_help_uri (panel); if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) gtk_show_uri (gtk_widget_get_screen (window), uri ? uri : "help:ubuntu-help/prefs", GDK_CURRENT_TIME, NULL); else gtk_show_uri (gtk_widget_get_screen (window), uri ? uri : "help:gnome-help/prefs", GDK_CURRENT_TIME, NULL); } static void quit_activated (GSimpleAction *action, GVariant *parameter, gpointer user_data) { CinnamonControlCenter *shell = user_data; g_object_unref (shell); } static void application_startup_cb (GApplication *application, CinnamonControlCenter *shell) { GMenu *menu, *section; GAction *action; action = G_ACTION (g_simple_action_new ("help", NULL)); g_action_map_add_action (G_ACTION_MAP (application), action); g_signal_connect (action, "activate", G_CALLBACK (help_activated), shell); action = G_ACTION (g_simple_action_new ("quit", NULL)); g_action_map_add_action (G_ACTION_MAP (application), action); g_signal_connect (action, "activate", G_CALLBACK (quit_activated), shell); menu = g_menu_new (); section = g_menu_new (); g_menu_append (section, _("Help"), "app.help"); g_menu_append (section, _("Quit"), "app.quit"); g_menu_append_section (menu, NULL, G_MENU_MODEL (section)); gtk_application_set_app_menu (GTK_APPLICATION (application), G_MENU_MODEL (menu)); gtk_application_add_accelerator (GTK_APPLICATION (application), "F1", "app.help", NULL); /* nothing else to do here, we don't want to show a window before * we've looked at the commandline */ } int main (int argc, char **argv) { CinnamonControlCenter *shell; GtkApplication *application; int status; bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); #ifdef GDK_WINDOWING_X11 XInitThreads (); #endif gtk_init (&argc, &argv); cc_shell_log_init (); /* register a symbolic icon size for use in sidebar lists */ gtk_icon_size_register ("cc-sidebar-list", 24, 24); notify_init ("cinnamon-control-center"); shell = cinnamon_control_center_new (); /* enforce single instance of this application */ application = gtk_application_new ("org.cinnamon.ControlCenter", G_APPLICATION_HANDLES_COMMAND_LINE); g_signal_connect (application, "startup", G_CALLBACK (application_startup_cb), shell); g_signal_connect (application, "command-line", G_CALLBACK (application_command_line_cb), shell); status = g_application_run (G_APPLICATION (application), argc, argv); g_object_unref (application); return status; }
486
./cinnamon-control-center/shell/cc-shell-log.c
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- * * Copyright (C) 2009 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "config.h" #include <glib.h> #include <glib/gstdio.h> #include "cc-shell-log.h" static int log_levels = G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG; static void cc_shell_log_default_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data) { if ((log_level & log_levels) == 0) return; g_log_default_handler (log_domain, log_level, message, unused_data); } void cc_shell_log_init (void) { g_log_set_default_handler (cc_shell_log_default_handler, NULL); } void cc_shell_log_set_debug (gboolean debug) { g_setenv ("G_MESSAGES_DEBUG", "all", TRUE); if (debug) { log_levels |= (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO); g_debug ("Enabling debugging"); } else { log_levels &= ~ (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO); } }
487
./cinnamon-control-center/shell/cc-shell-item-view.c
/* * Copyright (c) 2010 Intel, Inc. * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Thomas Wood <thos@gnome.org> */ #include "cc-shell-item-view.h" #include "cc-shell-model.h" #include "cc-shell-marshal.h" G_DEFINE_TYPE (CcShellItemView, cc_shell_item_view, GTK_TYPE_ICON_VIEW) #define SHELL_ITEM_VIEW_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_SHELL_ITEM_VIEW, CcShellItemViewPrivate)) struct _CcShellItemViewPrivate { gboolean ignore_release; }; enum { DESKTOP_ITEM_ACTIVATED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {0,}; static void cc_shell_item_view_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_item_view_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_item_view_dispose (GObject *object) { G_OBJECT_CLASS (cc_shell_item_view_parent_class)->dispose (object); } static void cc_shell_item_view_finalize (GObject *object) { G_OBJECT_CLASS (cc_shell_item_view_parent_class)->finalize (object); } static gboolean iconview_button_press_event_cb (GtkWidget *widget, GdkEventButton *event, CcShellItemView *cc_view) { /* be sure to ignore double and triple clicks */ cc_view->priv->ignore_release = (event->type != GDK_BUTTON_PRESS); return FALSE; } static gboolean iconview_button_release_event_cb (GtkWidget *widget, GdkEventButton *event, CcShellItemView *cc_view) { CcShellItemViewPrivate *priv = cc_view->priv; if (event->button == 1 && !priv->ignore_release) { GList *selection; selection = gtk_icon_view_get_selected_items (GTK_ICON_VIEW (cc_view)); if (!selection) return TRUE; gtk_icon_view_item_activated (GTK_ICON_VIEW (cc_view), (GtkTreePath*) selection->data); g_list_free (selection); } return TRUE; } static void iconview_item_activated_cb (GtkIconView *icon_view, GtkTreePath *path, CcShellItemView *cc_view) { GtkTreeModel *model; GtkTreeIter iter; gchar *name, *desktop_file, *id; model = gtk_icon_view_get_model (icon_view); gtk_icon_view_unselect_all (icon_view); /* get the iter and ensure it is valid */ if (!gtk_tree_model_get_iter (model, &iter, path)) return; gtk_tree_model_get (model, &iter, COL_NAME, &name, COL_DESKTOP_FILE, &desktop_file, COL_ID, &id, -1); g_signal_emit (cc_view, signals[DESKTOP_ITEM_ACTIVATED], 0, name, id, desktop_file); g_free (desktop_file); g_free (name); g_free (id); } void cc_shell_item_view_update_cells (CcShellItemView *view) { GList *cells, *l; cells = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (view)); for (l = cells ; l != NULL; l = l->next) { GtkCellRenderer *cell = l->data; if (GTK_IS_CELL_RENDERER_TEXT (cell)) { g_object_set (G_OBJECT (cell), "wrap-mode", PANGO_WRAP_WORD, NULL); /* We only have one text cell */ break; } } } static void cc_shell_item_view_class_init (CcShellItemViewClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (CcShellItemViewPrivate)); object_class->get_property = cc_shell_item_view_get_property; object_class->set_property = cc_shell_item_view_set_property; object_class->dispose = cc_shell_item_view_dispose; object_class->finalize = cc_shell_item_view_finalize; signals[DESKTOP_ITEM_ACTIVATED] = g_signal_new ("desktop-item-activated", CC_TYPE_SHELL_ITEM_VIEW, G_SIGNAL_RUN_FIRST, 0, NULL, NULL, cc_shell_marshal_VOID__STRING_STRING_STRING, G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); } static void cc_shell_item_view_init (CcShellItemView *self) { self->priv = SHELL_ITEM_VIEW_PRIVATE (self); g_object_set (self, "margin", 0, NULL); g_signal_connect (self, "item-activated", G_CALLBACK (iconview_item_activated_cb), self); g_signal_connect (self, "button-press-event", G_CALLBACK (iconview_button_press_event_cb), self); g_signal_connect (self, "button-release-event", G_CALLBACK (iconview_button_release_event_cb), self); } GtkWidget * cc_shell_item_view_new (void) { return g_object_new (CC_TYPE_SHELL_ITEM_VIEW, NULL); }
488
./cinnamon-control-center/shell/cc-panel.c
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- * * Copyright (C) 2010 Red Hat, Inc. * Copyright (C) 2010 Intel, Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Authors: William Jon McCann <jmccann@redhat.com> * Thomas Wood <thomas.wood@intel.com> * */ /** * SECTION:cc-panel * @short_description: An abstract class for Control Center panels * * CcPanel is an abstract class used to implement panels for the shell. A * panel contains a collection of related settings that are displayed within * the shell window. */ #include "config.h" #include "cc-panel.h" #include <stdlib.h> #include <stdio.h> #include <gtk/gtk.h> #include <gio/gio.h> #define CC_PANEL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_PANEL, CcPanelPrivate)) struct CcPanelPrivate { gchar *id; gchar *display_name; gchar *category; gchar *current_location; gboolean is_active; CcShell *shell; }; enum { PROP_0, PROP_SHELL, PROP_ARGV }; G_DEFINE_ABSTRACT_TYPE (CcPanel, cc_panel, GTK_TYPE_BIN) static void cc_panel_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { CcPanel *panel; panel = CC_PANEL (object); switch (prop_id) { case PROP_SHELL: /* construct only property */ panel->priv->shell = g_value_get_object (value); break; case PROP_ARGV: { gchar **argv = g_value_get_boxed (value); if (argv && argv[0]) g_warning ("Ignoring additional argument %s", argv[0]); break; } default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void cc_panel_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { CcPanel *panel; panel = CC_PANEL (object); switch (prop_id) { case PROP_SHELL: g_value_set_object (value, panel->priv->shell); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void cc_panel_finalize (GObject *object) { CcPanel *panel; g_return_if_fail (object != NULL); g_return_if_fail (CC_IS_PANEL (object)); panel = CC_PANEL (object); g_free (panel->priv->id); g_free (panel->priv->display_name); G_OBJECT_CLASS (cc_panel_parent_class)->finalize (object); } static void cc_panel_get_preferred_width (GtkWidget *widget, gint *minimum, gint *natural) { GtkBin *bin = GTK_BIN (widget); GtkWidget *child; if (minimum != NULL) *minimum = 0; if (natural != NULL) *natural = 0; if ((child = gtk_bin_get_child (bin))) gtk_widget_get_preferred_width (child, minimum, natural); } static void cc_panel_get_preferred_height (GtkWidget *widget, gint *minimum, gint *natural) { GtkBin *bin = GTK_BIN (widget); GtkWidget *child; if (minimum != NULL) *minimum = 0; if (natural != NULL) *natural = 0; if ((child = gtk_bin_get_child (bin))) gtk_widget_get_preferred_height (child, minimum, natural); } static void cc_panel_size_allocate (GtkWidget *widget, GtkAllocation *allocation) { GtkAllocation child_allocation; gtk_widget_set_allocation (widget, allocation); child_allocation = *allocation; gtk_widget_size_allocate (gtk_bin_get_child (GTK_BIN (widget)), &child_allocation); } static void cc_panel_class_init (CcPanelClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); object_class->get_property = cc_panel_get_property; object_class->set_property = cc_panel_set_property; object_class->finalize = cc_panel_finalize; widget_class->get_preferred_width = cc_panel_get_preferred_width; widget_class->get_preferred_height = cc_panel_get_preferred_height; widget_class->size_allocate = cc_panel_size_allocate; gtk_container_class_handle_border_width (GTK_CONTAINER_CLASS (klass)); g_type_class_add_private (klass, sizeof (CcPanelPrivate)); pspec = g_param_spec_object ("shell", "Shell", "Shell the Panel resides in", CC_TYPE_SHELL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY); g_object_class_install_property (object_class, PROP_SHELL, pspec); pspec = g_param_spec_boxed ("argv", "Argument vector", "Additional arguments passed on the command line", G_TYPE_STRV, G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_ARGV, pspec); } static void cc_panel_init (CcPanel *panel) { panel->priv = CC_PANEL_GET_PRIVATE (panel); } /** * cc_panel_get_shell: * @panel: A #CcPanel * * Get the shell that the panel resides in * * Returns: a #CcShell */ CcShell * cc_panel_get_shell (CcPanel *panel) { return panel->priv->shell; } GPermission * cc_panel_get_permission (CcPanel *panel) { CcPanelClass *class = CC_PANEL_GET_CLASS (panel); if (class->get_permission) return class->get_permission (panel); return NULL; } const char * cc_panel_get_help_uri (CcPanel *panel) { CcPanelClass *class = CC_PANEL_GET_CLASS (panel); if (class->get_help_uri) return class->get_help_uri (panel); return NULL; }
489
./cinnamon-control-center/shell/cc-shell-category-view.c
/* * Copyright (c) 2010 Intel, Inc. * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Thomas Wood <thos@gnome.org> */ #include "cc-shell-category-view.h" #include "cc-shell-item-view.h" #include "cc-shell.h" #include "cc-shell-model.h" G_DEFINE_TYPE (CcShellCategoryView, cc_shell_category_view, GTK_TYPE_FRAME) #define SHELL_CATEGORY_VIEW_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_SHELL_CATEGORY_VIEW, CcShellCategoryViewPrivate)) enum { PROP_NAME = 1, PROP_MODEL }; struct _CcShellCategoryViewPrivate { gchar *name; GtkTreeModel *model; GtkWidget *iconview; }; static void cc_shell_category_view_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { CcShellCategoryViewPrivate *priv = CC_SHELL_CATEGORY_VIEW (object)->priv; switch (property_id) { case PROP_NAME: g_value_set_string (value, priv->name); break; case PROP_MODEL: g_value_set_object (value, priv->model); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_category_view_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { CcShellCategoryViewPrivate *priv = CC_SHELL_CATEGORY_VIEW (object)->priv; switch (property_id) { case PROP_NAME: priv->name = g_value_dup_string (value); break; case PROP_MODEL: priv->model = g_value_dup_object (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cc_shell_category_view_dispose (GObject *object) { CcShellCategoryViewPrivate *priv = CC_SHELL_CATEGORY_VIEW (object)->priv; if (priv->model) { g_object_unref (priv->model); priv->model = NULL; } G_OBJECT_CLASS (cc_shell_category_view_parent_class)->dispose (object); } static void cc_shell_category_view_finalize (GObject *object) { CcShellCategoryViewPrivate *priv = CC_SHELL_CATEGORY_VIEW (object)->priv; if (priv->name) { g_free (priv->name); priv->name = NULL; } G_OBJECT_CLASS (cc_shell_category_view_parent_class)->finalize (object); } static void cc_shell_category_view_constructed (GObject *object) { CcShellCategoryViewPrivate *priv = CC_SHELL_CATEGORY_VIEW (object)->priv; GtkWidget *iconview, *vbox; GtkCellRenderer *renderer; iconview = cc_shell_item_view_new (); gtk_icon_view_set_model (GTK_ICON_VIEW (iconview), priv->model); vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (renderer, "follow-state", TRUE, NULL); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (iconview), renderer, FALSE); gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (iconview), renderer, "pixbuf", COL_PIXBUF); gtk_icon_view_set_text_column (GTK_ICON_VIEW (iconview), COL_NAME); gtk_icon_view_set_item_width (GTK_ICON_VIEW (iconview), 100); cc_shell_item_view_update_cells (CC_SHELL_ITEM_VIEW (iconview)); /* create the header if required */ if (priv->name) { GtkWidget *label; PangoAttrList *attrs; label = gtk_label_new (priv->name); attrs = pango_attr_list_new (); pango_attr_list_insert (attrs, pango_attr_weight_new (PANGO_WEIGHT_BOLD)); gtk_label_set_attributes (GTK_LABEL (label), attrs); pango_attr_list_unref (attrs); gtk_frame_set_label_widget (GTK_FRAME (object), label); gtk_widget_show (label); } /* add the iconview to the vbox */ gtk_box_pack_start (GTK_BOX (vbox), iconview, FALSE, TRUE, 0); /* add the main vbox to the view */ gtk_container_add (GTK_CONTAINER (object), vbox); gtk_widget_show_all (vbox); priv->iconview = iconview; } static void cc_shell_category_view_class_init (CcShellCategoryViewClass *klass) { GParamSpec *pspec; GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (klass, sizeof (CcShellCategoryViewPrivate)); object_class->get_property = cc_shell_category_view_get_property; object_class->set_property = cc_shell_category_view_set_property; object_class->dispose = cc_shell_category_view_dispose; object_class->finalize = cc_shell_category_view_finalize; object_class->constructed = cc_shell_category_view_constructed; pspec = g_param_spec_string ("name", "Name", "Name of the category", NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_NAME, pspec); pspec = g_param_spec_object ("model", "Model", "Model of the category", GTK_TYPE_TREE_MODEL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_property (object_class, PROP_MODEL, pspec); } static void cc_shell_category_view_init (CcShellCategoryView *self) { self->priv = SHELL_CATEGORY_VIEW_PRIVATE (self); gtk_frame_set_shadow_type (GTK_FRAME (self), GTK_SHADOW_NONE); } GtkWidget * cc_shell_category_view_new (const gchar *name, GtkTreeModel *model) { return g_object_new (CC_TYPE_SHELL_CATEGORY_VIEW, "name", name, "model", model, NULL); } CcShellItemView* cc_shell_category_view_get_item_view (CcShellCategoryView *self) { return (CcShellItemView*) self->priv->iconview; }
490
./cinnamon-control-center/shell/cc-shell-model.c
/* * Copyright (c) 2009, 2010 Intel, Inc. * Copyright (c) 2010 Red Hat, Inc. * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Thomas Wood <thos@gnome.org> */ #include "cc-shell-model.h" #include <string.h> #define GNOME_SETTINGS_PANEL_ID_KEY "X-Cinnamon-Settings-Panel" #define GNOME_SETTINGS_PANEL_CATEGORY GNOME_SETTINGS_PANEL_ID_KEY #define GNOME_SETTINGS_PANEL_ID_KEYWORDS "Keywords" G_DEFINE_TYPE (CcShellModel, cc_shell_model, GTK_TYPE_LIST_STORE) static GdkPixbuf * load_pixbuf_for_gicon (GIcon *icon) { GtkIconTheme *theme; GtkIconInfo *icon_info; GdkPixbuf *pixbuf = NULL; GError *err = NULL; if (icon == NULL) return NULL; theme = gtk_icon_theme_get_default (); icon_info = gtk_icon_theme_lookup_by_gicon (theme, icon, 48, GTK_ICON_LOOKUP_FORCE_SIZE); if (icon_info) { pixbuf = gtk_icon_info_load_icon (icon_info, &err); if (err) { g_warning ("Could not load icon '%s': %s", gtk_icon_info_get_filename (icon_info), err->message); g_error_free (err); } gtk_icon_info_free (icon_info); } else { g_warning ("Could not find icon"); } return pixbuf; } static void icon_theme_changed (GtkIconTheme *theme, CcShellModel *self) { GtkTreeIter iter; GtkTreeModel *model; gboolean cont; model = GTK_TREE_MODEL (self); cont = gtk_tree_model_get_iter_first (model, &iter); while (cont) { GdkPixbuf *pixbuf; GIcon *icon; gtk_tree_model_get (model, &iter, COL_GICON, &icon, -1); pixbuf = load_pixbuf_for_gicon (icon); g_object_unref (icon); gtk_list_store_set (GTK_LIST_STORE (model), &iter, COL_PIXBUF, pixbuf, -1); cont = gtk_tree_model_iter_next (model, &iter); } } static void cc_shell_model_class_init (CcShellModelClass *klass) { } static void cc_shell_model_init (CcShellModel *self) { GType types[] = {G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_ICON, G_TYPE_STRV}; gtk_list_store_set_column_types (GTK_LIST_STORE (self), N_COLS, types); gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (self), COL_NAME, GTK_SORT_ASCENDING); g_signal_connect (G_OBJECT (gtk_icon_theme_get_default ()), "changed", G_CALLBACK (icon_theme_changed), self); } CcShellModel * cc_shell_model_new (void) { return g_object_new (CC_TYPE_SHELL_MODEL, NULL); } static gboolean desktop_entry_has_panel_category (GKeyFile *key_file) { char **strv; gsize len; int i; strv = g_key_file_get_string_list (key_file, "Desktop Entry", "Categories", &len, NULL); if (!strv) return FALSE; for (i = 0; strv[i]; i++) { if (g_str_equal (strv[i], GNOME_SETTINGS_PANEL_CATEGORY)) { g_strfreev (strv); return TRUE; } } g_strfreev (strv); return FALSE; } void cc_shell_model_add_item (CcShellModel *model, const gchar *category_name, GMenuTreeEntry *item) { GAppInfo *appinfo = G_APP_INFO (gmenu_tree_entry_get_app_info (item)); GIcon *icon = g_app_info_get_icon (appinfo); const gchar *name = g_app_info_get_name (appinfo); const gchar *desktop = gmenu_tree_entry_get_desktop_file_path (item); const gchar *comment = g_app_info_get_description (appinfo); gchar *id; GdkPixbuf *pixbuf = NULL; GKeyFile *key_file; gchar **keywords; /* load the .desktop file since gnome-menus doesn't have a way to read * custom properties from desktop files */ key_file = g_key_file_new (); g_key_file_load_from_file (key_file, desktop, 0, NULL); id = g_key_file_get_string (key_file, "Desktop Entry", GNOME_SETTINGS_PANEL_ID_KEY, NULL); if (!id) { /* Refuse to load desktop files without a panel ID, but * with the X-GNOME-Settings-Panel category */ if (desktop_entry_has_panel_category (key_file)) { g_warning ("Not loading desktop file '%s' because it uses the " GNOME_SETTINGS_PANEL_CATEGORY " category but isn't a panel.", desktop); g_key_file_free (key_file); return; } id = g_strdup (gmenu_tree_entry_get_desktop_file_id (item)); } keywords = g_key_file_get_locale_string_list (key_file, "Desktop Entry", GNOME_SETTINGS_PANEL_ID_KEYWORDS, NULL, NULL, NULL); g_key_file_free (key_file); key_file = NULL; pixbuf = load_pixbuf_for_gicon (icon); gtk_list_store_insert_with_values (GTK_LIST_STORE (model), NULL, 0, COL_NAME, name, COL_DESKTOP_FILE, desktop, COL_ID, id, COL_PIXBUF, pixbuf, COL_CATEGORY, category_name, COL_DESCRIPTION, comment, COL_GICON, icon, COL_KEYWORDS, keywords, -1); g_free (id); g_strfreev (keywords); }
491
./cinnamon-control-center/shell/cinnamon-control-center.c
/* * Copyright (c) 2009, 2010 Intel, Inc. * Copyright (c) 2010 Red Hat, Inc. * * The Control Center is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The Control Center is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with the Control Center; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Thomas Wood <thos@gnome.org> */ #include "cinnamon-control-center.h" #include <glib/gi18n.h> #include <gio/gio.h> #include <gio/gdesktopappinfo.h> #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include <string.h> #ifdef HAVE_CHEESE #include <clutter-gtk/clutter-gtk.h> #endif #define GMENU_I_KNOW_THIS_IS_UNSTABLE #include <gmenu-tree.h> #include "cc-panel.h" #include "cc-shell.h" #include "cc-shell-category-view.h" #include "cc-shell-model.h" #include "cc-shell-nav-bar.h" G_DEFINE_TYPE (CinnamonControlCenter, cinnamon_control_center, CC_TYPE_SHELL) #define CONTROL_CENTER_PRIVATE(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), CINNAMON_TYPE_CONTROL_CENTER, CinnamonControlCenterPrivate)) #define W(b,x) GTK_WIDGET (gtk_builder_get_object (b, x)) /* Use a fixed width for the shell, since resizing horizontally is more awkward * for the user than resizing vertically * Both sizes are defined in https://live.gnome.org/Design/SystemSettings/ */ #define FIXED_WIDTH 740 #define UNITY_FIXED_WIDTH 850 #define FIXED_HEIGHT 650 #define SMALL_SCREEN_FIXED_HEIGHT 400 #define MIN_ICON_VIEW_HEIGHT 300 typedef enum { SMALL_SCREEN_UNSET, SMALL_SCREEN_TRUE, SMALL_SCREEN_FALSE } CcSmallScreen; struct _CinnamonControlCenterPrivate { GtkBuilder *builder; GtkWidget *notebook; GtkWidget *main_vbox; GtkWidget *scrolled_window; GtkWidget *search_scrolled; GtkWidget *current_panel_box; GtkWidget *current_panel; char *current_panel_id; GtkWidget *window; GtkWidget *search_entry; GtkWidget *lock_button; GPtrArray *custom_widgets; GtkWidget *nav_bar; GMenuTree *menu_tree; GtkListStore *store; GHashTable *category_views; GtkTreeModel *search_filter; GtkWidget *search_view; gchar *filter_string; guint32 last_time; GIOExtensionPoint *extension_point; gchar *default_window_title; gchar *default_window_icon; int monitor_num; CcSmallScreen small_screen; }; /* Notebook helpers */ static GtkWidget * notebook_get_selected_page (GtkWidget *notebook) { int curr; curr = gtk_notebook_get_current_page (GTK_NOTEBOOK (notebook)); if (curr == -1) return NULL; return gtk_notebook_get_nth_page (GTK_NOTEBOOK (notebook), curr); } static void notebook_select_page (GtkWidget *notebook, GtkWidget *page) { int i, num; num = gtk_notebook_get_n_pages (GTK_NOTEBOOK (notebook)); for (i = 0; i < num; i++) { if (gtk_notebook_get_nth_page (GTK_NOTEBOOK (notebook), i) == page) { gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), i); return; } } g_warning ("Couldn't select GtkNotebook page %p", page); } static void notebook_remove_page (GtkWidget *notebook, GtkWidget *page) { int i, num; num = gtk_notebook_get_n_pages (GTK_NOTEBOOK (notebook)); for (i = 0; i < num; i++) { if (gtk_notebook_get_nth_page (GTK_NOTEBOOK (notebook), i) == page) { gtk_notebook_remove_page (GTK_NOTEBOOK (notebook), i); return; } } g_warning ("Couldn't find GtkNotebook page to remove %p", page); } static void notebook_add_page (GtkWidget *notebook, GtkWidget *page) { gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, NULL); } static const gchar * get_icon_name_from_g_icon (GIcon *gicon) { const gchar * const *names; GtkIconTheme *icon_theme; int i; if (!G_IS_THEMED_ICON (gicon)) return NULL; names = g_themed_icon_get_names (G_THEMED_ICON (gicon)); icon_theme = gtk_icon_theme_get_default (); for (i = 0; names[i] != NULL; i++) { if (gtk_icon_theme_has_icon (icon_theme, names[i])) return names[i]; } return NULL; } static gboolean activate_panel (CinnamonControlCenter *shell, const gchar *id, const gchar **argv, const gchar *desktop_file, const gchar *name, GIcon *gicon) { CinnamonControlCenterPrivate *priv = shell->priv; GType panel_type = G_TYPE_INVALID; GList *panels, *l; GtkWidget *box; const gchar *icon_name; /* check if there is an plugin that implements this panel */ panels = g_io_extension_point_get_extensions (priv->extension_point); if (!desktop_file) return FALSE; if (!id) return FALSE; for (l = panels; l != NULL; l = l->next) { GIOExtension *extension; const gchar *name; extension = l->data; name = g_io_extension_get_name (extension); if (!g_strcmp0 (name, id)) { panel_type = g_io_extension_get_type (extension); break; } } if (panel_type == G_TYPE_INVALID) { GKeyFile *key_file; /* It might be an external panel */ key_file = g_key_file_new (); if (g_key_file_load_from_file (key_file, desktop_file, G_KEY_FILE_NONE, NULL)) { gchar *command; command = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_EXEC, NULL); if (command && command[0]) { g_spawn_command_line_async (command, NULL); g_free (command); } } g_key_file_free (key_file); return FALSE; } /* create the panel plugin */ priv->current_panel = g_object_new (panel_type, "shell", shell, "argv", argv, NULL); cc_shell_set_active_panel (CC_SHELL (shell), CC_PANEL (priv->current_panel)); gtk_widget_show (priv->current_panel); gtk_lock_button_set_permission (GTK_LOCK_BUTTON (priv->lock_button), cc_panel_get_permission (CC_PANEL (priv->current_panel))); box = gtk_alignment_new (0, 0, 1, 1); gtk_alignment_set_padding (GTK_ALIGNMENT (box), 6, 6, 6, 6); gtk_container_add (GTK_CONTAINER (box), priv->current_panel); gtk_widget_set_name (box, id); notebook_add_page (priv->notebook, box); /* switch to the new panel */ gtk_widget_show (box); notebook_select_page (priv->notebook, box); cc_shell_nav_bar_show_detail_button (CC_SHELL_NAV_BAR(shell->priv->nav_bar), name); /* set the title of the window */ icon_name = get_icon_name_from_g_icon (gicon); gtk_window_set_role (GTK_WINDOW (priv->window), id); gtk_window_set_title (GTK_WINDOW (priv->window), name); gtk_window_set_default_icon_name (icon_name); gtk_window_set_icon_name (GTK_WINDOW (priv->window), icon_name); priv->current_panel_box = box; return TRUE; } static void _shell_remove_all_custom_widgets (CinnamonControlCenterPrivate *priv) { GtkBox *box; GtkWidget *widget; guint i; /* remove from the header */ box = GTK_BOX (W (priv->builder, "topright")); for (i = 0; i < priv->custom_widgets->len; i++) { widget = g_ptr_array_index (priv->custom_widgets, i); gtk_container_remove (GTK_CONTAINER (box), widget); } g_ptr_array_set_size (priv->custom_widgets, 0); } static void shell_show_overview_page (CinnamonControlCenter *center) { CinnamonControlCenterPrivate *priv = center->priv; notebook_select_page (priv->notebook, priv->scrolled_window); if (priv->current_panel_box) notebook_remove_page (priv->notebook, priv->current_panel_box); priv->current_panel = NULL; priv->current_panel_box = NULL; if (priv->current_panel_id) { g_free (priv->current_panel_id); priv->current_panel_id = NULL; } /* clear the search text */ g_free (priv->filter_string); priv->filter_string = g_strdup (""); gtk_lock_button_set_permission (GTK_LOCK_BUTTON (priv->lock_button), NULL); /* reset window title and icon */ gtk_window_set_role (GTK_WINDOW (priv->window), NULL); gtk_window_set_title (GTK_WINDOW (priv->window), priv->default_window_title); gtk_window_set_default_icon_name (priv->default_window_icon); gtk_window_set_icon_name (GTK_WINDOW (priv->window), priv->default_window_icon); cc_shell_set_active_panel (CC_SHELL (center), NULL); /* clear any custom widgets */ _shell_remove_all_custom_widgets (priv); cc_shell_nav_bar_hide_detail_button (CC_SHELL_NAV_BAR (priv->nav_bar)); } void cinnamon_control_center_set_overview_page (CinnamonControlCenter *center) { shell_show_overview_page (center); } static void item_activated_cb (CcShellCategoryView *view, gchar *name, gchar *id, gchar *desktop_file, CinnamonControlCenter *shell) { GError *err = NULL; if (!cc_shell_set_active_panel_from_id (CC_SHELL (shell), id, NULL, &err)) { /* TODO: show message to user */ if (err) { g_warning ("Could not active panel \"%s\": %s", id, err->message); g_error_free (err); } } } static gboolean category_focus_out (GtkWidget *view, GdkEventFocus *event, CinnamonControlCenter *shell) { gtk_icon_view_unselect_all (GTK_ICON_VIEW (view)); return FALSE; } static gboolean category_focus_in (GtkWidget *view, GdkEventFocus *event, CinnamonControlCenter *shell) { GtkTreePath *path; if (!gtk_icon_view_get_cursor (GTK_ICON_VIEW (view), &path, NULL)) { path = gtk_tree_path_new_from_indices (0, -1); gtk_icon_view_set_cursor (GTK_ICON_VIEW (view), path, NULL, FALSE); } gtk_icon_view_select_path (GTK_ICON_VIEW (view), path); gtk_tree_path_free (path); return FALSE; } static GList * get_item_views (CinnamonControlCenter *shell) { GList *list, *l; GList *res; list = gtk_container_get_children (GTK_CONTAINER (shell->priv->main_vbox)); res = NULL; for (l = list; l; l = l->next) { if (!CC_IS_SHELL_CATEGORY_VIEW (l->data)) continue; res = g_list_append (res, cc_shell_category_view_get_item_view (CC_SHELL_CATEGORY_VIEW (l->data))); } g_list_free (list); return res; } static gboolean keynav_failed (GtkIconView *current_view, GtkDirectionType direction, CinnamonControlCenter *shell) { GList *views, *v; GtkIconView *new_view; GtkTreePath *path; GtkTreeModel *model; GtkTreeIter iter; gint col, c, dist, d; GtkTreePath *sel; gboolean res; res = FALSE; views = get_item_views (shell); for (v = views; v; v = v->next) { if (v->data == current_view) break; } if (direction == GTK_DIR_DOWN && v != NULL && v->next != NULL) { new_view = v->next->data; if (gtk_icon_view_get_cursor (current_view, &path, NULL)) { col = gtk_icon_view_get_item_column (current_view, path); gtk_tree_path_free (path); sel = NULL; dist = 1000; model = gtk_icon_view_get_model (new_view); gtk_tree_model_get_iter_first (model, &iter); do { path = gtk_tree_model_get_path (model, &iter); c = gtk_icon_view_get_item_column (new_view, path); d = ABS (c - col); if (d < dist) { if (sel) gtk_tree_path_free (sel); sel = path; dist = d; } else gtk_tree_path_free (path); } while (gtk_tree_model_iter_next (model, &iter)); gtk_icon_view_set_cursor (new_view, sel, NULL, FALSE); gtk_tree_path_free (sel); } gtk_widget_grab_focus (GTK_WIDGET (new_view)); res = TRUE; } if (direction == GTK_DIR_UP && v != NULL && v->prev != NULL) { new_view = v->prev->data; if (gtk_icon_view_get_cursor (current_view, &path, NULL)) { col = gtk_icon_view_get_item_column (current_view, path); gtk_tree_path_free (path); sel = NULL; dist = 1000; model = gtk_icon_view_get_model (new_view); gtk_tree_model_get_iter_first (model, &iter); do { path = gtk_tree_model_get_path (model, &iter); c = gtk_icon_view_get_item_column (new_view, path); d = ABS (c - col); if (d <= dist) { if (sel) gtk_tree_path_free (sel); sel = path; dist = d; } else gtk_tree_path_free (path); } while (gtk_tree_model_iter_next (model, &iter)); gtk_icon_view_set_cursor (new_view, sel, NULL, FALSE); gtk_tree_path_free (sel); } gtk_widget_grab_focus (GTK_WIDGET (new_view)); res = TRUE; } g_list_free (views); return res; } static gboolean model_filter_func (GtkTreeModel *model, GtkTreeIter *iter, CinnamonControlCenterPrivate *priv) { gchar *name, *description; gchar *needle, *haystack; gboolean result; gchar **keywords; gtk_tree_model_get (model, iter, COL_NAME, &name, COL_DESCRIPTION, &description, COL_KEYWORDS, &keywords, -1); if (!priv->filter_string || !name) { g_free (name); g_free (description); g_strfreev (keywords); return FALSE; } needle = g_utf8_casefold (priv->filter_string, -1); haystack = g_utf8_casefold (name, -1); result = (strstr (haystack, needle) != NULL); if (!result && description) { gchar *folded; folded = g_utf8_casefold (description, -1); result = (strstr (folded, needle) != NULL); g_free (folded); } if (!result && keywords) { gint i; gchar *keyword; for (i = 0; !result && keywords[i]; i++) { keyword = g_utf8_casefold (keywords[i], -1); result = strstr (keyword, needle) == keyword; g_free (keyword); } } g_free (name); g_free (haystack); g_free (needle); g_strfreev (keywords); return result; } static gboolean category_filter_func (GtkTreeModel *model, GtkTreeIter *iter, gchar *filter) { gchar *category; gboolean result; gtk_tree_model_get (model, iter, COL_CATEGORY, &category, -1); result = (g_strcmp0 (category, filter) == 0); g_free (category); return result; } static void search_entry_changed_cb (GtkEntry *entry, CinnamonControlCenter *center) { CinnamonControlCenterPrivate *priv = center->priv; char *str; /* if the entry text was set manually (not by the user) */ if (!g_strcmp0 (priv->filter_string, gtk_entry_get_text (entry))) return; /* Don't re-filter for added trailing or leading spaces */ str = g_strdup (gtk_entry_get_text (entry)); g_strstrip (str); if (!g_strcmp0 (str, priv->filter_string)) { g_free (str); return; } g_free (priv->filter_string); priv->filter_string = str; if (!g_strcmp0 (priv->filter_string, "")) { shell_show_overview_page (center); } else { gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (priv->search_filter)); notebook_select_page (priv->notebook, priv->search_scrolled); } } static gboolean search_entry_key_press_event_cb (GtkEntry *entry, GdkEventKey *event, CinnamonControlCenterPrivate *priv) { if (event->keyval == GDK_KEY_Return) { GtkTreePath *path; path = gtk_tree_path_new_first (); priv->last_time = event->time; gtk_icon_view_item_activated (GTK_ICON_VIEW (priv->search_view), path); gtk_tree_path_free (path); return TRUE; } if (event->keyval == GDK_KEY_Escape) { gtk_entry_set_text (entry, ""); return TRUE; } return FALSE; } static void on_search_selection_changed (GtkTreeSelection *selection, CinnamonControlCenter *shell) { GtkTreeModel *model; GtkTreeIter iter; char *id = NULL; if (!gtk_tree_selection_get_selected (selection, &model, &iter)) return; gtk_tree_model_get (model, &iter, COL_ID, &id, -1); if (id) cc_shell_set_active_panel_from_id (CC_SHELL (shell), id, NULL, NULL); gtk_tree_selection_unselect_all (selection); g_free (id); } static void setup_search (CinnamonControlCenter *shell) { GtkWidget *search_view, *widget; GtkCellRenderer *renderer; GtkTreeViewColumn *column; CinnamonControlCenterPrivate *priv = shell->priv; g_return_if_fail (priv->store != NULL); /* create the search filter */ priv->search_filter = gtk_tree_model_filter_new (GTK_TREE_MODEL (priv->store), NULL); gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (priv->search_filter), (GtkTreeModelFilterVisibleFunc) model_filter_func, priv, NULL); /* set up the search view */ priv->search_view = search_view = gtk_tree_view_new (); gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (search_view), FALSE); gtk_tree_view_set_model (GTK_TREE_VIEW (search_view), GTK_TREE_MODEL (priv->search_filter)); renderer = gtk_cell_renderer_pixbuf_new (); g_object_set (renderer, "follow-state", TRUE, "xpad", 15, "ypad", 10, "stock-size", GTK_ICON_SIZE_DIALOG, NULL); column = gtk_tree_view_column_new_with_attributes ("Icon", renderer, "gicon", COL_GICON, NULL); gtk_tree_view_column_set_expand (column, FALSE); gtk_tree_view_append_column (GTK_TREE_VIEW (priv->search_view), column); renderer = gtk_cell_renderer_text_new (); g_object_set (renderer, "xpad", 0, NULL); column = gtk_tree_view_column_new_with_attributes ("Name", renderer, "text", COL_NAME, NULL); gtk_tree_view_column_set_expand (column, FALSE); gtk_tree_view_append_column (GTK_TREE_VIEW (priv->search_view), column); renderer = gtk_cell_renderer_text_new (); g_object_set (renderer, "xpad", 15, NULL); column = gtk_tree_view_column_new_with_attributes ("Description", renderer, "text", COL_DESCRIPTION, NULL); gtk_tree_view_column_set_expand (column, TRUE); gtk_tree_view_append_column (GTK_TREE_VIEW (priv->search_view), column); priv->search_scrolled = W (priv->builder, "search-scrolled-window"); gtk_container_add (GTK_CONTAINER (priv->search_scrolled), search_view); g_signal_connect (gtk_tree_view_get_selection (GTK_TREE_VIEW (priv->search_view)), "changed", G_CALLBACK (on_search_selection_changed), shell); } static void setup_lock (CinnamonControlCenter *shell) { CinnamonControlCenterPrivate *priv = shell->priv; priv->lock_button = W (priv->builder, "lock-button"); } static void maybe_add_category_view (CinnamonControlCenter *shell, const char *name) { GtkTreeModel *filter; GtkWidget *categoryview; if (g_hash_table_lookup (shell->priv->category_views, name) != NULL) return; if (g_hash_table_size (shell->priv->category_views) > 0) { GtkWidget *separator; separator = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL); gtk_widget_set_margin_top (separator, 11); gtk_widget_set_margin_bottom (separator, 10); gtk_box_pack_start (GTK_BOX (shell->priv->main_vbox), separator, FALSE, FALSE, 0); gtk_widget_show (separator); } /* create new category view for this category */ filter = gtk_tree_model_filter_new (GTK_TREE_MODEL (shell->priv->store), NULL); gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (filter), (GtkTreeModelFilterVisibleFunc) category_filter_func, g_strdup (name), g_free); categoryview = cc_shell_category_view_new (name, filter); gtk_box_pack_start (GTK_BOX (shell->priv->main_vbox), categoryview, FALSE, TRUE, 0); g_signal_connect (cc_shell_category_view_get_item_view (CC_SHELL_CATEGORY_VIEW (categoryview)), "desktop-item-activated", G_CALLBACK (item_activated_cb), shell); gtk_widget_show (categoryview); g_signal_connect (cc_shell_category_view_get_item_view (CC_SHELL_CATEGORY_VIEW (categoryview)), "focus-in-event", G_CALLBACK (category_focus_in), shell); g_signal_connect (cc_shell_category_view_get_item_view (CC_SHELL_CATEGORY_VIEW (categoryview)), "focus-out-event", G_CALLBACK (category_focus_out), shell); g_signal_connect (cc_shell_category_view_get_item_view (CC_SHELL_CATEGORY_VIEW (categoryview)), "keynav-failed", G_CALLBACK (keynav_failed), shell); g_hash_table_insert (shell->priv->category_views, g_strdup (name), categoryview); } static void reload_menu (CinnamonControlCenter *shell) { GError *error; GMenuTreeDirectory *d; GMenuTreeIter *iter; GMenuTreeItemType next_type; error = NULL; if (!gmenu_tree_load_sync (shell->priv->menu_tree, &error)) { g_warning ("Could not load control center menu: %s", error->message); g_clear_error (&error); return; } d = gmenu_tree_get_root_directory (shell->priv->menu_tree); iter = gmenu_tree_directory_iter (d); while ((next_type = gmenu_tree_iter_next (iter)) != GMENU_TREE_ITEM_INVALID) { if (next_type == GMENU_TREE_ITEM_DIRECTORY) { GMenuTreeDirectory *subdir; const gchar *dir_name; GMenuTreeIter *sub_iter; GMenuTreeItemType sub_next_type; subdir = gmenu_tree_iter_get_directory (iter); dir_name = gmenu_tree_directory_get_name (subdir); maybe_add_category_view (shell, dir_name); /* add the items from this category to the model */ sub_iter = gmenu_tree_directory_iter (subdir); while ((sub_next_type = gmenu_tree_iter_next (sub_iter)) != GMENU_TREE_ITEM_INVALID) { if (sub_next_type == GMENU_TREE_ITEM_ENTRY) { GMenuTreeEntry *item = gmenu_tree_iter_get_entry (sub_iter); cc_shell_model_add_item (CC_SHELL_MODEL (shell->priv->store), dir_name, item); gmenu_tree_item_unref (item); } } gmenu_tree_iter_unref (sub_iter); gmenu_tree_item_unref (subdir); } } gmenu_tree_iter_unref (iter); } static void on_menu_changed (GMenuTree *monitor, CinnamonControlCenter *shell) { gtk_list_store_clear (shell->priv->store); reload_menu (shell); } static void setup_model (CinnamonControlCenter *shell) { CinnamonControlCenterPrivate *priv = shell->priv; gtk_widget_set_margin_top (shell->priv->main_vbox, 8); gtk_widget_set_margin_bottom (shell->priv->main_vbox, 8); gtk_widget_set_margin_left (shell->priv->main_vbox, 12); gtk_widget_set_margin_right (shell->priv->main_vbox, 12); gtk_container_set_focus_vadjustment (GTK_CONTAINER (shell->priv->main_vbox), gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (shell->priv->scrolled_window))); priv->store = (GtkListStore *) cc_shell_model_new (); priv->category_views = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); priv->menu_tree = gmenu_tree_new_for_path (MENUDIR "/cinnamoncc.menu", 0); reload_menu (shell); g_signal_connect (priv->menu_tree, "changed", G_CALLBACK (on_menu_changed), shell); } static void load_panel_plugins (CinnamonControlCenter *shell) { GList *modules; /* only allow this function to be run once to prevent modules being loaded * twice */ if (shell->priv->extension_point) return; /* make sure the base type is registered */ g_type_from_name ("CcPanel"); shell->priv->extension_point = g_io_extension_point_register (CC_SHELL_PANEL_EXTENSION_POINT); /* load all the plugins in the panels directory */ modules = g_io_modules_load_all_in_directory (PANELS_DIR); g_list_free (modules); } static void home_button_clicked_cb (GtkButton *button, CinnamonControlCenter *shell) { shell_show_overview_page (shell); } static void notebook_page_notify_cb (GtkNotebook *notebook, GParamSpec *spec, CinnamonControlCenterPrivate *priv) { int nat_height; GtkWidget *child; child = notebook_get_selected_page (GTK_WIDGET (notebook)); if (child == priv->scrolled_window || child == priv->search_scrolled) { gtk_widget_hide (W (priv->builder, "lock-button")); if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) gtk_widget_get_preferred_height_for_width (GTK_WIDGET (priv->main_vbox), UNITY_FIXED_WIDTH, NULL, &nat_height); else gtk_widget_get_preferred_height_for_width (GTK_WIDGET (priv->main_vbox), FIXED_WIDTH, NULL, &nat_height); gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (priv->scrolled_window), priv->small_screen == SMALL_SCREEN_TRUE ? SMALL_SCREEN_FIXED_HEIGHT : nat_height); } else { /* set the scrolled window small so that it doesn't force the window to be larger than this panel */ if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) { gtk_widget_get_preferred_height_for_width (GTK_WIDGET (priv->window), UNITY_FIXED_WIDTH, NULL, &nat_height); gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (priv->scrolled_window), MIN_ICON_VIEW_HEIGHT); gtk_window_resize (GTK_WINDOW (priv->window), UNITY_FIXED_WIDTH, nat_height); } else { gtk_widget_get_preferred_height_for_width (GTK_WIDGET (priv->window), FIXED_WIDTH, NULL, &nat_height); gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (priv->scrolled_window), MIN_ICON_VIEW_HEIGHT); gtk_window_resize (GTK_WINDOW (priv->window), FIXED_WIDTH, nat_height); } } } /* CcShell implementation */ static void _shell_embed_widget_in_header (CcShell *shell, GtkWidget *widget) { CinnamonControlCenterPrivate *priv = CINNAMON_CONTROL_CENTER (shell)->priv; GtkBox *box; /* add to header */ box = GTK_BOX (W (priv->builder, "topright")); gtk_box_pack_end (box, widget, FALSE, FALSE, 0); g_ptr_array_add (priv->custom_widgets, g_object_ref (widget)); } /* CcShell implementation */ static gboolean _shell_set_active_panel_from_id (CcShell *shell, const gchar *start_id, const gchar **argv, GError **err) { GtkTreeIter iter; gboolean iter_valid; gchar *name = NULL; gchar *desktop = NULL; GIcon *gicon = NULL; CinnamonControlCenterPrivate *priv = CINNAMON_CONTROL_CENTER (shell)->priv; GtkWidget *old_panel; /* When loading the same panel again, just set the argv */ if (g_strcmp0 (priv->current_panel_id, start_id) == 0) { g_object_set (G_OBJECT (priv->current_panel), "argv", argv, NULL); return TRUE; } if (priv->current_panel_id) { g_free (priv->current_panel_id); priv->current_panel_id = NULL; } if (!g_strcmp0 (g_getenv ("XDG_CURRENT_DESKTOP"), "Unity") && !g_strcmp0(start_id, "sound")) start_id = "sound-nua"; /* clear any custom widgets */ _shell_remove_all_custom_widgets (priv); iter_valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->store), &iter); /* find the details for this item */ while (iter_valid) { gchar *id; gtk_tree_model_get (GTK_TREE_MODEL (priv->store), &iter, COL_NAME, &name, COL_DESKTOP_FILE, &desktop, COL_GICON, &gicon, COL_ID, &id, -1); if (id && !strcmp (id, start_id)) { g_free (id); break; } else { g_free (id); g_free (name); g_free (desktop); if (gicon) g_object_unref (gicon); name = NULL; id = NULL; desktop = NULL; gicon = NULL; } iter_valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (priv->store), &iter); } if (!name) { g_warning ("Could not find settings panel \"%s\"", start_id); } else if (activate_panel (CINNAMON_CONTROL_CENTER (shell), start_id, argv, desktop, name, gicon) == FALSE) { /* Failed to activate the panel for some reason */ old_panel = priv->current_panel_box; priv->current_panel_box = NULL; notebook_select_page (priv->notebook, priv->scrolled_window); if (old_panel) notebook_remove_page (priv->notebook, old_panel); } else { priv->current_panel_id = g_strdup (start_id); } g_free (name); g_free (desktop); if (gicon) g_object_unref (gicon); return TRUE; } static GtkWidget * _shell_get_toplevel (CcShell *shell) { return CINNAMON_CONTROL_CENTER (shell)->priv->window; } /* GObject Implementation */ static void cinnamon_control_center_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cinnamon_control_center_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void cinnamon_control_center_dispose (GObject *object) { CinnamonControlCenterPrivate *priv = CINNAMON_CONTROL_CENTER (object)->priv; g_free (priv->current_panel_id); if (priv->custom_widgets) { g_ptr_array_unref (priv->custom_widgets); priv->custom_widgets = NULL; } if (priv->window) { gtk_widget_destroy (priv->window); priv->window = NULL; /* destroying the window will destroy its children */ priv->notebook = NULL; priv->search_entry = NULL; priv->search_view = NULL; } if (priv->builder) { g_object_unref (priv->builder); priv->builder = NULL; } if (priv->store) { g_object_unref (priv->store); priv->store = NULL; } if (priv->search_filter) { g_object_unref (priv->search_filter); priv->search_filter = NULL; } G_OBJECT_CLASS (cinnamon_control_center_parent_class)->dispose (object); } static void cinnamon_control_center_finalize (GObject *object) { CinnamonControlCenterPrivate *priv = CINNAMON_CONTROL_CENTER (object)->priv; if (priv->filter_string) { g_free (priv->filter_string); priv->filter_string = NULL; } if (priv->default_window_title) { g_free (priv->default_window_title); priv->default_window_title = NULL; } if (priv->default_window_icon) { g_free (priv->default_window_icon); priv->default_window_icon = NULL; } if (priv->menu_tree) { g_signal_handlers_disconnect_by_func (priv->menu_tree, G_CALLBACK (on_menu_changed), object); g_object_unref (priv->menu_tree); } if (priv->category_views) { g_hash_table_destroy (priv->category_views); } G_OBJECT_CLASS (cinnamon_control_center_parent_class)->finalize (object); } static void cinnamon_control_center_class_init (CinnamonControlCenterClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); CcShellClass *shell_class = CC_SHELL_CLASS (klass); g_type_class_add_private (klass, sizeof (CinnamonControlCenterPrivate)); object_class->get_property = cinnamon_control_center_get_property; object_class->set_property = cinnamon_control_center_set_property; object_class->dispose = cinnamon_control_center_dispose; object_class->finalize = cinnamon_control_center_finalize; shell_class->set_active_panel_from_id = _shell_set_active_panel_from_id; shell_class->embed_widget_in_header = _shell_embed_widget_in_header; shell_class->get_toplevel = _shell_get_toplevel; } static gboolean window_key_press_event (GtkWidget *win, GdkEventKey *event, CinnamonControlCenter *self) { GdkKeymap *keymap; gboolean retval; GdkModifierType state; if (event->state == 0) return FALSE; retval = FALSE; state = event->state; keymap = gdk_keymap_get_default (); gdk_keymap_add_virtual_modifiers (keymap, &state); state = state & gtk_accelerator_get_default_mod_mask (); if (state == GDK_CONTROL_MASK) { switch (event->keyval) { case GDK_KEY_s: case GDK_KEY_S: case GDK_KEY_f: case GDK_KEY_F: retval = TRUE; break; case GDK_KEY_Q: case GDK_KEY_q: g_object_unref (self); retval = TRUE; break; case GDK_KEY_W: case GDK_KEY_w: if (notebook_get_selected_page (self->priv->notebook) != self->priv->scrolled_window) shell_show_overview_page (self); retval = TRUE; break; } } return retval; } static gint get_monitor_height (CinnamonControlCenter *self) { GdkScreen *screen; GdkRectangle rect; /* We cannot use workarea here, as this wouldn't * be updated when we read it after a monitors-changed signal */ screen = gtk_widget_get_screen (self->priv->window); gdk_screen_get_monitor_geometry (screen, self->priv->monitor_num, &rect); return rect.height; } static gboolean update_monitor_number (CinnamonControlCenter *self) { gboolean changed = FALSE; GtkWidget *widget; GdkScreen *screen; GdkWindow *window; int monitor; widget = self->priv->window; window = gtk_widget_get_window (widget); screen = gtk_widget_get_screen (widget); monitor = gdk_screen_get_monitor_at_window (screen, window); if (self->priv->monitor_num != monitor) { self->priv->monitor_num = monitor; changed = TRUE; } return changed; } static CcSmallScreen is_small (CinnamonControlCenter *self) { if (get_monitor_height (self) <= FIXED_HEIGHT) return SMALL_SCREEN_TRUE; return SMALL_SCREEN_FALSE; } static void update_small_screen_settings (CinnamonControlCenter *self) { CcSmallScreen small; update_monitor_number (self); small = is_small (self); if (small == SMALL_SCREEN_TRUE) { gtk_window_set_resizable (GTK_WINDOW (self->priv->window), TRUE); if (self->priv->small_screen != small) gtk_window_maximize (GTK_WINDOW (self->priv->window)); } else { if (self->priv->small_screen != small) gtk_window_unmaximize (GTK_WINDOW (self->priv->window)); gtk_window_set_resizable (GTK_WINDOW (self->priv->window), FALSE); } self->priv->small_screen = small; /* And update the minimum sizes */ notebook_page_notify_cb (GTK_NOTEBOOK (self->priv->notebook), NULL, self->priv); } static gboolean main_window_configure_cb (GtkWidget *widget, GdkEvent *event, CinnamonControlCenter *self) { update_small_screen_settings (self); return FALSE; } static void application_set_cb (GObject *object, GParamSpec *pspec, CinnamonControlCenter *self) { /* update small screen settings now - to avoid visible resizing, we want * to do it before showing the window, and GtkApplicationWindow cannot be * realized unless its application property has been set */ if (gtk_window_get_application (GTK_WINDOW (self->priv->window))) { gtk_widget_realize (self->priv->window); update_small_screen_settings (self); } } static void monitors_changed_cb (GdkScreen *screen, CinnamonControlCenter *self) { /* We reset small_screen_set to make sure that the * window gets maximised if need be, in update_small_screen_settings() */ self->priv->small_screen = SMALL_SCREEN_UNSET; update_small_screen_settings (self); } static void cinnamon_control_center_init (CinnamonControlCenter *self) { GError *err = NULL; CinnamonControlCenterPrivate *priv; GdkScreen *screen; GtkWidget *widget; priv = self->priv = CONTROL_CENTER_PRIVATE (self); #ifdef HAVE_CHEESE if (gtk_clutter_init (NULL, NULL) != CLUTTER_INIT_SUCCESS) { g_critical ("Clutter-GTK init failed"); return; } #endif priv->monitor_num = -1; self->priv->small_screen = SMALL_SCREEN_UNSET; /* load the user interface */ priv->builder = gtk_builder_new (); if (!gtk_builder_add_from_file (priv->builder, UIDIR "/shell.ui", &err)) { g_critical ("Could not build interface: %s", err->message); g_error_free (err); return; } /* connect various signals */ priv->window = W (priv->builder, "main-window"); gtk_window_set_hide_titlebar_when_maximized (GTK_WINDOW (priv->window), TRUE); screen = gtk_widget_get_screen (priv->window); g_signal_connect (screen, "monitors-changed", G_CALLBACK (monitors_changed_cb), self); g_signal_connect (priv->window, "configure-event", G_CALLBACK (main_window_configure_cb), self); g_signal_connect (priv->window, "notify::application", G_CALLBACK (application_set_cb), self); g_signal_connect_swapped (priv->window, "delete-event", G_CALLBACK (g_object_unref), self); g_signal_connect_after (priv->window, "key_press_event", G_CALLBACK (window_key_press_event), self); priv->notebook = W (priv->builder, "notebook"); /* Main scrolled window */ priv->scrolled_window = W (priv->builder, "scrolledwindow1"); if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity")) gtk_widget_set_size_request (priv->scrolled_window, UNITY_FIXED_WIDTH, -1); else gtk_widget_set_size_request (priv->scrolled_window, FIXED_WIDTH, -1); priv->main_vbox = W (priv->builder, "main-vbox"); g_signal_connect (priv->notebook, "notify::page", G_CALLBACK (notebook_page_notify_cb), priv); priv->nav_bar = cc_shell_nav_bar_new (); widget = W (priv->builder, "hbox1"); gtk_box_pack_start (GTK_BOX (widget), priv->nav_bar, FALSE, FALSE, 0); gtk_box_reorder_child (GTK_BOX (widget), priv->nav_bar, 0); gtk_widget_show (priv->nav_bar); g_signal_connect (priv->nav_bar, "home-clicked", G_CALLBACK (home_button_clicked_cb), self); /* keep a list of custom widgets to unload on panel change */ priv->custom_widgets = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref); /* load the available settings panels */ setup_model (self); /* load the panels that are implemented as plugins */ load_panel_plugins (self); /* setup search functionality */ setup_search (self); setup_lock (self); /* store default window title and name */ priv->default_window_title = g_strdup (gtk_window_get_title (GTK_WINDOW (priv->window))); priv->default_window_icon = g_strdup (gtk_window_get_icon_name (GTK_WINDOW (priv->window))); notebook_page_notify_cb (GTK_NOTEBOOK (priv->notebook), NULL, priv); } CinnamonControlCenter * cinnamon_control_center_new (void) { return g_object_new (CINNAMON_TYPE_CONTROL_CENTER, NULL); } void cinnamon_control_center_present (CinnamonControlCenter *center) { gtk_window_present (GTK_WINDOW (center->priv->window)); } void cinnamon_control_center_show (CinnamonControlCenter *center, GtkApplication *app) { gtk_window_set_application (GTK_WINDOW (center->priv->window), app); gtk_widget_show (gtk_bin_get_child (GTK_BIN (center->priv->window))); }
492
./pgen/pgen.c
#include <stdio.h> #include <stdlib.h> #include <openssl/bn.h> #include <openssl/rand.h> int main(int argc, char **argv) { if (argc != 3) { printf("%s: error: Please supply a generator and a bit count.\n", argv[0]); return 1; } char *end_ptr = NULL; unsigned long int bits = strtoul(argv[2], &end_ptr, 10); if (*end_ptr || end_ptr == argv[2]) { printf("%s: error: Please supply a valid bit count.\n", argv[0]); return 1; } if (!RAND_load_file("/dev/urandom", 1024)) { printf("%s: error: Could not seed PRNG from /dev/urandom.\n", argv[0]); return 1; } BIGNUM *g = NULL, *N = BN_new(), *p = BN_new(); if (!N || !p) goto failure; if (!BN_dec2bn(&g, argv[1])) { printf("%s: error: Please supply a valid generator.\n", argv[0]); return 1; } BN_CTX *ctx = BN_CTX_new(); if (BN_is_prime(g, BN_prime_checks, NULL, ctx, NULL) != 1) { printf("%s: error: The given generator is not a prime.\n", argv[0]); return 1; } if (!BN_generate_prime(N, bits, 1, NULL, NULL, NULL, NULL)) goto failure; BIGNUM *rg = BN_new(); ctx = BN_CTX_new(); if (!rg || !ctx) goto failure; if (!BN_gcd(rg, g, N, ctx)) goto failure; char *o_n = BN_bn2dec(N); char *o_g = BN_bn2dec(g); char *o_gcd = BN_bn2dec(rg); if (!o_n || !o_g || !o_gcd) goto failure; printf("N = %s\n", o_n); printf("g = %s\n", o_g); printf("gcd(g, N) = %s\n", o_gcd); return 0; failure: printf("%s: error: Big number operation failed.\n", argv[0]); return 1; }
493
./exodriver/liblabjackusb/labjackusb.c
//--------------------------------------------------------------------------- // // labjackusb.c // // Library for accessing a U3, U6, UE9, SkyMote bridge, T7 and Digit over // USB. // // support@labjack.com // //--------------------------------------------------------------------------- // #include "labjackusb.h" #include <unistd.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/utsname.h> #include <fcntl.h> #include <errno.h> #include <libusb-1.0/libusb.h> #define LJ_LIBUSB_TIMEOUT_DEFAULT 1000 // Milliseconds to wait on USB transfers // With a recent Linux kernel, firmware and hardware checks aren't necessary #define LJ_RECENT_KERNEL_MAJOR 2 #define LJ_RECENT_KERNEL_MINOR 6 #define LJ_RECENT_KERNEL_REV 28 #define MIN_UE9_FIRMWARE_MAJOR 1 #define MIN_UE9_FIRMWARE_MINOR 49 #define U3C_HARDWARE_MAJOR 1 #define U3C_HARDWARE_MINOR 30 #define MIN_U3C_FIRMWARE_MAJOR 1 #define MIN_U3C_FIRMWARE_MINOR 18 #define MIN_U6_FIRMWARE_MAJOR 0 #define MIN_U6_FIRMWARE_MINOR 81 // Set to 0 for no debug logging or 1 for logging. #define LJ_DEBUG 0 static bool gIsLibUSBInitialized = false; static struct libusb_context *gLJContext = NULL; enum LJUSB_TRANSFER_OPERATION { LJUSB_WRITE, LJUSB_READ, LJUSB_STREAM }; struct LJUSB_FirmwareHardwareVersion { unsigned char firmwareMajor; unsigned char firmwareMinor; unsigned char hardwareMajor; unsigned char hardwareMinor; }; static void LJUSB_U3_FirmwareHardwareVersion(HANDLE hDevice, struct LJUSB_FirmwareHardwareVersion * fhv) { unsigned long i = 0, r = 0; unsigned long epOut = U3_PIPE_EP1_OUT, epIn = U3_PIPE_EP2_IN; const unsigned long COMMAND_LENGTH = 26; const unsigned long RESPONSE_LENGTH = 38; BYTE command[COMMAND_LENGTH]; BYTE response[RESPONSE_LENGTH]; memset(command, 0, COMMAND_LENGTH); memset(response, 0, RESPONSE_LENGTH); //Checking firmware for U3. Using ConfigU3 Low-level command command[0] = 11; command[1] = (BYTE)(0xF8); command[2] = (BYTE)(0x0A); command[3] = (BYTE)(0x08); LJUSB_BulkWrite(hDevice, epOut, command, COMMAND_LENGTH); if ((r = LJUSB_BulkRead(hDevice, epIn, response, RESPONSE_LENGTH)) < RESPONSE_LENGTH) { fprintf(stderr, "ConfigU3 response failed when getting firmware and hardware versions\n"); fprintf(stderr, "Response was:\n"); for (i = 0; i < r; i++) { fprintf(stderr, "%d ", response[i]); } fprintf(stderr, "\n"); return; } if (response[1] != command[1] || response[2] != (BYTE)(0x10) || response[3] != command[3]) { fprintf(stderr, "Invalid ConfigU3 command bytes when getting firmware and hardware versions\n"); fprintf(stderr, "Response was:\n"); for (i = 0; i < r; i++) { fprintf(stderr, "%d ", response[i]); } fprintf(stderr, "\n"); return; } fhv->firmwareMajor = response[10]; fhv->firmwareMinor = response[9]; fhv->hardwareMajor = response[14]; fhv->hardwareMinor = response[13]; return; } static void LJUSB_U6_FirmwareHardwareVersion(HANDLE hDevice, struct LJUSB_FirmwareHardwareVersion * fhv) { unsigned long i = 0, r = 0; unsigned long epOut = U6_PIPE_EP1_OUT, epIn = U6_PIPE_EP2_IN; const unsigned long COMMAND_LENGTH = 26; const unsigned long RESPONSE_LENGTH = 38; BYTE command[COMMAND_LENGTH]; BYTE response[RESPONSE_LENGTH]; memset(command, 0, COMMAND_LENGTH); memset(response, 0, RESPONSE_LENGTH); //Checking firmware for U6. Using ConfigU3 Low-level command command[0] = 11; command[1] = (BYTE)(0xF8); command[2] = (BYTE)(0x0A); command[3] = (BYTE)(0x08); LJUSB_BulkWrite(hDevice, epOut, command, COMMAND_LENGTH); if ((r = LJUSB_BulkRead(hDevice, epIn, response, RESPONSE_LENGTH)) < RESPONSE_LENGTH) { fprintf(stderr, "ConfigU6 response failed when getting firmware and hardware versions\n"); fprintf(stderr, "Response was:\n"); for (i = 0; i < r; i++) { fprintf(stderr, "%d ", response[i]); } fprintf(stderr, "\n"); return; } if (response[1] != command[1] || response[2] != (BYTE)(0x10) || response[3] != command[3]) { fprintf(stderr, "Invalid ConfigU6 command bytes when getting firmware and hardware versions\n"); fprintf(stderr, "Response was:\n"); for (i = 0; i < r; i++) { fprintf(stderr, "%d ", response[i]); } fprintf(stderr, "\n"); return; } fhv->firmwareMajor = response[10]; fhv->firmwareMinor = response[9]; /* TODO: Add hardware major and minor */ return; } static void LJUSB_UE9_FirmwareHardwareVersion(HANDLE hDevice, struct LJUSB_FirmwareHardwareVersion * fhv) { unsigned long i = 0, r = 0; unsigned long epOut = UE9_PIPE_EP1_OUT, epIn = UE9_PIPE_EP1_IN; const unsigned long COMMAND_LENGTH = 38; const unsigned long RESPONSE_LENGTH = 38; BYTE command[COMMAND_LENGTH]; BYTE response[RESPONSE_LENGTH]; memset(command, 0, COMMAND_LENGTH); memset(response, 0, RESPONSE_LENGTH); //Checking firmware for UE9. Using CommConfig Low-level command command[0] = 137; command[1] = (BYTE)(0x78); command[2] = (BYTE)(0x10); command[3] = (BYTE)(0x01); LJUSB_BulkWrite(hDevice, epOut, command, COMMAND_LENGTH); if ((r = LJUSB_BulkRead(hDevice, epIn, response, RESPONSE_LENGTH)) < RESPONSE_LENGTH) { fprintf(stderr, "CommConfig response failed when getting firmware and hardware versions\n"); fprintf(stderr, "Response was:\n"); for (i = 0; i < r; i++) { fprintf(stderr, "%d ", response[i]); } fprintf(stderr, "\n"); return; } if (response[1] != command[1] || response[2] != command[2] || response[3] != command[3]) { fprintf(stderr, "Invalid CommConfig command bytes when getting firmware and hardware versions\n"); fprintf(stderr, "Response was:\n"); for (i = 0; i < r; i++) { fprintf(stderr, "%d ", response[i]); } fprintf(stderr, "\n"); return; } fhv->firmwareMajor = response[37]; fhv->firmwareMinor = response[36]; /* TODO: Add hardware major and minor */ return; } static bool LJUSB_isNullHandle(HANDLE hDevice) { if (hDevice == NULL) { // TODO: Consider different errno here errno = EINVAL; return true; } return false; } static int LJUSB_libusbError(int r) { switch (r) { case LIBUSB_SUCCESS: // No error return 0; break; case LIBUSB_ERROR_IO: fprintf(stderr, "libusb error: LIBUSB_ERROR_IO\n"); errno = EIO; break; case LIBUSB_ERROR_INVALID_PARAM: fprintf(stderr, "libusb error: LIBUSB_ERROR_INVALID_PARAM\n"); errno = EINVAL; break; case LIBUSB_ERROR_ACCESS: fprintf(stderr, "libusb error: LIBUSB_ERROR_ACCESS\n"); errno = EACCES; break; case LIBUSB_ERROR_NO_DEVICE: fprintf(stderr, "libusb error: LIBUSB_ERROR_NO_DEVICE\n"); errno = ENXIO; break; case LIBUSB_ERROR_NOT_FOUND: fprintf(stderr, "libusb error: LIBUSB_ERROR_NOT_FOUND\n"); errno = ENOENT; break; case LIBUSB_ERROR_BUSY: fprintf(stderr, "libusb error: LIBUSB_ERROR_BUSY\n"); errno = EBUSY; break; case LIBUSB_ERROR_TIMEOUT: fprintf(stderr, "libusb error: LIBUSB_ERROR_TIMEOUT\n"); errno = ETIMEDOUT; break; case LIBUSB_ERROR_OVERFLOW: fprintf(stderr, "libusb error: LIBUSB_ERROR_OVERFLOW\n"); errno = EOVERFLOW; break; case LIBUSB_ERROR_PIPE: fprintf(stderr, "libusb error: LIBUSB_ERROR_PIPE\n"); errno = EPIPE; break; case LIBUSB_ERROR_INTERRUPTED: fprintf(stderr, "libusb error: LIBUSB_ERROR_INTERRUPTED\n"); errno = EINTR; break; case LIBUSB_ERROR_NO_MEM: fprintf(stderr, "libusb error: LIBUSB_ERROR_NO_MEM\n"); errno = ENOMEM; break; case LIBUSB_ERROR_NOT_SUPPORTED: fprintf(stderr, "libusb error: LIBUSB_ERROR_NOT_SUPPORTED\n"); errno = ENOSYS; break; case LIBUSB_ERROR_OTHER: fprintf(stderr, "libusb error: LIBUSB_ERROR_OTHER\n"); if (errno == 0) { errno = ENOSYS; } break; default: fprintf(stderr, "libusb error: Unexpected error code: %d.\n", r); if (errno == 0) { errno = ENOSYS; } break; } return -1; } static bool LJUSB_U3_isMinFirmware(const struct LJUSB_FirmwareHardwareVersion * fhv) { if (fhv->hardwareMajor == U3C_HARDWARE_MAJOR && fhv->hardwareMinor == U3C_HARDWARE_MINOR) { if (fhv->firmwareMajor > MIN_U3C_FIRMWARE_MAJOR || (fhv->firmwareMajor == MIN_U3C_FIRMWARE_MAJOR && fhv->firmwareMinor >= MIN_U3C_FIRMWARE_MINOR)) { return true; } else { fprintf(stderr, "Minimum U3 firmware not met is not met for this kernel. Please update from firmware %d.%02d to firmware %d.%d or upgrade to kernel %d.%d.%d.\n", fhv->firmwareMajor, fhv->firmwareMinor, MIN_U3C_FIRMWARE_MAJOR, MIN_U3C_FIRMWARE_MINOR, LJ_RECENT_KERNEL_MAJOR, LJ_RECENT_KERNEL_MINOR, LJ_RECENT_KERNEL_REV); return false; } } else { fprintf(stderr, "Minimum U3 hardware version not met for this kernel. This driver supports only hardware %d.%d and above. Your hardware version is %d.%d.\n", U3C_HARDWARE_MAJOR, U3C_HARDWARE_MINOR, fhv->hardwareMajor, fhv->hardwareMinor); fprintf(stderr, "This hardware version is supported under kernel %d.%d.%d.\n", LJ_RECENT_KERNEL_MAJOR, LJ_RECENT_KERNEL_MINOR, LJ_RECENT_KERNEL_REV); return false; } return false; } static bool LJUSB_U6_isMinFirmware(const struct LJUSB_FirmwareHardwareVersion * fhv) { if (fhv->firmwareMajor > MIN_U6_FIRMWARE_MAJOR || (fhv->firmwareMajor == MIN_U6_FIRMWARE_MAJOR && fhv->firmwareMinor >= MIN_U6_FIRMWARE_MINOR)) { return true; } else { fprintf(stderr, "Minimum U6 firmware not met is not met for this kernel. Please update from firmware %d.%d to firmware %d.%d or upgrade to kernel %d.%d.%d.\n", fhv->firmwareMajor, fhv->firmwareMinor, MIN_U6_FIRMWARE_MAJOR, MIN_U6_FIRMWARE_MINOR, LJ_RECENT_KERNEL_MAJOR, LJ_RECENT_KERNEL_MINOR, LJ_RECENT_KERNEL_REV); return false; } return false; } static bool LJUSB_UE9_isMinFirmware(const struct LJUSB_FirmwareHardwareVersion * fhv) { #if LJ_DEBUG fprintf(stderr, "In LJUSB_UE9_isMinFirmware\n"); #endif if (fhv->firmwareMajor > MIN_UE9_FIRMWARE_MAJOR || (fhv->firmwareMajor == MIN_UE9_FIRMWARE_MAJOR && fhv->firmwareMinor >= MIN_UE9_FIRMWARE_MINOR)) { #if LJ_DEBUG fprintf(stderr, "Minimum UE9 firmware met. Version is %d.%d.\n", fhv->firmwareMajor, fhv->firmwareMinor); #endif return true; } else { fprintf(stderr, "Minimum UE9 firmware not met is not met for this kernel. Please update from firmware %d.%d to firmware %d.%d or upgrade to kernel %d.%d.%d.\n", fhv->firmwareMajor, fhv->firmwareMinor, MIN_UE9_FIRMWARE_MAJOR, MIN_UE9_FIRMWARE_MINOR, LJ_RECENT_KERNEL_MAJOR, LJ_RECENT_KERNEL_MINOR, LJ_RECENT_KERNEL_REV); return false; } return false; } static bool LJUSB_isRecentKernel(void) { struct utsname u; char *tok = NULL; unsigned long kernelMajor = 0, kernelMinor = 0, kernelRev = 0; if (uname(&u) != 0) { fprintf(stderr, "Error calling uname(2)."); return false; } // There are no known kernel-compatibility problems with Mac OS X. #if LJ_DEBUG fprintf(stderr, "LJUSB_recentKernel: sysname: %s.\n", u.sysname); #endif if (strncmp("Darwin", u.sysname, strlen("Darwin")) == 0) { #if LJ_DEBUG fprintf(stderr, "LJUSB_recentKernel: returning true on Darwin.\n"); #endif return true; } #if LJ_DEBUG fprintf(stderr, "LJUSB_recentKernel: Kernel release: %s.\n", u.release); #endif tok = strtok(u.release, ".-"); kernelMajor = strtoul(tok, NULL, 10); #if LJ_DEBUG fprintf(stderr, "LJUSB_recentKernel: tok: %s\n", tok); fprintf(stderr, "LJUSB_recentKernel: kernelMajor: %lu\n", kernelMajor); #endif tok = strtok(NULL, ".-"); kernelMinor = strtoul(tok, NULL, 10); #if LJ_DEBUG fprintf(stderr, "LJUSB_recentKernel: tok: %s\n", tok); fprintf(stderr, "LJUSB_recentKernel: kernelMinor: %lu\n", kernelMinor); #endif tok = strtok(NULL, ".-"); kernelRev = strtoul(tok, NULL, 10); #if LJ_DEBUG fprintf(stderr, "LJUSB_recentKernel: tok: %s\n", tok); fprintf(stderr, "LJUSB_recentKernel: kernelRev: %lu\n", kernelRev); #endif return (kernelMajor == LJ_RECENT_KERNEL_MAJOR && kernelMinor == LJ_RECENT_KERNEL_MINOR && kernelRev >= LJ_RECENT_KERNEL_REV) || (kernelMajor == LJ_RECENT_KERNEL_MAJOR && kernelMinor > LJ_RECENT_KERNEL_MINOR) || (kernelMajor > LJ_RECENT_KERNEL_MAJOR); } static bool LJUSB_isMinFirmware(HANDLE hDevice, unsigned long ProductID) { struct LJUSB_FirmwareHardwareVersion fhv = {0, 0, 0, 0}; // If we are running on a recent kernel, no firmware check is necessary. if (LJUSB_isRecentKernel()) { #if LJ_DEBUG fprintf(stderr, "LJUSB_isMinFirmware: LJUSB_isRecentKernel: true\n"); #endif return true; } #if LJ_DEBUG fprintf(stderr, "LJUSB_isMinFirmware: LJUSB_isRecentKernel: false\n"); #endif switch (ProductID) { case U3_PRODUCT_ID: LJUSB_U3_FirmwareHardwareVersion(hDevice, &fhv); return LJUSB_U3_isMinFirmware(&fhv); case U6_PRODUCT_ID: LJUSB_U6_FirmwareHardwareVersion(hDevice, &fhv); return LJUSB_U6_isMinFirmware(&fhv); case UE9_PRODUCT_ID: LJUSB_UE9_FirmwareHardwareVersion(hDevice, &fhv); return LJUSB_UE9_isMinFirmware(&fhv); case U12_PRODUCT_ID: //Add U12 stuff Mike F. return true; case BRIDGE_PRODUCT_ID: //Add Wireless bridge stuff Mike F. return true; case T7_PRODUCT_ID: return true; case DIGIT_PRODUCT_ID: return true; default: fprintf(stderr, "Firmware check not supported for product ID %ld\n", ProductID); return false; } } static void LJUSB_libusb_exit(void) { if (gIsLibUSBInitialized) { libusb_exit(gLJContext); gLJContext = NULL; gIsLibUSBInitialized = false; } } float LJUSB_GetLibraryVersion(void) { return LJUSB_LIBRARY_VERSION; } HANDLE LJUSB_OpenDevice(UINT DevNum, unsigned int dwReserved, unsigned long ProductID) { (void)dwReserved; libusb_device **devs = NULL, *dev = NULL; struct libusb_device_handle *devh = NULL; struct libusb_device_descriptor desc; ssize_t cnt = 0; int r = 1; unsigned int i = 0; unsigned int ljFoundCount = 0; HANDLE handle = NULL; if (!gIsLibUSBInitialized) { r = libusb_init(&gLJContext); if (r < 0) { fprintf(stderr, "failed to initialize libusb\n"); LJUSB_libusbError(r); return NULL; } gIsLibUSBInitialized = true; } cnt = libusb_get_device_list(gLJContext, &devs); if (cnt < 0) { fprintf(stderr, "failed to get device list\n"); LJUSB_libusbError(cnt); LJUSB_libusb_exit(); return NULL; } while ((dev = devs[i++]) != NULL) { #if LJ_DEBUG fprintf(stderr, "LJUSB_OpenDevice: calling libusb_get_device_descriptor\n"); #endif r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { fprintf(stderr, "failed to get device descriptor"); LJUSB_libusbError(r); LJUSB_libusb_exit(); return NULL; } if (LJ_VENDOR_ID == desc.idVendor && ProductID == desc.idProduct) { ljFoundCount++; if (ljFoundCount == DevNum) { // Found the one requested r = libusb_open(dev, &devh); if (r < 0) { LJUSB_libusbError(r); return NULL; } // Test if the kernel driver has the device. // Should only be true for HIDs. if (libusb_kernel_driver_active(devh, 0)) { #if LJ_DEBUG fprintf(stderr, "Kernel Driver was active, detaching...\n"); #endif // Detaches U12s from kernel driver. r = libusb_detach_kernel_driver(devh, 0); // Check the return value if ( r != 0 ) { fprintf(stderr, "failed to detach from kernel driver. Error Number: %i", r); return NULL; } } r = libusb_claim_interface(devh, 0); if (r < 0) { LJUSB_libusbError(r); libusb_close(devh); return NULL; } handle = (HANDLE) devh; #if LJ_DEBUG fprintf(stderr, "LJUSB_OpenDevice: Found handle for product ID %ld\n", ProductID); #endif break; } } } libusb_free_device_list(devs, 1); if (handle != NULL) { //We found a device, now check if it meets the minimum firmware requirement if (!LJUSB_isMinFirmware(handle, ProductID)) { //Does not meet the requirement. Close device and return an invalid handle. LJUSB_CloseDevice(handle); return NULL; } } #if LJ_DEBUG fprintf(stderr, "LJUSB_OpenDevice: Returning handle\n"); #endif return handle; } int LJUSB_OpenAllDevices(HANDLE* devHandles, UINT* productIds, UINT maxDevices) { libusb_device **devs = NULL, *dev = NULL; struct libusb_device_handle *devh = NULL; struct libusb_device_descriptor desc; ssize_t cnt = 0; int r = 1; unsigned int i = 0, ljFoundCount = 0; HANDLE handle = NULL; if (!gIsLibUSBInitialized) { r = libusb_init(&gLJContext); if (r < 0) { fprintf(stderr, "failed to initialize libusb\n"); LJUSB_libusbError(r); return -1; } gIsLibUSBInitialized = true; } cnt = libusb_get_device_list(gLJContext, &devs); if (cnt < 0) { fprintf(stderr, "failed to get device list\n"); LJUSB_libusbError(cnt); LJUSB_libusb_exit(); return -1; } while ((dev = devs[i++]) != NULL) { #if LJ_DEBUG fprintf(stderr, "LJUSB_OpenDevice: calling libusb_get_device_descriptor\n"); #endif r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { fprintf(stderr, "failed to get device descriptor"); LJUSB_libusbError(r); LJUSB_libusb_exit(); return -1; } if (LJ_VENDOR_ID == desc.idVendor) { // Found a LabJack device r = libusb_open(dev, &devh); if (r < 0) { LJUSB_libusbError(r); continue; } // Test if the kernel driver has the device. // Should only be true for HIDs. if (libusb_kernel_driver_active(devh, 0) ) { #if LJ_DEBUG fprintf(stderr, "Kernel Driver was active, detaching...\n"); #endif // Detaches U12s from kernel driver. r = libusb_detach_kernel_driver(devh, 0); // Check the return value if ( r != 0 ) { fprintf(stderr, "failed to detach from kernel driver. Error Number: %i", r); libusb_close(devh); continue; } } r = libusb_claim_interface(devh, 0); if (r < 0) { //LJUSB_libusbError(r); libusb_close(devh); continue; } handle = (HANDLE) devh; if (handle == NULL) { // Not a valid handle continue; } else if (ljFoundCount < maxDevices) { if (LJUSB_isMinFirmware(handle, desc.idProduct)) { devHandles[ljFoundCount] = handle; productIds[ljFoundCount] = desc.idProduct; ljFoundCount++; } else { // Not high enough firmware, keep moving. libusb_close(devh); ljFoundCount--; } } else { // Too many devices have been found. libusb_close(devh); break; } } } libusb_free_device_list(devs, 1); return ljFoundCount; } bool LJUSB_ResetConnection(HANDLE hDevice) { int r; if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_ResetConnection: returning false. hDevice is NULL.\n"); #endif return false; } r = libusb_reset_device(hDevice); if (r != 0) { LJUSB_libusbError(r); return false; } return true; //Success } static unsigned long LJUSB_DoTransfer(HANDLE hDevice, unsigned char endpoint, BYTE *pBuff, unsigned long count, unsigned int timeout, bool isBulk) { int r = 0; int transferred = 0; #if LJ_DEBUG fprintf(stderr, "Calling LJUSB_DoTransfer with endpoint = 0x%x, count = %lu, and isBulk = %d.\n", endpoint, count, isBulk); #endif if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_DoTransfer: returning 0. hDevice is NULL.\n"); #endif return 0; } if (isBulk && endpoint != 1 && endpoint < 0x81 ) { fprintf(stderr, "LJUSB_DoTransfer warning: Got endpoint = %d, however this not a known endpoint. Please verify you are using the header file provided in /usr/local/include/labjackusb.h and not an older header file.\n", endpoint); } if (isBulk) { r = libusb_bulk_transfer(hDevice, endpoint, pBuff, (int)count, &transferred, timeout); } else { if (endpoint == 0) { //HID feature request. r = libusb_control_transfer(hDevice, 0xa1 , 0x01, 0x0300, 0x0000, pBuff, count, timeout); if (r < 0) { LJUSB_libusbError(r); return 0; } #if LJ_DEBUG fprintf(stderr, "LJUSB_DoTransfer: returning control transferred = %d.\n", r); #endif return r; } else { r = libusb_interrupt_transfer(hDevice, endpoint, pBuff, count, &transferred, timeout); } } if (r == LIBUSB_ERROR_TIMEOUT) { //Timeout occured but may have received partial data. Setting errno but //returning the number of bytes transferred which may be > 0. #if LJ_DEBUG fprintf(stderr, "LJUSB_DoTransfer: Transfer timed out. Returning.\n"); #endif errno = ETIMEDOUT; return transferred; } else if (r != 0) { LJUSB_libusbError(r); return 0; } #if LJ_DEBUG fprintf(stderr, "LJUSB_DoTransfer: returning transferred = %d.\n", transferred); #endif return transferred; } // Automatically uses the correct endpoint and transfer method (bulk or interrupt) static unsigned long LJUSB_SetupTransfer(HANDLE hDevice, BYTE *pBuff, unsigned long count, unsigned int timeout, enum LJUSB_TRANSFER_OPERATION operation) { libusb_device *dev = NULL; struct libusb_device_descriptor desc; bool isBulk = true; unsigned char endpoint = 0; int r = 0; #if LJ_DEBUG fprintf(stderr, "Calling LJUSB_SetupTransfer with count = %lu and operation = %d.\n", count, operation); #endif if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_SetupTransfer: returning 0. hDevice is NULL.\n"); #endif return 0; } //First determine the device from handle. dev = libusb_get_device(hDevice); r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { LJUSB_libusbError(r); return 0; } switch (desc.idProduct) { /* These devices use bulk transfers */ case UE9_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = UE9_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = UE9_PIPE_EP1_IN; break; case LJUSB_STREAM: endpoint = UE9_PIPE_EP2_IN; break; default: errno = EINVAL; return 0; } break; case U3_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = U3_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = U3_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = U3_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case U6_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = U6_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = U6_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = U6_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case BRIDGE_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = BRIDGE_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = BRIDGE_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = BRIDGE_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case T7_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = T7_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = T7_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = T7_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case DIGIT_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = DIGIT_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = DIGIT_PIPE_EP2_IN; break; case LJUSB_STREAM: default: //No streaming interface errno = EINVAL; return 0; } break; /* These devices use interrupt transfers */ case U12_PRODUCT_ID: isBulk = false; switch (operation) { case LJUSB_READ: endpoint = U12_PIPE_EP1_IN; break; case LJUSB_WRITE: endpoint = U12_PIPE_EP2_OUT; break; case LJUSB_STREAM: endpoint = U12_PIPE_EP0; break; default: errno = EINVAL; return 0; } break; default: // Error, not a labjack device errno = EINVAL; return 0; } return LJUSB_DoTransfer(hDevice, endpoint, pBuff, count, timeout, isBulk); } // Deprecated: Kept for backwards compatibility unsigned long LJUSB_BulkRead(HANDLE hDevice, unsigned char endpoint, BYTE *pBuff, unsigned long count) { return LJUSB_DoTransfer(hDevice, endpoint, pBuff, count, LJ_LIBUSB_TIMEOUT_DEFAULT, true); } // Deprecated: Kept for backwards compatibility unsigned long LJUSB_BulkWrite(HANDLE hDevice, unsigned char endpoint, BYTE *pBuff, unsigned long count) { return LJUSB_DoTransfer(hDevice, endpoint, pBuff, count, LJ_LIBUSB_TIMEOUT_DEFAULT, true); } unsigned long LJUSB_Write(HANDLE hDevice, BYTE *pBuff, unsigned long count) { #if LJ_DEBUG fprintf(stderr, "LJUSB_Write: calling LJUSB_Write.\n"); #endif return LJUSB_SetupTransfer(hDevice, pBuff, count, LJ_LIBUSB_TIMEOUT_DEFAULT, LJUSB_WRITE); } unsigned long LJUSB_Read(HANDLE hDevice, BYTE *pBuff, unsigned long count) { #if LJ_DEBUG fprintf(stderr, "LJUSB_Read: calling LJUSB_Read.\n"); #endif return LJUSB_SetupTransfer(hDevice, pBuff, count, LJ_LIBUSB_TIMEOUT_DEFAULT, LJUSB_READ); } unsigned long LJUSB_Stream(HANDLE hDevice, BYTE *pBuff, unsigned long count) { #if LJ_DEBUG fprintf(stderr, "LJUSB_Stream: calling LJUSB_Stream.\n"); #endif return LJUSB_SetupTransfer(hDevice, pBuff, count, LJ_LIBUSB_TIMEOUT_DEFAULT, LJUSB_STREAM); } unsigned long LJUSB_WriteTO(HANDLE hDevice, BYTE *pBuff, unsigned long count, unsigned int timeout) { #if LJ_DEBUG fprintf(stderr, "LJUSB_Stream: calling LJUSB_WriteTO.\n"); #endif return LJUSB_SetupTransfer(hDevice, pBuff, count, timeout, LJUSB_WRITE); } unsigned long LJUSB_ReadTO(HANDLE hDevice, BYTE *pBuff, unsigned long count, unsigned int timeout) { #if LJ_DEBUG fprintf(stderr, "LJUSB_Stream: calling LJUSB_ReadTO.\n"); #endif return LJUSB_SetupTransfer(hDevice, pBuff, count, timeout, LJUSB_READ); } unsigned long LJUSB_StreamTO(HANDLE hDevice, BYTE *pBuff, unsigned long count, unsigned int timeout) { #if LJ_DEBUG fprintf(stderr, "LJUSB_Stream: calling LJUSB_StreamTO.\n"); #endif return LJUSB_SetupTransfer(hDevice, pBuff, count, timeout, LJUSB_STREAM); } void LJUSB_CloseDevice(HANDLE hDevice) { #if LJ_DEBUG fprintf(stderr, "LJUSB_CloseDevice\n"); #endif if (LJUSB_isNullHandle(hDevice)) { return; } //Release libusb_release_interface(hDevice, 0); //Close libusb_close(hDevice); #if LJ_DEBUG fprintf(stderr, "LJUSB_CloseDevice: closed\n"); #endif } unsigned int LJUSB_GetDevCount(unsigned long ProductID) { libusb_device **devs = NULL; ssize_t cnt = 0; int r = 1; unsigned int i = 0; unsigned int ljFoundCount = 0; if (!gIsLibUSBInitialized) { r = libusb_init(&gLJContext); if (r < 0) { fprintf(stderr, "failed to initialize libusb\n"); LJUSB_libusbError(r); return 0; } gIsLibUSBInitialized = true; } cnt = libusb_get_device_list(gLJContext, &devs); if (cnt < 0) { fprintf(stderr, "failed to get device list\n"); LJUSB_libusbError(cnt); LJUSB_libusb_exit(); return 0; } libusb_device *dev = NULL; // Loop over all USB devices and count the ones with the LabJack // vendor ID and the passed in product ID. while ((dev = devs[i++]) != NULL) { struct libusb_device_descriptor desc; r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { fprintf(stderr, "failed to get device descriptor\n"); LJUSB_libusbError(r); LJUSB_libusb_exit(); return 0; } if (LJ_VENDOR_ID == desc.idVendor && ProductID == desc.idProduct) { ljFoundCount++; } } libusb_free_device_list(devs, 1); return ljFoundCount; } unsigned int LJUSB_GetDevCounts(UINT *productCounts, UINT * productIds, UINT n) { libusb_device **devs = NULL, *dev = NULL; ssize_t cnt = 0; int r = 1; unsigned int i = 0; unsigned int u3ProductCount = 0, u6ProductCount = 0; unsigned int ue9ProductCount = 0, u12ProductCount = 0; unsigned int bridgeProductCount = 0, t7ProductCount = 0; unsigned int digitProductCount = 0, allProductCount = 0; if (!gIsLibUSBInitialized) { r = libusb_init(&gLJContext); if (r < 0) { fprintf(stderr, "failed to initialize libusb\n"); LJUSB_libusbError(r); return 0; } gIsLibUSBInitialized = true; } cnt = libusb_get_device_list(gLJContext, &devs); if (cnt < 0) { fprintf(stderr, "failed to get device list\n"); LJUSB_libusbError(cnt); LJUSB_libusb_exit(); return 0; } // Loop over all USB devices and count the ones with the LabJack // vendor ID and the passed in product ID. while ((dev = devs[i++]) != NULL) { struct libusb_device_descriptor desc; r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { fprintf(stderr, "failed to get device descriptor\n"); LJUSB_libusbError(r); LJUSB_libusb_exit(); return 0; } if (LJ_VENDOR_ID == desc.idVendor) { switch (desc.idProduct) { case U3_PRODUCT_ID: u3ProductCount++; break; case U6_PRODUCT_ID: u6ProductCount++; break; case UE9_PRODUCT_ID: ue9ProductCount++; break; case U12_PRODUCT_ID: u12ProductCount++; break; case BRIDGE_PRODUCT_ID: bridgeProductCount++; break; case T7_PRODUCT_ID: t7ProductCount++; break; case DIGIT_PRODUCT_ID: digitProductCount++; break; } } } libusb_free_device_list(devs, 1); for (i = 0; i < n; i++) { switch (i) { case 0: productCounts[i] = u3ProductCount; productIds[i] = U3_PRODUCT_ID; allProductCount += u3ProductCount; break; case 1: productCounts[i] = u6ProductCount; productIds[i] = U6_PRODUCT_ID; allProductCount += u6ProductCount; break; case 2: productCounts[i] = ue9ProductCount; productIds[i] = UE9_PRODUCT_ID; allProductCount += ue9ProductCount; break; case 3: productCounts[i] = u12ProductCount; productIds[i] = U12_PRODUCT_ID; allProductCount += u12ProductCount; break; case 4: productCounts[i] = bridgeProductCount; productIds[i] = BRIDGE_PRODUCT_ID; allProductCount += bridgeProductCount; break; case 5: productCounts[i] = t7ProductCount; productIds[i] = T7_PRODUCT_ID; allProductCount += t7ProductCount; break; case 6: productCounts[i] = digitProductCount; productIds[i] = DIGIT_PRODUCT_ID; allProductCount += digitProductCount; break; } } return allProductCount; } bool LJUSB_IsHandleValid(HANDLE hDevice) { uint8_t config = 0; int r = 1; if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_IsHandleValid: returning false. hDevice is NULL.\n"); #endif return false; } // If we can call get configuration without getting an error, // the handle is still valid. // Note that libusb_get_configuration() will return a cached value, // so we replace this call // r = libusb_get_configuration(hDevice, &config); // to the actual control tranfser, from the libusb source r = libusb_control_transfer(hDevice, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &config, 1, LJ_LIBUSB_TIMEOUT_DEFAULT); if (r < 0) { #if LJ_DEBUG fprintf(stderr, "LJUSB_IsHandleValid: returning false. Return value from libusb_get_configuration was: %d\n", r); #endif LJUSB_libusbError(r); return false; } else { #if LJ_DEBUG fprintf(stderr, "LJUSB_IsHandleValid: returning true.\n"); #endif return true; } } unsigned short LJUSB_GetDeviceDescriptorReleaseNumber(HANDLE hDevice) { libusb_device *dev = NULL; struct libusb_device_descriptor desc; int r = 0; if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_GetDeviceDescriptorReleaseNumber: returning 0. hDevice is NULL.\n"); #endif return 0; } dev = libusb_get_device(hDevice); r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { LJUSB_libusbError(r); return 0; } return desc.bcdDevice; } unsigned long LJUSB_GetHIDReportDescriptor(HANDLE hDevice, BYTE *pBuff, unsigned long count) { libusb_device *dev = NULL; struct libusb_device_descriptor desc; int r = 0; if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_GetHIDReportDescriptor: returning 0. hDevice is NULL.\n"); #endif return 0; } //Determine the device from handle. dev = libusb_get_device(hDevice); r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { LJUSB_libusbError(r); return 0; } if (desc.idProduct != U12_PRODUCT_ID) { //Only U12 supported errno = EINVAL; return 0; } r = libusb_control_transfer(hDevice, 0x81, 0x06, 0x2200, 0x0000, pBuff, count, LJ_LIBUSB_TIMEOUT_DEFAULT); if (r < 0) { LJUSB_libusbError(r); return 0; } #if LJ_DEBUG fprintf(stderr, "LJUSB_GetHIDReportDescriptor: returning control transferred = %d.\n", r); #endif return r; } //not supported bool LJUSB_AbortPipe(HANDLE hDevice, unsigned long Pipe) { (void)hDevice; (void)Pipe; errno = ENOSYS; return false; }
494
./exodriver/examples/U3/u3BasicConfigU3.c
/* An example that shows a minimal use of Exodriver without the use of functions hidden in header files. You can compile this example with the following command: $ g++ -lm -llabjackusb u3BasicConfigU3.c It is also included in the Makefile. */ /* Includes */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "labjackusb.h" // Defines how long the command is #define CONFIGU3_COMMAND_LENGTH 26 // Defines how long the response is #define CONFIGU3_RESPONSE_LENGTH 38 /* Buffer Helper Functions Protypes */ // Takes a buffer and an offset, and turns it into a 32-bit integer int makeInt(BYTE * buffer, int offset); // Takes a buffer and an offset, and turns it into a 16-bit integer int makeShort(BYTE * buffer, int offset); // Takes a buffer and calculates the checksum8 of it. BYTE calculateChecksum8(BYTE* buffer); // Takes a buffer and length, and calculates the checksum16 of the buffer. int calculateChecksum16(BYTE* buffer, int len); /* LabJack Related Helper Functions Protoypes */ // Demonstrates how to build the ConfigU3 packet. void buildConfigU3Bytes(BYTE * sendBuffer); // Demonstrates how to check a response for errors. int checkResponseForErrors(BYTE * recBuffer); // Demonstrates how to parse the response of ConfigU3. void parseConfigU3Bytes(BYTE * recBuffer); int main() { // Setup the variables we will need. int r = 0; // For checking return values HANDLE devHandle = 0; BYTE sendBuffer[CONFIGU3_COMMAND_LENGTH], recBuffer[CONFIGU3_RESPONSE_LENGTH]; // Open the U3 devHandle = LJUSB_OpenDevice(1, 0, U3_PRODUCT_ID); if( devHandle == NULL ) { printf("Couldn't open U3. Please connect one and try again.\n"); exit(-1); } // Builds the ConfigU3 command buildConfigU3Bytes(sendBuffer); // Write the command to the device. // LJUSB_Write( handle, sendBuffer, length of sendBuffer ) r = LJUSB_Write( devHandle, sendBuffer, CONFIGU3_COMMAND_LENGTH ); if( r != CONFIGU3_COMMAND_LENGTH ) { printf("An error occurred when trying to write the buffer. The error was: %d\n", errno); // *Always* close the device when you error out. LJUSB_CloseDevice(devHandle); exit(-1); } // Read the result from the device. // LJUSB_Read( handle, recBuffer, number of bytes to read) r = LJUSB_Read( devHandle, recBuffer, CONFIGU3_RESPONSE_LENGTH ); if( r != CONFIGU3_RESPONSE_LENGTH ) { printf("An error occurred when trying to read from the U3. The error was: %d\n", errno); LJUSB_CloseDevice(devHandle); exit(-1); } // Check the command for errors if( checkResponseForErrors(recBuffer) != 0 ){ LJUSB_CloseDevice(devHandle); exit(-1); } // Parse the response into something useful parseConfigU3Bytes(recBuffer); //Close the device. LJUSB_CloseDevice(devHandle); return 0; } /* ------------- LabJack Related Helper Functions Definitions ------------- */ // Uses information from section 5.2.2 of the U3 User's Guide to make a ConfigU3 // packet. // http://labjack.com/support/u3/users-guide/5.2.2 void buildConfigU3Bytes(BYTE * sendBuffer) { int i; // For loops int checksum = 0; // Build up the bytes //sendBuffer[0] = Checksum8 sendBuffer[1] = 0xF8; sendBuffer[2] = 0x0A; sendBuffer[3] = 0x08; //sendBuffer[4] = Checksum16 (LSB) //sendBuffer[5] = Checksum16 (MSB) // We just want to read, so we set the WriteMask to zero, and zero out the // rest of the bytes. sendBuffer[6] = 0; for( i = 7; i < CONFIGU3_COMMAND_LENGTH; i++){ sendBuffer[i] = 0; } // Calculate and set the checksum16 checksum = calculateChecksum16(sendBuffer, CONFIGU3_COMMAND_LENGTH); sendBuffer[4] = (BYTE)( checksum & 0xff ); sendBuffer[5] = (BYTE)( (checksum / 256) & 0xff ); // Calculate and set the checksum8 sendBuffer[0] = calculateChecksum8(sendBuffer); // The bytes have been set, and the checksum calculated. We are ready to // write to the U3. } // Checks the response for any errors. int checkResponseForErrors(BYTE * recBuffer) { if(recBuffer[0] == 0xB8 && recBuffer[1] == 0xB8) { // If the packet is [ 0xB8, 0xB8 ], that's a bad checksum. printf("The U3 detected a bad checksum. Double check your checksum calculations and try again.\n"); return -1; } else if (recBuffer[1] == 0xF8 && recBuffer[2] == 0x10 && recBuffer[2] == 0x08) { // Make sure the command bytes match what we expect. printf("Got the wrong command bytes back from the U3.\n"); return -1; } // Calculate the checksums. int checksum16 = calculateChecksum16(recBuffer, CONFIGU3_RESPONSE_LENGTH); BYTE checksum8 = calculateChecksum8(recBuffer); if ( checksum8 != recBuffer[0] || recBuffer[4] != (BYTE)( checksum16 & 0xff ) || recBuffer[5] != (BYTE)( (checksum16 / 256) & 0xff ) ) { // Check the checksum printf("Response had invalid checksum.\n%d != %d, %d != %d, %d != %d\n", checksum8, recBuffer[0], (BYTE)( checksum16 & 0xff ), recBuffer[4], (BYTE)( (checksum16 / 256) & 0xff ), recBuffer[5] ); return -1; } else if ( recBuffer[6] != 0 ) { // Check the error code in the packet. See section 5.3 of the U3 // User's Guide for errorcode descriptions. printf("Command returned with an errorcode = %d\n", recBuffer[6]); return -1; } return 0; } // Parses the ConfigU3 packet into something useful. void parseConfigU3Bytes(BYTE * recBuffer){ printf("Results of ConfigU3:\n"); printf(" FirmwareVersion = %d.%02d\n", recBuffer[10], recBuffer[9]); printf(" BootloaderVersion = %d.%02d\n", recBuffer[12], recBuffer[11]); printf(" HardwareVersion = %d.%02d\n", recBuffer[14], recBuffer[13]); printf(" SerialNumber = %d\n", makeInt(recBuffer, 15)); printf(" ProductID = %d\n", makeShort(recBuffer, 19)); printf(" LocalID = %d\n", recBuffer[21]); printf(" TimerCounterMask = %d\n", recBuffer[22]); printf(" FIOAnalog = %d\n", recBuffer[23]); printf(" FIODireciton = %d\n", recBuffer[24]); printf(" FIOState = %d\n", recBuffer[25]); printf(" EIOAnalog = %d\n", recBuffer[26]); printf(" EIODirection = %d\n", recBuffer[27]); printf(" EIOState = %d\n", recBuffer[28]); printf(" CIODirection = %d\n", recBuffer[29]); printf(" CIOState = %d\n", recBuffer[30]); printf(" DAC1Enable = %d\n", recBuffer[31]); printf(" DAC0 = %d\n", recBuffer[32]); printf(" DAC1 = %d\n", recBuffer[33]); printf(" TimerClockConfig = %d\n", recBuffer[34]); printf(" TimerClockDivisor = %d\n", recBuffer[35]); printf(" CompatibilityOptions = %d\n", recBuffer[36]); printf(" VersionInfo = %d\n", recBuffer[37]); if( recBuffer[37] == 0 ){ printf(" DeviceName = U3A\n"); } else if(recBuffer[37] == 1) { printf(" DeviceName = U3B\n"); } else if(recBuffer[37] == 2) { printf(" DeviceName = U3-LV\n"); } else if(recBuffer[37] == 18) { printf(" DeviceName = U3-HV\n"); } } /* ---------------- Buffer Helper Functions Definitions ---------------- */ // Takes a buffer and an offset, and turns into an 32-bit integer int makeInt(BYTE * buffer, int offset){ return (buffer[offset+3] << 24) + (buffer[offset+2] << 16) + (buffer[offset+1] << 8) + buffer[offset]; } // Takes a buffer and an offset, and turns into an 16-bit integer int makeShort(BYTE * buffer, int offset) { return (buffer[offset+1] << 8) + buffer[offset]; } // Calculates the checksum8 BYTE calculateChecksum8(BYTE* buffer){ int i; // For loops int temp; // For holding a value while we working. int checksum = 0; for( i = 1; i < 6; i++){ checksum += buffer[i]; } temp = checksum/256; checksum = ( checksum - 256 * temp ) + temp; temp = checksum/256; return (BYTE)( ( checksum - 256 * temp ) + temp ); } // Calculates the checksum16 int calculateChecksum16(BYTE* buffer, int len){ int i; int checksum = 0; for( i = 6; i < len; i++){ checksum += buffer[i]; } return checksum; }
495
./exodriver/examples/U3/u3Stream.c
//Author: LabJack //December 27, 2011 //This example program reads analog inputs AI0-AI4 using stream mode. Requires //a U3 with hardware version 1.21 or higher. #include "u3.h" int ConfigIO_example(HANDLE hDevice, int *isDAC1Enabled); int StreamConfig_example(HANDLE hDevice); int StreamStart(HANDLE hDevice); int StreamData_example(HANDLE hDevice, u3CalibrationInfo *caliInfo, int isDAC1Enabled); int StreamStop(HANDLE hDevice); const uint8 NumChannels = 5; //For this example to work proper, //SamplesPerPacket needs to be a multiple of //NumChannels. const uint8 SamplesPerPacket = 25; //Needs to be 25 to read multiple StreamData //responses in one large packet, otherwise //can be any value between 1-25 for 1 //StreamData response per packet. int main(int argc, char **argv) { HANDLE hDevice; u3CalibrationInfo caliInfo; int dac1Enabled; //Opening first found U3 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from U3 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; if( ConfigIO_example(hDevice, &dac1Enabled) != 0 ) goto close; //Stopping any previous streams StreamStop(hDevice); if( StreamConfig_example(hDevice) != 0 ) goto close; if( StreamStart(hDevice) != 0 ) goto close; StreamData_example(hDevice, &caliInfo, dac1Enabled); StreamStop(hDevice); close: closeUSBConnection(hDevice); done: return 0; } //Sends a ConfigIO low-level command that configures the FIOs, DAC, Timers and //Counters for this example int ConfigIO_example(HANDLE hDevice, int *isDAC1Enabled) { uint8 sendBuff[12], recBuff[12]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 13; //Writemask : Setting writemask for timerCounterConfig (bit 0), // FIOAnalog (bit 2) and EIOAnalog (bit 3) sendBuff[7] = 0; //Reserved sendBuff[8] = 64; //TimerCounterConfig: Disabling all timers and counters, // set TimerCounterPinOffset to 4 (bits 4-7) sendBuff[9] = 0; //DAC1Enable sendBuff[10] = 255; //FIOAnalog : setting all FIOs as analog inputs sendBuff[11] = 255; //EIOAnalog : setting all EIOs as analog inputs extendedChecksum(sendBuff, 12); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 12)) < 12 ) { if( sendChars == 0 ) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 12)) < 12 ) { if( recChars == 0 ) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 12); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x03) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } if( recBuff[8] != 64 ) { printf("ConfigIO error : TimerCounterConfig did not get set correctly\n"); return -1; } if( recBuff[10] != 255 && recBuff[10] != (uint8)(0x0F) ) { printf("ConfigIO error : FIOAnalog did not set get correctly\n"); return -1; } if( recBuff[11] != 255 ) { printf("ConfigIO error : EIOAnalog did not set get correctly (%d)\n", recBuff[11]); return -1; } *isDAC1Enabled = (int)recBuff[9]; return 0; } //Sends a StreamConfig low-level command to configure the stream. int StreamConfig_example(HANDLE hDevice) { uint8 sendBuff[64], recBuff[8]; uint16 checksumTotal, scanInterval; int sendBuffSize, sendChars, recChars, i; sendBuffSize = 12+NumChannels*2; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 3 + NumChannels; //Number of data words = NumChannels + 3 sendBuff[3] = (uint8)(0x11); //Extended command number sendBuff[6] = NumChannels; //NumChannels sendBuff[7] = SamplesPerPacket; //SamplesPerPacket sendBuff[8] = 0; //Reserved sendBuff[9] = 1; //ScanConfig: // Bit 7: Reserved // Bit 6: Reserved // Bit 3: Internal stream clock frequency = b0: 4 MHz // Bit 2: Divide Clock by 256 = b0 // Bits 0-1: Resolution = b01: 11.9-bit effective scanInterval = 4000; sendBuff[10] = (uint8)(scanInterval & (0x00FF)); //Scan interval (low byte) sendBuff[11] = (uint8)(scanInterval / 256); //Scan interval (high byte) for( i = 0; i < NumChannels; i++ ) { sendBuff[12 + i*2] = i; //PChannel = i sendBuff[13 + i*2] = 31; //NChannel = 31: Single Ended } extendedChecksum(sendBuff, sendBuffSize); //Sending command to U3 sendChars = LJUSB_Write(hDevice, sendBuff, sendBuffSize); if( sendChars < sendBuffSize ) { if( sendChars == 0 ) printf("Error : write failed (StreamConfig).\n"); else printf("Error : did not write all of the buffer (StreamConfig).\n"); return -1; } for( i = 0; i < 8; i++ ) recBuff[i] = 0; //Reading response from U3 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) printf("Error : read failed (StreamConfig).\n"); else printf("Error : did not read all of the buffer, %d (StreamConfig).\n", recChars); for( i = 0; i < 8; i++ ) printf("%d ", recBuff[i]); return -1; } checksumTotal = extendedChecksum16(recBuff, 8); if( (uint8)((checksumTotal / 256) & 0xFF) != recBuff[5] ) { printf("Error : read buffer has bad checksum16(MSB) (StreamConfig).\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Error : read buffer has bad checksum16(LBS) (StreamConfig).\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamConfig).\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x01) || recBuff[3] != (uint8)(0x11) || recBuff[7] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes (StreamConfig).\n"); return -1; } if( recBuff[6] != 0 ) { printf("Errorcode # %d from StreamConfig read.\n", (unsigned int)recBuff[6]); return -1; } return 0; } //Sends a StreamStart low-level command to start streaming. int StreamStart(HANDLE hDevice) { uint8 sendBuff[2], recBuff[4]; int sendChars, recChars; sendBuff[0] = (uint8)(0xA8); //CheckSum8 sendBuff[1] = (uint8)(0xA8); //command byte //Sending command to U3 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed.\n"); else printf("Error : did not write all of the buffer.\n"); return -1; } //Reading response from U3 recChars = LJUSB_Read(hDevice, recBuff, 4); if( recChars < 4 ) { if( recChars == 0 ) printf("Error : read failed.\n"); else printf("Error : did not read all of the buffer.\n"); return -1; } if( normalChecksum8(recBuff, 4) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamStart).\n"); return -1; } if( recBuff[1] != (uint8)(0xA9) || recBuff[3] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[2] != 0 ) { printf("Errorcode # %d from StreamStart read.\n", (unsigned int)recBuff[2]); return -1; } return 0; } //Reads the StreamData low-level function response in a loop. All voltages from //the stream are stored in the voltages 2D array. int StreamData_example(HANDLE hDevice, u3CalibrationInfo *caliInfo, int isDAC1Enabled) { uint16 voltageBytes, checksumTotal; long startTime, endTime; double hardwareVersion; int recBuffSize, recChars, backLog, autoRecoveryOn; int packetCounter, currChannel, scanNumber; int i, j, k, m; int totalPackets; //The total number of StreamData responses read int numDisplay; //Number of times to display streaming information int numReadsPerDisplay; //Number of packets to read before displaying //streaming information int readSizeMultiplier; //Multiplier for the StreamData receive buffer size int responseSize; //The number of bytes in a StreamData response //(differs with SamplesPerPacket) numDisplay = 6; numReadsPerDisplay = 24; readSizeMultiplier = 5; responseSize = 14 + SamplesPerPacket*2; /* Each StreamData response contains (SamplesPerPacket / NumChannels) * readSizeMultiplier * samples for each channel. * Total number of scans = (SamplesPerPacket / NumChannels) * readSizeMultiplier * numReadsPerDisplay * numDisplay */ double voltages[(SamplesPerPacket/NumChannels)*readSizeMultiplier*numReadsPerDisplay*numDisplay][NumChannels]; uint8 recBuff[responseSize*readSizeMultiplier]; packetCounter = 0; currChannel = 0; scanNumber = 0; totalPackets = 0; recChars = 0; autoRecoveryOn = 0; recBuffSize = 14 + SamplesPerPacket*2; hardwareVersion = caliInfo->hardwareVersion; printf("Reading Samples...\n"); startTime = getTickCount(); for( i = 0; i < numDisplay; i++ ) { for( j = 0; j < numReadsPerDisplay; j++ ) { /* For USB StreamData, use Endpoint 3 for reads. You can read the * multiple StreamData responses of 64 bytes only if * SamplesPerPacket is 25 to help improve streaming performance. In * this example this multiple is adjusted by the readSizeMultiplier * variable. */ //Reading stream response from U3 recChars = LJUSB_Stream(hDevice, recBuff, responseSize*readSizeMultiplier); if( recChars < responseSize*readSizeMultiplier ) { if( recChars == 0 ) printf("Error : read failed (StreamData).\n"); else printf("Error : did not read all of the buffer, expected %d bytes but received %d(StreamData).\n", responseSize*readSizeMultiplier, recChars); return -1; } //Checking for errors and getting data out of each StreamData //response for( m = 0; m < readSizeMultiplier; m++ ) { totalPackets++; checksumTotal = extendedChecksum16(recBuff + m*recBuffSize, recBuffSize); if( (uint8)((checksumTotal / 256) & 0xFF) != recBuff[m*recBuffSize + 5] ) { printf("Error : read buffer has bad checksum16(MSB) (StreamData).\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[m*recBuffSize + 4] ) { printf("Error : read buffer has bad checksum16(LBS) (StreamData).\n"); return -1; } checksumTotal = extendedChecksum8(recBuff + m*recBuffSize); if( checksumTotal != recBuff[m*recBuffSize] ) { printf("Error : read buffer has bad checksum8 (StreamData).\n"); return -1; } if( recBuff[m*recBuffSize + 1] != (uint8)(0xF9) || recBuff[m*recBuffSize + 2] != 4 + SamplesPerPacket || recBuff[m*recBuffSize + 3] != (uint8)(0xC0) ) { printf("Error : read buffer has wrong command bytes (StreamData).\n"); return -1; } if( recBuff[m*recBuffSize + 11] == 59 ) { if( !autoRecoveryOn ) { printf("\nU3 data buffer overflow detected in packet %d.\nNow using auto-recovery and reading buffered samples.\n", totalPackets); autoRecoveryOn = 1; } } else if( recBuff[m*recBuffSize + 11] == 60 ) { printf("Auto-recovery report in packet %d: %d scans were dropped.\nAuto-recovery is now off.\n", totalPackets, recBuff[m*recBuffSize + 6] + recBuff[m*recBuffSize + 7]*256); autoRecoveryOn = 0; } else if( recBuff[m*recBuffSize + 11] != 0 ) { printf("Errorcode # %d from StreamData read.\n", (unsigned int)recBuff[11]); return -1; } if( packetCounter != (int)recBuff[m*recBuffSize + 10] ) { printf("PacketCounter (%d) does not match with with current packet count (%d)(StreamData).\n", recBuff[m*recBuffSize + 10], packetCounter); return -1; } backLog = (int)recBuff[m*48 + 12 + SamplesPerPacket*2]; for( k = 12; k < (12 + SamplesPerPacket*2); k += 2 ) { voltageBytes = (uint16)recBuff[m*recBuffSize + k] + (uint16)recBuff[m*recBuffSize + k+1]*256; if( hardwareVersion >= 1.30 ) getAinVoltCalibrated_hw130(caliInfo, currChannel, 31, voltageBytes, &(voltages[scanNumber][currChannel])); else getAinVoltCalibrated(caliInfo, isDAC1Enabled, 31, voltageBytes, &(voltages[scanNumber][currChannel])); currChannel++; if( currChannel >= NumChannels ) { currChannel = 0; scanNumber++; } } if( packetCounter >= 255 ) packetCounter = 0; else packetCounter++; } } printf("\nNumber of scans: %d\n", scanNumber); printf("Total packets read: %d\n", totalPackets); printf("Current PacketCounter: %d\n", ((packetCounter == 0) ? 255 : packetCounter-1)); printf("Current BackLog: %d\n", backLog); for( k = 0; k < NumChannels; k++ ) printf(" AI%d: %.4f V\n", k, voltages[scanNumber - 1][k]); } endTime = getTickCount(); printf("\nRate of samples: %.0lf samples per second\n", ((scanNumber*NumChannels) / ((endTime-startTime) / 1000.0))); printf("Rate of scans: %.0lf scans per second\n\n", (scanNumber / ((endTime - startTime) / 1000.0))); return 0; } //Sends a StreamStop low-level command to stop streaming. int StreamStop(HANDLE hDevice) { uint8 sendBuff[2], recBuff[4]; int sendChars, recChars; sendBuff[0] = (uint8)(0xB0); //CheckSum8 sendBuff[1] = (uint8)(0xB0); //Command byte //Sending command to U3 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed (StreamStop).\n"); else printf("Error : did not write all of the buffer (StreamStop).\n"); return -1; } //Reading response from U3 recChars = LJUSB_Read(hDevice, recBuff, 4); if( recChars < 4 ) { if( recChars == 0 ) printf("Error : read failed (StreamStop).\n"); else printf("Error : did not read all of the buffer (StreamStop).\n"); return -1; } if( normalChecksum8(recBuff, 4) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamStop).\n"); return -1; } if( recBuff[1] != (uint8)(0xB1) || recBuff[3] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes (StreamStop).\n"); return -1; } if( recBuff[2] != 0 ) { printf("Errorcode # %d from StreamStop read.\n", (unsigned int)recBuff[2]); return -1; } return 0; }
496
./exodriver/examples/U3/u3allio.c
//Author : LabJack //December 27, 2011 //This example demonstrates how to write and read some or all analog and digital //I/O. It records the time for 1000 iterations and divides by 1000, to allow //measurement of the basic command/response communication times. These times //should be comparable to the Windows command/response communication times //documented in Section 3.1 of the U3 User's Guide. #include <stdlib.h> #include "u3.h" const uint8 numChannels = 8; //Number of AIN channels, 0-16. const uint8 quickSample = 1; //Set to TRUE for quick AIN sampling. const uint8 longSettling = 0; //Set to TRUE for extra AIN settling time. int configAllIO(HANDLE hDevice, int *isDAC1Enabled); int allIO(HANDLE hDevice, u3CalibrationInfo *caliInfo, int isDAC1Enabled); int main(int argc, char **argv) { HANDLE hDevice; u3CalibrationInfo caliInfo; int dac1Enabled; //Opening first found U3 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from U3 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; if( configAllIO(hDevice, &dac1Enabled) < 0 ) goto close;; allIO(hDevice, &caliInfo, dac1Enabled); close: closeUSBConnection(hDevice); done: return 0; } //Sends a ConfigIO low-level command that will set desired lines as analog, and //all else as digital. int configAllIO(HANDLE hDevice, int *isDAC1Enabled) { uint8 sendBuff[12], recBuff[12]; uint16 checksumTotal, FIOEIOAnalog; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 13; //Writemask : Setting writemask for TimerCounterConfig (bit 0), // FIOAnalog (bit 2) and EIOAnalog (bit 3) sendBuff[7] = 0; //Reserved sendBuff[8] = 64; //TimerCounterConfig: disable timer and counter, set // TimerCounterPinOffset to 4 (bits 4-7) sendBuff[9] = 0; //DAC1 enable : not enabling, though could already be enabled sendBuff[10] = 0; FIOEIOAnalog = pow(2.0, numChannels)-1; sendBuff[10] = (FIOEIOAnalog & 0xFF); //FIOAnalog sendBuff[11] = FIOEIOAnalog / 256; //EIOAnalog extendedChecksum(sendBuff, 12); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 12)) < 12 ) { if( sendChars == 0 ) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 12)) < 12 ) { if( recChars == 0 ) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 12); if( (uint8)((checksumTotal / 256) & 0xFF) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x03) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } if( recBuff[10] != (FIOEIOAnalog&(0xFF)) && recBuff[10] != ((FIOEIOAnalog&(0xFF))|(0x0F)) ) { printf("ConfigIO error : FIOAnalog did not set correctly"); return -1; } if( recBuff[11] != FIOEIOAnalog/256 ) { printf("ConfigIO error : EIOAnalog did not set correctly"); return -1; } *isDAC1Enabled = (int)recBuff[9]; return 0; } //Calls a Feedback low-level command 1000 times. int allIO(HANDLE hDevice, u3CalibrationInfo *caliInfo, int isDAC1Enabled) { uint8 *sendBuff, *recBuff; uint16 checksumTotal, ainBytes; int sendChars, recChars, sendSize, recSize; int valueDIPort, ret, i, j; double valueAIN[16]; long time, numIterations; double hardwareVersion; hardwareVersion = caliInfo->hardwareVersion; for( i = 0; i < 16; i++ ) valueAIN[i] = 9999; valueDIPort = 0; numIterations = 1000; //Number of iterations (how many times Feedback will //be called) //Setting up a Feedback command that will set CIO0-3 as input sendBuff = (uint8 *)malloc(14*sizeof(uint8)); //Creating an array of size 14 recBuff = (uint8 *)malloc(10*sizeof(uint8)); //Creating an array of size 10 sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 4; //Number of data words (.5 word for echo, 3.5 words for // IOTypes and data) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 29; //IOType is PortDirWrite sendBuff[8] = 0; //Writemask (for FIO) sendBuff[9] = 0; //Writemask (for EIO) sendBuff[10] = 15; //Writemask (for CIO) sendBuff[11] = 0; //Direction (for FIO) sendBuff[12] = 0; //Direction (for EIO) sendBuff[13] = 0; //Direction (for CIO) extendedChecksum(sendBuff, 14); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 14)) < 14 ) { if( sendChars == 0 ) printf("Feedback (CIO input) error : write failed\n"); else printf("Feedback (CIO input) error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 10)) < 10 ) { if( recChars == 0 ) { printf("Feedback (CIO input) error : read failed\n"); ret = -1; goto cleanmem; } else printf("Feedback (CIO input) error : did not read all of the buffer\n"); } checksumTotal = extendedChecksum16(recBuff, 10); if( (uint8)((checksumTotal / 256) & 0xFF) != recBuff[5] ) { printf("Feedback (CIO input) error : read buffer has bad checksum16(MSB)\n"); ret = -1; goto cleanmem; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Feedback (CIO input) error : read buffer has bad checksum16(LBS)\n"); ret = -1; goto cleanmem; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback (CIO input) error : read buffer has bad checksum8\n"); ret = -1; goto cleanmem; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback (CIO input) error : read buffer has wrong command bytes \n"); ret = -1; goto cleanmem; } if( recBuff[6] != 0 ) { printf("Feedback (CIO input) error : received errorcode %d for frame %d in Feedback response. \n", recBuff[6], recBuff[7]); ret = -1; goto cleanmem; } free(sendBuff); free(recBuff); //Setting up Feedback command that will run 1000 times if( ((sendSize = 7+2+1+numChannels*3) % 2) != 0 ) sendSize++; //Creating an array of size sendSize sendBuff = (uint8 *)malloc(sendSize*sizeof(uint8)); if( ((recSize = 9+3+numChannels*2) % 2) != 0 ) recSize++; //Creating an array of size recSize recBuff = (uint8 *)malloc(recSize*sizeof(uint8)); sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (sendSize - 6)/2; //Number of data words sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo //Setting DAC0 with 2.5 volt output sendBuff[7] = 34; //IOType is DAC0 //Value is 2.5 volts (in binary) getDacBinVoltCalibrated(caliInfo, 0, 2.5, &sendBuff[8]); sendBuff[9] = 26; //IOType is PortStateRead //Setting AIN read commands for( j = 0; j < numChannels; j++ ) { sendBuff[10 + j*3] = 1; //IOType is AIN //Positive Channel (bits 0 - 4), LongSettling (bit 6) and QuickSample (bit 7) sendBuff[11 + j*3] = j + (longSettling&(0x01))*64 + (quickSample&(0x01))*128; sendBuff[12 + j*3] = 31; //Negative Channel is single-ended } if( (sendSize % 2) != 0 ) sendBuff[sendSize - 1] = 0; extendedChecksum(sendBuff, sendSize); time = getTickCount(); for( i = 0; i < numIterations; i++ ) { //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, sendSize)) < sendSize ) { if( sendChars == 0 ) printf("Feedback error (Iteration %d): write failed\n", i); else printf("Feedback error (Iteration %d): did not write all of the buffer\n", i); ret = -1; goto cleanmem; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, recSize)) < recSize ) { if( recChars == 0 ) { printf("Feedback error (Iteration %d): read failed\n", i); ret = -1; goto cleanmem; } else printf("Feedback error (Iteration %d): did not read all of the expected buffer\n", i); } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256) & 0xFF) != recBuff[5] ) { printf("Feedback error (Iteration %d): read buffer has bad checksum16(MSB)\n", i); ret = -1; goto cleanmem; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Feedback error (Iteration %d): read buffer has bad checksum16(LBS)\n", i); ret = -1; goto cleanmem; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback error (Iteration %d): read buffer has bad checksum8\n", i); ret = -1; goto cleanmem; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback error (Iteration %d): read buffer has wrong command bytes \n", i); ret = -1; goto cleanmem; } if( recBuff[6] != 0 ) { printf("Feedback error (Iteration %d): received errorcode %d for frame %d in Feedback response. \n", i, recBuff[6], recBuff[7]); ret = -1; goto cleanmem; } if( recChars != recSize ) { ret = -1; goto cleanmem; } //Getting CIO digital states valueDIPort = recBuff[11]; //Getting AIN voltages for( j = 0; j < numChannels; j++ ) { ainBytes = recBuff[12+j*2] + recBuff[13+j*2]*256; if( hardwareVersion >= 1.30 ) getAinVoltCalibrated_hw130(caliInfo, j, 31, ainBytes, &valueAIN[j]); else getAinVoltCalibrated(caliInfo, isDAC1Enabled, 31, ainBytes, &valueAIN[j]); } } time = getTickCount() - time; printf("Milliseconds per iteration = %.3f\n", (double)time / (double)numIterations); printf("\nDigital Input = %d\n", valueDIPort); printf("\nAIN readings from last iteration:\n"); for( j = 0; j < numChannels; j++ ) printf("%.3f\n", valueAIN[j]); cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; }
497
./exodriver/examples/U3/u3Feedback.c
//Author : LabJack //December 27, 2011 //For U3s with hardware versions 1.20, 1.21 and 1.30 LV, this example will //set FIO0 and FIO1 to analog input, FIO2 to digital output set to low, and //FIO3 to digital input. FIO4 and FIO5 will be set as timers 0 and 1 with //timer modes PMW8 and PMW16. FIO6 will be set as counter 1. Also, DAC0 will //be set to 1.5 volts and the temperature will be read. //For U3s with hardware version 1.30 HV, this example will read AIN0-AIN4 and //set FIO7 to digital input. FIO4 and FIO5 will be set as timers 0 and 1 with //timer modes PMW8 and PMW16. FIO6 will be set as counter 1. Also, DAC0 will //be set to 3.5 volts and the temperature will be read. #include <unistd.h> #include <termios.h> #include "u3.h" static struct termios termNew, termOrig; static int peek = -1; int configIO_example(HANDLE hDevice, int enable, int *isDAC1Enabled); int configTimerClock_example(HANDLE hDevice); int feedback_setup_example(HANDLE hDevice, u3CalibrationInfo *caliInfo); int feedback_setup_HV_example(HANDLE hDevice, u3CalibrationInfo *caliInfo); int feedback_loop_example(HANDLE hDevice, u3CalibrationInfo *caliInfo, int isDAC1Enabled); int feedback_loop_HV_example(HANDLE hDevice, u3CalibrationInfo *caliInfo); void setTerm(); int kbhit(); void unsetTerm(); int main(int argc, char **argv) { HANDLE hDevice; u3CalibrationInfo caliInfo; int dac1Enabled; //setting terminal settings setTerm(); //Opening first found U3 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from U3 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; if( configIO_example(hDevice, 1, &dac1Enabled) != 0 ) goto close; if( configTimerClock_example(hDevice) != 0 ) goto close; if( caliInfo.hardwareVersion >= 1.30 && caliInfo.highVoltage == 1 ) { if( feedback_setup_HV_example(hDevice, &caliInfo) != 0 ) goto close; if( feedback_loop_HV_example(hDevice, &caliInfo) != 0 ) goto close; } else { if( feedback_setup_example(hDevice, &caliInfo) != 0 ) goto close; if( feedback_loop_example(hDevice, &caliInfo, dac1Enabled) != 0 ) goto close; } configIO_example(hDevice, 0, &dac1Enabled); close: closeUSBConnection(hDevice); done: printf("\nDone\n"); //Setting terminal settings to previous settings unsetTerm(); return 0; } //Sends a ConfigIO low-level command that configures the FIOs, DAC, Timers and //Counters for this example. int configIO_example(HANDLE hDevice, int enable, int *isDAC1Enabled) { uint8 sendBuff[12], recBuff[12]; uint8 timerCounterConfig, fioAnalog; uint16 checksumTotal; int sendChars, recChars; if( enable == 0 ) { timerCounterConfig = 64; //Disabling timers (bits 0 and 1) and Counters //(bits 2 and 3), setting TimerCounterPinOffset //to 4 (bits 4-7) fioAnalog = 255; //Setting all FIOs to analog } else { timerCounterConfig = 74; //Enabling 2 timers (bits 0 and 1), Counter 1 (bit 3) //and setting TimerCounterPinOffset (bits 4-7) to //4. Note that Counter 0 will not be available //since the timer clock will use a divisor in this //example. Also, for hardware version 1.30, HV //models need to have a TimerCounterPinOffset of 4-8, //otherwise an error will occur since FIO0-FIO3 can only //be analog inputs. fioAnalog = 3; //Setting FIO0 (bit 0) and FIO1 (bit 1) to analog input. Note that //hardware version 1.30, U3-HV models will always have FIO0-4 set as //analog inputs, and will ignore setting chages. In this case, FIO2 //and FIO3 will ignore the the digital setting and still be analog //inputs. } sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 5; //Writemask : Setting writemask for timerCounterConfig (bit 0) //and FIOAnalog (bit 2) sendBuff[7] = 0; //Reserved sendBuff[8] = timerCounterConfig; //TimerCounterConfig sendBuff[9] = 0; //DAC1 enable : not enabling, though could already be enabled. //If U3 hardware version 1.30, DAC1 is always enabled. sendBuff[10] = fioAnalog; //FIOAnalog sendBuff[11] = 0; //EIOAnalog : Not setting anything extendedChecksum(sendBuff, 12); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 12)) < 12 ) { if( sendChars == 0 ) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 12)) < 12 ) { if( recChars == 0 ) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 12); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x03) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } if( recBuff[8] != timerCounterConfig ) { printf("ConfigIO error : TimerCounterConfig did not get set correctly\n"); return -1; } if( recBuff[10] != fioAnalog && recBuff[10] != (fioAnalog|(0x0F)) ) { printf("ConfigIO error : FIOAnalog(%d) did not set correctly\n", recBuff[10]); return -1; } *isDAC1Enabled = (int)recBuff[9]; return 0; } //Sends a ConfigTimerClock low-level command that configures the timer clock //for this example. int configTimerClock_example(HANDLE hDevice) { uint8 sendBuff[10], recBuff[10]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x02); //Number of data words sendBuff[3] = (uint8)(0x0A); //Extended command number sendBuff[6] = 0; //Reserved sendBuff[7] = 0; //Reserved sendBuff[8] = 134; //TimerClockConfig : Configuring the clock (bit 7) and //setting the TimerClockBase (bits 0-2) to //24MHz/TimerClockDivisor sendBuff[9] = 2; //TimerClockDivisor : Setting to 2, so the actual timer //clock is 12 MHz extendedChecksum(sendBuff, 10); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 10)) < 10 ) { if( sendChars == 0 ) printf("ConfigTimerClock error : write failed\n"); else printf("ConfigTimerClock error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 10)) < 10 ) { if( recChars == 0 ) printf("ConfigTimerClock error : read failed\n"); else printf("ConfigTimerClock error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 10); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("ConfigTimerClock error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("ConfigTimerClock error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigTimerClock error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x02) || recBuff[3] != (uint8)(0x0A) ) { printf("ConfigTimerClock error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigTimerClock error : read buffer received errorcode %d\n", recBuff[6]); return -1; } /* if( recBuff[8] != timerClockConfig ) { printf("ConfigTimerClock error : TimerClockConfig did not get set correctly %d\n", recBuff[7]); return -1; } if( recBuff[9] != timerClockDivisor ) { printf("ConfigTimerClock error : TimerClockDivisor did not get set correctly %d\n", recBuff[7]); return -1; } */ return 0; } //Sends a Feedback low-level command that configures digital directions, states, //timer modes and DAC0 for this example. Will work with U3 hardware versions //1.20, 1.21 and 1.30 LV. int feedback_setup_example(HANDLE hDevice, u3CalibrationInfo *caliInfo) { uint8 sendBuff[32], recBuff[18]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 13; //Number of data words (.5 word for echo, 8 words for //IOTypes and data, and .5 words for the extra byte) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 13; //IOType is BitDirWrite sendBuff[8] = 130; //IONumber (bits 0 - 4) is 2 and Direction (bit 7) is //output sendBuff[9] = 13; //IOType is BitDirWrite sendBuff[10] = 3; //IONumber (bits 0 - 4) is 3 and Direction (bit 7) is //input sendBuff[11] = 11; //IOType is BitStateWrite sendBuff[12] = 2; //IONumber (bits 0 - 4) is 2 and State (bit 7) is low sendBuff[13] = 43; //IOType is Timer0Config sendBuff[14] = 0; //TimerMode is 16 bit PWM output (mode 0) sendBuff[15] = 0; //Value LSB sendBuff[16] = 0; //Value MSB, Whole value is 32768 sendBuff[17] = 42; //IOType is Timer0 sendBuff[18] = 1; //UpdateReset sendBuff[19] = 0; //Value LSB sendBuff[20] = 128; //Value MSB, Whole Value is 32768 sendBuff[21] = 45; //IOType is Timer1Config sendBuff[22] = 1; //TimerMode is 8 bit PWM output (mode 1) sendBuff[23] = 0; //Value LSB sendBuff[24] = 0; //Value MSB, Whole value is 32768 sendBuff[25] = 44; //IOType is Timer1 sendBuff[26] = 1; //UpdateReset sendBuff[27] = 0; //Value LSB sendBuff[28] = 128; //Value MSB, Whole Value is 32768 sendBuff[29] = 34; //IOType is DAC0 (8-bit) //Value is 1.5 volts (in binary form) getDacBinVoltCalibrated8Bit(caliInfo, 0, 1.5, &sendBuff[30]); sendBuff[31] = 0; //Extra byte extendedChecksum(sendBuff, 32); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 32)) < 32 ) { if( sendChars == 0 ) printf("Feedback setup error : write failed\n"); else printf("Feedback setup error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 18)) < 18 ) { if( recChars == 0 ) { printf("Feedback setup error : read failed\n"); return -1; } else printf("Feedback setup error : did not read all of the buffer\n"); } checksumTotal = extendedChecksum16(recBuff, 18); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("Feedback setup error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Feedback setup error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback setup error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != 6 || recBuff[3] != (uint8)(0x00) ) { printf("Feedback setup error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Feedback setup error : received errorcode %d for frame %d in Feedback response. \n", recBuff[6], recBuff[7]); return -1; } return 0; } //Sends a Feedback low-level command that configures digital directions, states, //timer modes and DAC0 for this example. Meant for U3 hardware versions 1.30 HV //example purposes, but will work with LV as well. int feedback_setup_HV_example(HANDLE hDevice, u3CalibrationInfo *caliInfo) { uint8 sendBuff[28], recBuff[18]; uint16 binVoltage16, checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 11; //Number of data words (.5 word for echo, 10.5 words for //IOTypes and data) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 13; //IOType is BitDirWrite sendBuff[8] = 7; //IONumber (bits 0 - 4) is 7 and Direction (bit 7) is //input sendBuff[9] = 43; //IOType is Timer0Config sendBuff[10] = 0; //TimerMode is 16 bit PWM output (mode 0) sendBuff[11] = 0; //Value LSB sendBuff[12] = 0; //Value MSB, Whole value is 32768 sendBuff[13] = 42; //IOType is Timer0 sendBuff[14] = 1; //UpdateReset sendBuff[15] = 0; //Value LSB sendBuff[16] = 128; //Value MSB, Whole Value is 32768 sendBuff[17] = 45; //IOType is Timer1Config sendBuff[18] = 1; //TimerMode is 8 bit PWM output (mode 1) sendBuff[19] = 0; //Value LSB sendBuff[20] = 0; //Value MSB, Whole value is 32768 sendBuff[21] = 44; //IOType is Timer1 sendBuff[22] = 1; //UpdateReset sendBuff[23] = 0; //Value LSB sendBuff[24] = 128; //Value MSB, Whole Value is 32768 sendBuff[25] = 38; //IOType is DAC0 (16-bit) //Value is 3.5 volts (in binary form) getDacBinVoltCalibrated16Bit(caliInfo, 0, 3.5, &binVoltage16); sendBuff[26] = (uint8)(binVoltage16&255); //Value LSB sendBuff[27] = (uint8)((binVoltage16&65280)/256); //Value MSB extendedChecksum(sendBuff, 28); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 28)) < 28 ) { if( sendChars == 0 ) printf("Feedback setup HV error : write failed\n"); else printf("Feedback setup HV error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 18)) < 18 ) { if( recChars == 0 ) { printf("Feedback setup HV error : read failed\n"); return -1; } else printf("Feedback setup HV error : did not read all of the buffer\n"); } checksumTotal = extendedChecksum16(recBuff, 18); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("Feedback setup HV error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Feedback setup HV error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback setup HV error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != 6 || recBuff[3] != (uint8)(0x00) ) { printf("Feedback setup HV error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Feedback setup HV error : received errorcode %d for frame %d in Feedback response. \n", recBuff[6], recBuff[7]); return -1; } return 0; } //Calls a Feedback low-level call to read AIN0, AIN1, FIO3, Counter1(FIO6) and //temperature. Will work with U3 hardware versions 1.20, 1.21 and 1.30 LV. int feedback_loop_example(HANDLE hDevice, u3CalibrationInfo *caliInfo, int isDAC1Enabled) { uint8 sendBuff[32], recBuff[28]; uint16 checksumTotal; int sendChars, recChars; long count; double voltage, temperature; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 13; //Number of data words (.5 word for echo, 12.5 words for //IOTypes) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 1; //IOType is AIN sendBuff[8] = 0; //Positive channel (bits 0-4) is 0, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[9] = 31; //Negative channel is 31 (SE) sendBuff[10] = 1; //IOType is AIN sendBuff[11] = 1; //Positive channel (bits 0-4) is 1, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[12] = 31; //Negative channel is 31 (SE) sendBuff[13] = 1; //IOType is AIN sendBuff[14] = 0; //Positive channel (bits 0-4) is 0, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[15] = 1; //Negative channel is 1 (FIO1) sendBuff[16] = 1; //IOType is AIN sendBuff[17] = 1; //Positive channel (bits 0-4) is 1, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[18] = 0; //Negative channel is 0 (FIO0) sendBuff[19] = 1; //IOType is AIN sendBuff[20] = 0; //Positive channel (bits 0-4) is 0, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[21] = 30; //Negative channel is 30 (Vref) sendBuff[22] = 1; //IOType is AIN sendBuff[23] = 1; //Positive channel (bits 0-4) is 1, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[24] = 30; //Negative channel is 30 (Vref) sendBuff[25] = 10; //IOType is BitStateRead sendBuff[26] = 3; //IO number is 3 (FIO3) sendBuff[27] = 55; //IOType is Counter1 sendBuff[28] = 0; //Reset (bit 0) is not set sendBuff[29] = 1; //IOType is AIN sendBuff[30] = 30; //Positive channel is 30 (temp sensor) sendBuff[31] = 31; //Negative channel is 31 (SE) extendedChecksum(sendBuff, 32); printf("Running Feedback calls in a loop\n"); count = 0; while( !kbhit() ) { count++; printf("Iteration %ld\n", count); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 32)) < 32 ) { if( sendChars == 0 ) printf("Feedback loop error : write failed\n"); else printf("Feedback loop error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 28)) < 28 ) { if( recChars == 0 ) { printf("Feedback loop error : read failed\n"); return -1; } else printf("Feedback loop error : did not read all of the expected buffer\n"); } if( recChars < 10 ) { printf("Feedback loop error : response is not large enough\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("Feedback loop error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Feedback loop error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback loop error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback loop error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Feedback loop error : received errorcode %d for frame %d ", recBuff[6], recBuff[7]); switch( recBuff[7] ) { case 1: printf("(AIN(SE))\n"); break; case 2: printf("(AIN(SE))\n"); break; case 3: printf("(AIN(Neg. chan. 1))\n"); break; case 4: printf("(AIN(Neg. chan. 0))\n"); break; case 5: printf("(AIN(Neg. chan. Vref))\n"); break; case 6: printf("(AIN(Neg. chan. Vref))\n"); break; case 7: printf("(BitStateRead for FIO3)\n"); break; case 8: printf("(Counter1)\n"); break; case 9: printf("(Temp. Sensor\n"); break; default: printf("(Unknown)\n"); break; } return -1; } getAinVoltCalibrated(caliInfo, isDAC1Enabled, 31, recBuff[9] + recBuff[10]*256, &voltage); printf("AIN0(SE) : %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, isDAC1Enabled, 31, recBuff[11] + recBuff[12]*256, &voltage); printf("AIN1(SE) : %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, isDAC1Enabled, 1, recBuff[13] + recBuff[14]*256, &voltage); printf("AIN0(Neg. chan. 1) : %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, isDAC1Enabled, 0, recBuff[15] + recBuff[16]*256, &voltage); printf("AIN1(Neg. chan. 0): %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, isDAC1Enabled, 30, recBuff[17] + recBuff[18]*256, &voltage); printf("AIN0(Neg. chan. Vref) : %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, isDAC1Enabled, 30, recBuff[19] + recBuff[20]*256, &voltage); printf("AIN1(Neg. chan. Vref): %.3f volts\n", voltage); printf("FIO3 state : %d\n", recBuff[21]); printf("Counter1(FIO6) : %u\n\n", recBuff[22] + recBuff[23]*256 + recBuff[24]*65536 + recBuff[25]*16777216); getTempKCalibrated(caliInfo, recBuff[26] + recBuff[27]*256, &temperature); printf("Temperature : %.3f K\n\n", temperature); sleep(1); } return 0; } //Calls a Feedback low-level call to read AIN0, AIN1, FIO7, Counter1(FIO6) and //temperature. Will work with U3 hardware versions 1.30 HV. int feedback_loop_HV_example(HANDLE hDevice, u3CalibrationInfo *caliInfo) { uint8 sendBuff[26], recBuff[24]; uint16 checksumTotal; int sendChars, recChars; long count; double voltage, temperature; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 10; //Number of data words (.5 word for echo, 9.5 words for //IOTypes) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 1; //IOType is AIN sendBuff[8] = 0; //Positive channel (bits 0-4) is 0, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[9] = 31; //Negative channel is 31 (SE) sendBuff[10] = 1; //IOType is AIN sendBuff[11] = 1; //Positive channel (bits 0-4) is 1, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[12] = 31; //Negative channel is 31 (SE) sendBuff[13] = 1; //IOType is AIN sendBuff[14] = 2; //Positive channel (bits 0-4) is 3, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[15] = 31; //Negative channel is 31 (SE) sendBuff[16] = 1; //IOType is AIN sendBuff[17] = 3; //Positive channel (bits 0-4) is 4, LongSettling (bit 6) //is not set and QuickSample (bit 7) is not set sendBuff[18] = 31; //Negative channel is 31 (SE) sendBuff[19] = 10; //IOType is BitStateRead sendBuff[20] = 7; //IO number is 7 (FIO7) sendBuff[21] = 55; //IOType is Counter1 sendBuff[22] = 0; //Reset (bit 0) is not set sendBuff[23] = 1; //IOType is AIN sendBuff[24] = 30; //Positive channel is 30 (temp sensor) sendBuff[25] = 31; //Negative channel is 31 (SE) extendedChecksum(sendBuff, 26); printf("Running Feedback calls in a loop\n"); count = 0; while( !kbhit() ) { count++; printf("Iteration %ld\n", count); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 26)) < 26 ) { if( sendChars == 0 ) printf("Feedback loop HV error : write failed\n"); else printf("Feedback loop HV error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 24)) < 24 ) { if( recChars == 0 ) { printf("Feedback loop HV error : read failed\n"); return -1; } else printf("Feedback loop HV error : did not read all of the expected buffer\n"); } if( recChars < 10 ) { printf("Feedback loop HV error : response is not large enough\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("Feedback loop HV error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("Feedback loop HV error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback loop HV error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback loop HV error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Feedback loop HV error : received errorcode %d for frame %d ", recBuff[6], recBuff[7]); switch( recBuff[7] ) { case 1: printf("(AIN0(SE))\n"); break; case 2: printf("(AIN1(SE))\n"); break; case 3: printf("(AIN2(SE))\n"); break; case 4: printf("(AIN3(SE))\n"); break; case 5: printf("(BitStateRead for FIO7)\n"); break; case 6: printf("(Counter1)\n"); break; case 7: printf("(Temp. Sensor\n"); break; default: printf("(Unknown)\n"); break; } return -1; } getAinVoltCalibrated_hw130(caliInfo, 0, 31, recBuff[9] + recBuff[10]*256, &voltage); printf("AIN0(SE) : %.3f volts\n", voltage); getAinVoltCalibrated_hw130(caliInfo, 1, 31, recBuff[11] + recBuff[12]*256, &voltage); printf("AIN1(SE) : %.3f volts\n", voltage); getAinVoltCalibrated_hw130(caliInfo, 2, 31, recBuff[13] + recBuff[14]*256, &voltage); printf("AIN2(SE) : %.3f volts\n", voltage); getAinVoltCalibrated_hw130(caliInfo, 3, 31, recBuff[15] + recBuff[16]*256, &voltage); printf("AIN3(SE) : %.3f volts\n", voltage); printf("FIO7 state : %d\n", recBuff[17]); printf("Counter1(FIO6) : %u\n\n", recBuff[18] + recBuff[19]*256 + recBuff[20]*65536 + recBuff[21]*16777216); getTempKCalibrated(caliInfo, recBuff[22] + recBuff[23]*256, &temperature); printf("Temperature : %.3f K\n\n", temperature); sleep(1); } return 0; } void setTerm() { tcgetattr(0, &termOrig); termNew = termOrig; termNew.c_lflag &= ~ICANON; termNew.c_lflag &= ~ECHO; termNew.c_lflag &= ~ISIG; termNew.c_cc[VMIN] = 1; termNew.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &termNew); } int kbhit() { char ch; int nread; if( peek != -1 ) return 1; termNew.c_cc[VMIN] = 0; tcsetattr(0, TCSANOW, &termNew); nread = read(0, &ch, 1); termNew.c_cc[VMIN] = 1; tcsetattr(0, TCSANOW, &termNew); if(nread == 1) { peek = ch; return 1; } return 0; } void unsetTerm() { tcsetattr(0, TCSANOW, &termOrig); }
498
./exodriver/examples/U3/u3.c
//Author: LabJack //December 27, 2011 //Example U3 helper functions. Function descriptions are in the u3.h file. #include "u3.h" #include <stdlib.h> u3CalibrationInfo U3_CALIBRATION_INFO_DEFAULT = { 3, 1.31, 0, //Nominal Values { 0.000037231, 0.0, 0.000074463, -2.44, 51.717, 0.0, 51.717, 0.0, 0.013021, 2.44, 3.66, 3.3, 0.000314, 0.000314, 0.000314, 0.000314, -10.3, -10.3, -10.3, -10.3} }; void normalChecksum(uint8 *b, int n) { b[0] = normalChecksum8(b, n); } void extendedChecksum(uint8 *b, int n) { uint16 a; a = extendedChecksum16(b, n); b[4] = (uint8)(a & 0xFF); b[5] = (uint8)((a/256) & 0xFF); b[0] = extendedChecksum8(b); } uint8 normalChecksum8(uint8 *b, int n) { int i; uint16 a, bb; //Sums bytes 1 to n-1 unsigned to a 2 byte value. Sums quotient and //remainder of 256 division. Again, sums quotient and remainder of //256 division. for( i = 1, a = 0; i < n; i++ ) a += (uint16)b[i]; bb = a / 256; a = (a - 256*bb) + bb; bb = a / 256; return (uint8)((a - 256*bb) + bb); } uint16 extendedChecksum16(uint8 *b, int n) { int i, a = 0; //Sums bytes 6 to n-1 to a unsigned 2 byte value for( i = 6; i < n; i++ ) a += (uint16)b[i]; return a; } uint8 extendedChecksum8(uint8 *b) { int i, a, bb; //Sums bytes 1 to 5. Sums quotient and remainder of 256 division. Again, //sums quotient and remainder of 256 division. for( i = 1, a = 0; i < 6; i++ ) a += (uint16)b[i]; bb=a / 256; a=(a - 256*bb) + bb; bb=a / 256; return (uint8)((a - 256*bb) + bb); } HANDLE openUSBConnection(int localID) { uint8 buffer[38]; //send size of 26, receive size of 38 uint16 checksumTotal = 0; uint32 numDevices = 0; uint32 dev; int i, serial; HANDLE hDevice = 0; numDevices = LJUSB_GetDevCount(U3_PRODUCT_ID); if( numDevices == 0 ) { printf("Open error: No U3 devices could be found\n"); return NULL; } for( dev = 1; dev <= numDevices; dev++ ) { hDevice = LJUSB_OpenDevice(dev, 0, U3_PRODUCT_ID); if( hDevice != NULL ) { if( localID < 0 ) { return hDevice; } else { checksumTotal = 0; //Setting up a ConfigU3 command buffer[1] = (uint8)(0xF8); buffer[2] = (uint8)(0x0A); buffer[3] = (uint8)(0x08); for( i = 6; i < 38; i++ ) buffer[i] = (uint8)(0x00); extendedChecksum(buffer, 26); if( LJUSB_Write(hDevice, buffer, 26) != 26 ) goto locid_error; if( LJUSB_Read(hDevice, buffer, 38) != 38 ) goto locid_error; checksumTotal = extendedChecksum16(buffer, 38); if( (uint8)((checksumTotal / 256) & 0xFF) != buffer[5] ) goto locid_error; if( (uint8)(checksumTotal & 0xFF) != buffer[4] ) goto locid_error; if( extendedChecksum8(buffer) != buffer[0] ) goto locid_error; if( buffer[1] != (uint8)(0xF8) || buffer[2] != (uint8)(0x10) || buffer[3] != (uint8)(0x08) ) goto locid_error; if( buffer[6] != 0 ) goto locid_error; //Check local ID if( (int)buffer[21] == localID ) return hDevice; //Check serial number serial = (int)(buffer[15] + buffer[16]*256 + buffer[17]*65536 + buffer[18]*16777216); if( serial == localID ) return hDevice; //No matches, not our device LJUSB_CloseDevice(hDevice); } //else localID >= 0 end } //if hDevice != NULL end } //for end printf("Open error: could not find a U3 with a local ID or serial number of %d\n", localID); return NULL; locid_error: printf("Open error: problem when checking local ID\n"); return NULL; } void closeUSBConnection(HANDLE hDevice) { LJUSB_CloseDevice(hDevice); } long getTickCount() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } long isCalibrationInfoValid(u3CalibrationInfo *caliInfo) { if( caliInfo == NULL ) goto invalid; if( caliInfo->prodID != 3 ) goto invalid; return 1; invalid: printf("Error: Invalid calibration info.\n"); return 0; } long isTdacCalibrationInfoValid(u3TdacCalibrationInfo *caliInfo) { if( caliInfo == NULL ) goto invalid; if( caliInfo->prodID != 3 ) goto invalid; return 1; invalid: printf("Error: Invalid LJTDAC calibration info.\n"); return 0; } long getCalibrationInfo(HANDLE hDevice, u3CalibrationInfo *caliInfo) { uint8 sendBuffer[8], recBuffer[40]; uint8 cU3SendBuffer[26], cU3RecBuffer[38]; int sentRec = 0, offset = 0, i = 0; /* Sending ConfigU3 command to get hardware version and see if HV */ cU3SendBuffer[1] = (uint8)(0xF8); //Command byte cU3SendBuffer[2] = (uint8)(0x0A); //Number of data words cU3SendBuffer[3] = (uint8)(0x08); //Extended command number //Setting WriteMask0 and all other bytes to 0 since we only want to read the //response for( i = 6; i < 26; i++ ) cU3SendBuffer[i] = 0; extendedChecksum(cU3SendBuffer, 26); sentRec = LJUSB_Write(hDevice, cU3SendBuffer, 26); if( sentRec < 26 ) { if( sentRec == 0 ) goto writeError0; else goto writeError1; } sentRec = LJUSB_Read(hDevice, cU3RecBuffer, 38); if( sentRec < 38 ) { if( sentRec == 0 ) goto readError0; else goto readError1; } if( cU3RecBuffer[1] != (uint8)(0xF8) || cU3RecBuffer[2] != (uint8)(0x10) || cU3RecBuffer[3] != (uint8)(0x08)) goto commandByteError; caliInfo->hardwareVersion = cU3RecBuffer[14] + cU3RecBuffer[13]/100.0; if( (cU3RecBuffer[37] & 18) == 18 ) caliInfo->highVoltage = 1; else caliInfo->highVoltage = 0; for( i = 0; i < 5; i++ ) { /* Reading block i from memory */ sendBuffer[1] = (uint8)(0xF8); //Command byte sendBuffer[2] = (uint8)(0x01); //Cumber of data words sendBuffer[3] = (uint8)(0x2D); //Extended command number sendBuffer[6] = 0; sendBuffer[7] = (uint8)i; //Blocknum = i extendedChecksum(sendBuffer, 8); sentRec = LJUSB_Write(hDevice, sendBuffer, 8); if( sentRec < 8 ) { if( sentRec == 0 ) goto writeError0; else goto writeError1; } sentRec = LJUSB_Read(hDevice, recBuffer, 40); if( sentRec < 40 ) { if( sentRec == 0 ) goto readError0; else goto readError1; } if( recBuffer[1] != (uint8)(0xF8) || recBuffer[2] != (uint8)(0x11) || recBuffer[3] != (uint8)(0x2D) ) goto commandByteError; offset = i * 4; //Block data starts on byte 8 of the buffer caliInfo->ccConstants[offset] = FPuint8ArrayToFPDouble(recBuffer + 8, 0); caliInfo->ccConstants[offset + 1] = FPuint8ArrayToFPDouble(recBuffer + 8, 8); caliInfo->ccConstants[offset + 2] = FPuint8ArrayToFPDouble(recBuffer + 8, 16); caliInfo->ccConstants[offset + 3] = FPuint8ArrayToFPDouble(recBuffer + 8, 24); } caliInfo->prodID = 3; return 0; writeError0: printf("Error : getCalibrationInfo write failed\n"); return -1; writeError1: printf("Error : getCalibrationInfo did not write all of the buffer\n"); return -1; readError0: printf("Error : getCalibrationInfo read failed\n"); return -1; readError1: printf("Error : getCalibrationInfo did not read all of the buffer\n"); return -1; commandByteError: printf("Error : getCalibrationInfo received wrong command bytes for ReadMem\n"); return -1; } long getTdacCalibrationInfo( HANDLE hDevice, u3TdacCalibrationInfo *caliInfo, uint8 DIOAPinNum) { int err; uint8 options, speedAdjust, sdaPinNum, sclPinNum; uint8 address, numByteToSend, numBytesToRec, errorcode; uint8 bytesComm[1], bytesResp[32]; uint8 ackArray[4]; err = 0; //Setting up I2C command for LJTDAC options = 0; //I2COptions : 0 speedAdjust = 0; //SpeedAdjust : 0 (for max communication speed of about //130 kHz) sdaPinNum = DIOAPinNum+1; //SDAPinNum : FIO channel connected to pin DIOB sclPinNum = DIOAPinNum; //SCLPinNum : FIO channel connected to pin DIOA address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numByteToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToRec = 32; //NumI2CBytesToReceive : getting 32 bytes starting at //EEPROM address specified in I2CByte0 bytesComm[0] = 64; //I2CByte0 : Memory Address (starting at address 64, // DACA Slope) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numByteToSend, numBytesToRec, bytesComm, &errorcode, ackArray, bytesResp); if( errorcode != 0 ) { printf("Getting LJTDAC calibration info error : received errorcode %d in response\n", errorcode); err = -1; } if( err == -1 ) return err; caliInfo->ccConstants[0] = FPuint8ArrayToFPDouble(bytesResp, 0); caliInfo->ccConstants[1] = FPuint8ArrayToFPDouble(bytesResp, 8); caliInfo->ccConstants[2] = FPuint8ArrayToFPDouble(bytesResp, 16); caliInfo->ccConstants[3] = FPuint8ArrayToFPDouble(bytesResp, 24); caliInfo->prodID = 3; return err; } double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex) { uint32 resultDec = 0, resultWh = 0; resultDec = (uint32)buffer[startIndex] | ((uint32)buffer[startIndex + 1] << 8) | ((uint32)buffer[startIndex + 2] << 16) | ((uint32)buffer[startIndex + 3] << 24); resultWh = (uint32)buffer[startIndex + 4] | ((uint32)buffer[startIndex + 5] << 8) | ((uint32)buffer[startIndex + 6] << 16) | ((uint32)buffer[startIndex + 7] << 24); return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 ); } long getAinVoltCalibrated(u3CalibrationInfo *caliInfo, int dacEnabled, uint8 negChannel, uint16 bytesVolt, double *analogVolt) { if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( caliInfo->hardwareVersion >= 1.30 ) { if( caliInfo->highVoltage == 1 ) { printf("getAinVoltCalibrated error: cannot handle U3-HV device. Please use getAinVoltCalibrated_hw130 function.\n"); return -1; } else return getAinVoltCalibrated_hw130(caliInfo, 0, negChannel, bytesVolt, analogVolt); } if( negChannel <= 15 || negChannel == 30 ) { if( dacEnabled == 0 ) *analogVolt = caliInfo->ccConstants[2]*((double)bytesVolt) + caliInfo->ccConstants[3]; else *analogVolt = (bytesVolt/65536.0)*caliInfo->ccConstants[11]*2.0 - caliInfo->ccConstants[11]; } else if( negChannel == 31 ) { if( dacEnabled == 0 ) *analogVolt = caliInfo->ccConstants[0]*((double)bytesVolt) + caliInfo->ccConstants[1]; else *analogVolt = (bytesVolt/65536.0)*caliInfo->ccConstants[11]; } else { printf("getAinVoltCalibrated error: invalid negative channel.\n"); return -1; } return 0; } long getAinVoltCalibrated_hw130(u3CalibrationInfo *caliInfo, uint8 positiveChannel, uint8 negChannel, uint16 bytesVolt, double *analogVolt) { if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( caliInfo->hardwareVersion < 1.30 ) { printf("getAinVoltCalibrated_hw130 error: cannot handle U3 hardware versions < 1.30 . Please use getAinVoltCalibrated function.\n"); return -1; } if( negChannel <= 15 || negChannel == 30 ) { if( caliInfo->highVoltage == 0 || (caliInfo->highVoltage == 1 && positiveChannel >= 4 && negChannel >= 4) ) { *analogVolt = caliInfo->ccConstants[2]*((double)bytesVolt) + caliInfo->ccConstants[3]; } else if( caliInfo->hardwareVersion >= 1.30 && caliInfo->highVoltage == 1 ) { printf("getAinVoltCalibrated_hw130 error: invalid negative channel for U3-HV.\n"); return -1; } } else if( negChannel == 31 ) { if( caliInfo->highVoltage == 1 && positiveChannel < 4 ) *analogVolt = caliInfo->ccConstants[12+positiveChannel]*((double)bytesVolt) + caliInfo->ccConstants[16+positiveChannel]; else *analogVolt = caliInfo->ccConstants[0]*((double)bytesVolt) + caliInfo->ccConstants[1]; } else if( negChannel == 32 ) //Special range (binary value should be from a //diff. AIN reading with negative channel 30) { if( caliInfo->highVoltage == 1 && positiveChannel < 4 ) { *analogVolt = (caliInfo->ccConstants[2]*((double)bytesVolt) + caliInfo->ccConstants[3] + caliInfo->ccConstants[9]) * caliInfo->ccConstants[12 + positiveChannel] / caliInfo->ccConstants[0] + caliInfo->ccConstants[16 + positiveChannel]; } else { *analogVolt = caliInfo->ccConstants[2]*((double)bytesVolt) + caliInfo->ccConstants[3] + caliInfo->ccConstants[9]; } } else { printf("getAinVoltCalibrated_hw130 error: invalid negative channel.\n"); return -1; } return 0; } long getDacBinVoltCalibrated(u3CalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint8 *bytesVolt) { return getDacBinVoltCalibrated8Bit(caliInfo, dacNumber, analogVolt, bytesVolt); } long getDacBinVoltCalibrated8Bit(u3CalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint8 *bytesVolt8) { double tBytesVolt; if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getDacBinVoltCalibrated8Bit error: invalid channelNumber.\n"); return -1; } tBytesVolt = analogVolt*caliInfo->ccConstants[4 + dacNumber*2] + caliInfo->ccConstants[5 + dacNumber*2]; //Checking to make sure bytesVolt will be a value between 0 and 255. Too //high of an analogVoltage (about 4.95 and above volts) or too low (below 0 //volts) will cause a value not between 0 and 255. if( tBytesVolt < 0 ) tBytesVolt = 0; else if( tBytesVolt > 255 && caliInfo->hardwareVersion < 1.30 ) tBytesVolt = 255; *bytesVolt8 = (uint8)tBytesVolt; return 0; } long getDacBinVoltCalibrated16Bit(u3CalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint16 *bytesVolt16) { double tBytesVolt; if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getDacBinVoltCalibrated16Bit error: invalid channelNumber.\n"); return -1; } if( caliInfo->hardwareVersion < 1.30 ) tBytesVolt = analogVolt*caliInfo->ccConstants[4 + dacNumber*2] + caliInfo->ccConstants[5 + dacNumber*2]; else tBytesVolt = analogVolt*caliInfo->ccConstants[4 + dacNumber*2]*256 + caliInfo->ccConstants[5 + dacNumber*2]*256; //Checking to make sure bytesVolt will be a value between 0 and 255/65535. //Too high of an analogVoltage (about 4.95 and above volts) or too low //(below 0 volts) will cause a value not between 0 and 255/65535. if( tBytesVolt < 0 ) tBytesVolt = 0; if( tBytesVolt > 65535 && caliInfo->hardwareVersion >= 1.30 ) tBytesVolt = 65535; else if( tBytesVolt > 255 && caliInfo->hardwareVersion < 1.30 ) tBytesVolt = 255; *bytesVolt16 = (uint16)tBytesVolt; return 0; } long getTdacBinVoltCalibrated(u3TdacCalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint16 *bytesVolt) { uint32 tBytesVolt; if( isTdacCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getTdacBinVoltCalibrated error: invalid channelNumber.\n"); return -1; } tBytesVolt = analogVolt*caliInfo->ccConstants[dacNumber*2] + caliInfo->ccConstants[dacNumber*2 + 1]; //Checking to make sure bytesVolt will be a value between 0 and 65535. if( tBytesVolt > 65535 ) tBytesVolt = 65535; *bytesVolt = (uint16)tBytesVolt; return 0; } long getTempKCalibrated(u3CalibrationInfo *caliInfo, uint32 bytesTemp, double *kelvinTemp) { if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; *kelvinTemp = caliInfo->ccConstants[8]*((double)bytesTemp); return 0; } long getAinVoltUncalibrated(int dacEnabled, uint8 negChannel, uint16 bytesVolt, double *analogVolt) { U3_CALIBRATION_INFO_DEFAULT.hardwareVersion = 1.20; U3_CALIBRATION_INFO_DEFAULT.highVoltage = 0; return getAinVoltCalibrated(&U3_CALIBRATION_INFO_DEFAULT, dacEnabled, negChannel, bytesVolt, analogVolt); } long getAinVoltUncalibrated_hw130(int highVoltage, uint8 positiveChannel, uint8 negChannel, uint16 bytesVolt, double *analogVolt) { U3_CALIBRATION_INFO_DEFAULT.hardwareVersion = 1.30; U3_CALIBRATION_INFO_DEFAULT.highVoltage = highVoltage; return getAinVoltCalibrated_hw130(&U3_CALIBRATION_INFO_DEFAULT, positiveChannel, negChannel, bytesVolt, analogVolt); } long getDacBinVoltUncalibrated(int dacNumber, double analogVolt, uint8 *bytesVolt) { U3_CALIBRATION_INFO_DEFAULT.hardwareVersion = 1.20; U3_CALIBRATION_INFO_DEFAULT.highVoltage = 0; return getDacBinVoltCalibrated(&U3_CALIBRATION_INFO_DEFAULT, dacNumber, analogVolt, bytesVolt); } long getDacBinVoltUncalibrated8Bit(int dacNumber, double analogVolt, uint8 *bytesVolt8) { U3_CALIBRATION_INFO_DEFAULT.hardwareVersion = 1.20; U3_CALIBRATION_INFO_DEFAULT.highVoltage = 0; return getDacBinVoltCalibrated8Bit(&U3_CALIBRATION_INFO_DEFAULT, dacNumber, analogVolt, bytesVolt8); } long getDacBinVoltUncalibrated16Bit(int dacNumber, double analogVolt, uint16 *bytesVolt16) { U3_CALIBRATION_INFO_DEFAULT.hardwareVersion = 1.30; U3_CALIBRATION_INFO_DEFAULT.highVoltage = 0; return getDacBinVoltCalibrated16Bit(&U3_CALIBRATION_INFO_DEFAULT, dacNumber, analogVolt, bytesVolt16); } long getTempKUncalibrated(uint16 bytesTemp, double *kelvinTemp) { U3_CALIBRATION_INFO_DEFAULT.hardwareVersion = 1.20; U3_CALIBRATION_INFO_DEFAULT.highVoltage = 0; return getTempKCalibrated(&U3_CALIBRATION_INFO_DEFAULT, bytesTemp, kelvinTemp); } long I2C(HANDLE hDevice, uint8 I2COptions, uint8 SpeedAdjust, uint8 SDAPinNum, uint8 SCLPinNum, uint8 Address, uint8 NumI2CBytesToSend, uint8 NumI2CBytesToReceive, uint8 *I2CBytesCommand, uint8 *Errorcode, uint8 *AckArray, uint8 *I2CBytesResponse) { uint8 *sendBuff, *recBuff; uint16 checksumTotal = 0; uint32 ackArrayTotal, expectedAckArray; int sendChars, recChars, sendSize, recSize; int i, ret; *Errorcode = 0; ret = 0; sendSize = 6 + 8 + ((NumI2CBytesToSend%2 != 0)?(NumI2CBytesToSend + 1):(NumI2CBytesToSend)); recSize = 6 + 6 + ((NumI2CBytesToReceive%2 != 0)?(NumI2CBytesToReceive + 1):(NumI2CBytesToReceive)); sendBuff = (uint8 *)malloc(sizeof(uint8)*sendSize); recBuff = (uint8 *)malloc(sizeof(uint8)*recSize); sendBuff[sendSize - 1] = 0; //I2C command sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (sendSize - 6) / 2; //Number of data words = 4 + NumI2CBytesToSend sendBuff[3] = (uint8)(0x3B); //extended command number sendBuff[6] = I2COptions; //I2COptions sendBuff[7] = SpeedAdjust; //SpeedAdjust sendBuff[8] = SDAPinNum; //SDAPinNum sendBuff[9] = SCLPinNum; //SCLPinNum sendBuff[10] = Address; //Address sendBuff[11] = 0; //Reserved sendBuff[12] = NumI2CBytesToSend; //NumI2CByteToSend sendBuff[13] = NumI2CBytesToReceive; //NumI2CBytesToReceive for( i = 0; i < NumI2CBytesToSend; i++ ) sendBuff[14 + i] = I2CBytesCommand[i]; //I2CByte extendedChecksum(sendBuff, sendSize); //Sending command to U3 sendChars = LJUSB_Write(hDevice, sendBuff, sendSize); if( sendChars < sendSize ) { if( sendChars == 0 ) printf("I2C Error : write failed\n"); else printf("I2C Error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from U3 recChars = LJUSB_Read(hDevice, recBuff, recSize); if( recChars < recSize ) { if( recChars == 0 ) printf("I2C Error : read failed\n"); else { printf("I2C Error : did not read all of the buffer\n"); if( recChars >= 12 ) *Errorcode = recBuff[6]; } ret = -1; goto cleanmem; } *Errorcode = recBuff[6]; AckArray[0] = recBuff[8]; AckArray[1] = recBuff[9]; AckArray[2] = recBuff[10]; AckArray[3] = recBuff[11]; for( i = 0; i < NumI2CBytesToReceive; i++ ) I2CBytesResponse[i] = recBuff[12 + i]; if( (uint8)(extendedChecksum8(recBuff)) != recBuff[0] ) { printf("I2C Error : read buffer has bad checksum (%d)\n", recBuff[0]); ret = -1; } if( recBuff[1] != (uint8)(0xF8) ) { printf("I2C Error : read buffer has incorrect command byte (%d)\n", recBuff[1]); ret = -1; } if( recBuff[2] != (uint8)((recSize - 6)/2) ) { printf("I2C Error : read buffer has incorrect number of data words (%d)\n", recBuff[2]); ret = -1; } if( recBuff[3] != (uint8)(0x3B) ) { printf("I2C Error : read buffer has incorrect extended command number (%d)\n", recBuff[3]); ret = -1; } checksumTotal = extendedChecksum16(recBuff, recSize); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] || (uint8)(checksumTotal & 255) != recBuff[4]) { printf("I2C error : read buffer has bad checksum16 (%u)\n", checksumTotal); ret = -1; } //ackArray should ack the Address byte in the first ack bit, but did not //until firmware 1.44 ackArrayTotal = AckArray[0] + AckArray[1]*256 + AckArray[2]*65536 + AckArray[3]*16777216; expectedAckArray = pow(2.0, NumI2CBytesToSend+1)-1; if( ackArrayTotal != expectedAckArray ) printf("I2C error : expected an ack of %u, but received %u\n", expectedAckArray, ackArrayTotal); cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; } long eAIN(HANDLE Handle, u3CalibrationInfo *CalibrationInfo, long ConfigIO, long *DAC1Enable, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2) { uint8 sendDataBuff[3], recDataBuff[2]; uint8 FIOAnalog, EIOAnalog, curFIOAnalog, curEIOAnalog; uint8 curTCConfig, settling, quicksample, Errorcode; uint8 ErrorFrame, outDAC1Enable; uint16 bytesVT; int hv, isSpecialRange = 0; long error; double hwver; if( isCalibrationInfoValid(CalibrationInfo) == 0 ) { printf("eAIN error: calibration information is required"); return -1; } hwver = CalibrationInfo->hardwareVersion; hv = CalibrationInfo->highVoltage; if( ChannelP < 0 || (ChannelP > 15 && ChannelP != 30 && ChannelP != 31) ) { printf("eAIN error: Invalid positive channel\n"); return -1; } if( ChannelN < 0 || (ChannelN > 15 && ChannelN != 30 && ChannelN != 31 && ChannelN != 32) || (hwver >= 1.30 && hv == 1 && ((ChannelP < 4 && ChannelN != 31 && ChannelN != 32) || ChannelN < 4)) ) { printf("eAIN error: Invalid negative channel\n"); return -1; } if( ChannelN == 32 ) { isSpecialRange = 1; ChannelN = 30; //Set to 30 for the feedback packet. We'll set it back //to 32 for conversion. } if( ConfigIO != 0 && !(hwver >= 1.30 && hv == 1 && ChannelP < 4) ) { FIOAnalog = 0; EIOAnalog = 0; //Setting ChannelP and ChannelN channels to analog using FIOAnalog and //EIOAnalog if( ChannelP <= 7 ) FIOAnalog = pow(2, ChannelP); else if( ChannelP <= 15 ) EIOAnalog = pow(2, (ChannelP - 8)); if( ChannelN <= 7 ) FIOAnalog = FIOAnalog | (int)pow(2, ChannelN); else if( ChannelN <= 15 ) EIOAnalog = EIOAnalog | (int)pow(2, (ChannelN - 8)); //Using ConfigIO to get current FIOAnalog and EIOAnalog settings if( (error = ehConfigIO(Handle, 0, 0, 0, 0, 0, &curTCConfig, &outDAC1Enable, &curFIOAnalog, &curEIOAnalog)) != 0 ) return error; *DAC1Enable = outDAC1Enable; if( !(FIOAnalog == curFIOAnalog && EIOAnalog == curEIOAnalog) ) { //Creating new FIOAnalog and EIOAnalog settings FIOAnalog = FIOAnalog | curFIOAnalog; EIOAnalog = EIOAnalog | curEIOAnalog; //Using ConfigIO to set new FIOAnalog and EIOAnalog settings if( (error = ehConfigIO(Handle, 12, curTCConfig, 0, FIOAnalog, EIOAnalog, NULL, NULL, &curFIOAnalog, &curEIOAnalog)) != 0 ) return error; } } /* Setting up Feedback command to read analog input */ sendDataBuff[0] = 1; //IOType is AIN settling = (Settling != 0) ? 1 : 0; quicksample = (Resolution != 0) ? 1 : 0; sendDataBuff[1] = (uint8)ChannelP + settling*64 + quicksample*128; //Positive channel (bits 0-4), LongSettling (bit 6) //QuickSample (bit 7) sendDataBuff[2] = (uint8)ChannelN; //Negative channel if( ehFeedback(Handle, sendDataBuff, 3, &Errorcode, &ErrorFrame, recDataBuff, 2) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; bytesVT = recDataBuff[0] + recDataBuff[1]*256; if( isSpecialRange ) { ChannelN = 32; // Change the negative channel back to 32 from 30 for conversion. } if( Binary != 0 ) { *Voltage = (double)bytesVT; } else { if( ChannelP == 30 ) { if( getTempKCalibrated(CalibrationInfo, bytesVT, Voltage) < 0 ) return -1; } else { if( hwver < 1.30 ) error = getAinVoltCalibrated(CalibrationInfo, (int)(*DAC1Enable), ChannelN, bytesVT, Voltage); else error = getAinVoltCalibrated_hw130(CalibrationInfo, ChannelP, ChannelN, bytesVT, Voltage); if( error < 0 ) return -1; } } return 0; } long eDAC(HANDLE Handle, u3CalibrationInfo *CalibrationInfo, long ConfigIO, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2) { uint8 sendDataBuff[3]; uint8 byteV, DAC1Enabled, Errorcode, ErrorFrame; uint16 bytesV; long error, sendSize; if( isCalibrationInfoValid(CalibrationInfo) == 0 ) { printf("eDAC error: calibration information is required"); return -1; } if( Channel < 0 || Channel > 1 ) { printf("eDAC error: Invalid DAC channel\n"); return -1; } if( ConfigIO != 0 && Channel == 1 && CalibrationInfo->hardwareVersion < 1.30 ) { //Using ConfigIO to enable DAC1 error = ehConfigIO(Handle, 2, 0, 1, 0, 0, NULL, &DAC1Enabled, NULL, NULL); if( error != 0 ) return error; } /* Setting up Feedback command to set DAC */ if( CalibrationInfo->hardwareVersion < 1.30 ) { sendSize = 2; sendDataBuff[0] = 34 + Channel; //IOType is DAC0/1 (8 bit) if( getDacBinVoltCalibrated8Bit(CalibrationInfo, (int)Channel, Voltage, &byteV) < 0 ) return -1; sendDataBuff[1] = byteV; //Value } else { sendSize = 3; sendDataBuff[0] = 38 + Channel; //IOType is DAC0/1 (16 bit) if( getDacBinVoltCalibrated16Bit(CalibrationInfo, (int)Channel, Voltage, &bytesV) < 0 ) return -1; sendDataBuff[1] = (uint8)(bytesV&255); //Value LSB sendDataBuff[2] = (uint8)((bytesV&65280)/256); //Value MSB } if( ehFeedback(Handle, sendDataBuff, sendSize, &Errorcode, &ErrorFrame, NULL, 0) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; return 0; } long eDI(HANDLE Handle, long ConfigIO, long Channel, long *State) { uint8 sendDataBuff[4], recDataBuff[1]; uint8 Errorcode, ErrorFrame, FIOAnalog, EIOAnalog; uint8 curFIOAnalog, curEIOAnalog, curTCConfig; long error; if( Channel < 0 || Channel > 19 ) { printf("eDI error: Invalid DI channel\n"); return -1; } if( ConfigIO != 0 && Channel <= 15 ) { FIOAnalog = 255; EIOAnalog = 255; //Setting Channel to digital using FIOAnalog and EIOAnalog if( Channel <= 7 ) FIOAnalog = 255 - pow(2, Channel); else EIOAnalog = 255 - pow(2, (Channel - 8)); //Using ConfigIO to get current FIOAnalog and EIOAnalog settings error = ehConfigIO(Handle, 0, 0, 0, 0, 0, &curTCConfig, NULL, &curFIOAnalog, &curEIOAnalog); if( error != 0 ) return error; if( !(FIOAnalog == curFIOAnalog && EIOAnalog == curEIOAnalog) ) { //Creating new FIOAnalog and EIOAnalog settings FIOAnalog = FIOAnalog & curFIOAnalog; EIOAnalog = EIOAnalog & curEIOAnalog; //Using ConfigIO to set new FIOAnalog and EIOAnalog settings error = ehConfigIO(Handle, 12, curTCConfig, 0, FIOAnalog, EIOAnalog, NULL, NULL, &curFIOAnalog, &curEIOAnalog); if( error != 0 ) return error; } } /* Setting up Feedback command to set digital Channel to input and to read from it */ sendDataBuff[0] = 13; //IOType is BitDirWrite sendDataBuff[1] = Channel; //IONumber(bits 0-4) + Direction (bit 7) sendDataBuff[2] = 10; //IOType is BitStateRead sendDataBuff[3] = Channel; //IONumber if( ehFeedback(Handle, sendDataBuff, 4, &Errorcode, &ErrorFrame, recDataBuff, 1) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; *State = recDataBuff[0]; return 0; } long eDO(HANDLE Handle, long ConfigIO, long Channel, long State) { uint8 sendDataBuff[4]; uint8 Errorcode, ErrorFrame, FIOAnalog, EIOAnalog; uint8 curFIOAnalog, curEIOAnalog, curTCConfig; long error; if( Channel < 0 || Channel > 19 ) { printf("eD0 error: Invalid DI channel\n"); return -1; } if( ConfigIO != 0 && Channel <= 15 ) { FIOAnalog = 255; EIOAnalog = 255; //Setting Channel to digital using FIOAnalog and EIOAnalog if( Channel <= 7 ) FIOAnalog = 255 - pow(2, Channel); else EIOAnalog = 255 - pow(2, (Channel - 8)); //Using ConfigIO to get current FIOAnalog and EIOAnalog settings error = ehConfigIO(Handle, 0, 0, 0, 0, 0, &curTCConfig, NULL, &curFIOAnalog, &curEIOAnalog); if( error != 0 ) return error; if( !(FIOAnalog == curFIOAnalog && EIOAnalog == curEIOAnalog) ) { //Using ConfigIO to get current FIOAnalog and EIOAnalog settings FIOAnalog = FIOAnalog & curFIOAnalog; EIOAnalog = EIOAnalog & curEIOAnalog; //Using ConfigIO to set new FIOAnalog and EIOAnalog settings error = ehConfigIO(Handle, 12, curTCConfig, 0, FIOAnalog, EIOAnalog, NULL, NULL, &curFIOAnalog, &curEIOAnalog); if( error != 0 ) return error; } } /* Setting up Feedback command to set digital Channel to output and to set the state */ sendDataBuff[0] = 13; //IOType is BitDirWrite sendDataBuff[1] = Channel + 128; //IONumber(bits 0-4) + Direction (bit 7) sendDataBuff[2] = 11; //IOType is BitStateWrite sendDataBuff[3] = Channel + 128*((State > 0) ? 1 : 0); //IONumber(bits 0-4) + State (bit 7) if( ehFeedback(Handle, sendDataBuff, 4, &Errorcode, &ErrorFrame, NULL, 0) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; return 0; } long eTCConfig(HANDLE Handle, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2) { uint8 sendDataBuff[8]; uint8 FIOAnalog, EIOAnalog, curFIOAnalog, curEIOAnalog; uint8 TimerCounterConfig, curTimerCounterConfig, Errorcode, ErrorFrame; int sendDataBuffSize, numTimers, numCounters, i; long error; if( TCPinOffset < 0 && TCPinOffset > 8 ) { printf("eTCConfig error: Invalid TimerCounterPinOffset\n"); return -1; } /* ConfigTimerClock */ if( TimerClockBaseIndex == LJ_tc2MHZ || TimerClockBaseIndex == LJ_tc6MHZ || TimerClockBaseIndex == LJ_tc24MHZ || TimerClockBaseIndex == LJ_tc500KHZ_DIV || TimerClockBaseIndex == LJ_tc2MHZ_DIV || TimerClockBaseIndex == LJ_tc6MHZ_DIV || TimerClockBaseIndex == LJ_tc24MHZ_DIV) { TimerClockBaseIndex = TimerClockBaseIndex - 10; } else if( TimerClockBaseIndex == LJ_tc4MHZ || TimerClockBaseIndex == LJ_tc12MHZ || TimerClockBaseIndex == LJ_tc48MHZ || TimerClockBaseIndex == LJ_tc1MHZ_DIV || TimerClockBaseIndex == LJ_tc4MHZ_DIV || TimerClockBaseIndex == LJ_tc12MHZ_DIV || TimerClockBaseIndex == LJ_tc48MHZ_DIV) { TimerClockBaseIndex = TimerClockBaseIndex - 20; } error = ehConfigTimerClock(Handle, (uint8)(TimerClockBaseIndex + 128), (uint8)TimerClockDivisor, NULL, NULL); if( error != 0 ) return error; //Using ConfigIO to get current FIOAnalog and curEIOAnalog settings error = ehConfigIO(Handle, 0, 0, 0, 0, 0, NULL, NULL, &curFIOAnalog, &curEIOAnalog); if( error != 0 ) return error; numTimers = 0; numCounters = 0; TimerCounterConfig = 0; FIOAnalog = 255; EIOAnalog = 255; for( i = 0; i < 2; i++ ) { if( aEnableTimers[i] != 0 ) numTimers++; else i = 999; } for( i = 0; i < 2; i++ ) { if( aEnableCounters[i] != 0 ) { numCounters++; TimerCounterConfig += pow(2, (i+2)); } } TimerCounterConfig += numTimers + TCPinOffset*16; for( i = 0; i < numCounters + numTimers; i++ ) { if( i + TCPinOffset < 8 ) FIOAnalog = FIOAnalog - pow(2, i + TCPinOffset); else EIOAnalog = EIOAnalog - pow(2, (i + TCPinOffset - 8)); } FIOAnalog = FIOAnalog & curFIOAnalog; EIOAnalog = EIOAnalog & curEIOAnalog; error = ehConfigIO(Handle, 13, TimerCounterConfig, 0, FIOAnalog, EIOAnalog, &curTimerCounterConfig, NULL, &curFIOAnalog, &curEIOAnalog); if( error != 0 ) return error; if( numTimers > 0 ) { /* Feedback */ for( i = 0; i < 8; i++ ) sendDataBuff[i] = 0; for( i = 0; i < numTimers; i++ ) { sendDataBuff[i*4] = 43 + i*2; //TimerConfig sendDataBuff[1 + i*4] = (uint8)aTimerModes[i]; //TimerMode sendDataBuff[2 + i*4] = (uint8)(((long)aTimerValues[i])&0x00ff); //Value LSB sendDataBuff[3 + i*4] = (uint8)((((long)aTimerValues[i])&0xff00)/256); //Value MSB } sendDataBuffSize = 4 * numTimers; if( ehFeedback(Handle, sendDataBuff, sendDataBuffSize, &Errorcode, &ErrorFrame, NULL, 0) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; } return 0; } long eTCValues(HANDLE Handle, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2) { uint8 sendDataBuff[12], recDataBuff[16], Errorcode, ErrorFrame; int sendDataBuffSize, recDataBuffSize, i, j; int numTimers, dataCountCounter, dataCountTimer; /* Feedback */ numTimers = 0; dataCountCounter = 0; dataCountTimer = 0; sendDataBuffSize = 0; recDataBuffSize = 0; for( i = 0; i < 2; i++ ) { if( aReadTimers[i] != 0 || aUpdateResetTimers[i] != 0 ) { sendDataBuff[sendDataBuffSize] = 42 + i*2; //Timer sendDataBuff[1 + sendDataBuffSize] = ((aUpdateResetTimers[i] != 0) ? 1 : 0); //UpdateReset sendDataBuff[2 + sendDataBuffSize] = (uint8)(((long)aTimerValues[i])&0x00ff); //Value LSB sendDataBuff[3 + sendDataBuffSize] = (uint8)((((long)aTimerValues[i])&0xff00)/256); //Value MSB sendDataBuffSize += 4; recDataBuffSize += 4; numTimers++; } } for( i = 0; i < 2; i++ ) { if( aReadCounters[i] != 0 || aResetCounters[i] != 0 ) { sendDataBuff[sendDataBuffSize] = 54 + i; //Counter sendDataBuff[1 + sendDataBuffSize] = ((aResetCounters[i] != 0) ? 1 : 0); //Reset sendDataBuffSize += 2; recDataBuffSize += 4; } } if( ehFeedback(Handle, sendDataBuff, sendDataBuffSize, &Errorcode, &ErrorFrame, recDataBuff, recDataBuffSize) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; for( i = 0; i < 2; i++ ) { aTimerValues[i] = 0; if( aReadTimers[i] != 0 ) { for( j = 0; j < 4; j++ ) aTimerValues[i] += (double)((long)recDataBuff[j + dataCountTimer*4]*pow(2, 8*j)); } if( aReadTimers[i] != 0 || aUpdateResetTimers[i] != 0 ) dataCountTimer++; aCounterValues[i] = 0; if( aReadCounters[i] != 0 ) { for( j = 0; j < 4; j++ ) aCounterValues[i] += (double)((long)recDataBuff[j + numTimers*4 + dataCountCounter*4]*pow(2, 8*j)); } if( aReadCounters[i] != 0 || aResetCounters[i] != 0 ) dataCountCounter++; } return 0; } long ehConfigIO(HANDLE hDevice, uint8 inWriteMask, uint8 inTimerCounterConfig, uint8 inDAC1Enable, uint8 inFIOAnalog, uint8 inEIOAnalog, uint8 *outTimerCounterConfig, uint8 *outDAC1Enable, uint8 *outFIOAnalog, uint8 *outEIOAnalog) { uint8 sendBuff[12], recBuff[12]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = inWriteMask; //Writemask sendBuff[7] = 0; //Reserved sendBuff[8] = inTimerCounterConfig; //TimerCounterConfig sendBuff[9] = inDAC1Enable; //DAC1 enable : not enabling sendBuff[10] = inFIOAnalog; //FIOAnalog sendBuff[11] = inEIOAnalog; //EIOAnalog extendedChecksum(sendBuff, 12); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 12)) < 12 ) { if( sendChars == 0 ) printf("ehConfigIO error : write failed\n"); else printf("ehConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 12)) < 12 ) { if( recChars == 0 ) printf("ehConfigIO error : read failed\n"); else printf("ehConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 12); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ehConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ehConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x03) || recBuff[3] != (uint8)(0x0B) ) { printf("ehConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ehConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return (int)recBuff[6]; } if( outTimerCounterConfig != NULL ) *outTimerCounterConfig = recBuff[8]; if( outDAC1Enable != NULL ) *outDAC1Enable = recBuff[9]; if( outFIOAnalog != NULL ) *outFIOAnalog = recBuff[10]; if( outEIOAnalog != NULL ) *outEIOAnalog = recBuff[11]; return 0; } long ehConfigTimerClock(HANDLE hDevice, uint8 inTimerClockConfig, uint8 inTimerClockDivisor, uint8 *outTimerClockConfig, uint8 *outTimerClockDivisor) { uint8 sendBuff[10], recBuff[10]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x02); //Number of data words sendBuff[3] = (uint8)(0x0A); //Extended command number sendBuff[6] = 0; //Reserved sendBuff[7] = 0; //Reserved sendBuff[8] = inTimerClockConfig; //TimerClockConfig sendBuff[9] = inTimerClockDivisor; //TimerClockDivisor extendedChecksum(sendBuff, 10); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 10)) < 10 ) { if( sendChars == 0 ) printf("ehConfigTimerClock error : write failed\n"); else printf("ehConfigTimerClock error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 10)) < 10 ) { if( recChars == 0 ) printf("ehConfigTimerClock error : read failed\n"); else printf("ehConfigTimerClock error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 10); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ehConfigTimerClock error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ehConfigTimerClock error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehConfigTimerClock error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x02) || recBuff[3] != (uint8)(0x0A) ) { printf("ehConfigTimerClock error : read buffer has wrong command bytes\n"); return -1; } if( outTimerClockConfig != NULL ) *outTimerClockConfig = recBuff[8]; if( outTimerClockDivisor != NULL ) *outTimerClockDivisor = recBuff[9]; if( recBuff[6] != 0 ) { printf("ehConfigTimerClock error : read buffer received errorcode %d\n", recBuff[6]); return recBuff[6]; } return 0; } long ehFeedback(HANDLE hDevice, uint8 *inIOTypesDataBuff, long inIOTypesDataSize, uint8 *outErrorcode, uint8 *outErrorFrame, uint8 *outDataBuff, long outDataSize) { uint8 *sendBuff, *recBuff; uint16 checksumTotal; int sendChars, recChars, sendDWSize, recDWSize; int commandBytes, ret, i; ret = 0; commandBytes = 6; if( ((sendDWSize = inIOTypesDataSize + 1)%2) != 0 ) sendDWSize++; if( ((recDWSize = outDataSize + 3)%2) != 0 ) recDWSize++; sendBuff = (uint8 *)malloc(sizeof(uint8)*(commandBytes + sendDWSize)); recBuff = (uint8 *)malloc(sizeof(uint8)*(commandBytes + recDWSize)); if( sendBuff == NULL || recBuff == NULL ) { ret = -1; goto cleanmem; } sendBuff[sendDWSize + commandBytes - 1] = 0; /* Setting up Feedback command */ sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = sendDWSize/2; //Number of data words (.5 word for echo, 1.5 // words for IOTypes) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo for( i = 0; i < inIOTypesDataSize; i++ ) sendBuff[i+commandBytes+1] = inIOTypesDataBuff[i]; extendedChecksum(sendBuff, (sendDWSize+commandBytes)); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, (sendDWSize+commandBytes))) < sendDWSize+commandBytes ) { if( sendChars == 0 ) printf("ehFeedback error : write failed\n"); else printf("ehFeedback error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, (commandBytes+recDWSize))) < commandBytes+recDWSize ) { if( recChars == -1 ) { printf("ehFeedback error : read failed\n"); ret = -1; goto cleanmem; } else if( recChars < 8 ) { printf("ehFeedback error : response buffer is too small\n"); ret = -1; goto cleanmem; } else printf("ehFeedback error : did not read all of the expected buffer (received %d, expected %d )\n", recChars, commandBytes+recDWSize); } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ehFeedback error : read buffer has bad checksum16(MSB)\n"); ret = -1; goto cleanmem; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ehFeedback error : read buffer has bad checksum16(LBS)\n"); ret = -1; goto cleanmem; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehFeedback error : read buffer has bad checksum8\n"); ret = -1; goto cleanmem; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("ehFeedback error : read buffer has wrong command bytes \n"); ret = -1; goto cleanmem; } *outErrorcode = recBuff[6]; *outErrorFrame = recBuff[7]; for( i = 0; i+commandBytes+3 < recChars && i < outDataSize; i++ ) outDataBuff[i] = recBuff[i+commandBytes+3]; cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; }
499
./exodriver/examples/U3/u3EFunctions.c
//Author: LabJack //April 7, 2008 //This examples demonstrates how to read from analog inputs (AIN) and digital //inputs(FIO), set analog outputs (DAC) and digital outputs (FIO), and how to //configure and enable timers and counters and read input timers and counters //values using the "easy" functions. #include "u3.h" #include <unistd.h> int main(int argc, char **argv) { HANDLE hDevice; u3CalibrationInfo caliInfo; int localID; long DAC1Enable, error; //Open first found U3 over USB localID = -1; if( (hDevice = openUSBConnection(localID)) == NULL ) goto done; //Get calibration information from U3 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; /* Note: The eAIN, eDAC, eDI, and eDO "easy" functions have the ConfigIO parameter. If calling, for example, eAIN to read AIN3 in a loop, set the ConfigIO parameter to 1 (True) on the first iteration so that the ConfigIO low-level function is called to ensure that channel 3 is set to an analog input. For the rest of the iterations in the loop, set the ConfigIO parameter to 0 (False) since the channel is already set as analog. */ //Set DAC0 to 2.1 volts. printf("Calling eDAC to set DAC0 to 2.1 V\n"); if( (error = eDAC(hDevice, &caliInfo, 0, 0, 2.1, 0, 0, 0)) != 0 ) goto close; sleep(1); /* Note: The eAIN "easy" function has the DAC1Enable parameter that needs to be set to calculate the correct voltage. In addition to the earlier note, if running eAIN in a loop, set ConfigIO to 1 (True) on the first iteration to also set the output of the DAC1Enable parameter with the current setting on the U3. For the rest of the iterations, set ConfigIO to 0 (False) and use the outputted DAC1Enable parameter from the first interation from then on. If DAC1 is enabled/disabled from a later eDAC or ConfigIO low-level call, change the DAC1Enable parameter accordingly or make another eAIN call with the ConfigIO parameter set to 1. */ //Read the single-ended voltage from AIN3 printf("\nCalling eAIN to read voltage from AIN3\n"); double dblVoltage; if( (error = eAIN(hDevice, &caliInfo, 1, &DAC1Enable, 3, 31, &dblVoltage, 0, 0, 0, 0, 0, 0)) != 0 ) goto close; printf("AIN3 value = %.3f\n", dblVoltage); //Set FIO5 to output-high printf("\nCalling eDO to set FIO5 to output-high\n"); if( (error = eDO(hDevice, 1, 5, 1)) != 0 ) goto close; //Read state of FIO4 printf("\nCalling eDI to read the state of FIO4\n"); long lngState; if( (error = eDI(hDevice, 1, 4, &lngState)) != 0 ) goto close; printf("FIO4 state = %ld\n", lngState); //Enable and configure 1 output timer and 1 input timer, and enable counter0 printf("\nCalling eTCConfig to enable and configure 1 output timer (Timer0) and 1 input timer (Timer1), and enable counter0\n"); long alngEnableTimers[2] = {1, 1}; //Enable Timer0-Timer1 long alngTimerModes[2] = {LJ_tmPWM8, LJ_tmRISINGEDGES32}; //Set timer modes double adblTimerValues[2] = {16384, 0}; //Set PWM8 duty-cycles to 75% long alngEnableCounters[2] = {1, 0}; //Enable Counter0 if( (error = eTCConfig(hDevice, alngEnableTimers, alngEnableCounters, 4, LJ_tc48MHZ, 0, alngTimerModes, adblTimerValues, 0, 0)) != 0 ) goto close; printf("\nWaiting for 1 second...\n"); sleep(1); //Read and reset the input timer (Timer1), read and reset Counter0, and //update the value (duty-cycle) of the output timer (Timer0) printf("\nCalling eTCValues to read and reset the input Timer1 and Counter0, and update the value (duty-cycle) of the output Timer0\n"); long alngReadTimers[2] = {0, 1}; //Read Timer1 long alngUpdateResetTimers[2] = {1, 0}; //Update timer0 long alngReadCounters[2] = {1, 0}; //Read Counter0 long alngResetCounters[2] = {0, 0}; //Reset no Counters double adblCounterValues[2] = {0, 0}; adblTimerValues[0] = 32768; //Change Timer0 duty-cycle to 50% if( (error = eTCValues(hDevice, alngReadTimers, alngUpdateResetTimers, alngReadCounters, alngResetCounters, adblTimerValues, adblCounterValues, 0, 0)) != 0 ) goto close; printf("Timer1 value = %.0f\n", adblTimerValues[1]); printf("Counter0 value = %.0f\n", adblCounterValues[0]); //Disable all timers and counters alngEnableTimers[0] = 0; alngEnableTimers[1] = 0; alngEnableCounters[0] = 0; alngEnableCounters[1] = 0; if( (error = eTCConfig(hDevice, alngEnableTimers, alngEnableCounters, 4, 0, 0, alngTimerModes, adblTimerValues, 0, 0)) != 0 ) goto close; printf("\nCalling eTCConfig to disable all timers and counters\n"); close: if( error > 0 ) printf("Received an error code of %ld\n", error); closeUSBConnection(hDevice); done: return 0; }
500
./exodriver/examples/U3/u3LJTDAC.c
//Author: LabJack //December 27, 2011 //Communicates with an LJTick-DAC using low level functions. The LJTDAC should //be plugged into FIO4/FIO5 for this example. //Tested with U3 firmware V1.44, and requires hardware version 1.21 or greater. #include "u3.h" #include <unistd.h> int configIO_example(HANDLE hDevice); int checkI2CErrorcode(uint8 errorcode); int LJTDAC_example(HANDLE hDevice, u3TdacCalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; u3TdacCalibrationInfo caliInfo; //Opening first found U3 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; if( configIO_example(hDevice) != 0 ) goto close; //Getting calibration information from LJTDAC if( getTdacCalibrationInfo(hDevice, &caliInfo, 4) < 0 ) goto close; LJTDAC_example(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Sends a ConfigIO low-level command that configures the FIO4 and FIO5 lines to //digital. int configIO_example(HANDLE hDevice) { uint8 sendBuff[12], recBuff[12]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 7; //Writemask : Setting writemask for TimerCounterConfig (bit 0), // DAC1Enable (bit 1) and FIOAnalog (bit 2) sendBuff[7] = 0; //Reserved sendBuff[8] = 64; //TimerCounterConfig : disable timers and counters. set // TimerCounterPinOffset to 4 (bits 4-7) sendBuff[9] = 0; //DAC1 enable : disabling sendBuff[10] = 0; //FIOAnalog : setting FIO channels to digital sendBuff[11] = 0; //EIOAnalog : Not setting anything extendedChecksum(sendBuff, 12); //Sending command to U3 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 12)) < 12 ) { if( sendChars == 0 ) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U3 if( (recChars = LJUSB_Read(hDevice, recBuff, 12)) < 12 ) { if( recChars == 0 ) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 12); if( (uint8)((checksumTotal / 256 ) & 0xFF) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x03) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } if( recBuff[8] != 64 ) { printf("ConfigIO error : TimerCounterConfig did not get set correctly\n"); return -1; } if( recBuff[10] != 0 && recBuff[10] != (uint8)(0x0F) ) { printf("ConfigIO error : FIOAnalog did not set correctly\n"); return -1; } return 0; } int checkI2CErrorcode(uint8 errorcode) { if(errorcode != 0) { printf("I2C error : received errorcode %d in response\n", errorcode); return -1; } return 0; } int LJTDAC_example(HANDLE hDevice, u3TdacCalibrationInfo *caliInfo) { uint8 options, speedAdjust, sdaPinNum, sclPinNum; uint8 address, numBytesToSend, numBytesToReceive, errorcode; uint8 bytesCommand[5], bytesResponse[64], ackArray[4]; uint16 binaryVoltage; int err, i; err = 0; //Setting up parts I2C command that will remain the same throughout this //example options = 0; //I2COptions : 0 speedAdjust = 0; //SpeedAdjust : 0 (for max communication speed of about //130 kHz) sdaPinNum = 5; //SDAPinNum : FIO5 connected to pin DIOB sclPinNum = 4; //SCLPinNum : FIO4 connected to pin DIOA /* Set DACA to 1.2 volts. */ //Setting up I2C command //Make note that the I2C command can only update 1 DAC channel at a time. address = (uint8)(0x24); //Address : h0x24 is the address for DAC numBytesToSend = 3; //NumI2CByteToSend : 3 bytes to specify DACA and the //value numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only setting //the value of the DAC bytesCommand[0] = (uint8)(0x30); //LJTDAC command byte : h0x30 (DACA) getTdacBinVoltCalibrated(caliInfo, 0, 1.2, &binaryVoltage); bytesCommand[1] = (uint8)(binaryVoltage/256); //value (high) bytesCommand[2] = (uint8)(binaryVoltage & (0x00FF)); //value (low) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("DACA set to 1.2 volts\n\n"); /* Set DACB to 2.3 volts. */ //Setting up I2C command address = (uint8)(0x24); //Address : h0x24 is the address for DAC numBytesToSend = 3; //NumI2CByteToSend : 3 bytes to specify DACB and the //value numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only setting //the value of the DAC bytesCommand[0] = (uint8)(0x31); //LJTDAC command byte : h0x31 (DACB) getTdacBinVoltCalibrated(caliInfo, 1, 2.3, &binaryVoltage); bytesCommand[1] = (uint8)(binaryVoltage/256); //value (high) bytesCommand[2] = (uint8)(binaryVoltage & (0x00FF)); //value (low) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("DACB set to 2.3 volts\n\n"); /* More advanced operations. */ /* Display LJTDAC calibration constants. Code for getting the calibration * constants is in the getLJTDACCalibrationInfo function in the u3.c file. */ printf("DACA Slope = %.1f bits/volt\n", caliInfo->ccConstants[0]); printf("DACA Offset = %.1f bits\n", caliInfo->ccConstants[1]); printf("DACB Slope = %.1f bits/volt\n", caliInfo->ccConstants[2]); printf("DACB Offset = %.1f bits\n\n", caliInfo->ccConstants[3]); /* Read the serial number. */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 4; //NumI2CBytesToReceive : getting 4 bytes starting at //EEPROM address specified in I2CByte0 bytesCommand[0] = 96; //I2CByte0 : Memory Address, starting at address 96 //(Serial Number) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("LJTDAC Serial Number = %u\n\n", (bytesResponse[0] + bytesResponse[1]*256 + bytesResponse[2]*65536 + bytesResponse[3]*16777216)); /* User memory example. We will read the memory, update a few elements, and * write the memory. The user memory is just stored as bytes, so almost any * information can be put in there such as integers, doubles, or strings. */ /* Read the user memory : need to perform 2 I2C calls since command/response packets can only be 64 bytes in size */ //Setting up 1st I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 52; //NumI2CBytesToReceive : getting 52 bytes starting //at EEPROM address specified in I2CByte0 bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 //(User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Setting up 2nd I2C command numBytesToReceive = 12; //NumI2CBytesToReceive : getting 12 bytes starting //at EEPROM address specified in I2CByte0 bytesCommand[0] = 52; //I2CByte0 : Memory Address, starting at address 52 //(User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse + 52); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Display the first 4 elements. printf("Read User Mem [0-3] = %d, %d, %d, %d\n", bytesResponse[0], bytesResponse[1], bytesResponse[2], bytesResponse[3]); /* Create 4 new pseudo-random numbers to write. We will update the first * 4 elements of user memory, but the rest will be unchanged. */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 5; //NumI2CByteToSend : 1 byte for the EEPROM address and //the rest for the bytes to write numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only writing to memory bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 //(User Area) srand((unsigned int)getTickCount()); for(i = 1; i < 5; i++) { //I2CByte : byte in user memory bytesCommand[i] = (uint8)(255 * ((float)rand()/RAND_MAX)); } printf("Write User Mem [0-3] = %d, %d, %d, %d\n", bytesCommand[1], bytesCommand[2], bytesCommand[3], bytesCommand[4]); //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Delay for 2 ms to allow the EEPROM to finish writing. //Re-read the user memory. usleep(2000); //Setting up 1st I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 52; //NumI2CBytesToReceive : getting 52 bytes starting //at EEPROM address specified in I2CByte0 bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 //(User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Setting up 2nd I2C command numBytesToReceive = 12; //NumI2CBytesToReceive : getting 12 bytes starting //at EEPROM address specified in I2CByte0 bytesCommand[0] = 52; //I2CByte0 : Memory Address, starting at address 52 //(User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse + 52); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Display the first 4 elements. printf("Read User Mem [0-3] = %d, %d, %d, %d\n", bytesResponse[0], bytesResponse[1], bytesResponse[2], bytesResponse[3]); return err; }