static void
get_device_info (RBGenericPlayerSource *source)
{
	RBGenericPlayerSourcePrivate *priv = GENERIC_PLAYER_SOURCE_GET_PRIVATE (source);
	GMount *mount;
	GFile *is_audio_player;
	GError *error = NULL;
#ifdef HAVE_HAL
	LibHalContext *ctx;
#endif
	g_object_get (source, "mount", &mount, NULL);

#ifdef HAVE_HAL
	ctx = get_hal_context ();
	if (ctx != NULL) {
		char *udi;

		udi = get_hal_udi_for_player (ctx, mount);

		if (udi != NULL) {
			DBusError error;
			char *prop;
			char **proplist;
			int value;

			/* get audio folders */
			dbus_error_init (&error);
			proplist = libhal_device_get_property_strlist (ctx, udi, "portable_audio_player.audio_folders", &error);
			if (proplist) {
				if (!dbus_error_is_set (&error)) {
					priv->audio_folders = g_strdupv (proplist);
				}
				libhal_free_string_array (proplist);
			}
			free_dbus_error ("getting audio folder list", &error);

			/* get supported mime-types */
			dbus_error_init (&error);
			proplist = libhal_device_get_property_strlist (ctx, udi, "portable_audio_player.output_formats", &error);
			if (proplist) {
				if (!dbus_error_is_set (&error)) {
					priv->output_mime_types = g_strdupv (proplist);
				}
				libhal_free_string_array (proplist);
			}
			free_dbus_error ("getting supported mime-type list", &error);

			/* get playlist format */
			dbus_error_init (&error);
			proplist = libhal_device_get_property_strlist (ctx, udi, "portable_audio_player.playlist_format", &error);
			if (proplist) {
				if (!dbus_error_is_set (&error)) {
					set_playlist_formats (source, proplist);
				}
				libhal_free_string_array (proplist);
			}
			free_dbus_error ("getting playlist format", &error);

			/* get playlist path - in current hal-info packages, this is sometimes a string
			 * and sometimes a strlist, so try both. 
			 * http://bugs.freedesktop.org/show_bug.cgi?id=19961
			 */
			dbus_error_init (&error);
			proplist = libhal_device_get_property_strlist (ctx, udi, "portable_audio_player.playlist_path", &error);
			if (proplist && !dbus_error_is_set (&error)) {
				set_playlist_path (source, proplist[0]);
				libhal_free_string_array (proplist);
			}
			free_dbus_error ("getting playlist path (strlist)", &error);
			
			dbus_error_init (&error);
			prop = libhal_device_get_property_string (ctx, udi, "portable_audio_player.playlist_path", &error);
			if (prop && !dbus_error_is_set (&error)) {
				set_playlist_path (source, prop);
				libhal_free_string (prop);
			}
			free_dbus_error ("getting playlist path (string)", &error);

			/* get max folder depth */
			dbus_error_init (&error);
			value = libhal_device_get_property_int (ctx, udi, "portable_audio_player.folder_depth", &error);
			if (!dbus_error_is_set (&error)) {
				priv->folder_depth = value;
			}
			free_dbus_error ("getting max folder depth", &error);

			debug_device_info (source, mount, "HAL");
		} else {
			rb_debug ("no player info available (HAL doesn't recognise it as a player");
		}
		g_free (udi);
	}
	cleanup_hal_context (ctx);
#endif

	/* allow HAL info to be overridden with .is_audio_player file */
	is_audio_player = get_is_audio_player_file (mount);
	if (is_audio_player != NULL) {
		char *data = NULL;
		gsize data_size = 0;

		rb_debug ("reading .is_audio_player file");

		g_file_load_contents (is_audio_player, NULL, &data, &data_size, NULL, &error);
		if (error != NULL) {
			/* can we sensibly report this anywhere? */
			rb_debug ("error reading .is_audio_player file: %s", error->message);
			g_clear_error (&error);
		} else {
			GKeyFile *keyfile;
			GError *error = NULL;
			char *munged;
			gsize munged_size;
			const char *fake_group = "[x-rb-data]\n";
			char *group;

			/* prepend a group name to the file contents */
			munged_size = data_size + strlen (fake_group);
			munged = g_malloc0 (munged_size + 1);
			strcpy (munged, fake_group);
			memcpy (munged + strlen (fake_group), data, data_size);

			keyfile = g_key_file_new ();
			g_key_file_set_list_separator (keyfile, ',');
			if (g_key_file_load_from_data (keyfile, munged, munged_size, G_KEY_FILE_NONE, &error) == FALSE) {
				/* and this */
				rb_debug ("error loading .is_audio_player file: %s", error->message);
				g_error_free (error);
			} else {
				char *value;
				char **list;

				group = g_key_file_get_start_group (keyfile);
				
				list = g_key_file_get_string_list (keyfile, group, "audio_folders", NULL, NULL);
				if (list != NULL) {
					g_strfreev (priv->audio_folders);
					priv->audio_folders = list;
				}

				list = g_key_file_get_string_list (keyfile, group, "output_formats", NULL, NULL);
				if (list != NULL) {
					g_strfreev (priv->output_mime_types);
					priv->output_mime_types = list;
				}
				
				list = g_key_file_get_string_list (keyfile, group, "playlist_format", NULL, NULL);
				if (list != NULL) {
					set_playlist_formats (source, list);
					g_strfreev (list);
				}

				value = g_key_file_get_string (keyfile, group, "playlist_path", NULL);
				if (value != NULL) {
					set_playlist_path (source, value);
					g_free (value);
				}

				if (g_key_file_has_key (keyfile, group, "folder_depth", NULL)) {
					priv->folder_depth = g_key_file_get_integer (keyfile, group, "folder_depth", NULL);
				}
				g_free (group);
			}

			g_key_file_free (keyfile);
			g_free (munged);
			
			debug_device_info (source, mount, ".is_audio_player file");
		}
		g_free (data);

		g_object_unref (is_audio_player);
	} else {
		rb_debug ("no .is_audio_player file found on this device");
	}

	g_object_unref (mount);
}
示例#2
0
void
mud_telnet_charset_handle_sub_neg(MudTelnetHandler *handler,
                               guchar *buf,
                               guint len)
{
    gint index = 0;
    guchar sep;
    guchar tbuf[9];
    gchar sep_buf[2];
    GString *encoding;
    gchar **encodings;
    MudTelnetCharset *self;

    self = MUD_TELNET_CHARSET(handler);

    g_return_if_fail(MUD_IS_TELNET_CHARSET(self));

    switch(buf[index])
    {
        case TEL_CHARSET_REQUEST:
            // Check for [TTABLE] and
            // reject if found.
            memcpy(tbuf, &buf[1], 8);
            tbuf[8] = '\0';

            if(strcmp((gchar *)tbuf, "[TTABLE]") == 0)
            {
                mud_telnet_send_sub_req(self->priv->telnet, 2,
                        (guchar)TELOPT_CHARSET,
                        (guchar)TEL_CHARSET_TTABLE_REJECTED);
                return;
            }

            sep = buf[++index];
            index++;

            encoding = g_string_new(NULL);

            while(buf[index] != (guchar)TEL_SE)
                encoding = g_string_append_c(encoding, buf[index++]);

            sep_buf[0] = (gchar)sep;
            sep_buf[1] = '\0';
            encodings = g_strsplit(encoding->str, sep_buf, -1);

            /* We are using VTE's locale fallback function
               to handle a charset we do not support so we
               just take the first returned and use it.

               This is potentially stupid. Fix me? */

            if(g_strv_length(encodings) != 0)
            {
                MudConnectionView *view;
                g_object_get(self->priv->telnet, "parent-view", &view, NULL);

                g_object_set(view,
                        "remote-encode", TRUE,
                        "remote-encoding", encodings[0],
                        NULL);


                mud_telnet_charset_send(self, encodings[0]);
            }

            g_string_free(encoding, TRUE);
            g_strfreev(encodings);

            break;
    }
}
示例#3
0
static void
add_data_tab (const gchar *demoname)
{
  gchar *resource_dir, *resource_name;
  gchar **resources;
  GtkWidget *widget, *label;
  guint i;

  resource_dir = g_strconcat ("/", demoname, NULL);
  resources = g_resources_enumerate_children (resource_dir, 0, NULL);
  if (resources == NULL)
    {
      g_free (resource_dir);
      return;
    }

  for (i = 0; resources[i]; i++)
    {
      resource_name = g_strconcat (resource_dir, "/", resources[i], NULL);

      widget = gtk_image_new_from_resource (resource_name);
      if (gtk_image_get_pixbuf (GTK_IMAGE (widget)) == NULL &&
          gtk_image_get_animation (GTK_IMAGE (widget)) == NULL)
        {
          GBytes *bytes;

          /* So we've used the best API available to figure out it's
           * not an image. Let's try something else then.
           */
          g_object_ref_sink (widget);
          g_object_unref (widget);

          bytes = g_resources_lookup_data (resource_name, 0, NULL);
          g_assert (bytes);

          if (g_utf8_validate (g_bytes_get_data (bytes, NULL), g_bytes_get_size (bytes), NULL))
            {
              /* Looks like it parses as text. Dump it into a textview then! */
              GtkTextBuffer *buffer;
              GtkWidget *textview;

              widget = create_text (&textview, FALSE);
              buffer = gtk_text_buffer_new (NULL);
              gtk_text_buffer_set_text (buffer, g_bytes_get_data (bytes, NULL), g_bytes_get_size (bytes));
              if (g_str_has_suffix (resource_name, ".c"))
                fontify (buffer);
              gtk_text_view_set_buffer (GTK_TEXT_VIEW (textview), buffer);
            }
          else
            {
              g_warning ("Don't know how to display resource '%s'", resource_name);
              widget = NULL;
            }

          g_bytes_unref (bytes);
        }

      gtk_widget_show_all (widget);
      label = gtk_label_new (resources[i]);
      gtk_widget_show (label);
      gtk_notebook_append_page (GTK_NOTEBOOK (notebook), widget, label);
      gtk_container_child_set (GTK_CONTAINER (notebook),
                               GTK_WIDGET (widget),
                               "tab-expand", TRUE,
                               NULL);

      g_free (resource_name);
    }

  g_strfreev (resources);
  g_free (resource_dir);
}
示例#4
0
/* Initialize the tracing system */
void
_priv_gst_tracing_init (void)
{
  gint i = 0;
  const gchar *env = g_getenv ("GST_TRACERS");

  /* We initialize the tracer sub system even if the end
   * user did not activate it through the env variable
   * so that external tools can use it anyway */
  GST_DEBUG ("Initializing GstTracer");
  _priv_tracers = g_hash_table_new (NULL, NULL);

  if (G_N_ELEMENTS (_quark_strings) != GST_TRACER_QUARK_MAX)
    g_warning ("the quark table is not consistent! %d != %d",
        (gint) G_N_ELEMENTS (_quark_strings), GST_TRACER_QUARK_MAX);

  for (i = 0; i < GST_TRACER_QUARK_MAX; i++) {
    _priv_gst_tracer_quark_table[i] =
        g_quark_from_static_string (_quark_strings[i]);
  }

  if (env != NULL && *env != '\0') {
    GstRegistry *registry = gst_registry_get ();
    GstPluginFeature *feature;
    GstTracerFactory *factory;
    gchar **t = g_strsplit_set (env, ";", 0);
    gchar *params;

    GST_INFO ("enabling tracers: '%s'", env);
    i = 0;
    while (t[i]) {
      // check t[i] for params
      if ((params = strchr (t[i], '('))) {
        gchar *end = strchr (&params[1], ')');
        *params = '\0';
        params++;
        if (end)
          *end = '\0';
      } else {
        params = NULL;
      }

      GST_INFO ("checking tracer: '%s'", t[i]);

      if ((feature = gst_registry_lookup_feature (registry, t[i]))) {
        factory = GST_TRACER_FACTORY (gst_plugin_feature_load (feature));
        if (factory) {
          GstTracer *tracer;

          GST_INFO_OBJECT (factory, "creating tracer: type-id=%u",
              (guint) factory->type);

          tracer = g_object_new (factory->type, "params", params, NULL);

          /* Clear floating flag */
          gst_object_ref_sink (tracer);

          /* tracers register them self to the hooks */
          gst_object_unref (tracer);
        } else {
          GST_WARNING_OBJECT (feature,
              "loading plugin containing feature %s failed!", t[i]);
        }
      } else {
        GST_WARNING ("no tracer named '%s'", t[i]);
      }
      i++;
    }
    g_strfreev (t);
  }
}
示例#5
0
static void paste(GeanyDocument * doc, const gchar * website)
{
    SoupSession *session;
    SoupMessage *msg = NULL;

    gchar *f_content;
    gchar const *f_type;
    gchar *f_title;
    gchar *p_url;
    gchar *formdata = NULL;
    gchar *user_agent = NULL;
    gchar *temp_body;
    gchar **tokens_array;

    const gchar *langs_supported_codepad[] =
    {
        "C", "C++", "D", "Haskell",
        "Lua", "OCaml", "PHP", "Perl", "Plain Text",
        "Python", "Ruby", "Scheme", "Tcl"
    };

    const gchar *langs_supported_dpaste[] =
    {
        "Bash", "C", "CSS", "Diff",
        "Django/Jinja", "HTML", "IRC logs", "JavaScript", "PHP",
        "Python console session", "Python Traceback", "Python",
        "Python3", "Restructured Text", "SQL", "Text only"
    };

    gint occ_position;
    gint i;
    guint status;
    gsize f_length;

    g_return_if_fail(doc && doc->is_valid);

    f_type = doc->file_type->name;

    if (doc->file_name == NULL)
        f_title = document_get_basename_for_display(doc, -1);
    else
        f_title = g_path_get_basename(doc->file_name);

    load_settings();

    f_content = get_paste_text(doc, &f_length);
    if (f_content == NULL || f_content[0] == '\0')
    {
        dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Refusing to create blank paste"));
        return;
    }

    switch (website_selected)
    {

    case CODEPAD_ORG:

        for (i = 0; i < G_N_ELEMENTS(langs_supported_codepad); i++)
        {
            if (g_strcmp0(f_type, langs_supported_codepad[i]) == 0)
                break;
            else
                f_type = DEFAULT_TYPE_CODEPAD;
        }

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("lang", f_type, "code", f_content,
                                    "submit", "Submit", NULL);

        break;

    case PASTEBIN_COM:

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("paste_code", f_content, "paste_format",
                                    f_type, "paste_name", f_title, NULL);

        break;


    case DPASTE_DE:

        for (i = 0; i < G_N_ELEMENTS(langs_supported_dpaste); i++)
        {
            if (g_strcmp0(f_type, langs_supported_dpaste[i]) == 0)
                break;
            else
                f_type = DEFAULT_TYPE_DPASTE;
        }

        msg = soup_message_new("POST", website);
        /* apparently dpaste.de detects automatically the syntax of the
         * pasted code so 'lexer' should be unneeded
         */
        formdata = soup_form_encode("content", f_content, "title", f_title,
                                    "lexer", f_type, NULL);

        break;

    case SPRUNGE_US:

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("sprunge", f_content, NULL);

        break;

    case PASTEBIN_GEANY_ORG:

        msg = soup_message_new("POST", website);
        formdata = soup_form_encode("content", f_content, "author", author_name,
                                    "title", f_title, "lexer", f_type, NULL);

        break;

    }

    user_agent = g_strconcat(PLUGIN_NAME, " ", PLUGIN_VERSION, " / Geany ", GEANY_VERSION, NULL);
    session = soup_session_async_new_with_options(SOUP_SESSION_USER_AGENT, user_agent, NULL);
    g_free(user_agent);

    soup_message_set_request(msg, "application/x-www-form-urlencoded",
                             SOUP_MEMORY_COPY, formdata, strlen(formdata));

    status = soup_session_send_message(session, msg);
    p_url = g_strdup(msg->response_body->data);

    if(status == SOUP_STATUS_OK)
    {

        /*
         * codepad.org doesn't return only the url of the new snippet pasted
         * but an html page. This minimal parser will get the bare url.
         */

        if (website_selected == CODEPAD_ORG)
        {
            temp_body = g_strdup(p_url);
            tokens_array = g_strsplit(temp_body, "<a href=\"", 0);

            /* cuts the string when it finds the first occurrence of '/'
             * It shoud work even if codepad would change its url.
             */

            p_url = g_strdup(tokens_array[5]);
            occ_position = indexof(tokens_array[5], '\"');

            g_free(temp_body);
            g_strfreev(tokens_array);

            if(occ_position != -1)
            {
                p_url[occ_position] = '\0';
            }
            else
            {
                dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Unable to paste the code on codepad.org\n"
                                    "Retry or select another pastebin."));
                g_free(p_url);
                return;
            }

        }
        else if(website_selected == DPASTE_DE)
        {
            p_url = g_strndup(p_url + 1, strlen(p_url) - 2);

        }
        else if(website_selected == SPRUNGE_US)
        {

            /* in order to enable the syntax highlightning on sprunge.us
             * it is necessary to append at the returned url a question
             * mark '?' followed by the file type.
             *
             * e.g. sprunge.us/xxxx?c
             */
            gchar *ft_tmp = g_ascii_strdown(f_type, -1);
            p_url[strlen(p_url) - 1] = '\0';
            temp_body = g_strdup_printf("?%s", ft_tmp);
            g_strlcat(p_url + 1, temp_body, -1);
            p_url = g_strstrip(p_url);
            g_free(temp_body);
            g_free(ft_tmp);
        }

        if (check_button_is_checked)
        {
            utils_open_browser(p_url);
        }
        else
        {
            GtkWidget *dlg = gtk_message_dialog_new(GTK_WINDOW(geany->main_widgets->window),
                GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK,
                _("Paste Successful"));
            gtk_message_dialog_format_secondary_markup(GTK_MESSAGE_DIALOG(dlg),
                _("Your paste can be found here:\n<a href=\"%s\" "
                "title=\"Click to open the paste in your browser\">%s</a>"), p_url, p_url);
            gtk_dialog_run(GTK_DIALOG(dlg));
            gtk_widget_destroy(dlg);
        }
    }
    else
    {
        dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Unable to paste the code. Check your connection and retry.\n"
                            "Error code: %d\n"), status);
    }

    g_free(f_content);
    g_free(p_url);
    g_object_unref(session);
}
示例#6
0
static void parse_config(GKeyFile *config)
{
	GError *error = NULL;
	gboolean boolean;
	char **timeservers;
	char **interfaces;
	char **str_list;
	gsize len;
	int timeout;

	if (config == NULL) {
		connman_settings.auto_connect =
			parse_service_types(default_auto_connect, 3);
		connman_settings.blacklisted_interfaces =
			g_strdupv(default_blacklist);
		return;
	}

	DBG("parsing main.conf");

	boolean = g_key_file_get_boolean(config, "General",
						"BackgroundScanning", &error);
	if (error == NULL)
		connman_settings.bg_scan = boolean;

	g_clear_error(&error);

	timeservers = g_key_file_get_string_list(config, "General",
						"FallbackTimeservers", NULL, &error);
	if (error == NULL)
		connman_settings.pref_timeservers = timeservers;

	g_clear_error(&error);

	str_list = g_key_file_get_string_list(config, "General",
			"DefaultAutoConnectTechnologies", &len, &error);

	if (error == NULL)
		connman_settings.auto_connect =
			parse_service_types(str_list, len);
	else
		connman_settings.auto_connect =
			parse_service_types(default_auto_connect, 3);

	g_strfreev(str_list);

	g_clear_error(&error);

	str_list = g_key_file_get_string_list(config, "General",
			"PreferredTechnologies", &len, &error);

	if (error == NULL)
		connman_settings.preferred_techs =
			parse_service_types(str_list, len);

	g_strfreev(str_list);

	g_clear_error(&error);

	str_list = g_key_file_get_string_list(config, "General",
			"FallbackNameservers", &len, &error);

	if (error == NULL)
		connman_settings.fallback_nameservers =
			parse_fallback_nameservers(str_list, len);

	g_strfreev(str_list);

	g_clear_error(&error);

	timeout = g_key_file_get_integer(config, "General",
			"InputRequestTimeout", &error);
	if (error == NULL && timeout >= 0)
		connman_settings.timeout_inputreq = timeout * 1000;

	g_clear_error(&error);

	timeout = g_key_file_get_integer(config, "General",
			"BrowserLaunchTimeout", &error);
	if (error == NULL && timeout >= 0)
		connman_settings.timeout_browserlaunch = timeout * 1000;

	g_clear_error(&error);

	interfaces = g_key_file_get_string_list(config, "General",
			"NetworkInterfaceBlacklist", &len, &error);

	if (error == NULL)
		connman_settings.blacklisted_interfaces = interfaces;
	else
		connman_settings.blacklisted_interfaces =
			g_strdupv(default_blacklist);

	g_clear_error(&error);
}
示例#7
0
gboolean
g_spawn_command_line_sync (const gchar *command_line,
				gchar **standard_output,
				gchar **standard_error,
				gint *exit_status,
				GError **error)
{
#ifdef G_OS_WIN32
#else
	pid_t pid;
	gchar **argv;
	gint argc;
	int stdout_pipe [2] = { -1, -1 };
	int stderr_pipe [2] = { -1, -1 };
	int status;
	int res;
	
	if (!g_shell_parse_argv (command_line, &argc, &argv, error))
		return FALSE;

	if (standard_output && !create_pipe (stdout_pipe, error))
		return FALSE;

	if (standard_error && !create_pipe (stderr_pipe, error)) {
		if (standard_output) {
			CLOSE_PIPE (stdout_pipe);
		}
		return FALSE;
	}

	pid = fork ();
	if (pid == 0) {
		gint i;

		if (standard_output) {
			close (stdout_pipe [0]);
			dup2 (stdout_pipe [1], STDOUT_FILENO);
		}

		if (standard_error) {
			close (stderr_pipe [0]);
			dup2 (stderr_pipe [1], STDERR_FILENO);
		}
		for (i = g_getdtablesize () - 1; i >= 3; i--)
			close (i);

		/* G_SPAWN_SEARCH_PATH is always enabled for g_spawn_command_line_sync */
		if (!g_path_is_absolute (argv [0])) {
			gchar *arg0;

			arg0 = g_find_program_in_path (argv [0]);
			if (arg0 == NULL) {
				exit (1);
			}
			//g_free (argv [0]);
			argv [0] = arg0;
		}
		execv (argv [0], argv);
		exit (1); /* TODO: What now? */
	}

	g_strfreev (argv);
	if (standard_output)
		close (stdout_pipe [1]);

	if (standard_error)
		close (stderr_pipe [1]);

	if (standard_output || standard_error) {
		res = read_pipes (stdout_pipe [0], standard_output, stderr_pipe [0], standard_error, error);
		if (res) {
			waitpid (pid, &status, WNOHANG); /* avoid zombie */
			return FALSE;
		}
	}

	NO_INTR (res, waitpid (pid, &status, 0));

	/* TODO: What if error? */
	if (WIFEXITED (status) && exit_status) {
		*exit_status = WEXITSTATUS (status);
	}
#endif
	return TRUE;
}
示例#8
0
gboolean ptk_dir_tree_view_chdir( GtkTreeView* dir_tree_view, const char* path )
{
    GtkTreeModel * model;
    GtkTreeIter it, parent_it;
    GtkTreePath* tree_path = NULL;
    gchar **dirs, **dir;
    gboolean found;
    VFSFileInfo* info;

    if ( !path || *path != '/' )
        return FALSE;

    dirs = g_strsplit( path + 1, "/", -1 );

    if ( !dirs )
        return FALSE;

    model = gtk_tree_view_get_model( dir_tree_view );

    if ( ! gtk_tree_model_iter_children ( model, &parent_it, NULL ) )
    {
        g_strfreev( dirs );
        return FALSE;
    }

    /* special case: root dir */
    if ( ! dirs[ 0 ] )
    {
        it = parent_it;
        tree_path = gtk_tree_model_get_path ( model, &parent_it );
        goto _found;
    }

    for ( dir = dirs; *dir; ++dir )
    {
        if ( ! gtk_tree_model_iter_children ( model, &it, &parent_it ) )
        {
            g_strfreev( dirs );
            return FALSE;
        }
        found = FALSE;
        do
        {
            gtk_tree_model_get( model, &it, COL_DIR_TREE_INFO, &info, -1 );
            if ( !info )
                continue;
            if ( 0 == strcmp( vfs_file_info_get_name( info ), *dir ) )
            {
                tree_path = gtk_tree_model_get_path( model, &it );

                if( dir[1] ) {
                    gtk_tree_view_expand_row ( dir_tree_view, tree_path, FALSE );
                    gtk_tree_model_get_iter( model, &parent_it, tree_path );
                }
                found = TRUE;
                vfs_file_info_unref( info );
                break;
            }
            vfs_file_info_unref( info );
        }
        while ( gtk_tree_model_iter_next( model, &it ) );

        if ( ! found )
            return FALSE; /* Error! */

        if ( tree_path && dir[ 1 ] )
        {
            gtk_tree_path_free( tree_path );
            tree_path = NULL;
        }
    }
_found:
    g_strfreev( dirs );
    gtk_tree_selection_select_path (
        gtk_tree_view_get_selection( dir_tree_view ), tree_path );

    gtk_tree_view_scroll_to_cell ( dir_tree_view, tree_path, NULL, FALSE, 0.5, 0.5 );

    gtk_tree_path_free( tree_path );

    return TRUE;
}
示例#9
0
void on_dir_tree_view_drag_data_received ( GtkWidget *widget,
                                         GdkDragContext *drag_context,
                                         gint x,
                                         gint y,
                                         GtkSelectionData *sel_data,
                                         guint info,
                                         guint time,
                                         gpointer user_data )  //MOD added
{
    gchar **list, **puri;
    GList* files = NULL;
    PtkFileTask* task;
    VFSFileTaskType file_action = VFS_FILE_TASK_MOVE;
    PtkFileBrowser* file_browser = ( PtkFileBrowser* ) user_data;
    char* dest_dir;
    char* file_path;
    GtkWidget* parent_win;

    /*  Don't call the default handler  */
    g_signal_stop_emission_by_name( widget, "drag-data-received" );

    if ( ( gtk_selection_data_get_length( sel_data ) >= 0 ) && ( gtk_selection_data_get_format( sel_data ) == 8 ) )
    {
        dest_dir = dir_tree_view_get_drop_dir( widget, x, y );
        if ( dest_dir )
        {
            puri = list = gtk_selection_data_get_uris( sel_data );
            if( file_browser->pending_drag_status_tree )
            {
                // We only want to update drag status, not really want to drop
                dev_t dest_dev;
                struct stat statbuf;    // skip stat64
                if( stat( dest_dir, &statbuf ) == 0 )
                {
                    dest_dev = statbuf.st_dev;
                    if( 0 == file_browser->drag_source_dev_tree )
                    {
                        file_browser->drag_source_dev_tree = dest_dev;
                        for( ; *puri; ++puri )
                        {
                            file_path = g_filename_from_uri( *puri, NULL, NULL );
                            if( stat( file_path, &statbuf ) == 0 && statbuf.st_dev != dest_dev )
                            {
                                file_browser->drag_source_dev_tree = statbuf.st_dev;
                                g_free( file_path );
                                break;
                            }
                            g_free( file_path );
                        }
                    }
                    if( file_browser->drag_source_dev_tree != dest_dev )
                        // src and dest are on different devices */
                        gdk_drag_status( drag_context, GDK_ACTION_COPY, time);
                    else
                        gdk_drag_status( drag_context, GDK_ACTION_MOVE, time);
                }
                else
                    // stat failed
                    gdk_drag_status( drag_context, GDK_ACTION_COPY, time);

                g_free( dest_dir );
                g_strfreev( list );
                file_browser->pending_drag_status_tree = 0;
                return;
            }

            if ( puri )
            {
                if ( 0 == ( gdk_drag_context_get_selected_action ( drag_context ) &
                            ( GDK_ACTION_MOVE | GDK_ACTION_COPY | GDK_ACTION_LINK ) ) )
                {
                    gdk_drag_status( drag_context, GDK_ACTION_MOVE, time);
                }
                gtk_drag_finish ( drag_context, TRUE, FALSE, time );

                while ( *puri )
                {
                    if ( **puri == '/' )
                        file_path = g_strdup( *puri );
                    else
                        file_path = g_filename_from_uri( *puri, NULL, NULL );

                    if ( file_path )
                        files = g_list_prepend( files, file_path );
                    ++puri;
                }
                g_strfreev( list );

                switch ( gdk_drag_context_get_selected_action ( drag_context ) )
                {
                case GDK_ACTION_COPY:
                    file_action = VFS_FILE_TASK_COPY;
                    break;
                case GDK_ACTION_LINK:
                    file_action = VFS_FILE_TASK_LINK;
                    break;
                    /* FIXME:
                      GDK_ACTION_DEFAULT, GDK_ACTION_PRIVATE, and GDK_ACTION_ASK are not handled */
                default:
                    break;
                }
                if ( files )
                {
                    /* Accept the drop and perform file actions */
                    {
                        parent_win = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
                        task = ptk_file_task_new( file_action,
                                                  files,
                                                  dest_dir,
                                                  GTK_WINDOW( parent_win ),
                                                  file_browser->task_view );
                        ptk_file_task_run( task );
                    }
                }
                g_free( dest_dir );
                gtk_drag_finish ( drag_context, TRUE, FALSE, time );
                return ;
            }
            g_free( dest_dir );
        }
        //else
        //    g_warning ("bad dest_dir in on_dir_tree_view_drag_data_received");
    }
    /* If we are only getting drag status, not finished. */
    if( file_browser->pending_drag_status_tree )
    {
        gdk_drag_status ( drag_context, GDK_ACTION_COPY, time );
        file_browser->pending_drag_status_tree = 0;
        return;
    }
    gtk_drag_finish ( drag_context, FALSE, FALSE, time );
}
示例#10
0
int bt_obex(int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

	/* Query current locale */
	setlocale(LC_CTYPE, "");

	g_type_init();
	dbus_init();

	context = g_option_context_new(" - a bluetooth OBEX client/server");
	g_option_context_add_main_entries(context, entries, NULL);
	g_option_context_set_summary(context, "Version "PACKAGE_VERSION);
	g_option_context_set_description(context,
			"Server Options:\n"
			"  -s, --server [<path>]\n"
			"  Register self at OBEX server and use given `path` as OPP save directory\n"
			"  If `path` does not specified - use current directory\n\n"
			"OPP Options:\n"
			"  -p, --opp <name|mac> <file>\n"
			"  Send `file` to remote device using Object Push Profile\n\n"
			//"Report bugs to <"PACKAGE_BUGREPORT">."
			"Project home page <"PACKAGE_URL">."
			);

	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("%s: %s\n", g_get_prgname(), error->message);
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (!server_arg && !opp_arg && (!ftp_arg || strlen(ftp_arg) == 0)) {
		g_print("%s", g_option_context_get_help(context, FALSE, NULL));
		exit(EXIT_FAILURE);
	} else if (server_arg && argc != 1 && (argc != 2 || strlen(argv[1]) == 0)) {
		g_print("%s: Invalid arguments for --server\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (opp_arg && (argc != 3 || strlen(argv[1]) == 0 || strlen(argv[2]) == 0)) {
		g_print("%s: Invalid arguments for --opp\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	}

	g_option_context_free(context);

	if (!dbus_system_connect(&error)) {
		g_printerr("Couldn't connect to DBus system bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	if (!dbus_session_connect(&error)) {
		g_printerr("Couldn't connect to DBus session bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	/* Check, that bluetooth daemon is running */
	if (!intf_supported(BLUEZ_DBUS_NAME, MANAGER_DBUS_PATH, MANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: bluez service is not found\n", g_get_prgname());
		g_printerr("Did you forget to run bluetoothd?\n");
		exit(EXIT_FAILURE);
	}

	/* Check, that obexd daemon is running */
	if (!intf_supported(OBEXS_DBUS_NAME, OBEXMANAGER_DBUS_PATH, OBEXMANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: obex service is not found\n", g_get_prgname());
		g_printerr("Did you forget to run obexd?\n");
		exit(EXIT_FAILURE);
	}

	if (server_arg) {
		if (argc == 2) {
			server_path_arg = argv[1];
		}

		/* Check that `path` is valid */
		gchar *root_folder = server_path_arg == NULL ? g_get_current_dir() : g_strdup(server_path_arg);
		if (!is_dir(root_folder, &error)) {
			exit_if_error(error);
		}

		server_transfers = g_hash_table_new(g_str_hash, g_str_equal);

		OBEXManager *manager = g_object_new(OBEXMANAGER_TYPE, NULL);
		g_signal_connect(manager, "SessionCreated", G_CALLBACK(obexmanager_session_created), NULL);
		g_signal_connect(manager, "SessionRemoved", G_CALLBACK(obexmanager_session_removed), NULL);
		g_signal_connect(manager, "TransferStarted", G_CALLBACK(obexmanager_transfer_started), NULL);
		g_signal_connect(manager, "TransferCompleted", G_CALLBACK(obexmanager_transfer_completed), NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, "RootFolder", root_folder, NULL);

		g_free(root_folder);

		obexmanager_register_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		mainloop = g_main_loop_new(NULL, FALSE);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Waiting for connections... */

		g_main_loop_unref(mainloop);

		/* Stop active transfers */
		GHashTableIter iter;
		gpointer key, value;
		g_hash_table_iter_init(&iter, server_transfers);
		while (g_hash_table_iter_next(&iter, &key, &value)) {
			OBEXTransfer *t = OBEXTRANSFER(value);
			obextransfer_cancel(t, NULL); // skip errors
			g_object_unref(t);
			g_hash_table_iter_remove(&iter);
		}
		g_hash_table_unref(server_transfers);

		obexmanager_unregister_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		g_object_unref(agent);
		g_object_unref(manager);
	} else if (opp_arg) {
		opp_device_arg = argv[1];
		opp_file_arg = argv[2];

		/* Check that `file` is valid */
		if (!is_file(opp_file_arg, &error)) {
			exit_if_error(error);
		}

		gchar * files_to_send[] = {NULL, NULL};
		files_to_send[0] = g_path_is_absolute(opp_file_arg) ? g_strdup(opp_file_arg) : get_absolute_path(opp_file_arg);

		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		gchar *dst_address = NULL;
		if (g_regex_match_simple("^\\x{2}:\\x{2}:\\x{2}:\\x{2}:\\x{2}:\\x{2}$", opp_device_arg, 0, 0)) {
			dst_address = g_strdup(opp_device_arg);
		} else {
			Device *device = find_device(adapter, opp_device_arg, &error);
			exit_if_error(error);
			dst_address = g_strdup(device_get_address(device));
			g_object_unref(device);
		}

		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue src_v = {0};
		GValue dst_v = {0};
		g_value_init(&src_v, G_TYPE_STRING);
		g_value_init(&dst_v, G_TYPE_STRING);
		g_value_set_string(&src_v, src_address);
		g_value_set_string(&dst_v, dst_address);
		g_hash_table_insert(device_dict, "Source", &src_v);
		g_hash_table_insert(device_dict, "Destination", &dst_v);

		mainloop = g_main_loop_new(NULL, FALSE);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);
		g_signal_connect(agent, "AgentReleased", G_CALLBACK(agent_released), mainloop);

		/* Sending file(s) */
		obexclient_send_files(client, device_dict, files_to_send, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Sending files process here ?? */

		g_main_loop_unref(mainloop);

		g_object_unref(agent);
		g_object_unref(client);

		g_value_unset(&src_v);
		g_value_unset(&dst_v);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
		g_free(files_to_send[0]);
		files_to_send[0] = NULL;
	} else if (ftp_arg) {
		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		Device *device = find_device(adapter, ftp_arg, &error);
		exit_if_error(error);
		gchar *dst_address = g_strdup(device == NULL ? ftp_arg : device_get_address(device));

		g_object_unref(device);
		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue src_v = {0};
		GValue dst_v = {0};
		GValue target_v = {0};
		g_value_init(&src_v, G_TYPE_STRING);
		g_value_init(&dst_v, G_TYPE_STRING);
		g_value_init(&target_v, G_TYPE_STRING);
		g_value_set_string(&src_v, src_address);
		g_value_set_string(&dst_v, dst_address);
		g_value_set_string(&target_v, "FTP");
		g_hash_table_insert(device_dict, "Source", &src_v);
		g_hash_table_insert(device_dict, "Destination", &dst_v);
		g_hash_table_insert(device_dict, "Target", &target_v);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);
		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);

		/* Create FTP session */
		gchar *session_path = obexclient_create_session(client, device_dict, &error);
		exit_if_error(error);

		OBEXClientFileTransfer *ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
		g_free(session_path);

		g_print("FTP session opened\n");

		while (TRUE) {
			gchar *cmd;
			/*
			cmd = readline("> ");
			if (cmd == NULL) {
				continue;
			} else {
				add_history(cmd);
			}
			*/
			gint f_argc;
			gchar **f_argv;
			/* Parsing command line */
			if (!g_shell_parse_argv(cmd, &f_argc, &f_argv, &error)) {
				g_print("%s\n", error->message);
				g_error_free(error);
				error = NULL;

				g_free(cmd);
				continue;
			}

			/* Execute commands */
			if (g_strcmp0(f_argv[0], "cd") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_change_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mkdir") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_create_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "ls") == 0) {
				if (f_argc != 1) {
					g_print("invalid arguments\n");
				} else {
					GPtrArray *folders = obexclient_file_transfer_list_folder(ftp_session, &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						for (int i = 0; i < folders->len; i++) {
							GHashTable *el = g_ptr_array_index(folders, i);
							g_print(
									"%s\t%llu\t%s\n",
									g_value_get_string(g_hash_table_lookup(el, "Type")),
									G_VALUE_HOLDS_UINT64(g_hash_table_lookup(el, "Size")) ?
									g_value_get_uint64(g_hash_table_lookup(el, "Size")) :
									0,
									g_value_get_string(g_hash_table_lookup(el, "Name"))
									);
						}
					}

					if (folders) g_ptr_array_unref(folders);

					/*obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
					exit_if_error(error);
					g_object_unref(ftp_session);
					session_path = obexclient_create_session(client, device_dict, &error);
					exit_if_error(error);
					ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
					g_free(session_path);*/

				}
			} else if (g_strcmp0(f_argv[0], "get") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					gchar *abs_dst_path = get_absolute_path(f_argv[2]);
					gchar *dir = g_path_get_dirname(abs_dst_path);
					if (!is_dir(dir, &error)) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						obexclient_file_transfer_get_file(ftp_session, abs_dst_path, f_argv[1], &error);
						if (error) {
							g_print("%s\n", error->message);
							g_error_free(error);
							error = NULL;
						}
					}
					g_free(dir);
					g_free(abs_dst_path);
				}
			} else if (g_strcmp0(f_argv[0], "put") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					gchar *abs_src_path = get_absolute_path(f_argv[1]);
					if (!is_file(abs_src_path, &error)) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						obexclient_file_transfer_put_file(ftp_session, abs_src_path, f_argv[2], &error);
						if (error) {
							g_print("%s\n", error->message);
							g_error_free(error);
							error = NULL;
						}
					}
					g_free(abs_src_path);
				}
			} else if (g_strcmp0(f_argv[0], "cp") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_copy_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mv") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_move_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "rm") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_delete(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "help") == 0) {
				g_print(
						"help\t\t\tShow this message\n"
						"exit\t\t\tClose FTP session\n"
						"cd <folder>\t\tChange the current folder of the remote device\n"
						"mkdir <folder>\t\tCreate a new folder in the remote device\n"
						"ls\t\t\tList folder contents\n"
						"get <src> <dst>\t\tCopy the src file (from remote device) to the dst file (on local filesystem)\n"
						"put <src> <dst>\t\tCopy the src file (from local filesystem) to the dst file (on remote device)\n"
						"cp <src> <dst>\t\tCopy a file within the remote device from src file to dst file\n"
						"mv <src> <dst>\t\tMove a file within the remote device from src file to dst file\n"
						"rm <target>\t\tDeletes the specified file/folder\n"
						);
			} else if (g_strcmp0(f_argv[0], "exit") == 0 || g_strcmp0(f_argv[0], "quit") == 0) {
				obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
				exit_if_error(error);

				g_strfreev(f_argv);
				g_free(cmd);
				break;
			} else {
				g_print("invalid command\n");
			}

			g_strfreev(f_argv);
			g_free(cmd);
		}

		g_object_unref(agent);
		g_object_unref(client);
		g_object_unref(ftp_session);

		g_value_unset(&src_v);
		g_value_unset(&dst_v);
		g_value_unset(&target_v);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
	}

	dbus_disconnect();

	exit(EXIT_SUCCESS);
}
示例#11
0
文件: dialog.c 项目: K-Sonoda/gimp
static void
browser_dialog_make_index_foreach (const gchar    *help_id,
                                   GimpHelpItem   *item,
                                   GimpHelpLocale *locale)
{
  gchar *sort_key = item->title;

#if DEBUG_SORT_HELP_ITEMS
  g_printerr ("%s: processing %s (parent %s)\n",
              G_STRFUNC,
              item->title  ? item->title  : "NULL",
              item->parent ? item->parent : "NULL");
#endif

  if (item->sort &&
      g_regex_match_simple ("^[0-9]+([.][0-9]+)*$", item->sort, 0, 0))
    {
      sort_key = item->sort;

#if DEBUG_SORT_HELP_ITEMS
      g_printerr ("%s: sort key = %s\n", G_STRFUNC, sort_key);
#endif
    }

  item->index = 0;

  if (sort_key)
    {
      const gint max_tokens = GIMP_HELP_BROWSER_INDEX_MAX_DEPTH;
      gchar* *indices = g_strsplit (sort_key, ".", max_tokens + 1);
      gint    i;

      for (i = 0; i < max_tokens; i++)
        {
          gunichar c;

          if (! indices[i])
            {
              /* make sure that all item->index's are comparable */
              item->index <<= (8 * (max_tokens - i));
              break;
            }

          item->index <<= 8;  /* NOP if i = 0 */
          c = g_utf8_get_char (indices[i]);
          if (g_unichar_isdigit (c))
            {
              item->index += atoi (indices[i]);
            }
          else if (g_utf8_strlen (indices[i], -1) == 1)
            {
              item->index += (c & 0xFF);
            }
        }

      g_strfreev (indices);

#if DEBUG_SORT_HELP_ITEMS
      g_printerr ("%s: index = %lu\n", G_STRFUNC, item->index);
#endif
    }

  if (item->parent && strlen (item->parent))
    {
      GimpHelpItem *parent;

      parent = g_hash_table_lookup (locale->help_id_mapping, item->parent);

      if (parent)
        {
          parent->children = g_list_prepend (parent->children, item);
        }
    }
  else
    {
      locale->toplevel_items = g_list_prepend (locale->toplevel_items, item);
    }
}
示例#12
0
/**
 * gpk_package_id_format_twoline:
 *
 * Return value: "<b>GTK Toolkit</b>\ngtk2-2.12.2 (i386)"
 **/
gchar *
gpk_package_id_format_twoline (GtkStyleContext *style,
			       const gchar *package_id,
			       const gchar *summary)
{
	gchar *summary_safe = NULL;
	gchar *text = NULL;
	GString *string;
	gchar **split = NULL;
	gchar *color;
	const gchar *arch;
	GdkRGBA inactive;

	g_return_val_if_fail (package_id != NULL, NULL);

	/* get style color */
	if (style != NULL) {
		gtk_style_context_get_color (style,
					     GTK_STATE_FLAG_INSENSITIVE,
					     &inactive);
		color = g_strdup_printf ("#%02x%02x%02x",
					 (guint) (inactive.red * 255.0f),
					 (guint) (inactive.green * 255.0f),
					 (guint) (inactive.blue * 255.0f));
	} else {
		color = g_strdup ("gray");
	}

	/* optional */
	split = pk_package_id_split (package_id);
	if (split == NULL) {
		g_warning ("could not parse %s", package_id);
		goto out;
	}

	/* no summary */
	if (summary == NULL || summary[0] == '\0') {
		string = g_string_new (split[PK_PACKAGE_ID_NAME]);
		if (split[PK_PACKAGE_ID_VERSION][0] != '\0')
			g_string_append_printf (string, "-%s", split[PK_PACKAGE_ID_VERSION]);
		arch = gpk_get_pretty_arch (split[PK_PACKAGE_ID_ARCH]);
		if (arch != NULL)
			g_string_append_printf (string, " (%s)", arch);
		text = g_string_free (string, FALSE);
		goto out;
	}

	/* name and summary */
	string = g_string_new ("");
	summary_safe = g_markup_escape_text (summary, -1);
	g_string_append_printf (string, "%s\n", summary_safe);
	g_string_append_printf (string, "<span color=\"%s\">", color);
	g_string_append (string, split[PK_PACKAGE_ID_NAME]);
	if (split[PK_PACKAGE_ID_VERSION][0] != '\0')
		g_string_append_printf (string, "-%s", split[PK_PACKAGE_ID_VERSION]);
	arch = gpk_get_pretty_arch (split[PK_PACKAGE_ID_ARCH]);
	if (arch != NULL)
		g_string_append_printf (string, " (%s)", arch);
	g_string_append (string, "</span>");
	text = g_string_free (string, FALSE);
out:
	g_free (summary_safe);
	g_free (color);
	g_strfreev (split);
	return text;
}
示例#13
0
void
panel_layout_apply_default_from_gkeyfile (GdkScreen *screen)
{
    int          screen_n;
    gchar       *layout_file = NULL;
    GKeyFile    *keyfile = NULL;
    gchar      **groups = NULL;
    GError      *error = NULL;
    int          i;
    
    screen_n = gdk_screen_get_number (screen);
    layout_file = panel_layout_filename();
    
    if (layout_file)
    {
        keyfile = g_key_file_new ();
        if (g_key_file_load_from_file (keyfile,
                                       layout_file,
                                       G_KEY_FILE_NONE,
                                       &error))
        {
            groups = g_key_file_get_groups (keyfile, NULL);
            
            for (i = 0; groups[i] != NULL; i++) {
                
                if (g_strcmp0 (groups[i], "Toplevel") == 0 ||
                        g_str_has_prefix (groups[i], "Toplevel "))
                
                    panel_layout_append_group_helper (
                                        keyfile, groups[i],
                                        screen_n,
                                        "Toplevel",
                                        PANEL_TOPLEVEL_ID_LIST_KEY,
                                        PANEL_TOPLEVEL_SCHEMA,
                                        PANEL_TOPLEVEL_PATH,
                                        PANEL_TOPLEVEL_DEFAULT_PREFIX,
                                        panel_layout_toplevel_keys,
                                        G_N_ELEMENTS (panel_layout_toplevel_keys),
                                        "toplevel");
    
                else if (g_strcmp0 (groups[i], "Object") == 0 ||
                        g_str_has_prefix (groups[i], "Object "))
                
                    panel_layout_append_group_helper (
                                        keyfile, groups[i],
                                        -1,
                                        "Object",
                                        PANEL_OBJECT_ID_LIST_KEY,
                                        PANEL_OBJECT_SCHEMA,
                                        PANEL_OBJECT_PATH,
                                        PANEL_OBJECT_DEFAULT_PREFIX,
                                        panel_layout_object_keys,
                                        G_N_ELEMENTS (panel_layout_object_keys),
                                        "object");
                    
                else
                    
                    g_warning ("Unknown group in default layout: '%s'",
                               groups[i]);
                
            }
            
        }
        else
        {
            g_warning ("Error while parsing default layout from '%s': %s\n",
                       layout_file, error->message);
            g_error_free (error);
        }
        
    }
    else {
        g_warning ("Cant find a default layout file!");
        /* FIXME implement a fallback panel */
    }
    
    if (groups)
        g_strfreev (groups);
    
    if (keyfile)
        g_key_file_free (keyfile);
    
    if (layout_file)
        g_free (layout_file);
}
示例#14
0
static gboolean
panel_layout_append_group_helper (GKeyFile                  *keyfile,
                                  const char                *group,
                                  int                        set_screen_to,
                                  const char                *group_prefix,
                                  char                      *id_list_key,
                                  const char                *schema,
                                  const char                *path_prefix,
                                  const char                *default_prefix,
                                  PanelLayoutKeyDefinition  *key_definitions,
                                  int                        key_definitions_len,
                                  const char                *type_for_error_message)
{
    gboolean    retval = FALSE;
    const char *id;
    char       *unique_id = NULL;
    char       *path = NULL;
    GSettings  *settings = NULL;
    char      **keyfile_keys = NULL;
    char       *value_str;
    int         value_int;
    gboolean    value_boolean;
    int         i, j;
    GError     *error = NULL;
    gchar     **existing_ids;
    gboolean    existing_id = FALSE;
    gchar      *dir = NULL;
    gchar      *dconf_path = NULL;
    PanelGSettingsKeyType type;

    /* Try to extract an id from the group, by stripping the prefix,
     * and create a unique id out of that */
    id = group + strlen (group_prefix);
    while (g_ascii_isspace (*id))
        id++;

    if (!*id)
        id = NULL;

    if (id && !panel_gsettings_is_valid_keyname (id, &error)) {
        g_warning ("Invalid id name in layout '%s' (%s)", id, error->message);
        g_error_free (error);
        return FALSE;
    }

    if (g_strcmp0 (id_list_key, PANEL_TOPLEVEL_ID_LIST_KEY) == 0) {
        dir = "toplevels";
        type = PANEL_GSETTINGS_TOPLEVELS;
    }
    if (g_strcmp0 (id_list_key, PANEL_OBJECT_ID_LIST_KEY) == 0) {
        dir = "objects";
        type = PANEL_GSETTINGS_OBJECTS;
    }

    dconf_path = g_strdup_printf (PANEL_RESOURCE_PATH "/%s", dir);
    existing_ids = panel_dconf_list_subdirs (dconf_path, TRUE);

    if (id) {
        for (i = 0; existing_ids[i]; i++) {
                if (!strcmp (existing_ids[i], id)) {
                    existing_id = TRUE;
                }
        }
    }
    g_strfreev (existing_ids);
    g_free (dconf_path);
    
    if (existing_id || !id)
        unique_id = panel_profile_find_new_id (type);
    else
        unique_id = g_strdup (id);

    path = g_strdup_printf ("%s%s/", path_prefix, unique_id);
    settings = g_settings_new_with_path (schema, path);
    g_free (path);

    keyfile_keys = g_key_file_get_keys (keyfile, group, NULL, NULL);

    if (keyfile_keys) {

        /* validate/add keys from the keyfile */
        for (i = 0; keyfile_keys[i] != NULL; i++) {
            gboolean found = FALSE;

            for (j = 0; j < key_definitions_len; j++) {
                if (g_strcmp0 (keyfile_keys[i],
                               key_definitions[j].name) == 0) {
                    found = TRUE;
                    break;
                }
            }

            if (!found) {
                g_warning ("Unknown key '%s' for %s",
                             keyfile_keys[i],
                             unique_id);
                return FALSE;
            }

            switch (key_definitions[j].type) {
                case G_TYPE_STRING:
                    value_str = g_key_file_get_string (keyfile,
                                                       group, keyfile_keys[i],
                                                       NULL);
                    if (value_str)
                        g_settings_set_string (settings,
                                               key_definitions[j].name,
                                               value_str);
                    g_free (value_str);
                    break;

                case G_TYPE_INT:
                    value_int = g_key_file_get_integer (keyfile,
                                                        group, keyfile_keys[i],
                                                        NULL);
                    g_settings_set_int (settings,
                                        key_definitions[j].name,
                                        value_int);
                    break;

                case G_TYPE_BOOLEAN:
                    value_boolean = g_key_file_get_boolean (keyfile,
                                                            group, keyfile_keys[i],
                                                            NULL);
                    g_settings_set_boolean (settings,
                                            key_definitions[j].name,
                                            value_boolean);
                    break;
                default:
                    g_assert_not_reached ();
                    break;
            }
        }

        if (set_screen_to != -1 &&
                g_strcmp0 (schema, PANEL_TOPLEVEL_SCHEMA) == 0)
            g_settings_set_int (settings,
                                PANEL_TOPLEVEL_SCREEN_KEY,
                                set_screen_to);

        GSettings *panel_settings;
        panel_settings = g_settings_new (PANEL_SCHEMA);
        panel_gsettings_append_strv (panel_settings,
                                     id_list_key,
                                     unique_id);
        g_object_unref (panel_settings);

        retval = TRUE;
    }

    if (keyfile_keys)
        g_strfreev (keyfile_keys);

    if (settings)
        g_object_unref (settings);

    if (unique_id)
        g_free (unique_id);

    return retval;
}
示例#15
0
int
main (int argc, char *argv[])
{
  if (rpc_test_get_connection_path)
    g_connection_path = rpc_test_get_connection_path ();
  else
    g_connection_path = NPW_CONNECTION_PATH "/Test.RPC";

#ifdef BUILD_CLIENT
  gchar **child_args;

  if (argc < 2)
    g_error ("no server program provided on command line");

  signal (SIGSEGV, urgent_exit_sig);
  signal (SIGBUS,  urgent_exit_sig);
  signal (SIGINT,  urgent_exit_sig);
  signal (SIGABRT, urgent_exit_sig);

  if ((child_args = clone_args (argv)) == NULL)
    g_error ("could not create server program arguments\n");
  g_free (child_args[0]);
  child_args[0] = g_strdup (argv[1]);

  if (!g_spawn_async (NULL,
		      child_args,
		      NULL,
		      G_SPAWN_DO_NOT_REAP_CHILD,
		      NULL,
		      NULL,
		      &g_child_pid,
		      NULL))
    g_error ("could not start server program '%s'", child_args[0]);

  g_strfreev (child_args);

  if ((g_connection = rpc_init_client (g_connection_path, 0)) == NULL)
    g_error ("failed to initialize RPC client connection");
#endif

#ifdef BUILD_SERVER
  if ((g_connection = rpc_init_server (g_connection_path)) == NULL)
    g_error ("failed to initialize RPC server connection");
#endif

  int        fd            = -1;
  GSource   *rpc_source    = NULL;
  guint      rpc_source_id = 0;
  GPollFD    rpc_event_poll_fd;

#ifdef BUILD_CLIENT
  fd = rpc_socket (g_connection);
#endif
#ifdef BUILD_SERVER
  fd = rpc_listen_socket (g_connection);
#endif
  RPC_TEST_ENSURE (fd >= 0);

  if ((rpc_source = g_source_new (&rpc_event_funcs, sizeof (GSource))) == NULL)
    g_error ("failed to initialize RPC source");

  rpc_source_id = g_source_attach (rpc_source, NULL);
  memset (&rpc_event_poll_fd, 0, sizeof (rpc_event_poll_fd));
  rpc_event_poll_fd.fd      = fd;
  rpc_event_poll_fd.events  = G_IO_IN;
  rpc_event_poll_fd.revents = 0;
  g_source_add_poll (rpc_source, &rpc_event_poll_fd);

  static const rpc_method_descriptor_t vtable[] = {
    { RPC_TEST_METHOD_EXIT, handle_rpc_test_exit }
  };
  if (rpc_connection_add_method_descriptor (g_connection, &vtable[0]) < 0)
    g_error ("could not add method descriptor for TEST_RPC_METHOD_EXIT");

  g_main_loop = g_main_loop_new (NULL, TRUE);
#ifdef BUILD_CLIENT
  g_child_watch_id = g_child_watch_add (g_child_pid, child_exited_cb, NULL);
#endif
  rpc_test_init_invoke (argv);
  g_main_loop_run (g_main_loop);
  if (rpc_source_id)
    g_source_remove (rpc_source_id);
  if (g_connection)
    rpc_exit (g_connection);
  return g_exit_status;
}
示例#16
0
文件: xprops.c 项目: Gymnasiast/marco
/* this one freakishly returns g_malloc memory */
static gboolean
utf8_list_from_results (GetPropertyResults *results,
                        char             ***str_p,
                        int                *n_str_p)
{
    int i;
    int n_strings;
    char **retval;
    const char *p;

    *str_p = NULL;
    *n_str_p = 0;

    if (!validate_or_free_results (results, 8,
                                   results->display->atom_UTF8_STRING, FALSE))
        return FALSE;

    /* I'm not sure this is right, but I'm guessing the
     * property is nul-separated
     */
    i = 0;
    n_strings = 0;
    while (i < (int) results->n_items)
    {
        if (results->prop[i] == '\0')
            ++n_strings;
        ++i;
    }

    if (results->prop[results->n_items - 1] != '\0')
        ++n_strings;

    /* we're guaranteed that results->prop has a nul on the end
     * by XGetWindowProperty
     */

    retval = g_new0 (char*, n_strings + 1);

    p = (char *)results->prop;
    i = 0;
    while (i < n_strings)
    {
        if (!g_utf8_validate (p, -1, NULL))
        {
            char *name;

            meta_error_trap_push (results->display);
            name = XGetAtomName (results->display->xdisplay, results->xatom);
            meta_error_trap_pop (results->display, TRUE);
            meta_warning (_("Property %s on window 0x%lx contained invalid UTF-8 for item %d in the list\n"),
                          name, results->xwindow, i);
            meta_XFree (name);
            meta_XFree (results->prop);
            results->prop = NULL;

            g_strfreev (retval);
            return FALSE;
        }

        retval[i] = g_strdup (p);

        p = p + strlen (p) + 1;
        ++i;
    }

    *str_p = retval;
    *n_str_p = i;

    meta_XFree (results->prop);
    results->prop = NULL;

    return TRUE;
}
示例#17
0
文件: util.c 项目: iNode/mc
void
load_file_position (const vfs_path_t * filename_vpath, long *line, long *column, off_t * offset,
                    GArray ** bookmarks)
{
    char *fn;
    FILE *f;
    char buf[MC_MAXPATHLEN + 100];
    const size_t len = vfs_path_len (filename_vpath);

    /* defaults */
    *line = 1;
    *column = 0;
    *offset = 0;

    /* open file with positions */
    fn = mc_config_get_full_path (MC_FILEPOS_FILE);
    f = fopen (fn, "r");
    g_free (fn);
    if (f == NULL)
        return;

    /* prepare array for serialized bookmarks */
    if (bookmarks != NULL)
        *bookmarks = g_array_sized_new (FALSE, FALSE, sizeof (size_t), MAX_SAVED_BOOKMARKS);

    while (fgets (buf, sizeof (buf), f) != NULL)
    {
        const char *p;
        gchar **pos_tokens;

        /* check if the filename matches the beginning of string */
        if (strncmp (buf, vfs_path_as_str (filename_vpath), len) != 0)
            continue;

        /* followed by single space */
        if (buf[len] != ' ')
            continue;

        /* and string without spaces */
        p = &buf[len + 1];
        if (strchr (p, ' ') != NULL)
            continue;

        pos_tokens = g_strsplit (p, ";", 3 + MAX_SAVED_BOOKMARKS);
        if (pos_tokens[0] == NULL)
        {
            *line = 1;
            *column = 0;
            *offset = 0;
        }
        else
        {
            *line = strtol (pos_tokens[0], NULL, 10);
            if (pos_tokens[1] == NULL)
            {
                *column = 0;
                *offset = 0;
            }
            else
            {
                *column = strtol (pos_tokens[1], NULL, 10);
                if (pos_tokens[2] == NULL)
                    *offset = 0;
                else if (bookmarks != NULL)
                {
                    size_t i;

                    *offset = (off_t) g_ascii_strtoll (pos_tokens[2], NULL, 10);

                    for (i = 0; i < MAX_SAVED_BOOKMARKS && pos_tokens[3 + i] != NULL; i++)
                    {
                        size_t val;

                        val = strtoul (pos_tokens[3 + i], NULL, 10);
                        g_array_append_val (*bookmarks, val);
                    }
                }
            }
        }

        g_strfreev (pos_tokens);
    }

    fclose (f);
}
示例#18
0
GList *
gimp_palette_load_psp (const gchar  *filename,
                       GError      **error)
{
  GimpPalette *palette;
  gchar       *palette_name;
  gint         fd;
  guchar       color_bytes[4];
  gint         number_of_colors;
  gint         data_size;
  gint         i, j;
  gboolean     color_ok;
  gchar        buffer[4096];
  /*Maximum valid file size: 256 * 4 * 3 + 256 * 2  ~= 3650 bytes */
  gchar      **lines;
  gchar      **ascii_colors;

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

  fd = g_open (filename, O_RDONLY | _O_BINARY, 0);
  if (! fd)
    {
      g_set_error (error,
                   G_FILE_ERROR, g_file_error_from_errno (errno),
                   _("Could not open '%s' for reading: %s"),
                   gimp_filename_to_utf8 (filename), g_strerror (errno));
      return NULL;
    }

  palette_name = g_filename_display_basename (filename);
  palette = GIMP_PALETTE (gimp_palette_new (palette_name));
  g_free (palette_name);

  lseek (fd, 16, SEEK_SET);
  data_size = read (fd, buffer, sizeof (buffer) - 1);
  buffer[data_size] = '\0';

  lines = g_strsplit (buffer, "\x0d\x0a", -1);

  number_of_colors = atoi (lines[0]);

  for (i = 0; i < number_of_colors; i++)
    {
      if (lines[i + 1] == NULL)
        {
          g_printerr ("Premature end of file reading %s.",
                      gimp_filename_to_utf8 (filename));
          break;
        }

      ascii_colors = g_strsplit (lines[i + 1], " ", 3);
      color_ok = TRUE;

      for (j = 0 ; j < 3; j++)
        {
          if (ascii_colors[j] == NULL)
            {
              g_printerr ("Corrupted palette file %s.",
                          gimp_filename_to_utf8 (filename));
              color_ok = FALSE;
              break;
            }

          color_bytes[j] = atoi (ascii_colors[j]);
        }

      if (color_ok)
        {
          GimpRGB color;

          gimp_rgba_set_uchar (&color,
                               color_bytes[0],
                               color_bytes[1],
                               color_bytes[2],
                               255);
          gimp_palette_add_entry (palette, -1, NULL, &color);
        }

      g_strfreev (ascii_colors);
    }

  g_strfreev (lines);

  close (fd);

  return g_list_prepend (NULL, palette);
}
示例#19
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	GKeyFile *config;
	guint signal;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach == TRUE) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			exit(1);
		}
	}

	if (mkdir(STATEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create state directory");
	}

	if (mkdir(STORAGEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create storage directory");
	}

	umask(0077);

	main_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	signal = setup_signalfd();

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, CONNMAN_SERVICE, &err);
	if (conn == NULL) {
		if (dbus_error_is_set(&err) == TRUE) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	__connman_log_init(argv[0], option_debug, option_detach);

	__connman_dbus_init(conn);

	config = load_config(CONFIGDIR "/main.conf");
	parse_config(config);
	if (config != NULL)
		g_key_file_free(config);

	__connman_storage_migrate();
	__connman_technology_init();
	__connman_notifier_init();
	__connman_service_init();
	__connman_provider_init();
	__connman_network_init();
	__connman_device_init(option_device, option_nodevice);

	__connman_agent_init();
	__connman_ippool_init();
	__connman_iptables_init();
	__connman_nat_init();
	__connman_tethering_init();
	__connman_counter_init();
	__connman_manager_init();
	__connman_config_init();
	__connman_stats_init();
	__connman_clock_init();

	__connman_resolver_init(option_dnsproxy);
	__connman_ipconfig_init();
	__connman_rtnl_init();
	__connman_task_init();
	__connman_proxy_init();
	__connman_detect_init();
	__connman_session_init();
	__connman_timeserver_init();
	__connman_connection_init();

	__connman_plugin_init(option_plugin, option_noplugin);

	__connman_rtnl_start();
	__connman_dhcp_init();
	__connman_dhcpv6_init();
	__connman_wpad_init();
	__connman_wispr_init();
	__connman_rfkill_init();

	g_free(option_device);
	g_free(option_plugin);
	g_free(option_nodevice);
	g_free(option_noplugin);

	g_main_loop_run(main_loop);

	g_source_remove(signal);

	__connman_rfkill_cleanup();
	__connman_wispr_cleanup();
	__connman_wpad_cleanup();
	__connman_dhcpv6_cleanup();
	__connman_dhcp_cleanup();
	__connman_provider_cleanup();
	__connman_plugin_cleanup();
	__connman_connection_cleanup();
	__connman_timeserver_cleanup();
	__connman_session_cleanup();
	__connman_detect_cleanup();
	__connman_proxy_cleanup();
	__connman_task_cleanup();
	__connman_rtnl_cleanup();
	__connman_resolver_cleanup();

	__connman_clock_cleanup();
	__connman_stats_cleanup();
	__connman_config_cleanup();
	__connman_manager_cleanup();
	__connman_counter_cleanup();
	__connman_agent_cleanup();
	__connman_tethering_cleanup();
	__connman_nat_cleanup();
	__connman_iptables_cleanup();
	__connman_ippool_cleanup();
	__connman_device_cleanup();
	__connman_network_cleanup();
	__connman_service_cleanup();
	__connman_ipconfig_cleanup();
	__connman_notifier_cleanup();
	__connman_technology_cleanup();

	__connman_dbus_cleanup();

	__connman_log_cleanup();

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	if (connman_settings.pref_timeservers != NULL)
		g_strfreev(connman_settings.pref_timeservers);

	g_free(connman_settings.auto_connect);
	g_free(connman_settings.preferred_techs);
	g_strfreev(connman_settings.fallback_nameservers);
	g_strfreev(connman_settings.blacklisted_interfaces);

	g_free(option_debug);

	return 0;
}
示例#20
0
static void
crs_data_free (CRSData *data)
{
  g_strfreev (data->events);
  g_slice_free (CRSData, data);
}
示例#21
0
/*
 * @conflict_hash: conflicting_dir_path -> conflict_free_dname
 * @no_conflict_hash: a hash table to remember dirs that have no case conflict.
 */
static char *
build_case_conflict_free_path (const char *worktree,
                               const char *ce_name,
                               GHashTable *conflict_hash,
                               GHashTable *no_conflict_hash,
                               gboolean *is_case_conflict)
{
    GString *buf = g_string_new (worktree);
    char **components, *ptr;
    guint i, n_comps;
    static int dummy;

    components = g_strsplit (ce_name, "/", -1);
    n_comps = g_strv_length (components);
    for (i = 0; i < n_comps; ++i) {
        char *path = NULL, *dname = NULL, *case_conflict_free_path = NULL;
        SeafStat st;

        ptr = components[i];

        path = g_build_path ("/", buf->str, ptr, NULL);
        /* If path doesn't exist, case conflict is not possible. */
        if (seaf_stat (path, &st) < 0) {
            if (i != n_comps - 1) {
                if (g_mkdir (path, 0777) < 0) {
                    seaf_warning ("Failed to create dir %s.\n", path);
                    g_free (path);
                    goto error;
                }
            }
            g_string_append_printf (buf, "/%s", ptr);
            g_free (path);
            continue;
        }

        dname = g_hash_table_lookup (conflict_hash, path);
        if (dname) {
            /* We've detected (and fixed) case conflict for this dir before. */
            *is_case_conflict = TRUE;
            g_free (path);
            g_string_append_printf (buf, "/%s", dname);
            continue;
        }

        if (g_hash_table_lookup (no_conflict_hash, path) != NULL) {
            /* We've confirmed this dir has no case conflict before. */
            g_free (path);
            g_string_append_printf (buf, "/%s", ptr);
            continue;
        }

        /* No luck in the hash tables, we have to run case conflict detection. */
        if (!case_conflict_exists (buf->str, ptr)) {
            /* No case conflict. */
            if (i != n_comps - 1)
                g_hash_table_insert (no_conflict_hash,
                                     g_strdup(path),
                                     &dummy);
            g_free (path);
            g_string_append_printf (buf, "/%s", ptr);
            continue;
        }

        *is_case_conflict = TRUE;

        /* If case conflict, create a conflict free path and
         * remember it in the hash table.
         */

        dname = gen_case_conflict_free_dname (buf->str, ptr);

        case_conflict_free_path = g_build_path ("/", buf->str, dname, NULL);
        if (i != n_comps - 1) {
            if (g_mkdir (case_conflict_free_path, 0777) < 0) {
                seaf_warning ("Failed to create dir %s.\n", case_conflict_free_path);
                g_free (path);
                g_free (dname);
                g_free (case_conflict_free_path);
                goto error;
            }

            g_hash_table_insert (conflict_hash, g_strdup(path), g_strdup(dname));
        }

        g_string_append_printf (buf, "/%s", dname);

        g_free (path);
        g_free (dname);
        g_free (case_conflict_free_path);
    }

    g_strfreev (components);
    return g_string_free (buf, FALSE);

error:
    g_strfreev (components);
    return NULL;
}
示例#22
0
文件: dia_dirs.c 项目: AmiGanguli/dia
/** Remove all instances of . and .. from an absolute path.
 * This is not a cheap function.
 * @param path String to canonicalize.
 * @returns A newly allocated string, or NULL if too many ..'s were found
 */
gchar *
dia_get_canonical_path(const gchar *path)
{
  gchar  *ret = NULL;
  gchar **list;
  int i = 0, n = 0;

  /* shortcut for nothing to do (also keeps UNC path intact */
  if (!strstr(path, "..") && !strstr(path, "." G_DIR_SEPARATOR_S))
    return g_strdup(path);

  list = g_strsplit (path, G_DIR_SEPARATOR_S, -1);
  while (list[i] != NULL) {
    if (0 == strcmp (list[i], ".")) {
      /* simple, just remove it */
      g_free (list[i]);
      list[i] = g_strdup ("");
    }
    else if  (0 == strcmp (list[i], "..")) {
      /* need to 'remove' the previous non empty part too */
      n = i;
      g_free (list[i]);
      list[i] = g_strdup ("");
      while (n >= 0) {
        if (0 != strlen(list[n])) {
          /* remove it */
          g_free (list[n]);
          list[n] = g_strdup ("");
          break;
        }
        n--;
      }
      /* we haven't found an entry to remove for '..' */
      if (n < 0)
        break;
    }
    i++;
  }
  if (n >= 0) {
    /* cant use g_strjoinv () cause it would stumble about empty elements */
    GString *str = g_string_new (NULL);

    i = 0;
    while (list[i] != NULL) {
      if (strlen(list[i]) > 0) {

        /* win32 filenames usually don't start with a dir separator but
         * with <drive>:\ 
         */
	if (i != 0 || list[i][1] != ':')
          g_string_append (str, G_DIR_SEPARATOR_S);
        g_string_append (str, list[i]);
      }
      i++;
    }
    ret = g_string_free (str, FALSE);
  }

  g_strfreev(list);

  return ret;
}
示例#23
0
文件: msg.c 项目: arminius2/apolloim
void
msn_message_parse_payload(MsnMessage *msg,
						  const char *payload, size_t payload_len)
{
	char *tmp_base, *tmp;
	const char *content_type;
	char *end;
	char **elems, **cur, **tokens;

	g_return_if_fail(payload != NULL);

	tmp_base = tmp = g_malloc0(payload_len + 1);
	memcpy(tmp_base, payload, payload_len);

	/* Parse the attributes. */
	end = strstr(tmp, "\r\n\r\n");
	/* TODO? some clients use \r delimiters instead of \r\n, the official client
	 * doesn't send such messages, but does handle receiving them. We'll just
	 * avoid crashing for now */
	if (end == NULL) {
		g_free(tmp_base);
		g_return_if_reached();
	}
	*end = '\0';

	elems = g_strsplit(tmp, "\r\n", 0);

	for (cur = elems; *cur != NULL; cur++)
	{
		const char *key, *value;

		tokens = g_strsplit(*cur, ": ", 2);

		key = tokens[0];
		value = tokens[1];

		if (!strcmp(key, "MIME-Version"))
		{
			g_strfreev(tokens);
			continue;
		}

		if (!strcmp(key, "Content-Type"))
		{
			char *charset, *c;

			if ((c = strchr(value, ';')) != NULL)
			{
				if ((charset = strchr(c, '=')) != NULL)
				{
					charset++;
					msn_message_set_charset(msg, charset);
				}

				*c = '\0';
			}

			msn_message_set_content_type(msg, value);
		}
		else
		{
			msn_message_set_attr(msg, key, value);
		}

		g_strfreev(tokens);
	}

	g_strfreev(elems);

	/* Proceed to the end of the "\r\n\r\n" */
	tmp = end + 4;

	/* Now we *should* be at the body. */
	content_type = msn_message_get_content_type(msg);

	if (content_type != NULL &&
		!strcmp(content_type, "application/x-msnmsgrp2p"))
	{
		MsnSlpHeader header;
		MsnSlpFooter footer;
		int body_len;

		if (payload_len - (tmp - tmp_base) < sizeof(header)) {
			g_free(tmp_base);
			g_return_if_reached();
		}

		msg->msnslp_message = TRUE;

		/* Import the header. */
		memcpy(&header, tmp, sizeof(header));
		tmp += sizeof(header);

		msg->msnslp_header.session_id = GUINT32_FROM_LE(header.session_id);
		msg->msnslp_header.id         = GUINT32_FROM_LE(header.id);
		msg->msnslp_header.offset     = GUINT64_FROM_LE(header.offset);
		msg->msnslp_header.total_size = GUINT64_FROM_LE(header.total_size);
		msg->msnslp_header.length     = GUINT32_FROM_LE(header.length);
		msg->msnslp_header.flags      = GUINT32_FROM_LE(header.flags);
		msg->msnslp_header.ack_id     = GUINT32_FROM_LE(header.ack_id);
		msg->msnslp_header.ack_sub_id = GUINT32_FROM_LE(header.ack_sub_id);
		msg->msnslp_header.ack_size   = GUINT64_FROM_LE(header.ack_size);

		body_len = payload_len - (tmp - tmp_base) - sizeof(footer);

		/* Import the body. */
		if (body_len > 0) {
			msg->body_len = body_len;
			msg->body = g_malloc0(msg->body_len + 1);
			memcpy(msg->body, tmp, msg->body_len);
			tmp += body_len;
		}

		/* Import the footer. */
		if (body_len >= 0) {
			memcpy(&footer, tmp, sizeof(footer));
			tmp += sizeof(footer);
			msg->msnslp_footer.value = GUINT32_FROM_BE(footer.value);
		}
	}
	else
	{
		if (payload_len - (tmp - tmp_base) > 0) {
			msg->body_len = payload_len - (tmp - tmp_base);
			msg->body = g_malloc0(msg->body_len + 1);
			memcpy(msg->body, tmp, msg->body_len);
		}
	}

	g_free(tmp_base);
}
示例#24
0
static gchar * 
mud_trigger_parse(MudTrigger *self, const gchar *data)
{
    gint state;
    gchar **matches;
    GString *ret, *reg_num;
    guint length, matches_length, i, j, num;

    length = strlen(data);

    if(length == 0)
        return NULL;

    ret = g_string_new(NULL);
    reg_num = NULL;

    matches = g_match_info_fetch_all(self->priv->info);
    matches_length = g_strv_length(matches);

    state = PARSE_STATE_TEXT;

    for(i = 0; i < length; i++)
    {
        switch(state)
        {
            case PARSE_STATE_TEXT:
                if(data[i] == '%' && i + 1 < length)
                    state = PARSE_STATE_REGISTER;
                else
                    ret = g_string_append_c(ret, data[i]);
                break;

            case PARSE_STATE_REGISTER:
                reg_num = g_string_new(NULL);

                j = i;

                while(TRUE)
                {
                    if(j == length || data[j] != '%')
                        break;

                    ret = g_string_append_c(ret, data[j++]);
                }

                if(j == length)
                {
                    if(data[j - 1] == '%')
                        ret = g_string_append_c(ret, data[j - 1]);

                    i = j;
                    break;
                }

                for(; g_ascii_isdigit(data[j]) && j < length; j++)
                    reg_num = g_string_append_c(reg_num, data[j]);

                if(reg_num->len == 0) // No number, not a register.
                {
                    /* Append the % that got us here. */
                    ret = g_string_append_c(ret, '%');

                    i = j - 1;

                    g_string_free(reg_num, TRUE);

                    state = PARSE_STATE_TEXT;
                }
                else
                {
                    i = j - 1;

                    num = atol(reg_num->str);

                    g_string_free(reg_num, TRUE);

                    if(num >= matches_length)
                        ret = g_string_append(ret, _("#Submatch Out of Range#"));
                    else
                        ret = g_string_append(ret, matches[num]);

                    state = PARSE_STATE_TEXT;
                }
                break;
        }
    }

    if(matches_length != 0)
        g_strfreev(matches);

    return g_string_free(ret, (ret->len == 0) );
}
示例#25
0
文件: context.c 项目: ukleinek/rauc
static gboolean launch_and_wait_variables_handler(gchar *handler_name, GHashTable *variables, GError **error)
{
	g_autoptr(GSubprocessLauncher) handlelaunch = NULL;
	g_autoptr(GSubprocess) handleproc = NULL;
	GError *ierror = NULL;
	GHashTableIter iter;
	gchar *key = NULL;
	gchar *value = NULL;
	g_autoptr(GDataInputStream) datainstream = NULL;
	GInputStream *instream;
	gchar* outline;

	g_return_val_if_fail(handler_name, FALSE);
	g_return_val_if_fail(variables, FALSE);
	g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

	handlelaunch = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_MERGE);

	/* we copy the variables from the hashtable and add them to the
	   subprocess environment */
	g_hash_table_iter_init(&iter, variables);
	while (g_hash_table_iter_next(&iter, (gpointer*) &key, (gpointer*) &value)) {
		g_subprocess_launcher_setenv(handlelaunch, g_strdup(key), g_strdup(value), 1);
	}

	handleproc = g_subprocess_launcher_spawn(
			handlelaunch,
			&ierror, handler_name,
			NULL,
			NULL);

	if (!handleproc) {
		g_propagate_error(error, ierror);
		return FALSE;
	}

	instream = g_subprocess_get_stdout_pipe(handleproc);
	datainstream = g_data_input_stream_new(instream);

	do {
		outline = g_data_input_stream_read_line(datainstream, NULL, NULL, NULL);
		if (!outline)
			continue;

		if (g_str_has_prefix(outline, "RAUC_")) {
			gchar **split = g_strsplit(outline, "=", 2);

			if (g_strv_length(split) != 2)
				continue;

			g_hash_table_insert(variables, g_strdup(split[0]), g_strdup(split[1]));
			g_strfreev(split);
		}
	} while (outline);

	if (!g_subprocess_wait_check(handleproc, NULL, &ierror)) {
		g_propagate_error(error, ierror);
		return FALSE;
	}

	return TRUE;
}
示例#26
0
static void
search_init (GtkWidget      *entry,
             GeditViewFrame *frame)
{
	const gchar *entry_text;

	/* renew the flush timeout */
	if (frame->priv->typeselect_flush_timeout != 0)
	{
		g_source_remove (frame->priv->typeselect_flush_timeout);
		frame->priv->typeselect_flush_timeout =
			g_timeout_add (GEDIT_VIEW_FRAME_SEARCH_DIALOG_TIMEOUT,
			               (GSourceFunc)search_entry_flush_timeout,
			               frame);
	}

	entry_text = gtk_entry_get_text (GTK_ENTRY (entry));

	if (frame->priv->search_mode == SEARCH)
	{
		update_search (frame);

		run_search (frame,
		            entry_text,
		            FALSE,
		            frame->priv->wrap_around,
		            TRUE);
	}
	else
	{
		if (*entry_text != '\0')
		{
			gboolean moved, moved_offset;
			gint line;
			gint offset_line = 0;
			gint line_offset = 0;
			gchar **split_text = NULL;
			const gchar *text;
			GtkTextIter iter;
			GeditDocument *doc;

			doc = gedit_view_frame_get_document (frame);

			gtk_text_buffer_get_iter_at_mark (GTK_TEXT_BUFFER (doc),
			                                  &iter,
			                                  frame->priv->start_mark);

			split_text = g_strsplit (entry_text, ":", -1);

			if (g_strv_length (split_text) > 1)
			{
				text = split_text[0];
			}
			else
			{
				text = entry_text;
			}

			if (*text == '-')
			{
				gint cur_line = gtk_text_iter_get_line (&iter);

				if (*(text + 1) != '\0')
					offset_line = MAX (atoi (text + 1), 0);

				line = MAX (cur_line - offset_line, 0);
			}
			else if (*entry_text == '+')
			{
				gint cur_line = gtk_text_iter_get_line (&iter);

				if (*(text + 1) != '\0')
					offset_line = MAX (atoi (text + 1), 0);

				line = cur_line + offset_line;
			}
			else
			{
				line = MAX (atoi (text) - 1, 0);
			}

			if (split_text[1] != NULL)
			{
				line_offset = atoi (split_text[1]);
			}

			g_strfreev (split_text);

			moved = gedit_document_goto_line (doc, line);
			moved_offset = gedit_document_goto_line_offset (doc, line,
			                                                line_offset);

			gedit_view_scroll_to_cursor (GEDIT_VIEW (frame->priv->view));

			if (!moved || !moved_offset)
			{
				set_entry_background (frame, frame->priv->search_entry,
				                      GEDIT_SEARCH_ENTRY_NOT_FOUND);
			}
			else
			{
				set_entry_background (frame, frame->priv->search_entry,
				                      GEDIT_SEARCH_ENTRY_NORMAL);
			}
		}
	}
}
示例#27
0
文件: main.c 项目: enferex/LilyTerm
// it will return TRUE if succeed
gboolean read_socket(GIOChannel *channel, GIOCondition condition, gpointer user_data)
{
#ifdef DETAIL
	g_debug("! Launch read_socket() to read data !");
#endif
#ifdef SAFEMODE
	if (channel==NULL) return FALSE;
#endif

	GError *error = NULL;
	gchar *data = NULL, **datas;
	gsize len = 0;
	gsize term;

	if (g_io_channel_read_line (channel, &data, &len, &term, &error) == G_IO_STATUS_ERROR)
		return socket_fault(7, error, channel, TRUE);
	// g_debug("Read %ld bytes from Lilyterm socket: '%s'", len, data);
	if (len > 0)
	{
		//	     0			 1     2	   3	    4		5   6	 7		   8		9	      10      11
		// get data: SOCKET_DATA_VERSION SHELL LOCALE_LIST ENCODING LC_MESSAGES PWD HOME VTE_CJK_WIDTH_STR wmclass_name wmclass_class ENVIRON ARGV
		// clear '\n' at the end of data[]
		data[len-1] = 0;

		datas = split_string(data, "\x10", 12);
		// g_debug("The SOCKET_DATA_VERSION = %s ,and the data sent via socket is %s",
		//	   SOCKET_DATA_VERSION, datas[0]);
		if ((datas==NULL) || compare_strings(SOCKET_DATA_VERSION, datas[0], TRUE))
		{
			// The SOCKET_DATA_VERSION != the data sent via socket
			gchar *received_socket_version = NULL;
			if (datas) received_socket_version = datas[0];

			gchar *message = g_strdup_printf(_("The data got from socket seems incorrect.\n\n"
							   "\tReceived socket version: %s\n"
							   "\tExpected socket version: %s\n\n"
							   "If you just updated %s recently,\n"
							   "Please close all the windows of %s and try again."),
							   received_socket_version, SOCKET_DATA_VERSION,
							   PACKAGE, PACKAGE);
			error_dialog(NULL,
				     _("The format of socket data is out of date"),
				     "The format of socket data is out of date",
				     GTK_STOCK_DIALOG_ERROR,
				     message,
				     NULL);
			g_free(message);
		}
		else
		{
			gchar **argv = split_string(datas[11], "\x10", -1);
			gint argc = 0;
			if (argv)
				while (argv[argc])
					argc ++;

			// g_debug("Final:");
			// g_debug("\targc =%d", argc);
			// print_array("\targv", argv);
			// g_debug("\tSHELL = %s", datas[1]);
			// g_debug("\tenvironments = %s", datas[10]);
			// g_debug("\tlocale_list = %s", datas[2]);
			// g_debug("\tPWD = %s", datas[5]);
			// g_debug("\tHOME = %s", datas[6]);
			// g_debug("\tVTE_CJK_WIDTH_STR = %s", datas[7]);
			// g_debug("\twmclass_name = %s", datas[8]);
			// g_debug("\twmclass_class= %s", datas[9]);
			// g_debug("\tencoding = %s", datas[3]);
			// g_debug("\tlc_messages = %s", datas[4]);

			//GtkNotebook *new_window(int argc,
			//			char *argv[],
			//			gchar *shell,					// 1
			//			gchar *environment,				// 10
			//			gchar *locale_list,				// 2
			//			gchar *PWD,					// 5
			//			gchar *HOME,					// 6
			//			gchar *VTE_CJK_WIDTH_STR,			// 7
			//			gboolean VTE_CJK_WIDTH_STR_overwrite_profile,
			//			gchar *wmclass_name,				// 8
			//			gchar *wmclass_class,				// 9
			//			gchar *user_environ,
			//			gchar *encoding,				// 3
			//			gboolean encoding_overwrite_profile,
			//			gchar *lc_messages,				// 4
			//			struct Window *win_data_orig,
			//			struct Page *page_data_orig)

			new_window(argc,
				   argv,
				   datas[1],
				   datas[10],
				   datas[2],
				   datas[5],
				   datas[6],
				   datas[7],
				   FALSE,
				   datas[8],
				   datas[9],
				   NULL,
				   datas[3],
				   FALSE,
				   datas[4],
				   NULL,
				   NULL);
			g_strfreev(argv);
		}
		g_strfreev(datas);
		data[len-1] = '\n';
		g_free(data);
	}
	clear_channel(channel, TRUE);
	// return FALSE means this connection is finish.
	return FALSE;
}
示例#28
0
G_MODULE_EXPORT
void on_menu_docstat_activate (GtkWidget *widget, void *user) {
    gint i = 0;
    gchar* output = 0;
    gchar* cmd = 0;
    gchar** matched = NULL;
    GError* err = NULL;
    GMatchInfo* match_info;
    GRegex* regexs[TEXCOUNT_OUTPUT_LINES];
    gchar* res[TEXCOUNT_OUTPUT_LINES] = { 0 };
    
    
    /* TODO: can we deprecate this? */
    const gchar* terms[] = {
        _("Words in text"),
        _("Words in headers"),
        _("Words in float captions"),
        _("Number of headers"),
        _("Number of floats"),
        _("Number of math inlines"),
        _("Number of math displayed")
    };
    
    const gchar* terms_regex[] = {
        "Words in text: ([0-9]*)",
        "Words in headers: ([0-9]*)",
        "Words in float captions: ([0-9]*)",
        "Number of headers: ([0-9]*)",
        "Number of floats: ([0-9]*)",
        "Number of math inlines: ([0-9]*)",
        "Number of math displayed: ([0-9]*)"
    };


    /* TODO: move to non gui class (latex perhaps) */
    if (external_exists ("texcount")) {
        /* Copy workfile to /tmp to remove any spaces in filename to avoid
         * segfaults */
        gchar* tmpfile = g_strdup_printf ("%s.state", g_active_editor->fdname);
        if (!utils_copy_file (g_active_editor->workfile, tmpfile, &err)) {
            slog (L_G_ERROR, "utils_copy_file (): %s\n", err->message);
            g_free (tmpfile);
            g_error_free (err);
            goto cleanup;
        }

        cmd = g_strdup_printf ("texcount '%s'", tmpfile);
        Tuple2 result = utils_popen_r (cmd, NULL);

        for (i = 0; i < TEXCOUNT_OUTPUT_LINES; ++i)
            if (! (regexs[i] = g_regex_new (terms_regex[i], 0, 0, &err))) {
                slog (L_G_ERROR, "utils_copy_file (): %s\n", err->message);
                g_free (tmpfile);
                g_error_free (err);
                goto cleanup;
            }

        for (i = 0; i < TEXCOUNT_OUTPUT_LINES; ++i) {
            if (g_regex_match (regexs[i], result.second, 0, &match_info)) {
                matched = g_match_info_fetch_all (match_info);
                if (NULL == matched[1]) {
                    slog (L_WARNING, "can't extract info: %s\n", terms[i]);
                    res[i] = g_strdup ("N/A");
                } else {
                    res[i] = g_strdup (matched[1]);
                }
                g_strfreev (matched);
                g_match_info_free (match_info);
            }
        }
        g_free (result.second);
        g_free (tmpfile);
    }
    else {
        cmd = NULL;
        slog (L_G_ERROR, "The 'texcount' utility could not be found.\n");
        return;
    }

    gchararray items[6] = {"stats_words", "stats_head", "stats_float", 
                           "stats_nrhead", "stats_nrfloat", "stats_nrmath"};
    int j = 0;
    GtkLabel *tmp;
        
    for (j = 0; j < 6; j++) {
        gchar *value = items[j];
        tmp = GTK_LABEL(gtk_builder_get_object (gui->builder, value));
        gtk_label_set_text (tmp, res[j]);
    }
    

    gtk_label_set_text (GTK_LABEL (gtk_builder_get_object (gui->builder, 
                    "stats_filename")), tabmanagergui_get_labeltext (g_active_tab->page));
    gtk_widget_show (gui->docstatswindow);
    return;

cleanup:
    for (i = 0; i < TEXCOUNT_OUTPUT_LINES; ++i) {
        g_regex_unref (regexs[i]);
        g_free (res[i]);
    }
    g_free (cmd);
    g_free (output);
}
示例#29
0
void
load_file (const gchar *demoname,
           const gchar *filename)
{
  GtkTextBuffer *info_buffer, *source_buffer;
  GtkTextIter start, end;
  char *resource_filename;
  GError *err = NULL;
  int state = 0;
  gboolean in_para = 0;
  gchar **lines;
  GBytes *bytes;
  gint i;

  if (!g_strcmp0 (current_file, filename))
    return;

  remove_data_tabs ();

  add_data_tab (demoname);

  g_free (current_file);
  current_file = g_strdup (filename);

  info_buffer = gtk_text_buffer_new (NULL);
  gtk_text_buffer_create_tag (info_buffer, "title",
                              "font", "Sans 18",
                              "pixels-below-lines", 10,
                              NULL);

  source_buffer = gtk_text_buffer_new (NULL);

  resource_filename = g_strconcat ("/sources/", filename, NULL);
  bytes = g_resources_lookup_data (resource_filename, 0, &err);
  g_free (resource_filename);

  if (bytes == NULL)
    {
      g_warning ("Cannot open source for %s: %s", filename, err->message);
      g_error_free (err);
      return;
    }

  lines = g_strsplit (g_bytes_get_data (bytes, NULL), "\n", -1);
  g_bytes_unref (bytes);

  gtk_text_buffer_get_iter_at_offset (info_buffer, &start, 0);
  for (i = 0; lines[i] != NULL; i++)
    {
      gchar *p;
      gchar *q;
      gchar *r;

      /* Make sure \r is stripped at the end for the poor windows people */
      lines[i] = g_strchomp (lines[i]);

      p = lines[i];
      switch (state)
        {
        case 0:
          /* Reading title */
          while (*p == '/' || *p == '*' || g_ascii_isspace (*p))
            p++;
          r = p;
          while (*r != '\0')
            {
              while (*r != '/' && *r != ':' && *r != '\0')
                r++;
              if (*r == '/')
                {
                  r++;
                  p = r;
                }
              if (r[0] == ':' && r[1] == ':')
                *r = '\0';
            }
          q = p + strlen (p);
          while (q > p && g_ascii_isspace (*(q - 1)))
            q--;


          if (q > p)
            {
              int len_chars = g_utf8_pointer_to_offset (p, q);

              end = start;

              g_assert (strlen (p) >= q - p);
              gtk_text_buffer_insert (info_buffer, &end, p, q - p);
              start = end;

              gtk_text_iter_backward_chars (&start, len_chars);
              gtk_text_buffer_apply_tag_by_name (info_buffer, "title", &start, &end);

              start = end;

              while (*p && *p != '\n') p++;

              state++;
            }
          break;

        case 1:
          /* Reading body of info section */
          while (g_ascii_isspace (*p))
            p++;
          if (*p == '*' && *(p + 1) == '/')
            {
              gtk_text_buffer_get_iter_at_offset (source_buffer, &start, 0);
              state++;
            }
          else
            {
              int len;

              while (*p == '*' || g_ascii_isspace (*p))
                p++;

              len = strlen (p);
              while (g_ascii_isspace (*(p + len - 1)))
                len--;

              if (len > 0)
                {
                  if (in_para)
                    gtk_text_buffer_insert (info_buffer, &start, " ", 1);

                  g_assert (strlen (p) >= len);
                  gtk_text_buffer_insert (info_buffer, &start, p, len);
                  in_para = 1;
                }
              else
                {
                  gtk_text_buffer_insert (info_buffer, &start, "\n", 1);
                  in_para = 0;
                }
            }
          break;

        case 2:
          /* Skipping blank lines */
          while (g_ascii_isspace (*p))
            p++;
          if (*p)
            {
              p = lines[i];
              state++;
              /* Fall through */
            }
          else
            break;

        case 3:
          /* Reading program body */
          gtk_text_buffer_insert (source_buffer, &start, p, -1);
          if (lines[i+1] != NULL)
            gtk_text_buffer_insert (source_buffer, &start, "\n", 1);
          break;
        }
    }

  g_strfreev (lines);

  fontify (source_buffer);

  gtk_text_view_set_buffer (GTK_TEXT_VIEW (source_view), source_buffer);
  g_object_unref (source_buffer);

  gtk_text_view_set_buffer (GTK_TEXT_VIEW (info_view), info_buffer);
  g_object_unref (info_buffer);
}
示例#30
0
static gboolean ril_get_net_config(struct radio_data *rsd)
{
	GKeyFile *keyfile;
	GError *err = NULL;
	char *config_path = RIL_CONFIG_DIR;
	char **alreadyset = NULL;
	gboolean needsconfig = FALSE;
	gboolean value = FALSE;
	gboolean found = FALSE;
	rsd->ratmode = PREF_NET_TYPE_GSM_WCDMA_AUTO;
	GDir *config_dir;
	const gchar *config_file;
	gsize length;
	gchar **codes = NULL;
	int i;

	/*
	 * First we need to check should the LTE be on
	 * or not
	 */

	keyfile = g_key_file_new();

	g_key_file_set_list_separator(keyfile, ',');

	config_dir = g_dir_open(config_path, 0, NULL);
	while ((config_file = g_dir_read_name(config_dir)) != NULL) {
		char *path = g_strconcat(RIL_CONFIG_DIR "/", config_file, NULL);
		DBG("Rilconfig handling %s", path);
		gboolean ok = g_key_file_load_from_file(keyfile, path, 0, &err);

		g_free(path);
		if (!ok) {
			g_error_free(err);
			DBG("Rilconfig file skipped");
			continue;
		}

		if (g_key_file_has_group(keyfile, LTE_FLAG))
			found = TRUE;
		else if (g_key_file_has_group(keyfile, MCC_LIST)) {
			codes = g_key_file_get_string_list(keyfile, MCC_LIST,
						MCC_KEY, &length, NULL);
			if (codes) {
				for (i = 0; codes[i]; i++) {
					if (g_str_equal(codes[i],
						ofono_sim_get_mcc(get_sim()))
							== TRUE) {
						found = TRUE;
						break;
					}
				}
				g_strfreev(codes);
			}
		}

		if (found) {
			rsd->ratmode = PREF_NET_TYPE_LTE_GSM_WCDMA;
			break;
		}
	}

	g_key_file_free(keyfile);
	g_dir_close(config_dir);

	/* Then we need to check if it already set */

	keyfile = storage_open(NULL, RIL_STORE);
	alreadyset = g_key_file_get_groups(keyfile, NULL);

	if (alreadyset[0])
		value = g_key_file_get_boolean(
			keyfile, alreadyset[0], LTE_FLAG, NULL);
	else if (rsd->ratmode == PREF_NET_TYPE_GSM_WCDMA_AUTO)
		value = TRUE;

	if (!value && rsd->ratmode == PREF_NET_TYPE_LTE_GSM_WCDMA) {
			g_key_file_set_boolean(keyfile,
				LTE_FLAG, LTE_FLAG, TRUE);
			needsconfig = TRUE;
	} else if (value && rsd->ratmode == PREF_NET_TYPE_GSM_WCDMA_AUTO) {
			g_key_file_set_boolean(keyfile,
				LTE_FLAG, LTE_FLAG, FALSE);
			needsconfig = TRUE;
	}

	g_strfreev(alreadyset);

	storage_close(NULL, RIL_STORE, keyfile, TRUE);

	DBG("needsconfig %d, rat mode %d", needsconfig, rsd->ratmode);
	return needsconfig;
}