Exemple #1
0
/* session_restore(const char *name) {{{*/
gboolean
session_restore(char *name, int flags) 
{
    gboolean is_marked = false;
    char *uri = NULL;
    GList *currentview = NULL, *lastview = NULL;
    WebKitWebBackForwardList *bf_list = NULL;
    int last = 1;
    char *end;
    gboolean ret = false;
    int locked_state = 0;
    if (name == NULL) 
        s_session_name = g_strdup("default");
    else 
        s_session_name = name;

    char *group = session_get_group(s_session_name, &is_marked);
    if (is_marked && (flags & SESSION_FORCE) == 0) 
    {
        fprintf(stderr, "Warning: Session '%s' will not be restored.\n", s_session_name);
        fprintf(stderr, "There is already a restored session open with name '%s'.\n", s_session_name);
        fputs("To force opening a saved session use -f or --force.\n", stderr);
        s_has_marked = false;
        goto clean;
    }
    if (group == NULL) 
        return false;

    char *group_begin = strchr(group, '\n');
    session_save_file(s_session_name, group_begin+1, true);
    if (flags & SESSION_ONLY_MARK) 
        goto clean;

    char  **lines = g_strsplit(group, "\n", -1);
    int length = g_strv_length(lines) - 1;
    for (int i=1; i<=length; i++) 
    {
        char **line = g_strsplit(lines[i], " ", 4);
        if (line[0] && line[1] && line[2]) 
        {
            int current = strtol(line[0], &end, 10);

            if (current <= last) 
            {
                currentview = view_add(NULL, false);
                bf_list = webkit_web_view_get_back_forward_list(WEBVIEW(currentview));
                if (lastview) 
                {
                    session_load_webview(lastview, uri, last, locked_state);
                    locked_state = 0;
                }
                lastview = currentview;
            }
            if (current == 0 && *end == '|') 
                locked_state = strtol(end+1, NULL, 10);
            if (bf_list != NULL) 
            {
                WebKitWebHistoryItem *item = webkit_web_history_item_new_with_data(line[1], line[2]);
                webkit_web_back_forward_list_add_item(bf_list, item);
            }
            last = current;
            g_free(uri);
            uri = g_strdup(line[1]);
        }
        if (i == length && lastview)
            session_load_webview(lastview, uri, last, locked_state);

        g_strfreev(line);
    }
    g_strfreev(lines);

    if (!dwb.state.views) 
    {
        view_add(NULL, false);
        dwb_open_startpage(dwb.state.fview);
    }
    dwb_focus(dwb.state.fview);
    g_free(uri);
    ret = true;

clean:
    g_free(group);
    return ret;
}/*}}}*/
Exemple #2
0
/*****--- Callbacks ---*****/
static void log_file_changed_callback(GFileMonitor *mon,GFile *file,GFile *other,GFileMonitorEvent event,gpointer data)
{
	FacqLogWindow *log_window = FACQ_LOG_WINDOW(data);
	gchar *log_content = NULL, **read_lines = NULL;
	gsize log_size;
	GError *local_err = NULL;
	guint n_written_lines = 0, n_read_lines = 0, n_prev_lines = 0, n_empty_lines = 0;
	GtkTextBuffer *text_buffer = NULL;
	GtkTextIter endIter;

	if( g_io_channel_read_to_end(log_window->priv->log,
				     &log_content,
				     &log_size,&local_err) != G_IO_STATUS_NORMAL){
		if(local_err){
			g_printerr("%s\n",local_err->message);
			g_clear_error(&local_err);
		}
		if(log_content)
			g_free(log_content);
		return;
	}
	
	text_buffer = 
		gtk_text_view_get_buffer(GTK_TEXT_VIEW(log_window->priv->text_view));

	n_written_lines = gtk_text_buffer_get_line_count(text_buffer);
	read_lines = g_strsplit(log_content,"\n",0);
	n_read_lines = g_strv_length(read_lines);
	n_empty_lines = log_window->priv->lines - n_written_lines;

	if(n_empty_lines >= n_read_lines){
		/* append the read_lines lines to the end */
		facq_log_file_append_to_text_buffer(text_buffer,log_content);
	}
	else {
		if(n_read_lines >= log_window->priv->lines){
			/* update the buffer with the last priv->lines lines no
			 * need to store previous lines. */
			facq_log_file_replace_text_buffer(text_buffer,
							  read_lines,
							  n_read_lines,
							  log_window->priv->lines);
		}
		else {
			/* store the last previous lines from the buffer */
			n_prev_lines = log_window->priv->lines - n_read_lines;

			/* mix the last lines with the new lines and update the
			 * buffer */
			facq_log_file_update_text_buffer(text_buffer,log_content,n_prev_lines);
		}
	}

	/* scroll to end */
	gtk_text_buffer_get_end_iter(text_buffer,&endIter);
	gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(log_window->priv->text_view),
				     &endIter,
				     0.0,FALSE,0.0,0.0);

	g_free(log_content);
	g_strfreev(read_lines);
}
static void
mud_connections_connect_cb(GtkWidget *widget, MudConnections *conn)
{
    GList *selected =
	gtk_icon_view_get_selected_items(
	    GTK_ICON_VIEW(conn->priv->iconview));
    GtkTreeIter iter;
    gchar *buf, *mud_name, *key, *strip_name,
	*profile, *host, *logon, *char_name;
    gint port;
    gchar **mud_tuple;
    gint len;
    GConfClient *client = gconf_client_get_default();
    MudConnectionView *view;

    if(g_list_length(selected) == 0)
	return;

    logon = char_name = NULL;

    gtk_tree_model_get_iter(conn->priv->icon_model, &iter,
			    (GtkTreePath *)selected->data);
    gtk_tree_model_get(conn->priv->icon_model, &iter, 0, &buf, -1);
	
    mud_tuple = g_strsplit(buf, "\n", -1);

    len = g_strv_length(mud_tuple);

    switch(len)
    {
    case 1:
	mud_name = g_strdup(mud_tuple[0]);
	break;

    case 2:
	char_name = gconf_escape_key(mud_tuple[0], -1);
	mud_name = g_strdup(mud_tuple[1]);
	break;

    default:
	g_warning("Malformed mud name passed to delete.");
	return;
    }

    g_strfreev(mud_tuple);
    g_free(buf);

    strip_name = gconf_escape_key(mud_name, -1);

    key = g_strdup_printf("/apps/gnome-mud/muds/%s/host", strip_name);
    host = gconf_client_get_string(client, key, NULL);
    g_free(key);

    key = g_strdup_printf("/apps/gnome-mud/muds/%s/profile", strip_name);
    profile = gconf_client_get_string(client, key, NULL);
    g_free(key);

    key = g_strdup_printf("/apps/gnome-mud/muds/%s/port", strip_name);
    port = gconf_client_get_int(client, key, NULL);
    g_free(key);

    if(char_name && strlen(char_name) > 0)
    {
        key = g_strdup_printf(
                "/apps/gnome-mud/muds/%s/characters/%s/logon", 
                strip_name, char_name);
        logon = gconf_client_get_string(client, key, NULL);
        g_free(key);
    }

    mud_tray_update_icon(conn->priv->tray, offline);

    view = g_object_new(MUD_TYPE_CONNECTION_VIEW,
                        "hostname", host,
                        "port", port,
                        "profile-name", profile,
                        "mud-name", mud_name,
                        "connect-string", (logon && strlen(logon) != 0) ? logon : NULL,
                        "window", conn->parent_window,
                        NULL);

    mud_window_add_connection_view(conn->parent_window, G_OBJECT(view), mud_name);
    mud_connection_view_set_profile(view,
                                    mud_profile_manager_get_profile_by_name(conn->parent_window->profile_manager,
                                                                            profile));
    mud_window_profile_menu_set_active(conn->parent_window, profile);

    g_free(mud_name);
    g_free(strip_name);
    g_object_unref(client);

    g_list_foreach(selected, (GFunc)gtk_tree_path_free, NULL);
    g_list_free(selected);

    gtk_widget_destroy(conn->priv->window);
}
PyObject *
_pygi_marshal_to_py_array (PyGIInvokeState   *state,
                           PyGICallableCache *callable_cache,
                           PyGIArgCache      *arg_cache,
                           GIArgument        *arg)
{
    GArray *array_;
    PyObject *py_obj = NULL;
    PyGISequenceCache *seq_cache = (PyGISequenceCache *)arg_cache;
    gsize processed_items = 0;

     /* GArrays make it easier to iterate over arrays
      * with different element sizes but requires that
      * we allocate a GArray if the argument was a C array
      */
    if (seq_cache->array_type == GI_ARRAY_TYPE_C) {
        gsize len;
        if (seq_cache->fixed_size >= 0) {
            g_assert(arg->v_pointer != NULL);
            len = seq_cache->fixed_size;
        } else if (seq_cache->is_zero_terminated) {
            if (arg->v_pointer == NULL) {
                len = 0;
            } else if (seq_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8) {
                len = strlen (arg->v_pointer);
            } else {
                len = g_strv_length ((gchar **)arg->v_pointer);
            }
        } else {
            GIArgument *len_arg = state->args[seq_cache->len_arg_index];
            len = len_arg->v_long;
        }

        array_ = g_array_new (FALSE,
                              FALSE,
                              seq_cache->item_size);
        if (array_ == NULL) {
            PyErr_NoMemory ();

            if (arg_cache->transfer == GI_TRANSFER_EVERYTHING && arg->v_pointer != NULL)
                g_free (arg->v_pointer);

            return NULL;
        }

        if (array_->data != NULL) 
            g_free (array_->data);
        array_->data = arg->v_pointer;
        array_->len = len;
    } else {
        array_ = arg->v_pointer;
    }

    if (seq_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8) {
        if (arg->v_pointer == NULL) {
            py_obj = PYGLIB_PyBytes_FromString ("");
        } else {
            py_obj = PYGLIB_PyBytes_FromStringAndSize (array_->data, array_->len);
        }
    } else {
        if (arg->v_pointer == NULL) {
            py_obj = PyList_New (0);
        } else {
            int i;

            gsize item_size;
            PyGIMarshalToPyFunc item_to_py_marshaller;
            PyGIArgCache *item_arg_cache;

            py_obj = PyList_New (array_->len);
            if (py_obj == NULL)
                goto err;


            item_arg_cache = seq_cache->item_cache;
            item_to_py_marshaller = item_arg_cache->to_py_marshaller;

            item_size = g_array_get_element_size (array_);

            for (i = 0; i < array_->len; i++) {
                GIArgument item_arg;
                PyObject *py_item;

                if (seq_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY) {
                    item_arg.v_pointer = g_ptr_array_index ( ( GPtrArray *)array_, i);
                } else if (item_arg_cache->type_tag == GI_TYPE_TAG_INTERFACE) {
                    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *) item_arg_cache;
                    gboolean is_gvariant = iface_cache->g_type == G_TYPE_VARIANT;

                    // FIXME: This probably doesn't work with boxed types or gvalues. See fx. _pygi_marshal_from_py_array()
                    switch (g_base_info_get_type (iface_cache->interface_info)) {
                        case GI_INFO_TYPE_STRUCT:
                            if (is_gvariant) {
                              g_assert (item_size == sizeof (gpointer));
                              if (arg_cache->transfer == GI_TRANSFER_EVERYTHING)
                                item_arg.v_pointer = g_variant_ref_sink (g_array_index (array_, gpointer, i));
                              else
                                item_arg.v_pointer = g_array_index (array_, gpointer, i);
                            } else if (arg_cache->transfer == GI_TRANSFER_EVERYTHING) {
                                gpointer *_struct = g_malloc (item_size);
                                memcpy (_struct, array_->data + i * item_size,
                                        item_size);
                                item_arg.v_pointer = _struct;
                            } else
                                item_arg.v_pointer = array_->data + i * item_size;
                            break;
                        default:
                            item_arg.v_pointer = g_array_index (array_, gpointer, i);
                            break;
                    }
                } else {
                    memcpy (&item_arg, array_->data + i * item_size, item_size);
                }

                py_item = item_to_py_marshaller ( state,
                                                callable_cache,
                                                item_arg_cache,
                                                &item_arg);

                if (py_item == NULL) {
                    Py_CLEAR (py_obj);

                    if (seq_cache->array_type == GI_ARRAY_TYPE_C)
                        g_array_unref (array_);

                    goto err;
                }
                PyList_SET_ITEM (py_obj, i, py_item);
                processed_items++;
            }
        }
    }

    if (seq_cache->array_type == GI_ARRAY_TYPE_C)
        g_array_free (array_, FALSE);

    return py_obj;

err:
    if (seq_cache->array_type == GI_ARRAY_TYPE_C) {
        g_array_free (array_, arg_cache->transfer == GI_TRANSFER_EVERYTHING);
    } else {
        /* clean up unprocessed items */
        if (seq_cache->item_cache->to_py_cleanup != NULL) {
            int j;
            PyGIMarshalCleanupFunc cleanup_func = seq_cache->item_cache->to_py_cleanup;
            for (j = processed_items; j < array_->len; j++) {
                cleanup_func (state,
                              seq_cache->item_cache,
                              g_array_index (array_, gpointer, j),
                              FALSE);
            }
        }

        if (arg_cache->transfer == GI_TRANSFER_EVERYTHING)
            g_array_free (array_, TRUE);
    }

    return NULL;
}
/* this will do zap style channels.conf only for the moment */
static GHashTable *
parse_channels_conf_from_file (GstElement * dvbbasebin, const gchar * filename,
    GError ** error)
{
  gchar *contents;
  gchar **lines;
  gchar *line;
  gchar **fields;
  const gchar *terrestrial[] = { "inversion", "bandwidth",
    "code-rate-hp", "code-rate-lp", "modulation", "transmission-mode",
    "guard", "hierarchy"
  };
  const gchar *satellite[] = { "polarity", "diseqc-source",
    "symbol-rate"
  };
  const gchar *cable[] = { "inversion", "symbol-rate", "code-rate-hp",
    "modulation"
  };
  int i, parsedchannels = 0;
  GHashTable *res;
  GError *err = NULL;

  GST_INFO_OBJECT (dvbbasebin, "parsing '%s'", filename);

  if (!g_file_get_contents (filename, &contents, NULL, &err))
    goto open_fail;

  lines = g_strsplit (contents, "\n", 0);
  res = g_hash_table_new (g_str_hash, g_str_equal);

  i = 0;
  line = lines[0];
  while (line != NULL) {
    if (line[0] != '#') {
      int numfields;
      gboolean parsed = FALSE;
      GHashTable *params = g_hash_table_new_full (g_str_hash, g_str_equal,
          g_free, g_free);

      fields = g_strsplit (line, ":", 0);
      numfields = g_strv_length (fields);
      if (numfields == 8) {
        /* satellite */
        int j;

        g_hash_table_insert (params, g_strdup ("type"), g_strdup ("satellite"));
        for (j = 2; j <= 4; j++) {
          g_hash_table_insert (params, g_strdup (satellite[j - 2]),
              g_strdup (fields[j]));
        }
        /**
         * Some ZAP format variations store freqs in MHz
         * but we internally use kHz for DVB-S/S2.
         */
        if (strlen (fields[1]) < 6) {
          g_hash_table_insert (params, g_strdup ("frequency"),
              g_strdup_printf ("%d", atoi (fields[1]) * 1000));
        } else {
          g_hash_table_insert (params, g_strdup ("frequency"),
              g_strdup_printf ("%d", atoi (fields[1])));
        }
        parsed = TRUE;
      } else if (numfields == 13) {
        /* terrestrial */
        int j;

        g_hash_table_insert (params, g_strdup ("type"),
            g_strdup ("terrestrial"));
        for (j = 2; j <= 9; j++) {
          g_hash_table_insert (params, g_strdup (terrestrial[j - 2]),
              g_strdup (fields[j]));
        }
        g_hash_table_insert (params, g_strdup ("frequency"),
            g_strdup (fields[1]));
        parsed = TRUE;
      } else if (numfields == 9) {
        /* cable */
        int j;

        g_hash_table_insert (params, g_strdup ("type"), g_strdup ("cable"));
        for (j = 2; j <= 5; j++) {
          g_hash_table_insert (params, g_strdup (cable[j - 2]),
              g_strdup (fields[j]));
        }
        g_hash_table_insert (params, g_strdup ("frequency"),
            g_strdup (fields[1]));
        parsed = TRUE;
      } else if (numfields == 6) {
        /* atsc (vsb/qam) */
        g_hash_table_insert (params, g_strdup ("type"), g_strdup ("atsc"));
        g_hash_table_insert (params, g_strdup ("modulation"),
            g_strdup (fields[2]));

        g_hash_table_insert (params, g_strdup ("frequency"),
            g_strdup (fields[1]));
        parsed = TRUE;
      }
      if (parsed) {
        g_hash_table_insert (params, g_strdup ("sid"),
            g_strdup (fields[numfields - 1]));
        g_hash_table_insert (res, g_strdup (fields[0]), params);
        parsedchannels++;
      }
      g_strfreev (fields);
    }
    line = lines[++i];
  }
  g_strfreev (lines);
  g_free (contents);

  if (parsedchannels == 0)
    goto no_channels;

  return res;

open_fail:
  {
    if (err->code == G_FILE_ERROR_NOENT) {
      g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_NOT_FOUND,
          _("Couldn't find DVB channel configuration file"));
    } else {
      g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_READ,
          _("Couldn't load DVB channel configuration file: %s"), err->message);
    }
    g_clear_error (&err);
    return NULL;
  }

