Esempio n. 1
0
/**
 * vba_project_read:
 * @vba: #GsfInfileMSVBA
 * @err: (allow-none): place to store a #GError if anything goes wrong
 *
 * Read an VBA dirctory and its project file.
 * along the way.
 *
 * Returns: %FALSE on error setting @err if it is supplied.
 **/
static gboolean
vba_project_read (GsfInfileMSVBA *vba, GError **err)
{
	/* NOTE : This seems constant, find some confirmation */
	static guint8 const signature[]	  = { 0xcc, 0x61 };
	static struct {
		guint8 const signature[4];
		char const * const name;
		int const vba_version;
		gboolean const is_mac;
	} const  versions [] = {
		{ { 0x5e, 0x00, 0x00, 0x01 }, "Office 97",              5, FALSE},
		{ { 0x5f, 0x00, 0x00, 0x01 }, "Office 97 SR1",          5, FALSE },
		{ { 0x65, 0x00, 0x00, 0x01 }, "Office 2000 alpha?",     6, FALSE },
		{ { 0x6b, 0x00, 0x00, 0x01 }, "Office 2000 beta?",      6, FALSE },
		{ { 0x6d, 0x00, 0x00, 0x01 }, "Office 2000",            6, FALSE },
		{ { 0x6f, 0x00, 0x00, 0x01 }, "Office 2000",            6, FALSE },
		{ { 0x70, 0x00, 0x00, 0x01 }, "Office XP beta 1/2",     6, FALSE },
		{ { 0x73, 0x00, 0x00, 0x01 }, "Office XP",              6, FALSE },
		{ { 0x76, 0x00, 0x00, 0x01 }, "Office 2003",            6, FALSE },
		{ { 0x79, 0x00, 0x00, 0x01 }, "Office 2003",            6, FALSE },
		{ { 0x60, 0x00, 0x00, 0x0e }, "MacOffice 98",           5, TRUE },
		{ { 0x62, 0x00, 0x00, 0x0e }, "MacOffice 2001",         5, TRUE },
		{ { 0x63, 0x00, 0x00, 0x0e }, "MacOffice X",		6, TRUE },
		{ { 0x64, 0x00, 0x00, 0x0e }, "MacOffice 2004",         6, TRUE },
	};

	guint8 const *data;
	unsigned i, count, len;
	gunichar2 *uni_name;
	char *name;
	GsfInput *dir;

	dir = gsf_infile_child_by_name (vba->source, "dir");
	if (dir == NULL) {
		if (err != NULL)
			*err = g_error_new (gsf_input_error_id (), 0,
					    _("Can't find the VBA directory stream"));
		return FALSE;
	}

	if (gsf_input_seek (dir, 0, G_SEEK_SET) ||
	    NULL == (data = gsf_input_read (dir, VBA56_DIRENT_HEADER_SIZE, NULL)) ||
	    0 != memcmp (data, signature, sizeof (signature))) {
		if (err != NULL)
			*err = g_error_new (gsf_input_error_id (), 0,
					    _("No VBA signature"));
		return FALSE;
	}

	for (i = 0 ; i < G_N_ELEMENTS (versions); i++)
		if (!memcmp (data+2, versions[i].signature, 4))
			break;

	if (i >= G_N_ELEMENTS (versions)) {
		if (err != NULL)
			*err = g_error_new (gsf_input_error_id (), 0,
					    _("Unknown VBA version signature 0x%x%x%x%x"),
					    data[2], data[3], data[4], data[5]);
		return FALSE;
	}

	puts (versions[i].name);

	/* these depend strings seem to come in 2 blocks */
	count = GSF_LE_GET_GUINT16 (data + VBA56_DIRENT_RECORD_COUNT);
	for (; count > 0 ; count--) {
		if (NULL == ((data = gsf_input_read (dir, 2, NULL))))
			break;
		len = GSF_LE_GET_GUINT16 (data);
		if (NULL == ((data = gsf_input_read (dir, len, NULL)))) {
			printf ("len == 0x%x ??\n", len);
			break;
		}

		uni_name = g_new0 (gunichar2, len/2 + 1);

		/* be wary about endianness */
		for (i = 0 ; i < len ; i += 2)
			uni_name [i/2] = GSF_LE_GET_GUINT16 (data + i);
		name = g_utf16_to_utf8 (uni_name, -1, NULL, NULL, NULL);
		g_free (uni_name);

		printf ("%d %s\n", count, name);

		/* ignore this blob ???? */
		if (!strncmp ("*\\G", name, 3)) {
			if (NULL == ((data = gsf_input_read (dir, 12, NULL)))) {
				printf ("len == 0x%x ??\n", len);
				break;
			}
		}

		g_free (name);
	}

	g_return_val_if_fail (count == 0, FALSE);

	return TRUE;
}
static GstPad *
find_or_create_demux_pad_for_ssrc (GstRtpSsrcDemux * demux, guint32 ssrc,
    PadType padtype)
{
  GstPad *rtp_pad, *rtcp_pad;
  GstElementClass *klass;
  GstPadTemplate *templ;
  gchar *padname;
  GstRtpSsrcDemuxPad *demuxpad;
  GstPad *retpad;
  gulong rtp_block, rtcp_block;

  GST_PAD_LOCK (demux);

  demuxpad = find_demux_pad_for_ssrc (demux, ssrc);
  if (demuxpad != NULL) {
    gboolean forward = FALSE;

    switch (padtype) {
      case RTP_PAD:
        retpad = gst_object_ref (demuxpad->rtp_pad);
        if (!demuxpad->pushed_initial_rtp_events) {
          forward = TRUE;
          demuxpad->pushed_initial_rtp_events = TRUE;
        }
        break;
      case RTCP_PAD:
        retpad = gst_object_ref (demuxpad->rtcp_pad);
        if (!demuxpad->pushed_initial_rtcp_events) {
          forward = TRUE;
          demuxpad->pushed_initial_rtcp_events = TRUE;
        }
        break;
      default:
        retpad = NULL;
        g_assert_not_reached ();
    }

    GST_PAD_UNLOCK (demux);

    if (forward)
      forward_initial_events (demux, ssrc, retpad, padtype);
    return retpad;
  }

  GST_DEBUG_OBJECT (demux, "creating new pad for SSRC %08x", ssrc);

  klass = GST_ELEMENT_GET_CLASS (demux);
  templ = gst_element_class_get_pad_template (klass, "src_%u");
  padname = g_strdup_printf ("src_%u", ssrc);
  rtp_pad = gst_pad_new_from_template (templ, padname);
  g_free (padname);

  templ = gst_element_class_get_pad_template (klass, "rtcp_src_%u");
  padname = g_strdup_printf ("rtcp_src_%u", ssrc);
  rtcp_pad = gst_pad_new_from_template (templ, padname);
  g_free (padname);

  /* wrap in structure and add to list */
  demuxpad = g_new0 (GstRtpSsrcDemuxPad, 1);
  demuxpad->ssrc = ssrc;
  demuxpad->rtp_pad = rtp_pad;
  demuxpad->rtcp_pad = rtcp_pad;

  gst_pad_set_element_private (rtp_pad, demuxpad);
  gst_pad_set_element_private (rtcp_pad, demuxpad);

  demux->srcpads = g_slist_prepend (demux->srcpads, demuxpad);

  gst_pad_set_query_function (rtp_pad, gst_rtp_ssrc_demux_src_query);
  gst_pad_set_iterate_internal_links_function (rtp_pad,
      gst_rtp_ssrc_demux_iterate_internal_links_src);
  gst_pad_set_event_function (rtp_pad, gst_rtp_ssrc_demux_src_event);
  gst_pad_use_fixed_caps (rtp_pad);
  gst_pad_set_active (rtp_pad, TRUE);

  gst_pad_set_event_function (rtcp_pad, gst_rtp_ssrc_demux_src_event);
  gst_pad_set_iterate_internal_links_function (rtcp_pad,
      gst_rtp_ssrc_demux_iterate_internal_links_src);
  gst_pad_use_fixed_caps (rtcp_pad);
  gst_pad_set_active (rtcp_pad, TRUE);

  if (padtype == RTP_PAD) {
    demuxpad->pushed_initial_rtp_events = TRUE;
    forward_initial_events (demux, ssrc, rtp_pad, padtype);
  } else if (padtype == RTCP_PAD) {
    demuxpad->pushed_initial_rtcp_events = TRUE;
    forward_initial_events (demux, ssrc, rtcp_pad, padtype);
  } else {
    g_assert_not_reached ();
  }

  gst_element_add_pad (GST_ELEMENT_CAST (demux), rtp_pad);
  gst_element_add_pad (GST_ELEMENT_CAST (demux), rtcp_pad);

  switch (padtype) {
    case RTP_PAD:
      retpad = gst_object_ref (demuxpad->rtp_pad);
      break;
    case RTCP_PAD:
      retpad = gst_object_ref (demuxpad->rtcp_pad);
      break;
    default:
      retpad = NULL;
      g_assert_not_reached ();
  }

  gst_object_ref (rtp_pad);
  gst_object_ref (rtcp_pad);

  rtp_block = gst_pad_add_probe (rtp_pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
      NULL, NULL, NULL);
  rtcp_block = gst_pad_add_probe (rtcp_pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
      NULL, NULL, NULL);

  GST_PAD_UNLOCK (demux);

  g_signal_emit (G_OBJECT (demux),
      gst_rtp_ssrc_demux_signals[SIGNAL_NEW_SSRC_PAD], 0, ssrc, rtp_pad);

  gst_pad_remove_probe (rtp_pad, rtp_block);
  gst_pad_remove_probe (rtcp_pad, rtcp_block);

  gst_object_unref (rtp_pad);
  gst_object_unref (rtcp_pad);

  return retpad;
}
Esempio n. 3
0
RTSP_media *rtsp_media_create( void )
{
	return g_new0(RTSP_media, 1);
}
Esempio n. 4
0
File: fmon.c Progetto: bhuisgen/fmon
gint
main(gint argc, gchar *argv[])
{
  GError *error = NULL;
  gboolean daemon;
  gint ret;

  setlocale(LC_ALL, "");
  bindtextdomain(PACKAGE, LOCALEDIR);
  textdomain(PACKAGE);

  if (glib_check_version(2, 6, 0))
    {
      g_error(N_("GLib version 2.6.0 or above is needed"));
    }

#ifdef DEBUG
  g_type_init_with_debug_flags(G_TYPE_DEBUG_MASK);
#else
  g_type_init();
#endif

  app = g_new0(application_t, 1);
  app->loop = g_main_loop_new(NULL, TRUE);
  atexit(cleanup);

  parse_command_line(argc, argv);

  if (app->config_file && !load_config())
    exit(2);

  app->watchers = init_watchers();
  if (!app->watchers)
    exit(3);

  app->logger = init_logger();
  if (!app->logger)
    {
      g_printerr("%s\n", N_("Failed to create events logger."));

      exit(4);
    }

  daemon = g_key_file_get_boolean(app->settings, CONFIG_GROUP_MAIN,
      CONFIG_KEY_MAIN_DAEMONIZE, &error);
  if (error)
    {
      daemon = CONFIG_KEY_MAIN_DAEMONIZE_DEFAULT;

      g_error_free(error);
      error = NULL;
    }
  if (daemon)
    {
      gchar *pid_file, *user, *group;

      pid_file = g_key_file_get_string(app->settings, CONFIG_GROUP_MAIN,
          CONFIG_KEY_MAIN_PIDFILE, &error);
      if (error)
        {
          pid_file = g_strdup(CONFIG_KEY_MAIN_PIDFILE_DEFAULT);

          g_error_free(error);
          error = NULL;
        }

      user = g_key_file_get_string(app->settings, CONFIG_GROUP_MAIN,
          CONFIG_KEY_MAIN_USER, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      group = g_key_file_get_string(app->settings, CONFIG_GROUP_MAIN,
          CONFIG_KEY_MAIN_GROUP, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      ret = daemonize(pid_file, user, group);

      g_free(pid_file);
      if (user)
        g_free(user);
      if (group)
        g_free(group);

      if (ret < 0)
        {
          LOG_ERROR("%s: %d", N_("failed to daemonize, error code"), ret);

          exit(5);
        }

      app->daemon = TRUE;
      LOG_INFO("%s %s", PACKAGE, N_("daemon started"));
    }

  signal(SIGPIPE, sigpipe);
  signal(SIGINT, sigint);
  signal(SIGTERM, sigterm);

  if (app->daemon)
    {
      signal(SIGHUP, sighup);
      signal(SIGUSR1, sigusr1);
      signal(SIGUSR2, sigusr2);
    }
  else
    {
      signal(SIGHUP, SIG_IGN);
      signal(SIGUSR1, SIG_IGN);
      signal(SIGUSR2, SIG_IGN);
    }

  start_monitors();

  g_main_loop_run(app->loop);

  return 0;
}
Esempio n. 5
0
PidginXferDialog *
pidgin_xfer_dialog_new(void)
{
	PidginXferDialog *dialog;
	GtkWidget *window;
	GtkWidget *vbox1, *vbox2;
	GtkWidget *sw;
	GtkWidget *button;
	GtkWidget *expander;
	GtkWidget *table;
	GtkWidget *checkbox;

	dialog = g_new0(PidginXferDialog, 1);
	dialog->keep_open =
		purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/filetransfer/keep_open");
	dialog->auto_clear =
		purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/filetransfer/clear_finished");

	/* Create the window. */
	dialog->window = window = pidgin_create_dialog(_("File Transfers"), PIDGIN_HIG_BORDER, "file transfer", TRUE);

	g_signal_connect(G_OBJECT(window), "delete_event",
					 G_CALLBACK(delete_win_cb), dialog);

	/* Create the parent vbox for everything. */
	vbox1 = pidgin_dialog_get_vbox_with_properties(GTK_DIALOG(window), FALSE, PIDGIN_HIG_BORDER);

	/* Create the main vbox for top half of the window. */
	vbox2 = gtk_vbox_new(FALSE, PIDGIN_HIG_BOX_SPACE);
	gtk_box_pack_start(GTK_BOX(vbox1), vbox2, TRUE, TRUE, 0);
	gtk_widget_show(vbox2);

	/* Setup the listbox */
	sw = setup_tree(dialog);
	gtk_box_pack_start(GTK_BOX(vbox2), sw, TRUE, TRUE, 0);
	gtk_widget_set_size_request(sw,-1, 140);

	/* "Close this window when all transfers finish" */
	checkbox = gtk_check_button_new_with_mnemonic(
			_("Close this window when all transfers _finish"));
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox),
								 !dialog->keep_open);
	g_signal_connect(G_OBJECT(checkbox), "toggled",
					 G_CALLBACK(toggle_keep_open_cb), dialog);
	gtk_box_pack_start(GTK_BOX(vbox2), checkbox, FALSE, FALSE, 0);
	gtk_widget_show(checkbox);

	/* "Clear finished transfers" */
	checkbox = gtk_check_button_new_with_mnemonic(
			_("C_lear finished transfers"));
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox),
								 dialog->auto_clear);
	g_signal_connect(G_OBJECT(checkbox), "toggled",
					 G_CALLBACK(toggle_clear_finished_cb), dialog);
	gtk_box_pack_start(GTK_BOX(vbox2), checkbox, FALSE, FALSE, 0);
	gtk_widget_show(checkbox);

	/* "Download Details" arrow */
	expander = gtk_expander_new_with_mnemonic(_("File transfer _details"));
	dialog->expander = expander;
	gtk_box_pack_start(GTK_BOX(vbox2), expander, FALSE, FALSE, 0);
	gtk_widget_show(expander);

	gtk_widget_set_sensitive(expander, FALSE);

	/* The table of information. */
	table = make_info_table(dialog);
	gtk_container_add(GTK_CONTAINER(expander), table);
	gtk_widget_show(table);

	/* Open button */
	button = pidgin_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_OPEN, G_CALLBACK(open_button_cb), dialog);
	gtk_widget_set_sensitive(button, FALSE);
	dialog->open_button = button;

	/* Pause button */
	button = pidgin_dialog_add_button(GTK_DIALOG(window), _("_Pause"), G_CALLBACK(pause_button_cb), dialog);
	gtk_widget_set_sensitive(button, FALSE);
	dialog->pause_button = button;

	/* Resume button */
	button = pidgin_dialog_add_button(GTK_DIALOG(window), _("_Resume"), G_CALLBACK(resume_button_cb), dialog);
	gtk_widget_set_sensitive(button, FALSE);
	dialog->resume_button = button;

	/* Remove button */
	button = pidgin_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_REMOVE, G_CALLBACK(remove_button_cb), dialog);
	gtk_widget_hide(button);
	dialog->remove_button = button;

	/* Stop button */
	button = pidgin_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_STOP, G_CALLBACK(stop_button_cb), dialog);
	gtk_widget_set_sensitive(button, FALSE);
	dialog->stop_button = button;

	/* Close button */
	button = pidgin_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_CLOSE, G_CALLBACK(close_button_cb), dialog);
	dialog->close_button = button;

