コード例 #1
0
static void
clutter_flow_layout_get_preferred_height (ClutterLayoutManager *manager,
                                          ClutterContainer     *container,
                                          gfloat                for_width,
                                          gfloat               *min_height_p,
                                          gfloat               *nat_height_p)
{
  ClutterFlowLayoutPrivate *priv = CLUTTER_FLOW_LAYOUT (manager)->priv;
  GList *l, *children = clutter_container_get_children (container);
  gint n_columns, line_item_count, line_count;
  gfloat total_min_height, total_natural_height;
  gfloat line_min_height, line_natural_height;
  gfloat max_min_height, max_natural_height;
  gfloat item_x;

  n_columns = get_columns (CLUTTER_FLOW_LAYOUT (manager), for_width);

  total_min_height = 0;
  total_natural_height = 0;

  line_min_height = 0;
  line_natural_height = 0;

  line_item_count = 0;
  line_count = 0;

  item_x = 0;

  /* clear the line height arrays */
  if (priv->line_min != NULL)
    g_array_free (priv->line_min, TRUE);

  if (priv->line_natural != NULL)
    g_array_free (priv->line_natural, TRUE);

  priv->line_min = g_array_sized_new (FALSE, FALSE,
                                      sizeof (gfloat),
                                      16);
  priv->line_natural = g_array_sized_new (FALSE, FALSE,
                                          sizeof (gfloat),
                                          16);

  if (children)
    line_count = 1;

  max_min_height = max_natural_height = 0;

  for (l = children; l != NULL; l = l->next)
    {
      ClutterActor *child = l->data;
      gfloat child_min, child_natural;
      gfloat new_x, item_width;

      if (!CLUTTER_ACTOR_IS_VISIBLE (child))
        continue;

      if (priv->orientation == CLUTTER_FLOW_HORIZONTAL && for_width > 0)
        {
          if (line_item_count == n_columns)
            {
              total_min_height += line_min_height;
              total_natural_height += line_natural_height;

              g_array_append_val (priv->line_min,
                                  line_min_height);
              g_array_append_val (priv->line_natural,
                                  line_natural_height);

              line_min_height = line_natural_height = 0;

              line_item_count = 0;
              line_count += 1;
              item_x = 0;
            }

          new_x = ((line_item_count + 1) * (for_width + priv->col_spacing))
                / n_columns;
          item_width = new_x - item_x - priv->col_spacing;

          clutter_actor_get_preferred_height (child, item_width,
                                              &child_min,
                                              &child_natural);

          line_min_height = MAX (line_min_height, child_min);
          line_natural_height = MAX (line_natural_height, child_natural);

          item_x = new_x;
          line_item_count += 1;

          max_min_height = MAX (max_min_height, line_min_height);
          max_natural_height = MAX (max_natural_height, line_natural_height);
        }
      else
        {
          clutter_actor_get_preferred_height (child, for_width,
                                              &child_min,
                                              &child_natural);

          max_min_height = MAX (max_min_height, child_min);
          max_natural_height = MAX (max_natural_height, child_natural);

          total_min_height += max_min_height;
          total_natural_height += max_natural_height;

          line_count += 1;
        }
    }

  g_list_free (children);

  priv->row_height = max_natural_height;

  if (priv->max_row_height > 0 && priv->row_height > priv->max_row_height)
    priv->row_height = MAX (priv->max_row_height, max_min_height);

  if (priv->row_height < priv->min_row_height)
    priv->row_height = priv->min_row_height;

  if (priv->orientation == CLUTTER_FLOW_HORIZONTAL && for_width > 0)
    {
      /* if we have a non-full row we need to add it */
      if (line_item_count > 0)
        {
          total_min_height += line_min_height;
          total_natural_height += line_natural_height;

          g_array_append_val (priv->line_min,
                              line_min_height);
          g_array_append_val (priv->line_natural,
                              line_natural_height);
        }

      priv->line_count = line_count;
      if (priv->line_count > 0)
        {
          gfloat total_spacing;

          total_spacing = priv->row_spacing * (priv->line_count - 1);

          total_min_height += total_spacing;
          total_natural_height += total_spacing;
        }
    }
  else
    {
      g_array_append_val (priv->line_min, line_min_height);
      g_array_append_val (priv->line_natural, line_natural_height);

      priv->line_count = line_count;

      if (priv->line_count > 0)
        {
          gfloat total_spacing;

          total_spacing = priv->col_spacing * priv->line_count;

          total_min_height += total_spacing;
          total_natural_height += total_spacing;
        }
    }

  CLUTTER_NOTE (LAYOUT,
                "Flow[h]: %d lines (%d per line): w [ %.2f, %.2f ] for h %.2f",
                n_columns, priv->line_count,
                total_min_height,
                total_natural_height,
                for_width);

  if (min_height_p)
    *min_height_p = total_min_height;

  if (nat_height_p)
    *nat_height_p = total_natural_height;
}
コード例 #2
0
static gboolean
process_nduseropt_dnssl (NMIP6Device *device, struct nd_opt_hdr *opt)
{
	size_t opt_len;
	struct nd_opt_dnssl *dnssl_opt;
	unsigned char *opt_ptr;
	time_t now = time (NULL);
	GArray *new_domains;
	NMIP6DNSSL domain, *cur_domain;
	gboolean changed;
	guint i;

	opt_len = opt->nd_opt_len;

	if (opt_len < 2)
		return FALSE;

	dnssl_opt = (struct nd_opt_dnssl *) opt;

	opt_ptr = (unsigned char *)(dnssl_opt + 1);
	opt_len = (opt_len - 1) * 8; /* prefer bytes for later handling */

	new_domains = g_array_new (FALSE, FALSE, sizeof (NMIP6DNSSL));

	changed = FALSE;

	/* Pad the DNS server expiry somewhat to give a bit of slack in cases
	 * where one RA gets lost or something (which can happen on unreliable
	 * links like wifi where certain types of frames are not retransmitted).
	 * Note that 0 has special meaning and is therefore not adjusted.
	 */
	domain.expires = ntohl (dnssl_opt->nd_opt_dnssl_lifetime);
	if (domain.expires > 0)
		domain.expires += now + 10;

	while (opt_len) {
		const char *domain_str;

		domain_str = parse_dnssl_domain (opt_ptr, opt_len);
		if (domain_str == NULL) {
			nm_log_dbg (LOGD_IP6, "(%s): invalid DNSSL option, parsing aborted",
			            device->iface);
			break;
		}

		/* The DNSSL encoding of domains happen to occupy the same size
		 * as the length of the resulting string, including terminating
		 * null. */
		opt_ptr += strlen (domain_str) + 1;
		opt_len -= strlen (domain_str) + 1;

		/* Ignore empty domains. They're probably just padding... */
		if (domain_str[0] == '\0')
			continue;

		/* Update cached domain information if we've seen this domain before */
		for (i = 0; i < device->dnssl_domains->len; i++) {
			cur_domain = &(g_array_index (device->dnssl_domains, NMIP6DNSSL, i));

			if (strcmp (domain_str, cur_domain->domain) != 0)
				continue;

			cur_domain->expires = domain.expires;

			if (domain.expires > 0) {
				nm_log_dbg (LOGD_IP6, "(%s): refreshing RA-provided domain %s (expires in %ld seconds)",
				            device->iface, domain_str,
				            domain.expires - now);
				break;
			}

			nm_log_dbg (LOGD_IP6, "(%s): removing RA-provided domain %s on router request",
			            device->iface, domain_str);

			g_array_remove_index (device->dnssl_domains, i);
			changed = TRUE;
			break;
		}

		if (domain.expires == 0)
			continue;
		if (i < device->dnssl_domains->len)
			continue;

		nm_log_dbg (LOGD_IP6, "(%s): found RA-provided domain %s (expires in %ld seconds)",
		            device->iface, domain_str, domain.expires - now);

		g_assert (strlen (domain_str) < sizeof (domain.domain));
		strcpy (domain.domain, domain_str);
		g_array_append_val (new_domains, domain);
	}

	/* New domains must be added in the order they are listed in the
	 * RA option and before any existing domains.
	 *
	 * Note: This is the place to remove domains if we want to cap the
	 *       number of domains. The RFC states that the one to expire
	 *       first of the existing domains should be removed.
	 */
	if (new_domains->len) {
		g_array_prepend_vals (device->dnssl_domains,
		                      new_domains->data, new_domains->len);
		changed = TRUE;
	}

	g_array_free (new_domains, TRUE);

	/* Timeouts may have changed even if domains didn't */
	set_dnssl_timeout (device);

	return changed;
}
コード例 #3
0
ファイル: utils.c プロジェクト: aelarabawy/NetworkManager
/**
 * parse_output_fields:
 * @field_str: comma-separated field names to parse
 * @fields_array: array of allowed fields
 * @parse_groups: whether the fields can contain group prefix (e.g. general.driver)
 * @group_fields: (out) (allow-none): array of field names for particular groups
 * @error: (out) (allow-none): location to store error, or %NULL
 *
 * Parses comma separated fields in @fields_str according to @fields_array.
 * When @parse_groups is %TRUE, fields can be in the form 'group.field'. Then
 * @group_fields will be filled with the required field for particular group.
 * @group_fields array corresponds to the returned array.
 * Examples:
 *   @field_str:     "type,name,uuid" | "ip4,general.device" | "ip4.address,ip6"
 *   returned array:   2    0    1    |   7         0        |     7         9
 *   @group_fields:   NULL NULL NULL  |  NULL    "device"    | "address"    NULL
 *
 * Returns: #GArray with indices representing fields in @fields_array.
 *   Caller is responsible for freeing the array.
 */
