Exemplo n.º 1
0
static char *
decode_estring (unsigned char **in, unsigned char *inend, GError **err)
{
	unsigned char *inptr, *start;
	char *qstring = NULL;

	inptr = *in;

	while (inptr < inend && *inptr == ' ')
		inptr++;

	if (inptr == inend) {
		*in = inptr;
		set_error (err, in);
		return NULL;
	}

	if (strncmp ((const char *) inptr, "NIL", 3) != 0) {
		if (*inptr == '(') {
			gboolean first = TRUE;
			GString *str = NULL;

			if (*inptr != '(') {
				*in = inptr;
				set_error (err, in);
				return NULL;
			}

			str = g_string_new ("");

			inptr++; /* My '(' */
			while (*inptr == '(') {
				char *separator = NULL;
				char *name = NULL;
				char *user = NULL;
				char *server = NULL;

				inptr++; /* My '(' */

				if (!first)
					g_string_append (str, ", ");
				first = FALSE;

				name = decode_qstring (&inptr, inend, err);
				separator = decode_qstring (&inptr, inend, err);
				user = decode_qstring (&inptr, inend, err);
				server = decode_qstring (&inptr, inend, err);

				if (name) {
					g_string_append (str, name);
					g_string_append (str, " <");
				}

				if (user && server) {
					g_string_append (str, user);
					g_string_append_c (str, '@');
				}

				if (server)
					g_string_append (str, server);

				if (name) 
					g_string_append_c (str, '>');

				if (separator)
					g_free (separator);
				if (name)
					g_free (name);
				if (user)
					g_free (user);
				if (server)
					g_free (server);


				if (*inptr != ')') {
					*in = inptr;
					set_error (err, in);
					g_string_free (str, TRUE);
					return NULL;
				}

				inptr++; /* My ')' */

				/* Read spaces */
				while (inptr < inend && *inptr == ' ')
					inptr++;

			}

			/* TODO: check for ')' */
			if (*inptr != ')')
				g_warning ("strange");
			inptr++; /* My ')' */

			qstring = str->str;
			g_string_free (str, FALSE);
		} else {
			if (strncmp ((const char *) inptr, "NIL", 3) != 0) {
				if (*inptr != '"') {
					*in = inptr;
					set_error (err, in);
					return NULL;
				}
				inptr++;
				start = inptr;
				while (inptr < inend) {
					if (*inptr == '"' && inptr[-1] != '\\')
						break;
					inptr++;
				}
				
				qstring = g_strndup ((const char *) start, inptr - start);
				unescape_qstring (qstring);

				if (*inptr != '"') {
					*in = inptr;
					g_free (qstring);
					set_error (err, in);
					return NULL;
				}
				inptr++;
			} else
				inptr += 3;
		}

	} else
		inptr += 3;

	*in = inptr;

	return qstring;
}
Exemplo n.º 2
0
/*
 * @node must be a <command> tag
 */
static gchar *
help_xml_doc_to_string_single_command (xmlNodePtr node, gint width, gboolean color_term)
{
	g_assert (!strcmp ((gchar*) node->name, "command"));

	/* create output string */
	GString *string;
	string = g_string_new ("");
	for (node = node->children; node; node = node->next) {
		xmlChar *data = NULL;
		if (!strcmp ((gchar*) node->name, "shortdescription")) {
			data = xmlNodeGetContent (node);
			if (data) {
				append_to_string (string, (gchar*) data, width, 0);
				g_string_append (string, "\n");
			}
		}
		else if (!strcmp ((gchar*) node->name, "usage") || !strcmp ((gchar*) node->name, "example")) {
			if (!strcmp ((gchar*) node->name, "usage"))
				append_to_string (string, _("Usage"), width, 0);
			else
				append_to_string (string, _("Example"), width, 0);
			g_string_append (string, ":\n");
			xmlNodePtr snode;
			for (snode = node->children; snode; snode = snode->next) {
				if (!strcmp ((gchar*) snode->name, "synopsis")) {
					data = xmlNodeGetContent (snode);
					if (data) {
						append_to_string (string, "> ", width, 3);
						gchar *tmp;
						tmp = g_strdup_printf ("%s%s%s",
								       base_tool_output_color_s (BASE_TOOL_COLOR_BOLD, color_term),
								       data,
								       base_tool_output_color_s (BASE_TOOL_COLOR_RESET, color_term));
						append_to_string (string, tmp, width, 3);
						g_free (tmp);
						g_string_append_c (string, '\n');
					}
				}
				else if (!strcmp ((gchar*) snode->name, "comment")) {
					data = xmlNodeGetContent (snode);
					if (data) {
						append_to_string (string, (gchar*) data, width, 6);
						g_string_append_c (string, '\n');
					}
				}
				else if (!strcmp ((gchar*) snode->name, "raw")) {
					data = xmlNodeGetContent (snode);
					if (data) {
						append_raw_to_string (string, (gchar*) data, width, 6);
						g_string_append (string, "\n\n");
					}
				}
				if (data)
					xmlFree (data);
				data = NULL;
			}
		}
		if (data)
			xmlFree (data);
	}

	return g_string_free (string, FALSE);
}
Exemplo n.º 3
0
/* let the user select its preferred completion */
void
editcmd_dialog_completion_show (WEdit * edit, int max_len, int word_len,
                                struct selection *compl, int num_compl)
{

    int start_x, start_y, offset, i;
    char *curr = NULL;
    Dlg_head *compl_dlg;
    WListbox *compl_list;
    int compl_dlg_h;            /* completion dialog height */
    int compl_dlg_w;            /* completion dialog width */

    /* calculate the dialog metrics */
    compl_dlg_h = num_compl + 2;
    compl_dlg_w = max_len + 4;
    start_x = edit->curs_col + edit->start_col - (compl_dlg_w / 2) +
              EDIT_TEXT_HORIZONTAL_OFFSET + option_line_state_width;
    start_y = edit->curs_row + EDIT_TEXT_VERTICAL_OFFSET + 1;

    if (start_x < 0)
        start_x = 0;
    if (compl_dlg_w > COLS)
        compl_dlg_w = COLS;
    if (compl_dlg_h > LINES - 2)
        compl_dlg_h = LINES - 2;

    offset = start_x + compl_dlg_w - COLS;
    if (offset > 0)
        start_x -= offset;
    offset = start_y + compl_dlg_h - LINES;
    if (offset > 0)
        start_y -= (offset + 1);

    /* create the dialog */
    compl_dlg =
        create_dlg (start_y, start_x, compl_dlg_h, compl_dlg_w,
                    dialog_colors, NULL, "[Completion]", NULL, DLG_COMPACT);

    /* create the listbox */
    compl_list = listbox_new (1, 1, compl_dlg_h - 2, compl_dlg_w - 2, NULL);

    /* add the dialog */
    add_widget (compl_dlg, compl_list);

    /* fill the listbox with the completions */
    for (i = num_compl - 1; i >= 0; i--) /* reverse order */
        listbox_add_item (compl_list, LISTBOX_APPEND_AT_END, 0, (char *) compl[i].text, NULL);

    /* pop up the dialog and apply the choosen completion */
    if (run_dlg (compl_dlg) == B_ENTER) {
        listbox_get_current (compl_list, &curr, NULL);
        if (curr) {
#ifdef HAVE_CHARSET
	    GString *temp, *temp2;
	    temp = g_string_new("");
	    for (curr += word_len; *curr; curr++)
		g_string_append_c(temp, *curr);

	    temp2 = str_convert_to_input (temp->str);

	    if (temp2 && temp2->len){
		g_string_free(temp, TRUE);
		temp = temp2;
	    }
	    else
		g_string_free(temp2, TRUE);
	    for (curr = temp->str; *curr; curr++)
		edit_insert (edit, *curr);
	    g_string_free(temp, TRUE);
#else
            for (curr += word_len; *curr; curr++)
                edit_insert (edit, *curr);
#endif
        }
    }

    /* destroy dialog before return */
    destroy_dlg (compl_dlg);
}
Exemplo n.º 4
0
static gboolean
commit_editor (OstreeRepo     *repo,
               const char     *branch,
               char          **subject,
               char          **body,
               GCancellable   *cancellable,
               GError        **error)
{
  g_autofree char *input = NULL;
  g_autofree char *output = NULL;
  gboolean ret = FALSE;
  g_autoptr(GString) bodybuf = NULL;
  char **lines = NULL;
  int i;

  input = g_strdup_printf ("\n"
      "# Please enter the commit message for your changes. The first line will\n"
      "# become the subject, and the remainder the body. Lines starting\n"
      "# with '#' will be ignored, and an empty message aborts the commit."
      "%s%s%s%s%s%s\n"
              , branch ? "\n#\n# Branch: " : "", branch ? branch : ""
              , *subject ? "\n" : "", *subject ? *subject : ""
              , *body ? "\n" : "", *body ? *body : ""
              );

  *subject = NULL;
  *body = NULL;

  output = ot_editor_prompt (repo, input, cancellable, error);
  if (output == NULL)
    goto out;

  lines = g_strsplit (output, "\n", -1);
  for (i = 0; lines[i] != NULL; i++)
    {
      g_strchomp (lines[i]);

      /* Lines starting with # are skipped */
      if (lines[i][0] == '#')
        continue;

      /* Blank lines before body starts are skipped */
      if (lines[i][0] == '\0')
        {
          if (!bodybuf)
            continue;
        }

      if (!*subject)
        {
          *subject = g_strdup (lines[i]);
        }
      else if (!bodybuf)
        {
          bodybuf = g_string_new (lines[i]);
        }
      else
        {
          g_string_append_c (bodybuf, '\n');
          g_string_append (bodybuf, lines[i]);
        }
    }

  if (!*subject)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Aborting commit due to empty commit subject.");
      goto out;
    }

  if (bodybuf)
    {
      *body = g_string_free (bodybuf, FALSE);
      g_strchomp (*body);
      bodybuf = NULL;
    }

  ret = TRUE;