#ifdef _WIN32
	g_signal_connect(G_OBJECT(dialog->window), "show",
		G_CALLBACK(winpidgin_ensure_onscreen), dialog->window);
#endif

	return dialog;
}
Esempio n. 6
0
static void
vtable_dialog_init (VtableDialog *dlg, G_GNUC_UNUSED VtableDialogClass *klass)
{
	dlg->priv = g_new0 (VtableDialogPrivate, 1);
}
Esempio n. 7
0
browserHistory *
browser_history_new (void)
{	
	return (browserHistory *)g_new0 (browserHistory, 1);
}
Esempio n. 8
0
MdmDisplay *
mdm_display_alloc (gint id, const gchar *command, const gchar *device)
{
    gchar hostname[1024];
    MdmDisplay *d;

    hostname[1023] = '\0';
    if (gethostname (hostname, 1023) == -1)
            strcpy (hostname, "localhost.localdomain");

    d = g_new0 (MdmDisplay, 1);

    d->logout_action = MDM_LOGOUT_ACTION_NONE;
    d->authfile = NULL;
    d->authfile_mdm = NULL;
    d->auths = NULL;
    d->userauth = NULL;
    d->command = g_strdup (command);
    d->cookie = NULL;
    d->dispstat = DISPLAY_UNBORN;
    d->greetpid = 0;
    d->name = g_strdup_printf (":%d", id);
    d->hostname = g_strdup (hostname);
    d->windowpath = NULL;
    /* Not really used for not XDMCP */
    memset (&(d->addr), 0, sizeof (d->addr));
    d->dispnum = id;
    d->servpid = 0;
    d->servstat = SERVER_DEAD;
    d->sesspid = 0;
    d->slavepid = 0;
    d->type = TYPE_STATIC;
    d->attached = TRUE;
    d->dsp = NULL;
    d->screenx = 0; /* xinerama offset */
    d->screeny = 0;

    d->handled = TRUE;
    d->tcp_disallowed = FALSE;

    d->priority = 0;
    d->vt = -1;
    d->vtnum = -1;
    if (device != NULL)
	d->device_name = g_strdup (device);
    else
	d->device_name = NULL;

    d->x_servers_order = -1;

    d->last_loop_start_time = 0;
    d->last_start_time = 0;
    d->retry_count = 0;
    d->sleep_before_run = 0;
    d->login = NULL;
    d->preset_user = NULL;

    d->timed_login_ok = FALSE;

    d->slave_notify_fd = -1;
    d->master_notify_fd = -1;

    d->xsession_errors_bytes = 0;
    d->xsession_errors_fd = -1;
    d->session_output_fd = -1;

    d->chooser_output_fd = -1;
    d->chooser_last_line = NULL;

    d->theme_name = NULL;

    return d;
}
Esempio n. 9
0
static BDMDExamineData* get_examine_data_from_table (GHashTable *table, gboolean free_table, GError **error) {
    BDMDExamineData *data = g_new0 (BDMDExamineData, 1);
    gchar *value = NULL;
    gchar *first_space = NULL;
    BSSize size = NULL;
    BSError *bs_error = NULL;
    struct tm tm;
    char time_str[20];
    gchar *name_str = NULL;

    data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "Raid Level"));
    if (!(data->level))
        /* BUG: mdadm outputs "RAID Level" for some metadata formats (rhbz#1380034) */
        data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "RAID Level"));

    value = (gchar*) g_hash_table_lookup (table, "Raid Devices");
    if (!value)
        /* BUG: mdadm outputs "RAID Devices" for some metadata formats (rhbz#1380034) */
        value = (gchar*) g_hash_table_lookup (table, "RAID Devices");
    if (value)
        data->num_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->num_devices = 0;

    name_str = ((gchar*) g_hash_table_lookup (table, "Name"));
    if (name_str) {
        g_strstrip (name_str);
        first_space = strchr (name_str, ' ');
        if (first_space)
            *first_space = '\0';
        data->name = g_strdup (name_str);
    }

    value = (gchar*) g_hash_table_lookup (table, "Array Size");
    if (value) {
        first_space = strchr (value, ' ');
        if (first_space)
            *first_space = '\0';
        if (value && first_space)
            /* Array Size is in KiB */
            data->size = g_ascii_strtoull (value, NULL, 0) * 1024;
    } else
        data->size = 0;

    data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "Array UUID"));
    if (!data->uuid)
        /* also try just "UUID" which may be reported e.g for IMSM FW RAID */
        data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "UUID"));

    value = (gchar*) g_hash_table_lookup (table, "Update Time");
    if (value) {
        memset(&tm, 0, sizeof(struct tm));
        strptime(value, "%a %b %e %H:%M:%S %Y", &tm);
        strftime(time_str, sizeof(time_str), "%s" , &tm);

        data->update_time = g_ascii_strtoull (time_str, NULL, 0);
    } else
        data->update_time = 0;

    data->dev_uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "Device UUID"));

    value = (gchar*) g_hash_table_lookup (table, "Events");
    if (value)
        data->events = g_ascii_strtoull (value, NULL, 0);
    else
        data->events = 0;

    value = (gchar*) g_hash_table_lookup (table, "Version");
    if (value)
        data->metadata = g_strdup (value);
    else
        data->metadata = NULL;

    value = (gchar*) g_hash_table_lookup (table, "Chunk Size");
    if (value) {
        size = bs_size_new_from_str (value, &bs_error);
        if (size) {
            data->chunk_size = bs_size_get_bytes (size, NULL, &bs_error);
            bs_size_free (size);
        }

        if (bs_error) {
            g_set_error (error, BD_MD_ERROR, BD_MD_ERROR_PARSE,
                         "Failed to parse chunk size from mdexamine data: %s", bs_error->msg);
            bs_clear_error (&bs_error);
        }
    } else
        data->chunk_size = 0;

    if (free_table)
        g_hash_table_destroy (table);

    return data;
}
Esempio n. 10
0
static gpointer
gdk_pixbuf__jpeg_image_begin_load (GdkPixbufModuleSizeFunc size_func,
				   GdkPixbufModulePreparedFunc prepared_func, 
				   GdkPixbufModuleUpdatedFunc updated_func,
				   gpointer user_data,
                                   GError **error)
{
	JpegProgContext *context;
	my_source_mgr   *src;

	context = g_new0 (JpegProgContext, 1);
	context->size_func = size_func;
	context->prepared_func = prepared_func;
	context->updated_func  = updated_func;
	context->user_data = user_data;
	context->pixbuf = NULL;
	context->got_header = FALSE;
	context->did_prescan = FALSE;
	context->src_initialized = FALSE;
	context->in_output = FALSE;

        /* From jpeglib.h: "NB: you must set up the error-manager
         * BEFORE calling jpeg_create_xxx". */
	context->cinfo.err = jpeg_std_error (&context->jerr.pub);
	context->jerr.pub.error_exit = fatal_error_handler;
        context->jerr.pub.output_message = output_message_handler;
        context->jerr.error = error;

        if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
                jpeg_destroy_decompress (&context->cinfo);
                g_free(context);
                /* error should have been set by fatal_error_handler () */
                return NULL;
        }

	/* create libjpeg structures */
	jpeg_create_decompress (&context->cinfo);

	context->cinfo.src = (struct jpeg_source_mgr *) g_try_malloc (sizeof (my_source_mgr));
	if (!context->cinfo.src) {
		g_set_error_literal (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                     _("Couldn't allocate memory for loading JPEG file"));
		return NULL;
	}
	memset (context->cinfo.src, 0, sizeof (my_source_mgr));

	src = (my_src_ptr) context->cinfo.src;
	src->pub.init_source = init_source;
	src->pub.fill_input_buffer = fill_input_buffer;
	src->pub.skip_input_data = skip_input_data;
	src->pub.resync_to_restart = jpeg_resync_to_restart;
	src->pub.term_source = term_source;
	src->pub.bytes_in_buffer = 0;
	src->pub.next_input_byte = NULL;

        context->jerr.error = NULL;
        
	return (gpointer) context;
}
Esempio n. 11
0
/*
 * context - from image_begin_load
 * buf - new image data
 * size - length of new image data
 *
 * append image data onto inrecrementally built output image
 */
