Exemplo n.º 1
0
static void
geometry_start_element_callback (GMarkupParseContext *pcontext,
                                 const gchar         *element_name,
                                 const gchar        **attribute_names,
                                 const gchar        **attribute_values,
                                 gpointer             user_data,
                                 GError             **error)
{
    GeometryParseData *data = user_data;
    const gchar *attribute;

    if (!validate (geometry_valid_path_list,
                   G_N_ELEMENTS (geometry_valid_path_list),
                   element_name,
                   data->element_stack,
                   error)) {
        return;
    }

    if (g_strcmp0 (element_name, "bounds") == 0) {
        EekBounds bounds;

        attribute = get_attribute (attribute_names, attribute_values, "x");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"x\" attribute for \"bounds\"");
            return;
        }
        bounds.x = g_strtod (attribute, NULL);

        attribute = get_attribute (attribute_names, attribute_values,
                                   "y");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"y\" attribute for \"bounds\"");
            return;
        }
        bounds.y = g_strtod (attribute, NULL);

        attribute = get_attribute (attribute_names, attribute_values,
                                   "width");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"width\" attribute for \"bounds\"");
            return;
        }
        bounds.width = g_strtod (attribute, NULL);

        attribute = get_attribute (attribute_names, attribute_values,
                                   "height");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"height\" attribute for \"bounds\"");
            return;
        }
        bounds.height = g_strtod (attribute, NULL);

        if (g_strcmp0 (data->element_stack->data, "geometry") == 0)
            eek_element_set_bounds (EEK_ELEMENT(data->keyboard), &bounds);
        else if (g_strcmp0 (data->element_stack->data, "section") == 0)
            eek_element_set_bounds (EEK_ELEMENT(data->section), &bounds);
        else if (g_strcmp0 (data->element_stack->data, "key") == 0)
            eek_element_set_bounds (EEK_ELEMENT(data->key), &bounds);

        goto out;
    }

    if (g_strcmp0 (element_name, "section") == 0) {
        data->section = eek_keyboard_create_section (data->keyboard);
        attribute = get_attribute (attribute_names, attribute_values,
                                   "id");
        if (attribute != NULL)
            eek_element_set_name (EEK_ELEMENT(data->section), attribute);
        attribute = get_attribute (attribute_names, attribute_values,
                                   "angle");
        if (attribute != NULL) {
            gint angle;
            angle = strtol (attribute, NULL, 10);
            eek_section_set_angle (data->section, angle);
        }
        goto out;
    }

    if (g_strcmp0 (element_name, "row") == 0) {
        attribute = get_attribute (attribute_names, attribute_values,
                                   "orientation");
        if (attribute != NULL)
            data->orientation = strtol (attribute, NULL, 10);

        eek_section_add_row (data->section,
                             data->num_columns,
                             data->orientation);

        data->num_rows++;
        goto out;
    }

    if (g_strcmp0 (element_name, "key") == 0) {
        guint keycode;

        attribute = get_attribute (attribute_names, attribute_values,
                                   "keycode");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"keycode\" attribute for \"key\"");
            return;
        }
        keycode = strtoul (attribute, NULL, 10);

        data->key = eek_section_create_key (data->section,
                                            keycode,
                                            data->num_columns,
                                            data->num_rows - 1);

        attribute = get_attribute (attribute_names, attribute_values,
                                   "name");
        if (attribute != NULL)
            eek_element_set_name (EEK_ELEMENT(data->key), attribute);

        attribute = get_attribute (attribute_names, attribute_values,
                                   "oref");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"oref\" attribute for \"key\"");
            return;
        }
        g_hash_table_insert (data->key_oref_hash,
                             data->key,
                             g_strdup (attribute));

        data->num_columns++;

        goto out;
    }

    if (g_strcmp0 (element_name, "outline") == 0) {
        attribute = get_attribute (attribute_names, attribute_values, "id");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"id\" attribute for \"outline\"");
            return;
        }
        data->oref = g_strdup (attribute);

        attribute = get_attribute (attribute_names, attribute_values,
                                   "corner-radius");
        if (attribute != NULL)
            data->corner_radius = g_strtod (attribute, NULL);
        
        goto out;
    }

    if (g_strcmp0 (element_name, "point") == 0) {
        EekPoint *point;
        gdouble x, y;

        attribute = get_attribute (attribute_names, attribute_values, "x");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"x\" attribute for \"bounds\"");
            return;
        }
        x = g_strtod (attribute, NULL);

        attribute = get_attribute (attribute_names, attribute_values, "y");
        if (attribute == NULL) {
            g_set_error (error,
                         G_MARKUP_ERROR,
                         G_MARKUP_ERROR_MISSING_ATTRIBUTE,
                         "no \"y\" attribute for \"bounds\"");
            return;
        }
        y = g_strtod (attribute, NULL);

        point = g_slice_new (EekPoint);
        point->x = x;
        point->y = y;

        data->points = g_slist_prepend (data->points, point);
        goto out;
    }

 out:
    data->element_stack = g_slist_prepend (data->element_stack,
                                           g_strdup (element_name));
}
Exemplo n.º 2
0
static inline RenderFrame *
render_frame_new (void)
{
  return g_slice_new (RenderFrame);
}
Exemplo n.º 3
0
/**
 * fs_codec_list_from_keyfile
 * @filename: Name of the #GKeyFile to read the codecs parameters from
 * @error: location of a #GError, or NULL if no error occured
 *
 * Reads the content of a #GKeyFile of the following format into
 * a #GList of #FsCodec structures.
 *
 *
 * Example:
 * |[
 * [audio/codec1]
 * clock-rate=8000
 *
 * [audio/codec1:1]
 * clock-rate=16000
 *
 * [audio/codec2]
 * one_param=QCIF
 * another_param=WOW
 *
 * [video/codec3]
 * wierd_param=42
 * feedback:nack/pli=1
 * feedback:tfrc=
 * ]|
 *
 * Return value: (element-type FsCodec) (transfer full):
 * The #GList of #FsCodec or %NULL if the keyfile was empty or an error occured.
 */