GArray *
parse_output_fields (const char *fields_str,
                     const NmcOutputField fields_array[],
                     gboolean parse_groups,
                     GPtrArray **group_fields,
                     GError **error)
{
	char **fields, **iter;
	GArray *array;
	int i, j;

	g_return_val_if_fail (error == NULL || *error == NULL, NULL);
	g_return_val_if_fail (group_fields == NULL || *group_fields == NULL, NULL);

	array = g_array_new (FALSE, FALSE, sizeof (int));
	if (parse_groups && group_fields)
		*group_fields = g_ptr_array_new_full (20, (GDestroyNotify) g_free);

	/* Split supplied fields string */
	fields = g_strsplit_set (fields_str, ",", -1);
	for (iter = fields; iter && *iter; iter++) {
		int idx = -1;

		g_strstrip (*iter);
		if (parse_groups) {
			/* e.g. "general.device,general.driver,ip4,ip6" */
			gboolean found = FALSE;
			char *left = *iter;
			char *right = strchr (*iter, '.');

			if (right)
				*right++ = '\0';

			for (i = 0; fields_array[i].name; i++) {
				if (strcasecmp (left, fields_array[i].name) == 0) {
					NmcOutputField *valid_names = fields_array[i].group;
					idx = i;
					if (!right && !valid_names) {
						found = TRUE;
						break;
					}
					for (j = 0; valid_names && valid_names[j].name; j++) {
						if (!right || strcasecmp (right, valid_names[j].name) == 0) {
							found = TRUE;
							break;
						}
					}
					if (found)
						break;
				}
			}
			if (found) {
				/* Add index to array, and field name (or NULL) to group_fields array */
				g_array_append_val (array, idx);
				if (group_fields && *group_fields)
					g_ptr_array_add (*group_fields, g_strdup (right));
			}
			if (right)
				*(right-1) = '.';  /* Restore the original string */
		} else {
			/* e.g. "general,ip4,ip6" */
			for (i = 0; fields_array[i].name; i++) {
				if (strcasecmp (*iter, fields_array[i].name) == 0) {
					g_array_append_val (array, i);
					break;
				}
			}
		}

		/* Field was not found - error case */
		if (fields_array[i].name == NULL) {
			/* Set GError */
			if (!strcasecmp (*iter, "all") || !strcasecmp (*iter, "common"))
				g_set_error (error, NMCLI_ERROR, 0, _("field '%s' has to be alone"), *iter);
			else {
				char *allowed_fields = nmc_get_allowed_fields (fields_array, idx);
				g_set_error (error, NMCLI_ERROR, 1, _("invalid field '%s'; allowed fields: %s"),
				             *iter, allowed_fields);
				g_free (allowed_fields);
			}

			/* Free arrays on error */
			g_array_free (array, TRUE);
			array = NULL;
			if (group_fields && *group_fields) {
				g_ptr_array_free (*group_fields, TRUE);
				*group_fields = NULL;
			}
			goto done;
		}
	}
done:
	if (fields)
		g_strfreev (fields);
	return array;
}
コード例 #4
0
int main(int argc, char * argv[]){
    int i = 1;
    const char * bigram_filename = NULL;

    setlocale(LC_ALL, "");
    while ( i < argc ){
        if ( strcmp("--help", argv[i]) == 0 ){
            print_help();
            exit(0);
        } else if ( strcmp("-k", argv[i]) == 0 ){
            if ( ++i >= argc ){
                print_help();
                exit(EINVAL);
            }
            g_prune_k = atoi(argv[i]);
        } else if ( strcmp("--CDF", argv[i]) == 0 ){
            if ( ++i >= argc ){
                print_help();
                exit(EINVAL);
            }
            g_prune_poss = atof(argv[i]);
        } else {
            bigram_filename = argv[i];
        }
        ++i;
    }

    /* TODO: magic header signature check here. */
    KMixtureModelBigram bigram(K_MIXTURE_MODEL_MAGIC_NUMBER);
    bigram.attach(bigram_filename, ATTACH_READWRITE);

    KMixtureModelMagicHeader magic_header;
    bigram.get_magic_header(magic_header);
    GArray * items = g_array_new(FALSE, FALSE, sizeof(phrase_token_t));
    bigram.get_all_items(items);

    /* print prune progress */
    size_t progress = 0; size_t onestep = items->len / 20;
    for ( size_t i = 0; i < items->len; ++i ){
        if ( progress >= onestep ) {
            progress = 0; fprintf(stderr, "*");
        }
        progress ++;

        phrase_token_t * token = &g_array_index(items, phrase_token_t, i);
        KMixtureModelSingleGram * single_gram = NULL;
        bigram.load(*token, single_gram);

        FlexibleBigramPhraseArray removed_array = g_array_new(FALSE, FALSE, sizeof(KMixtureModelArrayItemWithToken));

        prune_k_mixture_model(&magic_header, single_gram, removed_array);
        bigram.store(*token, single_gram);

        delete single_gram;

        /* post processing for unigram reduce */
        for (size_t m = 0; m < removed_array->len; ++m ){
            KMixtureModelArrayItemWithToken * item =
                &g_array_index(removed_array,
                              KMixtureModelArrayItemWithToken, m);
            KMixtureModelArrayHeader array_header;
            assert(bigram.get_array_header(item->m_token, array_header));
            array_header.m_freq -= item->m_item.m_WC;
            assert(array_header.m_freq >= 0);
            assert(bigram.set_array_header(item->m_token, array_header));
        }

        g_array_free(removed_array, TRUE);
        removed_array = NULL;
    }

    fprintf(stderr, "\n");

    bigram.set_magic_header(magic_header);

    /* post processing clean up zero items */
    KMixtureModelArrayHeader array_header;
    for ( size_t i = 0; i < items->len; ++i ){
        phrase_token_t * token = &g_array_index(items, phrase_token_t, i);
        assert(bigram.get_array_header(*token, array_header));
        if ( 0 == array_header.m_WC && 0 == array_header.m_freq )
            assert(bigram.remove(*token));
    }

    g_array_free(items, TRUE);

    return 0;
}
コード例 #5
0
static void
pygi_signal_closure_marshal(GClosure *closure,
                            GValue *return_value,
                            guint n_param_values,
                            const GValue *param_values,
                            gpointer invocation_hint,
                            gpointer marshal_data)
{
    PyGILState_STATE state;
    PyGClosure *pc = (PyGClosure *)closure;
    PyObject *params, *ret = NULL;
    guint i;
    GISignalInfo *signal_info;
    gint n_sig_info_args;
    gint sig_info_highest_arg;
    GSList *list_item = NULL;
    GSList *pass_by_ref_structs = NULL;

    state = PyGILState_Ensure();

    signal_info = ((PyGISignalClosure *)closure)->signal_info;
    n_sig_info_args = g_callable_info_get_n_args(signal_info);
    /* the first argument to a signal callback is instance,
       but instance is not counted in the introspection data */
    sig_info_highest_arg = n_sig_info_args + 1;
    g_assert_cmpint(sig_info_highest_arg, ==, n_param_values);

    /* construct Python tuple for the parameter values */
    params = PyTuple_New(n_param_values);
    for (i = 0; i < n_param_values; i++) {
        /* swap in a different initial data for connect_object() */
        if (i == 0 && G_CCLOSURE_SWAP_DATA(closure)) {
            g_return_if_fail(pc->swap_data != NULL);
            Py_INCREF(pc->swap_data);
            PyTuple_SetItem(params, 0, pc->swap_data);

        } else if (i == 0) {
            PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);

            if (!item) {
                goto out;
            }
            PyTuple_SetItem(params, i, item);

        } else if (i < sig_info_highest_arg) {
            GIArgInfo arg_info;
            GITypeInfo type_info;
            GITypeTag type_tag;
            GIArgument arg = { 0, };
            PyObject *item = NULL;
            gboolean free_array = FALSE;
            gboolean pass_struct_by_ref = FALSE;

            g_callable_info_load_arg(signal_info, i - 1, &arg_info);
            g_arg_info_load_type(&arg_info, &type_info);

            arg = _pygi_argument_from_g_value(&param_values[i], &type_info);

            type_tag = g_type_info_get_tag (&type_info);
            if (type_tag == GI_TYPE_TAG_ARRAY) {
                /* Skip the self argument of param_values */
                arg.v_pointer = _pygi_argument_to_array (&arg,
                                                         _pygi_argument_array_length_marshal,
                                                         (void *)(param_values + 1),
                                                         signal_info,
                                                         &type_info,
                                                         &free_array);
            }

            /* Hack to ensure struct arguments are passed-by-reference allowing
             * callback implementors to modify the struct values. This is needed
             * for keeping backwards compatibility and should be removed in future
             * versions which support signal output arguments as return values.
             * See: https://bugzilla.gnome.org/show_bug.cgi?id=735486
             *
             * Note the logic here must match the logic path taken in _pygi_argument_to_object.
             */
            if (type_tag == GI_TYPE_TAG_INTERFACE) {
                GIBaseInfo *info = g_type_info_get_interface (&type_info);
                GIInfoType info_type = g_base_info_get_type (info);

                if (info_type == GI_INFO_TYPE_STRUCT ||
                        info_type == GI_INFO_TYPE_BOXED ||
                        info_type == GI_INFO_TYPE_UNION) {

                    GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
                    gboolean is_foreign = (info_type == GI_INFO_TYPE_STRUCT) &&
                                          (g_struct_info_is_foreign ((GIStructInfo *) info));

                    if (!is_foreign && !g_type_is_a (gtype, G_TYPE_VALUE) &&
                            g_type_is_a (gtype, G_TYPE_BOXED)) {
                        pass_struct_by_ref = TRUE;
                    }
                }

                g_base_info_unref (info);
            }

            if (pass_struct_by_ref) {
                /* transfer everything will ensure the struct is not copied when wrapped. */
                item = _pygi_argument_to_object (&arg, &type_info, GI_TRANSFER_EVERYTHING);
                if (item && PyObject_IsInstance (item, (PyObject *) &PyGIBoxed_Type)) {
                    ((PyGBoxed *)item)->free_on_dealloc = FALSE;
                    pass_by_ref_structs = g_slist_prepend (pass_by_ref_structs, item);
                }

            } else {
                item = _pygi_argument_to_object (&arg, &type_info, GI_TRANSFER_NOTHING);
            }

            if (free_array) {
                g_array_free (arg.v_pointer, FALSE);
            }

            if (item == NULL) {
                PyErr_Print ();
                goto out;
            }
            PyTuple_SetItem(params, i, item);
        }
    }
    /* params passed to function may have extra arguments */
    if (pc->extra_args) {
        PyObject *tuple = params;
        params = PySequence_Concat(tuple, pc->extra_args);
        Py_DECREF(tuple);
    }
    ret = PyObject_CallObject(pc->callback, params);
    if (ret == NULL) {
        if (pc->exception_handler)
            pc->exception_handler(return_value, n_param_values, param_values);
        else
            PyErr_Print();
        goto out;
    }

    if (G_IS_VALUE(return_value) && pyg_value_from_pyobject(return_value, ret) != 0) {
        PyErr_SetString(PyExc_TypeError,
                        "can't convert return value to desired type");

        if (pc->exception_handler)
            pc->exception_handler(return_value, n_param_values, param_values);
        else
            PyErr_Print();
    }
    Py_DECREF(ret);

    /* Run through the list of structs which have been passed by reference and
     * check if they are being held longer than the duration of the callback
     * execution. This is determined if the ref count is greater than 1.
     * A single ref is held by the argument list and any more would mean the callback
     * stored a ref somewhere else. In this case we make an internal copy of
     * the boxed struct so Python can own the memory to it.
     */
    list_item = pass_by_ref_structs;
    while (list_item) {
        PyObject *item = list_item->data;
        if (item->ob_refcnt > 1) {
            _pygi_boxed_copy_in_place ((PyGIBoxed *)item);
        }
        list_item = g_slist_next (list_item);
    }

 out:
    g_slist_free (pass_by_ref_structs);
    Py_DECREF(params);
    PyGILState_Release(state);
}
コード例 #6
0
ファイル: annots.c プロジェクト: BlueBrain/Poppler
static void
pgd_annots_add_annot (PgdAnnotsDemo *demo)
{
    PopplerRectangle rect;
    PopplerColor     color;
    PopplerAnnot    *annot;
    gdouble          height;

    g_assert (demo->mode == MODE_ADD);

    poppler_page_get_size (demo->page, NULL, &height);

    rect.x1 = demo->start.x;
    rect.y1 = height - demo->start.y;
    rect.x2 = demo->stop.x;
    rect.y2 = height - demo->stop.y;

    color.red = CLAMP ((guint) (demo->annot_color.red * 65535), 0, 65535);
    color.green = CLAMP ((guint) (demo->annot_color.green * 65535), 0, 65535);
    color.blue = CLAMP ((guint) (demo->annot_color.blue * 65535), 0, 65535);

    switch (demo->annot_type) {
        case POPPLER_ANNOT_TEXT:
            annot = poppler_annot_text_new (demo->doc, &rect);

            break;
        case POPPLER_ANNOT_LINE: {
            PopplerPoint start, end;

            start.x = rect.x1;
            start.y = rect.y1;
            end.x = rect.x2;
            end.y = rect.y2;

            annot = poppler_annot_line_new (demo->doc, &rect, &start, &end);
        }
            break;
        case POPPLER_ANNOT_SQUARE:
            annot = poppler_annot_square_new (demo->doc, &rect);
            break;
        case POPPLER_ANNOT_CIRCLE:
            annot = poppler_annot_circle_new (demo->doc, &rect);
            break;
        case POPPLER_ANNOT_HIGHLIGHT: {
            GArray *quads_array;

            quads_array = pgd_annots_create_quads_array_for_rectangle (&rect);
            annot = poppler_annot_text_markup_new_highlight (demo->doc, &rect, quads_array);
            g_array_free (quads_array, TRUE);
        }
            break;
        case POPPLER_ANNOT_UNDERLINE: {
            GArray *quads_array;

            quads_array = pgd_annots_create_quads_array_for_rectangle (&rect);
            annot = poppler_annot_text_markup_new_underline (demo->doc, &rect, quads_array);
            g_array_free (quads_array, TRUE);
        }
            break;
        case POPPLER_ANNOT_SQUIGGLY: {
            GArray *quads_array;

            quads_array = pgd_annots_create_quads_array_for_rectangle (&rect);
            annot = poppler_annot_text_markup_new_squiggly (demo->doc, &rect, quads_array);
            g_array_free (quads_array, TRUE);
        }
            break;
        case POPPLER_ANNOT_STRIKE_OUT: {
            GArray *quads_array;

            quads_array = pgd_annots_create_quads_array_for_rectangle (&rect);
            annot = poppler_annot_text_markup_new_strikeout (demo->doc, &rect, quads_array);
            g_array_free (quads_array, TRUE);
        }
            break;
        default:
            g_assert_not_reached ();
    }

    demo->active_annot = annot;

    poppler_annot_set_color (annot, &color);
    poppler_page_add_annot (demo->page, annot);
    pgd_annots_add_annot_to_model (demo, annot, rect, TRUE);
    g_object_unref (annot);
}
コード例 #7
0
ファイル: monitor.c プロジェクト: parinporecha/displayconfig
/*
 * make_logical_config:
 *
 * Turn outputs and CRTCs into logical MetaMonitorInfo,
 * that will be used by the core and API layer (MetaScreen
 * and friends)
 */