static gboolean
gdk_pixbuf__jpeg_image_load_increment (gpointer data,
                                       const guchar *buf, guint size,
                                       GError **error)
{
	JpegProgContext *context = (JpegProgContext *)data;
	struct           jpeg_decompress_struct *cinfo;
	my_src_ptr       src;
	guint            num_left, num_copy;
	guint            last_num_left, last_bytes_left;
	guint            spinguard;
	gboolean         first;
	const guchar    *bufhd;
	gint             width, height;
	char             otag_str[5];
	JpegExifContext *exif_context = NULL;
	gboolean	 retval;

	g_return_val_if_fail (context != NULL, FALSE);
	g_return_val_if_fail (buf != NULL, FALSE);

	src = (my_src_ptr) context->cinfo.src;

	cinfo = &context->cinfo;

        context->jerr.error = error;
        
	/* check for fatal error */
	if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
		retval = FALSE;
		goto out;
	}

	/* skip over data if requested, handle unsigned int sizes cleanly */
	/* only can happen if we've already called jpeg_get_header once   */
	if (context->src_initialized && src->skip_next) {
		if (src->skip_next > size) {
			src->skip_next -= size;
			retval = TRUE;
			goto out;
		} else {
			num_left = size - src->skip_next;
			bufhd = buf + src->skip_next;
			src->skip_next = 0;
		}
	} else {
		num_left = size;
		bufhd = buf;
	}

	if (num_left == 0) {
		retval = TRUE;
		goto out;
	}
	/* collect exif data */
	exif_context = g_new0 (JpegExifContext, 1);

	last_num_left = num_left;
	last_bytes_left = 0;
	spinguard = 0;
	first = TRUE;
	while (TRUE) {

		/* handle any data from caller we haven't processed yet */
		if (num_left > 0) {
			if(src->pub.bytes_in_buffer && 
			   src->pub.next_input_byte != src->buffer)
				memmove(src->buffer, src->pub.next_input_byte,
					src->pub.bytes_in_buffer);


			num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
					num_left);

			memcpy(src->buffer + src->pub.bytes_in_buffer, bufhd,num_copy);
			src->pub.next_input_byte = src->buffer;
			src->pub.bytes_in_buffer += num_copy;
			bufhd += num_copy;
			num_left -= num_copy;
		}

                /* did anything change from last pass, if not return */
                if (first) {
                        last_bytes_left = src->pub.bytes_in_buffer;
                        first = FALSE;
                } else if (src->pub.bytes_in_buffer == last_bytes_left
			   && num_left == last_num_left) {
                        spinguard++;
		} else {
                        last_bytes_left = src->pub.bytes_in_buffer;
			last_num_left = num_left;
		}

		/* should not go through twice and not pull bytes out of buf */
		if (spinguard > 2) {
			retval = TRUE;
			goto out;
		}

		/* try to load jpeg header */
		if (!context->got_header) {
			int rc;
		
			jpeg_save_markers (cinfo, JPEG_APP0+1, 0xffff);
			rc = jpeg_read_header (cinfo, TRUE);
			context->src_initialized = TRUE;
			
			if (rc == JPEG_SUSPENDED)
				continue;
			
			context->got_header = TRUE;

			/* parse exif data */
			jpeg_parse_exif (exif_context, cinfo);
		
			width = cinfo->image_width;
			height = cinfo->image_height;
			if (context->size_func) {
				(* context->size_func) (&width, &height, context->user_data);
				if (width == 0 || height == 0) {
					g_set_error_literal (error,
                                                             GDK_PIXBUF_ERROR,
                                                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                                             _("Transformed JPEG has zero width or height."));
					retval = FALSE;
					goto out;
				}
			}
			
			cinfo->scale_num = 1;
			for (cinfo->scale_denom = 2; cinfo->scale_denom <= 8; cinfo->scale_denom *= 2) {
				jpeg_calc_output_dimensions (cinfo);
				if (cinfo->output_width < width || cinfo->output_height < height) {
					cinfo->scale_denom /= 2;
					break;
				}
			}
			jpeg_calc_output_dimensions (cinfo);
			
			context->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 
							  cinfo->output_components == 4 ? TRUE : FALSE,
							  8, 
							  cinfo->output_width,
							  cinfo->output_height);

			if (context->pixbuf == NULL) {
                                g_set_error_literal (error,
                                                     GDK_PIXBUF_ERROR,
                                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                                     _("Couldn't allocate memory for loading JPEG file"));
                                retval = FALSE;
				goto out;
			}
		
		        /* if orientation tag was found set an option to remember its value */
			if (exif_context->orientation != 0) {
				g_snprintf (otag_str, sizeof (otag_str), "%d", exif_context->orientation);
		                gdk_pixbuf_set_option (context->pixbuf, "orientation", otag_str);
		        }

			/* Use pixbuf buffer to store decompressed data */
			context->dptr = context->pixbuf->pixels;
			
			/* Notify the client that we are ready to go */
			if (context->prepared_func)
				(* context->prepared_func) (context->pixbuf,
							    NULL,
							    context->user_data);
			
		} else if (!context->did_prescan) {
			int rc;			
			
			/* start decompression */
			cinfo->buffered_image = cinfo->progressive_mode;
			rc = jpeg_start_decompress (cinfo);
			cinfo->do_fancy_upsampling = FALSE;
			cinfo->do_block_smoothing = FALSE;

			if (rc == JPEG_SUSPENDED)
				continue;

			context->did_prescan = TRUE;
		} else if (!cinfo->buffered_image) {
                        /* we're decompressing unbuffered so
                         * simply get scanline by scanline from jpeg lib
                         */
                        if (! gdk_pixbuf__jpeg_image_load_lines (context,
                                                                 error)) {
                                retval = FALSE;
				goto out;
			}

			if (cinfo->output_scanline >= cinfo->output_height) {
				retval = TRUE;
				goto out;
			}
		} else {
                        /* we're decompressing buffered (progressive)
                         * so feed jpeg lib scanlines
                         */

			/* keep going until we've done all passes */
			while (!jpeg_input_complete (cinfo)) {
				if (!context->in_output) {
					if (jpeg_start_output (cinfo, cinfo->input_scan_number)) {
						context->in_output = TRUE;
						context->dptr = context->pixbuf->pixels;
					}
					else
						break;
				}

                                /* get scanlines from jpeg lib */
                                if (! gdk_pixbuf__jpeg_image_load_lines (context,
                                                                         error)) {
                                        retval = FALSE;
					goto out;
				}

				if (cinfo->output_scanline >= cinfo->output_height &&
				    jpeg_finish_output (cinfo))
					context->in_output = FALSE;
				else
					break;
			}
			if (jpeg_input_complete (cinfo)) {
				/* did entire image */
				retval = TRUE;
				goto out;
			}
			else
				continue;
		}
	}
