示例#1
0
static gboolean
_ostree_repo_list_refs_internal (OstreeRepo       *self,
                                 gboolean         cut_prefix,
                                 const char       *refspec_prefix,
                                 GHashTable      **out_all_refs,
                                 GCancellable     *cancellable,
                                 GError          **error)
{
  g_autoptr(GHashTable) ret_all_refs = NULL;
  g_autofree char *remote = NULL;
  g_autofree char *ref_prefix = NULL;

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

  if (refspec_prefix)
    {
      struct stat stbuf;
      const char *prefix_path;
      const char *path;

      if (!ostree_parse_refspec (refspec_prefix, &remote, &ref_prefix, error))
        return FALSE;

      if (remote)
        {
          prefix_path = glnx_strjoina ("refs/remotes/", remote, "/");
          path = glnx_strjoina (prefix_path, ref_prefix);
        }
      else
        {
          prefix_path = "refs/heads/";
          path = glnx_strjoina (prefix_path, ref_prefix);
        }

      if (fstatat (self->repo_dir_fd, path, &stbuf, 0) < 0)
        {
          if (errno != ENOENT)
            return glnx_throw_errno (error);
        }
      else
        {
          if (S_ISDIR (stbuf.st_mode))
            {
              glnx_fd_close int base_fd = -1;
              g_autoptr(GString) base_path = g_string_new ("");
              if (!cut_prefix)
                g_string_printf (base_path, "%s/", ref_prefix);

              if (!glnx_opendirat (self->repo_dir_fd, cut_prefix ? path : prefix_path, TRUE, &base_fd, error))
                return FALSE;

              if (!enumerate_refs_recurse (self, remote, base_fd, base_path,
                                           base_fd, cut_prefix ? "." : ref_prefix,
                                           ret_all_refs, cancellable, error))
                return FALSE;
            }
          else
            {
              glnx_fd_close int prefix_dfd = -1;

              if (!glnx_opendirat (self->repo_dir_fd, prefix_path, TRUE, &prefix_dfd, error))
                return FALSE;

              if (!add_ref_to_set (remote, prefix_dfd, ref_prefix, ret_all_refs,
                                   cancellable, error))
                return FALSE;
            }
        }
    }
  else
    {
      g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
      g_autoptr(GString) base_path = g_string_new ("");
      glnx_fd_close int refs_heads_dfd = -1;

      if (!glnx_opendirat (self->repo_dir_fd, "refs/heads", TRUE, &refs_heads_dfd, error))
        return FALSE;

      if (!enumerate_refs_recurse (self, NULL, refs_heads_dfd, base_path,
                                   refs_heads_dfd, ".",
                                   ret_all_refs, cancellable, error))
        return FALSE;

      g_string_truncate (base_path, 0);

      if (!glnx_dirfd_iterator_init_at (self->repo_dir_fd, "refs/remotes", TRUE, &dfd_iter, error))
        return FALSE;

      while (TRUE)
        {
          struct dirent *dent;
          glnx_fd_close int remote_dfd = -1;

          if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, cancellable, error))
            return FALSE;
          if (!dent)
            break;

          if (dent->d_type != DT_DIR)
            continue;

          if (!glnx_opendirat (dfd_iter.fd, dent->d_name, TRUE, &remote_dfd, error))
            return FALSE;

          if (!enumerate_refs_recurse (self, dent->d_name, remote_dfd, base_path,
                                       remote_dfd, ".",
                                       ret_all_refs,
                                       cancellable, error))
            return FALSE;
        }
    }

  ot_transfer_out_value (out_all_refs, &ret_all_refs);
  return TRUE;
}
示例#2
0
void logging_logv(const gchar *msgLogDomain, GLogLevelFlags msgLogLevel,
        const gchar* fileName, const gchar* functionName, const gint lineNumber,
        const gchar *format, va_list vargs) {
    /* this is called by worker threads, so we have access to worker */

    /* see if we can avoid some work because the message is filtered anyway */
    const gchar* logDomainStr = msgLogDomain ? msgLogDomain : "shadow";
    if(worker_isFiltered(msgLogLevel)) {
        return;
    }

    gchar* logFileStr = fileName ? g_path_get_basename(fileName) : g_strdup("n/a");
    const gchar* logFunctionStr = functionName ? functionName : "n/a";
    const gchar* formatStr = format ? format : "n/a";
    const gchar* logLevelStr = _logging_getNewLogLevelString(msgLogLevel);

    SimulationTime currentTime = worker_isAlive() ? worker_getCurrentTime() : SIMTIME_INVALID;
    Host* currentHost = worker_isAlive() ? worker_getCurrentHost() : NULL;
    gint workerThreadID = worker_isAlive() ? worker_getThreadID() : 0;

    /* format the simulation time if we are running an event */
    GString* clockStringBuffer = g_string_new("");
    if(currentTime != SIMTIME_INVALID) {
        SimulationTime hours, minutes, seconds, remainder;
        remainder = currentTime;

        hours = remainder / SIMTIME_ONE_HOUR;
        remainder %= SIMTIME_ONE_HOUR;
        minutes = remainder / SIMTIME_ONE_MINUTE;
        remainder %= SIMTIME_ONE_MINUTE;
        seconds = remainder / SIMTIME_ONE_SECOND;
        remainder %= SIMTIME_ONE_SECOND;

        g_string_printf(clockStringBuffer, "%02"G_GUINT64_FORMAT":%02"G_GUINT64_FORMAT":%02"G_GUINT64_FORMAT".%09"G_GUINT64_FORMAT"",
                hours, minutes, seconds, remainder);
    } else {
        g_string_printf(clockStringBuffer, "n/a");
    }

    /* we'll need to free clockString later */
    gchar* clockString = g_string_free(clockStringBuffer, FALSE);

    /* node identifier, if we are running a node
     * dont free this since we dont own the ip address string */
    GString* nodeStringBuffer = g_string_new("");
    if(currentHost) {
        g_string_printf(nodeStringBuffer, "%s~%s", host_getName(currentHost), host_getDefaultIPName(currentHost));
    } else {
        g_string_printf(nodeStringBuffer, "n/a");
    }
    gchar* nodeString = g_string_free(nodeStringBuffer, FALSE);

    /* the function name - no need to free this */
    GString* newLogFormatBuffer = g_string_new(NULL);
    g_string_printf(newLogFormatBuffer, "[thread-%i] %s [%s-%s] [%s] [%s:%i] [%s] %s",
            workerThreadID, clockString, logDomainStr, logLevelStr, nodeString,
            logFileStr, lineNumber, logFunctionStr, formatStr);

    /* get the new format out of our string buffer and log it */
    gchar* newLogFormat = g_string_free(newLogFormatBuffer, FALSE);
    g_logv(logDomainStr, msgLogLevel, newLogFormat, vargs);

    /* cleanup */
    g_free(logFileStr);
    g_free(newLogFormat);
    g_free(clockString);
    g_free(nodeString);
}
示例#3
0
const char *
sftpfs_fix_filename (const char *file_name)
{
    g_string_printf (sftpfs_filename_buffer, "%c%s", PATH_SEP, file_name);
    return sftpfs_filename_buffer->str;
}
gboolean working_area_button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
{
	// Local variables
	gint				box_height;					// Height of the bounding box
	gint				box_width;					// Width of the bounding box
	GList				*collision_list = NULL;
	guint				count_int;
	gint				finish_x;					// X position at the layer objects finish time
	gint				finish_y;					// Y position at the layer objects finish time
	GList				*layer_pointer;
	GString				*message;					// Used to construct message strings
	guint				num_collisions;
	gint				onscreen_bottom;			// Y coordinate of bounding box bottom
	gint				onscreen_left;				// X coordinate of bounding box left
	gint				onscreen_right;				// X coordinate of bounding box right
	gint				onscreen_top;				// Y coordinate of bounding box top
	gint				pixmap_height;				// Height of the front store
	gint				pixmap_width;				// Width of the front store
	gfloat				scaled_height_ratio;		// Used to calculate a vertical scaling ratio
	gfloat				scaled_width_ratio;			// Used to calculate a horizontal scaling ratio
	gint				selected_row;				// Holds the number of the row that is selected
	gint				start_x;					// X position at the layer objects start time
	gint				start_y;					// Y position at the layer objects start time
	layer 				*this_layer_data;			// Pointer to the data for the selected layer
	slide				*this_slide_data;			// Alias to make things easier
	guint				tmp_int;					// Temporary integer


	// Only do this function if we have a front store available and a project loaded
	if ((NULL == get_front_store()) || (FALSE == get_project_active()))
	{
		return TRUE;
	}

	// Set the delete key focus to be layers
	set_delete_focus(FOCUS_LAYER);

	// Change the focus of the window to be this widget
	gtk_widget_grab_focus(GTK_WIDGET(widget));

	// Initialise some things
	this_slide_data = get_current_slide_data();
	gdk_drawable_get_size(GDK_PIXMAP(get_front_store()), &pixmap_width, &pixmap_height);

	// Check for primary mouse button click
	if (1 != event->button)
	{
		// Not a primary mouse click, so return
		return TRUE;
	}

	// Reset the mouse drag toggle
	set_mouse_dragging(FALSE);

	// Check if this was a double mouse click.  If it was, open an edit dialog
	if (GDK_2BUTTON_PRESS == event->type)
	{
		// Open an edit dialog
		layer_edit();

		return TRUE;
	}

	// Check if this was a triple mouse click.  If it was, ignore it
	if (GDK_3BUTTON_PRESS == event->type)
	{
		return TRUE;
	}

	// If we're presently creating a new highlight layer, store the mouse coordinates
	if (TYPE_HIGHLIGHT == get_new_layer_selected())
	{
		// Save the mouse coordinates
		set_stored_x(event->x);
		set_stored_y(event->y);

		// Reset the invalidation area
		set_invalidation_end_x(event->x);
		set_invalidation_end_y(event->y);
		set_invalidation_start_x(event->x - 1);
		set_invalidation_start_y(event->y - 1);

		return TRUE;
	}

	// If the user has clicked on the start or end points for the selected layer, we
	// don't want to do the collision detection below that changes layers
	if (END_POINTS_INACTIVE == get_end_point_status())
	{
		// * Check if the user is clicking on the layer start or end points *

		// Calculate the height and width scaling values for the main drawing area at its present size
		scaled_height_ratio = (gfloat) get_project_height() / (gfloat) pixmap_height;
		scaled_width_ratio = (gfloat) get_project_width() / (gfloat) pixmap_width;

		// Determine which row is selected in the time line
		selected_row = time_line_get_selected_layer_num(this_slide_data->timeline_widget);
		layer_pointer = g_list_first(this_slide_data->layers);
		this_layer_data = g_list_nth_data(layer_pointer, selected_row);

		// If the layer data isn't accessible, then don't run this function
		if (NULL == this_layer_data)
		{
			return TRUE;
		}

		// Calculate start and end points
		finish_x = (this_layer_data->x_offset_finish / scaled_width_ratio) + END_POINT_HORIZONTAL_OFFSET;
		finish_y = (this_layer_data->y_offset_finish / scaled_height_ratio) + END_POINT_VERTICAL_OFFSET;
		start_x = (this_layer_data->x_offset_start / scaled_width_ratio) + END_POINT_HORIZONTAL_OFFSET;
		start_y = (this_layer_data->y_offset_start / scaled_height_ratio) + END_POINT_VERTICAL_OFFSET;

		// Is the user clicking on an end point?
		if (((event->x >= start_x)							// Start point
			&& (event->x <= start_x + END_POINT_WIDTH)
			&& (event->y >= start_y)
			&& (event->y <= start_y + END_POINT_HEIGHT)) ||
			((event->x >= finish_x)							// End point
			&& (event->x <= finish_x + END_POINT_WIDTH)
			&& (event->y >= finish_y)
			&& (event->y <= finish_y + END_POINT_HEIGHT)))
		{
			// Retrieve the layer size information
			switch (this_layer_data->object_type)
			{
				case TYPE_EMPTY:
					// We can't drag an empty layer, so reset things and return
					set_mouse_dragging(FALSE);
					set_end_point_status(END_POINTS_INACTIVE);
					set_stored_x(-1);
					set_stored_y(-1);
					return TRUE;

				case TYPE_HIGHLIGHT:
					box_width = ((layer_highlight *) this_layer_data->object_data)->width;
					box_height = ((layer_highlight *) this_layer_data->object_data)->height;
					break;

				case TYPE_GDK_PIXBUF:
					// If this is the background layer, then we ignore it
					if (TRUE == this_layer_data->background)
					{
						set_mouse_dragging(FALSE);
						set_end_point_status(END_POINTS_INACTIVE);
						set_stored_x(-1);
						set_stored_y(-1);
						return TRUE;
					}

					// No it's not, so process it
					box_width = ((layer_image *) this_layer_data->object_data)->width;
					box_height = ((layer_image *) this_layer_data->object_data)->height;
					break;

				case TYPE_MOUSE_CURSOR:
					box_width = ((layer_mouse *) this_layer_data->object_data)->width;
					box_height = ((layer_mouse *) this_layer_data->object_data)->height;
					break;

				case TYPE_TEXT:
					box_width = ((layer_text *) this_layer_data->object_data)->rendered_width;
					box_height = ((layer_text *) this_layer_data->object_data)->rendered_height;
					break;

				default:
					message = g_string_new(NULL);
					g_string_printf(message, "%s ED377: %s", _("Error"), _("Unknown layer type."));
					display_warning(message->str);
					g_string_free(message, TRUE);

					return TRUE;  // Unknown layer type, so no idea how to extract the needed data for the next code
			}

			// Work out the bounding box boundaries (scaled)
			if ((event->x >= start_x)							// Left
				&& (event->x <= start_x + END_POINT_WIDTH)		// Right
				&& (event->y >= start_y)						// Top
				&& (event->y <= start_y + END_POINT_HEIGHT))	// Bottom
			{
				// Start point clicked
				onscreen_left = this_layer_data->x_offset_start / scaled_width_ratio;
				onscreen_top = this_layer_data->y_offset_start / scaled_width_ratio;;
				onscreen_right = (this_layer_data->x_offset_start + box_width) / scaled_height_ratio;
				onscreen_bottom = (this_layer_data->y_offset_start + box_height) / scaled_height_ratio;
			} else
			{
				// End point clicked
				onscreen_left = this_layer_data->x_offset_finish / scaled_width_ratio;
				onscreen_top = this_layer_data->y_offset_finish / scaled_width_ratio;;
				onscreen_right = (this_layer_data->x_offset_finish + box_width) / scaled_height_ratio;
				onscreen_bottom = (this_layer_data->y_offset_finish + box_height) / scaled_height_ratio;
			}

			// Ensure the bounding box doesn't go out of bounds
			onscreen_left = CLAMP(onscreen_left, 2, pixmap_width - 2);
			onscreen_top = CLAMP(onscreen_top, 2, pixmap_height - 2);
			onscreen_right = CLAMP(onscreen_right, 2, pixmap_width - 2);
			onscreen_bottom = CLAMP(onscreen_bottom, 2, pixmap_height - 2);

			// Draw a bounding box onscreen
			draw_bounding_box(onscreen_left, onscreen_top, onscreen_right, onscreen_bottom);

			// End point clicked, so we return in order to avoid the collision detection
			return TRUE;
		}
	}

	// * Do collision detection here to determine if the user has clicked on a layer's object *

	this_slide_data = get_current_slide_data();
	calculate_object_boundaries();
	collision_list = detect_collisions(collision_list, event->x, event->y);
	if (NULL == collision_list)
	{
		// If there was no collision, then select the background layer
		time_line_set_selected_layer_num(this_slide_data->timeline_widget, this_slide_data->num_layers - 1);  // *Needs* the -1, don't remove

		// Clear any existing handle box
		gdk_draw_drawable(GDK_DRAWABLE(get_main_drawing_area()->window), GDK_GC(get_main_drawing_area()->style->fg_gc[GTK_WIDGET_STATE(get_main_drawing_area())]),
				GDK_PIXMAP(get_front_store()), 0, 0, 0, 0, -1, -1);

		// Reset the stored mouse coordinates
		set_stored_x(-1);
		set_stored_y(-1);

		// Free the memory allocated during the collision detection
		g_list_free(collision_list);
		collision_list = NULL;

		return TRUE;
	}

	// * To get here there must have been at least one collision *

	// Save the mouse coordinates
	set_stored_x(event->x);
	set_stored_y(event->y);

	// Determine which layer the user has selected in the timeline
	selected_row = time_line_get_selected_layer_num(this_slide_data->timeline_widget);

	// Is the presently selected layer in the collision list?
	collision_list = g_list_first(collision_list);
	num_collisions = g_list_length(collision_list);
	for (count_int = 0; count_int < num_collisions; count_int++)
	{
		collision_list = g_list_first(collision_list);
		collision_list = g_list_nth(collision_list, count_int);
		layer_pointer = g_list_first(this_slide_data->layers);
		tmp_int = g_list_position(layer_pointer, ((boundary_box *) collision_list->data)->layer_ptr);
		if (tmp_int == selected_row)
		{
			// Return if the presently selected row is in the collision list, as we don't want to change our selected layer
			return TRUE;
		}
	}

	// * To get here, the presently selected layer wasn't in the collision list *

	// The presently selected row is not in the collision list, so move the selection row to the first collision
	collision_list = g_list_first(collision_list);
	selected_row = g_list_position(this_slide_data->layers, ((boundary_box *) collision_list->data)->layer_ptr);
	time_line_set_selected_layer_num(this_slide_data->timeline_widget, selected_row);

	// Draw a handle box around the new selected object
	draw_handle_box();

	// Free the memory allocated during the collision detection
	g_list_free(collision_list);
	collision_list = NULL;

	return TRUE;
}
示例#5
0
文件: main.c 项目: harbop/spop
void spop_log_handler(const gchar* log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data) {
    GString* log_line = NULL;
    GDateTime* datetime;
    gchar* timestr;

    GError* err = NULL;
    gchar* level = "";

    /* Convert log_level to a string */
    if (log_level & G_LOG_LEVEL_ERROR)
        level = "ERR ";
    else if (log_level & G_LOG_LEVEL_CRITICAL)
        level = "CRIT";
    else if (log_level & G_LOG_LEVEL_WARNING)
        level = "WARN";
    else if (log_level & G_LOG_LEVEL_MESSAGE)
        level = "MSG ";
    else if (log_level & G_LOG_LEVEL_INFO) {
        if (!verbose_mode) return;
        level = "INFO";
    }
    else if (log_level & G_LOG_LEVEL_DEBUG) {
        if (!debug_mode) return;
        level = "DBG ";
    }
    else if (log_level & G_LOG_LEVEL_LIBSPOTIFY)
        level = "SPTF";
    else
        g_warn_if_reached();

    /* Allocate memory and read date/time */
    log_line = g_string_sized_new(1024);
    if (!log_line)
        g_error("Can't allocate memory.");

    datetime = g_date_time_new_now_local();
    if (!datetime)
        g_error("Can't get the current date.");
    timestr = g_date_time_format(datetime, "%Y-%m-%d %H:%M:%S");
    if (!timestr)
        g_error("Can't format current date to a string.");

    /* Format the message that will be displayed and logged */
    if (log_domain)
        g_string_printf(log_line, "%s ", log_domain);
    g_string_append_printf(log_line, "%s [%s] %s\n", timestr, level, message);

    /* Free memory used by datetime and timestr */
    g_date_time_unref(datetime);
    g_free(timestr);

    /* First display to stderr... */
    fprintf(stderr, "%s", log_line->str);
    /* ... then to the log file. */
    if (g_log_channel) {
        if (g_io_channel_write_chars(g_log_channel, log_line->str, log_line->len, NULL, &err) != G_IO_STATUS_NORMAL)
            g_error("Can't write to log file: %s", err->message);
        if (g_io_channel_flush(g_log_channel, &err) != G_IO_STATUS_NORMAL)
            g_error("Can't flush log file: %s", err->message);
    }
}
示例#6
0
static gboolean on_update_dlg(gpointer user_data)
{
    FmProgressDisplay* data = (FmProgressDisplay*)user_data;
    gdouble elapsed;

    char* data_transferred_str;
    char trans_size_str[128];
    char total_size_str[128];

    if (g_source_is_destroyed(g_main_current_source()) || data->dlg == NULL)
        return FALSE;
    data->update_timeout = 0;
    /* the g_strdup very probably returns the same pointer that was g_free'd
       so we cannot just compare data->old_cur_file with data->cur_file */
    if(data->cur_file && data->current)
    {
        g_string_printf(data->str, "<i>%s %s</i>", data->op_text, data->cur_file);
        gtk_label_set_markup(data->current, data->str->str);
        gtk_widget_set_tooltip_text(GTK_WIDGET(data->current), data->cur_file);
        g_free(data->old_cur_file);
        data->old_cur_file = data->cur_file;
        data->cur_file = NULL;
    }
    g_string_printf(data->str, "%d %%", data->percent);
    gtk_progress_bar_set_fraction(data->progress, (gdouble)data->percent/100);
    gtk_progress_bar_set_text(data->progress, data->str->str);

    /* display the amount of data transferred */
    fm_file_size_to_str(trans_size_str, sizeof(trans_size_str),
        data->data_transferred_size, fm_config->si_unit);
    fm_file_size_to_str(total_size_str, sizeof(total_size_str),
        data->data_total_size, fm_config->si_unit);
    data_transferred_str = g_strdup_printf("%s / %s", trans_size_str, total_size_str);
    gtk_label_set_text(data->data_transferred, data_transferred_str);
    g_free(data_transferred_str);

    elapsed = g_timer_elapsed(data->timer, NULL);
    if(elapsed >= 0.5 && data->percent > 0)
    {
        gdouble remaining = elapsed * (100 - data->percent) / data->percent;
        if(data->remaining_time)
        {
            char time_str[32];
            guint secs = (guint)remaining;
            guint mins = 0;
            guint hrs = 0;
            if(secs >= 60)
            {
                mins = secs / 60;
                secs %= 60;
                if(mins >= 60)
                {
                    hrs = mins / 60;
                    mins %= 60;
                }
            }
            g_snprintf(time_str, 32, "%02d:%02d:%02d", hrs, mins, secs);
            gtk_label_set_text(data->remaining_time, time_str);
        }
    }
    return FALSE;
}
示例#7
0
/**
 * seahorse_util_uris_package
 * @package: Package uri
 * @uris: null-terminated array of uris to package
 *
 * Package uris into an archive. The uris must be local.
 *
 * Returns: Success or failure
 */