static void
make_logical_config (MetaMonitorManager *manager)
{
  GArray *monitor_infos;
  unsigned int i, j;

  monitor_infos = g_array_sized_new (FALSE, TRUE, sizeof (MetaMonitorInfo),
                                     manager->n_outputs);

  /* Walk the list of MetaCRTCs, and build a MetaMonitorInfo
     for each of them, unless they reference a rectangle that
     is already there.
  */
  for (i = 0; i < manager->n_crtcs; i++)
    {
      MetaCRTC *crtc = &manager->crtcs[i];

      /* Ignore CRTCs not in use */
      if (crtc->current_mode == NULL)
        continue;

      for (j = 0; j < monitor_infos->len; j++)
        {
          MetaMonitorInfo *info = &g_array_index (monitor_infos, MetaMonitorInfo, i);
          if (meta_rectangle_equal (&crtc->rect,
                                    &info->rect))
            {
              crtc->logical_monitor = info;
              break;
            }
        }

      if (crtc->logical_monitor == NULL)
        {
          MetaMonitorInfo info;

          info.number = monitor_infos->len;
          info.rect = crtc->rect;
          info.is_primary = FALSE;
          /* This starts true because we want
             is_presentation only if all outputs are
             marked as such (while for primary it's enough
             that any is marked)
          */
          info.is_presentation = TRUE;
          info.in_fullscreen = -1;
          info.output_id = 0;

          g_array_append_val (monitor_infos, info);

          crtc->logical_monitor = &g_array_index (monitor_infos, MetaMonitorInfo,
                                                  info.number);
        }
    }

  /* Now walk the list of outputs applying extended properties (primary
     and presentation)
  */
  for (i = 0; i < manager->n_outputs; i++)
    {
      MetaOutput *output;
      MetaMonitorInfo *info;

      output = &manager->outputs[i];

      /* Ignore outputs that are not active */
      if (output->crtc == NULL)
        continue;

      /* We must have a logical monitor on every CRTC at this point */
      g_assert (output->crtc->logical_monitor != NULL);

      info = output->crtc->logical_monitor;

      info->is_primary = info->is_primary || output->is_primary;
      info->is_presentation = info->is_presentation && output->is_presentation;

      if (output->is_primary || info->output_id == 0)
        info->output_id = output->output_id;

      if (info->is_primary)
        manager->primary_monitor_index = info->number;
    }

  manager->n_monitor_infos = monitor_infos->len;
  manager->monitor_infos = (void*)g_array_free (monitor_infos, FALSE);
}
コード例 #8
0
ファイル: backend_kwallet.c プロジェクト: hauva69/darktable
// Store (key,value) pairs from a GHashTable in the kwallet.
// Every 'slot' has to take care of it's own data.
gboolean dt_pwstorage_kwallet_set(const backend_kwallet_context_t *context, const gchar* slot, GHashTable* table)
{
  printf("slot %s\n", slot);

  GArray* byte_array = g_array_new(FALSE, FALSE, sizeof(gchar));

  GHashTableIter iter;
  g_hash_table_iter_init (&iter, table);
  gpointer key, value;

  guint size = g_hash_table_size(table);

  size = GINT_TO_BE(size);

  g_array_append_vals(byte_array, &size, sizeof(guint)/sizeof(gchar));

  while (g_hash_table_iter_next (&iter, &key, &value))
  {
    dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_set] storing (%s, %s)\n",(gchar*)key, (gchar*)value);
    gsize length;
    gchar* new_key = char2qstring(key, &length);
    if(new_key == NULL)
    {
      g_free(g_array_free(byte_array, FALSE));
      return FALSE;
    }
    g_array_append_vals(byte_array, new_key, length);
    g_free(new_key);

    gchar* new_value = char2qstring(value, &length);
    if(new_value == NULL)
    {
      g_free(g_array_free(byte_array, FALSE));
      return FALSE;
    }
    g_array_append_vals(byte_array, new_value, length);
    g_free(new_value);
  }

  int wallet_handle = get_wallet_handle(context);
  GError* error = NULL;

  /* signature:
   *
   * in  i handle,
   * in  s folder,
   * in  s key,
   * in  ay value,
   * in  s appid,
   *
   * out i arg_0
   */
  GVariant *ret = g_dbus_proxy_call_sync(context->proxy,
                                         "writeMap",
                                         g_variant_new("(iss@ays)", wallet_handle, kwallet_folder, slot,
                                             g_variant_new_from_data(G_VARIANT_TYPE_BYTESTRING,
                                                 byte_array->data,
                                                 byte_array->len,
                                                 TRUE,
                                                 g_free,
                                                 byte_array->data),
                                             app_id),
                                         G_DBUS_CALL_FLAGS_NONE,
                                         -1,
                                         NULL,
                                         &error);

  g_array_free(byte_array, FALSE);

  if(check_error(error))
  {
    g_variant_unref(ret);
    return FALSE;
  }

  GVariant *child = g_variant_get_child_value(ret, 0);
  int return_code = g_variant_get_int32(child);
  g_variant_unref(child);
  g_variant_unref(ret);

  if (return_code != 0)
    dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_set] Warning: bad return code %d from kwallet\n", return_code);

  return return_code == 0;
}
コード例 #9
0
ファイル: BalancedBst.c プロジェクト: ahmedak/glib-funtions
/* Print preorder traversal */
GArray * balanced_bst_preorder(Bst * tree, GArray * traversal) {
	g_array_free(traversal, TRUE);
	GArray * newtraversal = g_array_new(FALSE, FALSE, sizeof(int));
	g_tree_traverse(tree, (GTraverseFunc)traverse_func, G_PRE_ORDER, newtraversal);
	return newtraversal;
}
コード例 #10
0
ファイル: tracker-writeback.c プロジェクト: UIKit0/tracker
static void
handle_method_call_perform_writeback (TrackerController     *controller,
                                      GDBusMethodInvocation *invocation,
                                      GVariant              *parameters)
{
	TrackerControllerPrivate *priv;
	TrackerDBusRequest *request;
	const gchar *subject;
	GPtrArray *results = NULL;
	GHashTableIter iter;
	gpointer key, value;
	GVariantIter *iter1, *iter2, *iter3;
	GArray *rdf_types_array;
	GStrv rdf_types;
	gchar *rdf_type = NULL;
	GList *writeback_handlers = NULL;

	priv = controller->priv;

	results = g_ptr_array_new_with_free_func ((GDestroyNotify) g_strfreev);
	g_variant_get (parameters, "(&sasaas)", &subject, &iter1, &iter2);

	rdf_types_array = g_array_new (TRUE, TRUE, sizeof (gchar *));
	while (g_variant_iter_loop (iter1, "&s", &rdf_type)) {
		g_array_append_val (rdf_types_array, rdf_type);
	}

	rdf_types = (GStrv) rdf_types_array->data;
	g_array_free (rdf_types_array, FALSE);

	while (g_variant_iter_loop (iter2, "as", &iter3)) {
		GArray *row_array = g_array_new (TRUE, TRUE, sizeof (gchar *));
		gchar *cell = NULL;

		while (g_variant_iter_loop (iter3, "&s", &cell)) {
			g_array_append_val (row_array, cell);
		}

		g_ptr_array_add (results, row_array->data);
		g_array_free (row_array, FALSE);
	}

	g_variant_iter_free (iter1);
	g_variant_iter_free (iter2);

	reset_shutdown_timeout (controller);
	request = tracker_dbus_request_begin (NULL, "%s (%s)", __FUNCTION__, subject);

	g_hash_table_iter_init (&iter, priv->modules);

	while (g_hash_table_iter_next (&iter, &key, &value)) {
		TrackerWritebackModule *module;
		const gchar * const *module_types;

		module = value;
		module_types = tracker_writeback_module_get_rdf_types (module);

		if (sparql_rdf_types_match (module_types, (const gchar * const *) rdf_types)) {
			TrackerWriteback *writeback;

			g_message ("  Updating metadata for subject:'%s' using module:'%s'",
			           subject,
			           module->name);

			writeback = tracker_writeback_module_create (module);
			writeback_handlers = g_list_prepend (writeback_handlers, writeback);
		}
	}

	if (writeback_handlers != NULL) {
		WritebackData *data;
		GTask *task;

		data = writeback_data_new (controller,
		                           writeback_handlers,
		                           priv->connection,
		                           subject,
		                           results,
		                           invocation,
		                           request);
		task = g_task_new (controller, data->cancellable, NULL, NULL);

		/* No need to free data here, it's done in the callback. */
		g_task_set_task_data (task, data, NULL);
		g_task_run_in_thread (task, io_writeback_job);
		g_object_unref (task);
	} else {
		g_dbus_method_invocation_return_error (invocation,
		                                       TRACKER_DBUS_ERROR,
		                                       TRACKER_DBUS_ERROR_UNSUPPORTED,
		                                       "No module for rdf types");
	}

	g_free (rdf_types);
}
コード例 #11
0
ファイル: gimpchannel-select.c プロジェクト: Amerekanets/gimp
void
gimp_channel_select_vectors (GimpChannel    *channel,
                             const gchar    *undo_desc,
                             GimpVectors    *vectors,
                             GimpChannelOps  op,
                             gboolean        antialias,
                             gboolean        feather,
                             gdouble         feather_radius_x,
                             gdouble         feather_radius_y,
                             gboolean        push_undo)
{
  GimpScanConvert *scan_convert;
  GList           *stroke;
  gboolean         coords_added = FALSE;

  g_return_if_fail (GIMP_IS_CHANNEL (channel));
  g_return_if_fail (gimp_item_is_attached (GIMP_ITEM (channel)));
  g_return_if_fail (undo_desc != NULL);
  g_return_if_fail (GIMP_IS_VECTORS (vectors));

  scan_convert = gimp_scan_convert_new ();

  for (stroke = vectors->strokes; stroke; stroke = stroke->next)
    {
      GArray   *coords;
      gboolean  closed;

      coords = gimp_stroke_interpolate (GIMP_STROKE (stroke->data),
                                        1.0, &closed);

      if (coords && coords->len)
        {
          GimpVector2 *points;
          gint         i;

          points = g_new0 (GimpVector2, coords->len);

          for (i = 0; i < coords->len; i++)
            {
              points[i].x = g_array_index (coords, GimpCoords, i).x;
              points[i].y = g_array_index (coords, GimpCoords, i).y;
            }

          gimp_scan_convert_add_polyline (scan_convert, coords->len,
                                          points, TRUE);
          coords_added = TRUE;

          g_free (points);
        }

      if (coords)
        g_array_free (coords, TRUE);
    }

  if (coords_added)
    gimp_channel_select_scan_convert (channel, undo_desc, scan_convert, 0, 0,
                                      op, antialias, feather,
                                      feather_radius_x, feather_radius_y,
                                      push_undo);

  gimp_scan_convert_free (scan_convert);
}
コード例 #12
0
void convert_tabfile(const char *filename, print_info_t print_info)
{			
	struct stat stats;
	if (g_stat (filename, &stats) == -1)
	{
		print_info("File not exist!\n");
		return;
	}
	gchar *basefilename = g_path_get_basename(filename);
	gchar *ch = strrchr(basefilename, '.');
	if (ch)
		*ch = '\0';
	gchar *dirname = g_path_get_dirname(filename);
	FILE *tabfile;
	tabfile = g_fopen(filename,"r");

	gchar *buffer = (gchar *)g_malloc (stats.st_size + 1);
	size_t readsize = fread (buffer, 1, stats.st_size, tabfile);
	fclose (tabfile);
	buffer[readsize] = '\0';	
	
	GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000);
		
	gchar *p, *p1, *p2;
	p = buffer;
	if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters.
		p+=3;
	struct _worditem worditem;
	glong linenum=1;
	while (1) {
		if (*p == '\0') {
                        print_info("Convert over.\n");
                        break;
                }
		p1 = strchr(p,'\n');
		if (!p1) {
			print_info("Error, no new line at the end\n");
			return;
		}
		*p1 = '\0';
		p1++;
		p2 = strchr(p,'\t');
		if (!p2) {
			gchar *str = g_strdup_printf("Warning, no tab, %ld\n", linenum);
			print_info(str);
			g_free(str);
			p= p1;
			linenum++;
			continue;
		}
		*p2 = '\0';
		p2++;
		worditem.word = p;
		worditem.definition = p2;
		my_strstrip(worditem.definition, linenum, print_info);
		g_strstrip(worditem.word);
		g_strstrip(worditem.definition);
		if (!worditem.word[0]) {
			gchar *str = g_strdup_printf("Warning: line %ld, bad word!\n", linenum);
			print_info(str);
			g_free(str);
			p= p1;
                	linenum++;
			continue;
		}
		if (!worditem.definition[0]) {
			gchar *str = g_strdup_printf("Warning: line %ld, bad definition!\n", linenum);
			print_info(str);
			g_free(str);
			p= p1;
                        linenum++;
                        continue;
		}
		g_array_append_val(array, worditem);			
		p= p1;				
		linenum++;
	}		
	g_array_sort(array,comparefunc);
		
	gchar ifofilename[256];
	gchar idxfilename[256];
	gchar dicfilename[256];
	sprintf(ifofilename, "%s" G_DIR_SEPARATOR_S "%s.ifo", dirname, basefilename);
	sprintf(idxfilename, "%s" G_DIR_SEPARATOR_S "%s.idx", dirname, basefilename);
	sprintf(dicfilename, "%s" G_DIR_SEPARATOR_S "%s.dict", dirname, basefilename);
	FILE *ifofile = g_fopen(ifofilename,"wb");
	if (!ifofile) {
		print_info("Write to ifo file failed!\n");
		return;
	}
	FILE *idxfile = g_fopen(idxfilename,"wb");
	if (!idxfile) {
		print_info("Write to idx file failed!\n");
		return;
	}
	FILE *dicfile = g_fopen(dicfilename,"wb");
	if (!dicfile) {
		print_info("Write to dict file failed!\n");
		return;
	}

	guint32 offset_old;
	guint32 tmpglong;
	struct _worditem *pworditem;
	gint definition_len;
	gulong i;
	for (i=0; i< array->len; i++) {
		offset_old = ftell(dicfile);
		pworditem = &g_array_index(array, struct _worditem, i);
		definition_len = strlen(pworditem->definition);
		fwrite(pworditem->definition, 1 ,definition_len,dicfile);
		fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile);
		tmpglong = g_htonl(offset_old);
		fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
		tmpglong = g_htonl(definition_len);
		fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
	}
	fclose(idxfile);
	fclose(dicfile);

	gchar *str = g_strdup_printf("%s wordcount: %d\n", basefilename, array->len);
	print_info(str);
	g_free(str);