GList *
fs_codec_list_from_keyfile (const gchar *filename, GError **error)
{
  GKeyFile *keyfile = NULL;
  GList *codecs = NULL;
  GError *gerror = NULL;
  gchar **groups = NULL;
  gsize groups_count = 0;
  int i;

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

  keyfile = g_key_file_new ();

  if (!g_key_file_load_from_file (keyfile, filename,
          G_KEY_FILE_NONE, error)) {
    goto out;
  }

  groups = g_key_file_get_groups (keyfile, &groups_count);

  if (!groups)
    goto out;

  for (i=0; i < groups_count && groups[i]; i++) {
    FsCodec *codec;
    gchar **keys = NULL;
    gsize keys_count;
    int j;
    gchar *encoding_name = NULL;
    gchar *next_tok = NULL;
    FsMediaType media_type;

    keys = g_key_file_get_keys (keyfile, groups[i], &keys_count, &gerror);

    if (!keys || gerror) {
      if (gerror)
        GST_WARNING ("Unable to read parameters for %s: %s\n",
            groups[i], gerror->message);
      else
        GST_WARNING ("Unknown errors while reading parameters for %s",
            groups[i]);

      g_clear_error (&gerror);

      goto next_codec;
    }

    next_tok = strchr (groups[i], '/');
    if (!next_tok)
    {
      GST_WARNING ("Invalid codec name: %s", groups[i]);
      goto next_codec;
    }

    if ((next_tok - groups[i]) == 5 /* strlen ("audio") */ &&
        !g_ascii_strncasecmp ("audio", groups[i], 5))
    {
      media_type = FS_MEDIA_TYPE_AUDIO;
    }
    else if ((next_tok - groups[i]) == 5 /* strlen ("video") */ &&
        !g_ascii_strncasecmp ("video", groups[i], 5))
    {
      media_type = FS_MEDIA_TYPE_VIDEO;
    }
    else
    {
      GST_WARNING ("Invalid media type in codec name name %s", groups[i]);
      goto next_codec;
    }

    encoding_name = next_tok + 1;

    next_tok = strchr (encoding_name, ':');

    if (encoding_name[0] == 0 || next_tok - encoding_name == 1)
      goto next_codec;

    if (next_tok)
      encoding_name = g_strndup (encoding_name,
          next_tok - encoding_name);
    else
      encoding_name = g_strdup (encoding_name);

    codec = fs_codec_new (FS_CODEC_ID_ANY, encoding_name, media_type, 0);

    g_free (encoding_name);

    for (j = 0; j < keys_count && keys[j]; j++) {
      if (!g_ascii_strcasecmp ("clock-rate", keys[j])) {
        codec->clock_rate = g_key_file_get_integer (keyfile, groups[i], keys[j],
            &gerror);
        if (gerror) {
          codec->clock_rate = 0;
          goto keyerror;
        }

      } else if (!g_ascii_strcasecmp ("id", keys[j])) {
         codec->id = g_key_file_get_integer (keyfile, groups[i], keys[j],
            &gerror);
        if (gerror) {
          codec->id = FS_CODEC_ID_ANY;
          goto keyerror;
        }

        if (codec->id < 0)
          codec->id = FS_CODEC_ID_DISABLE;

      } else if (!g_ascii_strcasecmp ("channels", keys[j])) {
         codec->channels = g_key_file_get_integer (keyfile, groups[i], keys[j],
            &gerror);
        if (gerror) {
          codec->channels = 0;
          goto keyerror;
        }
      } else if (!g_ascii_strcasecmp ("trr-int", keys[j])) {
        codec->minimum_reporting_interval =
            g_key_file_get_integer (keyfile, groups[i], keys[j], &gerror);
        if (gerror) {
          codec->minimum_reporting_interval = G_MAXUINT;
          goto keyerror;
        }
      } else if (g_str_has_prefix (keys[j], "feedback:")) {
        gchar *type = keys[j] + strlen ("feedback:");
        gchar *subtype = strchr (type, '/');
        gchar *extra_params;

        extra_params = g_key_file_get_string (keyfile, groups[i], keys[j],
            &gerror);
        if (gerror)
          goto keyerror;

        /* Replace / with \0 and point to name (the next char) */
        if (subtype)
        {
          *subtype=0;
          subtype++;
        }
        else
        {
          subtype = "";
        }

        fs_codec_add_feedback_parameter (codec, type, subtype,
            extra_params);
        g_free (extra_params);
      } else {
        FsCodecParameter *param = g_slice_new (FsCodecParameter);

        param->name = g_strdup (keys[j]);
        param->value = g_key_file_get_string (keyfile, groups[i], keys[j],
            &gerror);
        if (gerror) {
          fs_codec_parameter_free (param);
          goto keyerror;
        }

        if (!param->name || !param->value)
          fs_codec_parameter_free (param);
        else
          codec->optional_params = g_list_append (codec->optional_params,
              param);
      }
      continue;
    keyerror:
      GST_WARNING ("Error reading key %s codec %s: %s", keys[j], groups[i],
          gerror->message);
      g_clear_error (&gerror);

    }

    codecs = g_list_append (codecs, codec);

  next_codec:
    g_strfreev (keys);
  }


 out:

  g_strfreev (groups);
  g_key_file_free (keyfile);

  return codecs;
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
    wtap *wth = NULL;
    wtap_dumper *pdh = NULL;
    Buffer buf;
    int err;
    gchar *err_info;
    gint64 data_offset;
    const struct wtap_pkthdr *phdr;
    guint wrong_order_count = 0;
    gboolean write_output_regardless = TRUE;
    guint i;
    wtapng_section_t            *shb_hdr;
    wtapng_iface_descriptions_t *idb_inf;

    GPtrArray *frames;
    FrameRecord_t *prevFrame = NULL;

    int opt;
    int file_count;
    char *infile;
    char *outfile;

    /* Process the options first */
    while ((opt = getopt(argc, argv, "hn")) != -1) {
        switch (opt) {
            case 'n':
                write_output_regardless = FALSE;
                break;
            case 'h':
                usage(FALSE);
                exit(0);
            case '?':
                usage(TRUE);
                exit(1);
        }
    }

    /* Remaining args are file names */
    file_count = argc - optind;
    if (file_count == 2) {
        infile  = argv[optind];
        outfile = argv[optind+1];
    }
    else {
        usage(TRUE);
        exit(1);
    }

    init_open_routines();

    /* Open infile */
    wth = wtap_open_offline(infile, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
    if (wth == NULL) {
        fprintf(stderr, "reordercap: Can't open %s: %s\n", infile,
                wtap_strerror(err));
        switch (err) {

        case WTAP_ERR_UNSUPPORTED:
        case WTAP_ERR_UNSUPPORTED_ENCAP:
        case WTAP_ERR_BAD_FILE:
            fprintf(stderr, "(%s)\n", err_info);
            g_free(err_info);
            break;
        }
        exit(1);
    }
    DEBUG_PRINT("file_type_subtype is %u\n", wtap_file_type_subtype(wth));

    shb_hdr = wtap_file_get_shb_info(wth);
    idb_inf = wtap_file_get_idb_info(wth);

    /* Open outfile (same filetype/encap as input file) */
    pdh = wtap_dump_open_ng(outfile, wtap_file_type_subtype(wth), wtap_file_encap(wth),
                            65535, FALSE, shb_hdr, idb_inf, &err);
    g_free(idb_inf);
    if (pdh == NULL) {
        fprintf(stderr, "reordercap: Failed to open output file: (%s) - error %s\n",
                outfile, wtap_strerror(err));
        g_free(shb_hdr);
        exit(1);
    }

    /* Allocate the array of frame pointers. */
    frames = g_ptr_array_new();

    /* Read each frame from infile */
    while (wtap_read(wth, &err, &err_info, &data_offset)) {
        FrameRecord_t *newFrameRecord;

        phdr = wtap_phdr(wth);

        newFrameRecord = g_slice_new(FrameRecord_t);
        newFrameRecord->num = frames->len + 1;
        newFrameRecord->offset = data_offset;
        newFrameRecord->time = phdr->ts;

        if (prevFrame && frames_compare(&newFrameRecord, &prevFrame) < 0) {
           wrong_order_count++;
        }

        g_ptr_array_add(frames, newFrameRecord);
        prevFrame = newFrameRecord;
    }
    if (err != 0) {
      /* Print a message noting that the read failed somewhere along the line. */
      fprintf(stderr,
              "reordercap: An error occurred while reading \"%s\": %s.\n",
              infile, wtap_strerror(err));
      switch (err) {

      case WTAP_ERR_UNSUPPORTED:
      case WTAP_ERR_UNSUPPORTED_ENCAP:
      case WTAP_ERR_BAD_FILE:
          fprintf(stderr, "(%s)\n", err_info);
          g_free(err_info);
          break;
      }
    }

    printf("%u frames, %u out of order\n", frames->len, wrong_order_count);

    /* Sort the frames */
    if (wrong_order_count > 0) {
        g_ptr_array_sort(frames, frames_compare);
    }

    /* Write out each sorted frame in turn */
    buffer_init(&buf, 1500);
    for (i = 0; i < frames->len; i++) {
        FrameRecord_t *frame = (FrameRecord_t *)frames->pdata[i];

        /* Avoid writing if already sorted and configured to */
        if (write_output_regardless || (wrong_order_count > 0)) {
            frame_write(frame, wth, pdh, &buf, infile);
        }
        g_slice_free(FrameRecord_t, frame);
    }
    buffer_free(&buf);

    if (!write_output_regardless && (wrong_order_count == 0)) {
        printf("Not writing output file because input file is already in order!\n");
    }

    /* Free the whole array */
    g_ptr_array_free(frames, TRUE);

    /* Close outfile */
    if (!wtap_dump_close(pdh, &err)) {
        fprintf(stderr, "reordercap: Error closing %s: %s\n", outfile,
                wtap_strerror(err));
        g_free(shb_hdr);
        exit(1);
    }
    g_free(shb_hdr);

    /* Finally, close infile */
    wtap_fdclose(wth);

    return 0;
}
Exemplo n.º 5
0
/* HOLDS: g_dataset_global_lock */
static inline gpointer
g_data_set_internal (GData	  **datalist,
		     GQuark         key_id,
		     gpointer       data,
		     GDestroyNotify destroy_func,
		     GDataset	   *dataset)
{
  register GData *list;
  
  list = G_DATALIST_GET_POINTER (datalist);
  if (!data)
    {
      register GData *prev;
      
      prev = NULL;
      while (list)
	{
	  if (list->id == key_id)
	    {
	      gpointer ret_data = NULL;

	      if (prev)
		prev->next = list->next;
	      else
		{
		  G_DATALIST_SET_POINTER (datalist, list->next);
		  
		  /* the dataset destruction *must* be done
		   * prior to invocation of the data destroy function
		   */
		  if (!list->next && dataset)
		    g_dataset_destroy_internal (dataset);
		}
	      
	      /* the GData struct *must* already be unlinked
	       * when invoking the destroy function.
	       * we use (data==NULL && destroy_func!=NULL) as
	       * a special hint combination to "steal"
	       * data without destroy notification
	       */
	      if (list->destroy_func && !destroy_func)
		{
		  G_UNLOCK (g_dataset_global);
		  list->destroy_func (list->data);
		  G_LOCK (g_dataset_global);
		}
	      else
		ret_data = list->data;
	      
              g_slice_free (GData, list);
	      
	      return ret_data;
	    }
	  
	  prev = list;
	  list = list->next;
	}
    }
  else
    {
      while (list)
	{
	  if (list->id == key_id)
	    {
	      if (!list->destroy_func)
		{
		  list->data = data;
		  list->destroy_func = destroy_func;
		}
	      else
		{
		  register GDestroyNotify dfunc;
		  register gpointer ddata;
		  
		  dfunc = list->destroy_func;
		  ddata = list->data;
		  list->data = data;
		  list->destroy_func = destroy_func;
		  
		  /* we need to have updated all structures prior to
		   * invocation of the destroy function
		   */
		  G_UNLOCK (g_dataset_global);
		  dfunc (ddata);
		  G_LOCK (g_dataset_global);
		}
	      
	      return NULL;
	    }
	  
	  list = list->next;
	}
      
      list = g_slice_new (GData);
      list->next = G_DATALIST_GET_POINTER (datalist);
      list->id = key_id;
      list->data = data;
      list->destroy_func = destroy_func;
      G_DATALIST_SET_POINTER (datalist, list);
    }

  return NULL;
}
static void
inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection,
                                             gnutls_session_t session,
                                             InfCertificateChain* chain,
                                             gpointer user_data)
{
  InfGtkCertificateManager* manager;
  InfGtkCertificateManagerPrivate* priv;

  InfGtkCertificateDialogFlags flags;
  gnutls_x509_crt_t presented_cert;
  gnutls_x509_crt_t known_cert;
  gchar* hostname;

  gboolean match_hostname;
  gboolean issuer_known;
  gnutls_x509_crt_t root_cert;

  int ret;
  unsigned int verify;
  GHashTable* table;
  gboolean cert_equal;
  time_t expiration_time;

  InfGtkCertificateManagerQuery* query;
  gchar* text;
  GtkWidget* vbox;
  GtkWidget* button;
  GtkWidget* image;
  GtkWidget* label;

  GError* error;

  manager = INF_GTK_CERTIFICATE_MANAGER(user_data);
  priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);

  g_object_get(G_OBJECT(connection), "remote-hostname", &hostname, NULL);
  presented_cert = inf_certificate_chain_get_own_certificate(chain);

  match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname);

  /* First, validate the certificate */
  ret = gnutls_certificate_verify_peers2(session, &verify);
  error = NULL;

  if(ret != GNUTLS_E_SUCCESS)
    inf_gnutls_set_error(&error, ret);

  /* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification
   * result, and if the certificate is still invalid, then set an error. */
  if(error == NULL)
  {
    issuer_known = TRUE;
    if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND)
    {
      issuer_known = FALSE;

      /* Re-validate the certificate for other failure reasons --
       * unfortunately the gnutls_certificate_verify_peers2() call
       * does not tell us whether the certificate is otherwise invalid
       * if a signer is not found already. */
      /* TODO: Here it would be good to use the verify flags from the
       * certificate credentials, but GnuTLS does not have API to
       * retrieve them. */
      root_cert = inf_certificate_chain_get_root_certificate(chain);

      ret = gnutls_x509_crt_list_verify(
        inf_certificate_chain_get_raw(chain),
        inf_certificate_chain_get_n_certificates(chain),
        &root_cert,
        1,
        NULL,
        0,
        GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
        &verify
      );

      if(ret != GNUTLS_E_SUCCESS)
        inf_gnutls_set_error(&error, ret);
      else if(verify & GNUTLS_CERT_INVALID)
        inf_gnutls_certificate_verification_set_error(&error, verify);
    }
  }

  /* Look up the host in our database of pinned certificates if we could not
   * fully verify the certificate, i.e. if either the issuer is not known or
   * the hostname of the connection does not match the certificate. */
  table = NULL;
  if(error == NULL)
  {
    known_cert = NULL;
    if(!match_hostname || !issuer_known)
    {
      /* If we cannot load the known host file, then cancel the connection.
       * Otherwise it might happen that someone shows us a certificate that we
       * tell the user we don't know, if though actually for that host we expect
       * a different certificate. */
      table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error);
      if(table != NULL)
        known_cert = g_hash_table_lookup(table, hostname);
    }
  }

  /* Next, configure the flags for the dialog to be shown based on the
   * verification result, and on whether the pinned certificate matches
   * the one presented by the host or not. */
  flags = 0;
  if(error == NULL)
  {
    if(known_cert != NULL)
    {
      cert_equal = inf_gtk_certificate_manager_compare_fingerprint(
        known_cert,
        presented_cert,
        &error
      );

      if(error == NULL && cert_equal == FALSE)
      {
        if(!match_hostname)
          flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH;
        if(!issuer_known)
          flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN;

        flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED;
        expiration_time = gnutls_x509_crt_get_expiration_time(known_cert);
        if(expiration_time != (time_t)(-1))
        {
          expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE;
          if(time(NULL) > expiration_time)
          {
            flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED;
          }
        }
      }
    }
    else
    {
      if(!match_hostname)
        flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH;
      if(!issuer_known)
        flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN;
    }
  }

  /* Now proceed either by accepting the connection, rejecting it, or
   * bothering the user with an annoying dialog. */
  if(error == NULL)
  {
    if(flags == 0)
    {
      if(match_hostname && issuer_known)
      {
        /* Remove the pinned entry if we now have a valid certificate for
         * this host. */
        if(table != NULL && g_hash_table_remove(table, hostname) == TRUE)
        {
          inf_gtk_certificate_manager_write_known_hosts_with_warning(
            manager,
            table
          );
        }
      }

      inf_xmpp_connection_certificate_verify_continue(connection);
    }
    else
    {
      query = g_slice_new(InfGtkCertificateManagerQuery);
      query->manager = manager;
      query->known_hosts = table;
      query->connection = connection;
      query->dialog = inf_gtk_certificate_dialog_new(
        priv->parent_window,
        0,
        flags,
        hostname,
        chain
      );
      query->certificate_chain = chain;

      table = NULL;

      g_object_ref(query->connection);
      inf_certificate_chain_ref(chain);

      g_signal_connect(
        G_OBJECT(connection),
        "notify::status",
        G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb),
        query
      );

      g_signal_connect(
        G_OBJECT(query->dialog),
        "response",
        G_CALLBACK(inf_gtk_certificate_manager_response_cb),
        query
      );

      image = gtk_image_new_from_stock(GTK_STOCK_CANCEL, GTK_ICON_SIZE_BUTTON);
      gtk_widget_show(image);

      button = gtk_dialog_add_button(
        GTK_DIALOG(query->dialog),
        _("_Cancel connection"),
        GTK_RESPONSE_REJECT
      );

      gtk_button_set_image(GTK_BUTTON(button), image);

      image = gtk_image_new_from_stock(GTK_STOCK_CONNECT, GTK_ICON_SIZE_BUTTON);
      gtk_widget_show(image);

      button = gtk_dialog_add_button(
        GTK_DIALOG(query->dialog),
        _("C_ontinue connection"),
        GTK_RESPONSE_ACCEPT
      );

      gtk_button_set_image(GTK_BUTTON(button), image);

      text = g_strdup_printf(
        _("Do you want to continue the connection to host \"%s\"? If you "
          "choose to continue, this certificate will be trusted in the "
          "future when connecting to this host."),
        hostname
      );

      label = gtk_label_new(text);
      gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
      gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
      gtk_label_set_width_chars(GTK_LABEL(label), 60);
      gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
      gtk_widget_show(label);
      g_free(text);

      vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog));
      gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);

      priv->queries = g_slist_prepend(priv->queries, query);
      gtk_window_present(GTK_WINDOW(query->dialog));
    }
  }
  else
  {
    inf_xmpp_connection_certificate_verify_cancel(connection, error);
    g_error_free(error);
  }

  if(table != NULL) g_hash_table_unref(table);
  g_free(hostname);
}
Exemplo n.º 7
0
/**
 * pango_script_iter_new:
 * @text: a UTF-8 string
 * @length: length of @text, or -1 if @text is nul-terminated.
 *
 * Create a new #PangoScriptIter, used to break a string of
 * Unicode into runs by text. No copy is made of @text, so
 * the caller needs to make sure it remains valid until
 * the iterator is freed with pango_script_iter_free().
 *
 * Return value: the new script iterator, initialized
 *  to point at the first range in the text, which should be
 *  freed with pango_script_iter_free(). If the string is
 *  empty, it will point at an empty range.
 *
 * Since: 1.4
 **/