gboolean
seahorse_util_uris_package (const gchar* package, const char** uris)
{
    GError* err = NULL;
    gchar *out = NULL;
    gint status;
    gboolean r;
    GString *str;
    gchar *cmd;
    gchar *t;
    gchar *x;
    GFile *file, *fpackage;

    fpackage = g_file_new_for_uri (package);
    t = g_file_get_path (fpackage);
    x = g_shell_quote (t);
    g_free (t);

    /* create execution */
    str = g_string_new ("");
    g_string_printf (str, "file-roller --add-to=%s", x);
    g_free(x);

    while(*uris) {
        x = g_uri_parse_scheme (*uris);
        if (x)
            file = g_file_new_for_uri (*uris);
        else
            file = g_file_new_for_path (*uris);
        g_free (x);

        t = g_file_get_path (file);
        g_object_unref (file);
        g_return_val_if_fail (t != NULL, FALSE);

        x = g_shell_quote(t);
        g_free(t);

        g_string_append_printf (str, " %s", x);
        g_free(x);

        uris++;
    }

    /* Execute the command */
    cmd = g_string_free (str, FALSE);
    r = g_spawn_command_line_sync (cmd, &out, NULL, &status, &err);
    g_free (cmd);

    if (out) {
        g_print (out, NULL);
        g_free (out);
    }

    if (!r) {
        seahorse_util_handle_error (err, _("Couldn't run file-roller"));
        return FALSE;
    }

    if(!(WIFEXITED(status) && WEXITSTATUS(status) == 0)) {
        seahorse_util_show_error(NULL, _("Couldn't package files"),
                                 _("The file-roller process did not complete successfully"));
        return FALSE;
    }

    t = g_file_get_path (fpackage);
    if (t != NULL) {
        g_chmod (t, S_IRUSR | S_IWUSR);
        g_free (t);
    }

    return TRUE;
}
示例#8
0
文件: wtap.c 项目: pstavirs/wireshark
gchar *
wtap_get_debug_if_descr(const wtapng_if_descr_t *if_descr,
                        const int indent,
                        const char* line_end)
{
	GString *info = g_string_new("");

	g_assert(if_descr);

	g_string_printf(info,
			"%*cName = %s%s", indent, ' ',
			if_descr->if_name ? if_descr->if_name : "UNKNOWN",
			line_end);

	g_string_append_printf(info,
			"%*cDescription = %s%s", indent, ' ',
			if_descr->if_description ? if_descr->if_description : "NONE",
			line_end);

	g_string_append_printf(info,
			"%*cEncapsulation = %s (%d/%u - %s)%s", indent, ' ',
			wtap_encap_string(if_descr->wtap_encap),
			if_descr->wtap_encap,
			if_descr->link_type,
			wtap_encap_short_string(if_descr->wtap_encap),
			line_end);

	g_string_append_printf(info,
			"%*cSpeed = %" G_GINT64_MODIFIER "u%s", indent, ' ',
			if_descr->if_speed,
			line_end);

	g_string_append_printf(info,
			"%*cCapture length = %u%s", indent, ' ',
			if_descr->snap_len,
			line_end);

	g_string_append_printf(info,
			"%*cFCS length = %d%s", indent, ' ',
			if_descr->if_fcslen,
			line_end);

	g_string_append_printf(info,
			"%*cTime precision = %s (%d)%s", indent, ' ',
			wtap_tsprec_string(if_descr->tsprecision),
			if_descr->tsprecision,
			line_end);

	g_string_append_printf(info,
			"%*cTime ticks per second = %" G_GINT64_MODIFIER "u%s", indent, ' ',
			if_descr->time_units_per_second,
			line_end);

	g_string_append_printf(info,
			"%*cTime resolution = 0x%.2x%s", indent, ' ',
			if_descr->if_tsresol,
			line_end);

	g_string_append_printf(info,
			"%*cFilter string = %s%s", indent, ' ',
			if_descr->if_filter_str ? if_descr->if_filter_str : "NONE",
			line_end);

	g_string_append_printf(info,
			"%*cOperating system = %s%s", indent, ' ',
			if_descr->if_os ? if_descr->if_os : "UNKNOWN",
			line_end);

	g_string_append_printf(info,
			"%*cComment = %s%s", indent, ' ',
			if_descr->opt_comment ? if_descr->opt_comment : "NONE",
			line_end);

	g_string_append_printf(info,
			"%*cBPF filter length = %u%s", indent, ' ',
			if_descr->bpf_filter_len,
			line_end);

	g_string_append_printf(info,
			"%*cNumber of stat entries = %u%s", indent, ' ',
			if_descr->num_stat_entries,
			line_end);

	return g_string_free(info, FALSE);
}
示例#9
0
static void
send_http_request (CockpitHttpStream *self)
{
  CockpitChannel *channel = COCKPIT_CHANNEL (self);
  JsonObject *options;
  gboolean had_host;
  gboolean had_encoding;
  const gchar *method;
  const gchar *path;
  GString *string = NULL;
  JsonNode *node;
  JsonObject *headers;
  const gchar *header;
  const gchar *value;
  GList *request = NULL;
  GList *names = NULL;
  GBytes *bytes;
  GList *l;
  gsize total;

  options = cockpit_channel_get_options (channel);

  /*
   * The checks we do here for token validity are just enough to be able
   * to format an HTTP response, without leaking across lines etc.
   */

  if (!cockpit_json_get_string (options, "path", NULL, &path))
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: bad \"path\" field in HTTP stream request", self->name);
      goto out;
    }
  else if (path == NULL)
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: missing \"path\" field in HTTP stream request", self->name);
      goto out;
    }
  else if (!cockpit_web_response_is_simple_token (path))
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: invalid \"path\" field in HTTP stream request", self->name);
      goto out;
    }

  if (!cockpit_json_get_string (options, "method", NULL, &method))
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: bad \"method\" field in HTTP stream request", self->name);
      goto out;
    }
  else if (method == NULL)
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: missing \"method\" field in HTTP stream request", self->name);
      goto out;
    }
  else if (!cockpit_web_response_is_simple_token (method))
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: invalid \"method\" field in HTTP stream request", self->name);
      goto out;
    }

  g_debug ("%s: sending %s request", self->name, method);

  string = g_string_sized_new (128);
  g_string_printf (string, "%s %s HTTP/1.1\r\n", method, path);

  had_encoding = had_host = FALSE;

  node = json_object_get_member (options, "headers");
  if (node)
    {
      if (!JSON_NODE_HOLDS_OBJECT (node))
        {
          cockpit_channel_fail (channel, "protocol-error",
                                "%s: invalid \"headers\" field in HTTP stream request", self->name);
          goto out;
        }

      headers = json_node_get_object (node);
      names = json_object_get_members (headers);
      for (l = names; l != NULL; l = g_list_next (l))
        {
          header = l->data;
          if (!cockpit_web_response_is_simple_token (header))
            {
              cockpit_channel_fail (channel, "protocol-error",
                                    "%s: invalid header in HTTP stream request: %s", self->name, header);
              goto out;
            }
          node = json_object_get_member (headers, header);
          if (!node || !JSON_NODE_HOLDS_VALUE (node) || json_node_get_value_type (node) != G_TYPE_STRING)
            {
              cockpit_channel_fail (channel, "protocol-error",
                                    "%s: invalid header value in HTTP stream request: %s", self->name, header);
              goto out;
            }
          value = json_node_get_string (node);
          if (disallowed_header (header, value, self->binary))
            {
              cockpit_channel_fail (channel, "protocol-error",
                                    "%s: disallowed header in HTTP stream request: %s", self->name, header);
              goto out;
            }
          if (!cockpit_web_response_is_header_value (value))
            {
              cockpit_channel_fail (channel, "protocol-error",
                                    "%s: invalid header value in HTTP stream request: %s", self->name, header);
              goto out;
            }

          g_string_append_printf (string, "%s: %s\r\n", (gchar *)l->data, value);
          g_debug ("%s: sending header: %s %s", self->name, (gchar *)l->data, value);

          if (g_ascii_strcasecmp (l->data, "Host") == 0)
            had_host = TRUE;
          if (g_ascii_strcasecmp (l->data, "Accept-Encoding") == 0)
            had_encoding = TRUE;
        }
    }

  if (!had_host)
    {
      g_string_append (string, "Host: ");
      g_string_append_uri_escaped (string, self->client->connectable->name, "[]!%$&()*+,-.:;=\\_~", FALSE);
      g_string_append (string, "\r\n");
    }
  if (!had_encoding)
    g_string_append (string, "Accept-Encoding: identity\r\n");

  if (!self->binary)
    g_string_append (string, "Accept-Charset: UTF-8\r\n");

  request = g_list_reverse (self->request);
  self->request = NULL;

  /* Calculate how much data we have to send */
  total = 0;
  for (l = request; l != NULL; l = g_list_next (l))
    total += g_bytes_get_size (l->data);

  if (request || g_ascii_strcasecmp (method, "POST") == 0)
    g_string_append_printf (string, "Content-Length: %" G_GSIZE_FORMAT "\r\n", total);
  g_string_append (string, "\r\n");

  bytes = g_string_free_to_bytes (string);
  string = NULL;

  cockpit_stream_write (self->stream, bytes);
  g_bytes_unref (bytes);

  /* Now send all the data */
  for (l = request; l != NULL; l = g_list_next (l))
    cockpit_stream_write (self->stream, l->data);