#ifndef _WIN32
	gchar command[256];
        sprintf(command, "dictzip %s", dicfilename);
        system(command);
#endif

	g_stat(idxfilename, &stats);
	fprintf(ifofile, "StarDict's dict ifo file\nversion=2.4.2\nwordcount=%d\nidxfilesize=%ld\nbookname=%s\nsametypesequence=m\n", array->len, stats.st_size, basefilename);
	fclose(ifofile);

	g_free(buffer);
	g_array_free(array,TRUE);

	g_free(basefilename);
	g_free(dirname);
}
コード例 #13
0
ファイル: nemo-icon-dnd.c プロジェクト: Acidburn0zzz/nemo
static void
handle_nonlocal_move (NemoIconContainer *container,
		      GdkDragAction action,
		      int x, int y,
		      const char *target_uri,
		      gboolean icon_hit)
{
	GList *source_uris, *p;
	GArray *source_item_locations;
	gboolean free_target_uri, is_rtl;
	int index, item_x;
	GtkAllocation allocation;

	if (container->details->dnd_info->drag_info.selection_list == NULL) {
		return;
	}

	source_uris = NULL;
	for (p = container->details->dnd_info->drag_info.selection_list; p != NULL; p = p->next) {
		/* do a shallow copy of all the uri strings of the copied files */
		source_uris = g_list_prepend (source_uris, ((NemoDragSelectionItem *)p->data)->uri);
	}
	source_uris = g_list_reverse (source_uris);
	
	is_rtl = nemo_icon_container_is_layout_rtl (container);

	source_item_locations = g_array_new (FALSE, TRUE, sizeof (GdkPoint));
	if (!icon_hit) {
		/* Drop onto a container. Pass along the item points to allow placing
		 * the items in their same relative positions in the new container.
		 */
		source_item_locations = g_array_set_size (source_item_locations,
			g_list_length (container->details->dnd_info->drag_info.selection_list));
			
		for (index = 0, p = container->details->dnd_info->drag_info.selection_list;
			p != NULL; index++, p = p->next) {
		    	item_x = ((NemoDragSelectionItem *)p->data)->icon_x;
			if (is_rtl)
				item_x = -item_x - ((NemoDragSelectionItem *)p->data)->icon_width;
		     	g_array_index (source_item_locations, GdkPoint, index).x = item_x;
		     	g_array_index (source_item_locations, GdkPoint, index).y =
				((NemoDragSelectionItem *)p->data)->icon_y;
		}
	}

	free_target_uri = FALSE;
 	/* Rewrite internal desktop URIs to the normal target uri */
	if (eel_uri_is_desktop (target_uri)) {
		target_uri = nemo_get_desktop_directory_uri ();
		free_target_uri = TRUE;
	}

	if (is_rtl) {
		gtk_widget_get_allocation (GTK_WIDGET (container), &allocation);
		x = CANVAS_WIDTH (container, allocation) - x;
	}

	/* start the copy */
	g_signal_emit_by_name (container, "move_copy_items",
			       source_uris,
			       source_item_locations,
			       target_uri,
			       action,
			       x, y);

	if (free_target_uri) {
		g_free ((char *)target_uri);
	}

	g_list_free (source_uris);
	g_array_free (source_item_locations, TRUE);
}
コード例 #14
0
static void
free_string_array (GArray *array)
{
    gchar** lines = (gchar**)g_array_free (array, FALSE);
    g_strfreev (lines);
}
コード例 #15
0
ファイル: cairo-context.cpp プロジェクト: dreamsxin/gjs
static JSBool
setDash_func(JSContext *context,
             unsigned   argc,
             jsval     *vp)
{
    JS::CallArgs argv = JS::CallArgsFromVp (argc, vp);
    JSObject *obj = JSVAL_TO_OBJECT(argv.thisv());

    guint i;
    cairo_t *cr;
    JSObject *dashes;
    double offset;
    JSBool retval = JS_FALSE;
    guint len;
    GArray *dashes_c = NULL;

    if (!gjs_parse_call_args(context, "setDash", "of", argv,
                        "dashes", &dashes, "offset", &offset))
        return JS_FALSE;

    JS_AddObjectRoot(context, &dashes);

    if (!JS_IsArrayObject(context, dashes)) {
        gjs_throw(context, "dashes must be an array");
        goto out;
    }

    if (!JS_GetArrayLength(context, dashes, &len)) {
        gjs_throw(context, "Can't get length of dashes");
        goto out;
    }

    dashes_c = g_array_sized_new (FALSE, FALSE, sizeof(double), len);
    for (i = 0; i < len; ++i) {
        jsval elem;
        double b;

        elem = JSVAL_VOID;
        if (!JS_GetElement(context, dashes, i, &elem)) {
            goto out;
        }
        if (JSVAL_IS_VOID(elem))
            continue;

        if (!JS_ValueToNumber(context, elem, &b))
            goto out;
        if (b <= 0) {
            gjs_throw(context, "Dash value must be positive");
            goto out;
        }

        g_array_append_val(dashes_c, b);
    }

    cr = gjs_cairo_context_get_context(context, obj);
    cairo_set_dash(cr, (double*)dashes_c->data, dashes_c->len, offset);
    argv.rval().set(JSVAL_VOID);
    retval = JS_TRUE;
 out:
    if (dashes_c != NULL)
        g_array_free (dashes_c, TRUE);
    JS_RemoveObjectRoot(context, &dashes);
    return retval;
}
コード例 #16
0
static CK_RV
wrap_C_Initialize (CK_VOID_PTR init_args)
{
	CK_FUNCTION_LIST_PTR funcs;
	GArray *mappings = NULL;
	CK_SLOT_ID_PTR slots;
	Mapping mapping;
	CK_ULONG i, count;
	CK_RV rv = CKR_OK;
	GList *l;

	mappings = g_array_new (FALSE, TRUE, sizeof (Mapping));

	G_LOCK (wrap_layer);

		if (wrap_mappings)
			rv = CKR_CRYPTOKI_ALREADY_INITIALIZED;

		for (l = wrap_modules; rv == CKR_OK && l != NULL; l = g_list_next (l)) {
			funcs = l->data;

			/* Initialize each module */
			rv = (funcs->C_Initialize) (init_args);
			if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED)
				rv = CKR_OK;
			if (rv != CKR_OK)
				break;

			/* And then ask it for its slots */
			rv = (funcs->C_GetSlotList) (FALSE, NULL, &count);
			if (rv != CKR_OK)
				break;
			if (!count)
				continue;
			slots = g_new0 (CK_SLOT_ID, count);
			rv = (funcs->C_GetSlotList) (FALSE, slots, &count);
			if (rv != CKR_OK) {
				 g_free (slots);
				 break;
			}

			/* And now add a mapping for each of those slots */
			for (i = 0; i < count; ++i) {
				memset (&mapping, 0, sizeof (mapping));
				mapping.wrap_slot = mappings->len + PLEX_MAPPING_OFFSET;
				mapping.real_slot = slots[i];
				mapping.funcs = funcs;
				g_array_append_val (mappings, mapping);
			}

			g_free (slots);
		}

		/* If failed, then finalize all the ones that succeeded */
		if (rv != CKR_OK && l != NULL) {
			for (l = g_list_previous (l); l; l = g_list_previous (l)) {
				funcs = l->data;
				(funcs->C_Finalize) (NULL);
			}
		}

		/* If succeeded then swap in mappings */
		if (rv == CKR_OK) {
			g_assert (!wrap_mappings);
			n_wrap_mappings = mappings->len;
			wrap_mappings = (Mapping*)g_array_free (mappings, FALSE);
			mappings = NULL;
			wrap_sessions = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
		}

	G_UNLOCK (wrap_layer);

	/* If failed or somehow unused then free */
	if (mappings)
		g_array_free (mappings, TRUE);

	return rv;
}
コード例 #17
0
ファイル: annots.c プロジェクト: BlueBrain/Poppler
static void
pgd_annots_update_selected_text (PgdAnnotsDemo *demo)
{
    PopplerRectangle      doc_area, *rects = NULL, *r = NULL;
    gdouble               width, height;
    GArray               *quads_array = NULL;
    guint                 n_rects;
    gint                  i, lines = 0;
    GList                 *l_rects = NULL, *list;

    poppler_page_get_size (demo->page, &width, &height);

    doc_area.x1 = demo->start.x;
    doc_area.y1 = demo->start.y;
    doc_area.x2 = demo->stop.x;
    doc_area.y2 = demo->stop.y;

    if (! poppler_page_get_text_layout_for_area (demo->page, &doc_area,
                                                 &rects, &n_rects))
        return;

    r = g_slice_new (PopplerRectangle);
    r->x1 = G_MAXDOUBLE; r->y1 = G_MAXDOUBLE;
    r->x2 = G_MINDOUBLE; r->y2 = G_MINDOUBLE;

    for (i = 0; i < n_rects; i++) {
        /* Check if the rectangle belongs to the same line.
           On a new line, start a new target rectangle.
           On the same line, make an union of rectangles at
           the same line */
        if (ABS(r->y2 - rects[i].y2) > 0.0001) {
            if (i > 0)
                l_rects = g_list_append (l_rects, r);
            r = g_slice_new (PopplerRectangle);
            r->x1 = rects[i].x1;
            r->y1 = rects[i].y1;
            r->x2 = rects[i].x2;
            r->y2 = rects[i].y2;
            lines++;
        } else {
            r->x1 = MIN(r->x1, rects[i].x1);
            r->y1 = MIN(r->y1, rects[i].y1);
            r->x2 = MAX(r->x2, rects[i].x2);
            r->y2 = MAX(r->y2, rects[i].y2);
        }
    }

    l_rects = g_list_append (l_rects, r);
    l_rects = g_list_reverse (l_rects);

    quads_array = g_array_sized_new (TRUE, TRUE,
                                     sizeof (PopplerQuadrilateral),
                                     lines);
    g_array_set_size (quads_array, lines);

    for (list = l_rects, i = 0; list; list = list->next, i++) {
        PopplerQuadrilateral *quad;

        quad = &g_array_index (quads_array, PopplerQuadrilateral, i);
        r = (PopplerRectangle *)list->data;
        quad->p1.x = r->x1;
        quad->p1.y = height - r->y1;
        quad->p2.x = r->x2;
        quad->p2.y = height - r->y1;
        quad->p3.x = r->x1;
        quad->p3.y = height - r->y2;
        quad->p4.x = r->x2;
        quad->p4.y = height - r->y2;
        g_slice_free (PopplerRectangle, r);
    }

    poppler_annot_text_markup_set_quadrilaterals (POPPLER_ANNOT_TEXT_MARKUP (demo->active_annot), quads_array);
    g_array_free (quads_array, TRUE);
    g_free (rects);
    g_list_free (l_rects);
}
コード例 #18
0
ファイル: garray.c プロジェクト: jmckaskill/subversion
void	    g_byte_array_free     (GByteArray *array,
			           gboolean    free_segment)
{
  g_array_free ((GArray*) array, free_segment);
}
コード例 #19
0
ファイル: stack.c プロジェクト: collinss/muffin
/*
 * Order the windows on the X server to be the same as in our structure.
 * We do this using XRestackWindows if we don't know the previous order,
 * or XConfigureWindow on a few particular windows if we do and can figure
 * out the minimum set of changes.  After that, we set __NET_CLIENT_LIST
 * and __NET_CLIENT_LIST_STACKING.
 *
 * FIXME: Now that we have a good view of the stacking order on the server
 * with MetaStackTracker it should be possible to do a simpler and better
 * job of computing the minimal set of stacking requests needed.
 */