out:
  g_strfreev (lines);
  return ret;
}
Exemplo n.º 5
0
static void
options_form_param_changed_cb (G_GNUC_UNUSED GdauiBasicForm *form, G_GNUC_UNUSED GdaHolder *param,
			       G_GNUC_UNUSED gboolean is_user_modif, TablePreferences *tpref)
{
	GtkTreeIter iter;

	if (tpref->priv->save_plugin_changes &&
	    gtk_combo_box_get_active_iter (GTK_COMBO_BOX (tpref->priv->plugins_combo), &iter)) {
		GdauiPlugin *plugin;
		GError *error = NULL;
		GString *plugin_all = NULL;

		gtk_tree_model_get (tpref->priv->plugins_model, &iter, PL_COLUMN_PLUGIN, &plugin, -1);
		if (plugin) {
			plugin_all = g_string_new (plugin->plugin_name);
			if (tpref->priv->options_wid) {
				GdaSet *plist;
				GSList *list;
				gboolean first = TRUE;
				plist = gdaui_basic_form_get_data_set (GDAUI_BASIC_FORM (tpref->priv->options_wid));
				for (list = plist->holders; list; list = list->next) {
					GdaHolder *holder;
					const GValue *cvalue;
					gchar *str, *r1, *r2;
					holder = GDA_HOLDER (list->data);
					if (! gda_holder_is_valid (holder))
						continue;

					cvalue = gda_holder_get_value (holder);
					if (G_VALUE_TYPE (cvalue) == GDA_TYPE_NULL)
						continue;
					if (first) {
						g_string_append_c (plugin_all, ':');
						first = FALSE;
					}
					else
						g_string_append_c (plugin_all, ';');
					str = gda_value_stringify (cvalue);
					r1 = gda_rfc1738_encode (str);
					g_free (str);
					r2 = gda_rfc1738_encode (gda_holder_get_id (holder));
					g_string_append_printf (plugin_all, "%s=%s", r2, r1);
					g_free (r1);
					g_free (r2);
				}
			}
		}
		
		g_signal_handlers_block_by_func (tpref->priv->columns_store,
						 G_CALLBACK (columns_model_row_changed_cb), tpref);
		if (tpref->priv->current_table &&
		    tpref->priv->current_column &&
		    ! t_connection_set_table_column_attribute (tpref->priv->tcnc,
								     tpref->priv->current_table,
								     tpref->priv->current_column,
								     T_CONNECTION_COLUMN_PLUGIN,
								     plugin_all ? plugin_all->str : NULL,
								     &error)) {
			TO_IMPLEMENT; /* FIXME: add a notice somewhere in the UI */
			g_warning ("Error: %s\n", error && error->message ? error->message : _("No detail"));
			g_clear_error (&error);
		}
		g_signal_handlers_unblock_by_func (tpref->priv->columns_store,
						   G_CALLBACK (columns_model_row_changed_cb), tpref);

		if (plugin_all)
			g_string_free (plugin_all, TRUE);
	}
	set_preview_widget (tpref);
}
static gboolean
decode_filename (const char *filename,
		 char **service,
		 char **type,
		 char **domain)
{
	const char *p;
	char *end;
	GString *string;

	*service = NULL;
	*type = NULL;
	*domain = NULL;
	
	string = g_string_new (NULL);

	p = filename;

	while (*p && *p != '.') {
		if (*p == '\\') {
			p++;
			switch (*p) {
			case 's':
				g_string_append_c (string, '/');
				break;
			case '\\':
				g_string_append_c (string, '\\');
				break;
			case '.':
				g_string_append_c (string, '.');
				break;
			default:
				g_string_free (string, TRUE);
				return FALSE;
			}
			
		} else {
			g_string_append_c (string, *p);
		}
		p++;
	}
	
	*service = g_string_free (string, FALSE);

	if (*p == 0)
		goto error;

	p++;

	end = strchr (p, '.');
	if (end == NULL)
		goto error;
	end = strchr (end+1, '.');
	if (end == NULL)
		goto error;
	*end = 0;
	*type = g_strdup (p);
	p = end + 1;
	
	if (*p == 0 || *p == '.')
		goto error;

	*domain = g_strdup (p);

	return TRUE;

 error:
	g_free (*service);
	g_free (*type);
	return FALSE;
}
Exemplo n.º 7
0
static char *
str_utf8_create_key_gen (const char *text, int case_sen,
                         gchar * (*keygen) (const gchar * text, gssize size))
{
    char *result;

    if (case_sen)
        result = str_utf8_normalize (text);
    else
    {
        gboolean dot;
        GString *fixed;
        const char *start, *end;
        char *fold, *key;

        dot = text[0] == '.';
        fixed = g_string_sized_new (16);

        if (!dot)
            start = text;
        else
        {
            start = text + 1;
            g_string_append_c (fixed, '.');
        }

        while (!g_utf8_validate (start, -1, &end) && start[0] != '\0')
        {
            if (start != end)
            {
                fold = g_utf8_casefold (start, end - start);
                key = keygen (fold, -1);
                g_string_append (fixed, key);
                g_free (key);
                g_free (fold);
            }
            g_string_append_c (fixed, end[0]);
            start = end + 1;
        }

        if (start == text)
        {
            fold = g_utf8_casefold (start, -1);
            result = keygen (fold, -1);
            g_free (fold);
            g_string_free (fixed, TRUE);
        }
        else if (dot && (start == text + 1))
        {
            fold = g_utf8_casefold (start, -1);
            key = keygen (fold, -1);
            g_string_append (fixed, key);
            g_free (key);
            g_free (fold);
            result = g_string_free (fixed, FALSE);
        }
        else
        {
            if (start[0] != '\0' && start != end)
            {
                fold = g_utf8_casefold (start, end - start);
                key = keygen (fold, -1);
                g_string_append (fixed, key);
                g_free (key);
                g_free (fold);
            }
            result = g_string_free (fixed, FALSE);
        }
    }
    return result;
}
Exemplo n.º 8
0
gchar *
gda_web_render_CREATE_TABLE (GdaServerProvider *provider, GdaConnection *cnc, 
			      GdaServerOperation *op, GError **error)
{
	GString *string;
	const GValue *value;
	gboolean allok = TRUE;
	gboolean hasfields = FALSE;
	gint nrows;
	gint i;
	gboolean first;
	GSList *pkfields = NULL; /* list of GValue* composing the pkey */
	gint nbpkfields = 0;
	gchar *tmp;

	/* CREATE TABLE */
	string = g_string_new ("CREATE TABLE ");

	tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/TABLE_DEF_P/TABLE_NAME", error);
	if (!tmp) {
		g_string_free (string, TRUE);
		return NULL;
	}

	g_string_append (string, tmp);
	g_free (tmp);
	g_string_append (string, " (");
		
	/* FIELDS */
	if (allok) {
		GdaServerOperationNode *node;

		node = gda_server_operation_get_node_info (op, "/FIELDS_A");
		g_assert (node);

		/* finding if there is a composed primary key */
		nrows = gda_data_model_get_n_rows (node->model);
		for (i = 0; i < nrows; i++) {
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_PKEY/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
				tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
										  "/FIELDS_A/@COLUMN_NAME/%d",
										  error, i);
				if (!tmp) {
					g_string_free (string, TRUE);
					return NULL;
				}

				pkfields = g_slist_append (pkfields, tmp);
				nbpkfields++;
			}
		}

		/* manually defined fields */
		first = TRUE;
		for (i = 0; i < nrows; i++) {
			hasfields = TRUE;
			if (first) 
				first = FALSE;
			else
				g_string_append (string, ", ");
				
			tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
									  "/FIELDS_A/@COLUMN_NAME/%d", error, i);
			if (!tmp) {
				g_string_free (string, TRUE);
				return NULL;
			}

			g_string_append (string, tmp);
			g_free (tmp);
			g_string_append_c (string, ' ');
				
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_TYPE/%d", i);
			g_string_append (string, g_value_get_string (value));
				
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_DEFAULT/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_STRING)) {
				const gchar *str = g_value_get_string (value);
				if (str && *str) {
					g_string_append (string, " DEFAULT ");
					g_string_append (string, str);
				}
			}
				
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_NNUL/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
				g_string_append (string, " NOT NULL");

			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_UNIQUE/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
				g_string_append (string, " UNIQUE");
				
			if (nbpkfields == 1) {
				value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_PKEY/%d", i);
				if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
					g_string_append (string, " PRIMARY KEY");
			}
				
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_CHECK/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_STRING)) {
				const gchar *str = g_value_get_string (value);
				if (str && *str) {
					g_string_append (string, " CHECK (");
					g_string_append (string, str);
					g_string_append_c (string, ')');
				}
			}
		}
	}

	/* composed primary key */
	if (nbpkfields > 1) {
		GSList *list;

		g_string_append (string, ", PRIMARY KEY (");
		for (list = pkfields; list; list = list->next) {
			if (list != pkfields)
				g_string_append (string, ", ");
			g_string_append (string, (gchar*) list->data);
		}
		g_string_append_c (string, ')');
	}
	g_slist_foreach (pkfields, (GFunc) g_free, NULL);
	g_slist_free (pkfields);

	g_string_append (string, ")");

	if (!hasfields) {
		allok = FALSE;
		g_set_error (error, GDA_SERVER_OPERATION_ERROR,
                             GDA_SERVER_OPERATION_INCORRECT_VALUE_ERROR,
			     "%s", _("Table to create must have at least one row"));
	}

	return g_string_free (string, FALSE);
}
gboolean
nm_supplicant_config_add_setting_8021x (NMSupplicantConfig *self,
                                        NMSetting8021x *setting,
                                        const char *con_uuid,
                                        guint32 mtu,
                                        gboolean wired)
{
    NMSupplicantConfigPrivate *priv;
    char *tmp;
    const char *peapver, *value, *path;
    gboolean success, added;
    GString *phase1, *phase2;
    GBytes *bytes;
    gboolean fast = FALSE;
    guint32 i, num_eap;
    gboolean fast_provisoning_allowed = FALSE;
    const char *ca_path_override = NULL, *ca_cert_override = NULL;
    guint32 frag, hdrs;
    gs_free char *frag_str = NULL;

    g_return_val_if_fail (NM_IS_SUPPLICANT_CONFIG (self), FALSE);
    g_return_val_if_fail (setting != NULL, FALSE);
    g_return_val_if_fail (con_uuid != NULL, FALSE);

    priv = NM_SUPPLICANT_CONFIG_GET_PRIVATE (self);

    value = nm_setting_802_1x_get_password (setting);
    if (value) {
        if (!add_string_val (self, value, "password", FALSE, TRUE))
            return FALSE;
    } else {
        bytes = nm_setting_802_1x_get_password_raw (setting);
        if (bytes) {
            success = nm_supplicant_config_add_option (self,
                      "password",
                      (const char *) g_bytes_get_data (bytes, NULL),
                      g_bytes_get_size (bytes),
                      TRUE);
            if (!success) {
                nm_log_warn (LOGD_SUPPLICANT, "Error adding password-raw to supplicant config.");
                return FALSE;
            }
        }
    }
    value = nm_setting_802_1x_get_pin (setting);
    if (!add_string_val (self, value, "pin", FALSE, TRUE))
        return FALSE;

    if (wired) {
        if (!add_string_val (self, "IEEE8021X", "key_mgmt", FALSE, FALSE))
            return FALSE;
        /* Wired 802.1x must always use eapol_flags=0 */
        if (!add_string_val (self, "0", "eapol_flags", FALSE, FALSE))
            return FALSE;
        nm_supplicant_config_set_ap_scan (self, 0);
    }

    ADD_STRING_LIST_VAL (setting, 802_1x, eap_method, eap_methods, "eap", ' ', TRUE, FALSE);

    /* Check EAP method for special handling: PEAP + GTC, FAST */
    num_eap = nm_setting_802_1x_get_num_eap_methods (setting);
    for (i = 0; i < num_eap; i++) {
        const char *method = nm_setting_802_1x_get_eap_method (setting, i);

        if (method && (strcasecmp (method, "fast") == 0)) {
            fast = TRUE;
            priv->fast_required = TRUE;
        }
    }

    /* Adjust the fragment size according to MTU, but do not set it higher than 1280-14
     * for better compatibility */
    hdrs = 14; /* EAPOL + EAP-TLS */
    frag = 1280 - hdrs;
    if (mtu > hdrs)
        frag = CLAMP (mtu - hdrs, 100, frag);
    frag_str = g_strdup_printf ("%u", frag);

    if (!nm_supplicant_config_add_option (self, "fragment_size", frag_str, -1, FALSE))
        return FALSE;

    phase1 = g_string_new (NULL);
    peapver = nm_setting_802_1x_get_phase1_peapver (setting);
    if (peapver) {
        if (!strcmp (peapver, "0"))
            g_string_append (phase1, "peapver=0");
        else if (!strcmp (peapver, "1"))
            g_string_append (phase1, "peapver=1");
    }

    if (nm_setting_802_1x_get_phase1_peaplabel (setting)) {
        if (phase1->len)
            g_string_append_c (phase1, ' ');
        g_string_append_printf (phase1, "peaplabel=%s", nm_setting_802_1x_get_phase1_peaplabel (setting));
    }

    value = nm_setting_802_1x_get_phase1_fast_provisioning (setting);
    if (value) {
        if (phase1->len)
            g_string_append_c (phase1, ' ');
        g_string_append_printf (phase1, "fast_provisioning=%s", value);

        if (strcmp (value, "0") != 0)
            fast_provisoning_allowed = TRUE;
    }

    if (phase1->len) {
        if (!add_string_val (self, phase1->str, "phase1", FALSE, FALSE)) {
            g_string_free (phase1, TRUE);
            return FALSE;
        }
    }
    g_string_free (phase1, TRUE);

    phase2 = g_string_new (NULL);
    if (nm_setting_802_1x_get_phase2_auth (setting) && !fast_provisoning_allowed) {
        tmp = g_ascii_strup (nm_setting_802_1x_get_phase2_auth (setting), -1);
        g_string_append_printf (phase2, "auth=%s", tmp);
        g_free (tmp);
    }

    if (nm_setting_802_1x_get_phase2_autheap (setting)) {
        if (phase2->len)
            g_string_append_c (phase2, ' ');
        tmp = g_ascii_strup (nm_setting_802_1x_get_phase2_autheap (setting), -1);
        g_string_append_printf (phase2, "autheap=%s", tmp);
        g_free (tmp);
    }

    if (phase2->len) {
        if (!add_string_val (self, phase2->str, "phase2", FALSE, FALSE)) {
            g_string_free (phase2, TRUE);
            return FALSE;
        }
    }
    g_string_free (phase2, TRUE);

    /* PAC file */
    path = nm_setting_802_1x_get_pac_file (setting);
    if (path) {
        if (!add_string_val (self, path, "pac_file", FALSE, FALSE))
            return FALSE;
    } else {
        /* PAC file is not specified.
         * If provisioning is allowed, use an blob format.
         */
        if (fast_provisoning_allowed) {
            char *blob_name = g_strdup_printf ("blob://pac-blob-%s", con_uuid);
            if (!add_string_val (self, blob_name, "pac_file", FALSE, FALSE)) {
                g_free (blob_name);
                return FALSE;
            }
            g_free (blob_name);
        } else {
            /* This is only error for EAP-FAST; don't disturb other methods. */
            if (fast) {
                nm_log_err (LOGD_SUPPLICANT, "EAP-FAST error: no PAC file provided and "
                            "automatic PAC provisioning is disabled.");
                return FALSE;
            }
        }
    }

    /* If user wants to use system CA certs, either populate ca_path (if the path
     * is a directory) or ca_cert (the path is a file name) */
    if (nm_setting_802_1x_get_system_ca_certs (setting)) {
        if (g_file_test (SYSTEM_CA_PATH, G_FILE_TEST_IS_DIR))
            ca_path_override = SYSTEM_CA_PATH;
        else
            ca_cert_override = SYSTEM_CA_PATH;
    }

    /* CA path */
    path = nm_setting_802_1x_get_ca_path (setting);
    path = ca_path_override ? ca_path_override : path;
    if (path) {
        if (!add_string_val (self, path, "ca_path", FALSE, FALSE))
            return FALSE;
    }

    /* Phase2 CA path */
    path = nm_setting_802_1x_get_phase2_ca_path (setting);
    path = ca_path_override ? ca_path_override : path;
    if (path) {
        if (!add_string_val (self, path, "ca_path2", FALSE, FALSE))
            return FALSE;
    }

    /* CA certificate */
    if (ca_cert_override) {
        if (!add_string_val (self, ca_cert_override, "ca_cert", FALSE, FALSE))
            return FALSE;
    } else {
        switch (nm_setting_802_1x_get_ca_cert_scheme (setting)) {
        case NM_SETTING_802_1X_CK_SCHEME_BLOB:
            bytes = nm_setting_802_1x_get_ca_cert_blob (setting);
            ADD_BLOB_VAL (bytes, "ca_cert", con_uuid);
            break;
        case NM_SETTING_802_1X_CK_SCHEME_PATH:
            path = nm_setting_802_1x_get_ca_cert_path (setting);
            if (!add_string_val (self, path, "ca_cert", FALSE, FALSE))
                return FALSE;
            break;
        default:
            break;
        }
    }

    /* Phase 2 CA certificate */
    if (ca_cert_override) {
        if (!add_string_val (self, ca_cert_override, "ca_cert2", FALSE, FALSE))
            return FALSE;
    } else {
        switch (nm_setting_802_1x_get_phase2_ca_cert_scheme (setting)) {
        case NM_SETTING_802_1X_CK_SCHEME_BLOB:
            bytes = nm_setting_802_1x_get_phase2_ca_cert_blob (setting);
            ADD_BLOB_VAL (bytes, "ca_cert2", con_uuid);
            break;
        case NM_SETTING_802_1X_CK_SCHEME_PATH:
            path = nm_setting_802_1x_get_phase2_ca_cert_path (setting);
            if (!add_string_val (self, path, "ca_cert2", FALSE, FALSE))
                return FALSE;
            break;
        default:
            break;
        }
    }

    /* Subject match */
    value = nm_setting_802_1x_get_subject_match (setting);
    if (!add_string_val (self, value, "subject_match", FALSE, FALSE))
        return FALSE;
    value = nm_setting_802_1x_get_phase2_subject_match (setting);
    if (!add_string_val (self, value, "subject_match2", FALSE, FALSE))
        return FALSE;

    /* altSubjectName match */
    ADD_STRING_LIST_VAL (setting, 802_1x, altsubject_match, altsubject_matches, "altsubject_match", ';', FALSE, FALSE);
    ADD_STRING_LIST_VAL (setting, 802_1x, phase2_altsubject_match, phase2_altsubject_matches, "altsubject_match2", ';', FALSE, FALSE);

    /* Private key */
    added = FALSE;
    switch (nm_setting_802_1x_get_private_key_scheme (setting)) {
    case NM_SETTING_802_1X_CK_SCHEME_BLOB:
        bytes = nm_setting_802_1x_get_private_key_blob (setting);
        ADD_BLOB_VAL (bytes, "private_key", con_uuid);
        added = TRUE;
        break;
    case NM_SETTING_802_1X_CK_SCHEME_PATH:
        path = nm_setting_802_1x_get_private_key_path (setting);
        if (!add_string_val (self, path, "private_key", FALSE, FALSE))
            return FALSE;
        added = TRUE;
        break;
    default:
        break;
    }

    if (added) {
        NMSetting8021xCKFormat format;
        NMSetting8021xCKScheme scheme;

        format = nm_setting_802_1x_get_private_key_format (setting);
        scheme = nm_setting_802_1x_get_private_key_scheme (setting);

        if (   scheme == NM_SETTING_802_1X_CK_SCHEME_PATH
                || format == NM_SETTING_802_1X_CK_FORMAT_PKCS12) {
            /* Only add the private key password for PKCS#12 blobs and
             * all path schemes, since in both of these cases the private key
             * isn't decrypted at all.
             */
            value = nm_setting_802_1x_get_private_key_password (setting);
            if (!add_string_val (self, value, "private_key_passwd", FALSE, TRUE))
                return FALSE;
        }

        if (format != NM_SETTING_802_1X_CK_FORMAT_PKCS12) {
            /* Only add the client cert if the private key is not PKCS#12, as
             * wpa_supplicant configuration directs us to do.
             */
            switch (nm_setting_802_1x_get_client_cert_scheme (setting)) {
            case NM_SETTING_802_1X_CK_SCHEME_BLOB:
                bytes = nm_setting_802_1x_get_client_cert_blob (setting);
                ADD_BLOB_VAL (bytes, "client_cert", con_uuid);
                break;
            case NM_SETTING_802_1X_CK_SCHEME_PATH:
                path = nm_setting_802_1x_get_client_cert_path (setting);
                if (!add_string_val (self, path, "client_cert", FALSE, FALSE))
                    return FALSE;
                break;
            default:
                break;
            }
        }
    }

    /* Phase 2 private key */
    added = FALSE;
    switch (nm_setting_802_1x_get_phase2_private_key_scheme (setting)) {
    case NM_SETTING_802_1X_CK_SCHEME_BLOB:
        bytes = nm_setting_802_1x_get_phase2_private_key_blob (setting);
        ADD_BLOB_VAL (bytes, "private_key2", con_uuid);
        added = TRUE;
        break;
    case NM_SETTING_802_1X_CK_SCHEME_PATH:
        path = nm_setting_802_1x_get_phase2_private_key_path (setting);
        if (!add_string_val (self, path, "private_key2", FALSE, FALSE))
            return FALSE;
        added = TRUE;
        break;
    default:
        break;
    }

    if (added) {
        NMSetting8021xCKFormat format;
        NMSetting8021xCKScheme scheme;

        format = nm_setting_802_1x_get_phase2_private_key_format (setting);
        scheme = nm_setting_802_1x_get_phase2_private_key_scheme (setting);

        if (   scheme == NM_SETTING_802_1X_CK_SCHEME_PATH
                || format == NM_SETTING_802_1X_CK_FORMAT_PKCS12) {
            /* Only add the private key password for PKCS#12 blobs and
             * all path schemes, since in both of these cases the private key
             * isn't decrypted at all.
             */
            value = nm_setting_802_1x_get_phase2_private_key_password (setting);
            if (!add_string_val (self, value, "private_key2_passwd", FALSE, TRUE))
                return FALSE;
        }

        if (format != NM_SETTING_802_1X_CK_FORMAT_PKCS12) {
            /* Only add the client cert if the private key is not PKCS#12, as
             * wpa_supplicant configuration directs us to do.
             */
            switch (nm_setting_802_1x_get_phase2_client_cert_scheme (setting)) {
            case NM_SETTING_802_1X_CK_SCHEME_BLOB:
                bytes = nm_setting_802_1x_get_phase2_client_cert_blob (setting);
                ADD_BLOB_VAL (bytes, "client_cert2", con_uuid);
                break;
            case NM_SETTING_802_1X_CK_SCHEME_PATH:
                path = nm_setting_802_1x_get_phase2_client_cert_path (setting);
                if (!add_string_val (self, path, "client_cert2", FALSE, FALSE))
                    return FALSE;
                break;
            default:
                break;
            }
        }
    }

    value = nm_setting_802_1x_get_identity (setting);
    if (!add_string_val (self, value, "identity", FALSE, FALSE))
        return FALSE;
    value = nm_setting_802_1x_get_anonymous_identity (setting);
    if (!add_string_val (self, value, "anonymous_identity", FALSE, FALSE))
        return FALSE;

    return TRUE;
}
Exemplo n.º 10
0
/* print_rtf_localized_typography -- convert to "smart" typography */
void print_rtf_localized_typography(GString *out, int character, scratch_pad *scratch) {
	if (!extension(EXT_SMART, scratch->extensions)) {
		g_string_append_c(out, character);
		return;
	}
	switch (character) {
		case LSQUOTE:
			switch (scratch->language) {
				case SWEDISH:
					g_string_append_printf(out, "&#8217;");
					break;
				case FRENCH:
					g_string_append_printf(out,"&#39;");
					break;
				case GERMAN:
					g_string_append_printf(out,"&#8218;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#8250;");
					break;
				default:
					g_string_append_printf(out,"\\'91");
				}
			break;
		case RSQUOTE:
			switch (scratch->language) {
				case GERMAN:
					g_string_append_printf(out,"&#8216;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#8249;");
					break;
				default:
					g_string_append_printf(out,"\\'92");
				}
			break;
		case APOS:
			g_string_append_printf(out,"\\'27");
			break;
		case LDQUOTE:
			switch (scratch->language) {
				case DUTCH:
				case GERMAN:
					g_string_append_printf(out,"&#8222;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#187;");
					break;
				case FRENCH:
					g_string_append_printf(out,"&#171;");
					break;
				case SWEDISH:
					g_string_append_printf(out, "&#8221;");
					break;
				default:
					g_string_append_printf(out,"\\'93");
				}
			break;
		case RDQUOTE:
			switch (scratch->language) {
				case SWEDISH:
				case DUTCH:
					g_string_append_printf(out,"&#8221;");
					break;
				case GERMAN:
					g_string_append_printf(out,"&#8220;");
					break;
				case GERMANGUILL:
					g_string_append_printf(out,"&#171;");
					break;
				case FRENCH:
					g_string_append_printf(out,"&#187;");
					break;
				default:
					g_string_append_printf(out,"\\'94");
				}
			break;
		case NDASH:
			g_string_append_printf(out,"\\'96");
			break;
		case MDASH:
			g_string_append_printf(out,"\\'97");
			break;
		case ELLIP:
			g_string_append_printf(out,"\\'85");
			break;
			default:;
	}
}
Exemplo n.º 11
0
static gchar *
gda_sql_statement_update_serialize (gpointer stmt)
{
	GString *string;
	gchar *str;
	GSList *list;
	GdaSqlStatementUpdate *update = (GdaSqlStatementUpdate *) stmt;

	g_return_val_if_fail (stmt, NULL);

	string = g_string_new ("\"contents\":{");

	/* table name */
	g_string_append (string, "\"table\":");
	str = gda_sql_table_serialize (update->table);
	g_string_append (string, str);
	g_free (str);

	/* fields */
	g_string_append (string, ",\"fields\":");
	if (update->fields_list) {
		g_string_append_c (string, '[');
		for (list = update->fields_list; list; list = list->next) {
			if (list != update->fields_list)
				g_string_append_c (string, ',');
			str = gda_sql_field_serialize ((GdaSqlField *) list->data);
			g_string_append (string, str);
			g_free (str);
		}
		g_string_append_c (string, ']');
	}
	else
		g_string_append (string, "null");

	/* expressions */
	g_string_append (string, ",\"expressions\":");
	if (update->expr_list) {
		g_string_append_c (string, '[');
		for (list = update->expr_list; list; list = list->next) {
			if (list != update->expr_list)
				g_string_append_c (string, ',');
			str = gda_sql_expr_serialize ((GdaSqlExpr *) list->data);
			g_string_append (string, str);
			g_free (str);
		}
		g_string_append_c (string, ']');
	}
	else
		g_string_append (string, "null");	

	/* condition */
	if (update->cond) {
		g_string_append (string, ",\"condition\":");
		str = gda_sql_expr_serialize (update->cond);
		g_string_append (string, str);
		g_free (str);
	}

	/* conflict clause */
        if (update->on_conflict) {
                g_string_append (string, ",\"on_conflict\":");
                str = _json_quote_string (update->on_conflict);
                g_string_append (string, str);
                g_free (str);
        }
	g_string_append_c (string, '}');
	str = string->str;
	g_string_free (string, FALSE);
	return str;	
}
Exemplo n.º 12
0
static gboolean
convert_var_to_tmpfiles_d (GOutputStream *tmpfiles_out,
                           GFile         *yumroot,
                           GFile         *dir,
                           GCancellable  *cancellable,
                           GError       **error)
{
  gboolean ret = FALSE;
  gs_unref_object GFileEnumerator *direnum = NULL;
  gsize bytes_written;

  direnum = g_file_enumerate_children (dir, "standard::name,standard::type,unix::mode,standard::symlink-target,unix::uid,unix::gid",
                                       G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                       cancellable, error);
  if (!direnum)
    {
      g_prefix_error (error, "Enumerating /var in '%s'", gs_file_get_path_cached (dir));
      goto out;
    }

  while (TRUE)
    {
      GFileInfo *file_info;
      GFile *child;
      GString *tmpfiles_d_buf;
      gs_free char *tmpfiles_d_line = NULL;
      char filetype_c;
      gs_free char *relpath = NULL;

      if (!gs_file_enumerator_iterate (direnum, &file_info, &child,
                                       cancellable, error))
        goto out;
      if (!file_info)
        break;

      switch (g_file_info_get_file_type (file_info))
        {
        case G_FILE_TYPE_DIRECTORY:
          filetype_c = 'd';
          break;
        case G_FILE_TYPE_SYMBOLIC_LINK:
          filetype_c = 'L';
          break;
        default:
          g_print ("Ignoring non-directory/non-symlink '%s'\n",
                   gs_file_get_path_cached (child));
          continue;
        }

      tmpfiles_d_buf = g_string_new ("");
      g_string_append_c (tmpfiles_d_buf, filetype_c);
      g_string_append_c (tmpfiles_d_buf, ' ');

      relpath = g_file_get_relative_path (yumroot, child);
      g_assert (relpath);
      
      g_string_append_c (tmpfiles_d_buf, '/');
      g_string_append (tmpfiles_d_buf, relpath);

      if (filetype_c == 'd')
        {
          guint mode = g_file_info_get_attribute_uint32 (file_info, "unix::mode");
          mode &= ~S_IFMT;
          g_string_append_printf (tmpfiles_d_buf, " 0%02o", mode);
          g_string_append_printf (tmpfiles_d_buf, " %d %d - -",
                                  g_file_info_get_attribute_uint32 (file_info, "unix::uid"),
                                  g_file_info_get_attribute_uint32 (file_info, "unix::gid"));

          if (!convert_var_to_tmpfiles_d (tmpfiles_out, yumroot, child,
                                          cancellable, error))
            goto out;
        }
      else
        {
          g_string_append (tmpfiles_d_buf, " - - - - ");
          g_string_append (tmpfiles_d_buf, g_file_info_get_symlink_target (file_info));
        }

      g_string_append_c (tmpfiles_d_buf, '\n');

      tmpfiles_d_line = g_string_free (tmpfiles_d_buf, FALSE);

      if (!g_output_stream_write_all (tmpfiles_out, tmpfiles_d_line,
                                      strlen (tmpfiles_d_line), &bytes_written,
                                      cancellable, error))
        goto out;
    }

  ret = TRUE;
 out:
  return ret;
}
Exemplo n.º 13
0
// concatenate folder and file to new path and try create folder and empty file.
// If folder create failed, post UG_MESSAGE_ERROR_FOLDER_CREATE_FAILED.
// If file exist, it will change filename and post UG_MESSAGE_DATA_FILE_CHANGED.
// if function succeeded, return new path and it's folder length.
gchar*	ug_plugin_create_file (UgPlugin* plugin, const gchar* folder, const gchar* file, guint* folder_len)
{
	GString*		gstr;
	const gchar*	tail_str;
	guint			head_len;
	guint			location_len;
	guint			count;
	int				fd;

	if (folder == NULL && file == NULL) {
		ug_plugin_post (plugin, ug_message_new_error (UG_MESSAGE_ERROR_FILE_CREATE_FAILED, NULL));
		return NULL;
	}
	// concatenate full path
	gstr = g_string_sized_new (80);
	if (folder) {
		g_string_append (gstr, folder);
		if (gstr->len  &&  gstr->str [gstr->len -1] != G_DIR_SEPARATOR)
			g_string_append_c (gstr, G_DIR_SEPARATOR);
	}
	if (file)
		g_string_append (gstr, file);
	// get location_len (length of path exclude filename).
	tail_str = strrchr (gstr->str, G_DIR_SEPARATOR);
	if (tail_str == NULL)
		location_len = 0;
	else
		location_len = tail_str - gstr->str + 1;	// + G_DIR_SEPARATOR
	// create folder
	if (location_len && ug_create_dir_all (gstr->str, location_len) == -1) {
		ug_plugin_post (plugin, ug_message_new_error (UG_MESSAGE_ERROR_FOLDER_CREATE_FAILED, NULL));
		return g_string_free (gstr, TRUE);
	}
	// get head_len (length of folder + primary filename)
	// and tail_str ('.' + filename extension)
	tail_str = strrchr (gstr->str + location_len, '.');
	if (tail_str == NULL)
		tail_str = gstr->str + gstr->len;
	head_len = tail_str - gstr->str;
	tail_str = g_strdup (tail_str);
	// create file
	for (count=0;  count < 10000;  count++) {
//		fd = open (gstr->str, O_CREAT | O_EXCL | O_RDWR,
//		           S_IREAD | S_IWRITE | S_IRGRP | S_IROTH);
		fd = ug_fd_open (gstr->str, UG_FD_O_CREATE | UG_FD_O_EXCL | UG_FD_O_RDWR,
		                 UG_FD_S_IREAD | UG_FD_S_IWRITE | UG_FD_S_IRGRP | UG_FD_S_IROTH);
		if (fd != -1) {
//			close (fd);
			ug_fd_close (fd);
			break;
		}
		g_string_truncate (gstr, head_len);
		g_string_append_printf (gstr, "(%d)", count);
		g_string_append (gstr, tail_str);
	}
	// free tail_str
	g_free ((gpointer) tail_str);
	// result
	if (count == 10000) {
		ug_plugin_post (plugin,
				ug_message_new_error (UG_MESSAGE_ERROR_FILE_CREATE_FAILED, NULL));
		return g_string_free (gstr, TRUE);
	}
	if (count > 0) {
		ug_plugin_post (plugin,
				ug_message_new_data (UG_MESSAGE_DATA_FILE_CHANGED, gstr->str + location_len));
	}
	if (folder_len)
		*folder_len = location_len;

	return g_string_free (gstr, FALSE);
}
Exemplo n.º 14
0
static estr_t
_str_convert (GIConv coder, const char *string, int size, GString * buffer)
{
    estr_t state = ESTR_SUCCESS;
    gssize left;
    gsize bytes_read = 0;
    gsize bytes_written = 0;

    errno = 0;                  /* FIXME: is it really needed? */

    if (coder == INVALID_CONV)
        return ESTR_FAILURE;

    if (string == NULL || buffer == NULL)
        return ESTR_FAILURE;

    /*
       if (! used_class.is_valid_string (string))
       {
       return ESTR_FAILURE;
       }
     */
    if (size < 0)
        size = strlen (string);
    else
    {
        left = strlen (string);
        if (left < size)
            size = left;
    }

    left = size;
    g_iconv (coder, NULL, NULL, NULL, NULL);

    while (left != 0)
    {
        gchar *tmp_buff;
        GError *error = NULL;

        tmp_buff = g_convert_with_iconv ((const gchar *) string,
                                         left, coder, &bytes_read, &bytes_written, &error);
        if (error != NULL)
        {
            int code = error->code;

            g_error_free (error);
            error = NULL;

            switch (code)
            {
            case G_CONVERT_ERROR_NO_CONVERSION:
                /* Conversion between the requested character sets is not supported. */
                tmp_buff = g_strnfill (strlen (string), '?');
                g_string_append (buffer, tmp_buff);
                g_free (tmp_buff);
                return ESTR_FAILURE;

            case G_CONVERT_ERROR_ILLEGAL_SEQUENCE:
                /* Invalid byte sequence in conversion input. */
                if ((tmp_buff == NULL) && (bytes_read != 0))
                    /* recode valid byte sequence */
                    tmp_buff = g_convert_with_iconv ((const gchar *) string,
                                                     bytes_read, coder, NULL, NULL, NULL);

                if (tmp_buff != NULL)
                {
                    g_string_append (buffer, tmp_buff);
                    g_free (tmp_buff);
                }

                if ((int) bytes_read >= left)
                    return ESTR_PROBLEM;

                string += bytes_read + 1;
                size -= (bytes_read + 1);
                left -= (bytes_read + 1);
                g_string_append_c (buffer, *(string - 1));
                state = ESTR_PROBLEM;
                break;

            case G_CONVERT_ERROR_PARTIAL_INPUT:
                /* Partial character sequence at end of input. */
                g_string_append (buffer, tmp_buff);
                g_free (tmp_buff);
                if ((int) bytes_read < left)
                {
                    left = left - bytes_read;
                    tmp_buff = g_strnfill (left, '?');
                    g_string_append (buffer, tmp_buff);
                    g_free (tmp_buff);
                }
                return ESTR_PROBLEM;

            case G_CONVERT_ERROR_BAD_URI:      /* Don't know how handle this error :( */
            case G_CONVERT_ERROR_NOT_ABSOLUTE_PATH:    /* Don't know how handle this error :( */
            case G_CONVERT_ERROR_FAILED:       /* Conversion failed for some reason. */
            default:
                g_free (tmp_buff);
                return ESTR_FAILURE;
            }
        }
        else if (tmp_buff == NULL)
        {
            g_string_append (buffer, string);
            return ESTR_PROBLEM;
        }
        else if (*tmp_buff == '\0')
        {
            g_free (tmp_buff);
            g_string_append (buffer, string);
            return state;
        }
        else
        {
            g_string_append (buffer, tmp_buff);
            g_free (tmp_buff);
            string += bytes_read;
            left -= bytes_read;
        }
    }

    return state;
}
Exemplo n.º 15
0
static void
query (void)
{
  static GimpParamDef args[] =
  {
    { GIMP_PDB_INT32,    "run-mode",       "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }" },
    { GIMP_PDB_IMAGE,    "image",          "Input image (unused)"         },
    { GIMP_PDB_DRAWABLE, "drawable",       "Input drawable"               },
    { GIMP_PDB_STRING,   "decompose-type", NULL                           },
    { GIMP_PDB_INT32,    "layers-mode",    "Create channels as layers in a single image" }
  };
  static const GimpParamDef return_vals[] =
  {
    { GIMP_PDB_IMAGE, "new-image", "Output gray image" },
    { GIMP_PDB_IMAGE, "new-image", "Output gray image (N/A for single channel extract)" },
    { GIMP_PDB_IMAGE, "new-image", "Output gray image (N/A for single channel extract)" },
    { GIMP_PDB_IMAGE, "new-image", "Output gray image (N/A for single channel extract)" }
  };

  GString *type_desc;
  int i;

  type_desc = g_string_new ("What to decompose: ");
  g_string_append_c (type_desc, '"');
  g_string_append (type_desc, extract[0].type);
  g_string_append_c (type_desc, '"');

  for (i = 1; i < G_N_ELEMENTS (extract); i++)
    {
      g_string_append (type_desc, ", ");
      g_string_append_c (type_desc, '"');
      g_string_append (type_desc, extract[i].type);
      g_string_append_c (type_desc, '"');
    }

  args[3].description = type_desc->str;

  gimp_install_procedure (PLUG_IN_PROC,
                          N_("Decompose an image into separate colorspace components"),
                          "This function creates new gray images with "
                          "different channel information in each of them",
                          "Peter Kirchgessner",
                          "Peter Kirchgessner",
                          "1997",
                          N_("_Decompose..."),
                          "RGB*",
                          GIMP_PLUGIN,
                          G_N_ELEMENTS (args),
                          G_N_ELEMENTS (return_vals),
                          args, return_vals);

  gimp_install_procedure (PLUG_IN_PROC_REG,
                          N_("Decompose an image into separate colorspace components"),
                          "This function creates new gray images with "
                          "different channel information in each of them. "
                          "Pixels in the foreground color will appear black "
                          "in all output images.  This can be used for "
                          "things like crop marks that have to show up on "
                          "all channels.",
                          "Peter Kirchgessner",
                          "Peter Kirchgessner, Clarence Risher",
                          "1997",
                          N_("_Decompose..."),
                          "RGB*",
                          GIMP_PLUGIN,
                          G_N_ELEMENTS (args),
                          G_N_ELEMENTS (return_vals),
                          args, return_vals);

  gimp_plugin_menu_register (PLUG_IN_PROC_REG, "<Image>/Colors/Components");

  g_string_free (type_desc, TRUE);
}
Exemplo n.º 16
0
static void
jabber_bosh_connection_send(PurpleBOSHConnection *conn,
                            const PurpleBOSHPacketType type, const char *data)
{
	PurpleHTTPConnection *chosen;
	GString *packet = NULL;

	if (type != PACKET_FLUSH && type != PACKET_TERMINATE) {
		/*
		 * Unless this is a flush (or session terminate, which needs to be
		 * sent immediately), queue up the data and start a timer to flush
		 * the buffer.
		 */
		if (data) {
			int len = data ? strlen(data) : 0;
			purple_circ_buffer_append(conn->pending, data, len);
		}

		if (purple_debug_is_verbose())
			purple_debug_misc("jabber", "bosh: %p has %" G_GSIZE_FORMAT " bytes in "
			                  "the buffer.\n", conn, conn->pending->bufused);
		if (conn->send_timer == 0)
			conn->send_timer = purple_timeout_add_seconds(BUFFER_SEND_IN_SECS,
					send_timer_cb, conn);
		return;
	}

	chosen = find_available_http_connection(conn);

	if (!chosen) {
		/*
		 * For non-ordinary traffic, we can't 'buffer' it, so use the
		 * first connection.
		 */
		chosen = conn->connections[0];

		if (chosen->state != HTTP_CONN_CONNECTED) {
			purple_debug_warning("jabber", "Unable to find a ready BOSH "
					"connection. Ignoring send of type 0x%02x.\n", type);
			return;
		}
	}

	/* We're flushing the send buffer, so remove the send timer */
	if (conn->send_timer != 0) {
		purple_timeout_remove(conn->send_timer);
		conn->send_timer = 0;
	}

	packet = g_string_new(NULL);

	g_string_printf(packet, "<body "
	                "rid='%" G_GUINT64_FORMAT "' "
	                "sid='%s' "
	                "to='%s' "
	                "xml:lang='en' "
	                "xmlns='http://jabber.org/protocol/httpbind' "
	                "xmlns:xmpp='urn:xmpp:xbosh'",
	                ++conn->rid,
	                conn->sid,
	                conn->js->user->domain);

	if (conn->js->reinit) {
		packet = g_string_append(packet, " xmpp:restart='true'/>");
		/* TODO: Do we need to wait for a response? */
		conn->js->reinit = FALSE;
	} else {
		gsize read_amt;
		if (type == PACKET_TERMINATE)
			packet = g_string_append(packet, " type='terminate'");

		packet = g_string_append_c(packet, '>');

		while ((read_amt = purple_circ_buffer_get_max_read(conn->pending)) > 0) {
			packet = g_string_append_len(packet, conn->pending->outptr, read_amt);
			purple_circ_buffer_mark_read(conn->pending, read_amt);
		}

		if (data)
			packet = g_string_append(packet, data);
		packet = g_string_append(packet, "</body>");
	}

	http_connection_send_request(chosen, packet);
}
Exemplo n.º 17
0
static GError *
_client_manage_reply(struct gridd_client_s *client, MESSAGE reply)
{
	GError *err;
	gint status = 0;
	gchar *message = NULL;

	if (!metaXClient_reply_simple(reply, &status, &message, NULL))
		return NEWERROR(500, "Invalid reply");

	switch (status / 100) {

		case 0:
			err = NEWERROR(status, "net error: %s", message);
			g_free(message);
			metautils_pclose(&(client->fd));
			client->step = STATUS_FAILED;
			return err;

		case 1: /* Informational reply :  */
			g_get_current_time(&(client->tv_step));
			client->step = REP_READING_SIZE;
			g_free(message);
			return NULL;

		case 2:
			g_get_current_time(&(client->tv_step));
			client->step = (status==200) ? STATUS_OK : REP_READING_SIZE;
			if (client->step == STATUS_OK) {
				if (!client->keepalive)
					metautils_pclose(&(client->fd));
			}
			g_free(message);
			if (client->on_reply) {
				if (!client->on_reply(client->ctx, reply))
					return NEWERROR(500, "Handler error");
			}
			return NULL;

		case 3: /* redirection */
			if (status == CODE_REDIRECT) {
				/* Reset the context */
				_client_reset_reply(client);
				_client_reset_cnx(client);
				client->sent_bytes = 0;

				if ((++ client->nb_redirects) > 7) {
					g_free(message);
					return NEWERROR(CODE_TOOMANY_REDIRECT,
							"Too many redirections");
				}

				/* Save the current URL to avoid looping, and check
				 * for a potential loop */
				g_string_append_c(client->past_url, '|');
				g_string_append(client->past_url, client->url);
				if (_client_looped(client, message)) {
					g_free(message);
					return NEWERROR(CODE_LOOP_REDIRECT,
							"Looping on redirections");
				}

				/* Replace the URL */
				memset(client->url, 0, sizeof(client->url));
				g_strlcpy(client->url, message, sizeof(client->url)-1);
				if (NULL != (err = _client_connect(client))) {
					g_free(message);
					g_prefix_error(&err, "Redirection error: Connect error: ");
					return err;
				}

				g_free(message);
				return NULL;
			}
			/* FALLTHROUGH */

		default: /* all other are considered errors */
			err = NEWERROR(status, "Request error: %s", message);
			g_free(message);
			if (!client->keepalive)
				_client_reset_cnx(client);
			_client_reset_reply(client);
			return err;
	}
}
Exemplo n.º 18
0
Arquivo: util.c Projeto: vifino/dwb
gchar *
util_create_json(int n, ...) 
{
    va_list args;
    va_start(args, n);
    const gchar *key, *cval;
    gdouble dval;
    gint ival; guint uival; gulong ulval; glong lval; 
    gboolean bval;
    gchar *ret;

    gint type;
    setlocale(LC_NUMERIC, "C");

    GString *string = g_string_new("{");

    for (int i=0; i<n; i++) 
    {
        type = va_arg(args, gint);
        key = va_arg(args, gchar*);
        g_string_append_printf(string, "\"%s\":", key);
        switch (type) 
        {
            case CHAR : 
                cval = va_arg(args, gchar*); 
                if (cval == NULL)  
                    g_string_append(string, "null");
                else 
                {
                    g_string_append_c(string, '"');
                    while (*cval) {
                        if (   *cval == '"' 
                                || *cval == '/'
                                || *cval == '\\'
                                || *cval == '\b'
                                || *cval == '\f'
                                || *cval == '\n'
                                || *cval == '\r'
                                || *cval == '\t') 
                            g_string_append_c(string, '\\');
                        g_string_append_c(string, *cval);
                        cval++;
                    }
                    g_string_append_c(string, '"');
                }
                break;
            case INTEGER  : 
                ival = va_arg(args, gint);
                g_string_append_printf(string, "%d", ival);
                break;
            case UINTEGER  : 
                uival = va_arg(args, guint);
                g_string_append_printf(string, "%u", uival);
                break;
            case LONG  : 
                lval = va_arg(args, glong);
                g_string_append_printf(string, "%ld", lval);
                break;
            case ULONG  : 
                ulval = va_arg(args, gulong);
                g_string_append_printf(string, "%lu", ulval);
                break;
            case DOUBLE : 
                dval = va_arg(args, double); 
                g_string_append_printf(string, "%f", dval);
                break;
            case BOOLEAN:
                bval = va_arg(args, gboolean);
                g_string_append_printf(string, "%s", bval ? "true" : "false");
                break;
            default : g_string_append(string, "null"); break;
        }
        if (i<n-1)
            g_string_append_c(string, ',');
    }
    va_end(args);
    g_string_append_c(string, '}');
    ret = string->str;
    g_string_free(string, false);
    return ret;
}
Exemplo n.º 19
0
void feed_parser_atom10_start(void *data, const gchar *el, const gchar **attr)
{
	FeedParserCtx *ctx = (FeedParserCtx *)data;
	gchar *a = NULL;

	if( ctx->depth == 1 ) {

		if( !strcmp(el, "entry") ) {
			/* Start of new feed item found.
			 * Create a new FeedItem, freeing the one we already have, if any. */
			if( ctx->curitem != NULL )
				feed_item_free(ctx->curitem);
			ctx->curitem = feed_item_new(ctx->feed);
			ctx->location = FEED_LOC_ATOM10_ENTRY;
		} else if( !strcmp(el, "author") ) {
			/* Start of author info for the feed found.
			 * Set correct location. */
			ctx->location = FEED_LOC_ATOM10_AUTHOR;
		} else if( !strcmp(el, "link") ) {
			if (!feed_parser_get_attribute_value(attr, "rel")) {
				/* Link tag for the feed */
				g_free(ctx->feed->link);
				ctx->feed->link =
					g_strdup(feed_parser_get_attribute_value(attr, "href"));
			}
		} else ctx->location = FEED_LOC_ATOM10_NONE;

	} else if( ctx->depth == 2 ) {

		/* Make sure we are in one of known locations within the XML structure.
		 * This condition should never be true on a valid Atom feed. */
		if (ctx->location != FEED_LOC_ATOM10_AUTHOR &&
				ctx->location != FEED_LOC_ATOM10_ENTRY) {
			ctx->depth++;
			return;
		}

		if( !strcmp(el, "author") ) {
			/* Start of author info for current feed item.
			 * Set correct location. */
			ctx->location = FEED_LOC_ATOM10_AUTHOR;
		} else if( !strcmp(el, "link") ) {
			/* Capture item URL, from the "url" XML attribute. */
			if (ctx->curitem && ctx->location == FEED_LOC_ATOM10_ENTRY)
				ctx->curitem->url = g_strdup(feed_parser_get_attribute_value(attr, "href"));
		} else if( !strcmp(el, "source") ) {
			ctx->location = FEED_LOC_ATOM10_SOURCE;
		} else ctx->location = FEED_LOC_ATOM10_ENTRY;

		if( !strcmp(el, "title") && ctx->curitem != NULL) {
			a = feed_parser_get_attribute_value(attr, "type");
			if( !a || !strcmp(a, "text") )
				ctx->curitem->title_format = FEED_ITEM_TITLE_TEXT;
			else if( !strcmp(a, "html") )
				ctx->curitem->title_format = FEED_ITEM_TITLE_HTML;
			else if( !strcmp(a, "xhtml") )
				ctx->curitem->title_format = FEED_ITEM_TITLE_XHTML;
			else
				ctx->curitem->title_format = FEED_ITEM_TITLE_UNKNOWN;
		} else if (!strcmp(el, "content") && ctx->curitem != NULL) {
			ctx->location = FEED_LOC_ATOM10_CONTENT;
			a = feed_parser_get_attribute_value(attr, "type");
			if (a && !strcmp(a, "xhtml")) {
				ctx->curitem->xhtml_content = TRUE;
				ctx->xhtml_str = g_string_new(NULL);
			}
		}
	} else if (ctx->depth >= 3) {
		if (ctx->location == FEED_LOC_ATOM10_CONTENT
				&& ctx->curitem != NULL
				&& ctx->curitem->xhtml_content) {
			guint i;
			GString *txt = ctx->xhtml_str;
			g_string_append_c(txt, '<');
			g_string_append(txt, el);

			for (i = 0; attr[i] != NULL && attr[i+1] != NULL; i += 2) {
				g_string_append_printf(txt, " %s='%s'", attr[i], attr[i+1]);
			}
			g_string_append_c(txt, '>');
		}
	}


	ctx->depth++;
}
Exemplo n.º 20
0
static void
do_percent_subst (EggDesktopFile *desktop_file,
		  char            code,
		  GString        *str,
		  GSList        **documents,
		  gboolean        in_single_quotes,
		  gboolean        in_double_quotes)
{
  GSList *d;
  char *doc;

  switch (code)
    {
    case '%':
      g_string_append_c (str, '%');
      break;

    case 'F':
    case 'U':
      for (d = *documents; d; d = d->next)
	{
	  doc = d->data;
	  g_string_append (str, " ");
	  append_quoted_word (str, doc, in_single_quotes, in_double_quotes);
	}
      *documents = NULL;
      break;

    case 'f':
    case 'u':
      if (*documents)
	{
	  doc = (*documents)->data;
	  g_string_append (str, " ");
	  append_quoted_word (str, doc, in_single_quotes, in_double_quotes);
	  *documents = (*documents)->next;
	}
      break;

    case 'i':
      if (desktop_file->icon)
	{
	  g_string_append (str, "--icon ");
	  append_quoted_word (str, desktop_file->icon,
			      in_single_quotes, in_double_quotes);
	}
      break;

    case 'c':
      if (desktop_file->name)
	{
	  append_quoted_word (str, desktop_file->name,
			      in_single_quotes, in_double_quotes);
	}
      break;

    case 'k':
      if (desktop_file->source)
	{
	  append_quoted_word (str, desktop_file->source,
			      in_single_quotes, in_double_quotes);
	}
      break;

    case 'D':
    case 'N':
    case 'd':
    case 'n':
    case 'v':
    case 'm':
      /* Deprecated; skip */
      break;

    default:
      g_warning ("Unrecognized %%-code '%%%c' in Exec", code);
      break;
    }
}
Exemplo n.º 21
0
static void
gimp_tag_popup_toggle_tag (GimpTagPopup *popup,
                           PopupTagData *tag_data)
{
    gchar    **current_tags;
    GString   *tag_str;
    gint       length;
    gint       i;
    gboolean   tag_toggled_off = FALSE;

    if (tag_data->state == GTK_STATE_NORMAL)
    {
        tag_data->state = GTK_STATE_SELECTED;
    }
    else if (tag_data->state == GTK_STATE_SELECTED)
    {
        tag_data->state = GTK_STATE_NORMAL;
    }
    else
    {
        return;
    }

    current_tags = gimp_tag_entry_parse_tags (GIMP_TAG_ENTRY (popup->combo_entry));
    tag_str = g_string_new ("");
    length = g_strv_length (current_tags);
    for (i = 0; i < length; i++)
    {
        if (! gimp_tag_compare_with_string (tag_data->tag, current_tags[i]))
        {
            tag_toggled_off = TRUE;
        }
        else
        {
            if (tag_str->len)
            {
                g_string_append (tag_str, gimp_tag_entry_get_separator ());
                g_string_append_c (tag_str, ' ');
            }

            g_string_append (tag_str, current_tags[i]);
        }
    }

    if (! tag_toggled_off)
    {
        /* this tag was not selected yet, so it needs to be toggled on */

        if (tag_str->len)
        {
            g_string_append (tag_str, gimp_tag_entry_get_separator ());
            g_string_append_c (tag_str, ' ');
        }

        g_string_append (tag_str, gimp_tag_get_name (tag_data->tag));
    }

    gimp_tag_entry_set_tag_string (GIMP_TAG_ENTRY (popup->combo_entry),
                                   tag_str->str);

    g_string_free (tag_str, TRUE);
    g_strfreev (current_tags);

    if (GIMP_TAG_ENTRY (popup->combo_entry)->mode == GIMP_TAG_ENTRY_MODE_QUERY)
    {
        GimpTaggedContainer *container;

        container = GIMP_TAG_ENTRY (popup->combo_entry)->container;

        for (i = 0; i < popup->tag_count; i++)
        {
            if (popup->tag_data[i].state != GTK_STATE_SELECTED)
            {
                popup->tag_data[i].state = GTK_STATE_INSENSITIVE;
            }
        }

        gimp_container_foreach (GIMP_CONTAINER (container),
                                (GFunc) gimp_tag_popup_check_can_toggle,
                                popup);
    }
}
Exemplo n.º 22
0
static char *
parse_exec (EggDesktopFile  *desktop_file,
	    GSList         **documents,
	    GError         **error)
{
  char *exec, *p, *command;
  gboolean escape, single_quot, double_quot;
  GString *gs;

  exec = g_key_file_get_string (desktop_file->key_file,
				EGG_DESKTOP_FILE_GROUP,
				EGG_DESKTOP_FILE_KEY_EXEC,
				error);
  if (!exec)
    return NULL;

  /* Build the command */
  gs = g_string_new (NULL);
  escape = single_quot = double_quot = FALSE;

  for (p = exec; *p != '\0'; p++)
    {
      if (escape)
	{
	  escape = FALSE;
	  g_string_append_c (gs, *p);
	}
      else if (*p == '\\')
	{
	  if (!single_quot)
	    escape = TRUE;
	  g_string_append_c (gs, *p);
	}
      else if (*p == '\'')
	{
	  g_string_append_c (gs, *p);
	  if (!single_quot && !double_quot)
	    single_quot = TRUE;
	  else if (single_quot)
	    single_quot = FALSE;
	}
      else if (*p == '"')
	{
	  g_string_append_c (gs, *p);
	  if (!single_quot && !double_quot)
	    double_quot = TRUE;
	  else if (double_quot)
	    double_quot = FALSE;
	}
      else if (*p == '%' && p[1])
	{
	  do_percent_subst (desktop_file, p[1], gs, documents,
			    single_quot, double_quot);
	  p++;
	}
      else
	g_string_append_c (gs, *p);
    }

  g_free (exec);
  command = g_string_free (gs, FALSE);

  /* Prepend "xdg-terminal " if needed (FIXME: use gvfs) */
  if (g_key_file_has_key (desktop_file->key_file,
			  EGG_DESKTOP_FILE_GROUP,
			  EGG_DESKTOP_FILE_KEY_TERMINAL,
			  NULL))
    {
      GError *terminal_error = NULL;
      gboolean use_terminal =
	g_key_file_get_boolean (desktop_file->key_file,
				EGG_DESKTOP_FILE_GROUP,
				EGG_DESKTOP_FILE_KEY_TERMINAL,
				&terminal_error);
      if (terminal_error)
	{
	  g_free (command);
	  g_propagate_error (error, terminal_error);
	  return NULL;
	}

      if (use_terminal)
	{
	  gs = g_string_new ("xdg-terminal ");
	  append_quoted_word (gs, command, FALSE, FALSE);
	  g_free (command);
	  command = g_string_free (gs, FALSE);
	}
    }

  return command;
}
Exemplo n.º 23
0
static void
g_scanner_get_token_ll	(GScanner	*scanner,
			 GTokenType	*token_p,
			 GTokenValue	*value_p,
			 guint		*line_p,
			 guint		*position_p)
{
  GScannerConfig *config;
  GTokenType	   token;
  gboolean	   in_comment_multi;
  gboolean	   in_comment_single;
  gboolean	   in_string_sq;
  gboolean	   in_string_dq;
  GString	  *gstring;
  GTokenValue	   value;
  guchar	   ch;
  
  config = scanner->config;
  (*value_p).v_int64 = 0;
  
  if ((scanner->text >= scanner->text_end && scanner->input_fd < 0) ||
      scanner->token == G_TOKEN_EOF)
    {
      *token_p = G_TOKEN_EOF;
      return;
    }
  
  in_comment_multi = FALSE;
  in_comment_single = FALSE;
  in_string_sq = FALSE;
  in_string_dq = FALSE;
  gstring = NULL;
  
  do /* while (ch != 0) */
    {
      gboolean dotted_float = FALSE;
      
      ch = g_scanner_get_char (scanner, line_p, position_p);
      
      value.v_int64 = 0;
      token = G_TOKEN_NONE;
      
      /* this is *evil*, but needed ;(
       * we first check for identifier first character, because	 it
       * might interfere with other key chars like slashes or numbers
       */
      if (config->scan_identifier &&
	  ch && strchr (config->cset_identifier_first, ch))
	goto identifier_precedence;
      
      switch (ch)
	{
	case 0:
	  token = G_TOKEN_EOF;
	  (*position_p)++;
	  /* ch = 0; */
	  break;
	  
	case '/':
	  if (!config->scan_comment_multi ||
	      g_scanner_peek_next_char (scanner) != '*')
	    goto default_case;
	  g_scanner_get_char (scanner, line_p, position_p);
	  token = G_TOKEN_COMMENT_MULTI;
	  in_comment_multi = TRUE;
	  gstring = g_string_new (NULL);
	  while ((ch = g_scanner_get_char (scanner, line_p, position_p)) != 0)
	    {
	      if (ch == '*' && g_scanner_peek_next_char (scanner) == '/')
		{
		  g_scanner_get_char (scanner, line_p, position_p);
		  in_comment_multi = FALSE;
		  break;
		}
	      else
		gstring = g_string_append_c (gstring, ch);
	    }
	  ch = 0;
	  break;
	  
	case '\'':
	  if (!config->scan_string_sq)
	    goto default_case;
	  token = G_TOKEN_STRING;
	  in_string_sq = TRUE;
	  gstring = g_string_new (NULL);
	  while ((ch = g_scanner_get_char (scanner, line_p, position_p)) != 0)
	    {
	      if (ch == '\'')
		{
		  in_string_sq = FALSE;
		  break;
		}
	      else
		gstring = g_string_append_c (gstring, ch);
	    }
	  ch = 0;
	  break;
	  
	case '"':
	  if (!config->scan_string_dq)
	    goto default_case;
	  token = G_TOKEN_STRING;
	  in_string_dq = TRUE;
	  gstring = g_string_new (NULL);
	  while ((ch = g_scanner_get_char (scanner, line_p, position_p)) != 0)
	    {
	      if (ch == '"')
		{
		  in_string_dq = FALSE;
		  break;
		}
	      else
		{
		  if (ch == '\\')
		    {
		      ch = g_scanner_get_char (scanner, line_p, position_p);
		      switch (ch)
			{
			  guint	i;
			  guint	fchar;
			  
			case 0:
			  break;
			  
			case '\\':
			  gstring = g_string_append_c (gstring, '\\');
			  break;
			  
			case 'n':
			  gstring = g_string_append_c (gstring, '\n');
			  break;
			  
			case 't':
			  gstring = g_string_append_c (gstring, '\t');
			  break;
			  
			case 'r':
			  gstring = g_string_append_c (gstring, '\r');
			  break;
			  
			case 'b':
			  gstring = g_string_append_c (gstring, '\b');
			  break;
			  
			case 'f':
			  gstring = g_string_append_c (gstring, '\f');
			  break;
			  
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			  i = ch - '0';
			  fchar = g_scanner_peek_next_char (scanner);
			  if (fchar >= '0' && fchar <= '7')
			    {
			      ch = g_scanner_get_char (scanner, line_p, position_p);
			      i = i * 8 + ch - '0';
			      fchar = g_scanner_peek_next_char (scanner);
			      if (fchar >= '0' && fchar <= '7')
				{
				  ch = g_scanner_get_char (scanner, line_p, position_p);
				  i = i * 8 + ch - '0';
				}
			    }
			  gstring = g_string_append_c (gstring, i);
			  break;
			  
			default:
			  gstring = g_string_append_c (gstring, ch);
			  break;
			}
		    }
		  else
		    gstring = g_string_append_c (gstring, ch);
		}
	    }
	  ch = 0;
	  break;
	  
	case '.':
	  if (!config->scan_float)
	    goto default_case;
	  token = G_TOKEN_FLOAT;
	  dotted_float = TRUE;
	  ch = g_scanner_get_char (scanner, line_p, position_p);
	  goto number_parsing;
	  
	case '$':
	  if (!config->scan_hex_dollar)
	    goto default_case;
	  token = G_TOKEN_HEX;
	  ch = g_scanner_get_char (scanner, line_p, position_p);
	  goto number_parsing;
	  
	case '0':
	  if (config->scan_octal)
	    token = G_TOKEN_OCTAL;
	  else
	    token = G_TOKEN_INT;
	  ch = g_scanner_peek_next_char (scanner);
	  if (config->scan_hex && (ch == 'x' || ch == 'X'))
	    {
	      token = G_TOKEN_HEX;
	      g_scanner_get_char (scanner, line_p, position_p);
	      ch = g_scanner_get_char (scanner, line_p, position_p);
	      if (ch == 0)
		{
		  token = G_TOKEN_ERROR;
		  value.v_error = G_ERR_UNEXP_EOF;
		  (*position_p)++;
		  break;
		}
	      if (g_scanner_char_2_num (ch, 16) < 0)
		{
		  token = G_TOKEN_ERROR;
		  value.v_error = G_ERR_DIGIT_RADIX;
		  ch = 0;
		  break;
		}
	    }
	  else if (config->scan_binary && (ch == 'b' || ch == 'B'))
	    {
	      token = G_TOKEN_BINARY;
	      g_scanner_get_char (scanner, line_p, position_p);
	      ch = g_scanner_get_char (scanner, line_p, position_p);
	      if (ch == 0)
		{
		  token = G_TOKEN_ERROR;
		  value.v_error = G_ERR_UNEXP_EOF;
		  (*position_p)++;
		  break;
		}
	      if (g_scanner_char_2_num (ch, 10) < 0)
		{
		  token = G_TOKEN_ERROR;
		  value.v_error = G_ERR_NON_DIGIT_IN_CONST;
		  ch = 0;
		  break;
		}
	    }
	  else
	    ch = '0';
	  /* fall through */
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	number_parsing:
	{
          gboolean in_number = TRUE;
	  gchar *endptr;
	  
	  if (token == G_TOKEN_NONE)
	    token = G_TOKEN_INT;
	  
	  gstring = g_string_new (dotted_float ? "0." : NULL);
	  gstring = g_string_append_c (gstring, ch);
	  
	  do /* while (in_number) */
	    {
	      gboolean is_E;
	      
	      is_E = token == G_TOKEN_FLOAT && (ch == 'e' || ch == 'E');
	      
	      ch = g_scanner_peek_next_char (scanner);
	      
	      if (g_scanner_char_2_num (ch, 36) >= 0 ||
		  (config->scan_float && ch == '.') ||
		  (is_E && (ch == '+' || ch == '-')))
		{
		  ch = g_scanner_get_char (scanner, line_p, position_p);
		  
		  switch (ch)
		    {
		    case '.':
		      if (token != G_TOKEN_INT && token != G_TOKEN_OCTAL)
			{
			  value.v_error = token == G_TOKEN_FLOAT ? G_ERR_FLOAT_MALFORMED : G_ERR_FLOAT_RADIX;
			  token = G_TOKEN_ERROR;
			  in_number = FALSE;
			}
		      else
			{
			  token = G_TOKEN_FLOAT;
			  gstring = g_string_append_c (gstring, ch);
			}
		      break;
		      
		    case '0':
		    case '1':
		    case '2':
		    case '3':
		    case '4':
		    case '5':
		    case '6':
		    case '7':
		    case '8':
		    case '9':
		      gstring = g_string_append_c (gstring, ch);
		      break;
		      
		    case '-':
		    case '+':
		      if (token != G_TOKEN_FLOAT)
			{
			  token = G_TOKEN_ERROR;
			  value.v_error = G_ERR_NON_DIGIT_IN_CONST;
			  in_number = FALSE;
			}
		      else
			gstring = g_string_append_c (gstring, ch);
		      break;
		      
		    case 'e':
		    case 'E':
		      if ((token != G_TOKEN_HEX && !config->scan_float) ||
			  (token != G_TOKEN_HEX &&
			   token != G_TOKEN_OCTAL &&
			   token != G_TOKEN_FLOAT &&
			   token != G_TOKEN_INT))
			{
			  token = G_TOKEN_ERROR;
			  value.v_error = G_ERR_NON_DIGIT_IN_CONST;
			  in_number = FALSE;
			}
		      else
			{
			  if (token != G_TOKEN_HEX)
			    token = G_TOKEN_FLOAT;
			  gstring = g_string_append_c (gstring, ch);
			}
		      break;
		      
		    default:
		      if (token != G_TOKEN_HEX)
			{
			  token = G_TOKEN_ERROR;
			  value.v_error = G_ERR_NON_DIGIT_IN_CONST;
			  in_number = FALSE;
			}
		      else
			gstring = g_string_append_c (gstring, ch);
		      break;
		    }
		}
	      else
		in_number = FALSE;
	    }
	  while (in_number);
	  
	  endptr = NULL;
	  if (token == G_TOKEN_FLOAT)
	    value.v_float = g_strtod (gstring->str, &endptr);
	  else
	    {
	      guint64 ui64 = 0;
	      switch (token)
		{
		case G_TOKEN_BINARY:
		  ui64 = g_ascii_strtoull (gstring->str, &endptr, 2);
		  break;
		case G_TOKEN_OCTAL:
		  ui64 = g_ascii_strtoull (gstring->str, &endptr, 8);
		  break;
		case G_TOKEN_INT:
		  ui64 = g_ascii_strtoull (gstring->str, &endptr, 10);
		  break;
		case G_TOKEN_HEX:
		  ui64 = g_ascii_strtoull (gstring->str, &endptr, 16);
		  break;
		default: ;
		}
	      if (scanner->config->store_int64)
		value.v_int64 = ui64;
	      else
		value.v_int = ui64;
	    }
	  if (endptr && *endptr)
	    {
	      token = G_TOKEN_ERROR;
	      if (*endptr == 'e' || *endptr == 'E')
		value.v_error = G_ERR_NON_DIGIT_IN_CONST;
	      else
		value.v_error = G_ERR_DIGIT_RADIX;
	    }
	  g_string_free (gstring, TRUE);
	  gstring = NULL;
	  ch = 0;
	} /* number_parsing:... */
	break;
	
	default:
	default_case:
	{
	  if (config->cpair_comment_single &&
	      ch == config->cpair_comment_single[0])
	    {
	      token = G_TOKEN_COMMENT_SINGLE;
	      in_comment_single = TRUE;
	      gstring = g_string_new (NULL);
	      ch = g_scanner_get_char (scanner, line_p, position_p);
	      while (ch != 0)
		{
		  if (ch == config->cpair_comment_single[1])
		    {
		      in_comment_single = FALSE;
		      ch = 0;
		      break;
		    }
		  
		  gstring = g_string_append_c (gstring, ch);
		  ch = g_scanner_get_char (scanner, line_p, position_p);
		}
	    }
	  else if (config->scan_identifier && ch &&
		   strchr (config->cset_identifier_first, ch))
	    {
	    identifier_precedence:
	      
	      if (config->cset_identifier_nth && ch &&
		  strchr (config->cset_identifier_nth,
			  g_scanner_peek_next_char (scanner)))
		{
		  token = G_TOKEN_IDENTIFIER;
		  gstring = g_string_new (NULL);
		  gstring = g_string_append_c (gstring, ch);
		  do
		    {
		      ch = g_scanner_get_char (scanner, line_p, position_p);
		      gstring = g_string_append_c (gstring, ch);
		      ch = g_scanner_peek_next_char (scanner);
		    }
		  while (ch && strchr (config->cset_identifier_nth, ch));
		  ch = 0;
		}
	      else if (config->scan_identifier_1char)
		{
		  token = G_TOKEN_IDENTIFIER;
		  value.v_identifier = g_new0 (gchar, 2);
		  value.v_identifier[0] = ch;
		  ch = 0;
		}
	    }
	  if (ch)
	    {
	      if (config->char_2_token)
		token = ch;
	      else
		{
		  token = G_TOKEN_CHAR;
		  value.v_char = ch;
		}
	      ch = 0;
	    }
	} /* default_case:... */
	break;
	}
      g_assert (ch == 0 && token != G_TOKEN_NONE); /* paranoid */
    }
  while (ch != 0);
  
  if (in_comment_multi || in_comment_single ||
      in_string_sq || in_string_dq)
    {
      token = G_TOKEN_ERROR;
      if (gstring)
	{
	  g_string_free (gstring, TRUE);
	  gstring = NULL;
	}
      (*position_p)++;
      if (in_comment_multi || in_comment_single)
	value.v_error = G_ERR_UNEXP_EOF_IN_COMMENT;
      else /* (in_string_sq || in_string_dq) */
	value.v_error = G_ERR_UNEXP_EOF_IN_STRING;
    }
  
  if (gstring)
    {
      value.v_string = gstring->str;
      g_string_free (gstring, FALSE);
      gstring = NULL;
    }
  
  if (token == G_TOKEN_IDENTIFIER)
    {
      if (config->scan_symbols)
	{
	  GScannerKey *key;
	  guint scope_id;
	  
	  scope_id = scanner->scope_id;
	  key = g_scanner_lookup_internal (scanner, scope_id, value.v_identifier);
	  if (!key && scope_id && scanner->config->scope_0_fallback)
	    key = g_scanner_lookup_internal (scanner, 0, value.v_identifier);
	  
	  if (key)
	    {
	      g_free (value.v_identifier);
	      token = G_TOKEN_SYMBOL;
	      value.v_symbol = key->value;
	    }
	}
      
      if (token == G_TOKEN_IDENTIFIER &&
	  config->scan_identifier_NULL &&
	  strlen (value.v_identifier) == 4)
	{
	  gchar *null_upper = "NULL";
	  gchar *null_lower = "null";
	  
	  if (scanner->config->case_sensitive)
	    {
	      if (value.v_identifier[0] == null_upper[0] &&
		  value.v_identifier[1] == null_upper[1] &&
		  value.v_identifier[2] == null_upper[2] &&
		  value.v_identifier[3] == null_upper[3])
		token = G_TOKEN_IDENTIFIER_NULL;
	    }
	  else
	    {
	      if ((value.v_identifier[0] == null_upper[0] ||
		   value.v_identifier[0] == null_lower[0]) &&
		  (value.v_identifier[1] == null_upper[1] ||
		   value.v_identifier[1] == null_lower[1]) &&
		  (value.v_identifier[2] == null_upper[2] ||
		   value.v_identifier[2] == null_lower[2]) &&
		  (value.v_identifier[3] == null_upper[3] ||
		   value.v_identifier[3] == null_lower[3]))
		token = G_TOKEN_IDENTIFIER_NULL;
	    }
	}
    }
  
  *token_p = token;
  *value_p = value;
}
Exemplo n.º 24
0
static struct http_parsing_result_s
http_parse(struct http_parser_s *parser, const guint8 *data, gsize available)
{
	gsize consumed = 0;

	struct http_parsing_result_s _build_rc(int status, const gchar *msg) {
		struct http_parsing_result_s rc;
		if (msg)
			parser->error = NEWERROR(0, "%s", msg);
		rc.status = status;
		rc.consumed = consumed;
		return rc;
	}

	while (consumed < available) {
		guint8 d = data[consumed];
		gint64 max;
		switch (parser->step) {

			case STEP_FIRST_R0:
				if (d == '\r')
					parser->step = STEP_FIRST_N0;
				else
					g_string_append_c(parser->buf, d);
				++ consumed;
				continue;

			case STEP_FIRST_N0:
				if (d == '\n') {
					if (!_manage_and_renew_command(parser, parser->buf))
						return _build_rc(HPRC_ERROR, "CMD parsing error");
					parser->step = STEP_SEP_R0;
					++ consumed;
					continue;
				}
				return _build_rc(HPRC_ERROR, "CMD parsing error");

			case STEP_SEP_R0:
				if (d == '\r')
					parser->step = STEP_SEP_N0;
				else {
					if (!_manage_and_renew_header(parser, parser->buf))
						return _build_rc(HPRC_ERROR, "HDR parsing error");
					g_string_append_c(parser->buf, d);
					parser->step = STEP_HEADERS_R0;
				}
				++ consumed;
				continue;

			case STEP_SEP_N0:
				if (d == '\n') {
					++ consumed;
					if (!_manage_and_renew_header(parser, parser->buf))
						return _build_rc(HPRC_ERROR, "HDR parsing error");
					parser->step = STEP_BODY_ASIS;
					if (parser->content_read >= parser->content_length)
						return _build_rc(HPRC_SUCCESS, NULL);
					continue;
				}
				return _build_rc(HPRC_ERROR, "SEP parsing error");

			case STEP_HEADERS_R0:
				if (d == '\r')
					parser->step = STEP_HEADERS_N0;
				else
					g_string_append_c(parser->buf, d);
				++ consumed;
				continue;

			case STEP_HEADERS_N0:
				if (d == '\n') {
					parser->step = STEP_SEP_R0;
					++ consumed;
					continue;
				}
				return _build_rc(HPRC_ERROR, "HDR parsing error");

			case STEP_BODY_ASIS:
				max = available - consumed;
				if (max > (parser->content_length - parser->content_read))
					max = parser->content_length - parser->content_read;
				if (parser->body_provider)
					parser->body_provider(data+consumed, max);
				consumed += max;
				parser->content_read += max;

				if (parser->content_read >= parser->content_length)
					return _build_rc(HPRC_SUCCESS, NULL);
				continue;
		}
	}

	return _build_rc(HPRC_MORE, NULL);
}
Exemplo n.º 25
0
static void
set_preview_widget (TablePreferences *tpref)
{
	GtkWidget *preview = NULL;
	GtkTreeIter iter;

	if (!tpref->priv->current_column)
		return;

	if (gtk_combo_box_get_active_iter (GTK_COMBO_BOX (tpref->priv->plugins_combo), &iter)) {
		GdauiPlugin *plugin;
		GtkTreeModel *model;
		GType gtype;

		gtype = tpref->priv->current_column->gtype;
		
		model = tpref->priv->plugins_model;
		gtk_tree_model_get (model, &iter, PL_COLUMN_PLUGIN, &plugin, -1);
		if (plugin) {
			GString *string = NULL;
			if (tpref->priv->options_wid) {
				GdaSet *plist;
				GSList *list;
				
				plist = gdaui_basic_form_get_data_set (GDAUI_BASIC_FORM (tpref->priv->options_wid));
				for (list = plist->holders; list; list = list->next) {
					GdaHolder *holder;
					holder = GDA_HOLDER (list->data);
					if (gda_holder_is_valid (holder)) {
						const GValue *cvalue;
						cvalue = gda_holder_get_value (holder);
						if (cvalue && (G_VALUE_TYPE (cvalue) != GDA_TYPE_NULL)) {
							gchar *str = gda_value_stringify (cvalue);
							gchar *r1, *r2;
							if (!string)
								string = g_string_new ("");
							else
								g_string_append_c (string, ';');
							r1 = gda_rfc1738_encode (gda_holder_get_id (holder));
							r2 = gda_rfc1738_encode (str);
							g_free (str);
							g_string_append_printf (string, "%s=%s", r1, r2);
							g_free (r1);
							g_free (r2);
						}
					}
				}
			}
			if (string) {
				g_string_prepend_c (string, ':');
				g_string_prepend (string, plugin->plugin_name);
				preview = GTK_WIDGET (gdaui_new_data_entry (gtype, string->str));
				g_string_free (string, TRUE);
			}
			else
				preview = GTK_WIDGET (gdaui_new_data_entry (gtype, plugin->plugin_name));
		}
		else
			preview = GTK_WIDGET (gdaui_new_data_entry (gtype, NULL));
	}

	GValue *prev_value = NULL;
	if (tpref->priv->preview_wid) {
		prev_value = gdaui_data_entry_get_value (GDAUI_DATA_ENTRY (tpref->priv->preview_wid));
		gtk_widget_destroy (tpref->priv->preview_wid);
		gtk_widget_show (tpref->priv->preview_none);
		tpref->priv->preview_wid = NULL;
	}
	if (preview) {
		if (prev_value &&
		    (G_VALUE_TYPE (prev_value) == gdaui_data_entry_get_value_type (GDAUI_DATA_ENTRY (preview))))
			gdaui_data_entry_set_value (GDAUI_DATA_ENTRY (preview), prev_value);
		gdaui_data_entry_set_attributes (GDAUI_DATA_ENTRY (preview),
						 0, GDA_VALUE_ATTR_ACTIONS_SHOWN);
		tpref->priv->preview_wid = preview;
		gtk_box_pack_start (GTK_BOX (tpref->priv->preview_vbox), preview, TRUE, TRUE, 0);
		gtk_widget_hide (tpref->priv->preview_none);
		gtk_widget_show (tpref->priv->preview_wid);
	}
	if (prev_value)
		gda_value_free (prev_value);
}
Exemplo n.º 26
0
/* Save all settings, return 0 on success.  */
static int
save_settings (SettingsDlg *dialog)
{
  GtkWidget *errwdg;

  if (!dialog->modified)
    return 0;  /* No need to save anything.  */

  if ((errwdg = check_default_key (dialog)))
    {
      gtk_widget_grab_focus (errwdg);
      return -1;
    }

#ifdef ENABLE_KEYSERVER_SUPPORT
  if (!dialog->gnupg21)
    {
      if ((errwdg = check_default_keyserver (dialog)))
        {
          gpa_window_error
            (_("The URL given for the keyserver is not valid."),
             GTK_WIDGET (dialog));
          gtk_widget_grab_focus (errwdg);
          return -1;
        }
    }
#endif /*ENABLE_KEYSERVER_SUPPORT*/

  if ( dialog->akl.enabled && (errwdg = check_akl (dialog)))
    {
      gpa_window_error
        (_("The data given for \"Auto key locate\" is not valid."),
         GTK_WIDGET (dialog));
      gtk_widget_grab_focus (errwdg);
      return -1;
    }

  gpa_options_set_default_key (gpa_options_get_instance (),
 			       dialog->default_key.key);


#ifdef ENABLE_KEYSERVER_SUPPORT
  if (!dialog->gnupg21)
    gpa_options_set_default_keyserver (gpa_options_get_instance (),
                                       dialog->keyserver.url);
#endif /*ENABLE_KEYSERVER_SUPPORT*/

  if (!dialog->akl.enabled)
    ;
  else if (dialog->akl.method_idx == -1)
    ; /* oops: none selected.  */
  else if (!akl_table[dialog->akl.method_idx].list)
    {
      /* Custom setting: Do nothing.  */
    }
  else
    {
      const char *methods = akl_table[dialog->akl.method_idx].list;
      GString *newakl;

      newakl = g_string_new ("");
      for (; *methods; methods++)
        {
          if (newakl->len)
            g_string_append_c (newakl, ',');
          switch (*methods)
            {
            case 'n':
              g_string_append (newakl, "nodefault");
              break;
            case 'l':
              g_string_append (newakl, "local");
              break;
            case 'c':
              g_string_append (newakl, "cert");
              break;
            case 'L':
              g_string_append (newakl, "ldap");
              break;
            case 'k':
              g_string_append (newakl, "keyserver");
              break;
            case 'D':
              g_string_append_printf (newakl,
                                      "kdns://%s/?at=_kdnscert&usevc=1",
                                      dialog->akl.ip_addr ?
                                      dialog->akl.ip_addr : "");
              break;
            default:
              if (newakl->len)
                g_string_truncate (newakl, newakl->len - 1);
              break;
            }
        }
      gpa_store_gpgconf_string ("gpg", "auto-key-locate", newakl->str);
      g_string_free (newakl, TRUE);
    }
  return 0;
}
Exemplo n.º 27
0
/*
 * parses @str, and appends to @string lines which are @width large, if @offset is >0, then
 * leave that amount of spaces. If @width <= 0, then only adds @offset spaces at the beginning of each
 * new line.
 */
