Example #1
0
GHashTable *
SlashProcNet_GetSnmp(void)
{
   GHashTable *myHashTable = NULL;
   GIOChannel *myChannel = NULL;
   GIOStatus keyIoStatus;
   GIOStatus valIoStatus;
   gchar *myKeyLine = NULL;
   gchar *myValLine = NULL;
   Bool parseError = FALSE;
   int fd = -1;

   static GRegex *myKeyRegex = NULL;
   static GRegex *myValRegex = NULL;

   if (myKeyRegex == NULL) {
      myKeyRegex = g_regex_new("^(\\w+): (\\w+ )*(\\w+)$", G_REGEX_OPTIMIZE,
                               0, NULL);
      myValRegex = g_regex_new("^(\\w+): (-?\\d+ )*(-?\\d+)$", G_REGEX_OPTIMIZE,
                               0, NULL);
      ASSERT(myKeyRegex);
      ASSERT(myValRegex);
   }

   if ((fd = g_open(pathToNetSnmp, O_RDONLY)) == -1) {
      return NULL;
   }

   myChannel = g_io_channel_unix_new(fd);

   myHashTable = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

   /*
    * Expected format:
    *
    * pfx0: key0 key1 key2 ... keyN
    * pfx0: val0 val1 val2 ... valN
    * ...
    * pfxN: ...
    */

   while ((keyIoStatus = g_io_channel_read_line(myChannel, &myKeyLine, NULL, NULL,
                                                NULL)) == G_IO_STATUS_NORMAL &&
          (valIoStatus = g_io_channel_read_line(myChannel, &myValLine, NULL, NULL,
                                                NULL)) == G_IO_STATUS_NORMAL) {

      GMatchInfo *keyMatchInfo = NULL;
      GMatchInfo *valMatchInfo = NULL;

      gchar **myKeys = NULL;
      gchar **myVals = NULL;

      gchar **myKey = NULL;
      gchar **myVal = NULL;

      gchar *keyPrefix = NULL;
      gchar *valPrefix = NULL;

      /*
       * Per format above, we expect a pair of lines with a matching prefix.
       */
      {
         if (!g_regex_match(myKeyRegex, myKeyLine, 0, &keyMatchInfo) ||
             !g_regex_match(myValRegex, myValLine, 0, &valMatchInfo)) {
            parseError = TRUE;
            goto badIteration;
         }

         keyPrefix = g_match_info_fetch(keyMatchInfo, 1);
         valPrefix = g_match_info_fetch(valMatchInfo, 1);

         ASSERT(keyPrefix);
         ASSERT(valPrefix);

         if (strcmp(keyPrefix, valPrefix)) {
            parseError = TRUE;
            goto badIteration;
         }
      }

      myKeys = g_strsplit(myKeyLine, " ", 0);
      myVals = g_strsplit(myValLine, " ", 0);

      /*
       * Iterate over the columns, combining the column keys with the prefix
       * to form the new key name.  (I.e., "Ip: InDiscards" => "IpInDiscards".)
       */
      for (myKey = &myKeys[1], myVal = &myVals[1];
           *myKey && *myVal;
           myKey++, myVal++) {
         gchar *hashKey;
         guint64 *myIntVal = NULL;

         hashKey = g_strjoin(NULL, keyPrefix, *myKey, NULL);
         g_strstrip(hashKey);

         /*
          * By virtue of having matched the above regex, this conversion
          * must hold.
          */
         myIntVal = g_new(guint64, 1);
         *myIntVal = g_ascii_strtoull(*myVal, NULL, 10);

         /*
          * If our input contains duplicate keys, which I really don't see
          * happening, the latter value overrides the former.
          *
          * NB: myHashTable claims ownership of hashKey.
          */
         g_hash_table_insert(myHashTable, hashKey, myIntVal);
      }

      /*
       * Make sure the column counts matched.  If we succeeded, both pointers
       * should now be NULL.
       */
      if (*myKey || *myVal) {
         parseError = TRUE;
      }

badIteration:
      g_match_info_free(keyMatchInfo);
      g_match_info_free(valMatchInfo);

      g_free(keyPrefix);
      g_free(valPrefix);

      g_strfreev(myKeys);
      g_strfreev(myVals);

      g_free(myKeyLine);
      g_free(myValLine);
      myKeyLine = NULL;
      myValLine = NULL;

      if (parseError) {
         break;
      }
   }

   /*
    * Error conditions:
    *    Hash table empty:      Unable to parse any input.
    *    myKeyLine != NULL:     Failed to read "key" and "value" lines during
    *                           same loop iteration.
    *    parseError == TRUE:    See loop body above.
    */
   if (keyIoStatus == G_IO_STATUS_ERROR ||
       valIoStatus == G_IO_STATUS_ERROR ||
       g_hash_table_size(myHashTable) == 0 ||
       parseError) {
      g_hash_table_destroy(myHashTable);
      myHashTable = NULL;
   }

   g_free(myKeyLine);
   g_free(myValLine);
   myKeyLine = NULL;
   myValLine = NULL;

   close(fd);
   g_io_channel_unref(myChannel);

   return myHashTable;
}
void hamlib_init(void)
{
	rig_model_t model;
	struct timespec sleep;
	freq_t freq;
	rmode_t mode;
	pbwidth_t width;
	gboolean enable;
	gchar *port, *conf, *spd;
	gint ret, speed;

	if (rig != NULL)
		return;

	enable = conf_get_bool("hamlib/enable");
	model = conf_get_int("hamlib/rig");
	port = conf_get_filename("hamlib/port");
	speed = conf_get_int("hamlib/speed");
	conf = conf_get_string("hamlib/conf");

	if (!enable || !model || port[0] == 0)
		return;

	rig_set_debug(RIG_DEBUG_ERR);

	rig = rig_init(model);

	if (rig == NULL) {
		errmsg(_("Hamlib init: rig_init failed (model=%d)"), model);
		return;
	}

	g_strstrip(conf);
	if (conf[0]) {
		gchar **v, **p, *q;

		v = g_strsplit(conf, ",", 0);

		for (p = v; *p; p++) {
			if ((q = strchr(*p, '=')) == NULL) {
				errmsg(_("Hamlib init: Bad param=value pair: '%s'"), *p);
				break;
			}
			*q++ = 0;

			g_strstrip(*p);
			g_strstrip(q);

			if (hamlib_set_param(*p, q) == FALSE)
				break;
		}

		g_strfreev(v);
	}
	g_free(conf);

	hamlib_set_param("rig_pathname", port);
	g_free(port);

	spd = g_strdup_printf("%d", speed);
	hamlib_set_param("serial_speed", spd);
	g_free(spd);

	ret = rig_open(rig);

	if (ret != RIG_OK) {
		errmsg(_("Hamlib init: rig_open failed: %s"), rigerror(ret));
		rig_cleanup(rig);
		rig = NULL;
		return;
	}

	/* Polling the rig sometimes fails right after opening it */
	sleep.tv_sec = 0;
	sleep.tv_nsec = 100000000L;	/* 100ms */
	nanosleep(&sleep, NULL);

	if (need_freq == TRUE && \
	    (ret = rig_get_freq(rig, RIG_VFO_CURR, &freq)) != RIG_OK) {
		errmsg(_("Hamlib init: rig_get_freq failed: %s"), rigerror(ret));

		hamlib_waterfall = FALSE;
		hamlib_qsodata = FALSE;

		need_freq = FALSE;
		need_mode = FALSE;
	}

	if (need_mode == TRUE &&
	    (ret = rig_get_mode(rig, RIG_VFO_CURR, &mode, &width)) != RIG_OK) {
		errmsg(_("Hamlib init: rig_get_mode failed: %s.\nAssuming USB mode."), rigerror(ret));

		need_mode = FALSE;
	}

	if (hamlib_ptt == TRUE && 
	    (ret = rig_set_ptt(rig, RIG_VFO_CURR, RIG_PTT_OFF)) != RIG_OK) {
		errmsg(_("Hamlib init: rig_set_ptt failed: %s.\nHamlib PTT disabled"), rigerror(ret));

		hamlib_ptt = FALSE;
	}

	/* Don't create the thread if frequency data is not needed */
	if (need_freq == FALSE) {
//		g_warning("Freq data not needed, thread not started.");
		/* If PTT isn't needed either then close everything */
		if (hamlib_ptt == FALSE) {
//			g_warning("PTT not needed, closing rig.");
			rig_close(rig);
			rig_cleanup(rig);
			rig = NULL;
		}
		return;
	}

	if (pthread_create(&hamlib_thread, NULL, hamlib_loop, NULL) < 0) {
		errmsg(_("Hamlib init: pthread_create: %m"));
		rig_close(rig);
		rig_cleanup(rig);
		rig = NULL;
	}
}
static gboolean
commit_checksum_from_extensions_ref (OstreeRepo *repo,
                                     GCancellable *cancellable,
                                     const gchar *remote_name,
                                     const gchar *ref,
                                     const gchar *url_override,
                                     gchar **out_checksum,
                                     EosExtensions **out_extensions,
                                     GError **error)
{
  g_autofree gchar *extensions_url = NULL;
  g_autofree gchar *eos_ref_url = NULL;
  g_autoptr(GBytes) contents = NULL;
  g_autoptr(GBytes) signature = NULL;
  g_autoptr(OstreeGpgVerifyResult) gpg_result = NULL;
  g_autofree gchar *checksum = NULL;
  gconstpointer raw_data;
  gsize raw_len;
  g_autoptr(EosExtensions) extensions = NULL;
  g_autoptr(EosRef) ext_ref = NULL;
  g_autoptr(GKeyFile) ref_keyfile = NULL;
  g_autofree gchar *actual_ref = NULL;

  if (!get_extensions_url (repo, remote_name, url_override, &extensions_url, error))
    return FALSE;

  eos_ref_url = g_build_path ("/", extensions_url, "refs.d", ref, NULL);
  if (!must_download_file_and_signature (eos_ref_url, &contents, &signature, error))
    return FALSE;

  gpg_result = ostree_repo_gpg_verify_data (repo,
                                            remote_name,
                                            contents,
                                            signature,
                                            NULL,
                                            NULL,
                                            cancellable,
                                            error);
  if (!ostree_gpg_verify_result_require_valid_signature (gpg_result, error))
    return FALSE;

  ref_keyfile = g_key_file_new ();
  raw_data = g_bytes_get_data (contents, &raw_len);
  if (!g_key_file_load_from_data (ref_keyfile,
                                  raw_data,
                                  raw_len,
                                  G_KEY_FILE_NONE,
                                  error))
    return FALSE;

  actual_ref = g_key_file_get_string (ref_keyfile,
                                      "mapping",
                                      "ref",
                                      error);
  if (actual_ref == NULL)
    return FALSE;

  if (g_strcmp0 (actual_ref, ref) != 0)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "The file under %s contains data about ref %s, instead of %s",
                   eos_ref_url, actual_ref, ref);
      return FALSE;
    }

  checksum = g_key_file_get_string (ref_keyfile,
                                    "mapping",
                                    "commit",
                                    error);
  if (checksum == NULL)
    return FALSE;
  g_strstrip (checksum);

  if (!ostree_validate_structureof_checksum_string (checksum, error))
    return FALSE;

  ext_ref = eos_ref_new_empty ();
  ext_ref->contents = g_steal_pointer (&contents);
  ext_ref->signature = g_steal_pointer (&signature);
  ext_ref->name = g_strdup (ref);

  extensions = eos_extensions_new_empty ();
  g_ptr_array_add (extensions->refs, g_steal_pointer (&ext_ref));

  *out_checksum = g_steal_pointer (&checksum);
  *out_extensions = g_steal_pointer (&extensions);
  return TRUE;
}
Example #4
0
static int tree_scan_script(tree_scan_data_t *p, char *str)
{
  tree_t *tree = p->tree;
  char filename[strlen(p->dirname)+strlen(str)+10];
  char *name;
  script_t *script;
  tree_item_t *item;
  tree_item_t *save_current;
  tree_object_t *obj;
  FILE *f;

  /* Setup PERL script name */
  snprintf(filename, sizeof(filename), "%s" G_DIR_SEPARATOR_S "%s" SCRIPT_PERL_SUFFIX, p->dirname, str);
  if ( access(filename, R_OK) ) {
    tree_error(tree, &(p->loc), "Couldn't access script file '%s': %s", filename, strerror(errno));
    return -1;
  }

  /* Save current node pointer */
  save_current = tree->current;

  /* Compute Test Case identification */
  name = tree_scan_node_name(p, str);
  script = script_new(filename);

  debug("%s:%d: [SCRIPT   ] '%s' script='%s'\n", p->loc.filename, p->loc.lineno, name, script->name);

  /* Add new CASE reference to current sequence */
  item = tree_item_new(name, NULL, tree, NULL, &(p->loc));
  tree_seq_feed(p->seq, item);

  /* Create new CASE node */
  obj = tree_object_new(TYPE_CASE);
  obj->d.Case->script = script;
  tree->current = tree_item_new(name, NULL, tree, obj, &(p->loc));
  tree_add(tree, tree->current);

  /* Check a package definition is present */
  if ( script->package == NULL )
    tree_error(tree, &(p->loc), "CASE '%s': Missing package definition in script file '%s'", tree->current->name, script->name);

  free(name);

  /* Parse Test Script directives */
  name = (script->wizname != NULL) ? script->wizname : script->name;
  if ( (f = fopen(name, "r")) != NULL ) {
    char *buf = NULL;
    int size = 0;
    tree_scan_data_t d;

    d.tree = tree;
    d.seq = p->seq;
    d.loc.filename = name;
    d.loc.lineno = 0;
    d.dirname = p->dirname;

    while ( !feof(f) ) {
      int len = fgets2(f, &buf, &size);

      d.loc.lineno++;

      if ( len > 0 ) {
        char *s = g_strstrip(buf);
        if ( (s[0] == '#') && (s[1] == '$') ) {
          tree_scan_directive(&d, s+2);
        }
      }
    }

    if ( buf != NULL )
      free(buf);

    fclose(f);
  }

  /* Restore current node pointer */
  tree->current = save_current;

  return 0;
}
Example #5
0
static gboolean
process (GeglOperation       *op,
         void                *in_buf,
         void                *out_buf,
         glong                n_pixels,
         const GeglRectangle *roi,
         gint                 level)
{
  GeglProperties *o = GEGL_PROPERTIES (op);
  gfloat     *in = in_buf;
  gfloat     *out = out_buf;
  gfloat     *m;

  gfloat ma[25] = { 1.0, 0.0, 0.0, 0.0, 0.0,
                    0.0, 1.0, 0.0, 0.0, 0.0,
                    0.0, 0.0, 1.0, 0.0, 0.0,
                    0.0, 0.0, 0.0, 1.0, 0.0,
                    0.0, 0.0, 0.0, 0.0, 1.0};
  char         *endptr;
  gfloat        value;
  const gchar  *delimiter = ",";
  const gchar  *delimiters = " ";
  gchar       **values;
  glong         i;

  m = ma;

  if ( o->values != NULL )
    {
      g_strstrip(o->values);
      g_strdelimit (o->values, delimiters, *delimiter);
      values = g_strsplit (o->values, delimiter, 1);
      if (values[0] != NULL)
        {
          value = g_ascii_strtod(values[0], &endptr);
          if (endptr != values[0])
            if ( value >= 0.0 && value <= 1.0 )
              {
                 ma[0]  = 0.213 + 0.787 * value;
                 ma[1]  = 0.715 - 0.715 * value;
                 ma[2]  = 0.072 - 0.072 * value;
                 ma[5]  = 0.213 - 0.213 * value;
                 ma[6]  = 0.715 + 0.285 * value;
                 ma[7]  = 0.072 - 0.072 * value;
                 ma[10] = 0.213 - 0.213 * value;
                 ma[11] = 0.715 - 0.715 * value;
                 ma[12] = 0.072 + 0.928 * value;
              }
        }
      g_strfreev(values);
    }

  for (i=0; i<n_pixels; i++)
    {
      out[0] =  m[0]  * in[0] +  m[1]  * in[1] + m[2]  * in[2] + m[3]  * in[3] + m[4];
      out[1] =  m[5]  * in[0] +  m[6]  * in[1] + m[7]  * in[2] + m[8]  * in[3] + m[9];
      out[2] =  m[10] * in[0] +  m[11] * in[1] + m[12] * in[2] + m[13] * in[3] + m[14];
      out[3] =  m[15] * in[0] +  m[16] * in[1] + m[17] * in[2] + m[18] * in[3] + m[19];
      in  += 4;
      out += 4;
    }

  return TRUE;
}
Example #6
0
static void send_with_encryption(gpointer compose)
{
	GSList *alist, *cur;
	GHashTable *hash;
	SylPluginAttachInfo *ainfo;
	gboolean duplicated = FALSE;
	GtkWidget *dialog;
	gchar *password;
	const gchar *tmp_path;
	const gchar *arc_path;
	gchar *zip_path;
	gchar *filename;
	GString *cmdline;
	gint ret;
	gchar *orig_to;
	gchar *orig_cc;
	gchar *orig_bcc;
	gchar *orig_replyto;
	gchar *orig_subject;
	gchar *subject;
	gchar *body;
	gchar send_date[80];

	/* Check attachments */
	alist = syl_plugin_get_attach_list(compose);
	if (!alist) {
		syl_plugin_alertpanel_message(_("No attachment"), _("There is no attachment. Please attach files before sending."), 3);
		return;
	}
	hash = g_hash_table_new(str_case_hash, str_case_equal);
	for (cur = alist; cur != NULL; cur = cur->next) {
		const gchar *base;
		ainfo = (SylPluginAttachInfo *)cur->data;
		debug_print("attach: file: %s (%s) name: %s\n", ainfo->file, ainfo->content_type, ainfo->name);
		base = g_basename(ainfo->file);
		if (g_hash_table_lookup(hash, base)) {
			duplicated = TRUE;
			break;
		} else {
			g_hash_table_insert(hash, (gpointer)base, (gpointer)base);
		}
	}
	g_hash_table_destroy(hash);
	if (duplicated) {
		syl_plugin_alertpanel_message(_("Duplicate filename"), _("There are duplicate filenames. Multiple files with same name cannot be attached."), 3);
		return;
	}

	/* Get recipients */
	orig_to = syl_plugin_compose_entry_get_text(compose, 0);
	orig_cc = syl_plugin_compose_entry_get_text(compose, 1);
	orig_bcc = syl_plugin_compose_entry_get_text(compose, 2);
	orig_replyto = syl_plugin_compose_entry_get_text(compose, 3);
	orig_subject = syl_plugin_compose_entry_get_text(compose, 4);
	if (orig_to) g_strstrip(orig_to);
	if (orig_cc) g_strstrip(orig_cc);
	if (orig_bcc) g_strstrip(orig_bcc);

	if ((!orig_to || *orig_to == '\0') &&
	    (!orig_cc || *orig_cc == '\0') &&
	    (!orig_bcc || *orig_bcc == '\0')) {
		syl_plugin_alertpanel_message(_("No recipients"), _("Recipient is not specified."), 3);
		g_free(orig_subject);
		g_free(orig_replyto);
		g_free(orig_bcc);
		g_free(orig_cc);
		g_free(orig_to);
		return;
	}

	/* Show processing dialog */
	dialog = autoenc_processing_dialog_create();

	/* Generate password */
	password = generate_password();

	/* Generate encrypted zip */
	filename = generate_filename();
	tmp_path = get_autoenc_tmp_dir();
	if (!is_dir_exist(tmp_path)) {
		make_dir(tmp_path);
	}
	arc_path = get_7z_path();
	zip_path = g_strconcat(tmp_path, G_DIR_SEPARATOR_S,
			       filename, NULL);
	cmdline = g_string_new("");
	if (arc_path) {
		g_string_append_printf(cmdline, "\"%s\\7z\" a -y ", arc_path);
	} else {
		g_string_append(cmdline, "7z a -y ");
	}
	g_string_append(cmdline, "-p");
	g_string_append(cmdline, password);
	g_string_append(cmdline, " ");
	g_string_append_printf(cmdline, "\"%s\"", zip_path);
	for (cur = alist; cur != NULL; cur = cur->next) {
		ainfo = (SylPluginAttachInfo *)cur->data;
		g_string_append(cmdline, " ");
		g_string_append_printf(cmdline, "\"%s\"", ainfo->file);
	}
	debug_print("cmdline: %s\n", cmdline->str);
	ret = execute_command_line_async_wait(cmdline->str);

	/* Close processing dialog */
	gtk_widget_destroy(dialog);

	// check if zip was really created
	if (ret != 0 || !is_file_exist(zip_path) || get_file_size(zip_path) <= 0) {
		gchar message[256];

		if (ret < 0) {
			g_snprintf(message, sizeof(message), _("Error occurred while creating encrypted zip file.\n\n7z command could not be executed. Please check if 7-Zip is correctly installed."));
		} else if (ret > 0) {
			g_snprintf(message, sizeof(message), _("Error occurred while creating encrypted zip file.\n\n7z command returned error (%d)"), ret);
		} else {
			g_snprintf(message, sizeof(message), _("Encrypted zip file could not be created."));
		}
		syl_plugin_alertpanel_message(_("Encrypted zip file creation error"), message, 3);
		g_string_free(cmdline, TRUE);
		g_free(zip_path);
		g_free(filename);
		g_free(password);
		g_free(orig_subject);
		g_free(orig_replyto);
		g_free(orig_bcc);
		g_free(orig_cc);
		g_free(orig_to);
		g_slist_free(alist);
		return;
	}
	g_string_free(cmdline, TRUE);
	g_slist_free(alist);

	/* Replace attachments */
	syl_plugin_compose_attach_remove_all(compose);
	syl_plugin_compose_attach_append(compose, zip_path, filename,
					 "application/zip");

	/* Send */
	get_rfc822_date(send_date, sizeof(send_date));
	ret = syl_plugin_compose_send(compose, TRUE);
	if (ret != 0) {
		g_free(zip_path);
		g_free(filename);
		g_free(password);
		g_free(orig_subject);
		g_free(orig_replyto);
		g_free(orig_bcc);
		g_free(orig_cc);
		g_free(orig_to);
		return;
	}

	/* Create password mail */
	subject = create_password_mail_subject(orig_subject, send_date, filename, password);
	body = create_password_mail_body(orig_subject, send_date, filename, password);
	debug_print("%s\n", body);

	compose = syl_plugin_compose_new(NULL, NULL, body, NULL);
	syl_plugin_compose_entry_set(compose, orig_to, 0);
	syl_plugin_compose_entry_set(compose, orig_cc, 1);
	if (orig_bcc && *orig_bcc != '\0')
		syl_plugin_compose_entry_set(compose, orig_bcc, 2);
	if (orig_replyto && *orig_replyto != '\0')
		syl_plugin_compose_entry_set(compose, orig_replyto, 3);
	syl_plugin_compose_entry_set(compose, subject, 4);

	/* Cleanup */
	g_free(body);
	g_free(subject);
	g_free(zip_path);
	g_free(filename);
	g_free(password);
	g_free(orig_subject);
	g_free(orig_replyto);
	g_free(orig_bcc);
	g_free(orig_cc);
	g_free(orig_to);
}
static void
ide_recent_projects_load_recent (IdeRecentProjects *self)
{
  g_autoptr(GBookmarkFile) projects_file = NULL;
  g_autoptr(GError) error = NULL;
  gboolean needs_sync = FALSE;
  gchar **uris;

  g_assert (IDE_IS_RECENT_PROJECTS (self));

  if (!(projects_file = ide_recent_projects_get_bookmarks (self, &error)))
    {
      g_warning ("Unable to open recent projects file: %s", error->message);
      return;
    }

  uris = g_bookmark_file_get_uris (projects_file, NULL);

  for (gsize z = 0; uris[z]; z++)
    {
      g_autoptr(GDateTime) last_modified_at = NULL;
      g_autoptr(GFile) project_file = NULL;
      g_autoptr(GFile) directory = NULL;
      g_autoptr(GPtrArray) languages = NULL;
      g_autoptr(IdeProjectInfo) project_info = NULL;
      g_autofree gchar *name = NULL;
      g_autofree gchar *description = NULL;
      const gchar *build_system_hint = NULL;
      const gchar *build_system_name = NULL;
      const gchar *uri = uris[z];
      const gchar *diruri = NULL;
      time_t modified;
      g_auto(GStrv) groups = NULL;
      gsize len;

      groups = g_bookmark_file_get_groups (projects_file, uri, &len, NULL);

      for (gsize i = 0; i < len; i++)
        {
          if (g_str_equal (groups [i], IDE_RECENT_PROJECTS_GROUP))
            goto is_project;
        }

      continue;

    is_project:
      project_file = g_file_new_for_uri (uri);

      if (g_file_is_native (project_file) && !g_file_query_exists (project_file, NULL))
        {
          g_bookmark_file_remove_item (projects_file, uri, NULL);
          needs_sync = TRUE;
          continue;
        }

      name = g_bookmark_file_get_title (projects_file, uri, NULL);
      description = g_bookmark_file_get_description (projects_file, uri, NULL);
      modified = g_bookmark_file_get_modified  (projects_file, uri, NULL);
      last_modified_at = g_date_time_new_from_unix_local (modified);

      for (gsize i = 0; i < len; i++)
        {
          if (g_str_has_prefix (groups [i], IDE_RECENT_PROJECTS_DIRECTORY))
            diruri = groups [i] + strlen (IDE_RECENT_PROJECTS_DIRECTORY);
        }

      if (diruri == NULL)
        {
          /* If the old project was a plain-ol'-directory, then we don't want
           * it's parent (which might be ~/Projects), instead reuse the project
           * file as the directory too.
           */
          if (g_file_query_file_type (project_file, 0, NULL) == G_FILE_TYPE_DIRECTORY)
            directory = g_file_dup (project_file);
          else
            directory = g_file_get_parent (project_file);
        }
      else
        directory = g_file_new_for_uri (diruri);

      languages = g_ptr_array_new_with_free_func (g_free);
      for (gsize i = 0; i < len; i++)
        {
          if (g_str_has_prefix (groups [i], IDE_RECENT_PROJECTS_LANGUAGE_GROUP_PREFIX))
            g_ptr_array_add (languages, g_strdup (groups [i] + strlen (IDE_RECENT_PROJECTS_LANGUAGE_GROUP_PREFIX)));
          else if (g_str_has_prefix (groups [i], IDE_RECENT_PROJECTS_BUILD_SYSTEM_GROUP_PREFIX))
            build_system_name = groups [i] + strlen (IDE_RECENT_PROJECTS_BUILD_SYSTEM_GROUP_PREFIX);
          else if (g_str_has_prefix (groups [i], IDE_RECENT_PROJECTS_BUILD_SYSTEM_HINT_GROUP_PREFIX))
            build_system_hint = groups [i] + strlen (IDE_RECENT_PROJECTS_BUILD_SYSTEM_HINT_GROUP_PREFIX);
        }

      /* Cleanup any extra space */
      for (guint i = 0; i < languages->len; i++)
        g_strstrip ((gchar *)g_ptr_array_index (languages, i));
      g_ptr_array_add (languages, NULL);

      project_info = g_object_new (IDE_TYPE_PROJECT_INFO,
                                   "build-system-hint", build_system_hint,
                                   "build-system-name", build_system_name,
                                   "description", description,
                                   "directory", directory,
                                   "file", project_file,
                                   "is-recent", TRUE,
                                   "languages", (gchar **)languages->pdata,
                                   "last-modified-at", last_modified_at,
                                   "name", name,
                                   NULL);

      ide_recent_projects_added (self, project_info);

      g_hash_table_insert (self->recent_uris, g_strdup (uri), NULL);
    }

  g_strfreev (uris);

  if (needs_sync)
    g_bookmark_file_to_file (projects_file, self->file_uri, NULL);
}
gboolean
open_app_is_compatible_distribution (const gchar *distribution)
{
	GError *error;
	gchar *desc;
	gchar *release;
	gchar *output;
	gchar **infos;
	gchar *p;
	gint i;
	gboolean val;

	g_return_val_if_fail (distribution != NULL, TRUE);

	/*TODO: list all this ? */
	const gchar *special_types [] = {"Source", "Arch", "other", NULL};
	for (i = 0; special_types [i]; i++) {
		if (strcasestr (special_types [i], distribution)) {
			return TRUE;
		}
	}

	val = FALSE;
	desc = NULL;
	release = NULL;
	error = NULL;
	output = NULL;
	g_spawn_command_line_sync ("lsb-release -a",
			&output, NULL, NULL, &error);
	if (error) {
		g_debug ("Error in getting describution info %s.",
				error->message);
		g_error_free (error);
	} else {
		if (output) {
			infos = g_strsplit (output, "\n", -1);
			for (i = 0; infos [i]; i++) {
				p = strchr (infos [i], ':');
				if (!p)
					continue;
				if (strncmp (infos [i], "Description", strlen ("Description")) == 0) {
					desc = g_strstrip (g_strdup (p + 1));
				} else if (strncmp (infos [i], "Release", strlen ("Release")) == 0) {
					release = g_strstrip (g_strdup (p + 1));
				}
			}
			g_strfreev (infos);
			g_free (output);
		}
	}

	/*TODO: what about release? */
	if (strcasestr (desc, distribution)) {
		val = TRUE;
	}

	if (desc)
		g_free (desc);
	if (release)
		g_free (release);

	return val;
}
Example #9
0
/**
 * pk_get_distro_id:
 *
 * Return value: the distro-id, typically "distro;version;arch"
 **/