no_channels:
  {
    g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_FAILED,
        _("DVB channel configuration file doesn't contain any channels"));
    g_hash_table_unref (res);
    return NULL;
  }
}
static gboolean
install_packages_in_root (RpmOstreeTreeComposeContext  *self,
                          RpmOstreeContext *ctx,
                          JsonObject      *treedata,
                          GFile           *yumroot,
                          char           **packages,
                          gboolean        *out_unmodified,
                          char           **out_new_inputhash,
                          GCancellable    *cancellable,
                          GError         **error)
{
  gboolean ret = FALSE;
  guint progress_sigid;
  GFile *contextdir = self->treefile_context_dirs->pdata[0];
  g_autoptr(RpmOstreeInstall) hifinstall = { 0, };
  DnfContext *hifctx;
  g_autofree char *ret_new_inputhash = NULL;
  g_autoptr(GKeyFile) treespec = g_key_file_new ();
  JsonArray *enable_repos = NULL;
  JsonArray *add_files = NULL;

  /* TODO - uncomment this once we have SELinux working */
#if 0
  g_autofree char *cache_repo_pathstr = glnx_fdrel_abspath (self->cachedir_dfd, "repo");
  g_autoptr(GFile) cache_repo_path = g_file_new_for_path (cache_repo_pathstr);
  glnx_unref_object OstreeRepo *ostreerepo = ostree_repo_new (cache_repo_path);

  if (!g_file_test (cache_repo_pathstr, G_FILE_TEST_EXISTS))
    {
      if (!ostree_repo_create (ostreerepo, OSTREE_REPO_MODE_BARE_USER, cancellable, error))
        goto out;
    }
#endif

  hifctx = rpmostree_context_get_hif (ctx);
  if (opt_proxy)
    dnf_context_set_http_proxy (hifctx, opt_proxy);

  /* Hack this here... see https://github.com/rpm-software-management/libhif/issues/53
   * but in the future we won't be using librpm at all for unpack/scripts, so it won't
   * matter.
   */
  { const char *debuglevel = getenv ("RPMOSTREE_RPM_VERBOSITY");
    if (!debuglevel)
      debuglevel = "info";
    dnf_context_set_rpm_verbosity (hifctx, debuglevel);
    rpmlogSetFile(NULL);
  }

  dnf_context_set_repo_dir (hifctx, gs_file_get_path_cached (contextdir));

  /* By default, retain packages in addition to metadata with --cachedir */
  if (opt_cachedir)
    dnf_context_set_keep_cache (hifctx, TRUE);
  if (opt_cache_only)
    dnf_context_set_cache_age (hifctx, G_MAXUINT);

  g_key_file_set_string (treespec, "tree", "ref", self->ref);
  g_key_file_set_string_list (treespec, "tree", "packages", (const char *const*)packages, g_strv_length (packages));

  /* Some awful code to translate between JSON and GKeyFile */
  if (json_object_has_member (treedata, "install-langs"))
    {
      JsonArray *a = json_object_get_array_member (treedata, "install-langs");
      if (!set_keyfile_string_array_from_json (treespec, "tree", "install-langs", a, error))
        goto out;
    }

  /* Bind the json \"repos\" member to the hif state, which looks at the
   * enabled= member of the repos file.  By default we forcibly enable
   * only repos which are specified, ignoring the enabled= flag.
   */
  if (!json_object_has_member (treedata, "repos"))
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Treefile is missing required \"repos\" member");
      goto out;
    }

  enable_repos = json_object_get_array_member (treedata, "repos");

  if (!set_keyfile_string_array_from_json (treespec, "tree", "repos", enable_repos, error))
    goto out;

  { gboolean docs = TRUE;

    if (!_rpmostree_jsonutil_object_get_optional_boolean_member (treedata,
                                                                 "documentation",
                                                                 &docs,
                                                                 error))
      goto out;

    if (!docs)
      g_key_file_set_boolean (treespec, "tree", "documentation", FALSE);
  }

  { g_autoptr(GError) tmp_error = NULL;
    g_autoptr(RpmOstreeTreespec) treespec_value = rpmostree_treespec_new_from_keyfile (treespec, &tmp_error);
    g_assert_no_error (tmp_error);
    
    if (!rpmostree_context_setup (ctx, gs_file_get_path_cached (yumroot), "/", treespec_value,
                                  cancellable, error))
      goto out;
  }

  /* --- Downloading metadata --- */
  if (!rpmostree_context_download_metadata (ctx, cancellable, error))
    goto out;

  if (!rpmostree_context_prepare_install (ctx, &hifinstall, cancellable, error))
    goto out;

  rpmostree_print_transaction (hifctx);

  if (json_object_has_member (treedata, "add-files"))
    add_files = json_object_get_array_member (treedata, "add-files");

  /* FIXME - just do a depsolve here before we compute download requirements */
  if (!compute_checksum_from_treefile_and_goal (self, dnf_context_get_goal (hifctx),
                                                contextdir, add_files,
                                                &ret_new_inputhash, error))
    goto out;

  /* Only look for previous checksum if caller has passed *out_unmodified */
  if (self->previous_checksum && out_unmodified != NULL)
    {
      g_autoptr(GVariant) commit_v = NULL;
      g_autoptr(GVariant) commit_metadata = NULL;
      const char *previous_inputhash = NULL;
      
      if (!ostree_repo_load_variant (self->repo, OSTREE_OBJECT_TYPE_COMMIT,
                                     self->previous_checksum,
                                     &commit_v, error))
        goto out;

      commit_metadata = g_variant_get_child_value (commit_v, 0);
      if (g_variant_lookup (commit_metadata, "rpmostree.inputhash", "&s", &previous_inputhash))
        {
          if (strcmp (previous_inputhash, ret_new_inputhash) == 0)
            {
              *out_unmodified = TRUE;
              ret = TRUE;
              goto out;
            }
        }
      else
        g_print ("Previous commit found, but without rpmostree.inputhash metadata key\n");
    }

  if (opt_dry_run)
    {
      ret = TRUE;
      goto out;
    }

  /* --- Downloading packages --- */
  if (!rpmostree_context_download (ctx, hifinstall, cancellable, error))
    goto out;
  
  { g_auto(GLnxConsoleRef) console = { 0, };
    glnx_unref_object DnfState *hifstate = dnf_state_new ();

    progress_sigid = g_signal_connect (hifstate, "percentage-changed",
                                     G_CALLBACK (on_hifstate_percentage_changed), 
                                     "Installing packages:");

    glnx_console_lock (&console);

    if (!dnf_transaction_commit (dnf_context_get_transaction (hifctx),
                                 dnf_context_get_goal (hifctx),
                                 hifstate,
                                 error))
      goto out;

    g_signal_handler_disconnect (hifstate, progress_sigid);
  }
      
  ret = TRUE;
  if (out_unmodified)
    *out_unmodified = FALSE;
  gs_transfer_out_value (out_new_inputhash, &ret_new_inputhash);
 out:
  return ret;
}
TotemPlParserResult
totem_pl_parser_add_m3u (TotemPlParser *parser,
			 GFile *file,
			 GFile *base_file,
			 TotemPlParseData *parse_data,
			 gpointer data)
{
	TotemPlParserResult retval = TOTEM_PL_PARSER_RESULT_UNHANDLED;
	char *contents, **lines;
	gsize size;
	guint i, num_lines;
	gboolean dos_mode = FALSE;
	const char *extinfo, *extvlcopt_audiotrack;
	char *pl_uri;

	if (g_file_load_contents (file, NULL, &contents, &size, NULL, NULL) == FALSE) {
		DEBUG (file, g_print ("Failed to load '%s'\n", uri));
		return TOTEM_PL_PARSER_RESULT_ERROR;
	}

	/* .pls files with a .m3u extension, the nasties */
	if (g_str_has_prefix (contents, "[playlist]") != FALSE
			|| g_str_has_prefix (contents, "[Playlist]") != FALSE
			|| g_str_has_prefix (contents, "[PLAYLIST]") != FALSE) {
		DEBUG (file, g_print ("Parsing '%s' playlist as PLS\n", uri));
		retval = totem_pl_parser_add_pls_with_contents (parser, file, base_file, contents, parse_data);
		g_free (contents);
		return retval;
	}

	if (strstr (contents, EXTINF_HLS) ||
	    strstr (contents, EXTINF_HLS2)) {
		DEBUG (file, g_print ("Unhandled HLS playlist '%s', should be passed to player\n", uri));
		g_free (contents);
		return retval;
	}

	/* Try to use ISO-8859-1 if we don't have valid UTF-8,
	 * try to parse anyway if it's not ISO-8859-1 */
	if (g_utf8_validate (contents, -1, NULL) == FALSE) {
		char *fixed;
		fixed = g_convert (contents, -1, "UTF-8", "ISO8859-1", NULL, NULL, NULL);
		if (fixed != NULL) {
			g_free (contents);
			contents = fixed;
		}
	}

	/* is non-NULL if there's an EXTINF on a preceding line */
	extinfo = NULL;
	extvlcopt_audiotrack = NULL;

	/* figure out whether we're a unix m3u or dos m3u */
	if (strstr(contents, "\x0d")) {
		dos_mode = TRUE;
	}

	lines = g_strsplit_set (contents, "\r\n", 0);
	g_free (contents);
	num_lines = g_strv_length (lines);
	/* We don't count the terminating NULL */
	num_lines--;

	/* Send out the playlist start and get crackin' */
	pl_uri = g_file_get_uri (file);
	totem_pl_parser_add_uri (parser,
				 TOTEM_PL_PARSER_FIELD_IS_PLAYLIST, TRUE,
				 TOTEM_PL_PARSER_FIELD_URI, pl_uri,
				 TOTEM_PL_PARSER_FIELD_CONTENT_TYPE, "audio/x-mpegurl",
				 NULL);

	for (i = 0; lines[i] != NULL; i++) {
		const char *line;
		char *length;
		gint64 length_num = 0;
		char *audio_track;

		line = lines[i];

		if (line[0] == '\0')
			continue;

		retval = TOTEM_PL_PARSER_RESULT_SUCCESS;

		/* Ignore leading spaces */
		for (; g_ascii_isspace (line[0]); line++)
			;

		/* Ignore comments, but mark it if we have extra info */
		if (line[0] == '#') {
			if (extinfo == NULL && g_str_has_prefix (line, EXTINF) != FALSE)
				extinfo = line;
			if (extvlcopt_audiotrack == NULL && g_str_has_prefix (line, EXTVLCOPT_AUDIOTRACK) != FALSE)
				extvlcopt_audiotrack = line;
			continue;
		}

		length = totem_pl_parser_get_extinfo_length (extinfo);
		if (length != NULL)
			length_num = totem_pl_parser_parse_duration (length, totem_pl_parser_is_debugging_enabled (parser));
		g_free (length);

		audio_track = totem_pl_parser_get_extvlcopt_audio_track (extvlcopt_audiotrack);

		/* Either it's a URI, or it has a proper path ... */
		if (strstr(line, "://") != NULL
				|| line[0] == G_DIR_SEPARATOR) {
			GFile *uri;

			uri = g_file_new_for_commandline_arg (line);
			if (length_num < 0 ||
			    totem_pl_parser_parse_internal (parser, uri, NULL, parse_data) != TOTEM_PL_PARSER_RESULT_SUCCESS) {
				totem_pl_parser_add_uri (parser,
							 TOTEM_PL_PARSER_FIELD_URI, line,
							 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
							 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
							 NULL);
			}
			g_object_unref (uri);
		} else if (g_ascii_isalpha (line[0]) != FALSE
			   && g_str_has_prefix (line + 1, ":\\")) {
			/* Path relative to a drive on Windows, we need to use
			 * the base that was passed to us */
			GFile *uri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			/* + 2, skip drive letter */
			uri = g_file_get_child (base_file, line + 2);
			totem_pl_parser_add_uri (parser,
						 TOTEM_PL_PARSER_FIELD_FILE, uri,
						 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
						 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
						 NULL);
			g_object_unref (uri);
		} else if (line[0] == '\\' && line[1] == '\\') {
			/* ... Or it's in the windows smb form
			 * (\\machine\share\filename), Note drive names
			 * (C:\ D:\ etc) are unhandled (unknown base for
			 * drive letters) */
		        char *tmpuri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			tmpuri = g_strjoin (NULL, "smb:", line, NULL);

			totem_pl_parser_add_uri (parser,
						 TOTEM_PL_PARSER_FIELD_URI, tmpuri,
						 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
						 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
						 NULL);

			g_free (tmpuri);
		} else {
			/* Try with a base */
			GFile *uri, *_base_file;
			char sep;

			_base_file = g_file_get_parent (file);
			sep = (dos_mode ? '\\' : '/');
			if (sep == '\\')
				lines[i] = g_strdelimit (lines[i], "\\", '/');
			uri = g_file_get_child (_base_file, line);
			g_object_unref (_base_file);
			totem_pl_parser_add_uri (parser,
						 TOTEM_PL_PARSER_FIELD_FILE, uri,
						 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
						 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
						 NULL);
			g_object_unref (uri);
		}
		extinfo = NULL;
		extvlcopt_audiotrack = NULL;

		g_free (audio_track);
	}

	g_strfreev (lines);

	totem_pl_parser_playlist_end (parser, pl_uri);
	g_free (pl_uri);

	return retval;
}
Exemple #8
0
/**
 * pk_backend_spawn_parse_stdout:
 **/