static void
append_to_string (GString *string, gchar *str, gint width, gint offset)
{
	g_assert (string);
	if (!str)
		return;
	if ((width <= 0) && (offset <= 0)) {
		g_string_append (string, str);
		return;
	}
	if (offset < 0)
		offset = 0;

	/* replace @WORD@ by <WORD> */
	gchar *ptr;
	gboolean in = FALSE;
	for (ptr = str; *ptr; ptr++) {
		if (*ptr == '@') {
			if (in) {
				*ptr = '>';
				in = FALSE;
			}
			else {
				*ptr = '<';
				in = TRUE;
			}
		}
	}

	/* actual work */
	gboolean firstword = TRUE;
	gint clen = 0;
	if ((string->str) && (string->len > 0) &&
	    (string->str[string->len - 1] != '\n')) {
		for (ptr = string->str + (string->len -1); (ptr >= string->str) && (*ptr != '\n'); ptr --)
			clen++;
	}
	if (!strcmp (str, "> ")) {
		if (offset > 0) {
			gint i;
			for (i = 0; i < offset; i++)
				g_string_append_c (string, ' ');
		}
		g_string_append (string, str);
		return;
	}

	for (ptr = str; *ptr; ) {
		/* skip spaces */
		if ((*ptr == ' ') || (*ptr == '\t') || (*ptr == '\n') || (*ptr == '\r')) {
			ptr++;
			continue;
		}

		/* find end of next word */
		gchar *next;
		gint wlen;
		for (wlen = 0, next = ptr;
		     *next && (*next != ' ') && (*next != '\t') && (*next != '\n') && (*next != '\r');
		     wlen ++, next = g_utf8_next_char (next));

		if (wlen >= width - offset) {
			const gchar *n2;
			for (n2 = ptr; n2 < next; n2++) {
				g_string_append_c (string, *n2);
			}
			ptr = next;
			firstword = FALSE;
			g_string_append_c (string, '\n');
			clen = 0;
			continue;
		}
		else if ((width > 0) && ((wlen + clen) >= width)) {
			/* cut here */
			g_string_append_c (string, '\n');
			clen = 0;
			continue;
		}
		else {
			/* copy word */
			if (clen == 0) {
				if (offset > 0) {
					gint i;
					for (i = 0; i < offset; i++) {
						g_string_append_c (string, ' ');
						clen++;
					}
				}
			}
			else if (!firstword) {
				g_string_append_c (string, ' ');
				clen++;
			}
			const gchar *n2;
			for (n2 = ptr; n2 < next; n2++) {
				g_string_append_c (string, *n2);
				clen++;
			}
			ptr = next;
			firstword = FALSE;
		}
	}
}
Exemplo n.º 28
0
static gchar *
tmplayer_parse_line (ParserState * state, const gchar * line, guint line_num)
{
  GstClockTime ts = GST_CLOCK_TIME_NONE;
  const gchar *text_start = NULL;
  gboolean multiline = FALSE;
  gchar *ret = NULL;
  gchar divc = '\0';
  guint h, m, s, l = 1;

  if (sscanf (line, "%u:%02u:%02u,%u%c", &h, &m, &s, &l, &divc) == 5 &&
      (divc == '=')) {
    GST_LOG ("multiline format %u %u %u %u", h, m, s, l);
    ts = GST_SECOND * ((((h * 60) + m) * 60) + s);
    text_start = strchr (line, '=');
    multiline = TRUE;
  } else if (sscanf (line, "%u:%02u:%02u%c", &h, &m, &s, &divc) == 4 &&
      (divc == '=' || divc == ':')) {
    GST_LOG ("single line format %u %u %u %u %c", h, m, s, l, divc);
    ts = GST_SECOND * ((((h * 60) + m) * 60) + s);
    text_start = strchr (line + 6, divc);
  } else if (line[0] == '\0' && state->buf->len > 0 &&
      GST_CLOCK_TIME_IS_VALID (state->start_time)) {
    /* if we get an empty line (could be the end of the file, but doesn't have
     * to be), just push whatever is still in the buffer without a duration */
    GST_LOG ("empty line, and there's still text in the buffer");
    ret = tmplayer_process_buffer (state);
    state->duration = GST_CLOCK_TIME_NONE;
    return ret;
  } else {
    GST_WARNING ("failed to parse line: '%s'", line);
    return NULL;
  }

  /* if this is a line without text, or the first line in a multiline file,
   * process and return the data in the buffer, which is the previous line(s) */
  if (text_start == NULL || text_start[1] == '\0' ||
      (l == 1 && state->buf->len > 0)) {

    if (GST_CLOCK_TIME_IS_VALID (state->start_time) &&
        state->start_time < ts && line_num > 0) {
      ret = tmplayer_process_buffer (state);
      state->duration = ts - state->start_time;
      /* ..and append current line's text (if there is any) for the next round.
       * We don't have to store ts as pending_start_time, since we deduce the
       * durations from the start times anyway, so as long as the parser just
       * forwards state->start_time by duration after it pushes the line we
       * are about to return it will all be good. */
      g_string_append (state->buf, text_start + 1);
    } else if (line_num > 0) {
      GST_WARNING ("end of subtitle unit but no valid start time?!");
    }
  } else {
    if (l > 1)
      g_string_append_c (state->buf, '\n');
    g_string_append (state->buf, text_start + 1);
    state->start_time = ts;
  }

  GST_LOG ("returning: '%s'", GST_STR_NULL (ret));
  return ret;
}
Exemplo n.º 29
0
static gint sc_speller_check_word(GeanyDocument *doc, gint line_number, const gchar *word,
						   gint start_pos, gint end_pos)
{
	gsize n_suggs = 0;
	gchar *word_to_check;
	gint offset;

	g_return_val_if_fail(sc_speller_dict != NULL, 0);
	g_return_val_if_fail(doc != NULL, 0);
	g_return_val_if_fail(word != NULL, 0);
	g_return_val_if_fail(start_pos >= 0 && end_pos >= 0, 0);

	if (EMPTY(word))
		return 0;

	/* ignore numbers or words starting with digits */
	if (isdigit(*word))
		return 0;

	/* ignore non-text */
	if (! sc_speller_is_text(doc, start_pos))
		return 0;

	/* strip punctuation and white space */
	word_to_check = strip_word(word, &offset);
	if (! NZV(word_to_check))
	{
		g_free(word_to_check);
		return 0;
	}

	/* recalculate start_pos and end_pos */
	start_pos += offset;
	end_pos = start_pos + strlen(word_to_check);

	/* early out if the word is spelled correctly */
	if (enchant_dict_check(sc_speller_dict, word_to_check, -1) == 0)
	{
		g_free(word_to_check);
		return 0;
	}

	editor_indicator_set_on_range(doc->editor, GEANY_INDICATOR_ERROR, start_pos, end_pos);

	if (sc_info->use_msgwin && line_number != -1)
	{
		gsize j;
		gchar **suggs;
		GString *str;

		str = g_string_sized_new(256);
		suggs = enchant_dict_suggest(sc_speller_dict, word_to_check, -1, &n_suggs);
		if (suggs != NULL)
		{
			g_string_append_printf(str, "line %d: %s | ",  line_number + 1, word_to_check);

			g_string_append(str, _("Try: "));

			/* Now find the misspellings in the line, limit suggestions to a maximum of 15 (for now) */
			for (j = 0; j < MIN(n_suggs, 15); j++)
			{
				g_string_append(str, suggs[j]);
				g_string_append_c(str, ' ');
			}

			msgwin_msg_add(COLOR_RED, line_number + 1, doc, "%s", str->str);

			if (suggs != NULL && n_suggs > 0)
				enchant_dict_free_string_list(sc_speller_dict, suggs);
		}
		g_string_free(str, TRUE);
	}

	g_free(word_to_check);
	return n_suggs;
}
Exemplo n.º 30
0
static cb_ret_t
enter (WInput * lc_cmdline)
{
    char *cmd = lc_cmdline->buffer;

    if (!command_prompt)
        return MSG_HANDLED;

    /* Any initial whitespace should be removed at this point */
    while (*cmd == ' ' || *cmd == '\t' || *cmd == '\n')
        cmd++;

    if (!*cmd)
        return MSG_HANDLED;

    if (strncmp (cmd, "cd ", 3) == 0 || strcmp (cmd, "cd") == 0)
    {
        do_cd_command (cmd);
        input_clean (lc_cmdline);
        return MSG_HANDLED;
    }
    else if (strcmp (cmd, "exit") == 0)
    {
        input_assign_text (lc_cmdline, "");
        if (!quiet_quit_cmd ())
            return MSG_NOT_HANDLED;
    }
    else
    {
        GString *command;
        size_t i;

        if (!vfs_current_is_local ())
        {
            message (D_ERROR, MSG_ERROR, _("Cannot execute commands on non-local filesystems"));
            return MSG_NOT_HANDLED;
        }
#ifdef ENABLE_SUBSHELL
        /* Check this early before we clean command line
         * (will be checked again by shell_execute) */
        if (mc_global.tty.use_subshell && subshell_state != INACTIVE)
        {
            message (D_ERROR, MSG_ERROR, _("The shell is already running a command"));
            return MSG_NOT_HANDLED;
        }
#endif
        command = g_string_sized_new (32);

        for (i = 0; cmd[i] != '\0'; i++)
        {
            if (cmd[i] != '%')
                g_string_append_c (command, cmd[i]);
            else
            {
                char *s;

                s = expand_format (NULL, cmd[++i], TRUE);
                g_string_append (command, s);
                g_free (s);
            }
        }

        input_clean (lc_cmdline);
        shell_execute (command->str, 0);
        g_string_free (command, TRUE);

#ifdef ENABLE_SUBSHELL
        if ((quit & SUBSHELL_EXIT) != 0)
        {
            if (quiet_quit_cmd ())
                return MSG_HANDLED;

            quit = 0;
            /* restart subshell */
            if (mc_global.tty.use_subshell)
                init_subshell ();
        }

        if (mc_global.tty.use_subshell)
            do_load_prompt ();
#endif
    }
    return MSG_HANDLED;
}