out:
	jpeg_destroy_exif_context (exif_context);
	return retval;
}
Esempio n. 12
0
/* Shared library entry point */
static GdkPixbuf *
gdk_pixbuf__jpeg_image_load (FILE *f, GError **error)
{
	gint   i;
	char   otag_str[5];
	GdkPixbuf * volatile pixbuf = NULL;
	guchar *dptr;
	guchar *lines[4]; /* Used to expand rows, via rec_outbuf_height, 
                           * from the header file: 
                           * " Usually rec_outbuf_height will be 1 or 2, 
                           * at most 4."
			   */
	guchar **lptr;
	struct jpeg_decompress_struct cinfo;
	struct error_handler_data jerr;
	stdio_src_ptr src;
	gchar *icc_profile_base64;
	JpegExifContext *exif_context;

	/* setup error handler */
	cinfo.err = jpeg_std_error (&jerr.pub);
	jerr.pub.error_exit = fatal_error_handler;
        jerr.pub.output_message = output_message_handler;
        jerr.error = error;
        
	if (sigsetjmp (jerr.setjmp_buffer, 1)) {
		/* Whoops there was a jpeg error */
		if (pixbuf)
			g_object_unref (pixbuf);

		jpeg_destroy_decompress (&cinfo);

		/* error should have been set by fatal_error_handler () */
		return NULL;
	}

	/* load header, setup */
	jpeg_create_decompress (&cinfo);

	cinfo.src = (struct jpeg_source_mgr *)
	  (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
				  sizeof (stdio_source_mgr));
	src = (stdio_src_ptr) cinfo.src;
	src->buffer = (JOCTET *)
	  (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
				      JPEG_PROG_BUF_SIZE * sizeof (JOCTET));

	src->pub.init_source = stdio_init_source;
	src->pub.fill_input_buffer = stdio_fill_input_buffer;
	src->pub.skip_input_data = stdio_skip_input_data;
	src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
	src->pub.term_source = stdio_term_source;
	src->infile = f;
	src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
	src->pub.next_input_byte = NULL; /* until buffer loaded */

	jpeg_save_markers (&cinfo, JPEG_APP0+1, 0xffff);
	jpeg_save_markers (&cinfo, JPEG_APP0+2, 0xffff);
	jpeg_read_header (&cinfo, TRUE);

	/* parse exif data */
	exif_context = g_new0 (JpegExifContext, 1);
	jpeg_parse_exif (exif_context, &cinfo);
	
	jpeg_start_decompress (&cinfo);
	cinfo.do_fancy_upsampling = FALSE;
	cinfo.do_block_smoothing = FALSE;

	pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, 
				 cinfo.out_color_components == 4 ? TRUE : FALSE, 
				 8, cinfo.output_width, cinfo.output_height);
	      
	if (!pixbuf) {
		jpeg_destroy_decompress (&cinfo);

                /* broken check for *error == NULL for robustness against
                 * crappy JPEG library
                 */
                if (error && *error == NULL) {
                        g_set_error_literal (error,
                                             GDK_PIXBUF_ERROR,
                                             GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                             _("Insufficient memory to load image, try exiting some applications to free memory"));
                }
                
		return NULL;
	}

	/* if orientation tag was found */
	if (exif_context->orientation != 0) {
		g_snprintf (otag_str, sizeof (otag_str), "%d", exif_context->orientation);
		gdk_pixbuf_set_option (pixbuf, "orientation", otag_str);
	}

	/* if icc profile was found */
	if (exif_context->icc_profile != NULL) {
		icc_profile_base64 = g_base64_encode ((const guchar *) exif_context->icc_profile, exif_context->icc_profile_size);
		gdk_pixbuf_set_option (pixbuf, "icc-profile", icc_profile_base64);
		g_free (icc_profile_base64);
	}

	dptr = pixbuf->pixels;

	/* decompress all the lines, a few at a time */
	while (cinfo.output_scanline < cinfo.output_height) {
		lptr = lines;
		for (i = 0; i < cinfo.rec_outbuf_height; i++) {
			*lptr++ = dptr;
			dptr += pixbuf->rowstride;
		}

		jpeg_read_scanlines (&cinfo, lines, cinfo.rec_outbuf_height);

		switch (cinfo.out_color_space) {
		    case JCS_GRAYSCALE:
		      explode_gray_into_buf (&cinfo, lines);
		      break;
		    case JCS_RGB:
		      /* do nothing */
		      break;
		    case JCS_CMYK:
		      convert_cmyk_to_rgb (&cinfo, lines);
		      break;
		    default:
		      g_object_unref (pixbuf);
		      if (error && *error == NULL) {
                        g_set_error (error,
                                     GDK_PIXBUF_ERROR,
				     GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
				     _("Unsupported JPEG color space (%s)"),
				     colorspace_name (cinfo.out_color_space)); 
		      }
                
		      jpeg_destroy_decompress (&cinfo);
		      return NULL;
		}
	}

	jpeg_finish_decompress (&cinfo);
	jpeg_destroy_decompress (&cinfo);
	jpeg_destroy_exif_context (exif_context);

	return pixbuf;
}
Esempio n. 13
0
/* application specific data segment */
static gboolean
jpeg_parse_exif_app2_segment (JpegExifContext *context, jpeg_saved_marker_ptr marker)
{
	guint ret = FALSE;
	guint sequence_number;
	guint number_of_chunks;
	guint chunk_size;
	guint offset;

	/* do we have enough data? */
	if (marker->data_length < 16)
		goto out;

	/* unique identification string */
	if (memcmp (marker->data, "ICC_PROFILE\0", 12) != 0)
		goto out;

	/* get data about this segment */
	sequence_number = marker->data[12];
	number_of_chunks = marker->data[13];

	/* this is invalid, the base offset is 1 */
	if (sequence_number == 0)
		goto out;

	/* this is invalid, the base offset is 1 */
	if (sequence_number > number_of_chunks)
		goto out;

	/* size includes the id (12 bytes), length field (1 byte), and sequence field (1 byte) */
	chunk_size = marker->data_length - 14;
	offset = (sequence_number - 1) * 0xffef;

	/* Deal with the trivial profile (99% of images) to avoid allocating
	 * 64kb when we might only use a few kb. */
	if (number_of_chunks == 1) {
		if (context->icc_profile_size_allocated > 0)
			goto out;
		context->icc_profile_size = chunk_size;
		context->icc_profile_size_allocated = chunk_size;
		context->icc_profile = g_new (gchar, chunk_size);
		/* copy the segment data to the profile space */
		memcpy (context->icc_profile, marker->data + 14, chunk_size);
		goto out;
	}

	/* There is no promise the APP2 segments are going to be in order, so we
	 * have to allocate a huge swathe of memory and fill in the gaps when
	 * (if) we get the segment.
	 * Theoretically this could be as much as 16Mb, but display profiles are
	 * vary rarely above 100kb, and printer profiles are usually less than
	 * 2Mb */
	if (context->icc_profile_size_allocated == 0) {
		context->icc_profile_size_allocated = number_of_chunks * 0xffff;
		context->icc_profile = g_new0 (gchar, number_of_chunks * 0xffff);
	}

	/* check the data will fit in our previously allocated buffer */
	if (offset + chunk_size > context->icc_profile_size_allocated)
		goto out;

	/* copy the segment data to the profile space */
	memcpy (context->icc_profile + offset, marker->data + 14, chunk_size);

	/* it's now this big plus the new data we've just copied */
	context->icc_profile_size += chunk_size;

	/* success */
	ret = TRUE;
out:
	return ret;
}
Esempio n. 14
0
QCryptoTLSSession *
qcrypto_tls_session_new(QCryptoTLSCreds *creds,
                        const char *hostname,
                        const char *aclname,
                        QCryptoTLSCredsEndpoint endpoint,
                        Error **errp)
{
    QCryptoTLSSession *session;
    int ret;

    session = g_new0(QCryptoTLSSession, 1);
    trace_qcrypto_tls_session_new(
        session, creds, hostname ? hostname : "<none>",
        aclname ? aclname : "<none>", endpoint);

    if (hostname) {
        session->hostname = g_strdup(hostname);
    }
    if (aclname) {
        session->aclname = g_strdup(aclname);
    }
    session->creds = creds;
    object_ref(OBJECT(creds));

    if (creds->endpoint != endpoint) {
        error_setg(errp, "Credentials endpoint doesn't match session");
        goto error;
    }

    if (endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
        ret = gnutls_init(&session->handle, GNUTLS_SERVER);
    } else {
        ret = gnutls_init(&session->handle, GNUTLS_CLIENT);
    }
    if (ret < 0) {
        error_setg(errp, "Cannot initialize TLS session: %s",
                   gnutls_strerror(ret));
        goto error;
    }

    if (object_dynamic_cast(OBJECT(creds),
                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {
        QCryptoTLSCredsAnon *acreds = QCRYPTO_TLS_CREDS_ANON(creds);
        char *prio;

        if (creds->priority != NULL) {
            prio = g_strdup_printf("%s:+ANON-DH", creds->priority);
        } else {
            prio = g_strdup(CONFIG_TLS_PRIORITY ":+ANON-DH");
        }

        ret = gnutls_priority_set_direct(session->handle, prio, NULL);
        if (ret < 0) {
            error_setg(errp, "Unable to set TLS session priority %s: %s",
                       prio, gnutls_strerror(ret));
            g_free(prio);
            goto error;
        }
        g_free(prio);
        if (creds->endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
            ret = gnutls_credentials_set(session->handle,
                                         GNUTLS_CRD_ANON,
                                         acreds->data.server);
        } else {
            ret = gnutls_credentials_set(session->handle,
                                         GNUTLS_CRD_ANON,
                                         acreds->data.client);
        }
        if (ret < 0) {
            error_setg(errp, "Cannot set session credentials: %s",
                       gnutls_strerror(ret));
            goto error;
        }
    } else if (object_dynamic_cast(OBJECT(creds),
                                   TYPE_QCRYPTO_TLS_CREDS_X509)) {
        QCryptoTLSCredsX509 *tcreds = QCRYPTO_TLS_CREDS_X509(creds);
        const char *prio = creds->priority;
        if (!prio) {
            prio = CONFIG_TLS_PRIORITY;
        }

        ret = gnutls_priority_set_direct(session->handle, prio, NULL);
        if (ret < 0) {
            error_setg(errp, "Cannot set default TLS session priority %s: %s",
                       prio, gnutls_strerror(ret));
            goto error;
        }
        ret = gnutls_credentials_set(session->handle,
                                     GNUTLS_CRD_CERTIFICATE,
                                     tcreds->data);
        if (ret < 0) {
            error_setg(errp, "Cannot set session credentials: %s",
                       gnutls_strerror(ret));
            goto error;
        }

        if (creds->endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
            /* This requests, but does not enforce a client cert.
             * The cert checking code later does enforcement */
            gnutls_certificate_server_set_request(session->handle,
                                                  GNUTLS_CERT_REQUEST);
        }
    } else {
        error_setg(errp, "Unsupported TLS credentials type %s",
                   object_get_typename(OBJECT(creds)));
        goto error;
    }

    gnutls_transport_set_ptr(session->handle, session);
    gnutls_transport_set_push_function(session->handle,
                                       qcrypto_tls_session_push);
    gnutls_transport_set_pull_function(session->handle,
                                       qcrypto_tls_session_pull);

    return session;

 error:
    qcrypto_tls_session_free(session);
    return NULL;
}
Esempio n. 15
0
static const void *
MsgGetString(const char *domain,
             const char *msgid,
             StringEncoding encoding)
{
   const char *idp;
   const char *strp;
   char idBuf[MSG_MAX_ID];
   size_t len;
   HashTable *source = NULL;
   MsgCatalog *catalog;
   MsgState *state = MsgGetState();

   /* All message strings must be prefixed by the message ID. */
   ASSERT(domain != NULL);
   ASSERT(msgid != NULL);
   ASSERT(MsgHasMsgID(msgid));
#if defined(_WIN32)
   ASSERT(encoding == STRING_ENCODING_UTF8 ||
          encoding == STRING_ENCODING_UTF16_LE);
#else
   ASSERT(encoding == STRING_ENCODING_UTF8);
#endif

   /*
    * Find the beginning of the ID (idp) and the string (strp).
    * The string should have the correct MSG_MAGIC(...)... form.
    */

   idp = msgid + MSG_MAGIC_LEN + 1;
   strp = strchr(idp, ')') + 1;

   len = strp - idp - 1;
   ASSERT_NOT_IMPLEMENTED(len <= MSG_MAX_ID - 1);
   memcpy(idBuf, idp, len);
   idBuf[len] = '\0';

   /*
    * This lock is pretty coarse-grained, but a lot of the code below just runs
    * in exceptional situations, so it should be OK.
    */
   g_static_mutex_lock(&state->lock);

   catalog = MsgGetCatalog(domain);
   if (catalog != NULL) {
      switch (encoding) {
      case STRING_ENCODING_UTF8:
         source = catalog->utf8;
         break;

#if defined(_WIN32)
      case STRING_ENCODING_UTF16_LE:
         source = catalog->utf16;
         break;
#endif

      default:
         NOT_IMPLEMENTED();
      }
   }

#if defined(_WIN32)
   /*
    * Lazily create the local and UTF-16 dictionaries. This may require also
    * registering an empty message catalog for the desired domain.
    */
   if (source == NULL && encoding == STRING_ENCODING_UTF16_LE) {
      catalog = MsgGetCatalog(domain);
      if (catalog == NULL) {
         if (domain == NULL) {
            g_error("Application did not set up a default text domain.");
         }
         catalog = g_new0(MsgCatalog, 1);
         MsgSetCatalog(domain, catalog);
      }

      catalog->utf16 = HashTable_Alloc(8, HASH_STRING_KEY, g_free);
      ASSERT_MEM_ALLOC(catalog->utf16);
      source = catalog->utf16;
   }
#endif

   /*
    * Look up the localized string, converting to requested encoding as needed.
    */

   if (source != NULL) {
      const void *retval = NULL;

      if (HashTable_Lookup(source, idBuf, (void **) &retval)) {
         strp = retval;
#if defined(_WIN32)
      } else if (encoding == STRING_ENCODING_UTF16_LE) {
         gchar *converted;
         Bool success;

         /*
          * Look up the string in UTF-8, convert it and cache it.
          */
         retval = MsgGetString(domain, msgid, STRING_ENCODING_UTF8);
         ASSERT(retval);

         converted = (gchar *) g_utf8_to_utf16(retval, -1, NULL, NULL, NULL);
         ASSERT(converted != NULL);

         success = HashTable_Insert(source, idBuf, converted);
         ASSERT(success);
         strp = converted;
#endif
      }
   }

   g_static_mutex_unlock(&state->lock);

   return strp;
}
Esempio n. 16
0
static BDMDDetailData* get_detail_data_from_table (GHashTable *table, gboolean free_table) {
    BDMDDetailData *data = g_new0 (BDMDDetailData, 1);
    gchar *value = NULL;
    gchar *name_str = NULL;
    gchar *first_space = NULL;

    data->metadata = g_strdup ((gchar*) g_hash_table_lookup (table, "Version"));
    data->creation_time = g_strdup ((gchar*) g_hash_table_lookup (table, "Creation Time"));
    data->level = g_strdup ((gchar*) g_hash_table_lookup (table, "Raid Level"));
    data->uuid = g_strdup ((gchar*) g_hash_table_lookup (table, "UUID"));

    name_str = ((gchar*) g_hash_table_lookup (table, "Name"));
    if (name_str) {
        g_strstrip (name_str);
        first_space = strchr (name_str, ' ');
        if (first_space)
            *first_space = '\0';
        data->name = g_strdup (name_str);
    }

    value = (gchar*) g_hash_table_lookup (table, "Array Size");
    if (value) {
        first_space = strchr (value, ' ');
        if (first_space)
            *first_space = '\0';
        if (value && first_space)
            data->array_size = g_ascii_strtoull (value, NULL, 0);
    }
    else
        data->array_size = 0;

    value = (gchar*) g_hash_table_lookup (table, "Used Dev Size");
    if (value) {
        first_space = strchr (value, ' ');
        if (first_space)
            *first_space = '\0';
        if (value && first_space)
            data->use_dev_size = g_ascii_strtoull (value, NULL, 0);
    }
    else
        data->use_dev_size = 0;

    value = (gchar*) g_hash_table_lookup (table, "Raid Devices");
    if (value)
        data->raid_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->raid_devices = 0;

    value = (gchar*) g_hash_table_lookup (table, "Total Devices");
    if (value)
        data->total_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->total_devices = 0;

    value = (gchar*) g_hash_table_lookup (table, "Active Devices");
    if (value)
        data->active_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->active_devices = 0;

    value = (gchar*) g_hash_table_lookup (table, "Working Devices");
    if (value)
        data->working_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->working_devices = 0;

    value = (gchar*) g_hash_table_lookup (table, "Failed Devices");
    if (value)
        data->failed_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->failed_devices = 0;

    value = (gchar*) g_hash_table_lookup (table, "Spare Devices");
    if (value)
        data->spare_devices = g_ascii_strtoull (value, NULL, 0);
    else
        data->spare_devices = 0;

    value = (gchar*) g_hash_table_lookup (table, "State");
    if (value)
        data->clean = (g_strcmp0 (value, "clean") == 0);
    else
        data->clean = FALSE;

    if (free_table)
        g_hash_table_destroy (table);

    return data;
}
Esempio n. 17
0
static MsgCatalog *
MsgLoadCatalog(const char *path)
{
   gchar *localPath;
   GError *err = NULL;
   GIOChannel *stream;
   gboolean error = FALSE;
   MsgCatalog *catalog = NULL;
   HashTable *dict;

   ASSERT(path != NULL);
   localPath = VMTOOLS_GET_FILENAME_LOCAL(path, NULL);
   ASSERT(localPath != NULL);

   stream = g_io_channel_new_file(localPath, "r", &err);
   VMTOOLS_RELEASE_FILENAME_LOCAL(localPath);

   if (err != NULL) {
      g_debug("Unable to open '%s': %s\n", path, err->message);
      g_clear_error(&err);
      return NULL;
   }

   dict = HashTable_Alloc(8, HASH_STRING_KEY | HASH_FLAG_COPYKEY, g_free);
   ASSERT_MEM_ALLOC(dict);

   for (;;) {
      gboolean eof = FALSE;
      char *name = NULL;
      char *value = NULL;
      gchar *line;

      /* Read the next key / value pair. */
      for (;;) {
         gsize i;
         gsize len;
         gsize term;
         char *unused = NULL;
         gboolean cont = FALSE;

         g_io_channel_read_line(stream, &line, &len, &term, &err);

         if (err != NULL) {
            g_warning("Unable to read a line from '%s': %s\n",
                      path, err->message);
            g_clear_error(&err);
            error = TRUE;
            g_free(line);
            break;
         }

         if (line == NULL) {
            eof = TRUE;
            break;
         }

         /*
          * Fix the line break to always be Unix-style, to make lib/dict
          * happy.
          */
         if (line[term] == '\r') {
            line[term] = '\n';
            if (len > term) {
               line[term + 1] = '\0';
            }
         }

         /*
          * If currently name is not NULL, then check if this is a continuation
          * line and, if it is, just append the contents to the current value.
          */
         if (term > 0 && name != NULL && line[term - 1] == '"') {
            for (i = 0; i < len; i++) {
               if (line[i] == '"') {
                  /* OK, looks like a continuation line. */
                  char *tmp;
                  char *unescaped;

                  line[term - 1] = '\0';
                  unescaped = Escape_Undo('|', line + i + 1, len - i, NULL);
                  tmp = Str_Asprintf(NULL, "%s%s", value, unescaped);
                  free(unescaped);
                  free(value);
                  value = tmp;
                  cont = TRUE;
                  break;
               } else if (line[i] != ' ' && line[i] != '\t') {
                  break;
               }
            }
         }

         /*
          * If not a continuation line and we have a name, break out of the
          * inner loop to update the dictionaty.
          */
         if (!cont && name != NULL) {
            g_free(line);
            break;
         }

         /*
          * Finally, try to parse the string using the dictionary library.
          */
         if (!cont && DictLL_UnmarshalLine(line, len, &unused, &name, &value) == NULL) {
            g_warning("Couldn't parse line from catalog: %s", line);
            error = TRUE;
         }

         g_free(line);
         free(unused);
      }

      if (error) {
         break;
      }

      if (name != NULL) {
         ASSERT(value);

         if (!Unicode_IsBufferValid(name, strlen(name) + 1, STRING_ENCODING_UTF8) ||
             !Unicode_IsBufferValid(value, strlen(value) + 1, STRING_ENCODING_UTF8)) {
            g_warning("Invalid UTF-8 string in message catalog (key = %s)\n", name);
            error = TRUE;
            break;
         }

         MsgUnescape(value);
         HashTable_ReplaceOrInsert(dict, name, g_strdup(value));
         free(name);
         free(value);
         name = NULL;
         value = NULL;
      }

      if (eof) {
         break;
      }
   }

   g_io_channel_unref(stream);

   if (error) {
      HashTable_Free(dict);
      dict = NULL;
   } else {
      catalog = g_new0(MsgCatalog, 1);
      catalog->utf8 = dict;
   }

   return catalog;
}
Esempio n. 18
0
static ButtonData*
bigboard_button_add_to_widget (GtkWidget *applet)
{
        ButtonData *button_data;
        AtkObject  *atk_obj;
        GtkWidget  *hbox;

        button_data = g_new0 (ButtonData, 1);

        button_data->applet = applet;

        button_data->image = gtk_image_new ();

        button_data->orient = GTK_ORIENTATION_HORIZONTAL;

        button_data->size = 24;

        g_signal_connect (G_OBJECT (button_data->applet), "realize",
                          G_CALLBACK (bigboard_button_applet_realized), button_data);

        button_data->button = gtk_toggle_button_new ();

        gtk_widget_set_name (button_data->button, "bigboard-button");
        gtk_rc_parse_string ("\n"
                             "   style \"bigboard-button-style\"\n"
                             "   {\n"
                             "      GtkWidget::focus-line-width=0\n"
                             "      GtkWidget::focus-padding=0\n"
                             "      GtkButton::interior-focus=0\n"
                             "   }\n"
                             "\n"
                             "    widget \"*.bigboard-button\" style \"bigboard-button-style\"\n"
                             "\n");

        atk_obj = gtk_widget_get_accessible (button_data->button);
        atk_object_set_name (atk_obj, _("Show Sidebar Button"));
        g_signal_connect (G_OBJECT (button_data->button), "button_press_event",
                          G_CALLBACK (do_not_eat_button_press), NULL);

        g_signal_connect (G_OBJECT (button_data->button), "toggled",
                          G_CALLBACK (button_toggled_callback), button_data);

        gtk_container_set_border_width (GTK_CONTAINER (button_data->button), 0);
        gtk_container_add (GTK_CONTAINER (button_data->button), button_data->image);

        button_data->launchers = launchers_new();

        hbox = gtk_hbox_new(FALSE, 0);
        gtk_box_pack_start(GTK_BOX(hbox), button_data->button, FALSE, TRUE, 0);
        gtk_box_pack_start(GTK_BOX(hbox), button_data->launchers, FALSE, TRUE, 0);

        gtk_container_add (GTK_CONTAINER (button_data->applet), hbox);

        g_signal_connect (G_OBJECT (button_data->button),
                          "size_allocate",
                          G_CALLBACK (button_size_allocated),
                          button_data);

        g_signal_connect (G_OBJECT (button_data->applet),
                          "destroy",
                          G_CALLBACK (applet_destroyed),
                          button_data);

        gtk_drag_dest_set (GTK_WIDGET(button_data->button), 0, NULL, 0, 0);

        g_signal_connect (G_OBJECT(button_data->button), "drag_motion",
                          G_CALLBACK (button_drag_motion),
                          button_data);
        g_signal_connect (G_OBJECT(button_data->button), "drag_leave",
                          G_CALLBACK (button_drag_leave),
                          button_data);

        button_data->connection = dbus_bus_get (DBUS_BUS_SESSION, NULL);
        if (button_data->connection) {

                dbus_connection_setup_with_g_main(button_data->connection, NULL);

                hippo_dbus_helper_register_service_tracker(button_data->connection,
                                                           "org.gnome.BigBoard",
                                                           &bigboard_tracker,
                                                           signal_handlers,
                                                           button_data);
                button_data->bb_proxy =
                        hippo_dbus_proxy_new (button_data->connection,
                                              "org.gnome.BigBoard",
                                              "/bigboard/panel",
                                              "org.gnome.BigBoard.Panel");
        }

        self_add_icon_changed_callback(user_photo_changed_callback, button_data);

        gtk_widget_show_all (hbox);

        return button_data;
}
Esempio n. 19
0
GschemToplevel *gschem_toplevel_new ()
{
  GschemToplevel *w_current;

  w_current = g_new0 (GschemToplevel, 1);

  w_current->toplevel = NULL;

  w_current->dont_invalidate = FALSE;

  /* ------------------- */
  /* main window widgets */
  /* ------------------- */
  w_current->main_window  = NULL;
  w_current->drawing_area = NULL;
  w_current->menubar      = NULL;
  w_current->popup_menu   = NULL;
  w_current->find_text_widget = NULL;
  w_current->macro_widget  = NULL;
  w_current->bottom_widget = NULL;
  w_current->translate_widget = NULL;

  w_current->toolbar_select = NULL;
  w_current->toolbar_net    = NULL;
  w_current->toolbar_bus    = NULL;

  w_current->bottom_notebook = NULL;

  w_current->find_text_state = NULL;
  w_current->log_widget      = NULL;

  w_current->keyaccel_string = NULL;
  w_current->keyaccel_string_source_id = FALSE;

  /* ------------ */
  /* Dialog boxes */
  /* ------------ */
  w_current->sowindow     = NULL;
  w_current->pfswindow    = NULL;
  w_current->cswindow     = NULL;
  w_current->pswindow     = NULL;
  w_current->tiwindow     = NULL;
  w_current->sewindow     = NULL;
  w_current->aawindow     = NULL;
  w_current->mawindow     = NULL;
  w_current->aewindow     = NULL;
  w_current->hkwindow     = NULL;
  w_current->cowindow     = NULL;
  w_current->coord_world  = NULL;
  w_current->coord_screen = NULL;

  /* -------------------------------------- */
  /* Models for widgets inside dialog boxes */
  /* -------------------------------------- */
  w_current->dash_length_list_store = NULL;
  w_current->dash_space_list_store = NULL;
  w_current->fill_angle_list_store = NULL;
  w_current->fill_pitch_list_store = NULL;
  w_current->fill_width_list_store = NULL;
  w_current->line_width_list_store = NULL;
  w_current->text_size_list_store = NULL;

  /* ----------------------------------------- */
  /* An adapter for manipulating the selection */
  /* ----------------------------------------- */
  w_current->selection_adapter = NULL;

  /* ----------------- */
  /* Picture placement */
  /* ----------------- */
  w_current->current_pixbuf = NULL;
  w_current->pixbuf_filename = NULL;
  w_current->pixbuf_wh_ratio = 0;

  /* ------------- */
  /* Drawing state */
  /* ------------- */
  w_current->renderer = EDA_RENDERER (g_object_new (EDA_TYPE_RENDERER, NULL));
  w_current->first_wx = -1;
  w_current->first_wy = -1;
  w_current->second_wx = -1;
  w_current->second_wy = -1;
  w_current->third_wx = -1;
  w_current->third_wy = -1;
  w_current->distance = 0;
  w_current->magnetic_wx = -1;
  w_current->magnetic_wy = -1;
  w_current->inside_action = 0;
  w_current->rubber_visible = 0;
  w_current->net_direction = 0;
  w_current->which_grip = -1;
  w_current->which_object = NULL;
  w_current->temp_path = NULL;
  w_current->pathcontrol = TRUE;

  /* ------------------ */
  /* Rubberbanding nets */
  /* ------------------ */
  w_current->stretch_list = NULL;

  /* --------------------- */
  /* Gschem internal state */
  /* --------------------- */
  w_current->num_untitled = 0;
  w_current->event_state = SELECT;
  w_current->image_width  = 0;
  w_current->image_height = 0;
  w_current->min_zoom = 0;
  w_current->max_zoom = 8;
  w_current->drawbounding_action_mode = FREE;
  w_current->last_drawb_mode = LAST_DRAWB_MODE_NONE;
  w_current->CONTROLKEY = 0;
  w_current->SHIFTKEY   = 0;
  w_current->ALTKEY     = 0;
  w_current->buffer_number = 0;
  w_current->last_callback = NULL;
  w_current->clipboard_buffer = NULL;

  /* ------------------ */
  /* rc/user parameters */
  /* ------------------ */
  w_current->options = gschem_options_new();

  g_signal_connect_swapped (G_OBJECT (w_current->options),
                            "notify",
                            G_CALLBACK (notify_options),
                            w_current);

  w_current->text_caps = 0;
  w_current->text_size = 0;

  w_current->zoom_with_pan = 0;
  w_current->actionfeedback_mode = OUTLINE;
  w_current->net_direction_mode = TRUE;
  w_current->net_selection_mode = 0;
  w_current->net_selection_state = 0;
  w_current->embed_complex = 0;
  w_current->include_complex = 0;
  w_current->scrollbars_flag = 0;
  w_current->log_window = 0;
  w_current->log_window_type = 0;
  w_current->third_button = 0;
  w_current->third_button_cancel = TRUE;
  w_current->middle_button = 0;
  w_current->file_preview = 0;
  w_current->enforce_hierarchy = 0;
  w_current->fast_mousepan = 0;
  w_current->raise_dialog_boxes = 0;
  w_current->continue_component_place = 0;
  w_current->undo_levels = 0;
  w_current->undo_control = 0;
  w_current->undo_type = 0;
  w_current->undo_panzoom = 0;
  w_current->draw_grips = 0;
  w_current->warp_cursor = 0;
  w_current->toolbars = 0;
  w_current->handleboxes = 0;
  w_current->bus_ripper_size = 0;
  w_current->bus_ripper_type = 0;
  w_current->bus_ripper_rotation = 0;
  w_current->grid_mode = GRID_MODE_NONE;
  w_current->dots_grid_fixed_threshold = 10;
  w_current->dots_grid_dot_size = 1;
  w_current->dots_grid_mode = DOTS_GRID_VARIABLE_MODE;
  w_current->mesh_grid_display_threshold = 3;
  w_current->add_attribute_offset = 50;
  w_current->mousepan_gain = 5;
  w_current->keyboardpan_gain = 10;
  w_current->select_slack_pixels = 4;
  w_current->zoom_gain = 20;
  w_current->scrollpan_steps = 8;

  w_current->smob = SCM_UNDEFINED;

  return w_current;
}
Esempio n. 20
0
/* compatibility wrapper */
static InetSocketAddress *inet_parse(const char *str, Error **errp)
{
    InetSocketAddress *addr;
    const char *optstr, *h;
    char host[64];
    char port[33];
    int to;
    int pos;

    addr = g_new0(InetSocketAddress, 1);

    /* parse address */
    if (str[0] == ':') {
        /* no host given */
        host[0] = '\0';
        if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
            error_setg(errp, "error parsing port in address '%s'", str);
            goto fail;
        }
    } else if (str[0] == '[') {
        /* IPv6 addr */
        if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
            error_setg(errp, "error parsing IPv6 address '%s'", str);
            goto fail;
        }
        addr->ipv6 = addr->has_ipv6 = true;
    } else if (qemu_isdigit(str[0])) {
        /* IPv4 addr */
        if (2 != sscanf(str, "%64[0-9.]:%32[^,]%n", host, port, &pos)) {
            error_setg(errp, "error parsing IPv4 address '%s'", str);
            goto fail;
        }
        addr->ipv4 = addr->has_ipv4 = true;
    } else {
        /* hostname */
        if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
            error_setg(errp, "error parsing address '%s'", str);
            goto fail;
        }
    }

    addr->host = g_strdup(host);
    addr->port = g_strdup(port);

    /* parse options */
    optstr = str + pos;
    h = strstr(optstr, ",to=");
    if (h) {
        h += 4;
        if (sscanf(h, "%d%n", &to, &pos) != 1 ||
            (h[pos] != '\0' && h[pos] != ',')) {
            error_setg(errp, "error parsing to= argument");
            goto fail;
        }
        addr->has_to = true;
        addr->to = to;
    }
    if (strstr(optstr, ",ipv4")) {
        addr->ipv4 = addr->has_ipv4 = true;
    }
    if (strstr(optstr, ",ipv6")) {
        addr->ipv6 = addr->has_ipv6 = true;
    }
    return addr;