static void
stack_sync_to_server (MetaStack *stack)
{
  GArray *stacked;
  GArray *root_children_stacked;
  GList *tmp;
  GArray *all_hidden;
  int n_override_redirect = 0;
  int n_unmanaging = 0;
  
  /* Bail out if frozen */
  if (stack->freeze_count > 0)
    return;
  
  meta_topic (META_DEBUG_STACK, "Syncing window stack to server\n");  

  stack_ensure_sorted (stack);

  /* Create stacked xwindow arrays.
   * Painfully, "stacked" is in bottom-to-top order for the
   * _NET hints, and "root_children_stacked" is in top-to-bottom
   * order for XRestackWindows()
   */
  stacked = g_array_new (FALSE, FALSE, sizeof (Window));
  root_children_stacked = g_array_new (FALSE, FALSE, sizeof (Window));
  all_hidden = g_array_new (FALSE, FALSE, sizeof (Window));

  /* The screen guard window sits above all hidden windows and acts as
   * a barrier to input reaching these windows. */
  g_array_append_val (all_hidden, stack->screen->guard_window);

  meta_topic (META_DEBUG_STACK, "Top to bottom: ");
  meta_push_no_msg_prefix ();

  for (tmp = stack->sorted; tmp != NULL; tmp = tmp->next)
    {
      MetaWindow *w = tmp->data;
      Window top_level_window;

      if (w->unmanaging)
        {
          n_unmanaging ++;
          continue;
        }
      
      meta_topic (META_DEBUG_STACK, "%u:%d - %s ",
		  w->layer, w->stack_position, w->desc);

      /* remember, stacked is in reverse order (bottom to top) */
      if (w->override_redirect)
	n_override_redirect++;
      else
	g_array_prepend_val (stacked, w->xwindow);
      
      if (w->frame)
	top_level_window = w->frame->xwindow;
      else
	top_level_window = w->xwindow;

      /* We don't restack hidden windows along with the rest, though they are
       * reflected in the _NET hints. Hidden windows all get pushed below
       * the screens fullscreen guard_window. */
      if (w->hidden)
	{
	  g_array_append_val (all_hidden, top_level_window);
	  continue;
	}

      /* build XRestackWindows() array from top to bottom */
      g_array_append_val (root_children_stacked, top_level_window);
    }

  meta_topic (META_DEBUG_STACK, "\n");
  meta_pop_no_msg_prefix ();

  /* All windows should be in some stacking order */
  if (stacked->len != stack->windows->len - n_override_redirect - n_unmanaging)
    meta_bug ("%u windows stacked, %u windows exist in stack\n",
              stacked->len, stack->windows->len);
  
  /* Sync to server */

  meta_topic (META_DEBUG_STACK, "Restacking %u windows\n",
              root_children_stacked->len);
  
  meta_error_trap_push (stack->screen->display);

  if (stack->last_root_children_stacked == NULL)
    {
      /* Just impose our stack, we don't know the previous state.
       * This involves a ton of circulate requests and may flicker.
       */
      meta_topic (META_DEBUG_STACK, "Don't know last stack state, restacking everything\n");

      if (root_children_stacked->len > 0)
        {
          meta_stack_tracker_record_restack_windows (stack->screen->stack_tracker,
                                                     (Window *) root_children_stacked->data,
                                                     root_children_stacked->len,
                                                     XNextRequest (stack->screen->display->xdisplay));
          XRestackWindows (stack->screen->display->xdisplay,
                           (Window *) root_children_stacked->data,
                           root_children_stacked->len);
        }
    }
  else if (root_children_stacked->len > 0)
    {
      /* Try to do minimal window moves to get the stack in order */
      /* A point of note: these arrays include frames not client windows,
       * so if a client window has changed frame since last_root_children_stacked
       * was saved, then we may have inefficiency, but I don't think things
       * break...
       */
      const Window *old_stack = (Window *) stack->last_root_children_stacked->data;
      const Window *new_stack = (Window *) root_children_stacked->data;
      const int old_len = stack->last_root_children_stacked->len;
      const int new_len = root_children_stacked->len;
      const Window *oldp = old_stack;
      const Window *newp = new_stack;
      const Window *old_end = old_stack + old_len;
      const Window *new_end = new_stack + new_len;
      Window last_window = None;
      
      while (oldp != old_end &&
             newp != new_end)
        {
          if (*oldp == *newp)
            {
              /* Stacks are the same here, move on */
              ++oldp;
              last_window = *newp;
              ++newp;
            }
          else if (meta_display_lookup_x_window (stack->screen->display,
                                                 *oldp) == NULL)
            {
              /* *oldp is no longer known to us (probably destroyed),
               * so we can just skip it
               */
              ++oldp;
            }
          else
            {
              /* Move *newp below last_window */
              if (last_window == None)
                {
                  meta_topic (META_DEBUG_STACK, "Using window 0x%lx as topmost (but leaving it in-place)\n", *newp);

                  raise_window_relative_to_managed_windows (stack->screen,
                                                            *newp);
                }
              else
                {
                  /* This means that if last_window is dead, but not
                   * *newp, then we fail to restack *newp; but on
                   * unmanaging last_window, we'll fix it up.
                   */
                  
                  XWindowChanges changes;

                  changes.sibling = last_window;
                  changes.stack_mode = Below;

                  meta_topic (META_DEBUG_STACK, "Placing window 0x%lx below 0x%lx\n",
                              *newp, last_window);

                  meta_stack_tracker_record_lower_below (stack->screen->stack_tracker,
                                                         *newp, last_window,
                                                         XNextRequest (stack->screen->display->xdisplay));
                  XConfigureWindow (stack->screen->display->xdisplay,
                                    *newp,
                                    CWSibling | CWStackMode,
                                    &changes);
                }

              last_window = *newp;
              ++newp;
            }
        }

      if (newp != new_end)
        {
          /* Restack remaining windows */
          meta_topic (META_DEBUG_STACK, "Restacking remaining %d windows\n",
                        (int) (new_end - newp));
          /* We need to include an already-stacked window
           * in the restack call, so we get in the proper position
           * with respect to it.
           */
          if (newp != new_stack)
            --newp;
          meta_stack_tracker_record_restack_windows (stack->screen->stack_tracker,
                                                     (Window *) newp, new_end - newp,
                                                     XNextRequest (stack->screen->display->xdisplay));
          XRestackWindows (stack->screen->display->xdisplay,
                           (Window *) newp, new_end - newp);
        }
    }

  /* Push hidden windows to the bottom of the stack under the guard window */
  meta_stack_tracker_record_lower (stack->screen->stack_tracker,
                                   stack->screen->guard_window,
                                   XNextRequest (stack->screen->display->xdisplay));
  XLowerWindow (stack->screen->display->xdisplay, stack->screen->guard_window);
  meta_stack_tracker_record_restack_windows (stack->screen->stack_tracker,
                                             (Window *)all_hidden->data,
                                             all_hidden->len,
                                             XNextRequest (stack->screen->display->xdisplay));
  XRestackWindows (stack->screen->display->xdisplay,
		   (Window *)all_hidden->data,
		   all_hidden->len);
  g_array_free (all_hidden, TRUE);

  meta_error_trap_pop (stack->screen->display);
  /* on error, a window was destroyed; it should eventually
   * get removed from the stacking list when we unmanage it
   * and we'll fix stacking at that time.
   */
  
  /* Sync _NET_CLIENT_LIST and _NET_CLIENT_LIST_STACKING */

  XChangeProperty (stack->screen->display->xdisplay,
                   stack->screen->xroot,
                   stack->screen->display->atom__NET_CLIENT_LIST,
                   XA_WINDOW,
                   32, PropModeReplace,
                   (unsigned char *)stack->windows->data,
                   stack->windows->len);
  XChangeProperty (stack->screen->display->xdisplay,
                   stack->screen->xroot,
                   stack->screen->display->atom__NET_CLIENT_LIST_STACKING,
                   XA_WINDOW,
                   32, PropModeReplace,
                   (unsigned char *)stacked->data,
                   stacked->len);

  g_array_free (stacked, TRUE);

  if (stack->last_root_children_stacked)
    g_array_free (stack->last_root_children_stacked, TRUE);
  stack->last_root_children_stacked = root_children_stacked;

  /* That was scary... */
}
コード例 #20
0
ファイル: bios-linker-loader.c プロジェクト: 01org/qemu-lite
/* Free linker wrapper and return the linker array. */
void *bios_linker_loader_cleanup(GArray *linker)
{
    return g_array_free(linker, false);
}
コード例 #21
0
ファイル: pygi-marshal-cleanup.c プロジェクト: onia/pygobject
void
_pygi_marshal_cleanup_from_py_array (PyGIInvokeState *state,
                                     PyGIArgCache    *arg_cache,
                                     PyObject        *py_arg,
                                     gpointer         data,
                                     gboolean         was_processed)
{
    if (was_processed) {
        GArray *array_ = NULL;
        GPtrArray *ptr_array_ = NULL;
        PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;

        if (sequence_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY) {
            ptr_array_ = (GPtrArray *) data;
        } else {
            array_ = (GArray *) data;
        }

        /* clean up items first */
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            gsize i;
            guint len = (array_ != NULL) ? array_->len : ptr_array_->len;
            PyGIMarshalCleanupFunc cleanup_func =
                sequence_cache->item_cache->from_py_cleanup;

            for (i = 0; i < len; i++) {
                gpointer item;
                PyObject *py_item = NULL;

                /* case 1: GPtrArray */
                if (ptr_array_ != NULL)
                    item = g_ptr_array_index (ptr_array_, i);
                /* case 2: C array or GArray with object pointers */
                else if (sequence_cache->item_cache->is_pointer)
                    item = g_array_index (array_, gpointer, i);
                /* case 3: C array or GArray with simple types or structs */
                else {
                    item = array_->data + i * sequence_cache->item_size;
                    /* special-case hack: GValue array items do not get slice
                     * allocated in _pygi_marshal_from_py_array(), so we must
                     * not try to deallocate it as a slice and thus
                     * short-circuit cleanup_func. */
                    if (cleanup_func == _pygi_marshal_cleanup_from_py_interface_struct_gvalue) {
                        g_value_unset ((GValue*) item);
                        continue;
                    }
                }

                py_item = PySequence_GetItem (py_arg, i);
                cleanup_func (state, sequence_cache->item_cache, py_item, item, TRUE);
                Py_XDECREF (py_item);
            }
        }

        /* Only free the array when we didn't transfer ownership */
        if (sequence_cache->array_type == GI_ARRAY_TYPE_C) {
            /* always free the GArray wrapper created in from_py marshaling and
             * passed back as cleanup_data
             */
            g_array_free (array_, arg_cache->transfer == GI_TRANSFER_NOTHING);
        } else {
            if (array_ != NULL)
                g_array_unref (array_);
            else
                g_ptr_array_unref (ptr_array_);
        }
    }
}
コード例 #22
0
ファイル: uzbl-core.c プロジェクト: TaylanUB/uzbl
/*
 * recurse == 1: don't expand '@(command)@'
 * recurse == 2: don't expand '@<java script>@'
*/
gchar*
expand(const char* s, guint recurse) {
    enum exp_type etype;
    char*         end_simple_var = "\t^°!\"§$%&/()=?'`'+~*'#-:,;@<>| \\{}[]¹²³¼½";
    char*         ret = NULL;
    char*         vend = NULL;
    GError*       err = NULL;
    gchar*        cmd_stdout = NULL;
    gchar*        mycmd = NULL;
    GString*      buf = g_string_new("");
    GString*      js_ret = g_string_new("");

    while (s && *s) {
        switch(*s) {
            case '\\':
                g_string_append_c(buf, *++s);
                s++;
                break;

            case '@':
                etype = get_exp_type(s);
                s++;

                switch(etype) {
                    case EXP_SIMPLE_VAR:
                        vend = strpbrk(s, end_simple_var);
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_BRACED_VAR:
                        s++;
                        vend = strchr(s, '}');
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_EXPR:
                        s++;
                        vend = strstr(s, ")@");
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_JS:
                        s++;
                        vend = strstr(s, ">@");
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_ESCAPE:
                        s++;
                        vend = strstr(s, "]@");
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    /*@notreached@*/
                    case EXP_ERR:
                        break;
                }
                assert(vend);

                ret = g_strndup(s, vend-s);

                if(etype == EXP_SIMPLE_VAR ||
                   etype == EXP_BRACED_VAR) {

                    expand_variable(buf, ret);

                    if(etype == EXP_SIMPLE_VAR)
                        s = vend;
                    else
                        s = vend+1;
                }
                else if(recurse != 1 &&
                        etype == EXP_EXPR) {

                    /* execute program directly */
                    if(ret[0] == '+') {
                        mycmd = expand(ret+1, 1);
                        g_spawn_command_line_sync(mycmd, &cmd_stdout, NULL, NULL, &err);
                        g_free(mycmd);
                    }
                    /* execute program through shell, quote it first */
                    else {
                        mycmd = expand(ret, 1);
                        gchar *quoted = g_shell_quote(mycmd);
                        gchar *tmp = g_strdup_printf("%s %s",
                                uzbl.behave.shell_cmd?uzbl.behave.shell_cmd:"/bin/sh -c",
                                quoted);
                        g_spawn_command_line_sync(tmp, &cmd_stdout, NULL, NULL, &err);
                        g_free(mycmd);
                        g_free(quoted);
                        g_free(tmp);
                    }

                    if (err) {
                        g_printerr("error on running command: %s\n", err->message);
                        g_error_free (err);
                    }
                    else if (*cmd_stdout) {
                        size_t len = strlen(cmd_stdout);

                        if(len > 0 && cmd_stdout[len-1] == '\n')
                            cmd_stdout[--len] = '\0'; /* strip trailing newline */

                        g_string_append(buf, cmd_stdout);
                        g_free(cmd_stdout);
                    }
                    s = vend+2;
                }
                else if(recurse != 2 &&
                        etype == EXP_JS) {

                    /* read JS from file */
                    if(ret[0] == '+') {
                        GArray *tmp = g_array_new(TRUE, FALSE, sizeof(gchar *));
                        mycmd = expand(ret+1, 2);
                        g_array_append_val(tmp, mycmd);

                        run_external_js(uzbl.gui.web_view, tmp, js_ret);
                        g_array_free(tmp, TRUE);
                    }
                    /* JS from string */
                    else {
                        mycmd = expand(ret, 2);
                        eval_js(uzbl.gui.web_view, mycmd, js_ret, "(command)");
                        g_free(mycmd);
                    }

                    if(js_ret->str) {
                        g_string_append(buf, js_ret->str);
                        g_string_free(js_ret, TRUE);
                        js_ret = g_string_new("");
                    }
                    s = vend+2;
                }
                else if(etype == EXP_ESCAPE) {
                    mycmd = expand(ret, 0);
                    char *escaped = g_markup_escape_text(mycmd, strlen(mycmd));

                    g_string_append(buf, escaped);

                    g_free(escaped);
                    g_free(mycmd);
                    s = vend+2;
                }

                g_free(ret);
                ret = NULL;
                break;

            default:
                g_string_append_c(buf, *s);
                s++;
                break;
        }
    }
    g_string_free(js_ret, TRUE);
    return g_string_free(buf, FALSE);
}
コード例 #23
0
gint reaxmd_parse_properties(FILE *fp, struct model_pak *model, gpointer import)
{
gint i, j, k, n=1, time_column=0, num_tokens, num_properties;
gdouble frame_time=0.0, time, start, stop, value;
gchar *line, *label, **buff;
const gchar *xlabel, *ylabel;
GSList *item, *list;
GArray **property_array;

#if DEBUG_REAXMD_PARSE_PROPERTIES
printf("file_reaxmd(): parsing energy file...\n");
#endif

/* checks */
if (!fp)
  return(FALSE);
if (!import)
  return(FALSE);

/* setup internal frame counter */
if (model)
  {
  n = g_list_length(model->animate_list);
  i=0;
  frame_time = str_to_float(animate_frame_property_get(i, "Time", model));
  }

// NB: file_read_line() skips comments by default, so it'll auto skip the header line
file_skip_comment(FALSE);

// process first line for column locations of time, energy, etc ...
line = file_read_line(fp);

// error handling
if (!line)
  {
  return(FALSE);
  }
if (strlen(line) < 2)
  {
  return(FALSE);
  }

buff = g_strsplit(&line[1], "|", -1);
list = NULL;
if (buff)
  {
  j=0;
  while (buff[j])
    {
    label = g_strstrip(buff[j]);
    if (strlen(label))
      {
      if (g_strrstr(label, "Time"))
        {
        time_column = j;
        }
      list = g_slist_prepend(list, g_strdup(label));
      }
    j++;
    }
  }
g_strfreev(buff);
g_free(line);
line = file_read_line(fp);
list = g_slist_reverse(list);

#if DEBUG_REAXMD_PARSE_PROPERTIES
for (item=list ; item ; item=g_slist_next(item))
  {
  printf("[%s]\n", (gchar *) item->data);
  }
printf("Allocating %d property arrays, with start size %d\n", g_slist_length(list), n);
#endif

// NB: exclude the first - time
/* init arrays for properties */
num_properties = g_slist_length(list);
property_array = g_malloc(num_properties * sizeof(GArray));
for (k=0 ; k<num_properties ; k++)
  {
  property_array[k] = g_array_sized_new(FALSE, FALSE, sizeof(gdouble), n);
  }

/* iterate over all output data lines */
while (line)
  {
  buff = tokenize(line, &num_tokens);

  if (num_tokens > time_column)
    {
    time = str_to_float(buff[time_column]);

/* NEW - grab all values for property graphs */
    for (j=0 ; j<num_tokens ; j++)
      {
      if (j < num_properties)
        {
        value = str_to_float(buff[j]);
        g_array_append_val(property_array[j], value);
        }
      }

/* if output data time matches internal frame frame - store */
    if (model)
      {
      if (time >= frame_time)
        {
/* add current output data to the internally stored frame */
        item = list;
        for (j=0 ; j<num_tokens ; j++)
          {
          if (item)
            {
//printf("[%d][%s][%s]\n", i, (gchar *) item->data, buff[j]);
// add to actual model property list (reference frame only)
// leave this out now, since we're auto constructing graphs anyway
/*
            if (!i)
              {
              property_add_ranked(j, item->data, buff[j], model);
              }
*/

            animate_frame_property_put(i, item->data, buff[j], model);
            }
          else
            break;

          item = g_slist_next(item);
          }

/* update the internal frame count */
        i++;
        frame_time = str_to_float(animate_frame_property_get(i, "Time", model));
        }
      }
    }

  g_strfreev(buff);

  g_free(line);
  line = file_read_line(fp);
  }

/* iterate property arrays and construct graphs */
xlabel = g_slist_nth_data(list, time_column);
for (j=0 ; j<num_properties ; j++)
  {
// don't graph time column
  if (j != time_column)
    {
    gpointer data, graph;

    k = property_array[j]->len;
    data = g_array_free(property_array[j], FALSE);

    start = g_array_index(property_array[time_column],gdouble,0);
    stop = g_array_index(property_array[time_column],gdouble,k-1);

#if DEBUG_REAXMD_PARSE_PROPERTIES
printf("Building graph for: %s with %d data points and ", (gchar *) g_slist_nth_data(list, j), k);
printf("range: %f - %f\n", start, stop);
#endif

/* add graph if no ! prefix */
    ylabel = g_slist_nth_data(list, j);
    if (!g_strrstr(ylabel, "!"))
      {
/* create and attach graph object */
      label = g_strndup(ylabel, 8);
      graph = graph_new(label);
      g_free(label);
      graph_set_data(k, data, start, stop, graph);
      graph_x_label_set(xlabel, graph);
      graph_y_label_set(ylabel, graph);
      import_object_add(IMPORT_GRAPH, graph, import);
      }
    }
  }

g_array_free(property_array[time_column], TRUE);
g_free(property_array);

/* cleanup */
free_slist(list);

return(0);
}
コード例 #24
0
ファイル: print_manager.c プロジェクト: Pronghorn/pronghorn
static int do_tree_check(struct print_manager *pm)
{
//printf("Checking abs_off tree\n");
  pm->lookup_offset = pm->current_offset;
  g_tree_foreach(pm->abs_tree, (GTraverseFunc) abs_tree_check, pm);
  if (pm->destroy_array != NULL)
  {
    for (int i = 0; i < pm->destroy_array->len; i++)
    {
      long long off = g_array_index(pm->destroy_array, long long, i);
      GNode *node = (GNode *) g_tree_lookup(pm->abs_tree, &off);

      save_children(pm, node);
      g_tree_remove(pm->abs_tree, &off);
    }
    g_array_free(pm->destroy_array, TRUE);
    pm->destroy_array = NULL;
  }

  if (pm->print_array != NULL)
  {
    for (int i = 0; i < pm->print_array->len; i++)
    {
      long long off = g_array_index(pm->print_array, long long, i);
      GNode *node = (GNode *) g_tree_lookup(pm->abs_tree, &off);

      print_and_process_tree(pm, node);
      g_tree_remove(pm->abs_tree, &off);
    }
    g_array_free(pm->print_array, TRUE);
    pm->print_array = NULL;
  }
//printf("Checking continuation tree\n");
  g_tree_foreach(pm->continuation_tree, (GTraverseFunc) continuation_tree_check, pm);
  if (pm->destroy_array != NULL)
  {
    for (int i = 0; i < pm->destroy_array->len; i++)
    {
      block_range_t br = g_array_index(pm->destroy_array, block_range_t, i);

      gboolean ret = g_tree_remove(pm->continuation_tree, br);

      prong_assert(ret == TRUE);
      block_range_close(br);
    }
    g_array_free(pm->destroy_array, TRUE);
    pm->destroy_array = NULL;
  }

  if (pm->print_array != NULL)
  {
    for (int i = 0; i < pm->print_array->len; i++)
    {
      block_range_t br = g_array_index(pm->print_array, block_range_t, i);
      struct continuation_node *node = (struct continuation_node *) g_tree_lookup(pm->continuation_tree, br);

      prong_assert(node != NULL);
      if (node->is_constant == 1)
      {
        pm->print_handler->print_const_continuation((unsigned long long) pm->current_offset * pm->block_size, (unsigned long long) node->owner_offset * pm->block_size, node->path);
        //printf("%13lld %13lld   Constant\n", pm->current_offset * pm->block_size, node->owner_offset * pm->block_size);
      } else
      {
        pm->print_handler->print_continuation((unsigned long long) pm->current_offset * pm->block_size, (unsigned long long) node->owner_offset * pm->block_size, node->brief_description);
        //printf("%13lld %13lld   (Continuation of %s)\n", pm->current_offset * pm->block_size, node->owner_offset * pm->block_size, node->brief_description);
      }
//printf("Incremented current offset\n");
      pm->current_offset++;
      block_range_close(br);
    }
    g_array_free(pm->print_array, TRUE);
    pm->print_array = NULL;
    return 1;
  }

  return 0;
}
コード例 #25
0
static gboolean
process_nduseropt_rdnss (NMIP6Device *device, struct nd_opt_hdr *opt)
{
	size_t opt_len;
	struct nd_opt_rdnss *rdnss_opt;
	time_t now = time (NULL);
	struct in6_addr *addr;
	GArray *new_servers;
	NMIP6RDNSS server, *cur_server;
	gboolean changed = FALSE;
	guint i;

	opt_len = opt->nd_opt_len;

	if (opt_len < 3 || (opt_len & 1) == 0)
		return FALSE;

	rdnss_opt = (struct nd_opt_rdnss *) opt;

	new_servers = g_array_new (FALSE, FALSE, sizeof (NMIP6RDNSS));

	/* Pad the DNS server expiry somewhat to give a bit of slack in cases
	 * where one RA gets lost or something (which can happen on unreliable
	 * links like WiFi where certain types of frames are not retransmitted).
	 * Note that 0 has special meaning and is therefore not adjusted.
	 */
	server.expires = ntohl (rdnss_opt->nd_opt_rdnss_lifetime);
	if (server.expires > 0)
		server.expires += now + 10;

	for (addr = (struct in6_addr *) (rdnss_opt + 1); opt_len >= 2; addr++, opt_len -= 2) {
		char buf[INET6_ADDRSTRLEN + 1];

		if (!inet_ntop (AF_INET6, addr, buf, sizeof (buf))) {
			nm_log_warn (LOGD_IP6, "(%s): received invalid RA-provided nameserver", device->iface);
			continue;
		}

		/* Update the cached timeout if we already saw this server */
		for (i = 0; i < device->rdnss_servers->len; i++) {
			cur_server = &(g_array_index (device->rdnss_servers, NMIP6RDNSS, i));

			if (!IN6_ARE_ADDR_EQUAL (addr, &cur_server->addr))
				continue;

			cur_server->expires = server.expires;

			if (server.expires > 0) {
				nm_log_dbg (LOGD_IP6, "(%s): refreshing RA-provided nameserver %s (expires in %ld seconds)",
				            device->iface, buf,
				            server.expires - now);
				break;
			}

			nm_log_dbg (LOGD_IP6, "(%s): removing RA-provided nameserver %s on router request",
			            device->iface, buf);

			g_array_remove_index (device->rdnss_servers, i);
			changed = TRUE;
			break;
		}

		if (server.expires == 0)
			continue;
		if (i < device->rdnss_servers->len)
			continue;

		nm_log_dbg (LOGD_IP6, "(%s): found RA-provided nameserver %s (expires in %ld seconds)",
		            device->iface, buf, server.expires - now);

		server.addr = *addr;
		g_array_append_val (new_servers, server);
	}

	/* New servers must be added in the order they are listed in the
	 * RA option and before any existing servers.
	 *
	 * Note: This is the place to remove servers if we want to cap the
	 *       number of resolvers. The RFC states that the one to expire
	 *       first of the existing servers should be removed.
	 */
	if (new_servers->len) {
		g_array_prepend_vals (device->rdnss_servers,
		                      new_servers->data, new_servers->len);
		changed = TRUE;
	}

	g_array_free (new_servers, TRUE);

	/* Timeouts may have changed even if IPs didn't */
	set_rdnss_timeout (device);

	return changed;
}
コード例 #26
0
gboolean
gimp_paint_core_start (GimpPaintCore     *core,
                       GimpDrawable      *drawable,
                       GimpPaintOptions  *paint_options,
                       const GimpCoords  *coords,
                       GError           **error)
{
  GimpItem *item;

  g_return_val_if_fail (GIMP_IS_PAINT_CORE (core), FALSE);
  g_return_val_if_fail (GIMP_IS_DRAWABLE (drawable), FALSE);
  g_return_val_if_fail (gimp_item_is_attached (GIMP_ITEM (drawable)), FALSE);
  g_return_val_if_fail (GIMP_IS_PAINT_OPTIONS (paint_options), FALSE);
  g_return_val_if_fail (coords != NULL, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  item = GIMP_ITEM (drawable);

  if (core->stroke_buffer)
    {
      g_array_free (core->stroke_buffer, TRUE);
      core->stroke_buffer = NULL;
    }

  core->stroke_buffer = g_array_sized_new (TRUE, TRUE,
                                           sizeof (GimpCoords),
                                           STROKE_BUFFER_INIT_SIZE);

  core->cur_coords = *coords;

  if (! GIMP_PAINT_CORE_GET_CLASS (core)->start (core, drawable,
                                                 paint_options,
                                                 coords, error))
    {
      return FALSE;
    }

  /*  Allocate the undo structure  */
  if (core->undo_buffer)
    g_object_unref (core->undo_buffer);

  core->undo_buffer = gegl_buffer_dup (gimp_drawable_get_buffer (drawable));

  /*  Allocate the saved proj structure  */
  if (core->saved_proj_buffer)
    {
      g_object_unref (core->saved_proj_buffer);
      core->saved_proj_buffer = NULL;
    }

  if (core->use_saved_proj)
    {
      GimpImage    *image    = gimp_item_get_image (item);
      GimpPickable *pickable = GIMP_PICKABLE (gimp_image_get_projection (image));
      GeglBuffer   *buffer   = gimp_pickable_get_buffer (pickable);

      core->saved_proj_buffer = gegl_buffer_dup (buffer);
    }

  /*  Allocate the canvas blocks structure  */
  if (core->canvas_buffer)
    g_object_unref (core->canvas_buffer);

  core->canvas_buffer =
    gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                     gimp_item_get_width  (item),
                                     gimp_item_get_height (item)),
                     babl_format ("Y u8"));

  /*  Get the initial undo extents  */

  core->x1 = core->x2 = core->cur_coords.x;
  core->y1 = core->y2 = core->cur_coords.y;

  core->last_paint.x = -1e6;
  core->last_paint.y = -1e6;

  {
    GimpImage   *image;
    GimpChannel *mask;
    GeglBuffer  *mask_buffer = NULL;
    gint         offset_x    = 0;
    gint         offset_y    = 0;

    image = gimp_item_get_image (item);
    mask  = gimp_image_get_mask (image);

    /*  don't apply the mask to itself and don't apply an empty mask  */
    if (GIMP_DRAWABLE (mask) == drawable || gimp_channel_is_empty (mask))
      mask = NULL;

    if (mask)
      {
        mask_buffer = gimp_drawable_get_buffer (GIMP_DRAWABLE (mask));

        gimp_item_get_offset (item, &offset_x, &offset_y);
      }

    core->applicator =
      gimp_applicator_new (gimp_drawable_get_buffer (drawable),
                           gimp_drawable_get_active_mask (drawable),
                           mask_buffer,
                           -offset_x, -offset_y);
  }

  /*  Freeze the drawable preview so that it isn't constantly updated.  */
  gimp_viewable_preview_freeze (GIMP_VIEWABLE (drawable));

  return TRUE;
}
コード例 #27
0
ファイル: garray.c プロジェクト: geekmaster/buildroot-kindle
/**
 * g_byte_array_free:
 * @array: a #GByteArray.
 * @free_segment: if %TRUE the actual byte data is freed as well.
 * @Returns: the element data if @free_segment is %FALSE, otherwise
 *           %NULL.  The element data should be freed using g_free().
 *
 * Frees the memory allocated by the #GByteArray. If @free_segment is
 * %TRUE it frees the actual byte data. If the reference count of
 * @array is greater than one, the #GByteArray wrapper is preserved but
 * the size of @array will be set to zero.
 **/