PangoScriptIter *
pango_script_iter_new (const char *text,
		       int         length)
{
  return _pango_script_iter_init (g_slice_new (PangoScriptIter), text, length);
}
Exemplo n.º 8
0
static Tcs3_diag *css_diag(Tcs3_destination dest, Tcs3_style style, GtkWidget *transient_win, gboolean grab) {

	Tcs3_diag *diag;
	GtkWidget *scrolwin, *table, *but, *vbox, *hbox, *vbox2;
	GList *tmplist = NULL;
	Tcs3_arr tmp;
	gint count=0;
	GtkTreeSelection *selection;
	GtkCellRenderer *renderer;
	GtkTreeViewColumn *column;
	
	diag = g_slice_new(Tcs3_diag);
	diag->win = window_full2(_("Cascading Style Sheet Builder"), GTK_WIN_POS_CENTER_ON_PARENT, 
			12, G_CALLBACK(cs3d_destroy_lcb), diag, TRUE, transient_win);
	gtk_window_set_role(GTK_WINDOW(diag->win), "css");
	diag->dest = dest;
	diag->styletype = style;
	diag->grab = grab;
	diag->selected_row = -1;

	vbox = gtk_vbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(diag->win),vbox);
	
	table = gtk_table_new(3, 6, TRUE);
	gtk_table_set_row_spacings(GTK_TABLE(table), 12);
	gtk_table_set_col_spacings(GTK_TABLE(table), 12);
	gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
	tmplist = NULL;
	
	if (diag->styletype == multistyle) {
		tmplist = glist_with_html_tags(0);
		diag->selector = combobox_with_popdown("", tmplist,1);
		dialog_mnemonic_label_in_table(_("_Selector(s):"), diag->selector, table, 0, 1, 0, 1);
		gtk_table_attach_defaults(GTK_TABLE(table), diag->selector, 1 ,5 , 0, 1);
		gtk_combo_box_set_wrap_width(GTK_COMBO_BOX(diag->selector), 5);
		gtk_combo_box_set_add_tearoffs(GTK_COMBO_BOX(diag->selector), 1);

		diag->html5 = gtk_check_button_new_with_mnemonic("_html 5");
		gtk_table_attach_defaults(GTK_TABLE(table), diag->html5, 5,6, 0,1);
		g_signal_connect(diag->html5, "clicked", G_CALLBACK(cs3d_html5_clicked_lcb), diag);
		
		g_list_free(tmplist);
		tmplist = NULL;
	} 

	tmp = cs3_arr[count];
	while (tmp.property) {
		tmplist = g_list_append(tmplist, tmp.property);
		count++;
		tmp = cs3_arr[count];
	}
	diag->property = combobox_with_popdown("", tmplist,1);
	g_list_free(tmplist);
	tmplist = NULL;
	g_signal_connect(gtk_bin_get_child(GTK_BIN(diag->property)), "activate", G_CALLBACK(cs3d_prop_activate_lcb), diag);
	g_signal_connect(gtk_bin_get_child(GTK_BIN(diag->property)), "changed", G_CALLBACK(cs3d_prop_activate_lcb), diag);

	diag->value = combobox_with_popdown("", tmplist,1);
	dialog_mnemonic_label_in_table(_("_Property:"), diag->property, table, 0, 1, 1, 2);
	gtk_table_attach_defaults(GTK_TABLE(table), diag->property, 1, 5, 1, 2);
	gtk_combo_box_set_wrap_width(GTK_COMBO_BOX(diag->property), 4);
	gtk_combo_box_set_add_tearoffs(GTK_COMBO_BOX(diag->property), 1);
	dialog_mnemonic_label_in_table(_("_Value:"), diag->value, table, 0, 1, 2, 3);
	gtk_table_attach_defaults(GTK_TABLE(table), diag->value, 1, 4, 2, 3);

	
	gtk_widget_realize(diag->win);


	diag->extra_but = color_but_new(GTK_WIDGET(gtk_bin_get_child(GTK_BIN(diag->value))), diag->win);
	gtk_table_attach(GTK_TABLE(table), diag->extra_but, 4, 5, 2, 3, GTK_EXPAND, GTK_EXPAND, 0, 0);

	/* the list widget and the buttons are in a horizontal box */
	hbox = gtk_hbox_new(FALSE, 12);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 18);
	
	diag->lstore = gtk_list_store_new(3, G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING);
	gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(diag->lstore),0,GTK_SORT_ASCENDING);
	diag->lview = gtk_tree_view_new_with_model(GTK_TREE_MODEL(diag->lstore));
	g_object_unref(G_OBJECT(diag->lstore));
	if (diag->styletype == multistyle) {
		renderer = gtk_cell_renderer_text_new();
		column = gtk_tree_view_column_new_with_attributes (_("Selector(s)"),renderer,"text", 0,NULL);
		gtk_tree_view_append_column(GTK_TREE_VIEW(diag->lview), column);
	}
	renderer = gtk_cell_renderer_text_new();
	column = gtk_tree_view_column_new_with_attributes (_("Property"),renderer,"text", 1,NULL);
	gtk_tree_view_append_column(GTK_TREE_VIEW(diag->lview), column);
	renderer = gtk_cell_renderer_text_new();
	column = gtk_tree_view_column_new_with_attributes (_("Value"),renderer,"text", 2,NULL);
	gtk_tree_view_append_column(GTK_TREE_VIEW(diag->lview), column);
	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(diag->lview));
	gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
	g_signal_connect(G_OBJECT(selection), "changed",G_CALLBACK(cs3d_selection_changed_cb),diag);
	scrolwin = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolwin), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	gtk_widget_set_size_request(scrolwin, 400, 300);
	gtk_box_pack_start(GTK_BOX(hbox), scrolwin, TRUE, TRUE, 0);
	gtk_container_add(GTK_CONTAINER(scrolwin), diag->lview);
	/*if (diag->styletype == multistyle) {
		gchar *titles[] = {_("Selector"), _("Property"), _("Value"), NULL};
		diag->clist = gtk_clist_new_with_titles(3, titles);
	} else {
		gchar *titles[] = {_("Property"), _("Value"), NULL};
		diag->clist = gtk_clist_new_with_titles(2, titles);
	}
	gtk_clist_set_sort_column(GTK_CLIST(diag->clist), 0);
	gtk_clist_set_auto_sort(GTK_CLIST(diag->clist), TRUE);

	g_signal_connect(diag->clist, "select_row", G_CALLBACK(cs3d_select_row_lcb), diag);
	g_signal_connect(diag->clist, "unselect_row", G_CALLBACK(cs3d_unselect_row_lcb), diag);
	gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolwin), diag->lview);
	*/
	
	vbox2 = gtk_vbox_new(FALSE, 6);
	gtk_box_pack_start(GTK_BOX(hbox), vbox2, FALSE, FALSE, 0);
	
	but = gtk_button_new_with_mnemonic(_(" _Add "));
	g_signal_connect(but, "clicked", G_CALLBACK(cs3d_add_clicked_lcb), diag);
	gtk_box_pack_start(GTK_BOX(vbox2), but, FALSE, FALSE, 0);

	but = gtk_button_new_with_mnemonic(_(" _Update "));
	g_signal_connect(but, "clicked", G_CALLBACK(cs3d_update_clicked_lcb), diag);
	gtk_box_pack_start(GTK_BOX(vbox2), but, FALSE, FALSE, 0);
	
	but = gtk_button_new_with_mnemonic(_(" _Delete "));
	g_signal_connect(but, "clicked", G_CALLBACK(cs3d_del_clicked_lcb), diag);
	gtk_box_pack_start(GTK_BOX(vbox2), but, FALSE, FALSE, 0);

	/* the ok and cancel button are in a horizontal box below */
	hbox = gtk_hbox_new(FALSE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 12);	
#if GTK_CHECK_VERSION(3,0,0)
	hbox = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL);
#else
	hbox = gtk_hbutton_box_new();
#endif
	gtk_button_box_set_layout(GTK_BUTTON_BOX(hbox), GTK_BUTTONBOX_END);
	gtk_box_set_spacing(GTK_BOX(hbox), 12);
	
	but = bf_stock_cancel_button(G_CALLBACK(cs3d_cancel_clicked_lcb), diag);
	gtk_box_pack_start(GTK_BOX(hbox), but, FALSE, FALSE, 0);
	but = bf_stock_ok_button(G_CALLBACK(cs3d_ok_clicked_lcb), diag);
	gtk_box_pack_start(GTK_BOX(hbox), but, FALSE, FALSE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);	
	
	gtk_widget_show_all(diag->win);
	
	cs3d_prop_activate_lcb(NULL, diag);
		
	if (diag->grab) {
		gtk_grab_add(diag->win);
	}
	return diag;
}
Exemplo n.º 9
0
/*
 * gst_registry_chunks_save_pad_template:
 *
 * Store pad_templates in binary chunks.
 *
 * Returns: %TRUE for success
 */