static gboolean
pk_backend_spawn_parse_stdout (PkBackendSpawn *backend_spawn,
			       PkBackendJob *job,
			       const gchar *line,
			       GError **error)
{
	gchar **sections;
	guint size;
	gchar *command;
	gchar *text;
	gboolean ret = TRUE;
	guint64 speed;
	guint64 download_size_remaining;
	PkInfoEnum info;
	PkRestartEnum restart;
	PkGroupEnum group;
	gulong package_size;
	gint percentage;
	PkErrorEnum error_enum;
	PkStatusEnum status_enum;
	PkMessageEnum message_enum;
	PkRestartEnum restart_enum;
	PkSigTypeEnum sig_type;
	PkUpdateStateEnum update_state_enum;
	PkMediaTypeEnum media_type_enum;
	PkDistroUpgradeEnum distro_upgrade_enum;
	PkBackendSpawnPrivate *priv = backend_spawn->priv;

	g_return_val_if_fail (PK_IS_BACKEND_SPAWN (backend_spawn), FALSE);

	/* check if output line */
	if (line == NULL)
		return FALSE;

	/* split by tab */
	sections = g_strsplit (line, "\t", 0);
	command = sections[0];

	/* get size */
	size = g_strv_length (sections);

	if (g_strcmp0 (command, "package") == 0) {
		if (size != 4) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		if (pk_package_id_check (sections[2]) == FALSE) {
			g_set_error_literal (error, 1, 0, "invalid package_id");
			ret = FALSE;
			goto out;
		}
		info = pk_info_enum_from_string (sections[1]);
		if (info == PK_INFO_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Info enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_package (job, info, sections[2], sections[3]);
	} else if (g_strcmp0 (command, "details") == 0) {
		if (size != 7) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		group = pk_group_enum_from_string (sections[3]);

		/* ITS4: ignore, checked for overflow */
		package_size = atol (sections[6]);
		if (package_size > 1073741824) {
			g_set_error_literal (error, 1, 0, "package size cannot be larger than one Gb");
			ret = FALSE;
			goto out;
		}
		text = g_strdup (sections[4]);
		/* convert ; to \n as we can't emit them on stdout */
		g_strdelimit (text, ";", '\n');
		pk_backend_job_details (job, sections[1], sections[2],
					group, text, sections[5], package_size);
		g_free (text);
	} else if (g_strcmp0 (command, "finished") == 0) {
		if (size != 1) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_finished (job);
		priv->is_busy = FALSE;

		/* from this point on, we can start the kill timer */
		pk_backend_spawn_start_kill_timer (backend_spawn);

	} else if (g_strcmp0 (command, "files") == 0) {
		if (size != 3) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_files (job, sections[1], sections[2]);
	} else if (g_strcmp0 (command, "repo-detail") == 0) {
		if (size != 4) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		if (g_strcmp0 (sections[3], "true") == 0) {
			pk_backend_job_repo_detail (job, sections[1], sections[2], TRUE);
		} else if (g_strcmp0 (sections[3], "false") == 0) {
			pk_backend_job_repo_detail (job, sections[1], sections[2], FALSE);
		} else {
			g_set_error (error, 1, 0, "invalid qualifier '%s'", sections[3]);
			ret = FALSE;
			goto out;
		}
	} else if (g_strcmp0 (command, "updatedetail") == 0) {
		gchar **updates;
		gchar **obsoletes;
		gchar **vendor_urls;
		gchar **bugzilla_urls;
		gchar **cve_urls;
		if (size != 13) {
			g_set_error (error, 1, 0, "invalid command '%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		restart = pk_restart_enum_from_string (sections[7]);
		if (restart == PK_RESTART_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Restart enum not recognised, and hence ignored: '%s'", sections[7]);
			ret = FALSE;
			goto out;
		}
		update_state_enum = pk_update_state_enum_from_string (sections[10]);
		/* convert ; to \n as we can't emit them on stdout */
		g_strdelimit (sections[8], ";", '\n');
		g_strdelimit (sections[9], ";", '\n');
		updates = g_strsplit (sections[2], "&", -1);
		obsoletes = g_strsplit (sections[3], "&", -1);
		vendor_urls = g_strsplit (sections[4], ";", -1);
		bugzilla_urls = g_strsplit (sections[5], ";", -1);
		cve_urls = g_strsplit (sections[6], ";", -1);
		pk_backend_job_update_detail (job,
					  sections[1],
					  updates,
					  obsoletes,
					  vendor_urls,
					  bugzilla_urls,
					  cve_urls,
					  restart,
					  sections[8],
					  sections[9],
					  update_state_enum,
					  sections[11],
					  sections[12]);
		g_strfreev (updates);
		g_strfreev (obsoletes);
		g_strfreev (vendor_urls);
		g_strfreev (bugzilla_urls);
		g_strfreev (cve_urls);
	} else if (g_strcmp0 (command, "percentage") == 0) {
		if (size != 2) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		ret = pk_strtoint (sections[1], &percentage);
		if (!ret) {
			g_set_error (error, 1, 0, "invalid percentage value %s", sections[1]);
			ret = FALSE;
		} else if (percentage < 0 || percentage > 100) {
			g_set_error (error, 1, 0, "invalid percentage value %i", percentage);
			ret = FALSE;
		} else {
			pk_backend_job_set_percentage (job, percentage);
		}
	} else if (g_strcmp0 (command, "item-progress") == 0) {
		if (size != 4) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		if (!pk_package_id_check (sections[1])) {
			g_set_error (error, 1, 0, "invalid package_id");
			ret = FALSE;
			goto out;
		}
		status_enum = pk_status_enum_from_string (sections[2]);
		if (status_enum == PK_STATUS_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Status enum not recognised, and hence ignored: '%s'", sections[2]);
			ret = FALSE;
			goto out;
		}
		ret = pk_strtoint (sections[3], &percentage);
		if (!ret) {
			g_set_error (error, 1, 0, "invalid item-progress value %s", sections[3]);
			ret = FALSE;
			goto out;
		}
		if (percentage < 0 || percentage > 100) {
			g_set_error (error, 1, 0, "invalid item-progress value %i", percentage);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_set_item_progress (job,
						  sections[1],
						  status_enum,
						  percentage);
	} else if (g_strcmp0 (command, "error") == 0) {
		if (size != 3) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		error_enum = pk_error_enum_from_string (sections[1]);
		if (error_enum == PK_ERROR_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Error enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
		/* convert back all the ;'s to newlines */
		text = g_strdup (sections[2]);

		/* convert ; to \n as we can't emit them on stdout */
		g_strdelimit (text, ";", '\n');

		/* convert % else we try to format them */
		g_strdelimit (text, "%", '$');

		pk_backend_job_error_code (job, error_enum, text);
		g_free (text);
	} else if (g_strcmp0 (command, "requirerestart") == 0) {
		if (size != 3) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		restart_enum = pk_restart_enum_from_string (sections[1]);
		if (restart_enum == PK_RESTART_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Restart enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
		if (!pk_package_id_check (sections[2])) {
			g_set_error (error, 1, 0, "invalid package_id");
			ret = FALSE;
			goto out;
		}
		pk_backend_job_require_restart (job, restart_enum, sections[2]);
	} else if (g_strcmp0 (command, "message") == 0) {
		if (size != 3) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		message_enum = pk_message_enum_from_string (sections[1]);
		if (message_enum == PK_MESSAGE_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Message enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
		text = g_strdup (sections[2]);
		/* convert ; to \n as we can't emit them on stdout */
		g_strdelimit (text, ";", '\n');
		pk_backend_job_message (job, message_enum, text);
		g_free (text);
	} else if (g_strcmp0 (command, "status") == 0) {
		if (size != 2) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		status_enum = pk_status_enum_from_string (sections[1]);
		if (status_enum == PK_STATUS_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Status enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_set_status (job, status_enum);
	} else if (g_strcmp0 (command, "speed") == 0) {
		if (size != 2) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		ret = pk_strtouint64 (sections[1], &speed);
		if (!ret) {
			g_set_error (error, 1, 0,
				     "failed to parse speed: '%s'",
				     sections[1]);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_set_speed (job, speed);
	} else if (g_strcmp0 (command, "download-size-remaining") == 0) {
		if (size != 2) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		ret = pk_strtouint64 (sections[1], &download_size_remaining);
		if (!ret) {
			g_set_error (error, 1, 0,
				     "failed to parse download_size_remaining: '%s'",
				     sections[1]);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_set_download_size_remaining (job, download_size_remaining);
	} else if (g_strcmp0 (command, "allow-cancel") == 0) {
		if (size != 2) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		if (g_strcmp0 (sections[1], "true") == 0) {
			pk_backend_job_set_allow_cancel (job, TRUE);
		} else if (g_strcmp0 (sections[1], "false") == 0) {
			pk_backend_job_set_allow_cancel (job, FALSE);
		} else {
			g_set_error (error, 1, 0, "invalid section '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
	} else if (g_strcmp0 (command, "no-percentage-updates") == 0) {
		if (size != 1) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_set_percentage (job, PK_BACKEND_PERCENTAGE_INVALID);
	} else if (g_strcmp0 (command, "repo-signature-required") == 0) {

		if (size != 9) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}

		sig_type = pk_sig_type_enum_from_string (sections[8]);
		if (sig_type == PK_SIGTYPE_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "Sig enum not recognised, and hence ignored: '%s'", sections[8]);
			ret = FALSE;
			goto out;
		}
		if (pk_strzero (sections[1])) {
			g_set_error (error, 1, 0, "package_id blank, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}
		if (pk_strzero (sections[2])) {
			g_set_error (error, 1, 0, "repository name blank, and hence ignored: '%s'", sections[2]);
			ret = FALSE;
			goto out;
		}

		/* pass _all_ of the data */
		pk_backend_job_repo_signature_required (job, sections[1],
							  sections[2], sections[3], sections[4],
							  sections[5], sections[6], sections[7], sig_type);
		goto out;

	} else if (g_strcmp0 (command, "eula-required") == 0) {

		if (size != 5) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}

		if (pk_strzero (sections[1])) {
			g_set_error (error, 1, 0, "eula_id blank, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}

		if (pk_strzero (sections[2])) {
			g_set_error (error, 1, 0, "package_id blank, and hence ignored: '%s'", sections[2]);
			ret = FALSE;
			goto out;
		}

		if (pk_strzero (sections[4])) {
			g_set_error (error, 1, 0, "agreement name blank, and hence ignored: '%s'", sections[4]);
			ret = FALSE;
			goto out;
		}

		pk_backend_job_eula_required (job, sections[1], sections[2], sections[3], sections[4]);
		goto out;

	} else if (g_strcmp0 (command, "media-change-required") == 0) {

		if (size != 4) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}

		media_type_enum = pk_media_type_enum_from_string (sections[1]);
		if (media_type_enum == PK_MEDIA_TYPE_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "media type enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}

		pk_backend_job_media_change_required (job, media_type_enum, sections[2], sections[3]);
		goto out;
	} else if (g_strcmp0 (command, "distro-upgrade") == 0) {

		if (size != 4) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}

		distro_upgrade_enum = pk_distro_upgrade_enum_from_string (sections[1]);
		if (distro_upgrade_enum == PK_DISTRO_UPGRADE_ENUM_UNKNOWN) {
			g_set_error (error, 1, 0, "distro upgrade enum not recognised, and hence ignored: '%s'", sections[1]);
			ret = FALSE;
			goto out;
		}

		pk_backend_job_distro_upgrade (job, distro_upgrade_enum, sections[2], sections[3]);
		goto out;
	} else if (g_strcmp0 (command, "category") == 0) {

		if (size != 6) {
			g_set_error (error, 1, 0, "invalid command'%s', size %i", command, size);
			ret = FALSE;
			goto out;
		}
		if (g_strcmp0 (sections[1], sections[2]) == 0) {
			g_set_error_literal (error, 1, 0, "cat_id cannot be the same as parent_id");
			ret = FALSE;
			goto out;
		}
		if (pk_strzero (sections[2])) {
			g_set_error_literal (error, 1, 0, "cat_id cannot not blank");
			ret = FALSE;
			goto out;
		}
		if (pk_strzero (sections[3])) {
			g_set_error_literal (error, 1, 0, "name cannot not blank");
			ret = FALSE;
			goto out;
		}
		if (pk_strzero (sections[5])) {
			g_set_error_literal (error, 1, 0, "icon cannot not blank");
			ret = FALSE;
			goto out;
		}
		if (g_str_has_prefix (sections[5], "/")) {
			g_set_error (error, 1, 0, "icon '%s' should be a named icon, not a path", sections[5]);
			ret = FALSE;
			goto out;
		}
		pk_backend_job_category (job, sections[1], sections[2], sections[3], sections[4], sections[5]);
		goto out;
	} else {
		ret = FALSE;
		g_set_error (error, 1, 0, "invalid command '%s'", command);
	}
out:
	g_strfreev (sections);
	return ret;
}
static GtkTreeModel *
net_model_create (void)
{
  GtkTreeModel *model;
  GtkTreeStore *store;
  GtkTreeIter new_iter;
  GtkTreeIter parent_iter;
  GtkTreeIter *parent_ptr;
  GtkTreePath *path;
  GtkTreeRowReference *row_ref;
  GHashTable *prefix_hash;
  char *display_name;
  char *hash_string;
  char **join_array;
  char **path_segments;
  int path_depth;
  int try_depth;

  store = gtk_tree_store_new (N_NET_COLUMNS,
			      G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);

  model = GTK_TREE_MODEL (store);

  /* Hash table stores GtkTreeRowReference for given path prefixes */
  prefix_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
                                       (GDestroyNotify)
                                         gtk_tree_row_reference_free);

  MENU_LOOP (&PCB->NetlistLib);
  {
    if (!menu->Name)
      continue;

    if (loading_new_netlist)
      menu->flag = TRUE;

    parent_ptr = NULL;

    path_segments = g_strsplit (menu->Name, NET_HIERARCHY_SEPARATOR, 0);
    path_depth = g_strv_length (path_segments);

    for (try_depth = path_depth - 1; try_depth > 0; try_depth--)
      {
        join_array = g_new0 (char *, try_depth + 1);
        memcpy (join_array, path_segments, sizeof (char *) * try_depth);

        /* See if this net's parent node is in the hash table */
        hash_string = g_strjoinv (NET_HIERARCHY_SEPARATOR, join_array);
        g_free (join_array);

        row_ref = (GtkTreeRowReference *)g_hash_table_lookup (prefix_hash, hash_string);
        g_free (hash_string);

        /* If we didn't find the path at this level, keep looping */
        if (row_ref == NULL)
          continue;

        path = gtk_tree_row_reference_get_path (row_ref);
        gtk_tree_model_get_iter (model, &parent_iter, path);
        parent_ptr = &parent_iter;
        break;
      }

    /* NB: parent_ptr may still be NULL if we reached the toplevel */

    /* Now walk up the desired path, adding the nodes */

    for (; try_depth < path_depth - 1; try_depth++)
      {
        display_name = g_strconcat (path_segments[try_depth],
                                    NET_HIERARCHY_SEPARATOR, NULL);
        gtk_tree_store_append (store, &new_iter, parent_ptr);
        gtk_tree_store_set (store, &new_iter,
                            NET_ENABLED_COLUMN, "",
                            NET_NAME_COLUMN, display_name,
                            NET_LIBRARY_COLUMN, NULL, -1);
        g_free (display_name);

        path = gtk_tree_model_get_path (model, &new_iter);
        row_ref = gtk_tree_row_reference_new (model, path);
        parent_iter = new_iter;
        parent_ptr = &parent_iter;

        join_array = g_new0 (char *, try_depth + 2);
        memcpy (join_array, path_segments, sizeof (char *) * (try_depth + 1));

        hash_string = g_strjoinv (NET_HIERARCHY_SEPARATOR, join_array);
        g_free (join_array);

        /* Insert those node in the hash table */
        g_hash_table_insert (prefix_hash, hash_string, row_ref);
        /* Don't free hash_string, it is now oened by the hash table */
      }

    gtk_tree_store_append (store, &new_iter, parent_ptr);
    gtk_tree_store_set (store, &new_iter,
			NET_ENABLED_COLUMN, menu->flag ? "" : "*",
			NET_NAME_COLUMN, path_segments[path_depth - 1],
			NET_LIBRARY_COLUMN, menu, -1);
    g_strfreev (path_segments);
  }
  END_LOOP;

  g_hash_table_destroy (prefix_hash);

  return model;
}
Exemple #10
0
int
main (int argc, char **argv)
{
        struct sigaction  sa;
        GError           *error;
        char             *display_str;
        CsmManager       *manager;
        CsmStore         *client_store;
        CsmXsmpServer    *xsmp_server;
        MdmSignalHandler *signal_handler;
        static char     **override_autostart_dirs = NULL;
        static char      *session_name = NULL;
        static GOptionEntry entries[] = {
                { "autostart", 'a', 0, G_OPTION_ARG_STRING_ARRAY, &override_autostart_dirs, N_("Override standard autostart directories"), N_("AUTOSTART_DIR") },
                { "session", 0, 0, G_OPTION_ARG_STRING, &session_name, N_("Session to use"), N_("SESSION_NAME") },
                { "debug", 0, 0, G_OPTION_ARG_NONE, &debug, N_("Enable debugging code"), NULL },
                { "failsafe", 'f', 0, G_OPTION_ARG_NONE, &failsafe, N_("Do not load user-specified applications"), NULL },
                { "version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_("Version of this application"), NULL },
                /* Translators: the 'fail whale' is the black dialog we show when something goes seriously wrong */
                { "whale", 0, 0, G_OPTION_ARG_NONE, &please_fail, N_("Show the fail whale dialog for testing"), NULL },
                { NULL, 0, 0, 0, NULL, NULL, NULL }
        };

        /* Make sure that we have a session bus */
        if (!require_dbus_session (argc, argv, &error)) {
                csm_util_init_error (TRUE, "%s", error->message);
        }

        bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
        bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
        textdomain (GETTEXT_PACKAGE);

        sa.sa_handler = SIG_IGN;
        sa.sa_flags = 0;
        sigemptyset (&sa.sa_mask);
        sigaction (SIGPIPE, &sa, 0);

        error = NULL;
        gtk_init_with_args (&argc, &argv,
                            (char *) _(" - the Cinnamon session manager"),
                            entries, GETTEXT_PACKAGE,
                            &error);
        if (error != NULL) {
                g_warning ("%s", error->message);
                exit (1);
        }

        if (show_version) {
                g_print ("%s %s\n", argv [0], VERSION);
                exit (1);
        }

        if (please_fail) {
                csm_fail_whale_dialog_we_failed (TRUE, TRUE);
                gtk_main ();
                exit (1);
        }

        mdm_log_init ();
        mdm_log_set_debug (debug);

        /* Set DISPLAY explicitly for all our children, in case --display
         * was specified on the command line.
         */
        display_str = gdk_get_display ();
        csm_util_setenv ("DISPLAY", display_str);
        g_free (display_str);

        const gchar *gtk_modules;
        gchar *new_gtk_modules = NULL;

        gtk_modules = g_getenv ("GTK_MODULES");

        if (gtk_modules != NULL && g_strstr_len (gtk_modules, -1, "overlay-scrollbar")) {
            int i = 0;
            new_gtk_modules = g_strconcat ("", NULL);

            gchar **module_list = g_strsplit (gtk_modules, ":", -1);

            for (i = 0; i < g_strv_length (module_list); i++) {
                if (!g_strstr_len (module_list[i], -1, "overlay-scrollbar")) {
                    gchar *tmp = new_gtk_modules;
                    new_gtk_modules = g_strconcat (tmp, ":", module_list[i], NULL);
                    g_free (tmp);
                }
            }

            g_strfreev (module_list);
        }

        if (new_gtk_modules) {
            csm_util_setenv ("GTK_MODULES", new_gtk_modules);
        }

        g_free (new_gtk_modules);

        /* Some third-party programs rely on GNOME_DESKTOP_SESSION_ID to
         * detect if GNOME is running. We keep this for compatibility reasons.
         */
        csm_util_setenv ("GNOME_DESKTOP_SESSION_ID", "this-is-deprecated");
        csm_util_setenv ("CLUTTER_BACKEND", "x11");

        client_store = csm_store_new ();

        /* Talk to logind before acquiring a name, since it does synchronous
         * calls at initialization time that invoke a main loop and if we
         * already owned a name, then we would service too early during
         * that main loop.
         */
        g_object_unref (csm_get_system ());

        xsmp_server = csm_xsmp_server_new (client_store);

        if (!acquire_name ()) {
                csm_fail_whale_dialog_we_failed (TRUE, TRUE);
                gtk_main ();
                exit (1);
        }

        manager = csm_manager_new (client_store, failsafe);
        /*
        signal_handler = mdm_signal_handler_new ();
        mdm_signal_handler_add_fatal (signal_handler);
        mdm_signal_handler_add (signal_handler, SIGFPE, signal_cb, NULL);
        mdm_signal_handler_add (signal_handler, SIGHUP, signal_cb, NULL);
        mdm_signal_handler_add (signal_handler, SIGUSR1, signal_cb, NULL);
        mdm_signal_handler_add (signal_handler, SIGTERM, signal_cb, manager);
        mdm_signal_handler_add (signal_handler, SIGINT, signal_cb, manager);
        mdm_signal_handler_set_fatal_func (signal_handler, shutdown_cb, manager);
        */
        if (IS_STRING_EMPTY (session_name))
                session_name = _csm_manager_get_default_session (manager);

        csm_util_set_autostart_dirs (override_autostart_dirs);

        if (!csm_session_fill (manager, session_name)) {
                csm_util_init_error (TRUE, "Failed to load session \"%s\"", session_name ? session_name : "(null)");
        }

        csm_xsmp_server_start (xsmp_server);
        csm_manager_start (manager);

        gtk_main ();

        if (xsmp_server != NULL) {
                g_object_unref (xsmp_server);
        }

        if (manager != NULL) {
                g_debug ("Unreffing manager");
                g_object_unref (manager);
        }

        if (client_store != NULL) {
                g_object_unref (client_store);
        }

        if (bus_proxy != NULL) {
                g_object_unref (bus_proxy);
        }

        mdm_log_shutdown ();

        return 0;
}
Exemple #11
0
static gboolean
as_app_parse_file_key (AsApp *app,
		       GKeyFile *kf,
		       const gchar *key,
		       AsAppParseFlags flags,
		       GError **error)
{
	guint i;
	guint j;
	g_autofree gchar *locale = NULL;
	g_autofree gchar *tmp = NULL;
	g_auto(GStrv) list = NULL;

	/* NoDisplay */
	if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && strcasecmp (tmp, "True") == 0)
			as_app_add_veto (app, "NoDisplay=true");

	/* Type */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_TYPE) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (g_strcmp0 (tmp, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0) {
			g_set_error_literal (error,
					     AS_APP_ERROR,
					     AS_APP_ERROR_INVALID_TYPE,
					     "not an application");
			return FALSE;
		}

	/* Icon */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_ICON) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0') {
			g_autoptr(AsIcon) icon = NULL;
			icon = as_app_desktop_create_icon (app, tmp, flags);
			as_app_add_icon (app, icon);
		}

	/* Categories */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_CATEGORIES) == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			const gchar *category_blacklist[] = {
				"X-GNOME-Settings-Panel",
				"X-Unity-Settings-Panel",
				NULL };

			/* we have to veto these */
			for (j = 0; category_blacklist[j] != NULL; j++) {
				if (g_strcmp0 (list[i], category_blacklist[j]) == 0) {
					as_app_add_veto (app, "Has category %s",
							 category_blacklist[j]);
				}
			}

			/* check the category is valid */
			if (!as_utils_is_category_id (list[i]))
				continue;

			/* ignore some useless keys */
			if (g_strcmp0 (list[i], "GTK") == 0)
				continue;
			if (g_strcmp0 (list[i], "Qt") == 0)
				continue;
			if (g_strcmp0 (list[i], "KDE") == 0)
				continue;
			if (g_strcmp0 (list[i], "GNOME") == 0)
				continue;
			as_app_add_category (app, list[i]);
		}

	} else if (g_strcmp0 (key, "Keywords") == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			g_auto(GStrv) kw_split = NULL;
			kw_split = g_strsplit (list[i], ",", -1);
			for (j = 0; kw_split[j] != NULL; j++) {
				if (kw_split[j][0] == '\0')
					continue;
				as_app_add_keyword (app, "C", kw_split[j]);
			}
		}

	} else if (g_str_has_prefix (key, "Keywords")) {
		locale = as_app_desktop_key_get_locale (key);
		if (flags & AS_APP_PARSE_FLAG_ONLY_NATIVE_LANGS &&
		    !g_strv_contains (g_get_language_names (), locale))
			return TRUE;
		list = g_key_file_get_locale_string_list (kf,
							  G_KEY_FILE_DESKTOP_GROUP,
							  key,
							  locale,
							  NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			g_auto(GStrv) kw_split = NULL;
			kw_split = g_strsplit (list[i], ",", -1);
			for (j = 0; kw_split[j] != NULL; j++) {
				if (kw_split[j][0] == '\0')
					continue;
				as_app_add_keyword (app, locale, kw_split[j]);
			}
		}

	} else if (g_strcmp0 (key, "MimeType") == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++)
			as_app_add_mimetype (app, list[i]);

	} else if (g_strcmp0 (key, "X-AppInstall-Package") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_add_pkgname (app, tmp);

	/* OnlyShowIn */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN) == 0) {
		/* if an app has only one entry, it's that desktop */
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		if (g_strv_length (list) == 1)
			as_app_set_project_group (app, list[0]);

	/* Name */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_NAME) == 0 ||
	           g_strcmp0 (key, "_Name") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, "C", tmp);

	/* Name[] */
	} else if (g_str_has_prefix (key, G_KEY_FILE_DESKTOP_KEY_NAME)) {
		locale = as_app_desktop_key_get_locale (key);
		if (flags & AS_APP_PARSE_FLAG_ONLY_NATIVE_LANGS &&
		    !g_strv_contains (g_get_language_names (), locale))
			return TRUE;
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    G_KEY_FILE_DESKTOP_KEY_NAME,
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, locale, tmp);

	/* Comment */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_COMMENT) == 0 ||
	           g_strcmp0 (key, "_Comment") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_comment (app, "C", tmp);

	/* Comment[] */
	} else if (g_str_has_prefix (key, G_KEY_FILE_DESKTOP_KEY_COMMENT)) {
		locale = as_app_desktop_key_get_locale (key);
		if (flags & AS_APP_PARSE_FLAG_ONLY_NATIVE_LANGS &&
		    !g_strv_contains (g_get_language_names (), locale))
			return TRUE;
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    G_KEY_FILE_DESKTOP_KEY_COMMENT,
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_comment (app, locale, tmp);

	/* non-standard */
	} else if (g_strcmp0 (key, "X-Ubuntu-Software-Center-Name") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, "C", tmp);
	} else if (g_str_has_prefix (key, "X-Ubuntu-Software-Center-Name")) {
		locale = as_app_desktop_key_get_locale (key);
		if (flags & AS_APP_PARSE_FLAG_ONLY_NATIVE_LANGS &&
		    !g_strv_contains (g_get_language_names (), locale))
			return TRUE;
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    "X-Ubuntu-Software-Center-Name",
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, locale, tmp);

	/* for Ubuntu */
	} else if (g_strcmp0 (key, "X-AppStream-Ignore") == 0) {
		gboolean ret;
		ret = g_key_file_get_boolean (kf,
					      G_KEY_FILE_DESKTOP_GROUP,
					      key,
					      NULL);
		if (ret)
			as_app_add_veto (app, "X-AppStream-Ignore");
	}

	/* add any external attribute as metadata to the application */
	if (flags & AS_APP_PARSE_FLAG_ADD_ALL_METADATA)
		as_app_parse_file_metadata (app, kf, key);

	return TRUE;
}
/* Setup header fields (From:/To:/Date: etc) and message body for the e-mail.
 * This data is supposed to be sent to libcurl just before any media data.
 * This function is called once for each e-mail:
 * 1. we are about the send the first attachment
 * 2. we have sent all the attachments and continue sending new ones within
 *    a new e-mail (transfer options have been reset). */