gchar *
pk_get_distro_id (void)
{
	guint i;
	gboolean ret;
	gchar *contents = NULL;
	gchar *arch = NULL;
	gchar *version = NULL;
	gchar **split = NULL;
	gchar *distro = NULL;
	gchar *distro_id = NULL;

	/* The distro id property should have the
	   format "distro;version;arch" as this is
	   used to determine if a specific package
	   can be installed on a certain machine.
	   For instance, x86_64 packages cannot be
	   installed on a i386 machine.
	*/

	/* we can't get arch from /etc */
	arch = pk_get_distro_id_machine_type ();

	/* check for fedora */
	ret = g_file_get_contents ("/etc/fedora-release", &contents, NULL, NULL);
	if (ret) {
		/* Fedora release 8.92 (Rawhide) */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("fedora;%s;%s", split[2], arch);
		goto out;
	}

	/* check for suse */
	ret = g_file_get_contents ("/etc/SuSE-release", &contents, NULL, NULL);
	if (ret) {
		/* replace with spaces: openSUSE 11.0 (i586) Alpha3\nVERSION = 11.0 */
		g_strdelimit (contents, "()\n", ' ');

		/* openSUSE 11.0  i586  Alpha3 VERSION = 11.0 */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("suse;%s-%s;%s", split[1], split[3], arch);
		goto out;
	}

	/* check for meego */
	ret = g_file_get_contents ("/etc/meego-release", &contents, NULL, NULL);
	if (ret) {
		/* Meego release 1.0 (MeeGo) */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("meego;%s;%s", split[2], arch);
		goto out;
	}

	/* check for foresight or foresight derivatives */
	ret = g_file_get_contents ("/etc/distro-release", &contents, NULL, NULL);
	if (ret) {
		/* Foresight Linux 2 */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("foresight;%s;%s", split[2], arch);
		goto out;
	}

	/* check for PLD */
	ret = g_file_get_contents ("/etc/pld-release", &contents, NULL, NULL);
	if (ret) {
		/* 2.99 PLD Linux (Th) */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("pld;%s;%s", split[0], arch);
		goto out;
	}

	/* check for Arch */
	ret = g_file_test ("/etc/arch-release", G_FILE_TEST_EXISTS);
	if (ret) {
		/* complete! */
		distro_id = g_strdup_printf ("arch;current;%s", arch);
		goto out;
	}

	/* check for LSB */
	ret = g_file_get_contents ("/etc/lsb-release", &contents, NULL, NULL);
	if (ret) {
		/* split by lines */
		split = g_strsplit (contents, "\n", -1);
		for (i=0; split[i] != NULL; i++) {
			if (g_str_has_prefix (split[i], "DISTRIB_ID="))
				distro = g_ascii_strdown (&split[i][11], -1);
			if (g_str_has_prefix (split[i], "DISTRIB_RELEASE="))
				version = g_ascii_strdown (&split[i][16], -1);
		}

		/* complete! */
		distro_id = g_strdup_printf ("%s;%s;%s", distro, version, arch);
		goto out;
	}

	/* check for Debian or Debian derivatives */
	ret = g_file_get_contents ("/etc/debian_version", &contents, NULL, NULL);
	if (ret) {
		/* remove "\n": "squeeze/sid\n" */
		g_strdelimit (contents, "\n", '\0');
		/* removes leading and trailing whitespace */
		g_strstrip (contents);

		/* complete! */
		distro_id = g_strdup_printf ("debian;%s;%s", contents, arch);
		goto out;
	}

#ifdef __FreeBSD__
	ret = TRUE;
#endif
	/* FreeBSD */
	if (ret) {
		/* we can't get version from /etc */
		version = pk_get_distro_id_os_release ();
		if (version == NULL)
			goto out;

		/* 7.2-RELEASE */
		split = g_strsplit (version, "-", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("freebsd;%s;%s", split[0], arch);
		goto out;
	}
out:
	g_strfreev (split);
	g_free (version);
	g_free (distro);
	g_free (arch);
	g_free (contents);
	return distro_id;
}
Example #10
0
File: wtools.c Project: artzub/mc
/**
 * Show dialog, not background safe.
 *
 * If the arguments "header" and "text" should be translated,
 * that MUST be done by the caller of fg_input_dialog_help().
 *
 * The argument "history_name" holds the name of a section
 * in the history file. Data entered in the input field of
 * the dialog box will be stored there.
 *
 */
static char *
fg_input_dialog_help (const char *header, const char *text, const char *help,
                      const char *history_name, const char *def_text)
{
    char *my_str;

    QuickWidget quick_widgets[] = {
        /* 0 */ QUICK_BUTTON (6, 64, 1, 0, N_("&Cancel"), B_CANCEL, NULL),
        /* 1 */ QUICK_BUTTON (3, 64, 1, 0, N_("&OK"), B_ENTER, NULL),
        /* 2 */ QUICK_INPUT (3, 64, 0, 0, def_text, 58, 0, NULL, &my_str),
        /* 3 */ QUICK_LABEL (3, 64, 2, 0, ""),
        QUICK_END
    };

    int b0_len, b1_len, b_len, gap;
    char histname[64] = "inp|";
    int lines, cols;
    int len;
    int i;
    char *p_text;
    int ret;

    /* buttons */
#ifdef ENABLE_NLS
    quick_widgets[0].u.button.text = _(quick_widgets[0].u.button.text);
    quick_widgets[1].u.button.text = _(quick_widgets[1].u.button.text);
#endif /* ENABLE_NLS */

    b0_len = str_term_width1 (quick_widgets[0].u.button.text) + 3;
    b1_len = str_term_width1 (quick_widgets[1].u.button.text) + 5;      /* default button */
    b_len = b0_len + b1_len + 2;        /* including gap */

    /* input line */
    if (history_name != NULL && *history_name != '\0')
    {
        g_strlcpy (histname + 3, history_name, sizeof (histname) - 3);
        quick_widgets[2].u.input.histname = histname;
    }

    /* The special value of def_text is used to identify password boxes
       and hide characters with "*".  Don't save passwords in history! */
    if (def_text == INPUT_PASSWORD)
    {
        quick_widgets[2].u.input.flags = 1;
        histname[3] = '\0';
        quick_widgets[2].u.input.text = "";
    }

    /* text */
    p_text = g_strstrip (g_strdup (text));
    str_msg_term_size (p_text, &lines, &cols);
    quick_widgets[3].u.label.text = p_text;

    /* dialog width */
    len = str_term_width1 (header);
    len = max (max (len, cols) + 4, 64);
    len = min (max (len, b_len + 6), COLS);

    /* button locations */
    gap = (len - 8 - b_len) / 3;
    quick_widgets[1].relative_x = 3 + gap;
    quick_widgets[0].relative_x = quick_widgets[1].relative_x + b1_len + gap + 2;

    {
        QuickDialog Quick_input = {
            len, lines + 6, -1, -1, header,
            help, quick_widgets, NULL, TRUE
        };

        for (i = 0; i < 4; i++)
        {
            quick_widgets[i].x_divisions = Quick_input.xlen;
            quick_widgets[i].y_divisions = Quick_input.ylen;
        }

        for (i = 0; i < 3; i++)
            quick_widgets[i].relative_y += 2 + lines;

        /* input line length */
        quick_widgets[2].u.input.len = Quick_input.xlen - 6;

        ret = quick_dialog (&Quick_input);
    }

    g_free (p_text);

    return (ret != B_CANCEL) ? my_str : NULL;
}
static gchar *get_winepath(const gchar *p_wine_path, const gchar *p_cwd, GHashTable *p_environ, const gchar *p_command)
{
	// Build argument vector
	static gchar *argv[] = { NULL, "winepath.exe", "-u", NULL, NULL };

	gchar *wine_cmd = g_strdup_printf("%s/wine", p_wine_path);
	argv[0] = wine_cmd;
    argv[3] = (gchar*)p_command;

#ifdef DEBUG_VERBOSE
	purple_debug_misc("gfire", "get_winepath: argv: \"%s %s %s '%s'\"\n", argv[0], argv[1], argv[2], argv[3]);
#endif // DEBUG_VERBOSE

	// Build environment vector
	gchar **env = (gchar**)g_malloc(sizeof(gchar*) * (g_hash_table_size(p_environ) + 1));

	GHashTableIter iter;
	g_hash_table_iter_init(&iter, p_environ);

	gchar *key, *value;
	gint pos = 0;
	while(g_hash_table_iter_next(&iter, (gpointer*)&key, (gpointer*)&value))
	{
		if(g_strcmp0(key, "WINESERVERSOCKET") != 0)
		{
			env[pos] = g_strdup_printf("%s=%s", key, value);
			pos++;
		}
	}
	env[pos] = NULL;

#ifdef DEBUG_VERBOSE
	gchar **cur = env;
	while(*cur != NULL)
	{
		purple_debug_misc("gfire", "get_winepath: env: %s\n", *cur);
		cur++;
	}
#endif // DEBUG_VERBOSE

	gchar *result = NULL;

#ifdef DEBUG_VERBOSE
	gchar *error = NULL;
	if(!g_spawn_sync(p_cwd, argv, env, 0, NULL, NULL, &result, &error, NULL, NULL))
#else
	if(!g_spawn_sync(p_cwd, argv, env, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, &result, NULL, NULL, NULL))
#endif // DEBUG_VERBOSE
	{
#ifdef DEBUG
		purple_debug_error("gfire", "get_winepath: g_spawn_sync() failed\n");
#endif // DEBUG
		g_strfreev(env);
		g_free(wine_cmd);
		return NULL;
	}

	g_strfreev(env);
	g_free(wine_cmd);

#ifdef DEBUG_VERBOSE
	purple_debug_misc("gfire", "get_winepath: Error: \"%s\"\n", error ? error : "NULL");
	purple_debug_misc("gfire", "get_winepath: Result: \"%s\"\n", result ? result : "NULL");
	g_free(error);
#endif // DEBUG_VERBOSE

	// Remove trailing spaces and return
	if(!result)
		return NULL;
	else
		return g_strstrip(result);
}
Example #12
0
static void
gst_gnome_vfs_src_received_headers_callback (gconstpointer in,
    gsize in_size, gpointer out, gsize out_size, gpointer callback_data)
{
  GList *i;
  gint icy_metaint;
  GstGnomeVFSSrc *src = GST_GNOME_VFS_SRC (callback_data);
  GnomeVFSModuleCallbackReceivedHeadersIn *in_args =
      (GnomeVFSModuleCallbackReceivedHeadersIn *) in;

  /* This is only used for internet radio stuff right now */
  if (!src->iradio_mode)
    return;

  GST_DEBUG_OBJECT (src, "receiving internet radio metadata\n");

  /* FIXME: Could we use "Accept-Ranges: bytes"
   * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.5
   * to enable pull-mode?
   */

  for (i = in_args->headers; i; i = i->next) {
    char *data = (char *) i->data;
    char *value = strchr (data, ':');
    char *key;

    if (!value)
      continue;

    value++;
    g_strstrip (value);
    if (!strlen (value))
      continue;

    GST_LOG_OBJECT (src, "data %s", data);

    /* Icecast stuff */
    if (strncmp (data, "icy-metaint:", 12) == 0) {      /* ugh */
      if (sscanf (data + 12, "%d", &icy_metaint) == 1) {
        if (icy_metaint > 0) {
          GstCaps *icy_caps;

          icy_caps = gst_caps_new_simple ("application/x-icy",
              "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
          gst_pad_set_caps (GST_BASE_SRC_PAD (src), icy_caps);
          gst_caps_unref (icy_caps);
        }
      }
      continue;
    }

    if (!strncmp (data, "icy-", 4))
      key = data + 4;
    else
      continue;

    GST_DEBUG_OBJECT (src, "key: %s", key);
    if (!strncmp (key, "name", 4)) {
      g_free (src->iradio_name);
      src->iradio_name = gst_gnome_vfs_src_unicodify (value);
      if (src->iradio_name)
        g_object_notify (G_OBJECT (src), "iradio-name");
    } else if (!strncmp (key, "genre", 5)) {
      g_free (src->iradio_genre);
      src->iradio_genre = gst_gnome_vfs_src_unicodify (value);
      if (src->iradio_genre)
        g_object_notify (G_OBJECT (src), "iradio-genre");
    } else if (!strncmp (key, "url", 3)) {
      g_free (src->iradio_url);
      src->iradio_url = gst_gnome_vfs_src_unicodify (value);
      if (src->iradio_url)
        g_object_notify (G_OBJECT (src), "iradio-url");
    }
  }
}
Example #13
0
static gboolean
ui_to_setting (CEPageIP4 *self)
{
	CEPageIP4Private *priv = CE_PAGE_IP4_GET_PRIVATE (self);
	GtkTreeModel *model;
	GtkTreeIter tree_iter;
	int int_method = IP4_METHOD_AUTO;
	const char *method;
	GArray *dns_servers = NULL;
	GSList *search_domains = NULL;
	GPtrArray *addresses = NULL;
	gboolean valid = FALSE, iter_valid;
	const char *text;
	gboolean ignore_auto_dns = FALSE;
	const char *dhcp_client_id = NULL;
	char **items = NULL, **iter;

	/* Method */
	if (gtk_combo_box_get_active_iter (priv->method, &tree_iter)) {
		gtk_tree_model_get (GTK_TREE_MODEL (priv->method_store), &tree_iter,
		                    METHOD_COL_NUM, &int_method, -1);
	}

	switch (int_method) {
	case IP4_METHOD_LINK_LOCAL:
		method = NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL;
		break;
	case IP4_METHOD_MANUAL:
		method = NM_SETTING_IP4_CONFIG_METHOD_MANUAL;
		break;
	case IP4_METHOD_SHARED:
		method = NM_SETTING_IP4_CONFIG_METHOD_SHARED;
		break;
	case IP4_METHOD_AUTO_ADDRESSES:
		ignore_auto_dns = TRUE;
		/* fall through */
	default:
		method = NM_SETTING_IP4_CONFIG_METHOD_AUTO;
		break;
	}

	/* IP addresses */
	model = gtk_tree_view_get_model (priv->addr_list);
	iter_valid = gtk_tree_model_get_iter_first (model, &tree_iter);

	addresses = g_ptr_array_sized_new (1);
	while (iter_valid) {
		char *item = NULL;
		struct in_addr tmp_addr, tmp_gateway = { 0 };
		GArray *addr;
		guint32 empty_val = 0, prefix;

		gtk_tree_model_get (model, &tree_iter, COL_ADDRESS, &item, -1);
		if (!item || !inet_aton (item, &tmp_addr)) {
			g_warning ("%s: IPv4 address '%s' missing or invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		gtk_tree_model_get (model, &tree_iter, COL_PREFIX, &item, -1);
		if (!item) {
			g_warning ("%s: IPv4 prefix '%s' missing!",
			           __func__, item ? item : "<none>");
			goto out;
		}

		if (!parse_netmask (item, &prefix)) {
			g_warning ("%s: IPv4 prefix '%s' invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		/* Gateway is optional... */
		gtk_tree_model_get (model, &tree_iter, COL_GATEWAY, &item, -1);
		if (item && !inet_aton (item, &tmp_gateway)) {
			g_warning ("%s: IPv4 gateway '%s' invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		addr = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 3);
		g_array_append_val (addr, tmp_addr.s_addr);
		g_array_append_val (addr, prefix);
		if (tmp_gateway.s_addr)
			g_array_append_val (addr, tmp_gateway.s_addr);
		else
			g_array_append_val (addr, empty_val);
		g_ptr_array_add (addresses, addr);

		iter_valid = gtk_tree_model_iter_next (model, &tree_iter);
	}

	/* Don't pass empty array to the setting */
	if (!addresses->len) {
		g_ptr_array_free (addresses, TRUE);
		addresses = NULL;
	}

	/* DNS servers */
	dns_servers = g_array_new (FALSE, FALSE, sizeof (guint));

	text = gtk_entry_get_text (GTK_ENTRY (priv->dns_servers));
	if (text && strlen (text)) {
		items = g_strsplit_set (text, ", ;:", 0);
		for (iter = items; *iter; iter++) {
			struct in_addr tmp_addr;
			char *stripped = g_strstrip (*iter);

			if (!strlen (stripped))
				continue;

			if (inet_pton (AF_INET, stripped, &tmp_addr))
				g_array_append_val (dns_servers, tmp_addr.s_addr);
			else {
				g_strfreev (items);
				goto out;
			}
		}
		g_strfreev (items);
	}

	/* Search domains */
	text = gtk_entry_get_text (GTK_ENTRY (priv->dns_searches));
	if (text && strlen (text)) {
		items = g_strsplit_set (text, ", ;:", 0);
		for (iter = items; *iter; iter++) {
			char *stripped = g_strstrip (*iter);

			if (strlen (stripped))
				search_domains = g_slist_prepend (search_domains, g_strdup (stripped));
		}

		if (items)
			g_strfreev (items);
	}

	search_domains = g_slist_reverse (search_domains);

	/* DHCP client ID */
	if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) {
		dhcp_client_id = gtk_entry_get_text (priv->dhcp_client_id);
		if (dhcp_client_id && !strlen (dhcp_client_id))
			dhcp_client_id = NULL;
	}

	/* Update setting */
	g_object_set (priv->setting,
				  NM_SETTING_IP4_CONFIG_METHOD, method,
				  NM_SETTING_IP4_CONFIG_ADDRESSES, addresses,
				  NM_SETTING_IP4_CONFIG_DNS, dns_servers,
				  NM_SETTING_IP4_CONFIG_DNS_SEARCH, search_domains,
				  NM_SETTING_IP4_CONFIG_IGNORE_AUTO_DNS, ignore_auto_dns,
				  NM_SETTING_IP4_CONFIG_DHCP_CLIENT_ID, dhcp_client_id,
				  NULL);
	valid = TRUE;

out:
	if (addresses) {
		g_ptr_array_foreach (addresses, (GFunc) free_one_addr, NULL);
		g_ptr_array_free (addresses, TRUE);
	}

	if (dns_servers)
		g_array_free (dns_servers, TRUE);

	g_slist_foreach (search_domains, (GFunc) g_free, NULL);
	g_slist_free (search_domains);

	return valid;
}
static gboolean
parse_lyric_file_without_check(LmplayerLyricWidgetDa *lyric, const gchar *filename)
{
	gchar buf[1024];
	gchar *pbuf;
	gint n;
	gboolean flag = FALSE;
	LmplayerLyricWidgetDaPrivate *priv = lyric->priv;

	FILE* fp = fopen(filename, "r");

	if(fp == NULL) return FALSE;

	n = 0;
	while(fgets(buf, 1024, fp))
	{
		g_strstrip(buf);
		if(strlen(buf) == 0 || buf[0] != '[')
			continue;

		if(g_utf8_validate(buf, -1, NULL))
			pbuf = g_strdup(buf);
		else 
			pbuf = g_convert(buf, -1, "utf-8", "gb18030", NULL, NULL, NULL);

		//title:
		if(strncmp(pbuf, "[ti:", 4) == 0)
		{
			pbuf[strlen(pbuf) - 1] = '\0';
			priv->title = (gchar*)g_strdup(&pbuf[4]);
			flag = TRUE;
			g_free(pbuf);
			continue;
		}

		//artist:
		if(strncmp(pbuf, "[ar:", 4) == 0)
		{
			pbuf[strlen(pbuf) - 1] = '\0';
			priv->artist = g_strdup(&pbuf[4]);
			flag = TRUE;
			g_free(pbuf);
			continue; 
		}

		//album:
		if(strncmp(pbuf, "[al:", 4) == 0)
		{
			pbuf[strlen(pbuf) - 1] = '\0';
			priv->album = g_strdup(&pbuf[4]);
			flag = TRUE;
			g_free(pbuf);
			continue;
		}

		//author
		if(strncmp(pbuf, "[by:", 4) == 0)
		{
			pbuf[strlen(pbuf) - 1] = '\0';
			priv->author = g_strdup(&pbuf[4]);
			flag = TRUE;
			g_free(pbuf);
			continue;
		}

		//offset:
		if(strncmp(pbuf, "[offset:", 8) == 0)
		{
			pbuf[strlen(pbuf) - 1] = '\0';
			priv->offset = atoi(&pbuf[8]);
			flag = TRUE;
			g_free(pbuf);
			continue;
		}

		flag = parse_lyric_line(lyric, pbuf, n);
		++n;
		g_free(pbuf);
	}

	fclose(fp);

	priv->lines = g_list_sort(priv->lines, (GCompareFunc)lyric_line_compare);
	update_xy_coordinate(lyric);

	return flag;
}
Example #15
0
static void Etag(struct Manifest *manifest, char *value)
{
  manifest->etag = g_strdup(g_strstrip(value));
}
static void
ide_source_snippet_parser_do_snippet (IdeSourceSnippetParser *parser,
                                      const gchar            *line)
{
  parser->cur_name = g_strstrip (g_strdup (&line[8]));
}
Example #17
0
void
read_xml_file (const gchar *xmlfilename, GdaEx *gdaex)
{
	xmlDoc *xdoc;
	xmlNode *xnode;

	gchar *filename;
	gchar *sql;
	GdaDataModel *dm;

	GError *error;

	xdoc = xmlParseFile (xmlfilename);
	if (xdoc == NULL)
		{
			g_error ("Unable to parse xml file «%s».", xmlfilename);
		}
	else
		{
			xnode = xmlDocGetRootElement (xdoc);
			if (xnode != NULL)
				{
					if (xmlStrcmp (xnode->name, "gdaex2gettext") != 0)
						{
							g_error ("Xml file not valid: «%s».", xmlfilename);
						}
					else
						{
							xnode = xnode->children;
							while (xnode)
								{
									if (xmlStrcmp (xnode->name, "file") == 0)
										{
											filename = g_strdup (xmlGetProp (xnode, "filename"));
											if (filename != NULL
												&& g_strcmp0 (g_strstrip (filename), "") != 0)
												{
													sql = g_strdup (xmlNodeGetContent (xnode));

													dm = gdaex_query (gdaex, g_strstrip (sql));
													xmlFree (sql);
													if (dm != NULL)
														{
															error = NULL;
															if (!gda_data_model_export_to_file (dm,
																								GDA_DATA_MODEL_IO_DATA_ARRAY_XML,
																								filename,
																								NULL, 0,
																								NULL, 0,
																								NULL,
																								&error)
																|| error != NULL)
																{
																	g_warning ("Error on data model export: %s.",
																			   error != NULL && error->message != NULL ? error->message : "no details");
																}
															g_object_unref (dm);
														}
												}
											if (filename != NULL)
												{
													g_free (filename);
												}
										}

									xnode = xnode->next;
								}
						}
				}
			else
				{
					g_error ("Xml file not valid: «%s».", xmlfilename);
				}
	}

	return;
}
static void
ide_source_snippet_parser_feed_line (IdeSourceSnippetParser *parser,
                                     gchar                  *basename,
                                     const gchar            *line)
{
  const gchar *orig = line;

  g_assert (parser);
  g_assert (basename);
  g_assert (line);

  parser->lineno++;

  switch (*line)
    {
    case '\0':
      if (parser->cur_name)
        g_string_append_c (parser->cur_text, '\n');
      break;

    case '#':
      break;

    case '\t':
      if (parser->cur_name)
        {
          GList *iter;
          gboolean add_default_scope = TRUE;
          for (iter = parser->scope; iter; iter = iter->next)
            {
              if (g_strcmp0(iter->data, basename) == 0)
                {
                  add_default_scope = FALSE;
                  break;
                }
            }

          if (add_default_scope)
            parser->scope = g_list_append(parser->scope,
                                        g_strstrip (g_strdup (basename)));

          if (parser->cur_text->len || parser->chunks)
            g_string_append_c (parser->cur_text, '\n');
          ide_source_snippet_parser_do_part (parser, line);
        }
      break;

    case 's':
      if (g_str_has_prefix (line, "snippet"))
        {
          ide_source_snippet_parser_finish (parser);
          ide_source_snippet_parser_do_snippet (parser, line);
          break;
        }

    /* Fall through */
    case '-':
      if (parser->cur_text->len || parser->chunks)
        {
          ide_source_snippet_parser_store(parser);

          g_string_truncate (parser->cur_text, 0);

          g_list_foreach (parser->chunks, (GFunc) g_object_unref, NULL);
          g_list_free (parser->chunks);
          parser->chunks = NULL;

          g_list_free_full(parser->scope, g_free);
          parser->scope = NULL;
        }

      if (g_str_has_prefix(line, "- scope"))
        {
          ide_source_snippet_parser_do_snippet_scope (parser, line);
          break;
        }

      if (g_str_has_prefix(line, "- desc"))
        {
          ide_source_snippet_parser_do_snippet_description (parser, line);
          break;
        }

    /* Fall through */
    default:
      g_warning (_("Invalid snippet at line %d: %s"), parser->lineno, line);
      break;
    }

  g_string_append (parser->snippet_text, orig);
  g_string_append_c (parser->snippet_text, '\n');
}
void matedialog_fileselection (MateDialogData *data, MateDialogFileData *file_data)
{
  GtkWidget *dialog;
  gchar *dir;
  gchar *basename;
  GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;

  zen_data = data;

  if (file_data->directory) {
    if (file_data->save)
      action = GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER;
    else
      action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
  } else {
    if (file_data->save)
      action = GTK_FILE_CHOOSER_ACTION_SAVE;
  }

  dialog = gtk_file_chooser_dialog_new (NULL, NULL,
		  			action,
					GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
					GTK_STOCK_OK, GTK_RESPONSE_OK,
					NULL);

  gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), 
                                                  file_data->confirm_overwrite);

  g_signal_connect (G_OBJECT (dialog), "response", 
                    G_CALLBACK (matedialog_fileselection_dialog_response), file_data);

  if (data->dialog_title)
    gtk_window_set_title (GTK_WINDOW (dialog), data->dialog_title);
	
  matedialog_util_set_window_icon (dialog, data->window_icon, MATEDIALOG_IMAGE_FULLPATH ("matedialog-file.png"));

  if (file_data->uri) {
    dir = g_path_get_dirname (file_data->uri);

    if (g_path_is_absolute (file_data->uri) == TRUE)
      gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), dir);

    if (file_data->uri[strlen (file_data->uri) - 1] != '/') {
      basename = g_path_get_basename (file_data->uri);
      if (file_data->save)
        gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), basename);
      else
        (void) gtk_file_chooser_set_filename (GTK_FILE_CHOOSER (dialog), file_data->uri);
      g_free (basename);
    }
    g_free (dir);
  }

  if (file_data->multi)
    gtk_file_chooser_set_select_multiple (GTK_FILE_CHOOSER (dialog), TRUE);

  if (file_data->filter) {
    /* Filter format: Executables | *.exe *.bat *.com */
    gint filter_i;

    for (filter_i = 0; file_data->filter [filter_i]; filter_i++) {
      GtkFileFilter *filter = gtk_file_filter_new();
      gchar *filter_str = file_data->filter [filter_i];
      gchar **pattern, **patterns;
      gchar *name = NULL;
      gint i;

      /* Set name */
      for (i = 0; filter_str[i] != '\0'; i++)
        if (filter_str[i] == '|')
          break;

      if (filter_str[i] == '|') {
        name = g_strndup (filter_str, i);
        g_strstrip (name);
      }

      if (name) {
        gtk_file_filter_set_name (filter, name);

        /* Point i to the right position for split */
        for (++i; filter_str[i] == ' '; i++);
      } else {
        gtk_file_filter_set_name (filter, filter_str);
        i = 0;
      }

      /* Get patterns */
      patterns = g_strsplit_set (filter_str + i, " ", -1);

      for (pattern = patterns; *pattern; pattern++)
        gtk_file_filter_add_pattern (filter, *pattern);

      if (name)
        g_free (name);

      g_strfreev (patterns);

      gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
    }
  }

  matedialog_util_show_dialog (dialog);

  if(data->timeout_delay > 0) {
    g_timeout_add_seconds (data->timeout_delay, (GSourceFunc) matedialog_util_timeout_handle, NULL);
  }

  gtk_main ();
}
Example #20
0
/**
 * Build an address list entry and append to list of address items in the
 * address cache. Name is formatted as "<first-name> <last-name>".
 * \param ldifFile LDIF import control object.
 * \param rec      LDIF field object.
 * \param cache    Address cache to be populated with data.
 */
static void ldif_build_items(
		LdifFile *ldifFile, Ldif_ParsedRec *rec, AddressCache *cache )
{
	GSList *nodeFirst;
	GSList *nodeAddress;
	GSList *nodeAttr;
	gchar *firstName = NULL, *lastName = NULL, *fullName = NULL;
	gchar *nickName = NULL;
	gint iLen = 0, iLenT = 0;
	ItemPerson *person;
	ItemEMail *email;

	nodeAddress = rec->listAddress;
//	if( nodeAddress == NULL ) return;

	/* Find longest first name in list */
	nodeFirst = rec->listFName;
	while( nodeFirst ) {
		if( firstName == NULL ) {
			firstName = nodeFirst->data;
			iLen = strlen( firstName );
		}
		else {
			if( ( iLenT = strlen( nodeFirst->data ) ) > iLen ) {
				firstName = nodeFirst->data;
				iLen = iLenT;
			}
		}
		nodeFirst = g_slist_next( nodeFirst );
	}

	/* Format name */
	if( rec->listLName ) {
		lastName = rec->listLName->data;
	}

	if( firstName ) {
		if( lastName ) {
			fullName = g_strdup_printf(
				"%s %s", firstName, lastName );
		}
		else {
			fullName = g_strdup_printf( "%s", firstName );
		}
	}
	else {
		if( lastName ) {
			fullName = g_strdup_printf( "%s", lastName );
		}
	}
	
	if (!fullName || strlen(fullName) == 0) {
		g_free(fullName);
		fullName = NULL;
		if (rec->listCName)
			fullName = g_strdup(rec->listCName->data);
	}
	
	if( fullName ) {
		g_strstrip( fullName );
	}

	if( rec->listNName ) {
		nickName = rec->listNName->data;
	}

	person = addritem_create_item_person();
	addritem_person_set_common_name( person, fullName );
	addritem_person_set_first_name( person, firstName );
	addritem_person_set_last_name( person, lastName );
	addritem_person_set_nick_name( person, nickName );
	addrcache_id_person( cache, person );
	addrcache_add_person( cache, person );
	++ldifFile->importCount;

	/* Add address item */
	while( nodeAddress ) {
		email = addritem_create_item_email();
		addritem_email_set_address( email, nodeAddress->data );
		addrcache_id_email( cache, email );
		addrcache_person_add_email( cache, person, email );
		nodeAddress = g_slist_next( nodeAddress );
	}
	g_free( fullName );
	fullName = firstName = lastName = NULL;

	/* Add user attributes */
	nodeAttr = rec->userAttr;
	while( nodeAttr ) {
		Ldif_UserAttr *attr = nodeAttr->data;
		UserAttribute *attrib = addritem_create_attribute();
		addritem_attrib_set_name( attrib, attr->name );
		addritem_attrib_set_value( attrib, attr->value );
		addritem_person_add_attribute( person, attrib );
		nodeAttr = g_slist_next( nodeAttr );
	}
	nodeAttr = NULL;
}
Example #21
0
int tgp_msg_send (struct tgl_state *TLS, const char *message, tgl_peer_id_t to) {

#ifndef __ADIUM_
  // search for outgoing embedded image tags and send them
  gchar *img = NULL;
  gchar *stripped = NULL;
  
  if ((img = g_strrstr (message, "<IMG")) || (img = g_strrstr (message, "<img"))) {
    if (tgl_get_peer_type(to) == TGL_PEER_ENCR_CHAT) {
      tgp_msg_err_out (TLS, _("Sorry, sending documents to encrypted chats not yet supported."), to);
      return 0;
    }
    debug ("img found: %s", img);
    gchar *id;
    if ((id = g_strrstr (img, "ID=\"")) || (id = g_strrstr (img, "id=\""))) {
      id += 4;
      int imgid = atoi (id);
      if (imgid > 0) {
        PurpleStoredImage *psi = purple_imgstore_find_by_id (imgid);
        if (! psi) {
          failure ("Img %d not found in imgstore", imgid);
          return -1;
        }
        gchar *tmp = g_build_filename (g_get_tmp_dir(), purple_imgstore_get_filename (psi), NULL) ;
        GError *err = NULL;
        gconstpointer data = purple_imgstore_get_data (psi);
        g_file_set_contents (tmp, data, purple_imgstore_get_size (psi), &err);
        if (! err) {
          stripped = g_strstrip(purple_markup_strip_html (message));
          tgl_do_send_document (TLS, to, tmp, stripped, (int)strlen (stripped),
                                TGL_SEND_MSG_FLAG_DOCUMENT_AUTO, send_inline_picture_done, NULL);
          g_free (stripped);
          
          // return 0 to assure that the picture is not echoed, since
          // it will already be echoed with the outgoing message
          return 0;
        } else {
          failure ("Storing %s in imagestore failed: %s\n", tmp, err->message);
          g_error_free (err);
          return -1;
        }
      }
    }
    // no image id found in image
    return -1;
  }
  
  /*
    Adium won't escape any HTML markup and just pass any user-input through,
    while Pidgin will replace special chars with the escape chars and also add 
    additional markup for RTL languages and such.

    First, we remove any HTML markup added by Pidgin, since Telegram won't handle it properly.
    User-entered HTML is still escaped and therefore won't be harmed.
   */
  stripped = purple_markup_strip_html (message);
  
   // now unescape the markup, so that html special chars will still show
   // up properly in Telegram
  gchar *unescaped = purple_unescape_text (stripped);
  int ret = tgp_msg_send_split (TLS, stripped, to);
  
  g_free (unescaped);
  g_free (stripped);
  return ret;
#endif
  
  // when the other peer receives a message it is obvious that the previous messages were read
  pending_reads_send_user (TLS, to);
  
  return tgp_msg_send_split (TLS, message, to);
}
Example #22
0
/**
 * Read tag names for file data.
 * \param  ldifFile LDIF import control object.
 */
static void ldif_read_tag_list( LdifFile *ldifFile ) {
	gchar *tagName = NULL;
	GSList *listTags = NULL;
	gboolean flagEOF = FALSE, flagEOR = FALSE, flagMail = FALSE;
	gboolean flag64 = FALSE;
	long posEnd = 0L;
	long posCur = 0L;

	/* Clear hash table */
	g_hash_table_foreach_remove(
		ldifFile->hashFields, ldif_hash_free_vis, NULL );

	/* Find EOF for progress indicator */
	fseek( ldifFile->file, 0L, SEEK_END );
	posEnd = ftell( ldifFile->file );
	fseek( ldifFile->file, 0L, SEEK_SET );

	if (posEnd == 0) {
		ldifFile->retVal = MGU_EOF;
		return;
	}
		
	/* Process file */
	while( ! flagEOF ) {
		gchar *line = ldif_get_line( ldifFile );
		posCur = ftell( ldifFile->file );
		if( ldifFile->cbProgress ) {
			/* Call progress indicator */
			( ldifFile->cbProgress ) ( ldifFile, & posEnd, & posCur );
		}

		flag64 = FALSE;
		if( line == NULL ) {
			flagEOF = flagEOR = TRUE;
		}
		else if( *line == '\0' ) {
			flagEOR = TRUE;
		}

		if( flagEOR ) {
			/* EOR, Output address data */
			/* Save field list to hash table */
			if( flagMail ) {
				ldif_hash_add_list(
					ldifFile->hashFields, listTags );
			}
			mgu_free_list( listTags );
			listTags = NULL;
			flagMail = FALSE;
		}
		if( line ) {
			flagEOR = FALSE;
			if( *line == ' ' ) {
				/* Continuation line */
			}
			else if( *line == '=' ) {
				/* Base-64 encoded continuation field */
			}
			else {
				/* Parse line */
				tagName = ldif_get_tagname( line, &flag64 );
				if( tagName ) {
					/* Add tag to list */
					listTags = g_slist_append( listTags, tagName );

					if( g_utf8_collate(
						tagName, LDIF_TAG_EMAIL ) == 0 )
					{
						flagMail = TRUE;
					}
				} else {
					g_strstrip(line);
					if (*line != '\0') {
						debug_print("ldif: bad format: '%s'\n", line);
						ldifFile->retVal = MGU_BAD_FORMAT;
					}
				}
			}
		}
		g_free( line );
	}

	/* Release data */
	mgu_free_list( listTags );
	listTags = NULL;
}
Example #23
0
static int tree_scan_file(tree_t *tree, char *name, char *filename)
{
  FILE *f;
  char buf[BUFSIZ];
  char *buf_dirname;
  tree_item_t *save_current;
  tree_object_t *obj;
  tree_scan_data_t d;
  int ret = 0;

  /* Retrieve cannonical file name */
  if ( (filename[0] == '.') && (filename[1] == G_DIR_SEPARATOR) )
    filename += 2;

  /* Open Tree definition file */
  debug("SCAN TREE FILE %s\n", filename);
  if ( (f = fopen(filename, "r")) == NULL )
    return -1;

  /* Save current node pointer */
  save_current = tree->current;

  /* Setup scan iterator */
  d.tree = tree;
  d.seq = NULL;
  d.loc.filename = filename;
  d.loc.lineno = 0;
  d.dirname = buf_dirname = g_path_get_dirname(filename);
  debug(">>>>> OPEN TREE FILE %s (dirname=%s)\n", d.loc.filename, d.dirname);

  /* Create new SEQuence object */
  obj = tree_object_new(TYPE_SEQ);
  tree->current = tree_item_new(name, NULL, tree, obj, &(d.loc));
  tree_add(tree, tree->current);
  d.seq = obj->d.Seq;

  /* If no sequence was defined before, assume it is the tree Tree Root  */
  if ( tree->head == NULL )
    tree->head = tree->current;

  /* Parse tree file */
  while ( ! feof(f) ) {
    if ( fgets(buf, BUFSIZ, f) != NULL ) {
      char *str = g_strstrip(buf);

      d.loc.lineno++;

      if ( *str != '\0' )
        tree_scan_line(&d, str);
    }
  }

  free(buf_dirname);
  fclose(f);
  debug("<<<<< CLOSE TREE FILE %s\n", d.loc.filename);

  /* Check branch emptyness */
  if ( d.seq->nodes == NULL ) {
    tree_warning(d.tree, &(d.loc), "SEQ '%s' ignored: branch file is empty", name);
    tree_remove(tree, tree->current);
    tree_item_destroy(tree->current);
    tree_object_destroy(obj);
    ret = -1;
  }

  /* Restore current node pointer */
  tree->current = save_current;

  return ret;
}
Example #24
0
/* test manifest version */
static void Version(struct Manifest *manifest, char *value)
{
  ZLOGFAIL(g_strcmp0(MANIFEST_VERSION, g_strstrip(value)) != 0,
      EFAULT, "invalid manifest version");
}
Example #25
0
/* Return values:
 *
 * -2:    timeout
 * -1:    read error or response not found
 * 0...N: response index in **needles array
 */
static int
modem_wait_reply (int fd,
                  guint32 timeout_secs,
                  const char **needles,
                  const char **terminators,
                  int *out_terminator,
                  char **out_response)
{
	char buf[SERIAL_BUF_SIZE + 1];
	int reply_index = -1, bytes_read;
	GString *result = g_string_sized_new (RESPONSE_LINE_MAX * 2);
	time_t end;
	const char *response = NULL;
	gboolean done = FALSE;

	*out_terminator = -1;
	end = time (NULL) + timeout_secs;
	do {
		bytes_read = read (fd, buf, SERIAL_BUF_SIZE);
		if (bytes_read < 0 && errno != EAGAIN) {
			g_string_free (result, TRUE);
			g_printerr ("read error: %d\n", errno);
			return -1;
		}

		if (bytes_read == 0)
			break; /* EOF */
		else if (bytes_read > 0) {
			char **lines, **iter, *tmp;

			buf[bytes_read] = 0;
			g_string_append (result, buf);

			verbose ("Got: '%s'", result->str);

			lines = g_strsplit_set (result->str, "\n\r", 0);

			/* Find response terminators */
			for (iter = lines; *iter && !done; iter++) {
				tmp = g_strstrip (*iter);
				if (tmp && strlen (tmp)) {
					*out_terminator = find_terminator (tmp, terminators);
					if (*out_terminator >= 0)
						done = TRUE;
				}
			}

			/* If the terminator is found, look for expected responses */
			if (done) {
				for (iter = lines; *iter && (reply_index < 0); iter++) {
					tmp = g_strstrip (*iter);
					if (tmp && strlen (tmp)) {
						response = find_response (tmp, needles, &reply_index);
						if (response) {
							g_free (*out_response);
							*out_response = g_strdup (response);
						}
					}
				}
			}
			g_strfreev (lines);
		}

		if (!done)
			g_usleep (1000);
	} while (!done && (time (NULL) < end) && (result->len <= SERIAL_BUF_SIZE));

	/* Handle timeout */
	if (*out_terminator < 0 && !*out_response)
		reply_index = -2;

	g_string_free (result, TRUE);
	return reply_index;
}
Example #26
0
/* set program field (should be g_free later) */
static void Program(struct Manifest *manifest, char *value)
{
  manifest->program = g_strdup(g_strstrip(value));
}
Example #27
0
void ControllerServer::process_command( gpointer connection, ConnectionInfo & info, gchar ** parts , bool * read_again )
{
    guint count = g_strv_length( parts );

    if ( count < 1 )
    {
        return;
    }

    const gchar * cmd = parts[0];

    if ( strlen( cmd ) < 2 )
    {
        return;
    }

    if ( cmp2( cmd, "ID" ) )
    {
        // Device id line
        // ID <version> <name> <cap>*

        * read_again = false;

        // Not enough parts

        if ( count < 3 )
        {
            return;
        }

        // Already have a version

        if ( info.version )
        {
            return;
        }


        info.version = atoi( parts[1] );

        if ( !info.version )
        {
            return;
        }

        if ( info.version < 2 )
        {
            g_warning( "CONTROLLER DOES NOT SUPPORT PROTOCOL VERSION >= 2" );
            info.version = 0;
            return;
        }

        if ( info.version < 3 )
        {
            g_warning( "CONTROLLER DOES NOT SUPPORT PROTOCOL VERSION >= 3" );
            info.version = 0;
            return;
        }

        if ( info.version < 4 )
        {
            g_warning( "CONTROLLER DOES NOT SUPPORT PROTOCOL VERSION >= 4" );
            info.version = 0;
            return;
        }

        const char * name = g_strstrip( parts[2] );

        // Capability entries

        TPControllerSpec spec;

        memset( &spec, 0, sizeof( spec ) );

        for ( guint i = 3; i < count; ++i )
        {
            const gchar * cap = g_strstrip( parts[i] );

            size_t len = strlen( cap );

            if ( len == 2 )
            {
                if ( cmp2( cap, "KY" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_KEYS;
                }
                else if ( cmp2( cap, "AX" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_ACCELEROMETER;
                }
                else if ( cmp2( cap, "FM" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_FULL_MOTION;
                }
                else if ( cmp2( cap, "PT" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_POINTER;
                }
                else if ( cmp2( cap, "CK" ) )
                {
                    // Deprecated
                    // spec.capabilities |= TP_CONTROLLER_HAS_CLICKS;
                }
                else if ( cmp2( cap, "TC" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_TOUCHES;
                }
                else if ( cmp2( cap, "MC" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_MULTIPLE_CHOICE;
                }
                else if ( cmp2( cap, "SD" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_SOUND;
                }
                else if ( cmp2( cap, "UI" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_UI;
                }
                else if ( cmp2( cap, "TE" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_TEXT_ENTRY;
                }
                else if ( cmp2( cap, "PS" ) )
				{
					spec.capabilities |= TP_CONTROLLER_HAS_IMAGES;
				}
                else if ( cmp2( cap, "AC" ) )
				{
					spec.capabilities |= TP_CONTROLLER_HAS_AUDIO_CLIPS;
				}
                else if ( cmp2( cap , "UX" ) )
                {
                    spec.capabilities |= TP_CONTROLLER_HAS_ADVANCED_UI;
                }
                else if ( cmp2( cap , "VR" ) )
                {
                	spec.capabilities |= TP_CONTROLLER_HAS_VIRTUAL_REMOTE;
                }
                else if ( cmp2( cap , "SV" ) )
                {
                	spec.capabilities |= TP_CONTROLLER_HAS_STREAMING_VIDEO;
                }
                else
                {
                    g_warning( "UNKNOWN CONTROLLER CAPABILITY '%s'", cap );
                }
            }
            else if ( len > 3 )
            {
                if ( cmp2( cap, "IS" ) )
                {
                    sscanf( cap, "IS=%ux%u", &spec.input_width, &spec.input_height );
                }
                else if ( cmp2( cap, "US" ) )
                {
                    sscanf( cap, "US=%ux%u", &spec.ui_width, &spec.ui_height );
                }
                else if ( cmp2( cap , "ID" ) )
                {
                	spec.id = cap + 3;
                }
                else
                {
                    g_warning( "UNKNOWN CONTROLLER CAPABILITY '%s'", cap );
                }
            }
        }

        * read_again = true;

        spec.execute_command = execute_command;

        info.controller = tp_context_add_controller( context, name, &spec, this );

        server->write_printf( connection , "WM\t%s\t%u\t%lu\n" , CONTROLLER_PROTOCOL_VERSION , context->get_http_server()->get_port() , info.aui_id );
    }
    else if ( cmp2( cmd, "KP" ) )
    {
        // Key press
        // KP <hex key code> <hex unicode>

        if ( count < 2 || !info.controller )
        {
            return;
        }

        unsigned int key_code = 0;
        unsigned long int unicode = 0;

        sscanf( parts[1], "%x", &key_code );

        if ( count > 2 )
        {
            sscanf( parts[2], "%lx", &unicode );
        }

        tp_controller_key_down( info.controller, key_code, unicode , TP_CONTROLLER_MODIFIER_NONE );
        tp_controller_key_up( info.controller, key_code, unicode , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "KD" ) )
    {
        // Key down
        // KD <hex key code> <hex unicode>

        if ( count < 2 || !info.controller )
        {
            return;
        }

        unsigned int key_code = 0;
        unsigned long int unicode = 0;

        sscanf( parts[1], "%x", &key_code );

        if ( count > 2 )
        {
            sscanf( parts[2], "%lx", &unicode );
        }

        tp_controller_key_down( info.controller, key_code, unicode , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "KU" ) )
    {
        // Key up
        // KU <hex key code> <hex unicode>

        if ( count < 2 || !info.controller )
        {
            return;
        }

        unsigned int key_code = 0;
        unsigned long int unicode = 0;

        sscanf( parts[1], "%x", &key_code );

        if ( count > 2 )
        {
            sscanf( parts[2], "%lx", &unicode );
        }

        tp_controller_key_up( info.controller, key_code, unicode , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "CK" ) )
    {
        // Click
        // CK <x> <y>

        // deprecated

        return;
    }
    else if ( cmp2( cmd, "AX" ) )
    {
        // Acelerometer
        // AX <x> <y> <z>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_accelerometer( info.controller, atof( parts[1] ), atof( parts[2] ), atof( parts[3] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "GY" ) )
    {
        // Acelerometer
        // AX <x> <y> <z>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_gyroscope( info.controller, atof( parts[1] ), atof( parts[2] ), atof( parts[3] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "MM" ) )
    {
        // Acelerometer
        // AX <x> <y> <z>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_magnetometer( info.controller, atof( parts[1] ), atof( parts[2] ), atof( parts[3] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "AT" ) )
    {
        // Acelerometer
        // AX <x> <y> <z>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_attitude( info.controller, atof( parts[1] ), atof( parts[2] ), atof( parts[3] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "UI" ) )
    {
        // UI
        // UI <type> <txt>

        if ( count < 2 || !info.controller || strlen(parts[1]) != 2)
        {
            return;
        }

        // Enter text or multiple-choice
        if(cmp2( parts[1], "ET") || cmp2( parts[1], "MC"))
        {
            if(count < 3)
            {
                return;
            }
            tp_controller_ui_event( info.controller, parts[2] );
        }
        // Advanced UI event
        else if (cmp2( parts[1] , "UX" ) )
        {
        	if ( count < 3 )
        	{
        		return;
        	}
        	tp_controller_advanced_ui_event( info.controller , parts[ 2 ] );
        }
        // Cancel image
        else if(cmp2( parts[1], "CI"))
        {
            tp_controller_cancel_image( info.controller );
        }
        // Cancel audio
        else if(cmp2( parts[1], "CA"))
        {
            tp_controller_cancel_audio_clip( info.controller );
        }
    }
    else if ( cmp2( cmd, "PD" ) )
    {
        // Pointer button down
        // PD <button> <x> <y>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_pointer_button_down( info.controller, atoi( parts[1] ), atoi( parts[2] ) , atoi( parts[ 3 ] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "PM" ) )
    {
        // Pointer move
        // PM <x> <y>

        if ( count < 3 || !info.controller )
        {
            return;
        }

        tp_controller_pointer_move( info.controller, atoi( parts[1] ), atoi( parts[2] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "PU" ) )
    {
        // Pointer button up
        // PU <button> <x> <y>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_pointer_button_up( info.controller, atoi( parts[1] ), atoi( parts[2] ) , atoi( parts[ 3 ] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "TD" ) )
    {
        // Touch down
        // TD <finger> <x> <y>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_touch_down( info.controller, atoi( parts[1] ), atoi( parts[2] ) , atoi( parts[ 3 ] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "TM" ) )
    {
        // Touch move
        // TM <finger> <x> <y>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_touch_move( info.controller, atoi( parts[1] ), atoi( parts[2] ) , atoi( parts[ 3 ] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd, "TU" ) )
    {
        // Touch up
        // TU <finger> <x> <y>

        if ( count < 4 || !info.controller )
        {
            return;
        }

        tp_controller_touch_up( info.controller, atoi( parts[1] ), atoi( parts[2] ) , atoi( parts[ 3 ] ) , TP_CONTROLLER_MODIFIER_NONE );
    }
    else if ( cmp2( cmd , "UX" ) )
    {
        // Stop reading from this connection. We will only read
        // synchronously after we write. If there is a problem with the UX message,
        // we stop reading anyway - they only get one shot at it.

        * read_again = false;

        if ( count < 2 )
        {
            return;
        }

        gulong id = 0;

        if ( sscanf( parts[1], "%lu", & id ) != 1 )
        {
            return;
        }

        // The ID is bad

        if ( id == 0 )
        {
            return;
        }

        ConnectionInfo * parent_info = 0;

        for ( ConnectionMap::iterator it = connections.begin(); it != connections.end(); ++it )
        {
            if ( it->second.aui_id == id )
            {
                parent_info = & it->second;
                break;
            }
        }

        // Could not find a connection for this ID

        if ( ! parent_info )
        {
            return;
        }

        // The controller connection for this ID has not identified itself yet

        if ( ! parent_info->version )
        {
            return;
        }

        // OK, everything is cool

        // Set this connection's version, so it does not get booted.

        info.version = parent_info->version;

        // Tell the parent that this connection belongs to it

        parent_info->aui_connection = connection;

        // Now, generate the event that it is ready

        tp_controller_advanced_ui_ready( parent_info->controller );
    }
    else if ( cmp4( cmd, "SVCC" ) )
    {
        // Streaming video call connected
        // SVCC <address>

        if ( count < 2 || !info.controller )
        {
            return;
        }

        tp_controller_streaming_video_connected( info.controller, parts[1] );
    }
    else if ( cmp4( cmd, "SVCF" ) )
    {
        // Streaming video call failed
        // SVCF <address> <reason>

        if ( count < 3 || !info.controller )
        {
            return;
        }

        tp_controller_streaming_video_failed( info.controller, parts[1], parts[2] );
    }
    else if ( cmp4( cmd, "SVCD" ) )
    {
        // Streaming video call was dropped
        // SVCD <address> <reason>

        if ( count < 3 || !info.controller )
        {
            return;
        }

        tp_controller_streaming_video_dropped( info.controller, parts[1], parts[2] );
    }
    else if ( cmp4( cmd, "SVCE" ) )
    {
        // Streaming video call ended
        // SVCE <address> <who>

        if ( count < 3 || !info.controller )
        {
            return;
        }

        tp_controller_streaming_video_ended( info.controller, parts[1], parts[2] );
    }
    else if ( cmp4( cmd, "SVCS" ) )
    {
        // Streaming video call status
        // SVCS <status> <address>

        if ( count < 3 || !info.controller )
        {
            return;
        }

        tp_controller_streaming_video_status( info.controller, parts[1], parts[2] );
    }
    else
    {
        g_warning( "UNKNOWN CONTROLLER COMMAND '%s'", cmd );
    }
}
Example #28
0
static void Job(struct Manifest *manifest, char *value)
{
  ZLOGFAIL(strlen(value) > UNIX_PATH_MAX, EFAULT, "too long Job name");
  manifest->job = g_strdup(g_strstrip(value));
}
Example #29
0
/*
 * env tree view value changed handler 
 */
static void on_value_changed(GtkCellRendererText *renderer, gchar *path, gchar *new_text, gpointer user_data)
{
	gchar *striped;
	GtkTreeIter  iter;
	GtkTreePath *tree_path = gtk_tree_path_new_from_string (path);
	GtkTreePath *empty_path = gtk_tree_row_reference_get_path(empty_row);
	gboolean empty = !gtk_tree_path_compare(tree_path, empty_path);
	gtk_tree_path_free(empty_path);

	gtk_tree_model_get_iter (
		 model,
		 &iter,
		 tree_path);
	
	striped = g_strstrip(g_strdup(new_text));
	if (!strlen(striped))
	{
		/* if new value is empty string, if it's a new row - do nothig
		 otheerwise - offer to delete a variable */
		if (empty)
			gtk_list_store_set(store, &iter, NAME, "", -1);
		else
		{
			if (dialogs_show_question(_("Delete variable?")))
			{
				delete_selected_rows();
				config_set_debug_changed();

				gtk_widget_grab_focus(tree);
			}
		}
	}
	else
	{
		/* if old variable - change value, otherwise - add another empty row below */
		gchar* oldvalue;
		gtk_tree_model_get (
			model,
			&iter,
			VALUE, &oldvalue,
		   -1);

		if (strcmp(oldvalue, striped))
		{
			gtk_list_store_set(store, &iter, VALUE, striped, -1);
			if (empty)
				add_empty_row();
			
			g_object_set (renderer_value, "editable", FALSE, NULL);
			config_set_debug_changed();
		}
		
		g_free(oldvalue);
	}
	
	if (empty)
		entering_new_var = FALSE;

	gtk_tree_path_free(tree_path);
	g_free(striped);

	gtk_tree_path_free(being_edited_value);
	being_edited_value = NULL;
}
Example #30
0
/* FIXME: check format of fields. */
static gboolean
process_header (CamelMedium *medium,
                const gchar *name,
                const gchar *value)
{
	CamelHeaderType header_type;
	CamelMimeMessage *message = CAMEL_MIME_MESSAGE (medium);
	CamelInternetAddress *addr;
	const gchar *charset;
	gchar *unfolded;

	header_type = (CamelHeaderType) g_hash_table_lookup (header_name_table, name);
	switch (header_type) {
	case HEADER_FROM:
		addr = camel_internet_address_new ();
		unfolded = camel_header_unfold (value);
		if (camel_address_decode ((CamelAddress *) addr, unfolded) <= 0) {
			g_object_unref (addr);
		} else {
			if (message->from)
				g_object_unref (message->from);
			message->from = addr;
		}
		g_free (unfolded);
		break;
	case HEADER_REPLY_TO:
		addr = camel_internet_address_new ();
		unfolded = camel_header_unfold (value);
		if (camel_address_decode ((CamelAddress *) addr, unfolded) <= 0) {
			g_object_unref (addr);
		} else {
			if (message->reply_to)
				g_object_unref (message->reply_to);
			message->reply_to = addr;
		}
		g_free (unfolded);
		break;
	case HEADER_SUBJECT:
		g_free (message->subject);
		if (((CamelDataWrapper *) message)->mime_type) {
			charset = camel_content_type_param (((CamelDataWrapper *) message)->mime_type, "charset");
			charset = camel_iconv_charset_name (charset);
		} else
			charset = NULL;

		unfolded = camel_header_unfold (value);
		message->subject = g_strstrip (camel_header_decode_string (unfolded, charset));
		g_free (unfolded);
		break;
	case HEADER_TO:
	case HEADER_CC:
	case HEADER_BCC:
	case HEADER_RESENT_TO:
	case HEADER_RESENT_CC:
	case HEADER_RESENT_BCC:
		addr = g_hash_table_lookup (message->recipients, name);
		if (value) {
			unfolded = camel_header_unfold (value);
			camel_address_decode (CAMEL_ADDRESS (addr), unfolded);
			g_free (unfolded);
		} else {
			camel_address_remove (CAMEL_ADDRESS (addr), -1);
		}
		return FALSE;
	case HEADER_DATE:
		if (value) {
			message->date = camel_header_decode_date (value, &message->date_offset);
		} else {
			message->date = CAMEL_MESSAGE_DATE_CURRENT;
			message->date_offset = 0;
		}
		break;
	case HEADER_MESSAGE_ID:
		g_free (message->message_id);
		if (value)
			message->message_id = camel_header_msgid_decode (value);
		else
			message->message_id = NULL;
		break;
	default:
		return FALSE;
	}

	return TRUE;
}