static gboolean
gst_registry_chunks_save_pad_template (GList ** list,
    GstStaticPadTemplate * template)
{
  GstRegistryChunkPadTemplate *pt;
  GstRegistryChunk *chk;

  pt = g_slice_new (GstRegistryChunkPadTemplate);
  chk =
      gst_registry_chunks_make_data (pt, sizeof (GstRegistryChunkPadTemplate));

  pt->presence = template->presence;
  pt->direction = template->direction;

  /* pack pad template strings */
  gst_registry_chunks_save_const_string (list,
      (gchar *) (template->static_caps.string));
  gst_registry_chunks_save_const_string (list, template->name_template);

  *list = g_list_prepend (*list, chk);

  return TRUE;
}
Exemplo n.º 10
0
static void
resource_available (GSSDPResourceBrowser *resource_browser,
                    SoupMessageHeaders   *headers)
{
        GSSDPResourceBrowserPrivate *priv;
        const char *usn;
        const char *header;
        Resource *resource;
        gboolean was_cached;
        guint timeout;
        GList *locations;
        gboolean destroyLocations;
        GList *it1, *it2;
        char *canonical_usn;

        priv = gssdp_resource_browser_get_instance_private (resource_browser);
        usn = soup_message_headers_get_one (headers, "USN");
        if (!usn)
                return; /* No USN specified */

        /* Build list of locations */
        locations = NULL;
        destroyLocations = TRUE;

        header = soup_message_headers_get_one (headers, "Location");
        if (header)
                locations = g_list_append (locations, g_strdup (header));

        header = soup_message_headers_get_one (headers, "AL");
        if (header) {
                /* Parse AL header. The format is:
                 * <uri1><uri2>... */
                const char *start, *end;
                char *uri;

                start = header;
                while ((start = strchr (start, '<'))) {
                        start += 1;
                        if (!start || !*start)
                                break;

                        end = strchr (start, '>');
                        if (!end || !*end)
                                break;

                        uri = g_strndup (start, end - start);
                        locations = g_list_append (locations, uri);

                        start = end;
                }
        }

        if (!locations)
                return; /* No location specified */

        if (priv->version > 0) {
                char *version;

                version = g_strrstr (usn, ":");
                canonical_usn = g_strndup (usn, version - usn);
        } else {
                canonical_usn = g_strdup (usn);
        }

        /* Get from cache, if possible */
        resource = g_hash_table_lookup (priv->resources,
                                        canonical_usn);
        /* Put usn into fresh resources, so this resource will not be
         * removed on cache refreshing. */
        if (priv->fresh_resources != NULL) {
                g_hash_table_add (priv->fresh_resources,
                                  g_strdup (canonical_usn));
        }

        /* If location does not match, expect that we missed bye bye packet */
        if (resource) {
                for (it1 = locations, it2 = resource->locations;
                     it1 && it2;
                     it1 = it1->next, it2 = it2->next) {
                        if (strcmp ((const char *) it1->data,
                                    (const char *) it2->data) != 0) {
                               resource_unavailable (resource_browser, headers);
                               /* Will be destroyed by resource_unavailable */
                               resource = NULL;

                               break;
                        }
                }
        }

        if (resource) {
                /* Remove old timeout */
                g_source_destroy (resource->timeout_src);

                was_cached = TRUE;
        } else {
                /* Create new Resource data structure */
                resource = g_slice_new (Resource);

                resource->resource_browser = resource_browser;
                resource->usn              = g_strdup (usn);
                resource->locations        = locations;
                destroyLocations = FALSE; /* Ownership passed to resource */
                
                g_hash_table_insert (priv->resources,
                                     canonical_usn,
                                     resource);
                
                was_cached = FALSE;

                /* hash-table takes ownership of this */
                canonical_usn = NULL;
        }

        g_free (canonical_usn);

        /* Calculate new timeout */
        header = soup_message_headers_get_one (headers, "Cache-Control");
        if (header) {
                GSList *list;
                int res;

                res = 0;

                for (list = soup_header_parse_list (header);
                     list;
                     list = list->next) {
                        res = sscanf (list->data,
                                      "max-age = %d",
                                      &timeout);
                        if (res == 1)
                                break;
                }

                if (res != 1) {
                        g_warning ("Invalid 'Cache-Control' header. Assuming "
                                   "default max-age of %d.\n"
                                   "Header was:\n%s",
                                   SSDP_DEFAULT_MAX_AGE,
                                   header);

                        timeout = SSDP_DEFAULT_MAX_AGE;
                }

                soup_header_free_list (list);
        } else {
                const char *expires;

                expires = soup_message_headers_get_one (headers, "Expires");
                if (expires) {
                        SoupDate *soup_exp_time;
                        time_t exp_time, cur_time;

                        soup_exp_time = soup_date_new_from_string (expires);
                        exp_time = soup_date_to_time_t (soup_exp_time);
                        soup_date_free (soup_exp_time);

                        cur_time = time (NULL);

                        if (exp_time > cur_time)
                                timeout = exp_time - cur_time;
                        else {
                                g_warning ("Invalid 'Expires' header. Assuming "
                                           "default max-age of %d.\n"
                                           "Header was:\n%s",
                                           SSDP_DEFAULT_MAX_AGE,
                                           expires);

                                timeout = SSDP_DEFAULT_MAX_AGE;
                        }
                } else {
                        g_warning ("No 'Cache-Control' nor any 'Expires' "
                                   "header was specified. Assuming default "
                                   "max-age of %d.", SSDP_DEFAULT_MAX_AGE);

                        timeout = SSDP_DEFAULT_MAX_AGE;
                }
        }

        resource->timeout_src = g_timeout_source_new_seconds (timeout);
        g_source_set_callback (resource->timeout_src,
                               resource_expire,
                               resource, NULL);

        g_source_attach (resource->timeout_src,
                         g_main_context_get_thread_default ());

        g_source_unref (resource->timeout_src);

        /* Only continue with signal emission if this resource was not
         * cached already */
        if (!was_cached) {
                /* Emit signal */
                g_signal_emit (resource_browser,
                               signals[RESOURCE_AVAILABLE],
                               0,
                               usn,
                               locations);
        }
        /* Cleanup */
        if (destroyLocations)
                g_list_free_full (locations, g_free);
}
Exemplo n.º 11
0
P2trCDT* p2tr_cdt_new (P2tCDT *cdt)
{
    P2tTrianglePtrArray cdt_tris = p2t_cdt_get_triangles (cdt);
    GHashTable *point_map = g_hash_table_new (g_direct_hash, g_direct_equal);
    P2trCDT *rmesh = g_slice_new (P2trCDT);

    gint i, j;

    rmesh->mesh = p2tr_mesh_new ();
    rmesh->outline = p2tr_pslg_new ();

    /* First iteration over the CDT - create all the points */
    for (i = 0; i < cdt_tris->len; i++)
    {
        P2tTriangle *cdt_tri = triangle_index (cdt_tris, i);
        for (j = 0; j < 3; j++)
        {
            P2tPoint *cdt_pt = p2t_triangle_get_point(cdt_tri, j);
            P2trPoint *new_pt = g_hash_table_lookup (point_map, cdt_pt);

            if (new_pt == NULL)
            {
                new_pt = p2tr_point_new2 (cdt_pt->x, cdt_pt->y);
                g_hash_table_insert (point_map, cdt_pt, new_pt);
            }
        }
    }

    /* Second iteration over the CDT - create all the edges and find the
     * outline */
    for (i = 0; i < cdt_tris->len; i++)
    {
        P2tTriangle *cdt_tri = triangle_index (cdt_tris, i);

        for (j = 0; j < 3; j++)
        {
            P2tPoint *start = p2t_triangle_get_point (cdt_tri, j);
            P2tPoint *end = p2t_triangle_get_point (cdt_tri, (j + 1) % 3);
            int edge_index = p2t_triangle_edge_index (cdt_tri, start, end);

            P2trPoint *start_new = g_hash_table_lookup (point_map, start);
            P2trPoint *end_new = g_hash_table_lookup (point_map, end);

            if (! p2tr_point_has_edge_to (start_new, end_new))
            {
                gboolean constrained = cdt_tri->constrained_edge[edge_index];
                P2trEdge *edge = p2tr_mesh_new_edge (rmesh->mesh, start_new, end_new, constrained);

                /* If the edge is constrained, we should add it to the
                 * outline */
                if (constrained)
                    p2tr_pslg_add_new_line(rmesh->outline, &start_new->c,
                                           &end_new->c);

                /* We only wanted to create the edge now. We will use it
                 * later */
                p2tr_edge_unref (edge);
            }
        }
    }

    /* Third iteration over the CDT - create all the triangles */
    for (i = 0; i < cdt_tris->len; i++)
    {
        P2tTriangle *cdt_tri = triangle_index (cdt_tris, i);

        P2trPoint *pt1 = g_hash_table_lookup (point_map, p2t_triangle_get_point (cdt_tri, 0));
        P2trPoint *pt2 = g_hash_table_lookup (point_map, p2t_triangle_get_point (cdt_tri, 1));
        P2trPoint *pt3 = g_hash_table_lookup (point_map, p2t_triangle_get_point (cdt_tri, 2));

        P2trTriangle *new_tri = p2tr_mesh_new_triangle (rmesh->mesh,
                                p2tr_point_get_edge_to(pt1, pt2),
                                p2tr_point_get_edge_to(pt2, pt3),
                                p2tr_point_get_edge_to(pt3, pt1));

        /* We won't do any usage of the triangle, so just unref it */
        p2tr_triangle_unref (new_tri);
    }

    return rmesh;
}
Exemplo n.º 12
0
static GskbStrTable *
make_collision_free_hash_table (gsize     sizeof_entry_data,
                                gsize     alignof_entry_data,
                                guint     n_entries,
                                const GskbStrTableEntry *entries,
                                GskbStrTableType table_type,
                                guint size,
                                const guint32 *hashes)
{
  GskbStrTable *table;
  table = g_slice_new (GskbStrTable);
  guint ent_size;
  guint8 *ht_entries;
  guint i;
  guint str_slab_size, str_slab_offset;
  align_data (sizeof (HashEntry), ALIGNOF_HASH_ENTRY,
              sizeof_entry_data, alignof_entry_data,
              &table->sizeof_entry, &table->entry_data_offset);
  ent_size = table->sizeof_entry;
  ht_entries = g_malloc (ent_size * size);
  table->table_size = size;
  table->type = table_type;
  table->table_data = ht_entries;
  table->sizeof_entry_data = sizeof_entry_data;
  table->is_global = FALSE;
  table->is_ptr = FALSE;

  /* mark all entries unfilled. */
  for (i = 0; i < size; i++)
    {
      HashEntry *e;
      e = (HashEntry*)(ht_entries + ent_size * i);
      e->hash_code = 0;
      e->str_slab_offset = G_MAXUINT32;
      memset (e + 1, 0, sizeof_entry_data);
    }
  str_slab_size = 0;
  str_slab_offset = 0;
  if (table_type == GSKB_STR_TABLE_ABLZ)
    {
      for (i = 0; i < n_entries; i++)
        {
          guint len = strlen (entries[i].str);
          if (len < 3)
            str_slab_size += 1;
          else if (len < 65536)
            str_slab_size += 1 + (len - 3);
          else
            g_return_val_if_reached (NULL);
        }
      table->str_slab = g_malloc (str_slab_size);
      for (i = 0; i < n_entries; i++)
        {
          guint len = strlen (entries[i].str);
          guint index = hashes[i] % size;
          HashEntry *e;
          e = (HashEntry *) (ht_entries + ent_size * index);
          g_assert (e->str_slab_offset == G_MAXUINT32);
          e->str_slab_offset = str_slab_offset;
          e->hash_code = hashes[i];
          memcpy ((char*)e + table->entry_data_offset,
                  entries[i].entry_data, sizeof_entry_data);
          table->str_slab[str_slab_offset++] = len>>8;
          if (len > 3)
            {
              memcpy (table->str_slab + str_slab_offset,
                      entries[i].str + 2,
                      len - 3);
              str_slab_offset += len - 3;
            }
        }
    }
  else
    {
      for (i = 0; i < n_entries; i++)
Exemplo n.º 13
0
static void
gimp_action_view_conflict_confirm (GimpActionView  *view,
                                   GtkAction       *action,
                                   guint            accel_key,
                                   GdkModifierType  accel_mask,
                                   const gchar     *accel_path)
{
  GimpActionGroup *group;
  gchar           *label;
  gchar           *accel_string;
  ConfirmData     *confirm_data;
  GtkWidget       *dialog;
  GimpMessageBox  *box;

  g_object_get (action, "action-group", &group, NULL);

  label = gimp_strip_uline (gtk_action_get_label (action));

  accel_string = gtk_accelerator_get_label (accel_key, accel_mask);

  confirm_data = g_slice_new (ConfirmData);

  confirm_data->manager    = view->manager;
  confirm_data->accel_path = g_strdup (accel_path);
  confirm_data->accel_key  = accel_key;
  confirm_data->accel_mask = accel_mask;

  dialog =
    gimp_message_dialog_new (_("Conflicting Shortcuts"),
                             GIMP_STOCK_WARNING,
                             gtk_widget_get_toplevel (GTK_WIDGET (view)), 0,
                             gimp_standard_help_func, NULL,

                             GTK_STOCK_CANCEL,         GTK_RESPONSE_CANCEL,
                             _("_Reassign shortcut"),  GTK_RESPONSE_OK,

                             NULL);

  gtk_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
                                           GTK_RESPONSE_OK,
                                           GTK_RESPONSE_CANCEL,
                                           -1);
  g_signal_connect (dialog, "response",
                    G_CALLBACK (gimp_action_view_conflict_response),
                    confirm_data);

  box = GIMP_MESSAGE_DIALOG (dialog)->box;

  gimp_message_box_set_primary_text (box,
                                     _("Shortcut \"%s\" is already taken "
                                       "by \"%s\" from the \"%s\" group."),
                                     accel_string, label, group->label);
  gimp_message_box_set_text (box,
                             _("Reassigning the shortcut will cause it "
                               "to be removed from \"%s\"."),
                             label);

  g_free (label);
  g_free (accel_string);

  g_object_unref (group);

  gtk_widget_show (dialog);
}
Exemplo n.º 14
0
static mate_pdu* new_pdu(mate_cfg_pdu* cfg, guint32 framenum, field_info* proto, proto_tree* tree) {
	mate_pdu* pdu = (mate_pdu*)g_slice_new(mate_max_size);
	field_info* cfi;
	GPtrArray* ptrs;
	mate_range* range;
	mate_range* proto_range;
	tmp_pdu_data data;
	guint i,j;
	gint min_dist;
	field_info* range_fi;
	gint32 last_start;
	gint32 first_end;
	gint32 curr_end;
	int hfid;

	dbg_print (dbg_pdu,1,dbg_facility,"new_pdu: type=%s framenum=%i",cfg->name,framenum);

	pdu->id = ++(cfg->last_id);
	pdu->cfg = cfg;

	pdu->avpl = new_avpl(cfg->name);

	pdu->frame = framenum;
	pdu->next_in_frame = NULL;
	pdu->rel_time = rd->now;

	pdu->gop = NULL;
	pdu->next = NULL;
	pdu->time_in_gop = -1.0f;

	pdu->first = FALSE;
	pdu->is_start = FALSE;
	pdu->is_stop = FALSE;
	pdu->after_release = FALSE;

	data.ranges = g_ptr_array_new();
	data.pdu  = pdu;
	data.tree = tree;

	/* first we create the proto range */
	proto_range = (mate_range *)g_malloc(sizeof(mate_range));
	proto_range->start = proto->start;
	proto_range->end = proto->start + proto->length;
	g_ptr_array_add(data.ranges,proto_range);

	dbg_print(dbg_pdu,3,dbg_facility,"new_pdu: proto range %u-%u",proto_range->start,proto_range->end);

	last_start = proto_range->start;

	/* we move forward in the tranport */
	for (i = cfg->transport_ranges->len; i--; ) {
		hfid = *((int*)g_ptr_array_index(cfg->transport_ranges,i));
		ptrs = proto_get_finfo_ptr_array(tree, hfid);
		min_dist = 99999;
		range_fi = NULL;

		if (ptrs) {
			for (j=0; j < ptrs->len; j++) {
				cfi = (field_info*) g_ptr_array_index(ptrs,j);
				if (cfi->start < last_start && min_dist >= (last_start - cfi->start) ) {
					range_fi = cfi;
					min_dist = last_start - cfi->start;
				}
			}

			if ( range_fi ) {
				range = (mate_range *)g_malloc(sizeof(*range));
				range->start = range_fi->start;
				range->end = range_fi->start + range_fi->length;
				g_ptr_array_add(data.ranges,range);

				last_start = range_fi->start;

				dbg_print(dbg_pdu,3,dbg_facility,"new_pdu: transport(%i) range %i-%i",hfid,range->start,range->end);
			} else {
				/* we missed a range  */
				dbg_print(dbg_pdu,6,dbg_facility,"new_pdu: transport(%i) missed",hfid);
			}

		}
	}

	if (cfg->payload_ranges) {

		first_end = proto_range->end;

		for (i = 0 ; i < cfg->payload_ranges->len; i++) {
			hfid = *((int*)g_ptr_array_index(cfg->payload_ranges,i));
			ptrs = proto_get_finfo_ptr_array(tree, hfid);
			min_dist = 99999;
			range_fi = NULL;

			if (ptrs) {
				for (j=0; j < ptrs->len; j++) {
					cfi = (field_info*) g_ptr_array_index(ptrs,j);
					curr_end = cfi->start + cfi->length;
					if (curr_end > first_end && min_dist >= (curr_end - first_end) ) {
						range_fi = cfi;
						min_dist = curr_end - first_end;
					}
				}

				if ( range_fi ) {
					range = (mate_range *)g_malloc(sizeof(*range));
					range->start = range_fi->start;
					range->end = range_fi->start + range_fi->length;
					g_ptr_array_add(data.ranges,range);

					dbg_print(dbg_pdu,3,dbg_facility,"new_pdu: payload(%i) range %i-%i",hfid,range->start,range->end);
				} else {
					/* we missed a range  */
					dbg_print(dbg_pdu,5,dbg_facility,"new_pdu: payload(%i) missed",hfid);
				}

			}
		}
	}

	g_hash_table_foreach(cfg->hfids_attr,get_pdu_fields,&data);

	apply_transforms(pdu->cfg->transforms,pdu->avpl);

	g_ptr_array_free(data.ranges,TRUE);

	return pdu;
}
Exemplo n.º 15
0
static struct g_geom *
g_bsd_taste(struct g_class *mp, struct g_provider *pp, int flags)
{
	struct g_geom *gp;
	struct g_consumer *cp;
	int error, i;
	struct g_bsd_softc *ms;
	u_int secsize;
	struct g_slicer *gsp;
	u_char hash[16];
	MD5_CTX md5sum;
	struct uuid uuid;

	g_trace(G_T_TOPOLOGY, "bsd_taste(%s,%s)", mp->name, pp->name);
	g_topology_assert();

	/* We don't implement transparent inserts. */
	if (flags == G_TF_TRANSPARENT)
		return (NULL);

	/*
	 * BSD labels are a subclass of the general "slicing" topology so
	 * a lot of the work can be done by the common "slice" code.
	 * Create a geom with space for MAXPARTITIONS providers, one consumer
	 * and a softc structure for us.  Specify the provider to attach
	 * the consumer to and our "start" routine for special requests.
	 * The provider is opened with mode (1,0,0) so we can do reads
	 * from it.
	 */
	gp = g_slice_new(mp, MAXPARTITIONS, pp, &cp, &ms,
	     sizeof(*ms), g_bsd_start);
	if (gp == NULL)
		return (NULL);

	/* Get the geom_slicer softc from the geom. */
	gsp = gp->softc;

	/*
	 * The do...while loop here allows us to have multiple escapes
	 * using a simple "break".  This improves code clarity without
	 * ending up in deep nesting and without using goto or come from.
	 */
	do {
		/*
		 * If the provider is an MBR we will only auto attach
		 * to type 165 slices in the G_TF_NORMAL case.  We will
		 * attach to any other type.
		 */
		error = g_getattr("MBR::type", cp, &i);
		if (!error) {
			if (i != 165 && flags == G_TF_NORMAL)
				break;
			error = g_getattr("MBR::offset", cp, &ms->mbroffset);
			if (error)
				break;
		}

		/* Same thing if we are inside a PC98 */
		error = g_getattr("PC98::type", cp, &i);
		if (!error) {
			if (i != 0xc494 && flags == G_TF_NORMAL)
				break;
			error = g_getattr("PC98::offset", cp, &ms->mbroffset);
			if (error)
				break;
		}

		/* Same thing if we are inside a GPT */
		error = g_getattr("GPT::type", cp, &uuid);
		if (!error) {
			if (memcmp(&uuid, &freebsd_slice, sizeof(uuid)) != 0 &&
			    flags == G_TF_NORMAL)
				break;
		}

		/* Get sector size, we need it to read data. */
		secsize = cp->provider->sectorsize;
		if (secsize < 512)
			break;

		/* First look for a label at the start of the second sector. */
		error = g_bsd_try(gp, gsp, cp, secsize, ms, secsize);

		/*
		 * If sector size is not 512 the label still can be at
		 * offset 512, not at the start of the second sector. At least
		 * it's true for labels created by the FreeBSD's bsdlabel(8).
		 */
		if (error && secsize != HISTORIC_LABEL_OFFSET)
			error = g_bsd_try(gp, gsp, cp, secsize, ms,
			    HISTORIC_LABEL_OFFSET);

		/* Next, look for alpha labels */
		if (error)
			error = g_bsd_try(gp, gsp, cp, secsize, ms,
			    ALPHA_LABEL_OFFSET);

		/* If we didn't find a label, punt. */
		if (error)
			break;

		/*
		 * In order to avoid recursively attaching to the same
		 * on-disk label (it's usually visible through the 'c'
		 * partition) we calculate an MD5 and ask if other BSD's
		 * below us love that label.  If they do, we don't.
		 */
		MD5Init(&md5sum);
		MD5Update(&md5sum, ms->label, sizeof(ms->label));
		MD5Final(ms->labelsum, &md5sum);

		error = g_getattr("BSD::labelsum", cp, &hash);
		if (!error && !bcmp(ms->labelsum, hash, sizeof(hash)))
			break;

		/*
		 * Process the found disklabel, and modify our "slice"
		 * instance to match it, if possible.
		 */
		error = g_bsd_modify(gp, ms->label);
	} while (0);

	/* Success or failure, we can close our provider now. */
	g_access(cp, -1, 0, 0);

	/* If we have configured any providers, return the new geom. */
	if (gsp->nprovider > 0) {
		g_slice_conf_hot(gp, 0, ms->labeloffset, LABELSIZE,
		    G_SLICE_HOT_ALLOW, G_SLICE_HOT_DENY, G_SLICE_HOT_CALL);
		gsp->hot = g_bsd_hotwrite;
		return (gp);
	}
	/*
	 * ...else push the "self-destruct" button, by spoiling our own
	 * consumer.  This triggers a call to g_slice_spoiled which will
	 * dismantle what was setup.
	 */
	g_slice_spoiled(cp);
	return (NULL);
}
Exemplo n.º 16
0
static void
device_added (MMBaseManager *manager,
              GUdevDevice *port,
              gboolean hotplugged,
              gboolean manual_scan)
{
    MMDevice *device;
    const char *subsys, *name, *physdev_path, *physdev_subsys;
    gboolean is_candidate;
    GUdevDevice *physdev = NULL;

    g_return_if_fail (port != NULL);

    subsys = g_udev_device_get_subsystem (port);
    name = g_udev_device_get_name (port);

    /* ignore VTs */
    if (strncmp (name, "tty", 3) == 0 && isdigit (name[3]))
        return;

    /* Ignore devices that aren't completely configured by udev yet.  If
     * ModemManager is started in parallel with udev, explicitly requesting
     * devices may return devices for which not all udev rules have yet been
     * applied (a bug in udev/gudev).  Since we often need those rules to match
     * the device to a specific ModemManager driver, we need to ensure that all
     * rules have been processed before handling a device.
     */
    is_candidate = g_udev_device_get_property_as_boolean (port, "ID_MM_CANDIDATE");
    if (!is_candidate) {
        /* This could mean that device changed, loosing its ID_MM_CANDIDATE
         * flags (such as Bluetooth RFCOMM devices upon disconnect.
         * Try to forget it. */
        if (hotplugged && !manual_scan)
            device_removed (manager, port);
        return;
    }

    if (find_device_by_port (manager, port))
        return;

    /* Find the port's physical device's sysfs path.  This is the kernel device
     * that "owns" all the ports of the device, like the USB device or the PCI
     * device the provides each tty or network port.
     */
    physdev = find_physical_device (port);
    if (!physdev) {
        /* Warn about it, but filter out some common ports that we know don't have
         * anything to do with mobile broadband.
         */
        if (   strcmp (name, "console")
            && strcmp (name, "ptmx")
            && strcmp (name, "lo")
            && strcmp (name, "tty")
            && !strstr (name, "virbr"))
            mm_dbg ("(%s/%s): could not get port's parent device", subsys, name);

        goto out;
    }

    /* Is the device blacklisted? */
    if (g_udev_device_get_property_as_boolean (physdev, "ID_MM_DEVICE_IGNORE")) {
        mm_dbg ("(%s/%s): port's parent device is blacklisted", subsys, name);
        goto out;
    }

    /* Is the device in the manual-only greylist? If so, return if this is an
     * automatic scan. */
    if (!manual_scan && g_udev_device_get_property_as_boolean (physdev, "ID_MM_DEVICE_MANUAL_SCAN_ONLY")) {
        mm_dbg ("(%s/%s): port probed only in manual scan", subsys, name);
        goto out;
    }

    /* If the physdev is a 'platform' or 'pnp' device that's not whitelisted, ignore it */
    physdev_subsys = g_udev_device_get_subsystem (physdev);
    if (   physdev_subsys
        && (   g_str_equal (physdev_subsys, "platform")
            || g_str_equal (physdev_subsys, "pnp"))
        && !g_udev_device_get_property_as_boolean (physdev, "ID_MM_PLATFORM_DRIVER_PROBE")) {
        mm_dbg ("(%s/%s): port's parent platform driver is not whitelisted", subsys, name);
        goto out;
    }

    physdev_path = g_udev_device_get_sysfs_path (physdev);
    if (!physdev_path) {
        mm_dbg ("(%s/%s): could not get port's parent device sysfs path", subsys, name);
        goto out;
    }

    /* See if we already created an object to handle ports in this device */
    device = find_device_by_sysfs_path (manager, physdev_path);
    if (!device) {
        FindDeviceSupportContext *ctx;

        /* Keep the device listed in the Manager */
        device = mm_device_new (physdev, hotplugged);
        g_hash_table_insert (manager->priv->devices,
                             g_strdup (physdev_path),
                             device);

        /* Launch device support check */
        ctx = g_slice_new (FindDeviceSupportContext);
        ctx->self = g_object_ref (manager);
        ctx->device = g_object_ref (device);
        mm_plugin_manager_device_support_check (
            manager->priv->plugin_manager,
            device,
            (GAsyncReadyCallback) device_support_check_ready,
            ctx);
    }

    /* Grab the port in the existing device. */
    mm_device_grab_port (device, port);

out:
    if (physdev)
        g_object_unref (physdev);
}
/**
 * @fn int main (int argc, char **argv)
 * @brief Main program & Gtk thread.
 *
 * Create window and all widgets, then set there parameters to be the <br>
 * ROS params.
 */
int main (int argc, char **argv)
{
    GtkBuilder *builder;
    GdkColor black = { 0, 0, 0, 0 };
    GError *error = NULL;
    char glade_gui_file[FILENAME_MAX];
    int start_zoom = 15;
    char *mapcachedir;
    OsmGpsMapPoint ccny_coord = { 40.818551, -73.948674 };

    struct arg param;
    param.argc = argc;
    param.argv = argv;

    pthread_t rosThread;

    // **** init threads
    g_thread_init (NULL);
    gdk_threads_init ();
    gdk_threads_enter ();

    // **** init gtk
    gtk_init (&argc, &argv);

    // **** allocate data structure
    data = g_slice_new (AppData);

    // **** set the glade gui file & set icon directory
    std::string package_path = ros::package::getPath (ROS_PACKAGE_NAME);
    sprintf (glade_gui_file, "%s/gui/%s", package_path.c_str (), "gui.glade");
    sprintf (data->icon_directory, "%s/gui/icon", package_path.c_str ());

    std::string rosbag_path = ros::package::getPath("rosbag");
    sprintf (data->rosbag_rec_path, "%s/bin/record", rosbag_path.c_str ());

    data->current_page = 0;
    data->telemetry_opt_popup_state = false;
    data->gps_opt_popup_state = false;
    data->fullscreen = false;
    load_icon ();

    // **** Create new GtkBuilder object
    builder = gtk_builder_new ();
    // **** Load UI from file
    if (!gtk_builder_add_from_file (builder, glade_gui_file, &error))
    {
        g_warning ("%s", error->message);
        g_free (error);
        exit (-1);
    }

    // **** Get main window pointer from UI
    data->window = GTK_WIDGET (gtk_builder_get_object (builder, "window1"));
    gtk_window_set_title (GTK_WINDOW (data->window), "CityFlyer Ground Station");
    gtk_window_set_position (GTK_WINDOW (data->window), GTK_WIN_POS_CENTER);
    gtk_window_set_default_size (GTK_WINDOW (data->window), 1024, 576);

    // **** create ROS thread
    pthread_create (&rosThread, NULL, startROS, &param);

    // **** wait ros finish read params
    while (!data->ros_param_read)
    {
        ROS_DEBUG ("Waiting ROS params");
    }

    // **** Get GtkNotebook objsect
    data->notebook = GTK_WIDGET (gtk_builder_get_object (builder, "notebook1"));

    // #####################################################################
    // #####################################################################
    // **** Tab 1: Telemetry

    // **** create altimeter widgets
    data->alt = gtk_altimeter_new ();
    g_object_set (GTK_ALTIMETER (data->alt),
                  "grayscale-color", data->grayscale_color,
                  "unit-is-feet", data->altimeter_unit_is_feet,
                  "unit-step-value", data->altimeter_step_value, "radial-color", data->radial_color, NULL);

    // **** create compass widgets
    data->comp = gtk_compass_new ();
    g_object_set (GTK_COMPASS (data->comp),
                  "grayscale-color", data->grayscale_color, "radial-color", data->radial_color, NULL);

    data->comp2 = gtk_compass_new ();
    g_object_set (GTK_COMPASS (data->comp2),
                  "grayscale-color", data->grayscale_color, "radial-color", data->radial_color, NULL);

    data->gauge1 = gtk_gauge_new ();
    g_object_set (GTK_GAUGE (data->gauge1), "name", data->gauge1_name_f, NULL);
    g_object_set (GTK_GAUGE (data->gauge1),
                  "grayscale-color", data->grayscale_color,
                  "radial-color", data->radial_color,
                  "start-value", data->gauge1_start_value,
                  "end-value", data->gauge1_end_value,
                  "initial-step", data->gauge1_initial_step,
                  "sub-step", (gdouble) data->gauge1_sub_step,
                  "drawing-step", data->gauge1_drawing_step,
                  "color-strip-order", data->gauge1_color_strip_order,
                  "green-strip-start", data->gauge1_green_strip_start,
                  "yellow-strip-start", data->gauge1_yellow_strip_start,
                  "red-strip-start", data->gauge1_red_strip_start, NULL);

    // **** create artificial horizon widgets
    data->arh = gtk_artificial_horizon_new ();
    g_object_set (GTK_ARTIFICIAL_HORIZON (data->arh),
                  "grayscale-color", data->grayscale_color, "radial-color", data->radial_color, NULL);

    // **** create variometer widgets
    data->vario = gtk_variometer_new ();
    g_object_set (GTK_VARIOMETER (data->vario),
                  "grayscale-color", data->grayscale_color,
                  "unit-is-feet", data->variometer_unit_is_feet,
                  "unit-step-value", data->variometer_step_value, "radial-color", data->radial_color, NULL);

    data->widget_table = GTK_WIDGET (gtk_builder_get_object (builder, "table_Widgets"));
    gtk_table_attach_defaults (GTK_TABLE (data->widget_table), data->alt, 0, 1, 0, 1);
    gtk_table_attach_defaults (GTK_TABLE (data->widget_table), data->arh, 1, 2, 0, 1);
    gtk_table_attach_defaults (GTK_TABLE (data->widget_table), data->comp, 2, 3, 0, 1);
    gtk_table_attach_defaults (GTK_TABLE (data->widget_table), data->vario, 0, 1, 1, 2);
    gtk_table_attach_defaults (GTK_TABLE (data->widget_table), data->comp2, 1, 2, 1, 2);
    gtk_table_attach_defaults (GTK_TABLE (data->widget_table), data->gauge1, 2, 3, 1, 2);

    gtk_widget_modify_bg (data->alt, GTK_STATE_NORMAL, &black);
    gtk_widget_modify_bg (data->comp, GTK_STATE_NORMAL, &black);
    gtk_widget_modify_bg (data->comp2, GTK_STATE_NORMAL, &black);
    gtk_widget_modify_bg (data->arh, GTK_STATE_NORMAL, &black);
    gtk_widget_modify_bg (data->gauge1, GTK_STATE_NORMAL, &black);
    gtk_widget_modify_bg (data->vario, GTK_STATE_NORMAL, &black);

    data->telemetry_option_popup = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_TelemetryOption"));
    data->btn_open_telemetry_option_popup =
        GTK_WIDGET (gtk_builder_get_object (builder, "button_OpenTelemetryOptionPopup"));
    data->btn_close_telemetry_option_popup =
        GTK_WIDGET (gtk_builder_get_object (builder, "button_CloseTelemetryOptionPopup"));
    gtk_button_set_image (GTK_BUTTON (data->btn_open_telemetry_option_popup),
                          gtk_image_new_from_pixbuf (gdk_pixbuf_scale_simple
                                  (data->leftarrow_icon_64, 24, 50, GDK_INTERP_HYPER)));
    gtk_button_set_image (GTK_BUTTON (data->btn_close_telemetry_option_popup),
                          gtk_image_new_from_pixbuf (gdk_pixbuf_scale_simple
                                  (data->rightarrow_icon_64, 24, 50, GDK_INTERP_HYPER)));

    // #####################################################################
    // #####################################################################
    // **** Tab 2: Gps

    // Some GpsdViewer initialisation
    data->draw_path = false;
    data->map_provider = OSM_GPS_MAP_SOURCE_OPENSTREETMAP;
    data->map_zoom_max = 18;
    data->map_current_zoom = start_zoom;
    data->repo_uri = osm_gps_map_source_get_repo_uri (data->map_provider);
    data->friendly_name = osm_gps_map_source_get_friendly_name (data->map_provider);
    data->uav_track = osm_gps_map_track_new ();
    mapcachedir = osm_gps_map_get_default_cache_directory ();
    data->cachedir = g_build_filename (mapcachedir, data->friendly_name, NULL);
    g_free (mapcachedir);

    // Create the OsmGpsMap object
    data->map = (OsmGpsMap *) g_object_new (OSM_TYPE_GPS_MAP,
                                            "map-source", data->map_provider,
                                            "tile-cache", data->cachedir, "proxy-uri", g_getenv ("http_proxy"), NULL);

    //Set the starting coordinates and zoom level for the map
    osm_gps_map_set_zoom (data->map, start_zoom);
    osm_gps_map_set_center (data->map, ccny_coord.rlat, ccny_coord.rlon);

    data->osd = gpsd_viewer_osd_new ();
    g_object_set (GPSD_VIEWER_OSD (data->osd),
                  "show-scale", true,
                  "show-coordinates", true,
                  "show-dpad", true,
                  "show-zoom", true, "show-gps-in-dpad", true, "show-gps-in-zoom", false, "dpad-radius", 30, NULL);
    osm_gps_map_layer_add (OSM_GPS_MAP (data->map), OSM_GPS_MAP_LAYER (data->osd));

    data->map_box = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_map_box"));
    data->map_container = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_map_container"));
    gtk_box_pack_start (GTK_BOX (data->map_box), GTK_WIDGET (data->map), TRUE, TRUE, 0);

    data->gpsd_option_popup = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_GpsdOptionPopup"));
    data->btn_open_gpsd_option_popup = GTK_WIDGET (gtk_builder_get_object (builder, "button_OpenGpsdOptionPopup"));
    data->btn_close_gpsd_option_popup = GTK_WIDGET (gtk_builder_get_object (builder, "button_CloseGpsdOptionPopup"));
    gtk_button_set_image (GTK_BUTTON (data->btn_open_gpsd_option_popup),
                          gtk_image_new_from_pixbuf (gdk_pixbuf_scale_simple
                                  (data->leftarrow_icon_64, 24, 50, GDK_INTERP_HYPER)));
    gtk_button_set_image (GTK_BUTTON (data->btn_close_gpsd_option_popup),
                          gtk_image_new_from_pixbuf (gdk_pixbuf_scale_simple
                                  (data->rightarrow_icon_64, 24, 50, GDK_INTERP_HYPER)));

    // #####################################################################
    // #####################################################################
    // **** Tab 3: Rec

    data->recording = 0;
    data->rosbag_record_cmd = "rosbag record";
    data->topicsList = GTK_LIST_STORE (gtk_builder_get_object (builder, "liststore_TopicList"));
    data->cmd_line_entry = GTK_WIDGET (gtk_builder_get_object (builder, "entry_CommandLine"));
    data->prefix_entry = GTK_WIDGET (gtk_builder_get_object (builder, "entry_Prefix"));
    data->info_textview = GTK_WIDGET (gtk_builder_get_object (builder, "textview_BagInfo"));
    data->update_btn = GTK_WIDGET (gtk_builder_get_object (builder, "button_UpdateTopicList"));
    data->box_MotorStatus = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_MotorStatus"));
    data->box_Flying = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_Flying"));
    data->box_Gps = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_Gps"));
    data->flightMode_label = GTK_WIDGET (gtk_builder_get_object (builder, "label_FlightModeValue"));
    data->upTime_label = GTK_WIDGET (gtk_builder_get_object (builder, "label_UpTimeValue"));
    data->cpuLoad_label = GTK_WIDGET (gtk_builder_get_object (builder, "label_CpuLoadValue"));
    data->box_RecordStatus = GTK_WIDGET (gtk_builder_get_object (builder, "hbox_RecordStatus"));
    data->record_stop_btn = GTK_WIDGET (gtk_builder_get_object (builder, "button_RecordStop"));

    gtk_box_pack_end (GTK_BOX (data->box_MotorStatus), data->status_ok_icon_motor, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_MotorStatus), data->status_fail_icon_motor, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_Flying), data->status_ok_icon_flying, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_Flying), data->status_fail_icon_flying, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_Gps), data->status_ok_icon_gps, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_Gps), data->status_fail_icon_gps, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_RecordStatus), data->record_icon, TRUE, TRUE, 0);
    gtk_box_pack_end (GTK_BOX (data->box_RecordStatus), data->record_g_icon, TRUE, TRUE, 0);

    gtk_button_set_image (GTK_BUTTON (data->update_btn),
                          gtk_image_new_from_pixbuf (gdk_pixbuf_scale_simple
                                  (data->refresh_icon_64, 24, 24, GDK_INTERP_HYPER)));
    gtk_button_set_image (GTK_BUTTON (data->record_stop_btn),
                          gtk_image_new_from_pixbuf (gdk_pixbuf_scale_simple
                                  (data->record_icon_64, 40, 40, GDK_INTERP_HYPER)));

    // Connect signals
    gtk_builder_connect_signals (builder, data);

    // Destroy builder, since we don't need it anymore
    g_object_unref (G_OBJECT (builder));

    // Show window. All other widgets are automatically shown by GtkBuilder
    gtk_widget_show_all (data->window);
    gtk_widget_hide(data->record_icon);
    gtk_widget_hide(data->status_ok_icon_motor);
    gtk_widget_hide(data->status_ok_icon_flying);
    gtk_widget_hide(data->status_ok_icon_gps);
    gtk_widget_hide_all(data->telemetry_option_popup);
    gtk_widget_hide_all(data->gpsd_option_popup);

    // **** allow ROS spinning
    data->widget_created = true;

    // **** udpate all widgets
    g_timeout_add (data->telemetry_refresh_rate, widgets_update, NULL);

    gtk_main ();
    gdk_threads_leave ();
    return 0;
}
Exemplo n.º 18
0
static server_item* server_item_new(liPlugin *p, const liPluginItem *p_item) {
	server_item *si = g_slice_new(server_item);
	si->p = p;
	si->p_item = p_item;
	return si;
}
Exemplo n.º 19
0
static void coroutine_fn mirror_iteration(MirrorBlockJob *s)
{
    BlockDriverState *source = s->common.bs;
    int nb_sectors, sectors_per_chunk, nb_chunks;
    int64_t end, sector_num, next_chunk, next_sector, hbitmap_next_sector;
    MirrorOp *op;

    s->sector_num = hbitmap_iter_next(&s->hbi);
    if (s->sector_num < 0) {
        bdrv_dirty_iter_init(source, &s->hbi);
        s->sector_num = hbitmap_iter_next(&s->hbi);
        trace_mirror_restart_iter(s, bdrv_get_dirty_count(source));
        assert(s->sector_num >= 0);
    }

    hbitmap_next_sector = s->sector_num;
    sector_num = s->sector_num;
    sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
    end = s->common.len >> BDRV_SECTOR_BITS;

    /* Extend the QEMUIOVector to include all adjacent blocks that will
     * be copied in this operation.
     *
     * We have to do this if we have no backing file yet in the destination,
     * and the cluster size is very large.  Then we need to do COW ourselves.
     * The first time a cluster is copied, copy it entirely.  Note that,
     * because both the granularity and the cluster size are powers of two,
     * the number of sectors to copy cannot exceed one cluster.
     *
     * We also want to extend the QEMUIOVector to include more adjacent
     * dirty blocks if possible, to limit the number of I/O operations and
     * run efficiently even with a small granularity.
     */
    nb_chunks = 0;
    nb_sectors = 0;
    next_sector = sector_num;
    next_chunk = sector_num / sectors_per_chunk;

    /* Wait for I/O to this cluster (from a previous iteration) to be done.  */
    while (test_bit(next_chunk, s->in_flight_bitmap)) {
        trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
        qemu_coroutine_yield();
    }

    do {
        int added_sectors, added_chunks;

        if (!bdrv_get_dirty(source, next_sector) ||
            test_bit(next_chunk, s->in_flight_bitmap)) {
            assert(nb_sectors > 0);
            break;
        }

        added_sectors = sectors_per_chunk;
        if (s->cow_bitmap && !test_bit(next_chunk, s->cow_bitmap)) {
            bdrv_round_to_clusters(s->target,
                                   next_sector, added_sectors,
                                   &next_sector, &added_sectors);

            /* On the first iteration, the rounding may make us copy
             * sectors before the first dirty one.
             */
            if (next_sector < sector_num) {
                assert(nb_sectors == 0);
                sector_num = next_sector;
                next_chunk = next_sector / sectors_per_chunk;
            }
        }

        added_sectors = MIN(added_sectors, end - (sector_num + nb_sectors));
        added_chunks = (added_sectors + sectors_per_chunk - 1) / sectors_per_chunk;

        /* When doing COW, it may happen that there is not enough space for
         * a full cluster.  Wait if that is the case.
         */
        while (nb_chunks == 0 && s->buf_free_count < added_chunks) {
            trace_mirror_yield_buf_busy(s, nb_chunks, s->in_flight);
            qemu_coroutine_yield();
        }
        if (s->buf_free_count < nb_chunks + added_chunks) {
            trace_mirror_break_buf_busy(s, nb_chunks, s->in_flight);
            break;
        }

        /* We have enough free space to copy these sectors.  */
        bitmap_set(s->in_flight_bitmap, next_chunk, added_chunks);

        nb_sectors += added_sectors;
        nb_chunks += added_chunks;
        next_sector += added_sectors;
        next_chunk += added_chunks;
    } while (next_sector < end);

    /* Allocate a MirrorOp that is used as an AIO callback.  */
    op = g_slice_new(MirrorOp);
    op->s = s;
    op->sector_num = sector_num;
    op->nb_sectors = nb_sectors;

    /* Now make a QEMUIOVector taking enough granularity-sized chunks
     * from s->buf_free.
     */
    qemu_iovec_init(&op->qiov, nb_chunks);
    next_sector = sector_num;
    while (nb_chunks-- > 0) {
        MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
        QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
        s->buf_free_count--;
        qemu_iovec_add(&op->qiov, buf, s->granularity);

        /* Advance the HBitmapIter in parallel, so that we do not examine
         * the same sector twice.
         */
        if (next_sector > hbitmap_next_sector && bdrv_get_dirty(source, next_sector)) {
            hbitmap_next_sector = hbitmap_iter_next(&s->hbi);
        }

        next_sector += sectors_per_chunk;
    }

    bdrv_reset_dirty(source, sector_num, nb_sectors);

    /* Copy the dirty cluster.  */
    s->in_flight++;
    trace_mirror_one_iteration(s, sector_num, nb_sectors);
    bdrv_aio_readv(source, sector_num, &op->qiov, nb_sectors,
                   mirror_read_complete, op);
}
Exemplo n.º 20
0
/* Memory management routines ***************************************/
GncGUID *
guid_malloc (void)
{
    return g_slice_new(GncGUID);
}
Exemplo n.º 21
0
static GHashTable *read_directory(FILE *f, int64_t *diroff,
				  GHashTable *loop_detector,
				  uint16_t endian) {
  int64_t off = *diroff;
  *diroff = 0;
  GHashTable *result = NULL;
  int64_t *key = NULL;
  int64_t nextdiroff = -1;
  int dircount = -1;

  //  g_debug("diroff: %" PRId64, off);

  if (off <= 0) {
    g_warning("Bad offset");
    goto FAIL;
  }

  // loop detection
  if (g_hash_table_lookup_extended(loop_detector, &off, NULL, NULL)) {
    // loop
    g_warning("Loop detected");
    goto FAIL;
  }
  key = g_slice_new(int64_t);
  *key = off;
  g_hash_table_insert(loop_detector, key, NULL);

  // no loop, let's seek
  if (fseeko(f, off, SEEK_SET) != 0) {
    g_warning("Cannot seek to offset");
    goto FAIL;
  }

  // read directory count
  dircount = read_uint16(f, endian);
  if (dircount == -1) {
    g_warning("Cannot read dircount");
    goto FAIL;
  }

  //  g_debug("dircount: %d", dircount);


  // initial checks passed, initialized the hashtable
  result = g_hash_table_new_full(g_int_hash, g_int_equal,
				 g_free, tiffdump_item_destroy);

  // read all directory entries
  for (int i = 0; i < dircount; i++) {
    int32_t tag = read_uint16(f, endian);
    int32_t type = read_uint16(f, endian);
    int64_t count = read_uint32(f, endian);

    if ((tag == -1) || (type == -1) || (count == -1)) {
      g_warning("Cannot read tag, type, and count");
      goto FAIL;
    }

    //    g_debug(" tag: %d, type: %d, count: %" PRId64, tag, type, count);

    // read in the value/offset
    uint8_t value[4];
    if (fread(value, 1, 4, f) != 4) {
      g_warning("Cannot read value/offset");
      goto FAIL;
    }

    uint32_t offset;
    memcpy(&offset, value, 4);
    if (endian == TIFF_BIGENDIAN) {
      offset = GUINT32_FROM_BE(offset);
    } else {
      offset = GUINT32_FROM_LE(offset);
    }

    // allocate the item
    struct _openslide_tiffdump_item *data =
      g_slice_new(struct _openslide_tiffdump_item);
    data->type = (TIFFDataType) type;
    data->count = count;

    // load the value
    switch (type) {
    case TIFF_BYTE:
    case TIFF_ASCII:
    case TIFF_SBYTE:
    case TIFF_UNDEFINED:
      data->value = read_tiff_tag_1(f, count, offset, value);
      break;

    case TIFF_SHORT:
    case TIFF_SSHORT:
      data->value = read_tiff_tag_2(f, count, offset, value, endian);
      break;

    case TIFF_LONG:
    case TIFF_SLONG:
    case TIFF_FLOAT:
    case TIFF_IFD:
      data->value = read_tiff_tag_4(f, count, offset, value, endian);
      break;

    case TIFF_RATIONAL:
    case TIFF_SRATIONAL:
      data->value = read_tiff_tag_4(f, count * 2, offset, value, endian);
      break;

    case TIFF_DOUBLE:
      data->value = read_tiff_tag_8(f, count, offset, endian);
      break;

    default:
      g_warning("Unknown type encountered: %d", type);
      goto FAIL;
    }

    if (data->value == NULL) {
      g_warning("Cannot read value");
      goto FAIL;
    }

    // add this tag to the hashtable
    int *key = g_new(int, 1);
    *key = tag;
    g_hash_table_insert(result, key, data);
  }

  // read the next dir offset
  nextdiroff = read_uint32(f, endian);
  if (nextdiroff == -1) {
    g_warning("Cannot read next directory offset");
    goto FAIL;
  }
  *diroff = nextdiroff;

  // success
  return result;


 FAIL:
  if (result != NULL) {
    g_hash_table_unref(result);
  }
  return NULL;
}
Exemplo n.º 22
0
static CoglBool
_cogl_winsys_egl_onscreen_init (CoglOnscreen *onscreen,
                                EGLConfig egl_config,
                                CoglError **error)
{
  CoglFramebuffer *framebuffer = COGL_FRAMEBUFFER (onscreen);
  CoglContext *context = framebuffer->context;
  CoglDisplay *display = context->display;
  CoglRenderer *renderer = display->renderer;
  CoglRendererEGL *egl_renderer = renderer->winsys;
  CoglXlibRenderer *xlib_renderer =
    _cogl_xlib_renderer_get_data (renderer);
  CoglOnscreenXlib *xlib_onscreen;
  CoglOnscreenEGL *egl_onscreen = onscreen->winsys;
  Window xwin;

  /* FIXME: We need to explicitly Select for ConfigureNotify events.
   * For foreign windows we need to be careful not to mess up any
   * existing event mask.
   * We need to document that for windows we create then toolkits
   * must be careful not to clear event mask bits that we select.
   */

  /* XXX: Note we ignore the user's original width/height when
   * given a foreign X window. */
  if (onscreen->foreign_xid)
    {
      Status status;
      CoglXlibTrapState state;
      XWindowAttributes attr;
      int xerror;

      xwin = onscreen->foreign_xid;

      _cogl_xlib_renderer_trap_errors (display->renderer, &state);

      status = XGetWindowAttributes (xlib_renderer->xdpy, xwin, &attr);
      xerror = _cogl_xlib_renderer_untrap_errors (display->renderer,
                                                  &state);
      if (status == 0 || xerror)
        {
          char message[1000];
          XGetErrorText (xlib_renderer->xdpy, xerror,
                         message, sizeof (message));
          _cogl_set_error (error, COGL_WINSYS_ERROR,
                       COGL_WINSYS_ERROR_CREATE_ONSCREEN,
                       "Unable to query geometry of foreign "
                       "xid 0x%08lX: %s",
                       xwin, message);
          return FALSE;
        }

      _cogl_framebuffer_winsys_update_size (framebuffer,
                                            attr.width, attr.height);

      /* Make sure the app selects for the events we require... */
      onscreen->foreign_update_mask_callback (onscreen,
                                              COGL_ONSCREEN_X11_EVENT_MASK,
                                              onscreen->
                                              foreign_update_mask_data);
    }
  else
    {
      int width;
      int height;
      CoglXlibTrapState state;
      XVisualInfo *xvisinfo;
      XSetWindowAttributes xattr;
      unsigned long mask;
      int xerror;

      width = cogl_framebuffer_get_width (framebuffer);
      height = cogl_framebuffer_get_height (framebuffer);

      _cogl_xlib_renderer_trap_errors (display->renderer, &state);

      xvisinfo = get_visual_info (display, egl_config);
      if (xvisinfo == NULL)
        {
          _cogl_set_error (error, COGL_WINSYS_ERROR,
                       COGL_WINSYS_ERROR_CREATE_ONSCREEN,
                       "Unable to retrieve the X11 visual of context's "
                       "fbconfig");
          return FALSE;
        }

      /* window attributes */
      xattr.background_pixel =
        WhitePixel (xlib_renderer->xdpy,
                    DefaultScreen (xlib_renderer->xdpy));
      xattr.border_pixel = 0;
      /* XXX: is this an X resource that we are leaking‽... */
      xattr.colormap =
        XCreateColormap (xlib_renderer->xdpy,
                         DefaultRootWindow (xlib_renderer->xdpy),
                         xvisinfo->visual,
                         AllocNone);
      xattr.event_mask = COGL_ONSCREEN_X11_EVENT_MASK;

      mask = CWBorderPixel | CWColormap | CWEventMask;

      xwin = XCreateWindow (xlib_renderer->xdpy,
                            DefaultRootWindow (xlib_renderer->xdpy),
                            0, 0,
                            width, height,
                            0,
                            xvisinfo->depth,
                            InputOutput,
                            xvisinfo->visual,
                            mask, &xattr);

      XFree (xvisinfo);

      XSync (xlib_renderer->xdpy, False);
      xerror =
        _cogl_xlib_renderer_untrap_errors (display->renderer, &state);
      if (xerror)
        {
          char message[1000];
          XGetErrorText (xlib_renderer->xdpy, xerror,
                         message, sizeof (message));
          _cogl_set_error (error, COGL_WINSYS_ERROR,
                       COGL_WINSYS_ERROR_CREATE_ONSCREEN,
                       "X error while creating Window for CoglOnscreen: %s",
                       message);
          return FALSE;
        }
    }

  xlib_onscreen = g_slice_new (CoglOnscreenXlib);
  egl_onscreen->platform = xlib_onscreen;

  xlib_onscreen->xwin = xwin;
  xlib_onscreen->is_foreign_xwin = onscreen->foreign_xid ? TRUE : FALSE;

  egl_onscreen->egl_surface =
    eglCreateWindowSurface (egl_renderer->edpy,
                            egl_config,
                            (EGLNativeWindowType) xlib_onscreen->xwin,
                            NULL);

  return TRUE;
}
Exemplo n.º 23
0
static void
gfilter_load_args(GwyContainer *container,
                  GFilterArgs *args)
{
    GwyInventory *inventory;
    gchar *filename, *buffer;
    gsize size;
    guint i;

    inventory = gwy_grain_values();
    *args = gfilter_defaults;

    gwy_container_gis_boolean_by_name(container, update_key, &args->update);
    gwy_container_gis_int32_by_name(container, expanded_key, &args->expanded);
    gwy_container_gis_enum_by_name(container, logical_key, &args->logical);

    for (i = 0; i < NQUANTITIES; i++) {
        RangeRecord *rr = args->ranges + i;
        gchar buf[sizeof(quantity_key) + 10];

        g_snprintf(buf, sizeof(buf), "%s%u", quantity_key, i+1);
        gwy_container_gis_string_by_name(container, buf,
                                         (const guchar**)&rr->quantity);
    }

    args->ranges_history = g_hash_table_new_full(g_str_hash, g_str_equal,
                                                 NULL, range_record_free);
    filename = g_build_filename(gwy_get_user_dir(), "grain_filter", "ranges",
                                NULL);
    if (g_file_get_contents(filename, &buffer, &size, NULL)) {
        gchar *p = buffer, *line;
        for (line = gwy_str_next_line(&p); line; line = gwy_str_next_line(&p)) {
            g_strstrip(line);
            if (*line) {
                GwyGrainValue *gvalue;
                RangeRecord *rr;
                gchar *s = line, *end;
                gdouble lower, upper;

                lower = g_ascii_strtod(s, &end);
                s = end;
                upper = g_ascii_strtod(s, &end);
                if (end == s) {
                    g_warning("Invalid grain_filter range record: %s.", line);
                    continue;
                }
                s = end;
                g_strstrip(s);
                if (!(gvalue = gwy_inventory_get_item(inventory, s))) {
                    g_warning("Invalid grain_filter range record: %s.", line);
                    continue;
                }

                rr = g_slice_new(RangeRecord);
                rr->lower = lower;
                rr->upper = upper;
                rr->quantity = gwy_resource_get_name(GWY_RESOURCE(gvalue));
                g_hash_table_insert(args->ranges_history,
                                    (gpointer)rr->quantity, rr);
            }
        }
        g_free(buffer);
    }
    g_free(filename);

    gfilter_sanitize_args(args);
}
Exemplo n.º 24
0
MotoCommandTransaction *moto_command_transaction_new(void)
{
    MotoCommandTransaction *self = g_slice_new(MotoCommandTransaction);
    moto_command_transaction_init(self);
    return self;
}
Exemplo n.º 25
0
static RutShapeModel *
shape_model_new (RutContext *ctx,
                 CoglBool shaped,
                 float tex_width,
                 float tex_height)
{
  RutShapeModel *shape_model = g_slice_new (RutShapeModel);
  RutBuffer *buffer = rut_buffer_new (sizeof (CoglVertexP3) * 6);
  RutMesh *pick_mesh = rut_mesh_new_from_buffer_p3 (COGL_VERTICES_MODE_TRIANGLES,
                                                    6,
                                                    buffer);
  CoglVertexP3 *pick_vertices = (CoglVertexP3 *)buffer->data;
  CoglMatrix matrix;
  float tex_aspect;
  float size_x;
  float size_y;
  float half_size_x;
  float half_size_y;
  float geom_size_x;
  float geom_size_y;
  float half_geom_size_x;
  float half_geom_size_y;

  rut_object_init (&shape_model->_parent, &rut_shape_model_type);

  shape_model->ref_count = 1;

  if (shaped)
    {
      /* In this case we are using a shape mask texture which is has a
       * square size and is padded with transparent pixels to provide
       * antialiasing. The shape mask is half the size of the texture
       * itself so we make the geometry twice as large to compensate.
       */
      size_x = MIN (tex_width, tex_height);
      size_y = size_x;
      geom_size_x = size_x * 2.0;
      geom_size_y = geom_size_x;
    }
  else
    {
      size_x = tex_width;
      size_y = tex_height;
      geom_size_x = tex_width;
      geom_size_y = tex_height;
    }

  half_size_x = size_x / 2.0;
  half_size_y = size_y / 2.0;
  half_geom_size_x = geom_size_x / 2.0;
  half_geom_size_y = geom_size_y / 2.0;

    {
      int n_vertices;
      int i;

      VertexP2T2T2 vertices[] =
        {
          { -half_geom_size_x, -half_geom_size_y, 0, 0, 0, 0 },
          { -half_geom_size_x,  half_geom_size_y, 0, 1, 0, 1 },
          {  half_geom_size_x,  half_geom_size_y, 1, 1, 1, 1 },

          { -half_geom_size_x, -half_geom_size_y, 0, 0, 0, 0 },
          {  half_geom_size_x,  half_geom_size_y, 1, 1, 1, 1 },
          {  half_geom_size_x, -half_geom_size_y, 1, 0, 1, 0 },
        };

      cogl_matrix_init_identity (&matrix);
      tex_aspect = (float)tex_width / (float)tex_height;

      if (shaped)
        {
          float s_scale, t_scale;
          float s0, t0;

          /* NB: The circle mask texture has a centered circle that is
           * half the width of the texture itself. We want the primary
           * texture to be mapped to this center circle. */

          s_scale = 2;
          t_scale = 2;

          if (tex_aspect < 1) /* taller than it is wide */
            t_scale *= tex_aspect;
          else /* wider than it is tall */
            {
              float inverse_aspect = 1.0f / tex_aspect;
              s_scale *= inverse_aspect;
            }

          s0 = 0.5 - (s_scale / 2.0);
          t0 = 0.5 - (t_scale / 2.0);

          cogl_matrix_translate (&matrix, s0, t0, 0);
          cogl_matrix_scale (&matrix, s_scale, t_scale, 1);
        }

      n_vertices = sizeof (vertices) / sizeof (VertexP2T2T2);
      for (i = 0; i < n_vertices; i++)
        {
          float z = 0, w = 1;

          cogl_matrix_transform_point (&matrix,
                                       &vertices[i].s1,
                                       &vertices[i].t1,
                                       &z,
                                       &w);
#ifdef MESA_CONST_ATTRIB_BUG_WORKAROUND
          vertices[i].Nx = 0;
          vertices[i].Ny = 0;
          vertices[i].Nz = 1;

          vertices[i].Tx = 1;
          vertices[i].Ty = 0;
          vertices[i].Tz = 0;
#endif
        }

      shape_model->primitive =
        primitive_new_p2t2t2 (ctx->cogl_context,
                              COGL_VERTICES_MODE_TRIANGLES,
                              n_vertices,
                              vertices);
    }

  shape_model->shape_texture = cogl_object_ref (ctx->circle_texture);

  pick_vertices[0].x = -half_size_x;
  pick_vertices[0].y = -half_size_y;
  pick_vertices[1].x = -half_size_x;
  pick_vertices[1].y = half_size_y;
  pick_vertices[2].x = half_size_x;
  pick_vertices[2].y = half_size_y;
  pick_vertices[3] = pick_vertices[0];
  pick_vertices[4] = pick_vertices[2];
  pick_vertices[5].x = half_size_x;
  pick_vertices[5].y = -half_size_y;

  shape_model->pick_mesh = pick_mesh;


  return shape_model;
}
Exemplo n.º 26
0
static AuthFileData* auth_file_load(liServer *srv, AuthFile *f) {
	GHashTable *users;
	gchar *contents;
	gchar *c;
	gchar *username, *password;
	GError *err = NULL;
	AuthFileData *data = NULL;

	if (!g_file_get_contents(f->path->str, &contents, NULL, &err)) {
		ERROR(srv, "failed to load auth file \"%s\": %s", f->path->str, err->message);
		g_error_free(err);
		return NULL;
	}

	users = g_hash_table_new((GHashFunc) g_str_hash, (GEqualFunc) g_str_equal);

	/* parse file */
	for ( c = contents ; *c; ) {
		gboolean found_realm, found_newline;
		username = c; password = NULL;

		found_realm = FALSE;
		found_newline = FALSE;
		for ( ; '\0' != *c ; c++ ) {
			if ('\n' == *c || '\r' == *c) {
				*c = '\0';
				found_newline = TRUE;
			} else if (':' == *c) {
				if (NULL == password) {
					password = c+1;
					*c = '\0';
				} else {
					found_realm = TRUE;
				}
			} else if (found_newline) {
				break;
			}
		}

		if (!password) {
			/* missing delimiter for user:pass => bogus file */
			ERROR(srv, "failed to parse auth file \"%s\", missing user:password delimiter", f->path->str);
			goto cleanup_fail;
		}

		/* file is of type htdigest (user:realm:pass) */
		if (f->has_realm && !found_realm) {
			/* missing delimiter for realm:pass => bogus file */
			ERROR(srv, "failed to parse auth file \"%s\", missing realm:password delimiter", f->path->str);
			goto cleanup_fail;
		}

		g_hash_table_insert(users, username, password);
	}

	data = g_slice_new(AuthFileData);
	data->refcount = 1;
	data->contents = contents;
	data->users = users;

	return data;

cleanup_fail:
	g_hash_table_destroy(users);
	g_free(contents);
	return NULL;
}
/* this is loosely based on update_places() from nautilus-places-sidebar.c */
static void
panel_place_menu_item_append_local_gio (PanelPlaceMenuItem *place_item,
					GtkWidget          *menu)
{
	GList   *l;
	GList   *ll;
	GList   *drives;
	GDrive  *drive;
	GList   *volumes;
	GVolume *volume;
	GList   *mounts;
	GMount  *mount;
	GSList       *items;
	GSList       *sl;
	PanelGioItem *item;
	GtkWidget *add_menu;

	items = NULL;

	/* first go through all connected drives */
	drives = g_volume_monitor_get_connected_drives (place_item->priv->volume_monitor);
	for (l = drives; l != NULL; l = l->next) {
		drive = l->data;

		volumes = g_drive_get_volumes (drive);
		if (volumes != NULL) {
			for (ll = volumes; ll != NULL; ll = ll->next) {
				volume = ll->data;
				mount = g_volume_get_mount (volume);
				item = g_slice_new (PanelGioItem);
				if (mount != NULL) {
					item->type = PANEL_GIO_MOUNT;
					item->u.mount = mount;
				} else {
					/* Do show the unmounted volumes; this
					 * is so the user can mount it (in case
					 * automounting is off).
					 *
					 * Also, even if automounting is
					 * enabled, this gives a visual cue
					 * that the user should remember to
					 * yank out the media if he just
					 * unmounted it.
					 */
					item->type = PANEL_GIO_VOLUME;
					item->u.volume = g_object_ref (volume);
				}
				items = g_slist_prepend (items, item);
				g_object_unref (volume);
			}
			g_list_free (volumes);
		} else {
			if (g_drive_is_media_removable (drive) &&
			    !g_drive_is_media_check_automatic (drive)) {
				/* If the drive has no mountable volumes and we
				 * cannot detect media change.. we display the
				 * drive so the user can manually poll the
				 * drive by clicking on it..."
				 *
				 * This is mainly for drives like floppies
				 * where media detection doesn't work.. but
				 * it's also for human beings who like to turn
				 * off media detection in the OS to save
				 * battery juice.
				 */
				item = g_slice_new (PanelGioItem);
				item->type = PANEL_GIO_DRIVE;
				item->u.drive = g_object_ref (drive);
				items = g_slist_prepend (items, item);
			}
		}
		g_object_unref (drive);
	}
	g_list_free (drives);

	/* add all volumes that is not associated with a drive */
	volumes = g_volume_monitor_get_volumes (place_item->priv->volume_monitor);
	for (l = volumes; l != NULL; l = l->next) {
		volume = l->data;
		drive = g_volume_get_drive (volume);
		if (drive != NULL) {
		    	g_object_unref (volume);
			g_object_unref (drive);
			continue;
		}
		mount = g_volume_get_mount (volume);
		item = g_slice_new (PanelGioItem);
		if (mount != NULL) {
			item->type = PANEL_GIO_MOUNT;
			item->u.mount = mount;
		} else {
			/* see comment above in why we add an icon for an
			 * unmounted mountable volume */
			item->type = PANEL_GIO_VOLUME;
			item->u.volume = g_object_ref (volume);
		}
		items = g_slist_prepend (items, item);
		g_object_unref (volume);
	}
	g_list_free (volumes);

	/* add mounts that has no volume (/etc/mtab mounts, ftp, sftp,...) */
	mounts = g_volume_monitor_get_mounts (place_item->priv->volume_monitor);
	for (l = mounts; l != NULL; l = l->next) {
		GFile *root;

		mount = l->data;

		volume = g_mount_get_volume (mount);
		if (volume != NULL) {
			g_object_unref (volume);
			g_object_unref (mount);
			continue;
		}

		root = g_mount_get_root (mount);
		if (!g_file_is_native (root)) {
			g_object_unref (root);
			g_object_unref (mount);
			continue;
		}
		g_object_unref (root);

		item = g_slice_new (PanelGioItem);
		item->type = PANEL_GIO_MOUNT;
		item->u.mount = mount;
		items = g_slist_prepend (items, item);
	}
	g_list_free (mounts);

	/* now that we have everything, add the items inline or in a submenu */
	items = g_slist_reverse (items);

	if (g_slist_length (items) <= MAX_ITEMS_OR_SUBMENU) {
		add_menu = menu;
	} else {
		GtkWidget  *item;

		item = gtk_image_menu_item_new ();
		setup_menu_item_with_icon (item, panel_menu_icon_get_size (),
					   PANEL_ICON_REMOVABLE_MEDIA,
					   NULL, NULL,
					   _("Removable Media"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (sl = items; sl; sl = sl->next) {
		item = sl->data;
		switch (item->type) {
		case PANEL_GIO_DRIVE:
			panel_menu_item_append_drive (add_menu, item->u.drive);
			g_object_unref (item->u.drive);
			break;
		case PANEL_GIO_VOLUME:
			panel_menu_item_append_volume (add_menu, item->u.volume);
			g_object_unref (item->u.volume);
			break;
		case PANEL_GIO_MOUNT:
			panel_menu_item_append_mount (add_menu, item->u.mount);
			g_object_unref (item->u.mount);
			break;
		default:
			g_assert_not_reached ();
		}
		g_slice_free (PanelGioItem, item);
	}

	g_slist_free (items);
}
Exemplo n.º 28
0
static liAction* auth_generic_create(liServer *srv, liWorker *wrk, liPlugin* p, liValue *val, const char *actname, AuthBasicBackend basic_action, gboolean has_realm) {
	AuthFile *afd;
	liValue *method = NULL, *realm = NULL, *file = NULL;
	gint ttl = 10;

	GHashTableIter it;
	gpointer pkey, pvalue;

	if (!val || val->type != LI_VALUE_HASH) {
		ERROR(srv, "%s expects a hashtable with at least 3 elements: method, realm and file", actname);
		return NULL;
	}

	g_hash_table_iter_init(&it, val->data.hash);
	while (g_hash_table_iter_next(&it, &pkey, &pvalue)) {
		GString *key = pkey;
		liValue *value = pvalue;

		if (g_string_equal(key, &aon_method)) {
			if (value->type != LI_VALUE_STRING) {
				ERROR(srv, "auth option '%s' expects string as parameter", aon_method.str);
				return NULL;
			}
			method = value;
		} else if (g_string_equal(key, &aon_realm)) {
			if (value->type != LI_VALUE_STRING) {
				ERROR(srv, "auth option '%s' expects string as parameter", aon_realm.str);
				return NULL;
			}
			realm = value;
		} else if (g_string_equal(key, &aon_file)) {
			if (value->type != LI_VALUE_STRING) {
				ERROR(srv, "auth option '%s' expects string as parameter", aon_file.str);
				return NULL;
			}
			file = value;
		} else if (g_string_equal(key, &aon_ttl)) {
			if (value->type != LI_VALUE_NUMBER || value->data.number < 0) {
				ERROR(srv, "auth option '%s' expects non-negative number as parameter", aon_ttl.str);
				return NULL;
			}
			ttl = value->data.number;
		}
	}

	if (NULL == method || NULL == realm || NULL == file) {
		ERROR(srv, "%s expects a hashtable with 3 elements: method, realm and file", actname);
		return NULL;
	}

	if (!g_str_equal(method->data.string->str, "basic") && !g_str_equal(method->data.string->str, "digest")) {
		ERROR(srv, "%s: unknown method: %s", actname, method->data.string->str);
		return NULL;
	}

	if (g_str_equal(method->data.string->str, "digest")) {
		ERROR(srv, "%s: digest authentication not implemented yet", actname);
		return NULL;
	}

	/* load users from file */
	afd = auth_file_new(wrk, file->data.string, has_realm, ttl);

	if (!afd)
		return FALSE;

	if (g_str_equal(method->data.string->str, "basic")) {
		AuthBasicData *bdata;

		bdata = g_slice_new(AuthBasicData);
		bdata->p = p;
		bdata->realm = li_value_extract_string(realm);
		bdata->backend = basic_action;
		bdata->data = afd;

		return li_action_new_function(auth_basic, NULL, auth_basic_free, bdata);
	} else {
		auth_file_free(afd);
		return NULL; /* li_action_new_function(NULL, NULL, auth_backend_plain_free, ad); */
	}
}
Exemplo n.º 29
0
void mape_edit_view_reload(MapeEditView* edit_view)
{
	GError* error = NULL;
	ThreadData* data;
	GtkTextBuffer* buffer;
	GtkTextIter begin;
	GtkTextIter end;

	if(edit_view->render_thread == NULL)
	{
		data = g_slice_new(ThreadData);

		buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(edit_view->view) );
		gtk_text_buffer_get_start_iter(buffer, &begin);
		gtk_text_buffer_get_end_iter(buffer, &end);

		/* TODO: We need to ref view so that it is guaranteed to be alive in the 
		 * thread result handler */
		data->view = edit_view;
		data->source = gtk_text_buffer_get_text(buffer, &begin, &end, TRUE);
		data->type = edit_view->type;
		data->file_path = g_strdup(edit_view->file_path);

		/* TODO: We need to ref these so noone can delete them while the thread
		 * uses them. */
		data->mat_map = edit_view->pre_view->mat_tex->mat_map,
		data->tex_map = edit_view->pre_view->mat_tex->tex_map,

		data->map_width = edit_view->map_width;
		data->map_height = edit_view->map_height;
		data->map_zoom = edit_view->map_zoom;
		data->start_time = g_get_monotonic_time();

		if(edit_view->fixed_seed == TRUE)
			mape_random_seed(edit_view->random_seed);

		mape_statusbar_set_compile(
			edit_view->statusbar,
			"Rendering map..."
		);

		edit_view->rerender = FALSE;

		edit_view->render_thread = g_thread_create(
			mape_edit_view_thread_entry,
			data,
			TRUE,
			&error
		);
		
		if(edit_view->render_thread == NULL)
		{
			mape_statusbar_set_compile(
				edit_view->statusbar,
				error->message
			);

			g_free(data->source);
			g_slice_free(ThreadData, data);

			g_error_free(error);
		}
	}
	else
	{
		/* Rerender when thread finished */
		edit_view->rerender = TRUE;
	}
}
Exemplo n.º 30
0
jschema_builder *jschema_builder_create()
{
	jschema_builder *builder = g_slice_new(jschema_builder);
	jschema_builder_init(builder);
	return builder;
}