static gboolean
gst_curl_smtp_sink_set_transfer_options_unlocked (GstCurlBaseSink * bcsink)
{
  GstCurlSmtpSink *sink = GST_CURL_SMTP_SINK (bcsink);
  GstCurlTlsSinkClass *parent_class;
  gchar *request_headers;
  GDateTime *date;
  gchar *date_str;
  gchar **tmp_list = NULL;
  gchar *subject_header = NULL;
  gchar *message_body = NULL;
  gchar *rcpt_header = NULL;
  gchar *enc_rcpt;
  gchar *from_header = NULL;
  gchar *enc_from;
  gint i;

  g_assert (sink->payload_headers == NULL);
  g_assert (sink->mail_rcpt != NULL);
  g_assert (sink->mail_from != NULL);

  /* time */
  date = g_date_time_new_now_local ();
  date_str = g_date_time_format (date, "%a %b %e %H:%M:%S %Y");
  g_date_time_unref (date);

  /* recipient, sender and subject are all UTF-8 strings, which are additionally
   * base64-encoded */

  /* recipient */
  enc_rcpt = generate_encoded_word (sink->mail_rcpt);
  rcpt_header = g_strdup_printf ("%s <%s>", enc_rcpt, sink->mail_rcpt);
  g_free (enc_rcpt);

  /* sender */
  enc_from = generate_encoded_word (sink->mail_from);
  from_header = g_strdup_printf ("%s <%s>", enc_from, sink->mail_from);
  g_free (enc_from);

  /* subject */
  if (sink->subject != NULL) {
    subject_header = generate_encoded_word (sink->subject);
  }

  /* message */
  if (sink->message_body != NULL) {
    message_body = g_base64_encode ((const guchar *) sink->message_body,
        strlen (sink->message_body));
  }

  request_headers = g_strdup_printf (
      /* headers */
      "To: %s\r\n"
      "From: %s\r\n"
      "Subject: %s\r\n"
      "Date: %s\r\n"
      MIME_VERSION "\r\n"
      "Content-Type: multipart/mixed; boundary=%s\r\n" "\r\n"
      /* body headers */
      "--" BOUNDARY_STRING "\r\n"
      "Content-Type: text/plain; charset=utf-8\r\n"
      "Content-Transfer-Encoding: BASE64\r\n"
      /* message body */
      "\r\n%s\r\n",
      rcpt_header,
      from_header,
      subject_header ? subject_header : "",
      date_str, BOUNDARY_STRING, message_body ? message_body : "");

  sink->payload_headers = g_byte_array_new ();

  g_byte_array_append (sink->payload_headers, (guint8 *) request_headers,
      strlen (request_headers));
  g_free (date_str);
  g_free (subject_header);
  g_free (message_body);
  g_free (rcpt_header);
  g_free (from_header);
  g_free (request_headers);

  curl_easy_setopt (bcsink->curl, CURLOPT_MAIL_FROM, sink->mail_from);

  if (sink->curl_recipients != NULL) {
    curl_slist_free_all (sink->curl_recipients);
    sink->curl_recipients = NULL;
  }

  tmp_list = g_strsplit_set (sink->mail_rcpt, MAIL_RCPT_DELIMITER, -1);
  for (i = 0; i < g_strv_length (tmp_list); i++) {
    sink->curl_recipients = curl_slist_append (sink->curl_recipients,
        tmp_list[i]);
  }
  g_strfreev (tmp_list);

  /* note that the CURLOPT_MAIL_RCPT takes a list, not a char array */
  curl_easy_setopt (bcsink->curl, CURLOPT_MAIL_RCPT, sink->curl_recipients);

  parent_class = GST_CURL_TLS_SINK_GET_CLASS (sink);

  if (sink->use_ssl) {
    return parent_class->set_options_unlocked (bcsink);
  }

  return TRUE;
}
static void
do_action (GtkBuilder *builder, const gchar *action, GString *string)
{
  gchar **parts;
  gint len;
  gint i;

  parts = g_strsplit (action, " ", 0);
  len = g_strv_length (parts);
  if (len > 0)
    {
      if (strcmp (parts[0], "record") == 0)
        {
          for (i = 1; i < len; i++)
            {
              GObject *o, *a;

              o = gtk_builder_get_object (builder, parts[i]);
              if (ATK_IS_OBJECT (o))
                a = o;
              else if (GTK_IS_WIDGET (o))
                a = G_OBJECT (gtk_widget_get_accessible (GTK_WIDGET (o)));
              else
                g_assert_not_reached (); 
              g_signal_connect (a, "state-change", G_CALLBACK (record_state_change), string);
            }
        }
      else if (strcmp (parts[0], "states") == 0)
        {
          g_strfreev (states);
          states = g_strdupv (parts);
        }
      else if (strcmp (parts[0], "destroy") == 0)
        {
          for (i = 1; i < len; i++)
            {
              GObject *o;

              o = gtk_builder_get_object (builder, parts[i]);
              gtk_widget_destroy (GTK_WIDGET (o));
            }
        }
      else if (strcmp (parts[0], "show") == 0)
        {
          GObject *o;

          o = gtk_builder_get_object (builder, parts[1]);
          gtk_widget_show_now (GTK_WIDGET (o));
        }
      else if (strcmp (parts[0], "focus") == 0)
        {
          GObject *o;

          o = gtk_builder_get_object (builder, parts[1]);
          gtk_widget_grab_focus (GTK_WIDGET (o));
        }
      else if (strcmp (parts[0], "wait") == 0)
        {
          GMainLoop *loop;
          gulong id;

          loop = g_main_loop_new (NULL, FALSE);
          id = g_timeout_add (1000, stop, loop);
          g_main_loop_run (loop);
          g_source_remove (id);
          g_main_loop_unref (loop);
        }
    }
  g_free (parts);
}
Exemple #14
0
/**
 * r_new_pnode:
 *
 * Create a new parsing node.
 **/