fail:
    qapi_free_InetSocketAddress(addr);
    return NULL;
}
Esempio n. 21
0
BillImportGui *
gnc_plugin_bi_import_showGUI (GtkWindow *parent)
{
    BillImportGui *gui;
    GtkBuilder *builder;
    GList *glist;
    GtkCellRenderer *renderer;
    GtkTreeViewColumn *column;

    // if window exists already, activate it
    glist = gnc_find_gui_components ("dialog-bi-import-gui", NULL, NULL);
    if (glist)
    {
        // window found
        gui = g_list_nth_data (glist, 0);
        g_list_free (glist);

        gtk_window_set_transient_for(GTK_WINDOW(gui->dialog), GTK_WINDOW(parent));
        gui->parent = parent;
        gtk_window_present (GTK_WINDOW(gui->dialog));
        return gui;
    }

    // create new window
    gui = g_new0 (BillImportGui, 1);
    gui->type = "BILL"; // Set default type to match gui.  really shouldn't be here TODO change me
    gui->open_mode = "ALL";

    builder = gtk_builder_new();
    gnc_builder_add_from_file (builder, "dialog-bi-import-gui.glade", "bi_import_dialog");
    gui->dialog = GTK_WIDGET(gtk_builder_get_object (builder, "bi_import_dialog"));
    gtk_window_set_transient_for(GTK_WINDOW(gui->dialog), GTK_WINDOW(parent));
    gui->parent = parent;
    gui->tree_view = GTK_WIDGET(gtk_builder_get_object (builder, "treeview1"));
    gui->entryFilename = GTK_WIDGET(gtk_builder_get_object (builder, "entryFilename"));

    // Set the style context for this dialog so it can be easily manipulated with css
    gnc_widget_set_style_context (GTK_WIDGET(gui->dialog), "GncBillImportDialog");

    gtk_window_set_transient_for (GTK_WINDOW (gui->dialog), parent);

    gui->book = gnc_get_current_book();

    gui->regexp = g_string_new ( "^(?<id>[^;]*);(?<date_opened>[^;]*);(?<owner_id>[^;]*);(?<billing_id>[^;]*);?(?<notes>[^;]*);?(?<date>[^;]*);?(?<desc>[^;]*);?(?<action>[^;]*);?(?<account>[^;]*);?(?<quantity>[^;]*);?(?<price>[^;]*);?(?<disc_type>[^;]*);?(?<disc_how>[^;]*);?(?<discount>[^;]*);?(?<taxable>[^;]*);?(?<taxincluded>[^;]*);?(?<tax_table>[^;]*);(?<date_posted>[^;]*);(?<due_date>[^;]*);(?<account_posted>[^;]*);(?<memo_posted>[^;]*);(?<accu_splits>[^;]*)$");

    // create model and bind to view
    gui->store = gtk_list_store_new (N_COLUMNS,
                                     G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, // invoice settings
                                     G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, // entry settings
                                     G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); // autopost settings
    gtk_tree_view_set_model( GTK_TREE_VIEW(gui->tree_view), GTK_TREE_MODEL(gui->store) );
#define CREATE_COLUMN(description,column_id) \
  renderer = gtk_cell_renderer_text_new (); \
  column = gtk_tree_view_column_new_with_attributes (description, renderer, "text", column_id, NULL); \
  gtk_tree_view_column_set_resizable (column, TRUE); \
  gtk_tree_view_append_column (GTK_TREE_VIEW (gui->tree_view), column);
    CREATE_COLUMN ("id", ID);
    CREATE_COLUMN ("date__opened", DATE_OPENED);
    CREATE_COLUMN ("owner__id", OWNER_ID);
    CREATE_COLUMN ("billing__id", BILLING_ID);
    CREATE_COLUMN ("notes", NOTES);

    CREATE_COLUMN ("date", DATE);
    CREATE_COLUMN ("desc", DESC);
    CREATE_COLUMN ("action", ACTION);
    CREATE_COLUMN ("account", ACCOUNT);
    CREATE_COLUMN ("quantity", QUANTITY);
    CREATE_COLUMN ("price", PRICE);
    CREATE_COLUMN ("disc__type", DISC_TYPE);
    CREATE_COLUMN ("disc__how", DISC_HOW);
    CREATE_COLUMN ("discount", DISCOUNT);
    CREATE_COLUMN ("taxable", TAXABLE);
    CREATE_COLUMN ("taxincluded", TAXINCLUDED);
    CREATE_COLUMN ("tax__table", TAX_TABLE);

    CREATE_COLUMN ("date__posted", DATE_POSTED);
    CREATE_COLUMN ("due__date", DUE_DATE);
    CREATE_COLUMN ("account__posted", ACCOUNT_POSTED);
    CREATE_COLUMN ("memo__posted", MEMO_POSTED);
    CREATE_COLUMN ("accu__splits", ACCU_SPLITS);

    gui->component_id = gnc_register_gui_component ("dialog-bi-import-gui",
                        NULL,
                        gnc_bi_import_gui_close_handler,
                        gui);

    /* Setup signals */
    gtk_builder_connect_signals_full (builder, gnc_builder_connect_full_func, gui);

    gtk_widget_show_all ( gui->dialog );

    g_object_unref(G_OBJECT(builder));

    return gui;
}
Esempio n. 22
0
static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
                               Error **errp)
{
    const char *host = qemu_opt_get(opts, "host");
    const char *port = qemu_opt_get(opts, "port");
    const char *localaddr = qemu_opt_get(opts, "localaddr");
    const char *localport = qemu_opt_get(opts, "localport");
    bool has_local = false;
    SocketAddress *addr;
    ChardevUdp *udp;

    backend->type = CHARDEV_BACKEND_KIND_UDP;
    if (host == NULL || strlen(host) == 0) {
        host = "localhost";
    }
    if (port == NULL || strlen(port) == 0) {
        error_setg(errp, "chardev: udp: remote port not specified");
        return;
    }
    if (localport == NULL || strlen(localport) == 0) {
        localport = "0";
    } else {
        has_local = true;
    }
    if (localaddr == NULL || strlen(localaddr) == 0) {
        localaddr = "";
    } else {
        has_local = true;
    }

    udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
    qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));

    addr = g_new0(SocketAddress, 1);
    addr->type = SOCKET_ADDRESS_KIND_INET;
    addr->u.inet.data = g_new(InetSocketAddress, 1);
    *addr->u.inet.data = (InetSocketAddress) {
        .host = g_strdup(host),
        .port = g_strdup(port),
        .has_ipv4 = qemu_opt_get(opts, "ipv4"),
        .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
        .has_ipv6 = qemu_opt_get(opts, "ipv6"),
        .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
    };
    udp->remote = addr;

    if (has_local) {
        udp->has_local = true;
        addr = g_new0(SocketAddress, 1);
        addr->type = SOCKET_ADDRESS_KIND_INET;
        addr->u.inet.data = g_new(InetSocketAddress, 1);
        *addr->u.inet.data = (InetSocketAddress) {
            .host = g_strdup(localaddr),
            .port = g_strdup(localport),
        };
        udp->local = addr;
    }
}