guint8*	    g_byte_array_free     (GByteArray *array,
			           gboolean    free_segment)
{
  return (guint8*) g_array_free ((GArray*) array, free_segment);
}
コード例 #28
0
void
gimp_paint_core_finish (GimpPaintCore *core,
                        GimpDrawable  *drawable,
                        gboolean       push_undo)
{
  GimpImage *image;

  g_return_if_fail (GIMP_IS_PAINT_CORE (core));
  g_return_if_fail (GIMP_IS_DRAWABLE (drawable));
  g_return_if_fail (gimp_item_is_attached (GIMP_ITEM (drawable)));

  if (core->applicator)
    {
      g_object_unref (core->applicator);
      core->applicator = NULL;
    }

  if (core->stroke_buffer)
    {
      g_array_free (core->stroke_buffer, TRUE);
      core->stroke_buffer = NULL;
    }

  image = gimp_item_get_image (GIMP_ITEM (drawable));

  /*  Determine if any part of the image has been altered--
   *  if nothing has, then just return...
   */
  if ((core->x2 == core->x1) || (core->y2 == core->y1))
    {
      gimp_viewable_preview_thaw (GIMP_VIEWABLE (drawable));
      return;
    }

  if (push_undo)
    {
      GeglBuffer *buffer;
      gint        x, y, width, height;

      gimp_rectangle_intersect (core->x1, core->y1,
                                core->x2 - core->x1, core->y2 - core->y1,
                                0, 0,
                                gimp_item_get_width  (GIMP_ITEM (drawable)),
                                gimp_item_get_height (GIMP_ITEM (drawable)),
                                &x, &y, &width, &height);

      gimp_image_undo_group_start (image, GIMP_UNDO_GROUP_PAINT,
                                   core->undo_desc);

      GIMP_PAINT_CORE_GET_CLASS (core)->push_undo (core, image, NULL);

      buffer = gegl_buffer_new (GEGL_RECTANGLE (0, 0, width, height),
                                gimp_drawable_get_format (drawable));

      gegl_buffer_copy (core->undo_buffer,
                        GEGL_RECTANGLE (x, y, width, height),
                        buffer,
                        GEGL_RECTANGLE (0, 0, 0, 0));

      gimp_drawable_push_undo (drawable, NULL,
                               buffer, x, y, width, height);

      g_object_unref (buffer);

      gimp_image_undo_group_end (image);
    }

  g_object_unref (core->undo_buffer);
  core->undo_buffer = NULL;

  if (core->saved_proj_buffer)
    {
      g_object_unref (core->saved_proj_buffer);
      core->saved_proj_buffer = NULL;
    }

  gimp_viewable_preview_thaw (GIMP_VIEWABLE (drawable));
}
コード例 #29
0
GpStatus
GdipPathIterNextSubpathPath (GpPathIterator *iterator, int *resultCount, GpPath *path, BOOL *isClosed)
{
	int index = 0;
	GpPointF point;
	BYTE currentType;

	if (!iterator || !resultCount || !isClosed)
		return InvalidParameter;

	/* There are no subpaths or we are done with all the subpaths */
	if (!path || !iterator->path || (iterator->path->count == 0) || 
	    (iterator->subpathPosition == iterator->path->count)) {
		*resultCount = 0;
		*isClosed = TRUE;
		return Ok;
	}

	/* Clear the existing values from path */
	if (path->count > 0) {
		g_array_free (path->points, TRUE);
		g_byte_array_free (path->types, TRUE);

		path->points = g_array_new (FALSE, FALSE, sizeof (GpPointF));
		path->types = g_byte_array_new ();
		path->count = 0;
	}

	/* Copy the starting point */
	currentType = g_array_index (iterator->path->types, BYTE, iterator->subpathPosition);
	point = g_array_index (iterator->path->points, GpPointF, iterator->subpathPosition);
	g_array_append_val (path->points, point);
	g_byte_array_append (path->types, &currentType, 1);
	path->count++;

	/* Check for next start point */
	for (index = iterator->subpathPosition + 1; index < iterator->path->count; index++) {
		currentType = g_array_index (iterator->path->types, BYTE, index);

		/* Copy the start point till next start point */
		if (currentType == PathPointTypeStart)
			break;

		point = g_array_index (iterator->path->points, GpPointF, index);
		g_array_append_val (path->points, point);
		g_byte_array_append (path->types, &currentType, 1);
		path->count++;
	}

	*resultCount = index - iterator->subpathPosition;
	/* set positions for next iteration */
	iterator->pathTypePosition = iterator->subpathPosition;
	iterator->subpathPosition = index;

	/* Check if last subpath was closed */
	currentType = g_array_index (iterator->path->types, BYTE, index - 1);
	if (currentType & PathPointTypeCloseSubpath)
		*isClosed = TRUE;
	else
		*isClosed = FALSE;

	return Ok;
}
コード例 #30
0
ファイル: dsn-config.c プロジェクト: GNOME/libgda
static void
list_selection_changed_cb (GdauiRawGrid *grid, gpointer user_data)
{
	DsnConfigPrivate *priv;
	GdaDataModel *model;
	GArray *selection;
	gchar *str;
	const GValue *cvalue;
	GtkWidget *win = gtk_widget_get_toplevel (GTK_WIDGET (grid));
	if (gtk_widget_is_toplevel (win)) {
		g_simple_action_set_enabled (G_SIMPLE_ACTION (g_action_map_lookup_action (G_ACTION_MAP (win),
											  "DatasourceDelete")), FALSE);
	}

	priv = g_object_get_data (G_OBJECT (user_data), DSN_CONFIG_DATA);

	selection = gdaui_data_selector_get_selected_rows (GDAUI_DATA_SELECTOR (priv->dsn_list));
	if (!selection) {
		gtk_stack_set_visible_child_name (GTK_STACK (priv->stack), ST_NOPROP);
		return;
	}

	model = gdaui_data_selector_get_model (GDAUI_DATA_SELECTOR (priv->dsn_list));
	if (!GDA_IS_DATA_MODEL (model)) {
		g_array_free (selection, TRUE);
		gtk_stack_set_visible_child_name (GTK_STACK (priv->stack), ST_NOPROP);
		return;
	}

	cvalue = gda_data_model_get_value_at (model, 0, g_array_index (selection, gint, 0), NULL);
	g_array_free (selection, TRUE);
	if (!cvalue) {
		gtk_stack_set_visible_child_name (GTK_STACK (priv->stack), ST_NOPROP);
		return;
	}

	str = gda_value_stringify ((GValue *) cvalue);
	g_print ("==> %s\n", str);

	GdaDsnInfo *dsn_info;
	dsn_info = gda_config_get_dsn_info (str);
	g_free (str);
	if (!dsn_info) {
		/* something went wrong here... */
		gtk_stack_set_visible_child_name (GTK_STACK (priv->stack), ST_NOPROP);
		return;
	}

	gdaui_dsn_editor_set_dsn (priv->dsn_editor, dsn_info);

	if (gdaui_dsn_editor_need_authentication (priv->dsn_editor))
		gtk_widget_show (GTK_WIDGET (priv->view_buttons [GDAUI_DSN_EDITOR_PANE_AUTH]));
	else
		gtk_widget_hide (GTK_WIDGET (priv->view_buttons [GDAUI_DSN_EDITOR_PANE_AUTH]));
	gtk_toggle_button_set_active (priv->view_buttons [GDAUI_DSN_EDITOR_PANE_DEFINITION], TRUE);

	gtk_stack_set_visible_child_name (GTK_STACK (priv->stack), ST_PROP);
	if (gtk_widget_is_toplevel (win)) {
		g_simple_action_set_enabled (G_SIMPLE_ACTION (g_action_map_lookup_action (G_ACTION_MAP (win),
											  "DatasourceDelete")), TRUE);
	}
}