static RParserNode *
r_new_pnode(guint8 *key)
{
  RParserNode *parser_node = g_new0(RParserNode, 1);
  gchar **params = g_strsplit(key, ":", 3);
  guint params_len = g_strv_length(params);

  parser_node->first = 0;
  parser_node->last = 255;

  if (strcmp(params[0], "IPv4") == 0)
    {
      parser_node->parse = r_parser_ipv4;
      parser_node->type = RPT_IPV4;
      parser_node->first = '0';
      parser_node->last = '9';
    }
  else if (strcmp(params[0], "IPv6") == 0)
    {
      parser_node->parse = r_parser_ipv6;
      parser_node->type = RPT_IPV6;
    }
  else if (strcmp(params[0], "IPvANY") == 0)
    {
      parser_node->parse = r_parser_ip;
      parser_node->type = RPT_IP;
    }
  else if (strcmp(params[0], "NUMBER") == 0)
    {
      parser_node->parse = r_parser_number;
      parser_node->type = RPT_NUMBER;
      parser_node->first = '-';
      parser_node->last = '9';
    }
  else if (strcmp(params[0], "FLOAT") == 0 || strcmp(params[0], "DOUBLE") == 0)
    {
      /* DOUBLE is a deprecated alias for FLOAT */
      parser_node->parse = r_parser_float;
      parser_node->type = RPT_FLOAT;
      parser_node->first = '-';
      parser_node->last = '9';
    }
  else if (strcmp(params[0], "STRING") == 0)
    {
      parser_node->parse = r_parser_string;
      parser_node->type = RPT_STRING;
    }
  else if (strcmp(params[0], "ESTRING") == 0)
    {
      if (params_len == 3)
        {
          parser_node->parse = r_parser_estring_c;
          parser_node->type = RPT_ESTRING;

          if (params[2] && (strlen(params[2]) > 1))
            {
              gint len = strlen(params[2]);
              parser_node->state = GINT_TO_POINTER(len);
              parser_node->parse = r_parser_estring;
            }
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing ESTRING parser parameters",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }

    }
  else if (strcmp(params[0], "ANYSTRING") == 0)
    {
      parser_node->parse = r_parser_anystring;
      parser_node->type = RPT_ANYSTRING;
    }
  else if (strcmp(params[0], "SET") == 0)
    {
      if (params_len == 3)
        {
          parser_node->parse = r_parser_set;
          parser_node->type = RPT_SET;
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing SET parser parameters",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }
    }
  else if (g_str_has_prefix(params[0], "QSTRING"))
    {
      if (params_len == 3)
        {
          gchar *state = (gchar *) &(parser_node->state);

          parser_node->parse = r_parser_qstring;
          parser_node->type = RPT_QSTRING;
          parser_node->first = params[2][0];
          parser_node->last = params[2][0];

          if (params_len >= 2 && params[2] && strlen(params[2]) == 2)
            state[0] = params[2][1];
          else
            state[0] = params[2][0];
        }
      else
        {
          g_free(parser_node);
          msg_error("Missing QSTRING parser parameters",
                     evt_tag_str("type", params[0]), NULL);
          parser_node = NULL;
        }
    }
  else
    {
      g_free(parser_node);
      msg_error("Unknown parser type specified",
                 evt_tag_str("type", params[0]), NULL);
      parser_node = NULL;
    }

  if (parser_node && params[1])
    {
      if (params[1][0])
        parser_node->handle = log_msg_get_value_handle(params[1]);

      if (params[2])
        parser_node->param = g_strdup(params[2]);
    }


  g_strfreev(params);

  return parser_node;
}
/**
 * propono_connection_split_string:
 * @uri: The URI to be splitted.
 * @known_protocol: The protocol, if it's known. NULL otherwise.
 * @protocol: Will hold the protocol of this URI
 * @host: Will hold the host of this URI
 * @port: Will hold the port of this URI
 * @error_msg: Will hold an error message in case of fail
 *
 * Splits a URI into its several parts.
 *
 * Returns: %TRUE if the URI is splitted successfuly. FALSE otherwise.
 */
gboolean
propono_connection_split_string (const gchar *uri,
				 const gchar *known_protocol,
				 gchar       **protocol,
				 gchar       **host,
				 gint         *port,
				 gchar       **error_msg)
{
  gchar **server, **url;
  gint    lport;
  gchar  *lhost;
  gchar   ipv6_host[255] = {0,};
  ProponoPlugin *plugin;

  *error_msg = NULL;
  *host = NULL;
  *port = 0;

  url = g_strsplit (uri, "://", 2);
  if (g_strv_length (url) == 2)
    {
      if (known_protocol)
	*protocol = g_strdup (known_protocol);
      else
	*protocol = g_strdup (url[0]);
      lhost = url[1];
    }
  else
    {
      if (known_protocol)
	*protocol = g_strdup (known_protocol);
      else
	*protocol = g_strdup ("vnc");
      lhost = (gchar *) uri;
    }

  plugin = propono_plugins_engine_get_plugin_by_protocol (propono_plugins_engine_get_default (),
							  *protocol);
  if (!plugin)
    {
      *error_msg = g_strdup_printf (_("The protocol %s is not supported."), *protocol);
      g_free (*protocol);
      *protocol = NULL;
      g_strfreev (url);
      return FALSE;
    }

  if (lhost[0] == '[')
    {
      int i;
      for (i = 1; lhost[i] && lhost[i] != ']'; i++)
	{
	  ipv6_host[i-1] = lhost[i];
	  lhost[i-1] = '_';
	}
      ipv6_host[i-1] = '\0';
      lhost[i] = '_';
    }

  if (g_strrstr (lhost, "::") != NULL)
    {
      server = g_strsplit (lhost, "::", 2);
      lport = server[1] ? atoi (server[1]) : propono_plugin_get_default_port (plugin);
    }
  else
    {
      server = g_strsplit (lhost, ":", 2);
      lport = server[1] ? atoi (server[1]) : propono_plugin_get_default_port (plugin);

      if ((g_str_equal (*protocol, "vnc")) && (lport < 1024))
        lport += 5900;
    }

  lhost = ipv6_host[0] ? ipv6_host : (server[0][0] ? server[0] : "localhost");

  *host = g_strdup (lhost);
  *port = lport;

  g_strfreev (server);
  g_strfreev (url);

  return TRUE;
}
Exemple #16
0
PyObject *
pygi_get_property_value_real (PyGObject *instance,
                              const gchar *attr_name)
{
    GType g_type;
    GIPropertyInfo *property_info = NULL;
    char *property_name = g_strdup (attr_name);
    GParamSpec *pspec = NULL;
    GValue value = { 0, };
    GIArgument arg = { 0, };
    PyObject *py_value = NULL;
    GITypeInfo *type_info = NULL;
    GITransfer transfer;

    canonicalize_key (property_name);

    g_type = pyg_type_from_object ((PyObject *)instance);
    property_info = _pygi_lookup_property_from_g_type (g_type, property_name);

    if (property_info == NULL)
        goto out;

    pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (instance->obj),
                                          attr_name);
    if (pspec == NULL)
        goto out;

    g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (pspec));
    g_object_get_property (instance->obj, attr_name, &value);

    type_info = g_property_info_get_type (property_info);
    transfer = g_property_info_get_ownership_transfer (property_info);

    GITypeTag type_tag = g_type_info_get_tag (type_info);
    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
            arg.v_boolean = g_value_get_boolean (&value);
            break;
        case GI_TYPE_TAG_INT8:
            arg.v_int8 = g_value_get_schar (&value);
            break;
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_INT32:
            if (G_VALUE_HOLDS_LONG (&value))
                arg.v_long = g_value_get_long (&value);
            else
                arg.v_int = g_value_get_int (&value);
            break;
        case GI_TYPE_TAG_INT64:
            if (G_VALUE_HOLDS_LONG (&value))
                arg.v_long = g_value_get_long (&value);
            else
                arg.v_int64 = g_value_get_int64 (&value);
            break;
        case GI_TYPE_TAG_UINT8:
            arg.v_uint8 = g_value_get_uchar (&value);
            break;
        case GI_TYPE_TAG_UINT16:
        case GI_TYPE_TAG_UINT32:
            if (G_VALUE_HOLDS_ULONG (&value))
                arg.v_ulong = g_value_get_ulong (&value);
            else
                arg.v_uint = g_value_get_uint (&value);
            break;
        case GI_TYPE_TAG_UINT64:
            if (G_VALUE_HOLDS_ULONG (&value))
                arg.v_ulong = g_value_get_ulong (&value);
            else
                arg.v_uint64 = g_value_get_uint64 (&value);
            break;
        case GI_TYPE_TAG_FLOAT:
            arg.v_float = g_value_get_float (&value);
            break;
        case GI_TYPE_TAG_DOUBLE:
            arg.v_double = g_value_get_double (&value);
            break;
        case GI_TYPE_TAG_GTYPE:
            arg.v_size = g_value_get_gtype (&value);
            break;
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
            arg.v_string = g_value_dup_string (&value);
            break;
        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info;
            GIInfoType info_type;
            GType type;

            info = g_type_info_get_interface (type_info);
            type = g_registered_type_info_get_g_type (info);
            info_type = g_base_info_get_type (info);

            g_base_info_unref (info);

            switch (info_type) {
                case GI_INFO_TYPE_ENUM:
                    arg.v_int32 = g_value_get_enum (&value);
                    break;
                case GI_INFO_TYPE_INTERFACE:
                case GI_INFO_TYPE_OBJECT:
                    arg.v_pointer = g_value_get_object (&value);
                    break;
                case GI_INFO_TYPE_BOXED:
                case GI_INFO_TYPE_STRUCT:
                case GI_INFO_TYPE_UNION:

                    if (g_type_is_a (type, G_TYPE_BOXED)) {
                        arg.v_pointer = g_value_get_boxed (&value);
                    } else if (g_type_is_a (type, G_TYPE_POINTER)) {
                        arg.v_pointer = g_value_get_pointer (&value);
                    } else {
                        PyErr_Format (PyExc_NotImplementedError,
                                      "Retrieving properties of type '%s' is not implemented",
                                      g_type_name (type));
                    }
                    break;
                default:
                    PyErr_Format (PyExc_NotImplementedError,
                                  "Retrieving properties of type '%s' is not implemented",
                                  g_type_name (type));
                    goto out;
            }
            break;
        }
        case GI_TYPE_TAG_GHASH:
            arg.v_pointer = g_value_get_boxed (&value);
            break;
        case GI_TYPE_TAG_GLIST:
            arg.v_pointer = g_value_get_pointer (&value);
            break;
        case GI_TYPE_TAG_ARRAY:
        {
            gchar** strings;
            GArray *arg_items;
            int i;

            strings = g_value_get_boxed (&value);
            if (strings == NULL)
                arg.v_pointer = NULL;
            else {
                arg_items = g_array_sized_new (TRUE, TRUE, sizeof (GIArgument), g_strv_length (strings));
                g_array_set_size (arg_items, g_strv_length (strings));
                for (i = 0; strings[i] != NULL; ++i) {
                    g_array_index (arg_items, GIArgument, i).v_string = strings[i];
                }
                arg.v_pointer = arg_items;
            }
            break;
        }
        default:
            PyErr_Format (PyExc_NotImplementedError,
                          "Retrieving properties of type %s is not implemented",
                          g_type_tag_to_string (g_type_info_get_tag (type_info)));
            goto out;
    }

    py_value = _pygi_argument_to_object (&arg, type_info, transfer);

out:
    g_free (property_name);
    if (property_info != NULL)
        g_base_info_unref (property_info);
    if (type_info != NULL)
        g_base_info_unref (type_info);

    return py_value;
}
Exemple #17
0
/**
 * as_app_parse_file_key:
 **/