static void qmp_chardev_open_udp(Chardev *chr,
                                 ChardevBackend *backend,
                                 bool *be_opened,
                                 Error **errp)
{
    ChardevUdp *udp = backend->u.udp.data;
    QIOChannelSocket *sioc = qio_channel_socket_new();
    char *name;
    UdpChardev *s = UDP_CHARDEV(chr);

    if (qio_channel_socket_dgram_sync(sioc,
                                      udp->local, udp->remote,
                                      errp) < 0) {
        object_unref(OBJECT(sioc));
        return;
    }

    name = g_strdup_printf("chardev-udp-%s", chr->label);
    qio_channel_set_name(QIO_CHANNEL(sioc), name);
    g_free(name);

    s->ioc = QIO_CHANNEL(sioc);
    /* be isn't opened until we get a connection */
    *be_opened = false;
}
Esempio n. 23
0
File: fmon.c Progetto: bhuisgen/fmon
GSList *
init_watchers()
{
  GSList *list = NULL;
  GError *error = NULL;
  gchar **groups;
  gchar *value;
  gsize len;
  gint i;

  groups = g_key_file_get_groups(app->settings, &len);
  if (len < 2)
    {
      g_printerr("%s: %s (%s)\n", app->config_file,
          N_("error in configuration file"), N_("no watcher group found"));

      g_strfreev(groups);

      return NULL;
    }

  for (i = 0; i < len; i++)
    {
      if (g_strcmp0(groups[i], CONFIG_GROUP_MAIN) == 0)
        continue;

      watcher_t *watcher;
      watcher = g_new0(watcher_t, 1);

      watcher->name = g_strdup(groups[i]);

      watcher->path = g_key_file_get_string(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_PATH, &error);
      if (error)
        {
          g_printerr("%s: %s\n", watcher->name, N_("invalid path"));

          g_error_free(error);
          error = NULL;
          g_free(watcher->name);
          g_free(watcher);
          g_strfreev(groups);

          return NULL;
        }
      if (!g_file_test(watcher->path, G_FILE_TEST_EXISTS))
        {
          g_printerr("%s: %s\n", watcher->name, N_("file/path doesn't exist"));

          g_free(watcher->path);
          g_free(watcher->name);
          g_free(watcher);
          g_strfreev(groups);

          return NULL;
        }
      if (!g_file_test(watcher->path, G_FILE_TEST_IS_DIR))
        {
          if (g_access(watcher->path, R_OK))
            {
              g_printerr("%s: %s\n", watcher->name,
                  N_("bad permissions on file"));

              g_free(watcher->path);
              g_free(watcher->name);
              g_free(watcher);
              g_strfreev(groups);

              return NULL;
            }
        }
      else
        {
          if (g_access(watcher->path, R_OK | X_OK))
            {
              g_printerr("%s: %s\n", watcher->name,
                  N_("bad permissions on path"));

              g_free(watcher->path);
              g_free(watcher->name);
              g_free(watcher);
              g_strfreev(groups);

              return NULL;
            }
        }

      watcher->recursive = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_RECURSIVE, &error);
      if (error)
        {
          watcher->recursive = CONFIG_KEY_WATCHER_RECURSIVE_DEFAULT;

          g_error_free(error);
          error = NULL;
        }

      if (watcher->recursive)
        {
          if (!g_file_test(watcher->path, G_FILE_TEST_IS_DIR))
            {
              g_printerr("%s: %s\n", watcher->name,
                  N_("recursion is enabled but path is not a directory"));

              g_free(watcher->path);
              g_free(watcher->name);
              g_free(watcher);
              g_strfreev(groups);

              return NULL;
            }

          watcher->maxdepth = g_key_file_get_integer(app->settings,
              watcher->name, CONFIG_KEY_WATCHER_MAXDEPTH, &error);
          if (error)
            {
              watcher->recursive = CONFIG_KEY_WATCHER_MAXDEPTH_DEFAULT;

              g_error_free(error);
              error = NULL;
            }
          if (watcher->maxdepth < 0)
            {
              g_printerr("%s: %s\n", watcher->name,
                  N_("invalid maximum depth of recursion"));

              g_free(watcher->path);
              g_free(watcher->name);
              g_free(watcher);
              g_strfreev(groups);

              return NULL;
            }
        }

      watcher->events = g_key_file_get_string_list(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_EVENTS, &len, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }
      if (watcher->events)
        {
          for (i = 0; watcher->events[i]; i++)
            {
              if ((g_strcmp0(watcher->events[i],
                  CONFIG_KEY_WATCHER_EVENT_CHANGING) != 0)
                  && (g_strcmp0(watcher->events[i],
                  CONFIG_KEY_WATCHER_EVENT_CHANGED) != 0)
                  && (g_strcmp0(watcher->events[i],
                      CONFIG_KEY_WATCHER_EVENT_CREATED) != 0)
                  && (g_strcmp0(watcher->events[i],
                      CONFIG_KEY_WATCHER_EVENT_DELETED) != 0)
                  && (g_strcmp0(watcher->events[i],
                      CONFIG_KEY_WATCHER_EVENT_ATTRIBUTECHANGED) != 0)
                  && (g_strcmp0(watcher->events[i],
                      CONFIG_KEY_WATCHER_EVENT_MOUNTED) != 0)
                  && (g_strcmp0(watcher->events[i],
                      CONFIG_KEY_WATCHER_EVENT_UNMOUNTED) != 0))
                {
                  g_printerr("%s: %s\n", watcher->name, N_("invalid event"));

                  g_strfreev(watcher->events);
                  g_free(watcher->path);
                  g_free(watcher->name);
                  g_free(watcher);
                  g_strfreev(groups);

                  return NULL;
                }
            }
        }

      watcher->exec = g_key_file_get_string(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_EXEC, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->print = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_PRINT, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->print0 = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_PRINT0, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->mount = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_MOUNT, &error);
      if (error)
        {
          watcher->mount = CONFIG_KEY_WATCHER_MOUNT_DEFAULT;

          g_error_free(error);
          error = NULL;
        }

      watcher->readable = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_READABLE, &error);
      if (error)
        {
    	  watcher->readable = CONFIG_KEY_WATCHER_READABLE_DEFAULT;

          g_error_free(error);
          error = NULL;
        }

      watcher->writable = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_WRITABLE, &error);
      if (error)
        {
    	  watcher->writable = CONFIG_KEY_WATCHER_WRITABLE_DEFAULT;

          g_error_free(error);
          error = NULL;
        }

      watcher->executable = g_key_file_get_boolean(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_EXECUTABLE, &error);
      if (error)
        {
    	  watcher->executable = CONFIG_KEY_WATCHER_EXECUTABLE_DEFAULT;

          g_error_free(error);
          error = NULL;
        }

      watcher->size = -1;
      watcher->size_unit = WATCHER_SIZE_UNIT_BYTES;
      watcher->size_cmp = WATCHER_SIZE_COMPARE_EQUAL;

      value = g_key_file_get_string(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_SIZE, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }
      else
        {
          GRegex *regex_size;
          GMatchInfo *match_info;
          gchar *str, *err;

          regex_size = g_regex_new("^([^0-9])?(\\d+)([^0-9])?$", 0, 0, NULL);

          if (g_regex_match(regex_size, value, 0, &match_info))
            {
              str = g_match_info_fetch(match_info, 1);
              if (str)
                {
                  if ((g_strcmp0(str, "") != 0) &&
                      (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_GREATER) != 0) &&
                      (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_LESS) != 0))
                    {
                      g_printerr("%s: %s\n", watcher->name, N_("invalid size comparator"));

                      g_free(str);
                      g_match_info_free(match_info);
                      g_regex_unref(regex_size);
                      g_free(value);
                      g_free(watcher->exec);
                      g_strfreev(watcher->events);
                      g_free(watcher->path);
                      g_free(watcher->name);
                      g_free(watcher);
                      g_strfreev(groups);

                      return NULL;
                    }

                  if (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_GREATER) == 0)
                    watcher->size_cmp = WATCHER_SIZE_COMPARE_GREATER;

                  if (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_LESS) == 0)
                    watcher->size_cmp = WATCHER_SIZE_COMPARE_LESS;

                  g_free(str);
                }

              str = g_match_info_fetch(match_info, 2);
              watcher->size = (int) strtol (str, &err, 10);
              if ((err == str) || (errno == ERANGE))
                {
                  g_printerr("%s: %s\n", watcher->name, N_("invalid size"));

                  g_free(str);
                  g_match_info_free(match_info);
                  g_regex_unref(regex_size);
                  g_free(value);
                  g_free(watcher->exec);
                  g_strfreev(watcher->events);
                  g_free(watcher->path);
                  g_free(watcher->name);
                  g_free(watcher);
                  g_strfreev(groups);

                  return NULL;
                }

              g_free(str);

              str = g_match_info_fetch(match_info, 3);
              if (str)
                {
                  if ((g_strcmp0(str, "") != 0) &&
                      (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_BYTES) != 0) &&
                      (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_KBYTES) != 0) &&
                      (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_MBYTES) != 0) &&
                      (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_GBYTES) != 0))
                    {
                      g_printerr("%s: %s\n", watcher->name, N_("invalid size unit"));

                      g_free(str);
                      g_match_info_free(match_info);
                      g_regex_unref(regex_size);
                      g_free(value);
                      g_free(watcher->exec);
                      g_strfreev(watcher->events);
                      g_free(watcher->path);
                      g_free(watcher->name);
                      g_free(watcher);
                      g_strfreev(groups);

                      return NULL ;
                    }

                  if (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_KBYTES) == 0)
                    watcher->size_unit = WATCHER_SIZE_UNIT_KBYTES;

                  if (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_MBYTES) == 0)
                    watcher->size_unit = WATCHER_SIZE_UNIT_MBYTES;

                  if (g_strcmp0(str, CONFIG_KEY_WATCHER_SIZE_GBYTES) == 0)
                    watcher->size_unit = WATCHER_SIZE_UNIT_GBYTES;

                  g_free(str);
                }

              g_match_info_free(match_info);
              g_regex_unref(regex_size);
            }
          else
            {
              g_printerr("%s: %s\n", watcher->name, N_("invalid size"));

              g_match_info_free(match_info);
              g_regex_unref(regex_size);
              g_free(value);
              g_strfreev(watcher->events);
              g_free(watcher->path);
              g_free(watcher->name);
              g_free(watcher);
              g_strfreev(groups);

              return NULL;
            }
        }

      g_free(value);

      watcher->type = g_key_file_get_string(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_TYPE, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }
      if (watcher->type
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_BLOCK) != 0)
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_CHARACTER) != 0)
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_DIRECTORY) != 0)
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_FIFO) != 0)
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_REGULAR) != 0)
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_SOCKET) != 0)
          && (g_strcmp0(watcher->type, CONFIG_KEY_WATCHER_TYPE_SYMBOLICLINK)
              != 0))
        {
          g_printerr("%s: %s\n", watcher->name, N_("invalid type"));

          g_error_free(error);
          error = NULL;
          g_strfreev(watcher->events);
          g_free(watcher->path);
          g_free(watcher->name);
          g_free(watcher);
          g_strfreev(groups);

          return NULL;
        }

      watcher->user = g_key_file_get_string(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_USER, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->group = g_key_file_get_string(app->settings, watcher->name,
          CONFIG_KEY_WATCHER_GROUP, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->includes = g_key_file_get_string_list(app->settings,
          watcher->name, CONFIG_KEY_WATCHER_INCLUDE, NULL, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->excludes = g_key_file_get_string_list(app->settings,
          watcher->name, CONFIG_KEY_WATCHER_EXCLUDE, NULL, &error);
      if (error)
        {
          g_error_free(error);
          error = NULL;
        }

      watcher->monitors = g_hash_table_new(g_str_hash, g_str_equal);

      list = g_slist_append(list, watcher);
    }

  g_strfreev(groups);

  return list;
}
static gboolean
ldsm_check_all_mounts (gpointer data)
{
        GList *mounts;
        GList *l;
        GList *check_mounts = NULL;
        GList *full_mounts = NULL;
        guint number_of_mounts;
        guint number_of_full_mounts;
        gboolean multiple_volumes = FALSE;
        gboolean other_usable_volumes = FALSE;

        /* We iterate through the static mounts in /etc/fstab first, seeing if
         * they're mounted by checking if the GUnixMountPoint has a corresponding GUnixMountEntry.
         * Iterating through the static mounts means we automatically ignore dynamically mounted media.
         */
        mounts = g_unix_mount_points_get (time_read);

        for (l = mounts; l != NULL; l = l->next) {
                GUnixMountPoint *mount_point = l->data;
                GUnixMountEntry *mount;
                LdsmMountInfo *mount_info;
                const gchar *path;

                path = g_unix_mount_point_get_mount_path (mount_point);
                mount = g_unix_mount_at (path, time_read);
                g_unix_mount_point_free (mount_point);
                if (mount == NULL) {
                        /* The GUnixMountPoint is not mounted */
                        continue;
                }

                mount_info = g_new0 (LdsmMountInfo, 1);
                mount_info->mount = mount;

                path = g_unix_mount_get_mount_path (mount);

                if (g_unix_mount_is_readonly (mount)) {
                        ldsm_free_mount_info (mount_info);
                        continue;
                }

                if (ldsm_mount_is_user_ignore (path)) {
                        ldsm_free_mount_info (mount_info);
                        continue;
                }

                if (csd_should_ignore_unix_mount (mount)) {
                        ldsm_free_mount_info (mount_info);
                        continue;
                }

                if (statvfs (path, &mount_info->buf) != 0) {
                        ldsm_free_mount_info (mount_info);
                        continue;
                }

                if (ldsm_mount_is_virtual (mount_info)) {
                        ldsm_free_mount_info (mount_info);
                        continue;
                }

                check_mounts = g_list_prepend (check_mounts, mount_info);
        }

        g_list_free (mounts);

        number_of_mounts = g_list_length (check_mounts);
        if (number_of_mounts > 1)
                multiple_volumes = TRUE;

        for (l = check_mounts; l != NULL; l = l->next) {
                LdsmMountInfo *mount_info = l->data;

                if (!ldsm_mount_has_space (mount_info)) {
                        full_mounts = g_list_prepend (full_mounts, mount_info);
                } else {
                        g_hash_table_remove (ldsm_notified_hash, g_unix_mount_get_mount_path (mount_info->mount));
                        ldsm_free_mount_info (mount_info);
                }
        }

        number_of_full_mounts = g_list_length (full_mounts);
        if (number_of_mounts > number_of_full_mounts)
                other_usable_volumes = TRUE;

        ldsm_maybe_warn_mounts (full_mounts, multiple_volumes,
                                other_usable_volumes);

        g_list_free (check_mounts);
        g_list_free (full_mounts);

        return TRUE;
}
Esempio n. 25
0
gboolean
nautilus_list_model_add_file (NautilusListModel *model, NautilusFile *file,
			      NautilusDirectory *directory)
{
	GtkTreeIter iter;
	GtkTreePath *path;
	FileEntry *file_entry;
	GSequenceIter *ptr, *parent_ptr;
	GSequence *files;
	gboolean replace_dummy;
	GHashTable *parent_hash;

	parent_ptr = g_hash_table_lookup (model->details->directory_reverse_map,
					  directory);
	if (parent_ptr) {
		file_entry = g_sequence_get (parent_ptr);
		ptr = g_hash_table_lookup (file_entry->reverse_map, file);
	} else {
		file_entry = NULL;
		ptr = g_hash_table_lookup (model->details->top_reverse_map, file);
	}

	if (ptr != NULL) {
		g_warning ("file already in tree (parent_ptr: %p)!!!\n", parent_ptr);
		return FALSE;
	}
	
	file_entry = g_new0 (FileEntry, 1);
	file_entry->file = nautilus_file_ref (file);
	file_entry->parent = NULL;
	file_entry->subdirectory = NULL;
	file_entry->files = NULL;
	
	files = model->details->files;
	parent_hash = model->details->top_reverse_map;
	
	replace_dummy = FALSE;

	if (parent_ptr != NULL) {
		file_entry->parent = g_sequence_get (parent_ptr);
		/* At this point we set loaded. Either we saw
		 * "done" and ignored it waiting for this, or we do this
		 * earlier, but then we replace the dummy row anyway,
		 * so it doesn't matter */
		file_entry->parent->loaded = 1;
		parent_hash = file_entry->parent->reverse_map;
		files = file_entry->parent->files;
		if (g_sequence_get_length (files) == 1) {
			GSequenceIter *dummy_ptr = g_sequence_get_iter_at_pos (files, 0);
			FileEntry *dummy_entry = g_sequence_get (dummy_ptr);
			if (dummy_entry->file == NULL) {
				/* replace the dummy loading entry */
				model->details->stamp++;
				g_sequence_remove (dummy_ptr);
				
				replace_dummy = TRUE;
			}
		}
	}

	
	file_entry->ptr = g_sequence_insert_sorted (files, file_entry,
					    nautilus_list_model_file_entry_compare_func, model);

	g_hash_table_insert (parent_hash, file, file_entry->ptr);
	
	iter.stamp = model->details->stamp;
	iter.user_data = file_entry->ptr;

	path = gtk_tree_model_get_path (GTK_TREE_MODEL (model), &iter);
	if (replace_dummy) {
		gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter);
	} else {
		gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter);
	}

	if (nautilus_file_is_directory (file)) {
		file_entry->files = g_sequence_new ((GDestroyNotify)file_entry_free);

		add_dummy_row (model, file_entry);

		gtk_tree_model_row_has_child_toggled (GTK_TREE_MODEL (model),
						      path, &iter);
	}
	gtk_tree_path_free (path);
	
	return TRUE;
}
Esempio n. 26
0
MdatRecovFile *
mdat_recov_file_create (FILE * file, gboolean datafile, GError ** err)
{
  MdatRecovFile *mrf = g_new0 (MdatRecovFile, 1);
  guint32 fourcc, size;

  g_return_val_if_fail (file != NULL, NULL);

  mrf->file = file;
  mrf->rawfile = datafile;

  /* get the file/data length */
  if (fseek (file, 0, SEEK_END) != 0)
    goto file_length_error;
  /* still needs to deduce the mdat header and ftyp size */
  mrf->data_size = ftell (file);
  if (mrf->data_size == -1L)
    goto file_length_error;

  if (fseek (file, 0, SEEK_SET) != 0)
    goto file_seek_error;

  if (datafile) {
    /* this file contains no atoms, only raw data to be placed on the mdat
     * this happens when faststart mode is used */
    mrf->mdat_start = 0;
    mrf->mdat_header_size = 16;
    mrf->mdat_size = 16;
    return mrf;
  }

  if (!read_atom_header (file, &fourcc, &size)) {
    goto parse_error;
  }
  if (fourcc != FOURCC_ftyp) {
    /* this could be a prefix atom, let's skip it and try again */
    if (fseek (file, size - 8, SEEK_CUR) != 0) {
      goto file_seek_error;
    }
    if (!read_atom_header (file, &fourcc, &size)) {
      goto parse_error;
    }
  }

  if (fourcc != FOURCC_ftyp) {
    goto parse_error;
  }
  if (fseek (file, size - 8, SEEK_CUR) != 0)
    goto file_seek_error;

  /* we don't parse this if we have a tmpdatafile */
  if (!mdat_recov_file_parse_mdat_start (mrf)) {
    g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
        "Error while parsing mdat atom");
    goto fail;
  }

  return mrf;