out:
  g_list_free (names);
  g_list_free_full (request, (GDestroyNotify)g_bytes_unref);
  if (string)
    g_string_free (string, TRUE);
}
示例#10
0
/* Writes the value of the constant in 'tree' to file handle 'of' */
static char *
orbit_cbe_get_const(IDL_tree tree)
{
  char *opc = NULL, *retval, *ctmp;
  GString *tmpstr = g_string_new(NULL);

  switch(IDL_NODE_TYPE(tree)) {
  case IDLN_BOOLEAN:
    g_string_printf(tmpstr, "%s", IDL_BOOLEAN(tree).value?"CORBA_TRUE":"CORBA_FALSE");
    break;
  case IDLN_CHAR:
    g_string_printf(tmpstr, "'\\x%X'", *(unsigned char *)IDL_CHAR(tree).value);
    break;
  case IDLN_FLOAT:
    g_string_printf(tmpstr, "%f", IDL_FLOAT(tree).value);
    break;
  case IDLN_INTEGER:
    g_string_printf(tmpstr, "%" IDL_LL "d", IDL_INTEGER(tree).value);
    break;
  case IDLN_STRING:
    g_string_printf(tmpstr, "\"%s\"", IDL_STRING(tree).value);
    break;
  case IDLN_WIDE_CHAR:
    g_string_printf(tmpstr, "L'%ls'", IDL_WIDE_CHAR(tree).value);
    break;
  case IDLN_WIDE_STRING:
    g_string_printf(tmpstr, "L\"%ls\"", IDL_WIDE_STRING(tree).value);
    break;
  case IDLN_BINOP:
    g_string_printf(tmpstr, "(");
    ctmp = orbit_cbe_get_const(IDL_BINOP(tree).left);
    g_string_append(tmpstr, ctmp);
    g_free(ctmp);
    switch(IDL_BINOP(tree).op) {
    case IDL_BINOP_OR:
      opc = "|";
      break;
    case IDL_BINOP_XOR:
      opc = "^";
      break;
    case IDL_BINOP_AND:
      opc = "&";
      break;
    case IDL_BINOP_SHR:
      opc = ">>";
      break;
    case IDL_BINOP_SHL:
      opc = "<<";
      break;
    case IDL_BINOP_ADD:
      opc = "+";
      break;
    case IDL_BINOP_SUB:
      opc = "-";
      break;
    case IDL_BINOP_MULT:
      opc = "*";
      break;
    case IDL_BINOP_DIV:
      opc = "/";
      break;
    case IDL_BINOP_MOD:
      opc = "%";
      break;
    }
    g_string_append_printf(tmpstr, " %s ", opc);
    ctmp = orbit_cbe_get_const(IDL_BINOP(tree).right);
    g_string_append_printf(tmpstr, "%s)", ctmp);
    g_free(ctmp);
    break;
  case IDLN_UNARYOP:
    switch(IDL_UNARYOP(tree).op) {
    case IDL_UNARYOP_PLUS: opc = "+"; break;
    case IDL_UNARYOP_MINUS: opc = "-"; break;
    case IDL_UNARYOP_COMPLEMENT: opc = "~"; break;
    }
    ctmp = orbit_cbe_get_const(IDL_UNARYOP(tree).operand);
    g_string_printf(tmpstr, "%s%s", opc, ctmp);
    g_free(ctmp);
    break;
  case IDLN_IDENT:
    {
      char *id;
      id = IDL_ns_ident_to_qstring(IDL_IDENT_TO_NS(tree), "_", 0);
      g_string_printf(tmpstr, "%s", id);
      g_free(id);
    }
    break;
  default:
    g_error("We were asked to print a constant for %s", IDL_tree_type_names[tree->_type]);
    break;
  }

  retval = tmpstr->str;

  g_string_free(tmpstr, FALSE);

  return retval;
}
示例#11
0
static NMCResultCode
parse_command_line (NmCli *nmc, int argc, char **argv)
{
	char *base;

	base = strrchr (argv[0], '/');
	if (base == NULL)
		base = argv[0];
	else
		base++;

	/* parse options */
	while (argc > 1) {
		char *opt = argv[1];
		/* '--' ends options */
		if (strcmp (opt, "--") == 0) {
			argc--; argv++;
			break;
		}
		if (opt[0] != '-')
			break;
		if (opt[1] == '-')
			opt++;
		if (matches (opt, "-terse") == 0) {
			if (nmc->print_output == NMC_PRINT_TERSE) {
				g_string_printf (nmc->return_text, _("Error: Option '--terse' is specified the second time."));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			else if (nmc->print_output == NMC_PRINT_PRETTY) {
				g_string_printf (nmc->return_text, _("Error: Option '--terse' is mutually exclusive with '--pretty'."));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			else
				nmc->print_output = NMC_PRINT_TERSE;
		} else if (matches (opt, "-pretty") == 0) {
			if (nmc->print_output == NMC_PRINT_PRETTY) {
				g_string_printf (nmc->return_text, _("Error: Option '--pretty' is specified the second time."));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			else if (nmc->print_output == NMC_PRINT_TERSE) {
				g_string_printf (nmc->return_text, _("Error: Option '--pretty' is mutually exclusive with '--terse'."));
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			else
				nmc->print_output = NMC_PRINT_PRETTY;
		} else if (matches (opt, "-mode") == 0) {
			nmc->mode_specified = TRUE;
			next_arg (&argc, &argv);
			if (argc <= 1) {
		 		g_string_printf (nmc->return_text, _("Error: missing argument for '%s' option."), opt);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			if (!strcmp (argv[1], "tabular"))
				nmc->multiline_output = FALSE;
			else if (!strcmp (argv[1], "multiline"))
				nmc->multiline_output = TRUE;
			else {
		 		g_string_printf (nmc->return_text, _("Error: '%s' is not valid argument for '%s' option."), argv[1], opt);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
		} else if (matches (opt, "-escape") == 0) {
			next_arg (&argc, &argv);
			if (argc <= 1) {
		 		g_string_printf (nmc->return_text, _("Error: missing argument for '%s' option."), opt);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			if (!strcmp (argv[1], "yes"))
				nmc->escape_values = TRUE;
			else if (!strcmp (argv[1], "no"))
				nmc->escape_values = FALSE;
			else {
		 		g_string_printf (nmc->return_text, _("Error: '%s' is not valid argument for '%s' option."), argv[1], opt);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
		} else if (matches (opt, "-fields") == 0) {
			next_arg (&argc, &argv);
			if (argc <= 1) {
		 		g_string_printf (nmc->return_text, _("Error: fields for '%s' options are missing."), opt);
				nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
				return nmc->return_value;
			}
			nmc->required_fields = g_strdup (argv[1]);
		} else if (matches (opt, "-nocheck") == 0) {
			nmc->nocheck_ver = TRUE;
		} else if (matches (opt, "-version") == 0) {
			printf (_("nmcli tool, version %s\n"), NMCLI_VERSION);
			return NMC_RESULT_SUCCESS;
		} else if (matches (opt, "-help") == 0) {
			usage (base);
			return NMC_RESULT_SUCCESS;
		} else {
			g_string_printf (nmc->return_text, _("Error: Option '%s' is unknown, try 'nmcli -help'."), opt);
			nmc->return_value = NMC_RESULT_ERROR_USER_INPUT;
			return nmc->return_value;
		}
		argc--;
		argv++;
	}

	if (argc > 1)
		return do_cmd (nmc, argv[1], argc-1, argv+1);

	usage (base);
	return nmc->return_value;
}
示例#12
0
int main(
    int              argc,
    char            *argv[])
{

    glob_t                   gbuf;
    int                      grc, i;
    GString                 *cmd;
    GError                  *err = NULL;

    GMainLoop *loop;

    GPtrArray    *child_args     = NULL;

    /* parse options */
    parse_options(&argc, &argv);

    /* set up logging */
    if (!logc_setup(&err)) {
        air_opterr("%s", err->message);
    }

    if (fd_nextdir == NULL) {
        air_opterr("The --nextdir switch is required");
    }

    child_args = g_ptr_array_sized_new(64);
    for (i=1; i < argc; i++) {
        /* Double dash indicates end of filedaemon's arguments */
        if (!strncmp(argv[i], "--", strlen(argv[i])) )
            continue;
        g_ptr_array_add(child_args, g_strdup(argv[i]));
    }
    g_ptr_array_add(child_args, NULL);

    if (child_args->len > 1) {
        if (fd_faildir == NULL) {
            air_opterr("The --faildir switch is required");
        }
    }

    cmd  = g_string_new("");

    loop = g_main_loop_new(NULL, FALSE);

    /* We need an input glob */
    if (!fd_inspec) {
        air_opterr("Input glob must be specified");
    }

    /* If an output destination is provided, make sure it's a directory */
    if (fd_outspec && !g_file_test(fd_outspec, G_FILE_TEST_IS_DIR )) {
        air_opterr("Output is not a directory");
    }

    /* Options check out; daemonize */
    if (!fd_nodaemon) {
        if (!daemonize()) {
            goto end;
        }
    }

    while (1) {
        /* Evaluate glob expression */
        grc = glob(fd_inspec, 0, NULL, &gbuf);

        if (grc == GLOB_NOSPACE) {
            g_error("Out of memory: glob allocation failure");
        }
#ifdef GLOB_NOMATCH
        /* HaX0riffic! Simulate behavior without NOMATCH where we have it. */
        else if (grc == GLOB_NOMATCH) {
            gbuf.gl_pathc = 0;
            gbuf.gl_pathv = NULL;
        }
#endif

        /* Iterate over glob paths, enqueueing. */
        for (i = 0; i < gbuf.gl_pathc; i++) {
            char      **child_envp            = {NULL};
            GError     *child_err             = NULL;

            GString    *filename_in           = NULL;
            GString    *filename_out          = NULL;
            GString    *filename_lock         = NULL;

            GIOChannel *file_in               = NULL;
            GIOChannel *file_out              = NULL;

            GIOChannel *child_stdin           = NULL;
            gint        child_stdin_fd        = -1;

            GIOChannel *child_stdout          = NULL;
            gint        child_stdout_fd       = -1;

            GPid          child_pid;
            int         len;

            fd_read_data_t  read_data;
            fd_write_data_t write_data;

            filename_in = g_string_new(gbuf.gl_pathv[i]);

            /* Skip non-regular files */
            if (!g_file_test(filename_in->str, G_FILE_TEST_IS_REGULAR) ) {
                g_string_free(filename_in, TRUE);
                continue;
            }

            /* Skip lockfiles */
            if (!strcmp(".lock", filename_in->str
                        + strlen(filename_in->str) - 5))
            {
                g_string_free(filename_in, TRUE);
                continue;
            }

            /* Generate lock path */
            if (!filename_lock) filename_lock = g_string_new("");
            g_string_printf(filename_lock, "%s.lock", filename_in->str);

            /* Skip files locked at queue time */
            if (g_file_test(filename_lock->str, G_FILE_TEST_IS_REGULAR)) {
                g_debug("file %s is locked", filename_in->str);
                g_string_free(filename_in, TRUE);
                g_string_free(filename_lock, TRUE);
                continue;
            }

            if (child_args->len == 1) {
                /* Do move or delete */
                GString *destpath = g_string_new("");
                char    *dbase    = NULL;
                /* Calculate move destination path */
                dbase = g_path_get_basename(filename_in->str);

                g_string_printf(destpath, "%s/%s", fd_nextdir, dbase);
                if (dbase) free(dbase);
                /* Do link */
                g_message("moving %s -> %s", filename_in->str, fd_nextdir);
                if (link(filename_in->str, destpath->str) < 0)
                    g_critical(
                        "error moving input file to destination directory: %s",
                        strerror(errno));
                /* Do delete */
                if (unlink(filename_in->str) < 0) {
                    g_critical("error deleting input file");
                }
                g_string_free(destpath, TRUE);
                g_string_free(filename_in, TRUE);
                g_string_free(filename_lock, TRUE);
                continue;
            }

            if (fd_lock) {
                fd_lock_file(filename_in->str);
            }

            file_in = g_io_channel_new_file(filename_in->str, "r", &err);

            if (file_in == NULL) {
                g_critical("Cannot open input file!");
            }

            g_io_channel_set_encoding(file_in, NULL, &err);

            if (err) {
                g_critical("error setting input encoding!");
            }

            g_io_channel_set_buffer_size(file_in, fd_bufsize);

            filename_out = g_string_new("");

            if (fd_outspec == NULL) {
                g_string_printf(filename_out, "%s", gbuf.gl_pathv[i]);
            } else {
                g_string_printf(filename_out, "%s/%s", fd_outspec,
                                gbuf.gl_pathv[i]);
            }

            len  = filename_out->len;

            if (g_strrstr(filename_out->str, ".")) {
                while (len-- > 0
                       && !g_str_has_suffix(filename_out->str, ".") )
                {
                    g_string_set_size(filename_out, filename_out->len - 1);
                }
                g_string_set_size(filename_out, filename_out->len - 1);
            }
            if (fd_outext) {
                g_string_append_printf(filename_out, ".%s", fd_outext);
            } else {
                g_string_append(filename_out, ".out");
            }

            g_message("%d: %s -> %s", i, filename_in->str, filename_out->str);

            file_out = g_io_channel_new_file(filename_out->str, "w", &err);

            if (file_out == NULL) {
                g_error("Cannot open output file!");
            }

            g_io_channel_set_encoding(file_out, NULL, &err);

            if (err) {
                g_error("error setting output encoding!");
            }

            g_io_channel_set_buffer_size(file_out, fd_bufsize);

            if (!g_spawn_async_with_pipes(".",
                                          (gchar **) child_args->pdata,
                                          child_envp,
                                          G_SPAWN_SEARCH_PATH |
                                          G_SPAWN_DO_NOT_REAP_CHILD,
                                          NULL,
                                          NULL,
                                          &child_pid,
                                          &child_stdin_fd,
                                          &child_stdout_fd,
                                          NULL,
                                          &child_err))
            {
                g_error("error spawning process: %s",
                        (child_err && child_err->message ? child_err->
                         message : "unknown error"));
            }
            g_debug("spawned process %d", i);

            /* Watch for process exit status */
            g_child_watch_add(child_pid, on_child_exit, filename_in->str);

            child_stdin = g_io_channel_unix_new(child_stdin_fd);

            if (child_stdin == NULL) {
                g_error("Cannot open child stdin!");
            }

            g_io_channel_set_encoding(child_stdin, NULL, &err);

            if (err) {
                g_error("error setting child stdin encoding!");
            }

            g_io_channel_set_buffer_size(child_stdin, fd_bufsize);

            child_stdout = g_io_channel_unix_new(child_stdout_fd);

            if (child_stdout == NULL) {
                g_error("Cannot open child stdout!");
            }

            g_io_channel_set_encoding(child_stdout, NULL, &err);

            if (err) {
                g_error("error setting child stdout encoding!");
            }


            g_io_channel_set_buffer_size(child_stdout, fd_bufsize);


            write_data.infile = file_in;
            write_data.buf    = g_malloc(g_io_channel_get_buffer_size(file_in));

            if (write_data.buf == NULL) {
                g_error("error allocating file_in buffer");
            }

            if (!g_io_add_watch(child_stdin,  G_IO_OUT | G_IO_PRI | G_IO_HUP |
                                G_IO_ERR, write_to_child, &write_data))
                g_error("Cannot add watch on GIOChannel!");

            read_data.outfile = file_out;
            read_data.loop    = loop;
            read_data.buf     = g_malloc(g_io_channel_get_buffer_size(file_out));

            if (write_data.buf == NULL) {
                g_error("error allocating file_in buffer");
            }

            if (!g_io_add_watch(child_stdout, G_IO_IN | G_IO_PRI | G_IO_HUP |
                                G_IO_ERR, read_from_child, &read_data))
                g_error("Cannot add watch on GIOChannel!");

            g_main_loop_run(loop);

            if (fd_lock) {
                fd_unlock_file(filename_in->str);
            }

            if (read_data.buf) {
                g_free(read_data.buf);
            }
            if (write_data.buf) {
                g_free(write_data.buf);
            }

            g_string_free(filename_in, TRUE);
            g_string_free(filename_out, TRUE);
            g_string_free(filename_lock, TRUE);
        }
        sleep(fd_poll_delay);
    }

  end:

    return 0;
}
GtkTextBuffer *gtk_text_buffer_duplicate(GtkTextBuffer *source_buffer)
{
	// Local variables
	gchar				*conversion_buffer;			// Used when converting between unicode character types
	GtkTextIter			end_iter;
	GtkTextIter			end_iter_minus_one;
	gint				end_offset;
	gint				i;
	guint				loop_counter;
	GtkTextIter 		loop_iter;
	GtkTextBuffer		*new_text_buffer;
	guint				num_tags;
	GtkTextIter			source_buffer_end;
	GtkTextIter			source_buffer_start;
	gint				start_offset;
	GSList				*tag_list;
	GtkTextTag			*tag_ptr;
	gunichar			temp_char;
	GString				*temp_gstring;


	// Validate the tags in the source buffer
	text_layer_dialog_validate_buffer_tag_quantity(GTK_TEXT_BUFFER(source_buffer));

	// Initialise various things
	temp_gstring = g_string_new(NULL);

	// Create a new text buffer
	new_text_buffer = gtk_text_buffer_new(get_text_tags_table());

	// Get the bounds of the source buffer
	gtk_text_buffer_get_bounds(GTK_TEXT_BUFFER(source_buffer), &source_buffer_start, &source_buffer_end);
	gtk_text_iter_order(&source_buffer_start, &source_buffer_end);

	// Scan through the source text buffer one character at a time, getting the character and the tags that apply to it
	start_offset = gtk_text_iter_get_offset(&source_buffer_start);
	end_offset = gtk_text_iter_get_offset(&source_buffer_end);
	for (i = 0; i < end_offset; i++)
	{
		// Copy one character from the source text buffer to the new destination text buffer
		gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(source_buffer), &loop_iter, i);
		temp_char = gtk_text_iter_get_char(&loop_iter);
		conversion_buffer = g_ucs4_to_utf8(&temp_char, 1, NULL, NULL, NULL);
		if (NULL == conversion_buffer)
		{
			g_string_printf(temp_gstring, "%s ED441: %s", _("Error"), _("Could not convert unicode character from ucs4 to utf8."));
			display_warning(temp_gstring->str);
			continue;
		}

		// Validate the retrieved character
		if (TRUE != g_unichar_validate(temp_char))
		{
			// Something other than a unicode character was retrieved
			g_string_printf(temp_gstring, "%s ED442: %s", _("Error"), _("Invalid unicode character found in text."));
			display_warning(temp_gstring->str);
			continue;
		}
		gtk_text_buffer_insert_at_cursor(GTK_TEXT_BUFFER(new_text_buffer), conversion_buffer, -1);
		g_free(conversion_buffer);

		// Copy the tags from the character in the source buffer to the new character in the destination buffer
		tag_list = gtk_text_iter_get_tags(&loop_iter);
		num_tags = g_slist_length(tag_list);
		gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(new_text_buffer), &end_iter);
		end_iter_minus_one = end_iter;
		gtk_text_iter_backward_char(&end_iter_minus_one);
		for (loop_counter = 0; loop_counter < num_tags; loop_counter++)
		{
			// Copy each tag from the source text buffer to the destination one
			tag_ptr = g_slist_nth_data(tag_list, loop_counter);
			gtk_text_buffer_apply_tag(GTK_TEXT_BUFFER(new_text_buffer), tag_ptr, &end_iter_minus_one, &end_iter);
		}
		g_slist_free(tag_list);
	}
	g_string_free(temp_gstring, TRUE);

	// Validate the tags in the duplicated buffer
	text_layer_dialog_validate_buffer_tag_quantity(GTK_TEXT_BUFFER(new_text_buffer));

	// Return the duplicated text buffer
	return new_text_buffer;
}
示例#14
0
/*
 * Main function
 */
int
main(int argc, char* argv[])
{
    GError *parse_error = NULL;
    GOptionContext *context;

    context = g_option_context_new ("- generate non uniform grid of cartesian points in the robot workspace");
    g_option_context_add_main_entries (context, entries, NULL);
    if (!g_option_context_parse(context, &argc, &argv, &parse_error))
    {
        g_print("Options parsing failed: %s\n", parse_error->message);
        g_option_context_free(context);
        exit(1);
    }
    g_option_context_free(context);

    g_print("Using values interval [ %f , %f ], increment: %f \n", t_min, t_max, t_increment);

    DGeometry *geometry = d_geometry_new (a, b, h, r);
    g_print ( "Current geometry [ %f, %f, %f, %f ] \n", a, b, h, r );

    gsl_vector *pos = gsl_vector_alloc(3);
    gsl_vector *axes = gsl_vector_alloc(3);
    GError *err = NULL;

    GFile *out_file = g_file_new_for_path ("workspace.asc");
    GFileOutputStream *out_stream = g_file_replace(out_file,
            NULL,
            FALSE,
            G_FILE_CREATE_NONE,
            NULL,
            NULL);
    GString *buffer = g_string_new(NULL);

    gdouble t1 = t_min;
    gdouble t2 = t_min;
    gdouble t3 = t_min;

    while(t3 <= t_max)
    {
        while (t2 <= t_max)
        {
            while (t1 <= t_max)
            {
                if (verbose)
                {
                    g_print ( "Current axes [ %f, %f, %f ] \n", t1, t2, t3 );
                }
                gsl_vector_set(axes, 0, t1 / 180.0 * G_PI);
                gsl_vector_set(axes, 1, t2 / 180.0 * G_PI);
                gsl_vector_set(axes, 2, t3 / 180.0 * G_PI);
                d_solver_solve_direct (geometry, axes, pos, &err);
                if (err)
                {
                    g_clear_error(&err);
                } else {
                    if (verbose)
                    {
                        g_print ( "Point [ %f, %f, %f ] \n",
                                gsl_vector_get(pos, 0),
                                gsl_vector_get(pos, 1),
                                gsl_vector_get(pos, 2));
                    }
                    g_string_printf(buffer,
                            "%f %f %f\n",
                            gsl_vector_get(pos, 0),
                            gsl_vector_get(pos, 1),
                            gsl_vector_get(pos, 2));
                    g_output_stream_write (G_OUTPUT_STREAM (out_stream),
                            buffer->str,
                            buffer->len,
                            NULL,
                            NULL);
                }
                t1 += t_increment;
            }
            t1 = t_min;
            t2 += t_increment;
        }
        t1 = t_min;
        t2 = t_min;
        t3 += t_increment;
    }

    g_output_stream_close(out_stream, NULL, NULL);
    gsl_vector_free(axes);
    g_clear_object(&geometry);
    g_string_free(buffer, TRUE);

    return 0;
}
示例#15
0
int get_stripe_info(lmgr_t *p_mgr, PK_ARG_T pk, stripe_info_t *p_stripe_info,
                    stripe_items_t *p_items)
{
/* stripe_count, stripe_size, pool_name, validator => 4 */
#define STRIPE_INFO_COUNT 4
    char *res[STRIPE_INFO_COUNT];
    result_handle_t result;
    int i;
    int rc = DB_SUCCESS;
    GString *req;

    /* retrieve basic stripe info */
    req =
        g_string_new
        ("SELECT stripe_count, stripe_size, pool_name,validator FROM "
         STRIPE_INFO_TABLE " WHERE id=");
    g_string_append_printf(req, DPK, pk);

    rc = db_exec_sql(&p_mgr->conn, req->str, &result);
    if (rc)
        goto out;

    rc = db_next_record(&p_mgr->conn, &result, res, STRIPE_INFO_COUNT);

    if (rc == DB_END_OF_LIST)
        rc = DB_NOT_EXISTS;
    if (rc)
        goto res_free;

    for (i = 0; i < STRIPE_INFO_COUNT; i++) {
        DisplayLog(LVL_FULL, LISTMGR_TAG, "stripe_res[%u] = %s", i,
                   res[i] ? res[i] : "<null>");
        if (res[i] == NULL) {
            rc = DB_ATTR_MISSING;
            goto res_free;
        }
    }

    p_stripe_info->stripe_count = atoi(res[0]);
    p_stripe_info->stripe_size = atoi(res[1]);
    rh_strncpy(p_stripe_info->pool_name, res[2], MAX_POOL_LEN);
#ifdef HAVE_LLAPI_FSWAP_LAYOUTS
    p_stripe_info->validator = atoi(res[3]);
#endif

    db_result_free(&p_mgr->conn, &result);

    if (p_items) {
        /* retrieve stripe list */
        g_string_printf(req, "SELECT stripe_index,ostidx,details FROM "
                        STRIPE_ITEMS_TABLE " WHERE id=" DPK
                        " ORDER BY stripe_index ASC", pk);

        rc = db_exec_sql(&p_mgr->conn, req->str, &result);
        if (rc)
            goto out;

#ifndef _LUSTRE_HSM
        /* this is abnormal if LUSTRE/HSM feature is not present */
        if (p_stripe_info->stripe_count !=
            db_result_nb_records(&p_mgr->conn, &result)) {
            DisplayLog(LVL_MAJOR, LISTMGR_TAG,
                       "Warning: the number of stripe items (%d) doesn't match stripe count (%u)! (Pk="
                       DPK ")", db_result_nb_records(&p_mgr->conn, &result),
                       p_stripe_info->stripe_count, pk);
        }
#endif
        p_items->count = db_result_nb_records(&p_mgr->conn, &result);

        if (p_items->count > 0) {

            /* allocate stripe array */
            p_items->stripe = MemCalloc(p_items->count, sizeof(stripe_item_t));

            if (!p_items->stripe) {
                rc = DB_NO_MEMORY;
                goto res_free;
            }

            /* fill stripe units */
            for (i = 0; i < p_items->count; i++) {
                rc = db_next_record(&p_mgr->conn, &result, res,
                                    STRIPE_INFO_COUNT);
                if (rc)
                    goto stripe_free;

                if (res[0] == NULL) {
                    rc = DB_ATTR_MISSING;
                    goto stripe_free;
                }

                if (i != atoi(res[0])) {
                    DisplayLog(LVL_MAJOR, LISTMGR_TAG,
                               "Warning: inconsistent stripe order: stripe %s returned in position %u",
                               res[0], i);
                }
                p_items->stripe[i].ost_idx = atoi(res[1]);
                /* raw copy of binary buffer (last 3 fields of stripe_item_t
                 *                            = address of ost_gen field) */
                memcpy(&p_items->stripe[i].ost_gen, res[2], STRIPE_DETAIL_SZ);
            }
        } else
            p_items->stripe = NULL;

        /* last query result must be freed */
        rc = DB_SUCCESS;
        goto res_free;
    }

    rc = DB_SUCCESS;
    /* result is already freed */
    goto out;

 stripe_free:
    free_stripe_items(p_items);
 res_free:
    db_result_free(&p_mgr->conn, &result);
 out:
    g_string_free(req, TRUE);
    return rc;
}
示例#16
0
文件: merge.c 项目: appneta/wireshark
static gchar*
get_read_error_string(const merge_in_file_t *in_files, const guint in_file_count,
                      const int *err, gchar **err_info)
{
    GString *err_message = g_string_new("");
    gchar   *display_basename = NULL;
    guint    i;

    g_assert(in_files != NULL);
    g_assert(err != NULL);
    g_assert(err_info != NULL);

    if (*err_info == NULL) {
        *err_info = g_strdup("no information supplied");
    }

    /*
     * Find the file on which we got the error, and report the error.
     */
    for (i = 0; i < in_file_count; i++) {
        if (in_files[i].state == GOT_ERROR) {
            display_basename = g_filename_display_basename(in_files[i].filename);

            switch (*err) {

                case WTAP_ERR_SHORT_READ:
                    g_string_printf(err_message,
                         "The capture file %s appears to have been cut short"
                          " in the middle of a packet.", display_basename);
                    break;

                case WTAP_ERR_BAD_FILE:
                    g_string_printf(err_message,
                         "The capture file %s appears to be damaged or corrupt.\n(%s)",
                         display_basename, *err_info);
                    break;

                case WTAP_ERR_DECOMPRESS:
                    g_string_printf(err_message,
                         "The compressed capture file %s appears to be damaged or corrupt.\n"
                         "(%s)", display_basename, *err_info);
                    break;

                default:
                    g_string_printf(err_message,
                         "An error occurred while reading the"
                         " capture file %s: %s.",
                         display_basename,  wtap_strerror(*err));
                    break;
            }

            g_free(display_basename);
            break;
        }
    }

    g_free(*err_info);
    *err_info = g_string_free(err_message, FALSE);

    return *err_info;
}
示例#17
0
int batch_insert_stripe_info(lmgr_t *p_mgr, pktype *pklist, int *validators,
                             attr_set_t **p_attrs, unsigned int count,
                             bool update_if_exists)
{
    bool first;
    int i, rc = 0;
    int total_si;
    GString *req = g_string_new("");
    attr_mask_t tmp_mask = { ATTR_MASK_stripe_info, 0, 0LL };

    if (!attr_mask_is_null(sum_masks(p_attrs, count, tmp_mask))) {
        /* build batch request for STRIPE_INFO table */
        g_string_assign(req, "INSERT INTO " STRIPE_INFO_TABLE " ("
                        STRIPE_INFO_FIELDS ") VALUES ");

        first = true;
        for (i = 0; i < count; i++) {
            /* no request if the entry has no stripe info */
            if (!ATTR_MASK_TEST(p_attrs[i], stripe_info))
                continue;

            g_string_append_printf(req, "%s(" DPK ",%d,%u,%u,'%s')",
                                   first ? "" : ",", pklist[i], validators[i],
                                   ATTR(p_attrs[i], stripe_info).stripe_count,
                                   (unsigned int)ATTR(p_attrs[i],
                                                      stripe_info).stripe_size,
                                   ATTR(p_attrs[i], stripe_info).pool_name);
            first = false;
        }

        if (update_if_exists)
            /* append "on duplicate key ..." */
            g_string_append(req,
                            " ON DUPLICATE KEY UPDATE " STRIPE_INFO_SET_VALUES);

        if (!first) {   /* do nothing if no entry had stripe info */
            rc = db_exec_sql(&p_mgr->conn, req->str, NULL);
            if (rc)
                goto out;
        }
        /* reset the string */
        g_string_assign(req, "");
    }

    /* Stripe items more tricky because we want to delete previous items
     * on update. */
    /* If update_if_exists is false, insert them all as a batch.
     * For the update case, remove previous items before bluk insert.
     */
    if (update_if_exists) {
        for (i = 0; i < count; i++) {
            /* no request if the entry has no stripe items */
            if (!ATTR_MASK_TEST(p_attrs[i], stripe_items))
                continue;

            g_string_printf(req,
                            "DELETE FROM " STRIPE_ITEMS_TABLE " WHERE id=" DPK,
                            pklist[i]);

            rc = db_exec_sql(&p_mgr->conn, req->str, NULL);
            if (rc)
                goto out;
        }
    }

    /* bulk insert stripe items (if any is set) */
    tmp_mask.std = ATTR_MASK_stripe_items;
    if (attr_mask_is_null(sum_masks(p_attrs, count, tmp_mask)))
        goto out;

    total_si = 0;
    first = true;
    g_string_assign(req, "INSERT INTO " STRIPE_ITEMS_TABLE
                    " (" STRIPE_ITEMS_FIELDS ") VALUES ");

    /* loop on all entries and all stripe items */
    for (i = 0; i < count; i++) {
        int s;
        const stripe_items_t *p_items;

        /* skip the entry if it has no stripe items */
        if (!ATTR_MASK_TEST(p_attrs[i], stripe_items))
            continue;

        p_items = &ATTR(p_attrs[i], stripe_items);
        for (s = 0; s < p_items->count; s++) {
            char buff[2 * STRIPE_DETAIL_SZ + 1];

            total_si++;
            if (buf2hex
                (buff, sizeof(buff),
                 (unsigned char *)(&p_items->stripe[s].ost_gen),
                 STRIPE_DETAIL_SZ) < 0) {
                DisplayLog(LVL_CRIT, LISTMGR_TAG,
                           "Buffer too small to store details stripe info");
                memset(buff, 0, sizeof(buff));
            }
            g_string_append_printf(req, "%s(" DPK ",%u,%u,x'%s')",
                                   first && (s == 0) ? "" : ",", pklist[i],
                                   s, p_items->stripe[s].ost_idx, buff);
            first = false;
        }
    }

    /* only execute it if there was some stripe items */
    if (total_si > 0)
        rc = db_exec_sql(&p_mgr->conn, req->str, NULL);

 out:
    g_string_free(req, TRUE);
    return rc;
}
示例#18
0
文件: merge.c 项目: appneta/wireshark
static gchar*
get_write_error_string(const merge_in_file_t *in_file, const int file_type,
                       const gchar* out_filename, const int *err, gchar **err_info)
{
    GString *err_message = g_string_new("");
    gchar *display_basename = NULL;
    int write_err;

    /* in_file may be NULL */
    g_assert(err != NULL);
    g_assert(err_info != NULL);

    if (*err_info == NULL) {
        *err_info = g_strdup("no information supplied");
    }

    write_err = *err;

    display_basename = g_filename_display_basename(in_file ? in_file->filename : "UNKNOWN");

    if (write_err < 0) {

        switch (write_err) {

            case WTAP_ERR_UNWRITABLE_ENCAP:
                /*
                 * This is a problem with the particular frame we're writing and
                 * the file type and subtype we're wwriting; note that, and
                 * report the frame number and file type/subtype.
                 */
                g_string_printf(err_message,
                    "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
                    in_file ? in_file->packet_num : 0, display_basename,
                    wtap_file_type_subtype_string(file_type));
                break;

            case WTAP_ERR_PACKET_TOO_LARGE:
                /*
                 * This is a problem with the particular frame we're writing and
                 * the file type and subtype we're writing; note that, and report
                 * the frame number and file type/subtype.
                 */
                g_string_printf(err_message,
                    "Frame %u of \"%s\" is too large for a \"%s\" file.",
                    in_file ? in_file->packet_num : 0, display_basename,
                    wtap_file_type_subtype_string(file_type));
                break;

            case WTAP_ERR_UNWRITABLE_REC_TYPE:
                /*
                 * This is a problem with the particular record we're writing and
                 * the file type and subtype we're writing; note that, and report
                 * the record number and file type/subtype.
                 */
                g_string_printf(err_message,
                    "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.",
                    in_file ? in_file->packet_num : 0, display_basename,
                    wtap_file_type_subtype_string(file_type));
                break;

            case WTAP_ERR_UNWRITABLE_REC_DATA:
                /*
                 * This is a problem with the particular record we're writing and
                 * the file type and subtype we're writing; note that, and report
                 * the frame number and file type/subtype.
                 */
                g_string_printf(err_message,
                    "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)",
                    in_file ? in_file->packet_num : 0, display_basename,
                    wtap_file_type_subtype_string(file_type), *err_info);
                break;

            default:
                g_string_printf(err_message,
                    "An error occurred while writing to the file \"%s\": %s.",
                    out_filename, wtap_strerror(write_err));
                break;
        }
    }
    else {
        /* OS error. */
        g_string_printf(err_message, file_write_error_message(write_err), out_filename);
    }

    g_free(display_basename);
    g_free(*err_info);
    *err_info = g_string_free(err_message, FALSE);

    return *err_info;
}
示例#19
0
static gboolean _on_show_dlg(gpointer user_data)
{
    FmProgressDisplay* data = (FmProgressDisplay*)user_data;
    GtkBuilder* builder;
    GtkLabel* to;
    GtkWidget *to_label;
    FmPath* dest;
    const char* title = NULL;
    GtkTextTagTable* tag_table;

    builder = gtk_builder_new();
    tag_table = gtk_text_tag_table_new();
    gtk_builder_set_translation_domain(builder, GETTEXT_PACKAGE);
    gtk_builder_add_from_file(builder, PACKAGE_UI_DIR "/progress.ui", NULL);

    data->dlg = GTK_DIALOG(gtk_builder_get_object(builder, "dlg"));
    g_object_weak_ref(G_OBJECT(data->dlg), on_progress_dialog_destroy, data);

    g_signal_connect(data->dlg, "response", G_CALLBACK(on_response), data);
    /* FIXME: connect to "close" signal */

    to_label = (GtkWidget*)gtk_builder_get_object(builder, "to_label");
    to = GTK_LABEL(gtk_builder_get_object(builder, "dest"));
    data->icon = GTK_IMAGE(gtk_builder_get_object(builder, "icon"));
    data->msg = GTK_LABEL(gtk_builder_get_object(builder, "msg"));
    data->act = GTK_LABEL(gtk_builder_get_object(builder, "action"));
    data->src = GTK_LABEL(gtk_builder_get_object(builder, "src"));
    data->dest = (GtkWidget*)gtk_builder_get_object(builder, "dest");
    data->current = GTK_LABEL(gtk_builder_get_object(builder, "current"));
    data->progress = GTK_PROGRESS_BAR(gtk_builder_get_object(builder, "progress"));
    data->error_pane = (GtkWidget*)gtk_builder_get_object(builder, "error_pane");
    data->error_msg = GTK_TEXT_VIEW(gtk_builder_get_object(builder, "error_msg"));
    data->data_transferred = GTK_LABEL(gtk_builder_get_object(builder, "data_transferred"));
    data->data_transferred_label = GTK_LABEL(gtk_builder_get_object(builder, "data_transferred_label"));
    data->remaining_time = GTK_LABEL(gtk_builder_get_object(builder, "remaining_time"));
    data->remaining_time_label = GTK_LABEL(gtk_builder_get_object(builder, "remaining_time_label"));
    data->cancel = GTK_BUTTON(gtk_builder_get_object(builder, "cancel"));
    data->suspend = GTK_BUTTON(gtk_dialog_add_button(data->dlg, _("_Pause"), 1));
    gtk_button_set_use_stock(data->suspend, FALSE);
    gtk_button_set_use_underline(data->suspend, TRUE);
    gtk_button_set_image(data->suspend,
                         gtk_image_new_from_stock(GTK_STOCK_MEDIA_PAUSE,
                                                  GTK_ICON_SIZE_BUTTON));
    gtk_dialog_set_alternative_button_order(data->dlg, 1, GTK_RESPONSE_CANCEL, -1);
    data->bold_tag = gtk_text_tag_new("bold");
    g_object_set(data->bold_tag, "weight", PANGO_WEIGHT_BOLD, NULL);
    gtk_text_tag_table_add(tag_table, data->bold_tag);
    data->error_buf = gtk_text_buffer_new(tag_table);
    g_object_unref(tag_table);
    gtk_text_view_set_buffer(data->error_msg, data->error_buf);

    gtk_widget_hide(GTK_WIDGET(data->icon));

    g_object_unref(builder);

    /* set the src label */
    /* FIXME: direct access to job struct! */
    if(data->job->srcs)
    {
        GList* l = fm_path_list_peek_head_link(data->job->srcs);
        int i;
        char* disp;
        FmPath* path;
        GString* str = g_string_sized_new(512);
        path = FM_PATH(l->data);
        disp = fm_path_display_basename(path);
        g_string_assign(str, disp);
        g_free(disp);
        for( i =1, l=l->next; i < 10 && l; l=l->next, ++i)
        {
            path = FM_PATH(l->data);
            g_string_append(str, _(", "));
            disp = fm_path_display_basename(path);
            g_string_append(str, disp);
            g_free(disp);
        }
        if(l)
            g_string_append(str, "...");
        gtk_label_set_text(data->src, str->str);
        gtk_widget_set_tooltip_text(GTK_WIDGET(data->src), str->str);
        g_string_free(str, TRUE);
    }

    /* FIXME: use accessor functions instead */
    /* FIXME: direct access to job struct! */
    switch(data->job->type)
    {
    /* we set title here if text is complex so may be different from
       the op_text when is translated to other languages */
    case FM_FILE_OP_MOVE:
        /* translators: it is part of "Moving files:" or "Moving xxx.txt" */
        data->op_text = _("Moving");
        break;
    case FM_FILE_OP_COPY:
        /* translators: it is part of "Copying files:" or "Copying xxx.txt" */
        data->op_text = _("Copying");
        break;
    case FM_FILE_OP_TRASH:
        /* translators: it is part of "Trashing files:" or "Trashing xxx.txt" */
        data->op_text = _("Trashing");
        break;
    case FM_FILE_OP_DELETE:
        /* translators: it is part of "Deleting files:" or "Deleting xxx.txt" */
        data->op_text = _("Deleting");
        break;
    case FM_FILE_OP_LINK:
        /* translators: it is part of "Creating link /path/xxx.txt" */
        data->op_text = _("Creating link");
        /* translators: 'In:' string is followed by destination folder path */
        gtk_label_set_markup(GTK_LABEL(to_label), _("<b>In:</b>"));
        title = _("Creating links to files");
        /* NOTE: on creating single symlink or shortcut all operation
           is done in single I/O therefore it should fit into 0.5s
           timeout and progress window will never be shown */
        break;
    case FM_FILE_OP_CHANGE_ATTR:
        /* translators: it is part of "Changing attributes of xxx.txt" */
        data->op_text = _("Changing attributes of");
        title = _("Changing attributes of files");
        /* NOTE: the same about single symlink is appliable here so
           there is no need to add never used string for translation */
        break;
    case FM_FILE_OP_UNTRASH:
        /* translators: it is part of "Restoring files:" or "Restoring xxx.txt" */
        data->op_text = _("Restoring");
        break;
    case FM_FILE_OP_NONE: ;
    }
    data->str = g_string_sized_new(64);
    if (title)
        gtk_window_set_title(GTK_WINDOW(data->dlg), title);
    else
    {
        /* note to translators: resulting string is such as "Deleting files" */
        g_string_printf(data->str, _("%s files"), data->op_text);
        gtk_window_set_title(GTK_WINDOW(data->dlg), data->str->str);
    }
    gtk_label_set_markup(data->msg, _("<b>File operation is in progress...</b>"));
    gtk_widget_show(GTK_WIDGET(data->msg));
    if (title) /* we already know the exact string */
        g_string_printf(data->str, "<b>%s:</b>", title);
    else if (fm_path_list_get_length(data->job->srcs) == 1)
        /* note to translators: resulting string is such as "Deleting file" */
        g_string_printf(data->str, _("<b>%s file:</b>"), data->op_text);
    else
        /* note to translators: resulting string is such as "Deleting files" */
        g_string_printf(data->str, _("<b>%s files:</b>"), data->op_text);
    gtk_label_set_markup(data->act, data->str->str);

    dest = fm_file_ops_job_get_dest(data->job);
    if(dest)
    {
        char* dest_str = fm_path_display_name(dest, TRUE);
        gtk_label_set_text(to, dest_str);
        gtk_widget_set_tooltip_text(GTK_WIDGET(data->dest), dest_str);
        g_free(dest_str);
    }
    else
    {
        gtk_widget_destroy(data->dest);
        gtk_widget_destroy(to_label);
    }

    gtk_window_set_transient_for(GTK_WINDOW(data->dlg), data->parent);
    gtk_window_present(GTK_WINDOW(data->dlg));

    data->delay_timeout = 0;
    return FALSE;
}
示例#20
0
文件: merge.c 项目: appneta/wireshark
/*
 * Merges the files based on given input, and invokes callback during
 * execution. Returns MERGE_OK on success, or a MERGE_ERR_XXX on failure; note
 * that the passed-in 'err' variable will be more specific to what failed, and
 * err_info will have pretty output.
 */
merge_result
merge_files(int out_fd, const gchar* out_filename, const int file_type,
            const char *const *in_filenames, const guint in_file_count,
            const gboolean do_append, const idb_merge_mode mode,
            guint snaplen, const gchar *app_name, merge_progress_callback_t* cb,
            int *err, gchar **err_info, int *err_fileno)
{
    merge_in_file_t    *in_files = NULL, *in_file = NULL;
    int                 frame_type = WTAP_ENCAP_PER_PACKET;
    merge_result        status = MERGE_OK;
    wtap_dumper        *pdh;
    struct wtap_pkthdr *phdr, snap_phdr;
    int                 count = 0;
    gboolean            stop_flag = FALSE;
    wtapng_section_t            *shb_hdr = NULL;
    wtapng_iface_descriptions_t *idb_inf = NULL;

    g_assert(out_fd > 0);
    g_assert(in_file_count > 0);
    g_assert(in_filenames != NULL);
    g_assert(err != NULL);
    g_assert(err_info != NULL);
    g_assert(err_fileno != NULL);

    /* if a callback was given, it has to have a callback function ptr */
    g_assert((cb != NULL) ? (cb->callback_func != NULL) : TRUE);

    merge_debug("merge_files: begin");

    /* open the input files */
    if (!merge_open_in_files(in_file_count, in_filenames, &in_files,
                             err, err_info, err_fileno)) {
        merge_debug("merge_files: merge_open_in_files() failed with err=%d", *err);
        return MERGE_ERR_CANT_OPEN_INFILE;
    }

    if (cb)
        cb->callback_func(MERGE_EVENT_INPUT_FILES_OPENED, 0, in_files, in_file_count, cb->data);

    if (snaplen == 0) {
        /* Snapshot length not specified - default to the maximum. */
        snaplen = WTAP_MAX_PACKET_SIZE;
    }

    /*
     * This doesn't tell us that much. It tells us what to set the outfile's
     * encap type to, but that's all - for example, it does *not* tells us
     * whether the input files had the same number of IDBs, for the same exact
     * interfaces, and only one IDB each, so it doesn't actually tell us
     * whether we can merge IDBs into one or not.
     */
    frame_type = merge_select_frame_type(in_file_count, in_files);
    merge_debug("merge_files: got frame_type=%d", frame_type);

    if (cb)
        cb->callback_func(MERGE_EVENT_FRAME_TYPE_SELECTED, frame_type, in_files, in_file_count, cb->data);

    /* prepare the outfile */
    if (file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
        shb_hdr = create_shb_header(in_files, in_file_count, app_name);
        merge_debug("merge_files: SHB created");

        idb_inf = generate_merged_idb(in_files, in_file_count, mode);
        merge_debug("merge_files: IDB merge operation complete, got %u IDBs", idb_inf ? idb_inf->interface_data->len : 0);

        pdh = wtap_dump_fdopen_ng(out_fd, file_type, frame_type, snaplen,
                                  FALSE /* compressed */, shb_hdr, idb_inf,
                                  NULL, err);
    }
    else {
        pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, err);
    }

    if (pdh == NULL) {
        merge_close_in_files(in_file_count, in_files);
        g_free(in_files);
        wtap_free_shb(shb_hdr);
        wtap_free_idb_info(idb_inf);
        return MERGE_ERR_CANT_OPEN_OUTFILE;
    }

    if (cb)
        cb->callback_func(MERGE_EVENT_READY_TO_MERGE, 0, in_files, in_file_count, cb->data);

    for (;;) {
        *err = 0;

        if (do_append) {
            in_file = merge_append_read_packet(in_file_count, in_files, err,
                                               err_info);
        }
        else {
            in_file = merge_read_packet(in_file_count, in_files, err,
                                        err_info);
        }

        if (in_file == NULL) {
            /* EOF */
            break;
        }

        if (*err != 0) {
            /* I/O error reading from in_file */
            status = MERGE_ERR_CANT_READ_INFILE;
            break;
        }

        count++;
        if (cb)
            stop_flag = cb->callback_func(MERGE_EVENT_PACKET_WAS_READ, count, in_files, in_file_count, cb->data);

        if (stop_flag) {
            /* The user decided to abort the merge. */
            status = MERGE_USER_ABORTED;
            break;
        }

        phdr = wtap_phdr(in_file->wth);

        if (snaplen != 0 && phdr->caplen > snaplen) {
            /*
             * The dumper will only write up to caplen bytes out, so we only
             * need to change that value, instead of cloning the whole packet
             * with fewer bytes.
             *
             * XXX: but do we need to change the IDBs' snap_len?
             */
            snap_phdr = *phdr;
            snap_phdr.caplen = snaplen;
            phdr = &snap_phdr;
        }

        if (file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
            if (!map_phdr_interface_id(phdr, in_file)) {
                status = MERGE_ERR_BAD_PHDR_INTERFACE_ID;
                break;
            }
        }

        if (!wtap_dump(pdh, phdr, wtap_buf_ptr(in_file->wth), err, err_info)) {
            status = MERGE_ERR_CANT_WRITE_OUTFILE;
            break;
        }
    }

    if (cb)
        cb->callback_func(MERGE_EVENT_DONE, count, in_files, in_file_count, cb->data);

    merge_close_in_files(in_file_count, in_files);

    if (status == MERGE_OK || status == MERGE_USER_ABORTED) {
        if (!wtap_dump_close(pdh, err))
            status = MERGE_ERR_CANT_CLOSE_OUTFILE;
    } else {
        /*
         * We already got some error; no need to report another error on
         * close.
         *
         * Don't overwrite the earlier error.
         */
        int close_err = 0;
        (void)wtap_dump_close(pdh, &close_err);
    }

    if (status != MERGE_OK) {
        GString *err_message = NULL;
        gchar   *display_basename = NULL;

        switch(status) {

            case MERGE_ERR_CANT_READ_INFILE:
                *err_info = get_read_error_string(in_files, in_file_count, err, err_info);
                break;

            case MERGE_ERR_CANT_WRITE_OUTFILE: /* fall through */
            case MERGE_ERR_CANT_CLOSE_OUTFILE:
                *err_info = get_write_error_string(in_file, file_type, out_filename, err, err_info);
                break;

            case MERGE_ERR_BAD_PHDR_INTERFACE_ID:
                display_basename = g_filename_display_basename(in_file ? in_file->filename : "UNKNOWN");
                if (*err_info != NULL)
                    g_free(*err_info);
                err_message = g_string_new("");
                g_string_printf(err_message,
                    "Record %u of \"%s\" has an interface ID which does not match any IDB in its file.",
                    in_file ? in_file->packet_num : 0, display_basename);
                g_free(display_basename);
                *err_info = g_string_free(err_message, FALSE);
                break;

            case MERGE_USER_ABORTED: /* not really an error */
            default:
                break;
        }
    }

    g_free(in_files);
    wtap_free_shb(shb_hdr);
    wtap_free_idb_info(idb_inf);

    return status;
}
示例#21
0
文件: diritem.c 项目: EQ4/samplecat
/* Fill in more details of the DirItem for a directory item.
 * - Looks for an image (but maybe still NULL on error)
 * - Updates ITEM_FLAG_APPDIR
 *
 * link_target contains stat info for the link target for symlinks (or for the
 * item itself if not a link).
 */
static void examine_dir(const guchar *path, DirItem *item,
			struct stat *link_target)
{
	struct stat info;
	static GString *tmp = NULL;
	uid_t uid = link_target->st_uid;

	if (!tmp)
		tmp = g_string_new(NULL);

	//check_globicon(path, item);

	/*
	if (item->flags & ITEM_FLAG_MOUNT_POINT)
	{
		item->mime_type = inode_mountpoint;
		return;		// Try to avoid automounter problems
	}
	*/

	//if (link_target->st_mode & S_IWOTH)	return;		// Don't trust world-writable dirs

	/* Finding the icon:
	 *
	 * - If it contains a .DirIcon then that's the icon
	 * - If it contains an AppRun then it's an application
	 * - If it contains an AppRun but no .DirIcon then try to
	 *   use AppIcon.xpm as the icon.
	 *
	 * .DirIcon and AppRun must have the same owner as the
	 * directory itself, to prevent abuse of /tmp, etc.
	 * For symlinks, we want the symlink's owner.
	 */

	g_string_printf(tmp, "%s/.DirIcon", path);

	if (item->_image)
		goto no_diricon;	/* Already got an icon */

	if (lstat(tmp->str, &info) != 0 || info.st_uid != uid)
		goto no_diricon;	/* Missing, or wrong owner */

	if (S_ISLNK(info.st_mode) && stat(tmp->str, &info) != 0)
		goto no_diricon;	/* Bad symlink */

	if (info.st_size > MAX_ICON_SIZE || !S_ISREG(info.st_mode))
		goto no_diricon;	/* Too big, or non-regular file */

	/* Try to load image; may still get NULL... */
	//item->_image = g_fscache_lookup(pixmap_cache, tmp->str);
	item->_image = NULL;

no_diricon:

#if 0
	/* Try to find AppRun... */
	g_string_truncate(tmp, tmp->len - 8);
	g_string_append(tmp, "AppRun");

	if (lstat(tmp->str, &info) != 0 || info.st_uid != uid)
		goto out;	/* Missing, or wrong owner */
		
	if (!(info.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
		goto out;	/* Not executable */

	item->flags |= ITEM_FLAG_APPDIR;

	/* Try to load AppIcon.xpm... */

	if (item->_image)
		goto out;	/* Already got an icon */

	g_string_truncate(tmp, tmp->len - 3);
	g_string_append(tmp, "Icon.xpm");

	/* Note: since AppRun is valid we don't need to check AppIcon.xpm
	 *	 so carefully.
	 */
#endif

	if (stat(tmp->str, &info) != 0)
		goto out;	/* Missing, or broken symlink */

	if (info.st_size > MAX_ICON_SIZE || !S_ISREG(info.st_mode))
		goto out;	/* Too big, or non-regular file */

	/* Try to load image; may still get NULL... */
	//item->_image = g_fscache_lookup(pixmap_cache, tmp->str);
	item->_image = NULL;

out:
	;

#if 0
	if ((item->flags & ITEM_FLAG_APPDIR) && !item->_image)
	{
		/* This is an application without an icon */
		item->_image = im_appdir;
		g_object_ref(item->_image);
	}
#endif
}
示例#22
0
/* SYNTAX: WHOIS [-<server tag>] [<server>] [<nicks>] */
static void cmd_whois(const char *data, IRC_SERVER_REC *server,
                      WI_ITEM_REC *item)
{
	GHashTable *optlist;
	char *qserver, *query, *event_402, *str;
	void *free_arg;
	int free_nick;

	CMD_IRC_SERVER(server);

	if (!cmd_get_params(data, &free_arg, 2 | PARAM_FLAG_OPTIONS |
	                    PARAM_FLAG_UNKNOWN_OPTIONS,
	                    "whois", &optlist, &qserver, &query))
		return;

	/* -<server tag> */
	server = IRC_SERVER(cmd_options_get_server("whois", optlist,
	                                           SERVER(server)));
	if (server == NULL) {
		cmd_params_free(free_arg);
		return;
	}

	if (*query == '\0') {
		query = qserver;
		qserver = "";
	}
	if (*query == '\0') {
		QUERY_REC *queryitem = QUERY(item);
		if (queryitem == NULL)
			query = server->nick;
		else
			query = qserver = queryitem->name;
	}

	if (g_strcmp0(query, "*") == 0 &&
	    g_hash_table_lookup(optlist, "yes") == NULL)
		cmd_param_error(CMDERR_NOT_GOOD_IDEA);

	event_402 = "event 402";
	if (*qserver == '\0')
		g_string_printf(tmpstr, "WHOIS %s", query);
	else {
		g_string_printf(tmpstr, "WHOIS %s %s", qserver, query);
		if (g_ascii_strcasecmp(qserver, query) == 0)
			event_402 = "whois event not found";
	}

	query = get_redirect_nicklist(query, &free_nick);

	str = g_strconcat(qserver, " ", query, NULL);
	server_redirect_event(server, "whois", 1, str, TRUE,
	              NULL,
	              "event 318", "whois end",
	              "event 402", event_402,
	              "event 301", "whois away", /* 301 can come as a reply to /MSG, /WHOIS or /WHOWAS */
	              "event 313", "whois oper",
	              "event 401", (settings_get_bool("auto_whowas") ? "whois try whowas" : "whois event not found"),
	              "event 311", "whois event",
	              "", "whois default event", NULL);
	g_free(str);

	server->whois_found = FALSE;
	irc_send_cmd_split(server, tmpstr->str, 2, server->max_whois_in_cmd);

	if (free_nick) g_free(query);
	cmd_params_free(free_arg);
}
示例#23
0
/*
 * Format a value according to the xml setting.
 * Returns an allocated buffer that must be freed by the caller.
 */
GString *
format_value (XmlSettings *xml, gint value)
{
    GString        *buf = g_string_sized_new(1);
    EffectValues   *values = NULL;
    ValueType       vtype;
    gchar          *suffix = "";
    gdouble         step = 1.0;
    gint            offset = 0;
    gboolean        decimal = FALSE;

    values = xml->values;
    vtype = values->type;
    while ((vtype & VALUE_TYPE_EXTRA) && value_is_extra(values, value)) {
        values = values->extra;
        vtype = values->type;
    }
    vtype &= ~VALUE_TYPE_EXTRA;

    if (vtype & VALUE_TYPE_OFFSET) {
        offset = values->offset;
        vtype &= ~VALUE_TYPE_OFFSET;
    }

    if (vtype & VALUE_TYPE_STEP) {
        step = values->step;
        vtype &= ~VALUE_TYPE_STEP;
    }

    if (vtype & VALUE_TYPE_SUFFIX) {
        suffix = values->suffix;
        vtype &= ~VALUE_TYPE_SUFFIX;
    }

    if (vtype & VALUE_TYPE_DECIMAL) {
        decimal = TRUE;
        vtype &= ~VALUE_TYPE_DECIMAL;
    }

    switch (vtype) {
    case VALUE_TYPE_LABEL:
    {
        char *textp = map_xml_value(xml, value);
        if (!textp) {
            g_warning("Unable to map %s value %d for id %d position %d",
                      xml->label, value, xml->id, xml->position);
            textp = "";
        }
        g_string_printf(buf, "%s", textp);
        break;
    }
    case VALUE_TYPE_PLAIN:
    {
        if (decimal) {
            double dvalue = (value + offset) * step;
            g_string_printf(buf, "%0.2f%s", dvalue, suffix);
        } else {
            gint ivalue = (value + offset) * step;
            g_string_printf(buf, "%d%s", ivalue, suffix);
        }
        break;
    }
    case VALUE_TYPE_NONE:
        g_string_printf(buf, "%s", "");
        break;

    default:
        g_warning("Unhandled value type %d", vtype);
        break;
    }

    return buf;
}
示例#24
0
文件: qq.c 项目: Mons/libpurple-mini
/* a floating text when mouse is on the icon, show connection status here */
static void qq_tooltip_text(PurpleBuddy *b, PurpleNotifyUserInfo *user_info, gboolean full)
{
	qq_buddy_data *bd;
	gchar *tmp;
	GString *str;

	g_return_if_fail(b != NULL);

	bd = purple_buddy_get_protocol_data(b);
	if (bd == NULL)
		return;

	/* if (PURPLE_BUDDY_IS_ONLINE(b) && bd != NULL) */
	if (bd->ip.s_addr != 0) {
		str = g_string_new(NULL);
		g_string_printf(str, "%s:%d", inet_ntoa(bd->ip), bd->port);
		if (bd->comm_flag & QQ_COMM_FLAG_TCP_MODE) {
			g_string_append(str, " TCP");
		} else {
			g_string_append(str, " UDP");
		}
		g_string_free(str, TRUE);
	}

	tmp = g_strdup_printf("%d", bd->age);
	purple_notify_user_info_add_pair(user_info, _("Age"), tmp);
	g_free(tmp);

	switch (bd->gender) {
		case QQ_BUDDY_GENDER_GG:
			purple_notify_user_info_add_pair(user_info, _("Gender"), _("Male"));
			break;
		case QQ_BUDDY_GENDER_MM:
			purple_notify_user_info_add_pair(user_info, _("Gender"), _("Female"));
			break;
		case QQ_BUDDY_GENDER_UNKNOWN:
			purple_notify_user_info_add_pair(user_info, _("Gender"), _("Unknown"));
			break;
		default:
			tmp = g_strdup_printf("Error (%d)", bd->gender);
			purple_notify_user_info_add_pair(user_info, _("Gender"), tmp);
			g_free(tmp);
	}

	if (bd->level) {
		tmp = g_strdup_printf("%d", bd->level);
		purple_notify_user_info_add_pair(user_info, _("Level"), tmp);
		g_free(tmp);
	}

	str = g_string_new(NULL);
	if (bd->comm_flag & QQ_COMM_FLAG_QQ_MEMBER) {
		g_string_append( str, _("Member") );
	}
	if (bd->comm_flag & QQ_COMM_FLAG_QQ_VIP) {
		g_string_append( str, _(" VIP") );
	}
	if (bd->comm_flag & QQ_COMM_FLAG_TCP_MODE) {
		g_string_append( str, _(" TCP") );
	}
	if (bd->comm_flag & QQ_COMM_FLAG_MOBILE) {
		g_string_append( str, _(" FromMobile") );
	}
	if (bd->comm_flag & QQ_COMM_FLAG_BIND_MOBILE) {
		g_string_append( str, _(" BindMobile") );
	}
	if (bd->comm_flag & QQ_COMM_FLAG_VIDEO) {
		g_string_append( str, _(" Video") );
	}

	if (bd->ext_flag & QQ_EXT_FLAG_ZONE) {
		g_string_append( str, _(" Zone") );
	}
	purple_notify_user_info_add_pair(user_info, _("Flag"), str->str);

	g_string_free(str, TRUE);

#ifdef DEBUG
	tmp = g_strdup_printf( "%s (%04X)",
			qq_get_ver_desc(bd->client_tag),
			bd->client_tag );
	purple_notify_user_info_add_pair(user_info, _("Ver"), tmp);
	g_free(tmp);

	tmp = g_strdup_printf( "Ext 0x%X, Comm 0x%X",
			bd->ext_flag, bd->comm_flag );
	purple_notify_user_info_add_pair(user_info, _("Flag"), tmp);
	g_free(tmp);
#endif
}
示例#25
0
void
gtr_confirm_remove( GtkWindow  * parent,
                    TrCore     * core,
                    GSList     * torrent_ids,
                    gboolean     delete_files )
{
    GSList * l;
    GtkWidget * d;
    GString * primary_text;
    GString * secondary_text;
    struct delete_data * dd;
    int connected = 0;
    int incomplete = 0;
    const int count = g_slist_length( torrent_ids );

    if( !count )
        return;

    dd = g_new0( struct delete_data, 1 );
    dd->core = core;
    dd->torrent_ids = torrent_ids;
    dd->delete_files = delete_files;

    for( l=torrent_ids; l!=NULL; l=l->next )
    {
        const int id = GPOINTER_TO_INT( l->data );
        tr_torrent * tor = gtr_core_find_torrent( core, id );
        const tr_stat * stat = tr_torrentStat( tor );
        if( stat->leftUntilDone ) ++incomplete;
        if( stat->peersConnected ) ++connected;
    }

    primary_text = g_string_new( NULL );

    if( !delete_files )
    {
        g_string_printf( primary_text, ngettext( "Remove torrent?",
                                                 "Remove %d torrents?",
                                                 count ), count );
    }
    else
    {
        g_string_printf( primary_text, ngettext( "Delete this torrent's downloaded files?",
                                                 "Delete these %d torrents' downloaded files?",
                                                 count ), count );
    }

    secondary_text = g_string_new( NULL );

    if( !incomplete && !connected )
    {
        g_string_assign( secondary_text, ngettext(
                "Once removed, continuing the transfer will require the torrent file or magnet link.",
                "Once removed, continuing the transfers will require the torrent files or magnet links.",
                count ) );
    }
    else if( count == incomplete )
    {
        g_string_assign( secondary_text, ngettext( "This torrent has not finished downloading.",
                                                   "These torrents have not finished downloading.",
                                                   count ) );
    }
    else if( count == connected )
    {
        g_string_assign( secondary_text, ngettext( "This torrent is connected to peers.",
                                                   "These torrents are connected to peers.",
                                                   count ) );
    }
    else
    {
        if( connected )
            g_string_append( secondary_text, ngettext( "One of these torrents is connected to peers.",
                                                       "Some of these torrents are connected to peers.",
                                                       connected ) );
        if( connected && incomplete )
            g_string_append( secondary_text, "\n" );

        if( incomplete )
            g_string_assign( secondary_text, ngettext( "One of these torrents has not finished downloading.",
                                                       "Some of these torrents have not finished downloading.",
                                                       incomplete ) );
    }

    d = gtk_message_dialog_new_with_markup( parent,
                                            GTK_DIALOG_DESTROY_WITH_PARENT,
                                            GTK_MESSAGE_QUESTION,
                                            GTK_BUTTONS_NONE,
                                            "<big><b>%s</b></big>",
                                            primary_text->str );
    if( secondary_text->len )
        gtk_message_dialog_format_secondary_markup( GTK_MESSAGE_DIALOG( d ),
                                                    "%s", secondary_text->str );
    gtk_dialog_add_buttons( GTK_DIALOG( d ),
                            GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                            ( delete_files ? GTK_STOCK_DELETE :
                              GTK_STOCK_REMOVE ), GTK_RESPONSE_ACCEPT,
                            NULL );
    gtk_dialog_set_default_response( GTK_DIALOG ( d ),
                                     GTK_RESPONSE_CANCEL );
    gtk_dialog_set_alternative_button_order( GTK_DIALOG( d ),
                                             GTK_RESPONSE_ACCEPT,
                                             GTK_RESPONSE_CANCEL,
                                             -1 );
    g_signal_connect( d, "response", G_CALLBACK( on_remove_dialog_response ), dd );
    gtk_widget_show_all( d );

    g_string_free( primary_text, TRUE );
    g_string_free( secondary_text, TRUE );
}
示例#26
0
文件: string.c 项目: LogosBible/mono
static RESULT
test_gstring (void)
{
	GString *s = g_string_new_len ("My stuff", 2);
	char *ret;
	int i;

	if (strcmp (s->str, "My") != 0)
		return (char*)"Expected only 'My' on the string";
	g_string_free (s, TRUE);

	s = g_string_new_len ("My\0\0Rest", 6);
	if (s->str [2] != 0)
		return (char*)"Null was not copied";
	if (strcmp (s->str+4, "Re") != 0){
		return (char*)"Did not find the 'Re' part";
	}

	g_string_append (s, "lalalalalalalalalalalalalalalalalalalalalalal");
	if (s->str [2] != 0)
		return (char*)"Null as not copied";
	if (strncmp (s->str+4, "Relala", 6) != 0){
		return FAILED("Did not copy correctly, got: %s", s->str+4);
	}

	g_string_free (s, TRUE);

	s = g_string_new ("");
	for (i = 0; i < 1024; i++){
		g_string_append_c (s, 'x');
	}
	if (strlen (s->str) != 1024){
		return FAILED("Incorrect string size, got: %s %d\n", s->str, strlen (s->str));
	}
	g_string_free (s, TRUE);

	s = g_string_new ("hola");
	g_string_sprintfa (s, "%s%d", ", bola", 5);
	if (strcmp (s->str, "hola, bola5") != 0){
		return FAILED("Incorrect data, got: %s\n", s->str);
	}
	g_string_free (s, TRUE);

	s = g_string_new ("Hola");
	g_string_printf (s, "Dingus");
	
	/* Test that it does not release it */
	ret = g_string_free (s, FALSE);
	g_free (ret);

 	s = g_string_new_len ("H" "\000" "H", 3);
	g_string_append_len (s, "1" "\000" "2", 3);
	sfail ('H', 0);
	sfail ( 0, 1);
	sfail ('H', 2);
	sfail ('1', 3);
	sfail ( 0, 4);
	sfail ('2', 5);
	g_string_free (s, TRUE);
	
	return OK;
}
示例#27
0
static void
log_json_parser_process_single (struct json_object *jso,
                                const gchar *prefix,
                                const gchar *obj_key,
                                LogMessage *msg)
{
  ScratchBuffer *key, *value;
  gboolean parsed = FALSE;

  key = scratch_buffer_acquire ();
  value = scratch_buffer_acquire ();

  switch (json_object_get_type (jso))
    {
    case json_type_boolean:
      parsed = TRUE;
      if (json_object_get_boolean (jso))
        g_string_assign (sb_string (value), "true");
      else
        g_string_assign (sb_string (value), "false");
      break;
    case json_type_double:
      parsed = TRUE;
      g_string_printf (sb_string (value), "%f",
                       json_object_get_double (jso));
      break;
    case json_type_int:
      parsed = TRUE;
      g_string_printf (sb_string (value), "%i",
                       json_object_get_int (jso));
      break;
    case json_type_string:
      parsed = TRUE;
      g_string_assign (sb_string (value),
                       json_object_get_string (jso));
      break;
    case json_type_object:
      if (prefix)
        g_string_assign (sb_string (key), prefix);
      g_string_append (sb_string (key), obj_key);
      g_string_append_c (sb_string (key), '.');
      log_json_parser_process_object (jso, sb_string (key)->str, msg);
      break;
    case json_type_array:
      {
        gint i, plen;

        g_string_assign (sb_string (key), obj_key);

        plen = sb_string (key)->len;

        for (i = 0; i < json_object_array_length (jso); i++)
          {
            g_string_truncate (sb_string (key), plen);
            g_string_append_printf (sb_string (key), "[%d]", i);
            log_json_parser_process_single (json_object_array_get_idx (jso, i),
                                            prefix,
                                            sb_string (key)->str, msg);
          }
        break;
      }
    default:
      msg_error ("JSON parser encountered an unknown type, skipping",
                 evt_tag_str ("key", obj_key), NULL);
      break;
    }

  if (parsed)
    {
      if (prefix)
        {
          g_string_assign (sb_string (key), prefix);
          g_string_append (sb_string (key), obj_key);
          log_msg_set_value (msg,
                             log_msg_get_value_handle (sb_string (key)->str),
                             sb_string (value)->str, sb_string (value)->len);
        }
      else
        log_msg_set_value (msg,
                           log_msg_get_value_handle (obj_key),
                           sb_string (value)->str, sb_string (value)->len);
    }

  scratch_buffer_release (key);
  scratch_buffer_release (value);
}
示例#28
0
/**
 * Do a request.
 * This is actually pretty generic function... Perhaps it should move to the lib/http_client.c
 */
void *twitter_http(struct im_connection *ic, char *url_string, http_input_function func,
		   gpointer data, int is_post, char **arguments, int arguments_len)
{
	struct twitter_data *td = ic->proto_data;
	char *tmp;
	GString *request = g_string_new("");
	void *ret;
	char *url_arguments;

	url_arguments = g_strdup("");

	// Construct the url arguments.
	if (arguments_len != 0) {
		int i;
		for (i = 0; i < arguments_len; i += 2) {
			tmp = twitter_url_append(url_arguments, arguments[i], arguments[i + 1]);
			g_free(url_arguments);
			url_arguments = tmp;
		}
	}
	// Make the request.
	g_string_printf(request, "%s %s%s%s%s HTTP/1.0\r\n"
			"Host: %s\r\n"
			"User-Agent: BitlBee " BITLBEE_VERSION " " ARCH "/" CPU "\r\n",
			is_post ? "POST" : "GET",
			td->url_path, url_string,
			is_post ? "" : "?", is_post ? "" : url_arguments, td->url_host);

	// If a pass and user are given we append them to the request.
	if (td->oauth_info) {
		char *full_header;
		char *full_url;

		full_url = g_strconcat(set_getstr(&ic->acc->set, "base_url"), url_string, NULL);
		full_header = oauth_http_header(td->oauth_info, is_post ? "POST" : "GET",
						full_url, url_arguments);

		g_string_append_printf(request, "Authorization: %s\r\n", full_header);
		g_free(full_header);
		g_free(full_url);
	} else {
		char userpass[strlen(ic->acc->user) + 2 + strlen(ic->acc->pass)];
		char *userpass_base64;

		g_snprintf(userpass, sizeof(userpass), "%s:%s", ic->acc->user, ic->acc->pass);
		userpass_base64 = base64_encode((unsigned char *) userpass, strlen(userpass));
		g_string_append_printf(request, "Authorization: Basic %s\r\n", userpass_base64);
		g_free(userpass_base64);
	}

	// Do POST stuff..
	if (is_post) {
		// Append the Content-Type and url-encoded arguments.
		g_string_append_printf(request,
				       "Content-Type: application/x-www-form-urlencoded\r\n"
				       "Content-Length: %zd\r\n\r\n%s",
				       strlen(url_arguments), url_arguments);
	} else {
		// Append an extra \r\n to end the request...
		g_string_append(request, "\r\n");
	}

	ret = http_dorequest(td->url_host, td->url_port, td->url_ssl, request->str, func, data);

	g_free(url_arguments);
	g_string_free(request, TRUE);
	return ret;
}
示例#29
0
文件: file.c 项目: tal-nino/gnokii
GNOKII_API gint DB_Look (const gchar * const phone)
{
  DIR *dir;
  struct dirent *dirent;
  FILE *smsFile;
  GString *buf;
  gint numError, error;
  gint empty = 1;


  if (spool[0] == '\0')  // if user don't set spool dir, sending is disabled
    return (SMSD_NOK);
    
  if ((dir = opendir (spool)) == NULL)
  {
    g_print (_("Cannot open directory %s\n"), spool);
    return (SMSD_NOK);
  }

  buf = g_string_sized_new (64);
  
  while ((dirent = readdir (dir)))
  {
    gn_sms sms;
    gint slen = 0;
    
    if (strcmp (dirent->d_name, ".") == 0 || strcmp (dirent->d_name, "..") == 0 ||
        strncmp (dirent->d_name, "ERR.", 4) == 0)
      continue;
    
    g_string_printf (buf, "%s/%s", spool, dirent->d_name);
    
    if ((smsFile = fopen (buf->str, "r")) == NULL)
    {
      g_print (_("Can't open file %s for reading!\n"), buf->str);
      continue;
    }
    
    empty = 0;
    gn_sms_default_submit (&sms);
    memset (&sms.remote.number, 0, sizeof (sms.remote.number));

    if (fgets (sms.remote.number, sizeof (sms.remote.number), smsFile))
      slen = strlen (sms.remote.number);
    if (slen < 1)
    {
      error = -1;
      fclose (smsFile);
      g_print (_("Remote number is empty in %s!\n"), buf->str);
      goto handle_file;
    }
    
    if (sms.remote.number[slen - 1] == '\n')
      sms.remote.number[slen - 1] = '\0';
    
    /* Initialize SMS text */
    memset (&sms.user_data[0].u.text, 0, sizeof (sms.user_data[0].u.text));
    
    slen = fread ((gchar *) sms.user_data[0].u.text, 1, GN_SMS_MAX_LENGTH, smsFile);
    if (slen > 0 && sms.user_data[0].u.text[slen - 1] == '\n')
      sms.user_data[0].u.text[slen - 1] = '\0';
     
    fclose (smsFile);
    
//    sms.delivery_report = (smsdConfig.smsSets & SMSD_READ_REPORTS);

    if (sms.remote.number[0] == '+')
      sms.remote.type = GN_GSM_NUMBER_International;
    else
      sms.remote.type = GN_GSM_NUMBER_Unknown;
    
    sms.user_data[0].length = strlen ((gchar *) sms.user_data[0].u.text);
    sms.user_data[0].type = GN_SMS_DATA_Text;
    sms.user_data[1].type = GN_SMS_DATA_None;
    if (!gn_char_def_alphabet (sms.user_data[0].u.text))
       sms.dcs.u.general.alphabet = GN_SMS_DCS_UCS2;


    gn_log_xdebug ("Sending SMS: %s, %s\n", sms.remote.number, sms.user_data[0].u.text);
    
    numError = 0;
    do
    {
      error = WriteSMS (&sms);
      sleep (1);
    }
    while ((error == GN_ERR_TIMEOUT || error == GN_ERR_FAILED) && numError++ < 3);

 handle_file:
    if (error == GN_ERR_NONE)
    {
      if (unlink (buf->str))
        g_print (_("Cannot unlink %s."), buf->str);
    }
    else
    {
      GString *buf2;
      
      buf2 = g_string_sized_new (64);
      g_string_printf (buf2, "%s/ERR.%s", spool, dirent->d_name);
      
      g_print (_("Cannot send sms from file %s\n"), buf->str);
      if (rename (buf->str, buf2->str))
      {
        g_print (_("Cannot rename file %s to %s. Trying to unlink it.\n"),
                 buf->str, buf2->str);
        if (unlink (buf->str))
          g_print (_("Cannot unlink %s."), buf->str);
      }
      g_string_free (buf2, TRUE);
    }
  }
  
  g_string_free (buf, TRUE);
  closedir (dir);

  if (empty)
    return (SMSD_OUTBOXEMPTY);
  else
    return (SMSD_OK);
}
void cd_clock_load_theme (GldiModuleInstance *myApplet)
{
	cd_message ("%s (%s)", __func__, myConfig.cThemePath);
	//\_______________ On charge le theme choisi (on n'a pas besoin de connaitre les dimmensions de l'icone).
	if (myConfig.cThemePath != NULL)
	{
		GString *sElementPath = g_string_new ("");
		int i;
		for (i = 0; i < CLOCK_ELEMENTS; i ++)
		{
			g_string_printf (sElementPath, "%s/%s", myConfig.cThemePath, s_cFileNames[i]);
			myData.pSvgHandles[i] = rsvg_handle_new_from_file (sElementPath->str, NULL);
		}
		i = 0;
		while (i < CLOCK_FRAME && myData.pSvgHandles[i] == NULL)
		{
			i ++;
			if (i == CLOCK_HOUR_HAND_SHADOW)
				i = CLOCK_FACE_SHADOW;
		}
		if (i != CLOCK_FRAME)
			rsvg_handle_get_dimensions (myData.pSvgHandles[i], &myData.DimensionData);
		if (myData.pSvgHandles[CLOCK_HOUR_HAND] != NULL)
			rsvg_handle_get_dimensions (myData.pSvgHandles[CLOCK_HOUR_HAND], &myData.needleDimension);
		cd_debug ("clock bg dimension : %dx%d", (int) myData.DimensionData.width, (int) myData.DimensionData.height);
		cd_debug ("clock needle dimension : %dx%d", (int) myData.needleDimension.width, (int) myData.needleDimension.height);
		
		// recuperation des parametres des aiguilles.
		g_string_printf (sElementPath, "%s/%s", myConfig.cThemePath, "theme.conf");
		GKeyFile *pKeyFile = cairo_dock_open_key_file (sElementPath->str);
		if (pKeyFile != NULL)
		{
			GError *erreur = NULL;
			myData.iNeedleRealHeight = g_key_file_get_integer (pKeyFile, "Needle", "height", &erreur);
			if (erreur != NULL)
			{
				cd_warning (erreur->message);
				g_error_free (erreur);
				erreur = NULL;
			}
			myData.iNeedleOffsetX = g_key_file_get_double (pKeyFile, "Needle", "offset x", &erreur);
			if (erreur != NULL)
			{
				cd_warning (erreur->message);
				g_error_free (erreur);
				erreur = NULL;
			}
			g_key_file_free (pKeyFile);
		}
		else  // on prend des valeurs par defaut assez larges.
		{
			//g_print ("clock : default needle size\n");
			myData.iNeedleRealHeight = .5 * myData.needleDimension.height;
			myData.iNeedleOffsetX = .5 * myData.needleDimension.width;
		}
		myData.iNeedleRealWidth = myData.needleDimension.width/2 + myData.iNeedleOffsetX;
		myData.iNeedleOffsetY = .5 * myData.iNeedleRealHeight;
		cd_debug ("clock needle : H=%d; dx=%d", myData.iNeedleRealHeight, myData.iNeedleOffsetX);
		
		g_string_free (sElementPath, TRUE);
	}
	else
	{
		myData.DimensionData.width = 48;  // valeurs par defaut si aucun theme trouve.
		myData.DimensionData.height = 48;
		myData.needleDimension.width = 48;
		myData.needleDimension.height = 48;
	}
}