static gboolean
as_app_parse_file_key (AsApp *app,
		       GKeyFile *kf,
		       const gchar *key,
		       AsAppParseFlags flags,
		       GError **error)
{
	gchar *dot = NULL;
	guint i;
	guint j;
	_cleanup_free_ gchar *locale = NULL;
	_cleanup_free_ gchar *tmp = NULL;
	_cleanup_strv_free_ gchar **list = NULL;

	/* NoDisplay */
	if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && strcasecmp (tmp, "True") == 0)
			as_app_add_veto (app, "NoDisplay=true");

	/* Type */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_TYPE) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (g_strcmp0 (tmp, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0) {
			g_set_error_literal (error,
					     AS_APP_ERROR,
					     AS_APP_ERROR_INVALID_TYPE,
					     "not an application");
			return FALSE;
		}

	/* Icon */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_ICON) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0') {
			_cleanup_object_unref_ AsIcon *icon = NULL;
			icon = as_icon_new ();
			as_icon_set_name (icon, tmp);
			dot = g_strstr_len (tmp, -1, ".");
			if (dot != NULL)
				*dot = '\0';
			if (as_utils_is_stock_icon_name (tmp)) {
				as_icon_set_name (icon, tmp);
				as_icon_set_kind (icon, AS_ICON_KIND_STOCK);
			} else if ((flags & AS_APP_PARSE_FLAG_USE_FALLBACKS) > 0 &&
				   _as_utils_is_stock_icon_name_fallback (tmp)) {
				as_icon_set_name (icon, tmp);
				as_icon_set_kind (icon, AS_ICON_KIND_STOCK);
			} else {
				as_icon_set_kind (icon, AS_ICON_KIND_LOCAL);
			}
			as_app_add_icon (app, icon);
		}

	/* Categories */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_CATEGORIES) == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {

			/* check categories that if present would blacklist
			 * the application */
			if (fnmatch ("X-*-Settings-Panel", list[i], 0) == 0 ||
			    fnmatch ("X-*-Settings", list[i], 0) == 0 ||
			    fnmatch ("X-*-SettingsDialog", list[i], 0) == 0) {
				as_app_add_veto (app, "category '%s' blacklisted", list[i]);
				continue;
			}

			/* not a standard category */
			if (g_str_has_prefix (list[i], "X-"))
				continue;

			/* check the category is valid */
			if (!as_utils_is_category_id (list[i]))
				continue;

			/* ignore some useless keys */
			if (g_strcmp0 (list[i], "GTK") == 0)
				continue;
			if (g_strcmp0 (list[i], "Qt") == 0)
				continue;
			if (g_strcmp0 (list[i], "KDE") == 0)
				continue;
			if (g_strcmp0 (list[i], "GNOME") == 0)
				continue;
			as_app_add_category (app, list[i]);
		}

	} else if (g_strcmp0 (key, "Keywords") == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			_cleanup_strv_free_ gchar **kw_split = NULL;
			kw_split = g_strsplit (list[i], ",", -1);
			for (j = 0; kw_split[j] != NULL; j++) {
				if (kw_split[j][0] == '\0')
					continue;
				as_app_add_keyword (app, "C", kw_split[j]);
			}
		}

	} else if (g_str_has_prefix (key, "Keywords")) {
		locale = as_app_desktop_key_get_locale (key);
		list = g_key_file_get_locale_string_list (kf,
							  G_KEY_FILE_DESKTOP_GROUP,
							  key,
							  locale,
							  NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			_cleanup_strv_free_ gchar **kw_split = NULL;
			kw_split = g_strsplit (list[i], ",", -1);
			for (j = 0; kw_split[j] != NULL; j++) {
				if (kw_split[j][0] == '\0')
					continue;
				as_app_add_keyword (app, locale, kw_split[j]);
			}
		}

	} else if (g_strcmp0 (key, "MimeType") == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++)
			as_app_add_mimetype (app, list[i]);

	} else if (g_strcmp0 (key, "X-AppInstall-Package") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_add_pkgname (app, tmp);

	/* OnlyShowIn */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN) == 0) {
		/* if an app has only one entry, it's that desktop */
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		if (g_strv_length (list) == 1)
			as_app_set_project_group (app, list[0]);

	/* Name */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_NAME) == 0 ||
	           g_strcmp0 (key, "_Name") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, "C", tmp);

	/* Name[] */
	} else if (g_str_has_prefix (key, G_KEY_FILE_DESKTOP_KEY_NAME)) {
		locale = as_app_desktop_key_get_locale (key);
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    G_KEY_FILE_DESKTOP_KEY_NAME,
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, locale, tmp);

	/* Comment */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_COMMENT) == 0 ||
	           g_strcmp0 (key, "_Comment") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_comment (app, "C", tmp);

	/* Comment[] */
	} else if (g_str_has_prefix (key, G_KEY_FILE_DESKTOP_KEY_COMMENT)) {
		locale = as_app_desktop_key_get_locale (key);
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    G_KEY_FILE_DESKTOP_KEY_COMMENT,
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_comment (app, locale, tmp);

	/* non-standard */
	} else if (g_strcmp0 (key, "X-Ubuntu-Software-Center-Name") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, "C", tmp);
	} else if (g_str_has_prefix (key, "X-Ubuntu-Software-Center-Name")) {
		locale = as_app_desktop_key_get_locale (key);
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    "X-Ubuntu-Software-Center-Name",
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, locale, tmp);
	}

	return TRUE;
}
Exemple #18
0
gboolean
e_mail_store_save_initial_setup_sync (CamelStore *store,
				      GHashTable *save_setup,
				      ESource *collection_source,
				      ESource *account_source,
				      ESource *submission_source,
				      ESource *transport_source,
				      gboolean write_sources,
				      GCancellable *cancellable,
				      GError **error)
{
	gboolean collection_changed = FALSE;
	gboolean account_changed = FALSE;
	gboolean submission_changed = FALSE;
	gboolean transport_changed = FALSE;
	gboolean success = TRUE;
	GHashTableIter iter;
	gpointer key, value;

	g_return_val_if_fail (CAMEL_IS_STORE (store), FALSE);
	g_return_val_if_fail (save_setup != NULL, FALSE);
	g_return_val_if_fail (E_IS_SOURCE (account_source), FALSE);

	if (!g_hash_table_size (save_setup))
		return TRUE;

	/* The key name consists of up to four parts: Source:Extension:Property[:Type]
	   Source can be 'Collection', 'Account', 'Submission', 'Transport', 'Backend'
	   Extension is any extension name; it's up to the key creator to make sure
	   the extension belongs to that particular Source.
	   Property is a property name in the Extension.
	   Type is an optional letter describing the type of the value; if not set, then
	   string is used. Available values are: 'b' for boolean, 'i' for integer,
	   's' for string, 'f' for folder full path.
	   All the part values are case sensitive.
	*/

	g_hash_table_iter_init (&iter, save_setup);
	while (g_hash_table_iter_next (&iter, &key, &value)) {
		gchar **keys;

		keys = g_strsplit (key, ":", -1);
		if (g_strv_length (keys) < 3 || g_strv_length (keys) > 4) {
			g_warning ("%s: Incorrect store setup key, expects 3 or 4 parts, but %d given in '%s'",
				G_STRFUNC, g_strv_length (keys), (const gchar *) key);
		} else if (g_str_equal (keys[0], "Collection")) {
			if (mail_store_save_setup_key (store, collection_source, keys[1], keys[2], keys[3], value))
				collection_changed = TRUE;
		} else if (g_str_equal (keys[0], "Account")) {
			if (mail_store_save_setup_key (store, account_source, keys[1], keys[2], keys[3], value))
				account_changed = TRUE;
		} else if (g_str_equal (keys[0], "Submission")) {
			if (mail_store_save_setup_key (store, submission_source, keys[1], keys[2], keys[3], value))
				submission_changed = TRUE;
		} else if (g_str_equal (keys[0], "Transport")) {
			if (mail_store_save_setup_key (store, transport_source, keys[1], keys[2], keys[3], value))
				transport_changed = TRUE;
		} else if (g_str_equal (keys[0], "Backend")) {
			ESource *backend_source = NULL;

			if (collection_source && e_source_has_extension (collection_source, keys[1]))
				backend_source = collection_source;
			else if (account_source && e_source_has_extension (account_source, keys[1]))
				backend_source = account_source;

			if (mail_store_save_setup_key (store, backend_source, keys[1], keys[2], keys[3], value))
				transport_changed = TRUE;
		} else {
			g_warning ("%s: Unknown source name '%s' given in '%s'", G_STRFUNC, keys[0], (const gchar *) key);
		}
	}

	if (write_sources) {
		if (transport_changed && success && e_source_get_writable (transport_source))
			success = e_source_write_sync (transport_source, cancellable, error);
		if (submission_changed && success && e_source_get_writable (submission_source))
			success = e_source_write_sync (submission_source, cancellable, error);
		if (account_changed && success && e_source_get_writable (account_source))
			success = e_source_write_sync (account_source, cancellable, error);
		if (collection_changed && success && e_source_get_writable (collection_source))
			success = e_source_write_sync (collection_source, cancellable, error);
	}

	return success;
}
static gboolean
get_result_metas_cb (GcalShellSearchProvider  *search_provider,
                     GDBusMethodInvocation    *invocation,
                     gchar                   **results,
                     GcalShellSearchProvider2 *skel)
{
  GcalShellSearchProviderPrivate *priv;
  gint i;
  gchar *uuid, *desc;
  const gchar* location;

  g_autoptr(GTimeZone) tz;
  g_autoptr (GDateTime) datetime;
  g_autoptr (GDateTime) local_datetime;
  ECalComponentDateTime dtstart;
  gchar *start_date;

  ECalComponentText summary;
  GdkRGBA color;
  GVariantBuilder abuilder, builder;
  GVariant *icon_variant;
  GcalEventData *data;
  GdkPixbuf *gicon;

  priv = search_provider->priv;

  g_variant_builder_init (&abuilder, G_VARIANT_TYPE ("aa{sv}"));
  for (i = 0; i < g_strv_length (results); i++)
    {
      uuid = results[i];
      data = g_hash_table_lookup (priv->events, uuid);

      g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
      g_variant_builder_add (&builder, "{sv}", "id", g_variant_new_string (uuid));

      e_cal_component_get_summary (data->event_component, &summary);
      g_variant_builder_add (&builder, "{sv}", "name", g_variant_new_string (summary.value));

      get_color_name_from_source (data->source, &color);
      gicon = get_circle_pixbuf_from_color (&color, 128);
      icon_variant = g_icon_serialize (G_ICON (gicon));
      g_variant_builder_add (&builder, "{sv}", "icon", icon_variant);
      g_object_unref (gicon);
      g_variant_unref (icon_variant);

      e_cal_component_get_dtstart (data->event_component, &dtstart);

      if (dtstart.tzid != NULL)
        tz = g_time_zone_new (dtstart.tzid);
      else if (dtstart.value->zone != NULL)
        tz = g_time_zone_new (icaltimezone_get_tzid ((icaltimezone*) dtstart.value->zone));
      else
        tz = g_time_zone_new_local ();

      datetime = g_date_time_new (tz,
                                  dtstart.value->year, dtstart.value->month, dtstart.value->day,
                                  dtstart.value->hour, dtstart.value->minute, dtstart.value->second);
      local_datetime = g_date_time_to_local (datetime);

      /* FIXME: respect 24h time format */
      start_date = g_date_time_format (local_datetime,
                                       (dtstart.value->is_date == 1) ? "%x" : "%c");
      e_cal_component_free_datetime (&dtstart);

      e_cal_component_get_location (data->event_component, &location);
      if (location != NULL)
        desc = g_strconcat (start_date, ". ", location, NULL);
      else
        desc = g_strdup (start_date);

      g_variant_builder_add (&builder, "{sv}", "description", g_variant_new_string (desc));
      g_free (start_date);
      g_free (desc);

      g_variant_builder_add_value (&abuilder, g_variant_builder_end (&builder));
    }
  g_dbus_method_invocation_return_value (invocation, g_variant_new ("(aa{sv})", &abuilder));

  return TRUE;
}
static gboolean
backend_manage_packages_thread (PkBackend *backend)
{
	gchar **package_ids;
	gchar *pi;
	bool simulate;
	bool remove;

	package_ids = pk_backend_get_strv (backend, "package_ids");
	simulate = pk_backend_get_bool (backend, "simulate");
	remove = pk_backend_get_bool (backend, "remove");

	pk_backend_set_allow_cancel (backend, true);

	aptcc *m_apt = new aptcc(backend, _cancel);
	pk_backend_set_pointer(backend, "aptcc_obj", m_apt);
	if (m_apt->init()) {
		egg_debug ("Failed to create apt cache");
		delete m_apt;
		pk_backend_finished (backend);
		return false;
	}

	pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY);
	vector<pair<pkgCache::PkgIterator, pkgCache::VerIterator> > pkgs;
	for (uint i = 0; i < g_strv_length(package_ids); i++) {
		if (_cancel) {
			break;
		}

		pi = package_ids[i];
		if (pk_package_id_check(pi) == false) {
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_ID_INVALID,
					       pi);
			delete m_apt;
			pk_backend_finished (backend);
			return false;
		}

		pair<pkgCache::PkgIterator, pkgCache::VerIterator> pkg_ver;
		pkg_ver = m_apt->find_package_id(pi);
		// Ignore packages that could not be found or that exist only due to dependencies.
		if (pkg_ver.second.end() == true)
		{
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_NOT_FOUND,
					       "couldn't find package");

			delete m_apt;
			pk_backend_finished (backend);
			return false;
		} else {
			pkgs.push_back(pkg_ver);
		}
	}

	if (!m_apt->runTransaction(pkgs, simulate, remove)) {
		// Print transaction errors
		cout << "runTransaction failed" << endl;
		delete m_apt;
		pk_backend_finished (backend);
		return false;
	}

	delete m_apt;
	pk_backend_finished (backend);
	return true;
}
Exemple #21
0
/*!
  \brief bind_data() is a recursive function that is called for every container
  widget in a glade frame and it's purpose is to search the datamap file passed
  for the widget names in the glade file and if it's fond in the datamap to
  load all the attribues listed and bind them to the object using GTK+'s
  object model.
  \param widget is the widget passed to load attributes on
  \param user_data is the pointer to a BingGroup structure.
  */
G_MODULE_EXPORT void bind_data(GtkWidget *widget, gpointer user_data)
{
	BindGroup *bindgroup = (BindGroup *)user_data;
	ConfigFile *cfgfile = bindgroup->cfgfile;
	GHashTable *groups = bindgroup->groups;
	gchar * tmpbuf = NULL;
	gchar * section = NULL;
	gchar ** keys = NULL;
	gint num_keys = 0;
	gint offset = 0;
	gint page = 0;
	gint index = 0;
	gchar * initializer = NULL;
	GdkColor color;
	gchar *size = NULL;
	gint count = 0;
	gint tmpi = 0;
	gboolean hidden = FALSE;
	gchar *ptr = NULL;
	gchar **vector = NULL;
	gchar **vec2 = NULL;
	void (*func)(void) = NULL;
	GList *list = NULL;
	GList *list2 = NULL;
	const gchar *name = NULL;
	gboolean indexed = FALSE;
	Firmware_Details *firmware = NULL;
	GList ***ecu_widgets = NULL;
	GList *tab_widgets = NULL;
	void (*load_dep_obj)(GObject *, ConfigFile *,const gchar *,const gchar *) = NULL;

	ENTER();
	MTXDBG(TABLOADER,_("Entered"));
	ecu_widgets = (GList ***)DATA_GET(global_data,"ecu_widgets");
	firmware = (Firmware_Details *)DATA_GET(global_data,"firmware");

	g_return_if_fail(ecu_widgets);
	g_return_if_fail(firmware);

	if (!GTK_IS_WIDGET(widget))
	{
		EXIT();
		return;
	}

	if (GTK_IS_WIDGET(widget))
		if (GTK_IS_CONTAINER(widget))
			gtk_container_foreach(GTK_CONTAINER(widget),bind_data,user_data);
	name = gtk_widget_get_name(widget);
	if (!name)
	{
		EXIT();
		return;
	}

	if (NULL != (ptr = g_strrstr_len(name,strlen(name),"_of_")))
	{
		indexed = TRUE;
		ptr = g_strrstr_len(name,ptr-name,"_");
		tmpbuf = g_strdelimit(g_strdup(ptr),"_",' ');
		section = g_strndup(name,ptr-name);
		/*printf("(indexed) section is %s\n",section);*/
		gint result = sscanf(tmpbuf,"%d of %d",&index,&count);
		/*printf("sscanf result %i\n",result);*
		* printf("Found indexed value for \"%s\", index %i, count %i\n",tmpbuf,index,count);
		*/
		g_free(tmpbuf);
	}
	else
		section = g_strdup(name);

	if(cfg_read_string(cfgfile, section, "keys", &tmpbuf))
	{
		keys = parse_keys(tmpbuf,&num_keys,",");
		MTXDBG(TABLOADER,_("Number of keys for %s is %i\n"),section,num_keys);
		g_free(tmpbuf);
	}
	else 
	{
		g_free(section);
		EXIT();
		return;
	}

	page = -1;
	/* Store ptr to self in qdata, needed for bind_to_lists from groups*/
	OBJ_SET(widget,"self",widget);
	/* Bind the data in the "defaults" group per tab to EVERY var in that
	 * tab
	 */
	page = bind_group_data(cfgfile, G_OBJECT(widget), groups, "defaults");

	if(cfg_read_string(cfgfile, section, "group", &tmpbuf))
	{
		page = bind_group_data(cfgfile,G_OBJECT(widget),groups,tmpbuf);
		g_free(tmpbuf);
	}

	if ((!cfg_read_int(cfgfile, section, "page", &page)) && (page == -1))
	{
		MTXDBG(TABLOADER|CRITICAL,_("Object %s doesn't have a page assigned!!!!\n"),section);	

	}
	/* Bind widgets to lists if they have the bind_to_list flag set...
	 */
	tmpbuf = NULL;
	if (cfg_read_string(cfgfile, section, "bind_to_list", &tmpbuf))
	{
		bind_to_lists(widget, tmpbuf);
		g_free(tmpbuf);
	}
	if (cfg_read_boolean(cfgfile,section,"ellipsize",&tmpi))
	{
		if ((GTK_IS_LABEL(widget)) && (tmpi))
		{
			OBJ_SET(widget,"ellipsize_preferred",GINT_TO_POINTER(TRUE));
			if (DATA_GET(global_data,"ellipsize_tabs"))
				gtk_label_set_ellipsize(GTK_LABEL(widget),PANGO_ELLIPSIZE_END);
		}
	}

	/* Color selections */
	if (cfg_read_string(cfgfile, section, "active_fg", &tmpbuf))
	{
		gdk_color_parse(tmpbuf, &color);
		gtk_widget_modify_fg(widget, GTK_STATE_NORMAL, &color);
		g_free(tmpbuf);
	}
	if (cfg_read_string(cfgfile, section, "inactive_fg", &tmpbuf))
	{
		gdk_color_parse(tmpbuf, &color);
		gtk_widget_modify_fg(widget, GTK_STATE_INSENSITIVE, &color);
		g_free(tmpbuf);
	}

	/* If this widget has a "depend_on" tag we need to load the dependancy
	 * information  and store it for use when needed...
	 */
	if (cfg_read_string(cfgfile,section,"depend_on",&tmpbuf))
	{
		if (get_symbol("load_dependencies_obj",(void **)&load_dep_obj))
			load_dep_obj(G_OBJECT(widget),cfgfile,section,"depend_on");
		g_free(tmpbuf);
	}

	/* If this widget (a textview) has "create_tags" we call a special
	 * handler just for that..
	 */
	if (cfg_read_string(cfgfile,section,"create_tags",&tmpbuf))
	{
		load_tags(G_OBJECT(widget),cfgfile,section);
		g_free(tmpbuf);
	}

	/* If this widget has "tooltip" set the tip on the widget */
	if (cfg_read_string(cfgfile,section,"tooltip",&tmpbuf))
	{
		gtk_widget_set_tooltip_text(widget,tmpbuf);
		g_free(tmpbuf);
	}

	/* If this widget (a label) has "set_label" we set the label on it
	 */
	if (cfg_read_string(cfgfile,section,"set_label",&tmpbuf))
	{
/*		printf("setting label on %s to \"%s\"\n",glade_get_widget_name(widget),tmpbuf);*/
		gtk_label_set_text(GTK_LABEL(widget),tmpbuf);
		g_free(tmpbuf);
	}

	/* If this widget is temp dependant, set the current units on it 
	 */
	if (cfg_read_string(cfgfile,section,"temp_dep",&tmpbuf))
	{
		OBJ_SET(widget,"widget_temp",DATA_GET(global_data,"mtx_temp_units"));
		g_free(tmpbuf);
	}

	/* If this widget has "register_as", register it with the supplied name
	 */
	if (cfg_read_string(cfgfile,section,"register_as",&tmpbuf))
	{
		register_widget(tmpbuf,widget);
		g_free(tmpbuf);
	}
	/* If this widget has visible_functions defined */
	if (cfg_read_string(cfgfile,section,"visible_functions",&tmpbuf))
	{
		vector = g_strsplit(tmpbuf,",",-1);
		g_free(tmpbuf);
		for (guint i=0;i<g_strv_length(vector);i++)
		{
			vec2 = g_strsplit(vector[i],":",2);
			if (g_strv_length(vec2) != 2)
			{
				printf("ERROR in %s, visible_functions param is missing the framerate parameter (func:fps)\n",cfgfile->filename);
				g_strfreev(vec2);
				continue;
			}
			gint fps = (GINT)g_strtod(vec2[1],NULL);
			get_symbol(vec2[0],(void **)&func);
			if (func)
			{
				list = g_list_prepend(list,(gpointer)func);
				list2 = g_list_prepend(list2,GINT_TO_POINTER(fps));
			}
			g_strfreev(vec2);
		}
		g_strfreev(vector);
		OBJ_SET_FULL(widget,"func_list",list,g_list_free);
		OBJ_SET_FULL(widget,"func_fps_list",list2,g_list_free);
	}

	/* If this widget has "initializer" there's a global variable 
	 * with it's name on it 
	 */
	if (cfg_read_string(cfgfile,section,"initializer",&initializer))
	{
		gint widget_type = 0;
		if (!cfg_read_string(cfgfile,section,"widget_type",&tmpbuf))
			MTXDBG(TABLOADER|CRITICAL,_("Object %s has initializer, but no widget_type!!!!\n"),section);
		else
			widget_type = translate_string(tmpbuf);
		g_free(tmpbuf);
		switch (widget_type)
		{
			case MTX_RANGE:
				gtk_range_set_value(GTK_RANGE(widget),(GINT)DATA_GET(global_data,initializer));
				break;

			case MTX_SPINBUTTON:
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget),(GINT)DATA_GET(global_data,initializer));
				break;
			case MTX_ENTRY:
				gtk_entry_set_text(GTK_ENTRY(widget),(gchar *)DATA_GET(global_data,initializer));

			default:
				break;

		}
		g_free(initializer);
	}
	/* Hidden widgets have special handlers and should NOT be updated normally */
	cfg_read_boolean(cfgfile,section, "hidden", &hidden);
	offset = -1;
	cfg_read_int(cfgfile,section, "offset", &offset);
	if (offset >= 0 && indexed)
	{
		/*printf("indexed widget %s\n",name); */
		if (cfg_read_string(cfgfile, section, "size", &size))
		{
			offset += index * get_multiplier ((DataSize)translate_string (size));
			g_free(size);
		}
		else
		{
			if(OBJ_GET(widget, "size"))
			{
				offset += index * get_multiplier ((DataSize)(GINT)OBJ_GET(widget, "size"));
			}
			else
			{
				MTXDBG(TABLOADER|CRITICAL,_("Indexed Object %s has index and offset, but no size!!!!\n"),section);
				g_free(section);
				EXIT();
				return;
			}
		}
		/*printf("widget %s, offset %i\n",name,offset);*/
		OBJ_SET(widget,"offset",GINT_TO_POINTER(offset));
	}
	if (offset >= 0)
	{
		/* The way we do it now is to STORE widgets in LISTS for each
		 * offset, thus we can have multiple on screen controls bound
		 * to single data offset in the ECU
		 */
		if (page < 0)
		{
			MTXDBG(TABLOADER|CRITICAL,_("Attempting to append widget beyond bounds of Firmware Parameters,  there is a bug with this datamap widget %s, page %i, at offset %i...\n\n"),section,page,offset);
			g_free(section);
			EXIT();
			return;
		}
		if (page < firmware->total_pages)
		{
			if (offset >= firmware->page_params[page]->length)
				MTXDBG(TABLOADER|CRITICAL,_("Attempting to append widget beyond bounds of Firmware Parameters,  there is a bug with this datamap widget %s, at offset %i...\n\n"),section,offset);
			else if (!hidden)
			{

				tab_widgets = OBJ_GET(bindgroup->topframe,"tab_widgets");
				tab_widgets = g_list_prepend(tab_widgets, widget);
				OBJ_SET(bindgroup->topframe,"tab_widgets",tab_widgets);
				ecu_widgets[page][offset] = g_list_prepend(
						ecu_widgets[page][offset],
						(gpointer)widget);
			}
		}
		else
			MTXDBG(TABLOADER|CRITICAL,_("Attempting to append widget beyond bounds of Firmware Parameters, there is a bug with this datamap for widget %s, at page %i offset %i...\n\n"),section,page,offset);
	}

	/* If there is a "group" key in a section it means that it gets the
	 * rest of it's setting from the groupname listed.  This reduces
	 * redundant keys all throughout the file...
	 */
	bind_keys(G_OBJECT(widget), cfgfile, section, keys, num_keys);
	g_strfreev(keys);

	/* If this widget has the "choices" key (combobox)
	 */
	if (cfg_read_string(cfgfile,section,"choices",&tmpbuf))
	{
		combo_setup(G_OBJECT(widget),cfgfile,section);
		g_free(tmpbuf);
	}

	if (cfg_read_string(cfgfile,section,"post_functions_with_arg",&tmpbuf))
	{
		run_post_functions_with_arg(tmpbuf,widget);
		g_free(tmpbuf);
	}
	if (cfg_read_string(cfgfile,section,"post_functions",&tmpbuf))
	{
		run_post_functions(tmpbuf);
		g_free(tmpbuf);
	}
	if (cfg_read_boolean(cfgfile,section,"show_widget",&tmpi))
	{
		if (tmpi)
			gtk_widget_show(widget);
		else
			gtk_widget_hide(widget);
	}
	if (cfg_read_string(cfgfile,section,"set_tab_labels",&tmpbuf))
	{
		if (GTK_IS_NOTEBOOK(widget))
		{
			vector=g_strsplit(tmpbuf,",",-1);
			if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(widget)) == g_strv_length(vector))
			{
				for (int i=0;i<g_strv_length(vector);i++)
				{
					gtk_notebook_set_tab_label_text(GTK_NOTEBOOK(widget),
							gtk_notebook_get_nth_page(GTK_NOTEBOOK(widget),i),
							vector[i]);
				}
			}
			g_strfreev(vector);
		}
		g_free(tmpbuf);
	}
	g_free(section);
	MTXDBG(TABLOADER,_("Leaving"));
	EXIT();
	return;
}
static gboolean
backend_get_depends_or_requires_thread (PkBackend *backend)
{
	gchar **package_ids;
	PkBitfield filters;
	gchar *pi;
	bool recursive;

	package_ids = pk_backend_get_strv (backend, "package_ids");
	filters = (PkBitfield) pk_backend_get_uint (backend, "filters");
	recursive = pk_backend_get_bool (backend, "recursive");

	pk_backend_set_allow_cancel (backend, true);

	aptcc *m_apt = new aptcc(backend, _cancel);
	pk_backend_set_pointer(backend, "aptcc_obj", m_apt);
	if (m_apt->init()) {
		egg_debug ("Failed to create apt cache");
		delete m_apt;
		pk_backend_finished (backend);
		return false;
	}

	bool depends = pk_backend_get_bool(backend, "get_depends");

	pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY);
	vector<pair<pkgCache::PkgIterator, pkgCache::VerIterator> > output;
	for (uint i = 0; i < g_strv_length(package_ids); i++) {
		if (_cancel) {
			break;
		}
		pi = package_ids[i];
		if (pk_package_id_check(pi) == false) {
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_ID_INVALID,
					       pi);
			delete m_apt;
			pk_backend_finished (backend);
			return false;
		}

		pair<pkgCache::PkgIterator, pkgCache::VerIterator> pkg_ver;
		pkg_ver = m_apt->find_package_id(pi);
		if (pkg_ver.second.end() == true)
		{
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_NOT_FOUND,
					       "Couldn't find package");
			delete m_apt;
			pk_backend_finished (backend);
			return false;
		}

		if (depends) {
			m_apt->get_depends(output, pkg_ver.first, recursive);
		} else {
			m_apt->get_requires(output, pkg_ver.first, recursive);
		}
	}

	// It's faster to emmit the packages here than in the matching part
	m_apt->emit_packages(output, filters);

	delete m_apt;
	pk_backend_finished (backend);
	return true;
}
/**
 * pk_action_lookup_get_message:
 **/