parse_error:
  g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
      "Failed to parse atom");
  goto fail;

file_seek_error:
  g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
      "Failed to seek to start of the file");
  goto fail;

file_length_error:
  g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
      "Failed to determine file size");
  goto fail;

fail:
  mdat_recov_file_free (mrf);
  return NULL;
}
Esempio n. 27
0
void
dlg_export_to_picasaweb (GthBrowser *browser,
		         GList      *file_list)
{
	DialogData       *data;
	GtkTreeSelection *selection;
	GList            *scan;
	int               n_total;
	goffset           total_size;
	char             *total_size_formatted;
	char             *text;

	data = g_new0 (DialogData, 1);
	data->browser = browser;
	data->location = gth_file_data_dup (gth_browser_get_location_data (browser));
	data->builder = _gtk_builder_new_from_file ("export-to-picasaweb.ui", "picasaweb");
	data->dialog = _gtk_builder_get_widget (data->builder, "export_dialog");
	data->cancellable = g_cancellable_new ();

	{
		GtkCellLayout   *cell_layout;
		GtkCellRenderer *renderer;

		cell_layout = GTK_CELL_LAYOUT (GET_WIDGET ("name_treeviewcolumn"));

		renderer = gtk_cell_renderer_pixbuf_new ();
		gtk_cell_layout_pack_start (cell_layout, renderer, FALSE);
		gtk_cell_layout_set_attributes (cell_layout, renderer,
						"icon-name", ALBUM_ICON_COLUMN,
						NULL);

		renderer = gtk_cell_renderer_text_new ();
		gtk_cell_layout_pack_start (cell_layout, renderer, TRUE);
		gtk_cell_layout_set_attributes (cell_layout, renderer,
						"text", ALBUM_NAME_COLUMN,
						NULL);

		renderer = gtk_cell_renderer_pixbuf_new ();
		gtk_cell_layout_pack_start (cell_layout, renderer, FALSE);
		gtk_cell_layout_set_attributes (cell_layout, renderer,
						"icon-name", ALBUM_EMBLEM_COLUMN,
						NULL);
	}

	_gtk_window_resize_to_fit_screen_height (data->dialog, 500);

	data->file_list = NULL;
	n_total = 0;
	total_size = 0;
	for (scan = file_list; scan; scan = scan->next) {
		GthFileData *file_data = scan->data;
		const char  *mime_type;

		mime_type = gth_file_data_get_mime_type (file_data);
		if (g_content_type_equals (mime_type, "image/bmp")
		    || g_content_type_equals (mime_type, "image/gif")
		    || g_content_type_equals (mime_type, "image/jpeg")
		    || g_content_type_equals (mime_type, "image/png"))
		{
			total_size += g_file_info_get_size (file_data->info);
			n_total++;
			data->file_list = g_list_prepend (data->file_list, g_object_ref (file_data));
		}
	}
	data->file_list = g_list_reverse (data->file_list);

	if (data->file_list == NULL) {
		GError *error;

		if (data->conn != NULL)
			gth_task_dialog (GTH_TASK (data->conn), TRUE);

		error = g_error_new_literal (GTH_ERROR, GTH_ERROR_GENERIC, _("No valid file selected."));
		_gtk_error_dialog_from_gerror_show (GTK_WINDOW (browser), _("Could not export the files"), &error);
		destroy_dialog (data);
		return;
	}

	total_size_formatted = g_format_size_for_display (total_size);
	text = g_strdup_printf (g_dngettext (NULL, "%d file (%s)", "%d files (%s)", n_total), n_total, total_size_formatted);
	gtk_label_set_text (GTK_LABEL (GET_WIDGET ("images_info_label")), text);
	g_free (text);
	g_free (total_size_formatted);

	/* Set the widget data */

	data->list_view = gth_file_list_new (GTH_FILE_LIST_TYPE_NO_SELECTION, FALSE);
	gth_file_list_set_thumb_size (GTH_FILE_LIST (data->list_view), 112);
	gth_file_view_set_spacing (GTH_FILE_VIEW (gth_file_list_get_view (GTH_FILE_LIST (data->list_view))), 0);
	gth_file_list_enable_thumbs (GTH_FILE_LIST (data->list_view), TRUE);
	gth_file_list_set_caption (GTH_FILE_LIST (data->list_view), "none");
	gth_file_list_set_sort_func (GTH_FILE_LIST (data->list_view), gth_main_get_sort_type ("file::name")->cmp_func, FALSE);
	gtk_widget_show (data->list_view);
	gtk_box_pack_start (GTK_BOX (GET_WIDGET ("images_box")), data->list_view, TRUE, TRUE, 0);
	gth_file_list_set_files (GTH_FILE_LIST (data->list_view), data->file_list);

	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (GET_WIDGET ("album_liststore")), ALBUM_NAME_COLUMN, GTK_SORT_ASCENDING);

	gtk_widget_set_sensitive (GET_WIDGET ("upload_button"), FALSE);

	/* Set the signals handlers. */

	g_signal_connect (data->dialog,
			  "delete-event",
			  G_CALLBACK (gtk_widget_hide_on_delete),
			  NULL);
	g_signal_connect (data->dialog,
			  "response",
			  G_CALLBACK (export_dialog_response_cb),
			  data);
	g_signal_connect (GET_WIDGET ("add_album_button"),
			  "clicked",
			  G_CALLBACK (add_album_button_clicked_cb),
			  data);
	g_signal_connect (GET_WIDGET ("edit_accounts_button"),
			  "clicked",
			  G_CALLBACK (edit_accounts_button_clicked_cb),
			  data);
	g_signal_connect (GET_WIDGET ("account_combobox"),
			  "changed",
			  G_CALLBACK (account_combobox_changed_cb),
			  data);

	selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (GET_WIDGET ("albums_treeview")));
	gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
	g_signal_connect (selection,
			  "changed",
			  G_CALLBACK (albums_treeview_selection_changed_cb),
			  data);

	data->accounts = picasa_web_accounts_load_from_file (&data->email);
	auto_select_account (data);
}
Esempio n. 28
0
static RHKPage*
rhk_sm3_read_page(const guchar **buffer,
                  gsize *len)