static gchar *
pk_action_lookup_get_message (PolkitBackendActionLookup *lookup, const gchar *action_id,
			      PolkitDetails *details, PolkitActionDescription *action_description)
{
	PkRoleEnum role = PK_ROLE_ENUM_UNKNOWN;
	gboolean only_trusted = TRUE;
	const gchar *cmdline;
	const gchar *role_text;
	const gchar *only_trusted_text;
	const gchar *str;
	const gchar *text;
	gchar *message = NULL;
	gchar **package_ids = NULL;
	GString *string;
	guint len = 1;

	if (!g_str_has_prefix (action_id, "org.freedesktop.packagekit."))
		goto out;

	/* get role */
	role_text = polkit_details_lookup (details, "role");
	if (role_text != NULL)
		role = pk_role_enum_from_string (role_text);

	/* get only-trusted */
	only_trusted_text = polkit_details_lookup (details, "only-trusted");
	if (only_trusted_text != NULL)
		only_trusted = g_str_equal (only_trusted_text, "true");

	/* get the command line */
	cmdline = polkit_details_lookup (details, "cmdline");
	if (role == PK_ROLE_ENUM_REPO_ENABLE &&
	    pk_action_lookup_cmdline_is_debuginfo_install (cmdline)) {
		message = g_strdup (N_("To install debugging packages, extra sources need to be enabled"));
		goto out;
	}

	/* use the message shipped in the policy file */
	if (only_trusted)
		goto out;

	/* find out the number of packages so we pluralize corectly */
	str = polkit_details_lookup (details, "package_ids");
	if (str != NULL) {
		package_ids = pk_package_ids_from_string (str);
		len = g_strv_length (package_ids);
		g_strfreev (package_ids);
	}

	/* UpdatePackages */
	if (role == PK_ROLE_ENUM_UPDATE_PACKAGES) {
		string = g_string_new ("");

		/* TRANSLATORS: is not GPG signed */
		g_string_append (string, g_dgettext (GETTEXT_PACKAGE, N_("The software is not from a trusted source.")));
		g_string_append (string, "\n");

		/* TRANSLATORS: user has to trust provider -- I know, this sucks */
		text = g_dngettext (GETTEXT_PACKAGE,
				    N_("Do not update this package unless you are sure it is safe to do so."),
				    N_("Do not update these packages unless you are sure it is safe to do so."),
				    len);
		g_string_append (string, text);

		message = g_string_free (string, FALSE);
		goto out;
	}

	/* InstallPackages */
	if (role == PK_ROLE_ENUM_INSTALL_PACKAGES) {
		string = g_string_new ("");

		/* TRANSLATORS: is not GPG signed */
		g_string_append (string, g_dgettext (GETTEXT_PACKAGE, N_("The software is not from a trusted source.")));
		g_string_append (string, "\n");

		/* TRANSLATORS: user has to trust provider -- I know, this sucks */
		text = g_dngettext (GETTEXT_PACKAGE,
				    N_("Do not install this package unless you are sure it is safe to do so."),
				    N_("Do not install these packages unless you are sure it is safe to do so."),
				    len);
		g_string_append (string, text);

		message = g_string_free (string, FALSE);
		goto out;
	}
out:
	return message;
}
static gboolean
backend_get_details_thread (PkBackend *backend)
{
	gchar **package_ids;
	gchar *pi;

	bool updateDetail = pk_backend_get_bool (backend, "updateDetail");
	package_ids = pk_backend_get_strv (backend, "package_ids");
	if (package_ids == NULL) {
		pk_backend_error_code (backend,
				       PK_ERROR_ENUM_PACKAGE_ID_INVALID,
				       "Invalid package id");
		pk_backend_finished (backend);
		return false;
	}

	aptcc *m_apt = new aptcc(backend, _cancel);
	pk_backend_set_pointer(backend, "aptcc_obj", m_apt);
	if (m_apt->init()) {
		egg_debug ("Failed to create apt cache");
		delete m_apt;
		pk_backend_finished (backend);
		return false;
	}

	pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY);
	for (uint i = 0; i < g_strv_length(package_ids); i++) {
		pi = package_ids[i];
		if (pk_package_id_check(pi) == false) {
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_ID_INVALID,
					       pi);
			delete m_apt;
			pk_backend_finished (backend);
			return false;
		}

		pair<pkgCache::PkgIterator, pkgCache::VerIterator> pkg_ver;
		pkg_ver = m_apt->find_package_id(pi);
		if (pkg_ver.second.end() == true)
		{
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_NOT_FOUND,
					       "couldn't find package");

			delete m_apt;
			pk_backend_finished (backend);
			return false;
		}

		if (updateDetail) {
			m_apt->emit_update_detail(pkg_ver.first);
		} else {
			m_apt->emit_details(pkg_ver.first);
		}
	}

	delete m_apt;
	pk_backend_finished (backend);
	return true;
}
static void
recent_add(gchar *uri, const gchar *mime_type)
{
    GtkRecentManager *recent;
    GtkRecentData meta = {
        .app_name     = (char*)"remote-viewer",
        .app_exec     = (char*)"remote-viewer %u",
        .mime_type    = (char*)mime_type,
    };

    if (uri == NULL)
        return;

    recent = gtk_recent_manager_get_default();
    meta.display_name = uri;
    if (!gtk_recent_manager_add_full(recent, uri, &meta))
        g_warning("Recent item couldn't be added");
}

static void connected(VirtViewerSession *session,
                      VirtViewerApp *self G_GNUC_UNUSED)
{
    gchar *uri = virt_viewer_session_get_uri(session);
    const gchar *mime = virt_viewer_session_mime_type(session);

    recent_add(uri, mime);
    g_free(uri);
}

//char buffer[1024]={0}; 
struct remote_viewer_data rvdata;
int connectflag;
/////////////////////
//socket here declare
int cfd;				/*connecting socket*/
int recbytes;
int isn_size;
struct sockaddr_in s_add, c_add;
unsigned short portnum = 6666;
///////////////////////
int
main(int argc, char **argv)
{
/*
int cfd;
int recbytes;
int sin_size;
struct sockaddr_in s_add,c_add;
unsigned short portnum=6666; 
*/
//print***
printf("Hello,welcome to client !\r\n");
memset(&rvdata, 0 , sizeof(rvdata));

cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd)
{
	//print***
    printf("socket fail ! \r\n");
    return -1;
}
//print***
printf("socket ok !\r\n");

bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family=AF_INET;

//获取本机IP
//
char localeIp[32];
struct ifaddrs * ifAddrStruct=NULL;

     void * tmpAddrPtr=NULL;
     getifaddrs(&ifAddrStruct);
     while (ifAddrStruct!=NULL)
	 {
         if (ifAddrStruct->ifa_addr->sa_family==AF_INET)
			{ // check it is IP4
             // is a valid IP4 Address
				tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
				char addressBuffer[INET_ADDRSTRLEN];
				inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
				printf("\n%s\n",ifAddrStruct->ifa_name);
				if(strcmp(ifAddrStruct->ifa_name,"eth0") == 0)
				{
					printf("i need IP:%s\n",addressBuffer);
					strcpy(localeIp, addressBuffer);
					localeIp[strlen(addressBuffer)] = '\0';
				}
				printf("%s IP Address %s\n", ifAddrStruct->ifa_name, addressBuffer); 
			} 
		 else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6)
		 { 	// check it is IP6
             // is a valid IP6 Address
             tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
             char addressBuffer[INET6_ADDRSTRLEN];
             inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
             printf("%s IP Address %s\n", ifAddrStruct->ifa_name, addressBuffer); 
         } 
         ifAddrStruct=ifAddrStruct->ifa_next;
     }
////////////////////////////////////

s_add.sin_addr.s_addr= inet_addr(localeIp);//应该改为获取本机IP获取作为参数传递
s_add.sin_port=htons(portnum);
//print***
printf("s_addr = %#x ,port : %#x\r\n",s_add.sin_addr.s_addr,s_add.sin_port);