{
    RHKPage *page;
    const guchar *p = *buffer;
    guint i, expected;

    if (!*len)
        return NULL;

    if (*len < HEADER_SIZE + 4) {
        g_warning("Page header truncated");
        return NULL;
    }
    if (memcmp(p + MAGIC_OFFSET, MAGIC, MAGIC_SIZE) != 0) {
        g_warning("Magic doesn't match");
        return NULL;
    }

    page = g_new0(RHKPage, 1);
    page->param_size = get_WORD(&p);
    gwy_debug("param_size = %u", page->param_size);
    if (*len < page->param_size + 4) {
        g_warning("Real page header truncated");
        goto FAIL;
    }
    /* TODO: Convert to UTF-8, store to meta */
    memcpy(page->version, p, MAGIC_TOTAL_SIZE);
    p += MAGIC_TOTAL_SIZE;
    page->string_count = get_WORD(&p);
    gwy_debug("string_count = %u", page->string_count);
    page->type = get_DWORD(&p);
    gwy_debug("type = %u", page->type);
    page->page_type = get_DWORD(&p);
    gwy_debug("page_type = %u", page->page_type);
    page->data_sub_source = get_DWORD(&p);
    page->line_type = get_DWORD(&p);
    page->x_coord = get_DWORD(&p);
    page->y_coord = get_DWORD(&p);
    page->x_size = get_DWORD(&p);
    page->y_size = get_DWORD(&p);
    gwy_debug("x_size = %u, y_size = %u", page->x_size, page->y_size);
    page->source_type = get_DWORD(&p);
    page->image_type = get_DWORD(&p);
    gwy_debug("image_type = %u", page->image_type);
    page->scan_dir = get_DWORD(&p);
    gwy_debug("scan_dir = %u", page->scan_dir);
    page->group_id = get_DWORD(&p);
    gwy_debug("group_id = %u", page->group_id);
    page->data_size = get_DWORD(&p);
    gwy_debug("data_size = %u", page->data_size);
    page->min_z_value = (gint)get_DWORD(&p);
    page->max_z_value = (gint)get_DWORD(&p);
    gwy_debug("min,max_z_value = %d %d", page->min_z_value, page->max_z_value);
    page->x_scale = get_FLOAT(&p);
    page->y_scale = get_FLOAT(&p);
    page->z_scale = get_FLOAT(&p);
    gwy_debug("x,y,z_scale = %g %g %g",
              page->x_scale, page->y_scale, page->z_scale);
    page->xy_scale = get_FLOAT(&p);
    page->x_offset = get_FLOAT(&p);
    page->y_offset = get_FLOAT(&p);
    page->z_offset = get_FLOAT(&p);
    gwy_debug("x,y,z_offset = %g %g %g",
              page->x_offset, page->y_offset, page->z_offset);
    page->period = get_FLOAT(&p);
    page->bias = get_FLOAT(&p);
    page->current = get_FLOAT(&p);
    page->angle = get_FLOAT(&p);
    gwy_debug("period = %g, bias = %g, current = %g, angle = %g",
              page->period, page->bias, page->current, page->angle);
    memcpy(page->page_id, p, 16);
    p += 16;

    p = *buffer + 2 + page->param_size;
    for (i = 0; i < page->string_count; i++) {
        gchar *s;

        gwy_debug("position %04x", p - *buffer);
        s = rhk_sm3_read_string(&p, *len - (p - *buffer));
        if (!s) {
            g_warning("String truncated");
            goto FAIL;
        }
        if (i < RHK_STRING_NSTRINGS)
            page->strings[i] = s;
        else
            g_free(s);
    }

    expected = page->x_size * page->y_size * sizeof(gint32);
    gwy_debug("expecting %u bytes of page data now", expected);
    if (*len < (p - *buffer) + expected) {
        g_warning("Page data truncated");
        goto FAIL;
    }

    if (page->type == RHK_TYPE_IMAGE)
        page->page_data = p;
    else
        page->spectral_data = p;
    p += expected;

    if (page->type == RHK_TYPE_IMAGE) {
        if (*len < (p - *buffer) + 4) {
            g_warning("Color data header truncated");
            goto FAIL;
        }
        /* Info size includes itself */
        page->color_info.size = get_DWORD(&p) - 2;
        if (*len < (p - *buffer) + page->color_info.size) {
            g_warning("Color data truncated");
            goto FAIL;
        }

        p += page->color_info.size;
    }

    *len -= p - *buffer;
    *buffer = p;
    return page;

FAIL:
    rhk_sm3_page_free(page);
    return NULL;
}
Esempio n. 29
0
/* Config struct routines */
void
mail_config_init (EMailSession *session)
{
	g_return_if_fail (E_IS_MAIL_SESSION (session));

	if (config)
		return;

	config = g_new0 (MailConfig, 1);

	mail_settings = g_settings_new ("org.gnome.evolution.mail");

	/* Composer Configuration */

	settings_outlook_filenames_changed (
		mail_settings, "composer-outlook-filenames", NULL);
	g_signal_connect (
		mail_settings, "changed::composer-outlook-filenames",
		G_CALLBACK (settings_outlook_filenames_changed), NULL);

	/* Display Configuration */

	g_signal_connect (
		mail_settings, "changed::address-compress",
		G_CALLBACK (settings_bool_value_changed),
		&config->address_compress);
	config->address_compress = g_settings_get_boolean (
		mail_settings, "address-compress");

	g_signal_connect (
		mail_settings, "changed::address-count",
		G_CALLBACK (settings_int_value_changed),
		&config->address_count);
	config->address_count = g_settings_get_int (
		mail_settings, "address-count");

	/* Junk Configuration */

	g_signal_connect (
		mail_settings, "changed::junk-check-custom-header",
		G_CALLBACK (settings_jh_check_changed), session);
	config->jh_check = g_settings_get_boolean (
		mail_settings, "junk-check-custom-header");

	g_signal_connect (
		mail_settings, "changed::junk-custom-header",
		G_CALLBACK (settings_jh_headers_changed), session);

	g_signal_connect (
		mail_settings, "changed::junk-lookup-addressbook",
		G_CALLBACK (settings_bool_value_changed), &config->book_lookup);
	config->book_lookup = g_settings_get_boolean (
		mail_settings, "junk-lookup-addressbook");

	g_signal_connect (
		mail_settings, "changed::junk-lookup-addressbook-local-only",
		G_CALLBACK (settings_bool_value_changed),
		&config->book_lookup_local_only);
	config->book_lookup_local_only = g_settings_get_boolean (
		mail_settings, "junk-lookup-addressbook-local-only");

	settings_jh_check_changed (mail_settings, NULL, session);
}
Esempio n. 30
0
static gboolean
xmms_modplug_init (xmms_xform_t *xform)
{
	xmms_modplug_data_t *data;
	const gchar *metakey;
	gint filesize;
	xmms_config_property_t *cfgv;
	gint i;

	g_return_val_if_fail (xform, FALSE);

	data = g_new0 (xmms_modplug_data_t, 1);

	xmms_xform_private_data_set (xform, data);

	for (i = 0; i < G_N_ELEMENTS (config_params); i++) {
		cfgv = xmms_xform_config_lookup (xform, config_params[i].key);
		xmms_config_property_callback_set (cfgv,
		                                   xmms_modplug_config_changed,
		                                   data);

		xmms_modplug_config_changed (XMMS_OBJECT (cfgv), NULL, data);
	}

	/* mFrequency and mResamplingMode are set in config_changed */
	data->settings.mChannels = 2;
	data->settings.mBits = 16;
	ModPlug_SetSettings (&data->settings);

	xmms_xform_outdata_type_add (xform,
	                             XMMS_STREAM_TYPE_MIMETYPE,
	                             "audio/pcm",
	                             XMMS_STREAM_TYPE_FMT_FORMAT,
	                             XMMS_SAMPLE_FORMAT_S16,
	                             XMMS_STREAM_TYPE_FMT_CHANNELS,
	                             2,
	                             XMMS_STREAM_TYPE_FMT_SAMPLERATE,
	                             data->settings.mFrequency,
	                             XMMS_STREAM_TYPE_END);

	data->buffer = g_string_new ("");

	for (;;) {
		xmms_error_t error;
		gchar buf[4096];
		gint ret;

		ret = xmms_xform_read (xform, buf, sizeof (buf), &error);
		if (ret == -1) {
			XMMS_DBG ("Error reading mod");
			return FALSE;
		}
		if (ret == 0) {
			break;
		}
		g_string_append_len (data->buffer, buf, ret);
	}

	data->mod = ModPlug_Load (data->buffer->str, data->buffer->len);
	if (!data->mod) {
		XMMS_DBG ("Error loading mod");
		return FALSE;
	}

	metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_SIZE;
	if (xmms_xform_metadata_get_int (xform, metakey, &filesize)) {
		metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION;
		xmms_xform_metadata_set_int (xform, metakey,
		                             ModPlug_GetLength (data->mod));
	}

	metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_TITLE;
	xmms_xform_metadata_set_str (xform, metakey, ModPlug_GetName (data->mod));

	return TRUE;
}