//发送连接请求知道服务器响应连接
while (1)
{
	if(0 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
	{
	    break;
	}
}
//print***
printf("connect ok !\r\n");

//接收服务器发送的需连接的虚拟机IP地址
if(-1 == (recbytes = read(cfd,&rvdata,sizeof(rvdata))))		/*@modify by yl*/
{
	//print***
    printf("read data fail !\r\n");
    return -1;
}
//print***
printf("read ok\r\nREC:\r\n");
//buffer[recbytes]='\0';
//print***
//printf("Buffer:%s\r\n",buffer);
printf("ip_str:%s\n", rvdata.ip_str);

///////////////////////////////////////////////////
    GOptionContext *context;
    GError *error = NULL;
    int ret = 1;
    gchar **args = NULL;
    gchar *uri = NULL;
    char *title = NULL;
    RemoteViewer *viewer = NULL;
#ifdef HAVE_SPICE_GTK
    gboolean controller = FALSE;
#endif
    VirtViewerApp *app;
    const GOptionEntry options [] = {
        { "version", 'V', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          remote_viewer_version, N_("Display version information"), NULL },
        { "title", 't', 0, G_OPTION_ARG_STRING, &title,
          N_("Set window title"), NULL },
#ifdef HAVE_SPICE_GTK
        { "spice-controller", '\0', 0, G_OPTION_ARG_NONE, &controller,
          N_("Open connection using Spice controller communication"), NULL },
#endif
        { G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_STRING_ARRAY, &args,
          NULL, "-- URI" },
        { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
    };

    virt_viewer_util_init(_("Remote Viewer"));

    /* Setup command line options */
    context = g_option_context_new (_("- Remote viewer client"));
    g_option_context_add_main_entries (context, virt_viewer_app_get_options(), NULL);
    g_option_context_add_main_entries (context, options, NULL);
    g_option_context_add_group (context, gtk_get_option_group (TRUE));
#ifdef HAVE_GTK_VNC
    g_option_context_add_group (context, vnc_display_get_option_group ());
#endif
#ifdef HAVE_SPICE_GTK
    g_option_context_add_group (context, spice_get_option_group ());
#endif
#ifdef HAVE_OVIRT
    g_option_context_add_group (context, ovirt_get_option_group ());
#endif
    g_option_context_parse (context, &argc, &argv, &error);
    if (error) {
        char *base_name;
        base_name = g_path_get_basename(argv[0]);
        g_printerr(_("%s\nRun '%s --help' to see a full list of available command line options\n"),
                   error->message, base_name);
        g_free(base_name);
        g_error_free(error);
        goto cleanup;
    }

    g_option_context_free(context);

#ifdef HAVE_SPICE_GTK
    if (controller) {
        if (args) {
            g_printerr(_("Error: extra arguments given while using Spice controller\n"));
            goto cleanup;
        }
    } else
#endif
    if (args) {
        if (g_strv_length(args) > 1) {
            g_printerr(_("Error: can't handle multiple URIs\n"));
            goto cleanup;
        } else if (g_strv_length(args) == 1) {
            uri = g_strdup(args[0]);
        }
    }

#ifdef HAVE_SPICE_GTK
    if (controller) {
        viewer = remote_viewer_new_with_controller();
        g_object_set(viewer, "guest-name", "defined by Spice controller", NULL);
    } else {
#endif
        viewer = remote_viewer_new(uri, title);
        g_object_set(viewer, "guest-name", uri, NULL);
#ifdef HAVE_SPICE_GTK
    }
#endif
    if (viewer == NULL)
        goto cleanup;

    app = VIRT_VIEWER_APP(viewer);

    if (!virt_viewer_app_start(app))
        goto cleanup;

    g_signal_connect(virt_viewer_app_get_session(app), "session-connected",
                     G_CALLBACK(connected), app);

    gtk_main();

    ret = 0;

 cleanup:
    g_free(uri);
    if (viewer)
        g_object_unref(viewer);
    g_strfreev(args);

///////////////////////////////////////
//连接虚出move to Error widget showing
/*
    if (1 == connectflag)
	write(cfd, "false", 6);
    else
	write(cfd, "true", 5);

close(cfd);
*/
///////////////////////////////////////

    return ret;
}
/**
 * backend_download_packages_thread:
 */
static gboolean
backend_download_packages_thread (PkBackend *backend)
{
	gchar **package_ids;
	string directory;

	package_ids = pk_backend_get_strv(backend, "package_ids");
	directory = _config->FindDir("Dir::Cache::archives") + "partial/";
	pk_backend_set_allow_cancel (backend, true);

	aptcc *m_apt = new aptcc(backend, _cancel);
	pk_backend_set_pointer(backend, "aptcc_obj", m_apt);
	if (m_apt->init()) {
		egg_debug ("Failed to create apt cache");
		delete m_apt;
		pk_backend_finished (backend);
		return false;
	}

	pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY);
	// Create the progress
	AcqPackageKitStatus Stat(m_apt, backend, _cancel);

	// get a fetcher
	pkgAcquire fetcher(&Stat);
	string filelist;
	gchar *pi;

	// TODO this might be useful when the item is in the cache
// 	for (pkgAcquire::ItemIterator I = fetcher.ItemsBegin(); I < fetcher.ItemsEnd();)
// 	{
// 		if ((*I)->Local == true)
// 		{
// 			I++;
// 			continue;
// 		}
//
// 		// Close the item and check if it was found in cache
// 		(*I)->Finished();
// 		if ((*I)->Complete == false) {
// 			Transient = true;
// 		}
//
// 		// Clear it out of the fetch list
// 		delete *I;
// 		I = fetcher.ItemsBegin();
// 	}

	for (uint i = 0; i < g_strv_length(package_ids); i++) {
		pi = package_ids[i];
		if (pk_package_id_check(pi) == false) {
			pk_backend_error_code (backend,
					       PK_ERROR_ENUM_PACKAGE_ID_INVALID,
					       pi);
			delete m_apt;
			pk_backend_finished (backend);
			return false;
		}

		if (_cancel) {
			break;
		}

		pair<pkgCache::PkgIterator, pkgCache::VerIterator> pkg_ver;
		pkg_ver = m_apt->find_package_id(pi);
		// Ignore packages that could not be found or that exist only due to dependencies.
		if (pkg_ver.second.end() == true)
		{
			_error->Error("Can't find this package id \"%s\".", pi);
			continue;
		} else {
			if(!pkg_ver.second.Downloadable()) {
				_error->Error("No downloadable files for %s,"
					      "perhaps it is a local or obsolete" "package?",
					      pi);
				continue;
			}

			string storeFileName;
			if (get_archive(&fetcher,
					m_apt->packageSourceList,
					m_apt->packageRecords,
					pkg_ver.second,
					directory,
					storeFileName))
			{
				Stat.addPackagePair(pkg_ver);
			}
			string destFile = directory + "/" + flNotDir(storeFileName);
			if (filelist.empty()) {
				filelist = destFile;
			} else {
				filelist.append(";" + destFile);
			}
		}
	}

	if (fetcher.Run() != pkgAcquire::Continue
	    && _cancel == false)
	// We failed and we did not cancel
	{
		show_errors(backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED);
		delete m_apt;
		pk_backend_finished (backend);
		return _cancel;
	}

	// send the filelist
	pk_backend_files(backend, NULL, filelist.c_str());

	delete m_apt;
	pk_backend_finished (backend);
	return true;
}
Exemple #27
0
static void
drag_data_received_callback (GtkWidget *widget,
		       	     GdkDragContext *context,
		       	     int x,
		       	     int y,
		       	     GtkSelectionData *data,
		             guint info,
		             guint32 time,
			     gpointer callback_data)
{
	char **names;
	NemoApplication *application;
	int name_count;
	NemoWindow *new_window, *window;
	GdkScreen      *screen;
	gboolean new_windows_for_extras;
	char *prompt;
	char *detail;
	GFile *location;
	NemoLocationBar *self = NEMO_LOCATION_BAR (widget);

	g_assert (data != NULL);
	g_assert (callback_data == NULL);

	names = g_uri_list_extract_uris ((const gchar *) gtk_selection_data_get_data (data));

	if (names == NULL || *names == NULL) {
		g_warning ("No D&D URI's");
		g_strfreev (names);
		gtk_drag_finish (context, FALSE, FALSE, time);
		return;
	}

	window = nemo_location_bar_get_window (widget);
	new_windows_for_extras = FALSE;
	/* Ask user if they really want to open multiple windows
	 * for multiple dropped URIs. This is likely to have been
	 * a mistake.
	 */
	name_count = g_strv_length (names);
	if (name_count > 1) {
		prompt = g_strdup_printf (ngettext("Do you want to view %d location?",
						   "Do you want to view %d locations?",
						   name_count), 
					  name_count);
		detail = g_strdup_printf (ngettext("This will open %d separate window.",
						   "This will open %d separate windows.",
						   name_count),
					  name_count);			  
		/* eel_run_simple_dialog should really take in pairs
		 * like gtk_dialog_new_with_buttons() does. */
		new_windows_for_extras = eel_run_simple_dialog 
			(GTK_WIDGET (window),
			 TRUE,
			 GTK_MESSAGE_QUESTION,
			 prompt,
			 detail,
			 GTK_STOCK_CANCEL, GTK_STOCK_OK,
			 NULL) != 0 /* GNOME_OK */;

		g_free (prompt);
		g_free (detail);
		
		if (!new_windows_for_extras) {
			g_strfreev (names);
			gtk_drag_finish (context, FALSE, FALSE, time);
			return;
		}
	}

	nemo_location_bar_set_location (self, names[0]);	
	emit_location_changed (self);

	if (new_windows_for_extras) {
		int i;

		application = nemo_application_get_singleton ();
		screen = gtk_window_get_screen (GTK_WINDOW (window));

		for (i = 1; names[i] != NULL; ++i) {
			new_window = nemo_application_create_window (application, screen);
			location = g_file_new_for_uri (names[i]);
			nemo_window_go_to (new_window, location);
			g_object_unref (location);
		}
	}

	g_strfreev (names);

	gtk_drag_finish (context, TRUE, FALSE, time);
}
static gboolean
backend_resolve_thread (PkBackend *backend)
{
	gchar **package_ids;
	PkBitfield filters;

	filters = (PkBitfield) pk_backend_get_uint (backend, "filters");
	package_ids = pk_backend_get_strv (backend, "package_ids");
	pk_backend_set_allow_cancel (backend, true);

	aptcc *m_apt = new aptcc(backend, _cancel);
	pk_backend_set_pointer(backend, "aptcc_obj", m_apt);
	if (m_apt->init()) {
		egg_debug ("Failed to create apt cache");
		delete m_apt;
		pk_backend_finished (backend);
		return false;
	}

	pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY);
	gchar *pi;
	vector<pair<pkgCache::PkgIterator, pkgCache::VerIterator> > output;
	for (uint i = 0; i < g_strv_length(package_ids); i++) {
		if (_cancel) {
			break;
		}

		pair<pkgCache::PkgIterator, pkgCache::VerIterator> pkg_ver;
		pi = package_ids[i];
		if (pk_package_id_check(pi) == false) {
			pkg_ver.first = m_apt->packageCache->FindPkg(pi);
			// Ignore packages that could not be found or that exist only due to dependencies.
			if (pkg_ver.first.end() == true ||
			    (pkg_ver.first.VersionList().end() && pkg_ver.first.ProvidesList().end()))
			{
				continue;
			}

			pkg_ver.second = m_apt->find_ver(pkg_ver.first);
			// check to see if the provided package isn't virtual too
			if (pkg_ver.second.end() == false)
			{
				output.push_back(pkg_ver);
			}

			pkg_ver.second = m_apt->find_candidate_ver(pkg_ver.first);
			// check to see if the provided package isn't virtual too
			if (pkg_ver.second.end() == false)
			{
				output.push_back(pkg_ver);
			}
		} else {
			pkg_ver = m_apt->find_package_id(pi);
			// check to see if we found the package
			if (pkg_ver.second.end() == false)
			{
				output.push_back(pkg_ver);
			}
		}
	}
	// It's faster to emmit the packages here rather than in the matching part
	m_apt->emit_packages(output, filters);

	delete m_apt;

	pk_backend_finished (backend);
	return true;
}
static void
mud_connections_delete_cb(GtkWidget *widget, MudConnections *conn)
{
    GList *selected =
	gtk_icon_view_get_selected_items(
	    GTK_ICON_VIEW(conn->priv->iconview));
    GtkTreeIter iter;
    gchar *buf, *mud_name, *key, *strip_name,
          *strip_char_name,  *char_name;
    gchar **mud_tuple;
    gint len;
    GConfClient *client = gconf_client_get_default();

    if(g_list_length(selected) == 0)
	return;

    char_name = strip_name = NULL;

    gtk_tree_model_get_iter(conn->priv->icon_model, &iter,
			    (GtkTreePath *)selected->data);
    gtk_tree_model_get(conn->priv->icon_model, &iter, 0, &buf, -1);
	
    mud_tuple = g_strsplit(buf, "\n", -1);
    g_free(buf);

    len = g_strv_length(mud_tuple);

    switch(len)
    {
        /* Delete Mud */
        case 1:
            mud_name = g_strdup(mud_tuple[0]);
            break;

        /* Delete Character */
        case 2:
            char_name = g_strdup(mud_tuple[0]);
            mud_name = g_strdup(mud_tuple[1]);
            break;

        default:
            g_warning("Malformed mud name passed to delete.");
            return;
    }

    if(!mud_connections_delete_confirm(mud_tuple[0]))
    {
        g_free(mud_name);

        if(char_name)
            g_free(char_name);

        g_strfreev(mud_tuple);
        g_object_unref(client);

        g_list_foreach(selected, (GFunc)gtk_tree_path_free, NULL);
        g_list_free(selected);

        return;
    }

    g_strfreev(mud_tuple);

    if(len == 1)
    {
        strip_name = gconf_escape_key(mud_name, -1);
        
        key = g_strdup_printf("/apps/gnome-mud/muds/%s", strip_name);
        gconf_client_recursive_unset(client, key, 0, NULL);
        
        g_free(key);
        
        gconf_client_suggest_sync(client, NULL);
    }
    else if(len == 2)
    {
        strip_name = gconf_escape_key(mud_name, -1);
        strip_char_name = gconf_escape_key(char_name, -1);

        key = g_strdup_printf("/apps/gnome-mud/muds/%s/characters/%s",
                strip_name, strip_char_name);

        gconf_client_recursive_unset(client, key, 0, NULL);

        g_free(key);
        g_free(strip_char_name);
        g_free(char_name);

        gconf_client_suggest_sync(client, NULL);
    }

    g_free(mud_name);
    g_free(strip_name);
    g_object_unref(client);

    g_list_foreach(selected, (GFunc)gtk_tree_path_free, NULL);
    g_list_free(selected);
}
static void
virt_viewer_file_set_property(GObject* object, guint property_id,
                        const GValue* value, GParamSpec* pspec)
{
    VirtViewerFile *self = VIRT_VIEWER_FILE(object);
    gchar **strv;

    switch (property_id) {
    case PROP_TYPE:
        virt_viewer_file_set_type(self, g_value_get_string(value));
        break;
    case PROP_HOST:
        virt_viewer_file_set_host(self, g_value_get_string(value));
        break;
    case PROP_PORT:
        virt_viewer_file_set_port(self, g_value_get_int(value));
        break;
    case PROP_TLS_PORT:
        virt_viewer_file_set_tls_port(self, g_value_get_int(value));
        break;
    case PROP_USERNAME:
        virt_viewer_file_set_username(self, g_value_get_string(value));
        break;
    case PROP_PASSWORD:
        virt_viewer_file_set_password(self, g_value_get_string(value));
        break;
    case PROP_DISABLE_CHANNELS:
        strv = g_value_get_boxed(value);
        virt_viewer_file_set_disable_channels(self, (const gchar* const*)strv, g_strv_length(strv));
        break;
    case PROP_TLS_CIPHERS:
        virt_viewer_file_set_tls_ciphers(self, g_value_get_string(value));
        break;
    case PROP_CA:
        virt_viewer_file_set_ca(self, g_value_get_string(value));
        break;
    case PROP_HOST_SUBJECT:
        virt_viewer_file_set_host_subject(self, g_value_get_string(value));
        break;
    case PROP_FULLSCREEN:
        virt_viewer_file_set_fullscreen(self, g_value_get_int(value));
        break;
    case PROP_TITLE:
        virt_viewer_file_set_title(self, g_value_get_string(value));
        break;
    case PROP_TOGGLE_FULLSCREEN:
        virt_viewer_file_set_toggle_fullscreen(self, g_value_get_string(value));
        break;
    case PROP_RELEASE_CURSOR:
        virt_viewer_file_set_release_cursor(self, g_value_get_string(value));
        break;
    case PROP_SECURE_ATTENTION:
        virt_viewer_file_set_secure_attention(self, g_value_get_string(value));
        break;
    case PROP_ENABLE_SMARTCARD:
        virt_viewer_file_set_enable_smartcard(self, g_value_get_int(value));
        break;
    case PROP_ENABLE_USBREDIR:
        virt_viewer_file_set_enable_usbredir(self, g_value_get_int(value));
        break;
    case PROP_COLOR_DEPTH:
        virt_viewer_file_set_color_depth(self, g_value_get_int(value));
        break;
    case PROP_DISABLE_EFFECTS:
        strv = g_value_get_boxed(value);
        virt_viewer_file_set_disable_effects(self, (const gchar* const*)strv, g_strv_length(strv));
        break;
    case PROP_ENABLE_USB_AUTOSHARE:
        virt_viewer_file_set_enable_usb_autoshare(self, g_value_get_int(value));
        break;
    case PROP_USB_FILTER:
        virt_viewer_file_set_usb_filter(self, g_value_get_string(value));
        break;
    case PROP_PROXY:
        virt_viewer_file_set_proxy(self, g_value_get_string(value));
        break;
    case PROP_VERSION:
        virt_viewer_file_set_version(self, g_value_get_string(value));
        break;
    case PROP_VERSIONS:
        virt_viewer_file_set_versions(self, g_value_get_boxed(value));
        break;
    case PROP_VERSION_URL:
        virt_viewer_file_set_version_url(self, g_value_get_string(value));
        break;
    case PROP_SECURE_CHANNELS:
        strv = g_value_get_boxed(value);
        virt_viewer_file_set_secure_channels(self, (const gchar* const*)strv, g_strv_length(strv));
        break;
    case PROP_DELETE_THIS_FILE:
        virt_viewer_file_set_delete_this_file(self, g_value_get_int(value));
        break;
    case PROP_OVIRT_ADMIN:
        virt_viewer_file_set_ovirt_admin(self, g_value_get_int(value));
        break;
    case PROP_OVIRT_HOST:
        virt_viewer_file_set_ovirt_host(self, g_value_get_string(value));
        break;
    case PROP_OVIRT_VM_GUID:
        virt_viewer_file_set_ovirt_vm_guid(self, g_value_get_string(value));
        break;
    case PROP_OVIRT_JSESSIONID:
        virt_viewer_file_set_ovirt_jsessionid(self, g_value_get_string(value));
        break;
    case PROP_OVIRT_SSO_TOKEN:
        virt_viewer_file_set_ovirt_sso_token(self, g_value_get_string(value));
        break;
    case PROP_OVIRT_CA:
        virt_viewer_file_set_ovirt_ca(self, g_value_get_string(value));
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
        break;
    }
}