void
ags_polling_thread_run(AgsThread *thread)
{
  AgsPollingThread *polling_thread;
  AgsThread *main_loop;
  
  GList *list;
  
  struct timespec timeout;

  sigset_t sigmask;
  gint position;
  int ret;

  polling_thread = AGS_POLLING_THREAD(thread);
  main_loop = ags_thread_get_toplevel(thread);
  
  /* real-time setup */
#ifdef AGS_WITH_RT
  if((AGS_THREAD_RT_SETUP & (g_atomic_int_get(&(thread->flags)))) == 0){
    struct sched_param param;
    
    /* Declare ourself as a real time task */
    param.sched_priority = AGS_POLLING_THREAD_RT_PRIORITY;
      
    if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
      perror("sched_setscheduler failed");
    }

    g_atomic_int_or(&(thread->flags),
		    AGS_THREAD_RT_SETUP);
  }
#endif

  sigemptyset(&sigmask);

  timeout.tv_sec = 0;

  if(g_atomic_int_get(&(main_loop->time_late)) != 0){
    timeout.tv_nsec = 0;
  }else{
    if(main_loop->tic_delay == main_loop->delay){
      if(AGS_THREAD_TOLERANCE > 0.0){
	timeout.tv_nsec = 0;
      }else{
	timeout.tv_nsec = -1 * AGS_THREAD_TOLERANCE;
      }
    }else{
      if(thread->freq > AGS_THREAD_HERTZ_JIFFIE){
	timeout.tv_nsec = (NSEC_PER_SEC / thread->freq + AGS_POLLING_THREAD_UNDERLOAD);
      }else{
	timeout.tv_nsec = (NSEC_PER_SEC / AGS_THREAD_HERTZ_JIFFIE + AGS_POLLING_THREAD_UNDERLOAD);
      }
    }
  }
  
  pthread_mutex_lock(polling_thread->fd_mutex);

  if((AGS_POLLING_THREAD_OMIT & (g_atomic_int_get(&(polling_thread->flags)))) == 0){
    list = polling_thread->poll_fd;

    /* pre flag */
    while(list != NULL){
      position = ags_polling_thread_fd_position(polling_thread,
						AGS_POLL_FD(list->data)->fd);

      if(position != -1 &&
	 AGS_POLL_FD(list->data)->poll_fd != NULL){
	AGS_POLL_FD(list->data)->poll_fd->events = polling_thread->fds[position].events;
      }

      list = list->next;
    }  

    /* poll */	
    if(polling_thread->fds != NULL){
#ifndef __APPLE__
      ppoll(polling_thread->fds,
	    g_list_length(polling_thread->poll_fd),
	    &timeout,
	    &sigmask);
#else
      poll(polling_thread->fds,
	   g_list_length(polling_thread->poll_fd),
	   timeout.tv_nsec / 1000);
#endif
    }

    /* post flag */
    list = polling_thread->poll_fd;

    while(list != NULL){
      if(AGS_POLL_FD(list->data)->delay_counter >= AGS_POLL_FD(list->data)->delay){
	position = ags_polling_thread_fd_position(polling_thread,
						  AGS_POLL_FD(list->data)->fd);

	if(position != -1){
	  if((POLLIN & (polling_thread->fds[position].revents)) != 0){
	    AGS_POLL_FD(list->data)->flags |= AGS_POLL_FD_INPUT;
	  }

	  if((POLLPRI & (polling_thread->fds[position].revents)) != 0){
	    AGS_POLL_FD(list->data)->flags |= AGS_POLL_FD_PRIORITY_INPUT;
	  }

	  if((POLLOUT & (polling_thread->fds[position].revents)) != 0){
	    AGS_POLL_FD(list->data)->flags |= AGS_POLL_FD_OUTPUT;
	  }

	  if((POLLHUP & (polling_thread->fds[position].revents)) != 0){
	    AGS_POLL_FD(list->data)->flags |= AGS_POLL_FD_HANG_UP;
	  }

	  /* do legacy */
	  if(AGS_POLL_FD(list->data)->poll_fd != NULL){
	    AGS_POLL_FD(list->data)->poll_fd->revents = polling_thread->fds[position].revents;
	  }

	  ags_poll_fd_dispatch(list->data);
      
	  AGS_POLL_FD(list->data)->flags &= (~(AGS_POLL_FD_INPUT |
					       AGS_POLL_FD_PRIORITY_INPUT |   
					       AGS_POLL_FD_OUTPUT |
					       AGS_POLL_FD_HANG_UP));
	  
	  AGS_POLL_FD(list->data)->delay_counter = 0.0;
	}else{
	  AGS_POLL_FD(list->data)->delay_counter += 1.0;
	}
      }
      
      list = list->next;
    }  
  }
  
  pthread_mutex_unlock(polling_thread->fd_mutex);
}
GNCSearchWindow *
gnc_ui_find_transactions_dialog_create2 (GNCLedgerDisplay2 * orig_ledg)
{
    QofIdType type = GNC_ID_SPLIT;
    struct _ftd_data *ftd;
    static GList *params = NULL;
    QofQuery *start_q, *show_q = NULL;
    gboolean num_action =
                qof_book_use_split_action_for_num_field(gnc_get_current_book());

    /* Build parameter list in reverse order */
    if (params == NULL)
    {
        params = gnc_search_param_prepend (params, N_("All Accounts"),
                                           ACCOUNT_MATCH_ALL_TYPE,
                                           type, SPLIT_TRANS, TRANS_SPLITLIST,
                                           SPLIT_ACCOUNT_GUID, NULL);
        params = gnc_search_param_prepend (params, N_("Account"), GNC_ID_ACCOUNT,
                                           type, SPLIT_ACCOUNT, QOF_PARAM_GUID,
                                           NULL);
        params = gnc_search_param_prepend (params, N_("Balanced"), NULL,
                                           type, SPLIT_TRANS, TRANS_IS_BALANCED,
                                           NULL);
        params = gnc_search_param_prepend (params, N_("Closing Entries"), NULL,
                                           type, SPLIT_TRANS, TRANS_IS_CLOSING,
                                           NULL);
        params = gnc_search_param_prepend (params, N_("Reconcile"), RECONCILED_MATCH_TYPE,
                                           type, SPLIT_RECONCILE, NULL);
        params = gnc_search_param_prepend (params, N_("Share Price"), NULL,
                                           type, SPLIT_SHARE_PRICE, NULL);
        params = gnc_search_param_prepend (params, N_("Shares"), NULL,
                                           type, SPLIT_AMOUNT, NULL);
        params = gnc_search_param_prepend (params, N_("Value"), NULL,
                                           type, SPLIT_VALUE, NULL);
        params = gnc_search_param_prepend (params, N_("Date Posted"), NULL,
                                           type, SPLIT_TRANS, TRANS_DATE_POSTED,
                                           NULL);
        params = gnc_search_param_prepend (params, (num_action
                                                    ? N_("Number/Action")
                                                    : N_("Action")), NULL,
                                           type, SPLIT_ACTION, NULL);
        params = gnc_search_param_prepend (params, (num_action
                                                    ? N_("Transaction Number")
                                                    : N_("Number")), NULL,
                                           type, SPLIT_TRANS, TRANS_NUM, NULL);
        {
            GList *params2 = NULL;
            params2 = gnc_search_param_prepend (params2, "", NULL,
                                               type, SPLIT_MEMO, NULL);
            params2 = gnc_search_param_prepend (params2, "", NULL,
                                               type, SPLIT_TRANS, TRANS_DESCRIPTION,
                                               NULL);
            params2 = gnc_search_param_prepend (params2, "", NULL,
                                               type, SPLIT_TRANS, TRANS_NOTES, NULL);
            params = gnc_search_param_prepend_compound (params, 
                                                        N_("Description, Notes, or Memo"),
                                                        params2,
                                                        GTK_JUSTIFY_LEFT, SEARCH_PARAM_ANY);
        }
        params = gnc_search_param_prepend (params, N_("Memo"), NULL,
                                           type, SPLIT_MEMO, NULL);
        params = gnc_search_param_prepend (params, N_("Notes"), NULL,
                                           type, SPLIT_TRANS, TRANS_NOTES, NULL);
        params = gnc_search_param_prepend (params, N_("Description"), NULL,
                                           type, SPLIT_TRANS, TRANS_DESCRIPTION,
                                           NULL);
    }
    else
    {
        GList *l;
        for (l = params; l; l = l->next)
        {
            GNCSearchParam *param = l->data;

            if (num_action)
            {
                if (strcmp (param->title, N_("Action")) == 0)
                    gnc_search_param_set_title (param, N_("Number/Action"));
                if (strcmp (param->title, N_("Number")) == 0)
                    gnc_search_param_set_title (param, N_("Transaction Number"));
            }
            else
            {
                if (strcmp (param->title, N_("Number/Action")) == 0)
                    gnc_search_param_set_title (param, N_("Action"));
                if (strcmp (param->title, N_("Transaction Number")) == 0)
                    gnc_search_param_set_title (param, N_("Number"));
            }
        }
    }

    ftd = g_new0 (struct _ftd_data, 1);

    if (orig_ledg)
    {
        ftd->ledger_q = gnc_ledger_display2_get_query (orig_ledg);
        start_q = show_q = qof_query_copy (ftd->ledger_q);
    }
    else
    {
        start_q = qof_query_create ();
        qof_query_set_book (start_q, gnc_get_current_book ());

        /* In lieu of not "mis-using" some portion of the infrastructure by writing
         * a bunch of new code, we just filter out the accounts of the template
         * transactions.  While these are in a seperate Account trees just for this
         * reason, the query engine makes no distinction between Account trees.
         * See Gnome Bug 86302.
         * 	-- jsled
         *
         * copied from gnc-ledger-display2.c:gnc_ledger_display2_gl()  -- warlord
         *
         * <jsled> Alternatively, you could look for a GNC_SX_ACCOUNT [SchedAction.h]
         * key in the KVP frame of the split.
         */
        {
            Account *tRoot;
            GList *al;

            tRoot = gnc_book_get_template_root( gnc_get_current_book() );
            al = gnc_account_get_descendants( tRoot );

            if (g_list_length(al) != 0)
                xaccQueryAddAccountMatch( start_q, al, QOF_GUID_MATCH_NONE, QOF_QUERY_AND );

            g_list_free (al);
            al = NULL;
            tRoot = NULL;
        }

        ftd->q = start_q;		/* save this to destroy it later */
    }

    ftd->sw = gnc_search_dialog_create (type, _("Find Transaction"),
                                        params, NULL, start_q, show_q,
                                        NULL, do_find_cb, NULL,
                                        ftd, free_ftd_cb, GNC_PREFS_GROUP_SEARCH, NULL);

    if (!ftd->sw)
    {
        free_ftd_cb (ftd);
        return NULL;
    }

    return ftd->sw;
}
Exemple #3
0
void
pseudo_tcp_socket_notify_clock(PseudoTcpSocket *self)
{
  PseudoTcpSocketPrivate *priv = self->priv;
  guint32 now = get_current_time ();

  if (priv->state == TCP_CLOSED)
    return;

  // Check if it's time to retransmit a segment
  if (priv->rto_base &&
      (time_diff(priv->rto_base + priv->rx_rto, now) <= 0)) {
    if (g_list_length (priv->slist) == 0) {
      g_assert_not_reached ();
    } else {
      // Note: (priv->slist.front().xmit == 0)) {
      // retransmit segments
      guint32 nInFlight;
      guint32 rto_limit;

      DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "timeout retransmit (rto: %d) "
          "(rto_base: %d) (now: %d) (dup_acks: %d)",
          priv->rx_rto, priv->rto_base, now, (guint) priv->dup_acks);

      if (!transmit(self, priv->slist, now)) {
        closedown(self, ECONNABORTED);
        return;
      }

      nInFlight = priv->snd_nxt - priv->snd_una;
      priv->ssthresh = max(nInFlight / 2, 2 * priv->mss);
      //LOG(LS_INFO) << "priv->ssthresh: " << priv->ssthresh << "  nInFlight: " << nInFlight << "  priv->mss: " << priv->mss;
      priv->cwnd = priv->mss;

      // Back off retransmit timer.  Note: the limit is lower when connecting.
      rto_limit = (priv->state < TCP_ESTABLISHED) ? DEF_RTO : MAX_RTO;
      priv->rx_rto = min(rto_limit, priv->rx_rto * 2);
      priv->rto_base = now;
    }
  }

  // Check if it's time to probe closed windows
  if ((priv->snd_wnd == 0)
        && (time_diff(priv->lastsend + priv->rx_rto, now) <= 0)) {
    if (time_diff(now, priv->lastrecv) >= 15000) {
      closedown(self, ECONNABORTED);
      return;
    }

    // probe the window
    packet(self, priv->snd_nxt - 1, 0, 0, 0);
    priv->lastsend = now;

    // back off retransmit timer
    priv->rx_rto = min(MAX_RTO, priv->rx_rto * 2);
  }

  // Check if it's time to send delayed acks
  if (priv->t_ack && (time_diff(priv->t_ack + ACK_DELAY, now) <= 0)) {
    packet(self, priv->snd_nxt, 0, 0, 0);
  }

}
Exemple #4
0
/* functions */
GtkWidget *
gmdb_table_data_new(MdbCatalogEntry *entry)
{
MdbTableDef *table;
MdbColumn *col;
GtkWidget *clist;
GtkWidget *scroll;
int i, rownum;
long row, maxrow;
gchar *bound_data[256];
GMdbDataWindow *dataw = NULL;


	/* do we have an active window for this object? if so raise it */
	for (i=0;i<g_list_length(window_list);i++) {
		dataw = g_list_nth_data(window_list, i);
		if (!strcmp(dataw->table_name, entry->object_name)) {
			gdk_window_raise (dataw->window->window);
			return dataw->window;
		}
	}

	dataw = g_malloc(sizeof(GMdbDataWindow));
	strcpy(dataw->table_name, entry->object_name);

	dataw->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);	
	gtk_window_set_title(GTK_WINDOW(dataw->window), entry->object_name);
	gtk_widget_set_usize(dataw->window, 300,200);
	gtk_widget_set_uposition(dataw->window, 50,50);
	gtk_widget_show(dataw->window);

    gtk_signal_connect (GTK_OBJECT (dataw->window), "delete_event",
        GTK_SIGNAL_FUNC (gmdb_table_data_close), dataw);


	scroll = gtk_scrolled_window_new(NULL,NULL);
	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scroll),
		GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	gtk_widget_show (scroll);
	gtk_container_add(GTK_CONTAINER(dataw->window), scroll);

	/* read table */
	table = mdb_read_table(entry);
	mdb_read_columns(table);
	mdb_rewind_table(table);

	clist = gtk_clist_new(table->num_cols);
	gtk_widget_show(clist);
	gtk_container_add(GTK_CONTAINER(scroll),clist);

	for (i=0;i<table->num_cols;i++) {
		/* bind columns */
		bound_data[i] = (char *) g_malloc0(MDB_BIND_SIZE);
		mdb_bind_column(table, i+1, bound_data[i], NULL);

		/* display column titles */
		col=g_ptr_array_index(table->columns,i);
		gtk_clist_set_column_title(GTK_CLIST(clist), i, col->name);
	}
	gtk_clist_column_titles_show(GTK_CLIST(clist));

	maxrow = gmdb_prefs_get_maxrows();

	/* fetch those rows! */
	row = 0;
	while(mdb_fetch_row(table) && 
			(!maxrow || (row < maxrow))) {
		row++;
		rownum = gtk_clist_append(GTK_CLIST(clist), bound_data);
	}

	/* free the memory used to bind */
	for (i=0;i<table->num_cols;i++) {
		g_free(bound_data[i]);
	}

	/* add this one to the window list */
	window_list = g_list_append(window_list, dataw);

	return dataw->window;
}
Exemple #5
0
/* This updates the box size to the given value, adding placeholders or
   deleting widgets as necessary. */
void
gb_box_set_size (GtkWidget * widget, gint size)
{
  GtkWidget *new_child;
  gint current_size = g_list_length (GTK_BOX (widget)->children);
  gint i;

  if (current_size < size)
    {
      /* This avoids any problems with redrawing the selection. */
      editor_clear_selection (NULL);

      for (i = 0; i < size - current_size; i++)
	{
	  if (GTK_IS_BUTTON_BOX (widget))
	    {
	      new_child = gb_widget_new ("GtkButton", widget);
	      GTK_WIDGET_SET_FLAGS (new_child, GTK_CAN_DEFAULT);
	      gtk_box_pack_start (GTK_BOX (widget), new_child, TRUE, TRUE, 0);
	      tree_add_widget (new_child);
	    }
	  else
	    {
	      new_child = editor_new_placeholder ();
	      gtk_box_pack_start (GTK_BOX (widget), new_child, TRUE, TRUE, 0);
	    }
	}
    }
  else if (current_size > size)
    {
      GList *children, *elem;
      GtkWidget *child;
      gchar *error = NULL;

      /* Get a list of children in the order they appear in the box, start at
	 the end and move backwards until we find a widget that can be
	 destroyed. If we can't find any, show a message box. */
      children = gtk_container_get_children (GTK_CONTAINER (widget));
      elem = g_list_last (children);

      while (elem)
	{
	  child = elem->data;
	  error = editor_can_delete_widget (child);
	  if (!error)
	    {
	      gtk_container_remove (GTK_CONTAINER (widget), child);
	      current_size--;
	      if (current_size == size)
		break;
	    }
	  elem = elem->prev;
	}

      g_list_free (children);

      if (current_size > size)
	{
	  glade_util_show_message_box (error ? error
				       : _("Can't delete any children."),
				       widget);
	}
    }
}
Exemple #6
0
static void
gimp_align_tool_align (GimpAlignTool     *align_tool,
                       GimpAlignmentType  align_type)
{
  GimpAlignOptions *options = GIMP_ALIGN_TOOL_GET_OPTIONS (align_tool);
  GimpImage        *image;
  GObject          *reference_object = NULL;
  GList            *list;
  gint              offset = 0;

  /* if nothing is selected, just return */
  if (! align_tool->selected_objects)
    return;

  image  = gimp_display_get_image (GIMP_TOOL (align_tool)->display);

  switch (align_type)
    {
    case GIMP_ALIGN_LEFT:
    case GIMP_ALIGN_HCENTER:
    case GIMP_ALIGN_RIGHT:
    case GIMP_ALIGN_TOP:
    case GIMP_ALIGN_VCENTER:
    case GIMP_ALIGN_BOTTOM:
      offset = 0;
      break;

    case GIMP_ARRANGE_LEFT:
    case GIMP_ARRANGE_HCENTER:
    case GIMP_ARRANGE_RIGHT:
    case GIMP_ARRANGE_HFILL:
      offset = options->offset_x;
      break;

    case GIMP_ARRANGE_TOP:
    case GIMP_ARRANGE_VCENTER:
    case GIMP_ARRANGE_BOTTOM:
    case GIMP_ARRANGE_VFILL:
      offset = options->offset_y;
      break;
    }

  /* if only one object is selected, use the image as reference
   * if multiple objects are selected, use the first one as reference if
   * "set_reference" is TRUE, otherwise use NULL.
   */

  list = align_tool->selected_objects;

  switch (options->align_reference)
    {
    case GIMP_ALIGN_REFERENCE_IMAGE:
      reference_object = G_OBJECT (image);
      break;

    case GIMP_ALIGN_REFERENCE_FIRST:
      if (g_list_length (list) == 1)
        {
          reference_object = G_OBJECT (image);
        }
      else
        {
          if (align_tool->set_reference)
            {
              reference_object = G_OBJECT (list->data);
              list = g_list_next (list);
            }
          else
            {
              reference_object = NULL;
            }
        }
      break;

    case GIMP_ALIGN_REFERENCE_SELECTION:
      reference_object = G_OBJECT (gimp_image_get_mask (image));
      break;

    case GIMP_ALIGN_REFERENCE_ACTIVE_LAYER:
      reference_object = G_OBJECT (gimp_image_get_active_layer (image));
      break;

    case GIMP_ALIGN_REFERENCE_ACTIVE_CHANNEL:
      reference_object = G_OBJECT (gimp_image_get_active_channel (image));
      break;

    case GIMP_ALIGN_REFERENCE_ACTIVE_PATH:
      reference_object = G_OBJECT (gimp_image_get_active_vectors (image));
      break;
    }

  if (! reference_object)
    return;

  gimp_draw_tool_pause (GIMP_DRAW_TOOL (align_tool));

  gimp_image_arrange_objects (image, list,
                              align_type,
                              reference_object,
                              align_type,
                              offset);

  gimp_draw_tool_resume (GIMP_DRAW_TOOL (align_tool));

  gimp_image_flush (image);
}
Exemple #7
0
int main (int argc, char *argv[])
{
  int i;
  GError *gerror = NULL;
  GdkColor color;
  plugin_t *plugin;
  
  gtk_init (&argc, &argv);

  ask_language();

  /* Create a new assistant widget with no pages. */
  assistant = gtk_assistant_new ();
  gtk_widget_set_size_request (assistant, 800, 600);
  //gtk_window_unfullscreen (GTK_WINDOW (assistant));
  gtk_window_set_title (GTK_WINDOW (assistant), _("Fwife : Frugalware Installer Front-End"));

  /* Connect signals with functions */
  g_signal_connect (G_OBJECT (assistant), "destroy", G_CALLBACK (cancel_install), NULL);
  g_signal_connect (G_OBJECT (assistant), "cancel", G_CALLBACK (cancel_install), NULL);
  g_signal_connect (G_OBJECT (assistant), "close", G_CALLBACK (close_install), NULL);

  /* Some trick to connect buttons with plugin move functions */
  g_signal_connect(G_OBJECT(((GtkAssistant *) assistant)->forward), "clicked", G_CALLBACK(plugin_next), NULL);
  g_signal_connect(G_OBJECT(((GtkAssistant *) assistant)->back), "clicked", G_CALLBACK(plugin_previous), NULL);

  // Remove useless button and add usefull one
  gtk_assistant_remove_action_widget(GTK_ASSISTANT(assistant), (GtkWidget*)(((GtkAssistant *) assistant)->last));
  GtkWidget *help = gtk_button_new_from_stock(GTK_STOCK_HELP);
  gtk_widget_show(help);
  g_signal_connect (G_OBJECT (help), "clicked", G_CALLBACK (show_help), NULL);
  gtk_assistant_add_action_widget(GTK_ASSISTANT(assistant), help);
  /* Load a nice image */
  GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file (g_strdup_printf("%s/headlogo.png", IMAGEDIR), &gerror);
  if(!pixbuf) {
       fprintf(stdout, "error message: %s\n", gerror->message);
  }

  /* Set it as icon window */
  gtk_window_set_icon(GTK_WINDOW (assistant),pixbuf);

  /* Make ugly colors ;) */
  gdk_color_parse ("#94b6db", &color);
  gtk_widget_modify_bg (assistant, GTK_STATE_SELECTED, &color);
  /*gdk_color_parse ("black", &color);
  gtk_widget_modify_fg (assistant, GTK_STATE_SELECTED, &color);*/


  /* Load plugins.... */
  fwife_load_plugins(PLUGINDIR);

  plugin_list = g_list_sort(plugin_list, sort_plugins);

  /*Allocate memory for stocking pages */
  MALLOC(pages, sizeof(PageInfo)*g_list_length(plugin_list));

  //* Initializing pages... *//
  for(i=0; i<g_list_length(plugin_list); i++)
  {
      if ((plugin = g_list_nth_data(plugin_list, i)) == NULL)
        LOG("Error when loading plugins...\n");
      else
        LOG("Loading plugin : %s\n", plugin->name);

      pages[i] = (PageInfo) {NULL, -1, GET_UTF8(plugin->desc()), plugin->type, plugin->complete};

      if ((pages[i].widget = plugin->load_gtk_widget()) == NULL)
       { LOG("Error when loading plugin's widget @ %s\n", plugin->name); }

      pages[i].index = gtk_assistant_append_page (GTK_ASSISTANT (assistant), pages[i].widget);
      gtk_assistant_set_page_title (GTK_ASSISTANT (assistant), pages[i].widget, pages[i].title);
      gtk_assistant_set_page_type (GTK_ASSISTANT (assistant), pages[i].widget, pages[i].type);
      gtk_assistant_set_page_complete (GTK_ASSISTANT (assistant), pages[i].widget, pages[i].complete);
      gtk_assistant_set_page_header_image(GTK_ASSISTANT (assistant), pages[i].widget,pixbuf);
  }

  //* Begin with first plugin *//
  plugin_active = g_list_nth_data(plugin_list, 0);

  gtk_widget_show_all (assistant);
  // begin event loop
  gtk_main ();
  return 0;
}
int osync_format_env_num_filters(OSyncFormatEnv *env)
{
  osync_assert(env);
  return g_list_length(env->custom_filters);
}
Exemple #9
0
static void
gdl_dock_object_real_reduce (GdlDockObject *object)
{
    GdlDockObject *parent;
    GList         *children;
    
    g_return_if_fail (object != NULL);

    if (!gdl_dock_object_is_compound (object))
        return;

    parent = gdl_dock_object_get_parent_object (object);
    children = gtk_container_get_children (GTK_CONTAINER (object));
    if (g_list_length (children) <= 1) {
        GList *l;
        GList *dchildren = NULL;
        
        /* detach ourselves and then re-attach our children to our
           current parent.  if we are not currently attached, the
           children are detached */
        if (parent)
            gdl_dock_object_freeze (parent);
        gdl_dock_object_freeze (object);
        /* Detach the children before detaching this object, since in this
         * way the children can have access to the whole object hierarchy.
         * Set the InDetach flag now, so the children know that this object
         * is going to be detached. */
        
        
        GDL_DOCK_OBJECT_SET_FLAGS (object, GDL_DOCK_IN_DETACH);
        
        for (l = children; l; l = l->next) {
            GdlDockObject *child;
            
            if (!GDL_IS_DOCK_OBJECT (l->data))
                continue;
            
            child = GDL_DOCK_OBJECT (l->data);

            g_object_ref (child);
            gdl_dock_object_detach (child, FALSE);
            GDL_DOCK_OBJECT_SET_FLAGS (child, GDL_DOCK_IN_REFLOW);
            if (parent)
                dchildren = g_list_append (dchildren, child);
            GDL_DOCK_OBJECT_UNSET_FLAGS (child, GDL_DOCK_IN_REFLOW);
        }
        /* Now it can be detached */
        gdl_dock_object_detach (object, FALSE);
        
        /* After detaching the reduced object, we can add the
        children (the only child in fact) to the new parent */
        for (l = dchildren; l; l = l->next) {
            gtk_container_add (GTK_CONTAINER (parent), l->data);
            g_object_unref (l->data);
        }
        g_list_free (dchildren);
        
        
        /* sink the widget, so any automatic floating widget is destroyed */
        g_object_ref_sink (object);
        /* don't reenter */
        object->reduce_pending = FALSE;
        gdl_dock_object_thaw (object);
        if (parent)
            gdl_dock_object_thaw (parent);
    }
    g_list_free (children);
}
static OSyncFormatConverterPath *osync_format_env_find_path_fn(OSyncFormatEnv *env, OSyncData *sourcedata, OSyncPathTargetFn target_fn, OSyncTargetLastConverterFn last_converter_fn, const void *fndata, const char * preferred_format, OSyncError **error)
{
  OSyncFormatConverterPath *path = NULL;
  OSyncFormatConverterTree *tree = NULL;
  OSyncFormatConverterPathVertice *begin = NULL;
  OSyncFormatConverterPathVertice *result = NULL;
  OSyncFormatConverterPathVertice *neighbour = NULL;
  GList *e, *v;
  guint vertice_id = 0;
	
  osync_trace(TRACE_ENTRY, "%s(%p, %p, %p, %p, %p)", __func__, env, sourcedata, target_fn, fndata, error);
  osync_assert(env);
  osync_assert(sourcedata);
  osync_assert(target_fn);
	
  //Vertice = Spitze = Format
  //edge = Kante = Converter

  /* Optimization: check if the format is already valid */
  if (target_fn(fndata, osync_data_get_objformat(sourcedata))) {
    path = osync_converter_path_new(error);
    if (!path)
      goto error;
		
    osync_trace(TRACE_EXIT, "%s: Target already valid", __func__);
    return path;
  }

  /* Make a new search tree */
  tree = osync_try_malloc0(sizeof(OSyncFormatConverterTree), error);
  if (!tree)
    goto error;
  tree->unused = g_list_copy(env->converters);
	
  /* We make our starting point (which is the current format of the 
   * change of course */
  begin = osync_format_converter_path_vertice_new(error);
  if (!begin)
    goto error_free_tree;
	
  begin->format = osync_data_get_objformat(sourcedata);
  begin->path = NULL;
  begin->id = vertice_id;
  begin->neighbour_id = 0;
	
  tree->search = g_list_append(NULL, begin);
	
  /* While there are still vertices in our
   * search queue */
  while (g_list_length(tree->search)) {
    /* log current tree search list */
    GString *string = g_string_new("");
    guint size = g_list_length(tree->search);
    guint count = 0;
    guint neighbour_id = 0;
    OSyncFormatConverterPathVertice *current = NULL;
    OSyncFormatConverterPath *path_tmp = NULL;
    for (v = tree->search; v; v = v->next) {
      OSyncFormatConverterPathVertice *vertice = v->data;
      GString *string2 = g_string_new("");
      guint size2 = g_list_length(vertice->path);
      guint count2 = 0;
      count ++;
      for (e = vertice->path; e; e = e->next) {
        OSyncFormatConverter *edge = e->data;
        count2 ++;
        if (count2 == 1) {
          g_string_append(string2, osync_objformat_get_name(osync_converter_get_sourceformat(edge)));
          g_string_append(string2, " -> ");
        }
        g_string_append(string2, osync_objformat_get_name(osync_converter_get_targetformat(edge)));
        if (size2 > 1 && count2 < size2)
          g_string_append(string2, " -> ");
      }
      g_string_append(string, osync_objformat_get_name(vertice->format));
      g_string_append(string, " ( ");
      g_string_append(string, string2->str);
      g_string_append(string, " ) ");

      g_string_free(string2, TRUE);

      if (size > 1 && count < size)
        g_string_append(string, " -> ");
    }
    osync_trace(TRACE_INTERNAL, "Tree : %s", string->str);
    g_string_free(string, TRUE);

    /* Get the first OSyncFormatConverterPathVertice from the search queue
     * and remove it from the queue */
    current = tree->search->data;
    tree->search = g_list_remove(tree->search, current);
		
    /* log current OSyncFormatConverterPathVertice */
    string = g_string_new("");
    size = g_list_length(current->path);
    count = 0;
    for (e = current->path; e; e = e->next) {
      OSyncFormatConverter *edge = e->data;
      count ++;
      if (count == 1) {
        g_string_append(string, osync_objformat_get_name(osync_converter_get_sourceformat(edge)));
        g_string_append(string, " -> ");
      }
      g_string_append(string, osync_objformat_get_name(osync_converter_get_targetformat(edge)));
      if (size > 1 && count < size)
        g_string_append(string, " -> ");
    }
    osync_trace(TRACE_INTERNAL, "Next vertice : %s (%s).", osync_objformat_get_name(current->format), string->str);
    g_string_free(string, TRUE);

    current->neighbour_id = 0;
    vertice_id++; // current OSyncFormatConverterPathVertice id for its neighbours

    /* Check if we have reached a target format */
    if (target_fn(fndata, current->format)) {
      osync_trace(TRACE_INTERNAL, "Target %s found", osync_objformat_get_name(current->format));
      /* Done. return the result */
      result = current;
      break;
    }
		
    /*
     * Optimizations : 
     */
    if (last_converter_fn(fndata, tree)) {
      osync_trace(TRACE_INTERNAL, "Last converter for target format reached: %s.", (result)?osync_objformat_get_name(result->format):"null");
      osync_format_converter_path_vertice_unref(current);
      break;
    }
    /* Check if saved result is equal to current regarding losses, objtype_changes
     * and conversions. If yes, we can skip further searches and break here */
    if (result) {
      if (result->losses <= current->losses && result->objtype_changes <= current->objtype_changes && result->conversions <= current->conversions) {
        osync_trace(TRACE_INTERNAL, "Target %s found in queue", osync_objformat_get_name(result->format));
        tree->search = g_list_remove(tree->search, result);
        break;
      } else {
        result = NULL;
      }
    }


    /*
     * If we dont have reached a target, we look at our neighbours 
     */
    osync_trace(TRACE_INTERNAL, "Looking at %s's neighbours.", osync_objformat_get_name(current->format));

    /* Convert the "current" data to the last edge found in the "current" conversion path  */
    current->data = osync_data_clone(sourcedata, error);
    path_tmp = osync_converter_path_new(error);
    if (!path_tmp)
      goto error;
    for (e = current->path; e; e = e->next) {
      OSyncFormatConverter *edge = e->data;
      osync_converter_path_add_edge(path_tmp, edge);
    }
    if (!(osync_format_env_convert(env, path_tmp, current->data, error))) {
      osync_trace(TRACE_INTERNAL, "osync format env convert on this path failed - skipping the conversion");
      continue;
    }
    osync_converter_path_unref(path_tmp);

    /* Find all the neighboors or "current" at its current conversion point */
    while ((neighbour = osync_format_converter_path_vertice_get_next_vertice_neighbour(env, tree, current, error))) {
      GString *string = g_string_new("");
      guint size = g_list_length(neighbour->path);
      guint count = 0;

      neighbour->id = vertice_id;
      neighbour_id++;
      neighbour->neighbour_id = neighbour_id;

      neighbour->preferred = FALSE;
      if (current->preferred)	  /* preferred is inherited by the neighbours */
        neighbour->preferred = TRUE;
      if(preferred_format && !strcmp(preferred_format, osync_objformat_get_name(neighbour->format)))
        neighbour->preferred = TRUE;

      /* log neighbour to be added to the tree search list */
      for (e = neighbour->path; e; e = e->next) {
        OSyncFormatConverter *edge = e->data;
        count ++;
        if (count == 1) {
          g_string_append(string, osync_objformat_get_name(osync_converter_get_sourceformat(edge)));
          g_string_append(string, " -> ");
        }
        g_string_append(string, osync_objformat_get_name(osync_converter_get_targetformat(edge)));
        if (size > 1 && count < size)
          g_string_append(string, " -> ");
      }
      osync_trace(TRACE_INTERNAL, "%s's neighbour : %s (%s)", osync_objformat_get_name(current->format), osync_objformat_get_name(neighbour->format), string->str);
      g_string_free(string, TRUE);

      /* We found a neighbour and insert it sorted in our search queue 
         If vertices are equals in losses, objtypes and conversions, first registered is inserted before the others 
         in the same OSyncFormatConverterPathVertice group (vertice_id) */
      tree->search = g_list_insert_sorted(tree->search, neighbour, osync_format_converter_path_vertice_compare_distance); 

      /* Optimization:
       * We found a possible target. Save it. */
      if (target_fn(fndata, neighbour->format)) {
        osync_trace(TRACE_INTERNAL, "Possible target found.");
        result = neighbour;
        osync_format_converter_path_vertice_ref(result);
      }
    }

    if (osync_error_is_set(error))
      goto error_free_tree;
		
    /* Done, drop the reference to the OSyncFormatConverterPathVertice */
    osync_format_converter_path_vertice_unref(current);
  }
			
  if (!result) {
    osync_error_set(error, OSYNC_ERROR_GENERIC, "Unable to find conversion path");
    goto error_free_tree;
  }
	
  /* Found it. Create a path object */
  path = osync_converter_path_new(error);
  if (!path)
    goto error;
	
  for (e = result->path; e; e = e->next) {
    OSyncFormatConverter *edge = e->data;
    osync_converter_path_add_edge(path, edge);
  }
	
  /* Drop the reference to the result OSyncFormatConverterPathVertice */
  osync_format_converter_path_vertice_unref(result);
	
  /* Free the tree */
  osync_converter_tree_free(tree);
	
  osync_trace(TRACE_EXIT, "%s: %p", __func__, path);
  return path;

 error_free_tree:
  osync_converter_tree_free(tree);
 error:
  osync_trace(TRACE_EXIT_ERROR, "%s: %s", __func__, osync_error_print(error));
  return NULL;
}
int osync_format_env_num_objformats(OSyncFormatEnv *env)
{
  osync_assert(env);
  return g_list_length(env->objformats);
}
Exemple #12
0
G_MODULE_EXPORT gboolean
display_show(NOTIFICATION_INFO* ni) {
  GdkColor color;
  GtkWidget* vbox;
  GtkWidget* hbox;
  GtkWidget* label;
  GtkWidget* image;
  GdkScreen* screen;
  gint n, pos, len;
  gint x, y;
  gint monitor_num;
  GdkRectangle rect;

  DISPLAY_INFO* di = g_new0(DISPLAY_INFO, 1);
  if (!di) {
    perror("g_new0");
    return FALSE;
  }
  di->ni = ni;

  len = g_list_length(notifications);
  for (pos = 0; pos < len; pos++) {
    DISPLAY_INFO* p = g_list_nth_data(notifications, pos);
    if (pos != p->pos) break;
  }

  screen = gdk_screen_get_default();
  monitor_num = gdk_screen_get_primary_monitor(screen);
  gdk_screen_get_monitor_geometry(screen, monitor_num, &rect);

  x = rect.x + rect.width - 250;
  y = rect.y + rect.height - 110;
  for (n = 0; n < pos; n++) {
    y -= 110;
    if (y < 0) {
      x -= 250;
      if (x < 0) {
        return FALSE;
      }
      y = rect.y + rect.height - 110;
    }
  }

  di->pos = pos;
  notifications = g_list_insert_sorted(notifications, di, notifications_compare);
  di->x = x;
  di->y = y;

  di->popup = gtk_window_new(GTK_WINDOW_POPUP);
  gtk_window_set_title(GTK_WINDOW(di->popup), "growl-for-linux");
  gtk_window_set_resizable(GTK_WINDOW(di->popup), FALSE);
  gtk_window_set_decorated(GTK_WINDOW(di->popup), FALSE);
  gtk_window_set_keep_above(GTK_WINDOW(di->popup), TRUE);

  gtk_window_stick(GTK_WINDOW(di->popup));

  vbox = gtk_vbox_new(FALSE, 5);
  gtk_container_set_border_width(GTK_CONTAINER(vbox), 18);
  gtk_container_add(GTK_CONTAINER(di->popup), vbox);

  hbox = gtk_hbox_new(FALSE, 5);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0);

  if (di->ni->icon && *di->ni->icon) {
    GdkPixbuf* pixbuf;
    if (di->ni->local) {
      gchar* newurl = g_filename_from_uri(di->ni->icon, NULL, NULL);
      GError* error = NULL;
      pixbuf = gdk_pixbuf_new_from_file(newurl ? newurl : di->ni->icon, &error);
      if (newurl) g_free(newurl);
    } else
      pixbuf = url2pixbuf(di->ni->icon, NULL);
    if (pixbuf) {
      GdkPixbuf* tmp = gdk_pixbuf_scale_simple(pixbuf, 32, 32, GDK_INTERP_TILES);
      if (tmp) {
        g_object_unref(pixbuf);
        pixbuf = tmp;
      }
      image = gtk_image_new_from_pixbuf(pixbuf);
      gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0);
      g_object_unref(pixbuf);
    }
  }

  PangoFontDescription* font_desc;
  
  font_desc = pango_font_description_new();
  pango_font_description_set_family(font_desc, "Sans");
  pango_font_description_set_size(font_desc, 12 * PANGO_SCALE);

  label = gtk_label_new(di->ni->title);
  gdk_color_parse("white", &color);
  gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &color);
  gtk_widget_modify_font(label, font_desc);
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  pango_font_description_free(font_desc);

  font_desc = pango_font_description_new();
  pango_font_description_set_family(font_desc, "Sans");
  pango_font_description_set_size(font_desc, 8 * PANGO_SCALE);

  label = gtk_label_new(di->ni->text);
  gdk_color_parse("white", &color);
  gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &color);
  gtk_widget_modify_font(label, font_desc);
  g_signal_connect(G_OBJECT(label), "size-allocate", G_CALLBACK(label_size_allocate), NULL);
  gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT);
  gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
  gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_CHAR);
  gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, FALSE, 0);

  pango_font_description_free(font_desc);

  gtk_widget_set_events(di->popup, GDK_BUTTON_PRESS_MASK);
  g_signal_connect(G_OBJECT(di->popup), "button-press-event", G_CALLBACK(display_clicked), di);

  di->offset = 0;
  di->timeout = 500;

  gtk_window_move(GTK_WINDOW(di->popup), di->x, di->y);
  gtk_window_set_opacity(GTK_WINDOW(di->popup), 0);
  gtk_widget_set_app_paintable(di->popup, TRUE);
  gtk_widget_show_all(di->popup);

  if (pixmap == NULL) {
     pixmap = gdk_pixmap_create_from_xpm_d(di->popup->window, &bitmap, NULL, balloon);
  }
  gdk_drawable_get_size(pixmap, &pixmap_width, &pixmap_height);
  gtk_widget_set_size_request(di->popup, pixmap_width, pixmap_height);
  gdk_window_shape_combine_mask(di->popup->window, bitmap, 0, 0);
  g_signal_connect(G_OBJECT(di->popup), "expose-event", G_CALLBACK(display_expose), di);

  g_timeout_add(10, display_animation_func, di);

  return FALSE;
}
Exemple #13
0
void wxMDIParentFrame::OnInternalIdle()
{
    /* if a MDI child window has just been inserted
       it has to be brought to the top in idle time. we
       simply set the last notebook page active as new
       pages can only be appended at the end */

    if (m_justInserted)
    {
        GtkNotebook *notebook = GTK_NOTEBOOK(m_clientWindow->m_widget);
        gtk_notebook_set_current_page( notebook, g_list_length( notebook->children ) - 1 );

        /* need to set the menubar of the child */
        wxMDIChildFrame *active_child_frame = GetActiveChild();
        if (active_child_frame != NULL)
        {
            wxMenuBar *menu_bar = active_child_frame->m_menuBar;
            if (menu_bar)
            {
                menu_bar->Attach(active_child_frame);
            }
        }
        m_justInserted = false;
        return;
    }

    wxFrame::OnInternalIdle();

    wxMDIChildFrame *active_child_frame = GetActiveChild();
    bool visible_child_menu = false;

    wxWindowList::compatibility_iterator node = m_clientWindow->GetChildren().GetFirst();
    while (node)
    {
        wxMDIChildFrame *child_frame = wxDynamicCast( node->GetData(), wxMDIChildFrame );

        if ( child_frame )
        {
            wxMenuBar *menu_bar = child_frame->m_menuBar;
            if ( menu_bar )
            {
                if (child_frame == active_child_frame)
                {
                    if (menu_bar->Show(true))
                    {
                        // Attach() asserts if we call it for an already
                        // attached menu bar so don't do it if we're already
                        // associated with this frame (it would be nice to get
                        // rid of this check and ensure that this doesn't
                        // happen...)
                        if ( menu_bar->GetFrame() != child_frame )
                            menu_bar->Attach( child_frame );
                    }
                    visible_child_menu = true;
                }
                else
                {
                    if (menu_bar->Show(false))
                    {
                        menu_bar->Detach();
                    }
                }
            }
        }

        node = node->GetNext();
    }

    /* show/hide parent menu bar as required */
    if ((m_frameMenuBar) &&
        (m_frameMenuBar->IsShown() == visible_child_menu))
    {
        if (visible_child_menu)
        {
            m_frameMenuBar->Show( false );
            m_frameMenuBar->Detach();
        }
        else
        {
            m_frameMenuBar->Show( true );
            m_frameMenuBar->Attach( this );
        }
    }
}
int
main( int argc, char** argv )
{
	static const gchar *thisfn = "caja_actions_run_main";
	int status = EXIT_SUCCESS;
	GOptionContext *context;
	GError *error = NULL;
	gchar *help;
	gint errors;
	NAObjectAction *action;
	NAObjectProfile *profile;
	GList *targets;

	g_type_init();
	setlocale( LC_ALL, "" );
	console_init_log_handler();

	/* pwi 2011-01-05
	 * run MateConf migration tools before doing anything else
	 * above all before allocating a new NAPivot
	 */
	na_mateconf_migration_run();

	context = init_options();

	if( argc == 1 ){
		g_set_prgname( argv[0] );
		help = g_option_context_get_help( context, FALSE, NULL );
		g_print( "\n%s", help );
		g_free( help );
		exit( status );
	}

	if( !g_option_context_parse( context, &argc, &argv, &error )){
		g_printerr( _( "Syntax error: %s\n" ), error->message );
		g_error_free (error);
		exit_with_usage();
	}

	g_option_context_free( context );

	if( version ){
		na_core_utils_print_version();
		exit( status );
	}

	errors = 0;

	if( !id || !strlen( id )){
		g_printerr( _( "Error: action id is mandatory.\n" ));
		errors += 1;
	}

	action = get_action( id );
	if( !action ){
		errors += 1;
	} else {
		g_debug( "%s: action %s have been found, and is enabled and valid", thisfn, id );
	}

	if( errors ){
		exit_with_usage();
	}

	if( targets_array ){
		targets = targets_from_commandline();

	} else {
		targets = targets_from_selection();
	}

	dump_targets( targets );

	if( g_list_length( targets ) == 0 ){
		g_print( _( "No current selection. Nothing to do. Exiting.\n" ));
		exit( status );
	}

	if( !na_icontext_is_candidate( NA_ICONTEXT( action ), ITEM_TARGET_ANY, targets )){
		g_printerr( _( "Action %s is not a valid candidate. Exiting.\n" ), id );
		exit( status );
	}

	profile = get_profile_for_targets( action, targets );
	if( !profile ){
		g_print( _( "No valid profile is candidate to execution. Exiting.\n" ));
		exit( status );
	}
	g_debug( "%s: profile %p found", thisfn, ( void * ) profile );

	execute_action( action, profile, targets );

	na_selected_info_free_list( targets );
	exit( status );
}
Exemple #15
0
int main(int argc, char **argv)
{
    abrt_init(argv);

    /* I18n */
    setlocale(LC_ALL, "");
#if ENABLE_NLS
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);
#endif

    const char *program_usage_string = _(
        "\n& [-vf] [-c CONFFILE]... [-F FMTFILE] [-A FMTFILE2] -d DIR"
        "\nor:"
        "\n& [-v] [-c CONFFILE]... [-d DIR] -t[ID] FILE..."
        "\nor:"
        "\n& [-v] [-c CONFFILE]... [-d DIR] -t[ID] -w"
        "\nor:"
        "\n& [-v] [-c CONFFILE]... -h DUPHASH"
        "\n"
        "\nReports problem to MantisBT."
        "\n"
        "\nThe tool reads DIR. Then it tries to find an issue"
        "\nwith the same abrt_hash in custom field 'abrt_hash'."
        "\n"
        "\nIf such issue is not found, then a new issue is created. Elements of DIR"
        "\nare stored in the issue as part of issue description or as attachments,"
        "\ndepending on their type and size."
        "\n"
        "\nOtherwise, if such issue is found and it is marked as CLOSED DUPLICATE,"
        "\nthe tool follows the chain of duplicates until it finds a non-DUPLICATE issue."
        "\nThe tool adds a new comment to found issue."
        "\n"
        "\nThe URL to new or modified issue is printed to stdout and recorded in"
        "\n'reported_to' element."
        "\n"
        "\nOption -t uploads FILEs to the already created issue on MantisBT site."
        "\nThe issue ID is retrieved from directory specified by -d DIR."
        "\nIf problem data in DIR was never reported to MantisBT, upload will fail."
        "\n"
        "\nOption -tID uploads FILEs to the issue with specified ID on MantisBT site."
        "\n-d DIR is ignored."
        "\n"
        "\nOption -r sets the last url from reporter_to element which is prefixed with"
        "\nTRACKER_NAME to URL field. This option is applied only when a new issue is to be"
        "\nfiled. The default value is 'ABRT Server'"
        "\n"
        "\nIf not specified, CONFFILE defaults to "CONF_DIR"/plugins/mantisbt.conf"
        "\nand user's local ~"USER_HOME_CONFIG_PATH"/mantisbt.conf."
        "\nIts lines should have 'PARAM = VALUE' format."
        "\nRecognized string parameters: MantisbtURL, Login, Password, Project, ProjectVersion."
        "\nRecognized boolean parameter (VALUE should be 1/0, yes/no): SSLVerify, CreatePrivate."
        "\nUser's local configuration overrides the system wide configuration."
        "\nParameters can be overridden via $Mantisbt_PARAM environment variables."
        "\n"
        "\nFMTFILE default to "CONF_DIR"/plugins/mantisbt_format.conf."
        "\nFMTFILE2 default to "CONF_DIR"/plugins/mantisbt_formatdup.conf."
    );

    enum {
        OPT_v = 1 << 0,
        OPT_d = 1 << 1,
        OPT_c = 1 << 2,
        OPT_F = 1 << 3,
        OPT_A = 1 << 4,
        OPT_t = 1 << 5,
        OPT_f = 1 << 6,
        OPT_h = 1 << 7,
        OPT_r = 1 << 8,
        OPT_D = 1 << 9,
    };

    const char *dump_dir_name = ".";
    GList *conf_file = NULL;
    const char *fmt_file = CONF_DIR"/plugins/mantisbt_format.conf";
    const char *fmt_file2 = CONF_DIR"/plugins/mantisbt_formatdup.conf";
    char *abrt_hash = NULL;
    char *ticket_no = NULL;
    const char *tracker_str = "ABRT Server";
    char *debug_str = NULL;
    mantisbt_settings_t mbt_settings = { 0 };
    /* Keep enum above and order of options below in sync! */
    struct options program_options[] = {
        OPT__VERBOSE(&g_verbose),
        OPT_STRING(   'd', NULL, &dump_dir_name , "DIR"    , _("Problem directory")),
        OPT_LIST(     'c', NULL, &conf_file     , "FILE"   , _("Configuration file (may be given many times)")),
        OPT_STRING(   'F', NULL, &fmt_file      , "FILE"   , _("Formatting file for initial comment")),
        OPT_STRING(   'A', NULL, &fmt_file2     , "FILE"   , _("Formatting file for duplicates")),
        OPT_OPTSTRING('t', "ticket", &ticket_no , "ID"     , _("Attach FILEs [to issue with this ID]")),
        OPT_BOOL(     'f', NULL, NULL,                       _("Force reporting even if this problem is already reported")),
        OPT_STRING(   'h', "duphash", &abrt_hash, "DUPHASH", _("Print BUG_ID which has given DUPHASH")),
        OPT_STRING(   'r', "tracker", &tracker_str, "TRACKER_NAME", _("A name of bug tracker for an additional URL from 'reported_to'")),

        OPT_OPTSTRING('D', "debug", &debug_str  , "STR"    , _("Debug")),
        OPT_END()
    };

    unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);
    argv += optind;

    export_abrt_envvars(0);

    map_string_t *settings = new_map_string();

    {
        char *local_conf = NULL;
        if (!conf_file)
        {
            conf_file = g_list_append(conf_file, (char*) CONF_DIR"/plugins/mantisbt.conf");
            local_conf = xasprintf("%s"USER_HOME_CONFIG_PATH"/mantisbt.conf", getenv("HOME"));
            conf_file = g_list_append(conf_file, local_conf);
        }
        while (conf_file)
        {
            char *fn = (char *)conf_file->data;
            log_notice("Loading settings from '%s'", fn);
            load_conf_file(fn, settings, /*skip key w/o values:*/ false);
            log_debug("Loaded '%s'", fn);
            conf_file = g_list_delete_link(conf_file, conf_file);
        }
        free(local_conf);

        struct dump_dir *dd = NULL;
        if (abrt_hash == NULL)
        {
            dd = dd_opendir(dump_dir_name, /*flags:*/ 0);
            if (!dd)
                error_msg_and_die(_("Can't open problem dir '%s'."), dump_dir_name);
        }

        set_settings(&mbt_settings, settings, dd);
        dd_close(dd);
        /* WRONG! set_settings() does not copy the strings, it merely sets up pointers
         * to settings[] dictionary:
         */
        /*free_map_string(settings);*/
    }

    /* No connection is opened between client and server. Users authentication
     * is performed on every SOAP method call. In the first step we verify the
     * credentials by calling 'mc_login' method.  In the case the credentials are
     * correctly applies the reporter uses them in the next requests. It is not
     * necessary to call 'mc_login' method because the method provides only
     * verification of credentials.
     */
    verify_credentials(&mbt_settings);

    if (abrt_hash)
    {
        log_warning(_("Looking for similar problems in MantisBT"));
        GList *ids = mantisbt_search_by_abrt_hash(&mbt_settings, abrt_hash);
        mantisbt_settings_free(&mbt_settings);

        if (ids == NULL)
            return EXIT_FAILURE;

        puts(ids->data);
        response_values_free(ids);
        return EXIT_SUCCESS;
    }

    mantisbt_get_project_id_from_name(&mbt_settings);

    if (opts & OPT_t)
    {
        if (!argv[0])
            show_usage_and_die(program_usage_string, program_options);

        if (!ticket_no)
        {
            struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0);
            if (!dd)
                xfunc_die();
            report_result_t *reported_to = find_in_reported_to(dd, "MantisBT");
            dd_close(dd);

            if (!reported_to || !reported_to->url)
                error_msg_and_die(_("Can't get MantisBT ID because this problem has not yet been reported to MantisBT."));

            char *url = reported_to->url;
            reported_to->url = NULL;
            free_report_result(reported_to);

            if (prefixcmp(url, mbt_settings.m_mantisbt_url) != 0)
                error_msg_and_die(_("This problem has been reported to MantisBT '%s' which differs from the configured MantisBT '%s'."), url, mbt_settings.m_mantisbt_url);

            ticket_no = strrchr(url, '=');
            if (!ticket_no)
                error_msg_and_die(_("Malformed url to MantisBT '%s'."), url);

            /* won't ever call free on it - it simplifies the code a lot */
            ticket_no = xstrdup(ticket_no + 1);
            log_warning(_("Using MantisBT ID '%s'"), ticket_no);
        }

        /* Attach files to existing MantisBT issues */
        while (*argv)
        {
            const char *path = *argv++;
            char *filename = basename(path);
            log_warning(_("Attaching file '%s' to issue %s"), filename, ticket_no);
            mantisbt_attach_file(&mbt_settings, ticket_no, filename, path);
        }

        return 0;
    }

    /* Create new issue in MantisBT */

    if (!(opts & OPT_f))
    {
        struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0);
        if (!dd)
            xfunc_die();
        report_result_t *reported_to = find_in_reported_to(dd, "MantisBT");
        dd_close(dd);

        if (reported_to && reported_to->url)
        {
            char *msg = xasprintf(_("This problem was already reported to MantisBT (see '%s')."
                            " Do you still want to create a new issue?"),
                            reported_to->url);
            int yes = ask_yes_no(msg);
            free(msg);
            if (!yes)
                return 0;
        }
        free_report_result(reported_to);
    }

    problem_data_t *problem_data = create_problem_data_for_reporting(dump_dir_name);
    if (!problem_data)
        xfunc_die(); /* create_problem_data_for_reporting already emitted error msg */

    const char *category = problem_data_get_content_or_die(problem_data, FILENAME_COMPONENT);
    const char *duphash   = problem_data_get_content_or_die(problem_data, FILENAME_DUPHASH);

    if (opts & OPT_D)
    {
        problem_formatter_t *pf = problem_formatter_new();
        problem_formatter_add_section(pf, PR_SEC_ADDITIONAL_INFO, /* optional section */ 0);

        if (problem_formatter_load_file(pf, fmt_file))
            error_msg_and_die("Invalid format file: %s", fmt_file);

        problem_report_t *pr = NULL;
        if (problem_formatter_generate_report(pf, problem_data, &pr))
            error_msg_and_die("Failed to format issue report from problem data");

        printf("summary: %s\n"
                "\n"
                "Description:\n%s\n"
                "Additional info:\n%s\n"
                , problem_report_get_summary(pr)
                , problem_report_get_description(pr)
                , problem_report_get_section(pr, PR_SEC_ADDITIONAL_INFO)
        );

        puts("attachments:");
        for (GList *a = problem_report_get_attachments(pr); a != NULL; a = g_list_next(a))
            printf(" %s\n", (const char *)a->data);

        problem_report_free(pr);
        problem_formatter_free(pf);
        exit(0);
    }

     unsigned long bug_id = 0;

    /* If REMOTE_RESULT contains "DUPLICATE 12345", we consider it a dup of 12345
     * and won't search on MantisBT server.
     */
    char *remote_result;
    remote_result = problem_data_get_content_or_NULL(problem_data, FILENAME_REMOTE_RESULT);
    if (remote_result)
    {
        char *cmd = strtok(remote_result, " \n");
        char *id = strtok(NULL, " \n");

        if (!prefixcmp(cmd, "DUPLICATE"))
        {
            errno = 0;
            char *e;
            bug_id = strtoul(id, &e, 10);
            if (errno || id == e || *e != '\0' || bug_id > INT_MAX)
            {
                /* error / no digits / illegal trailing chars / too big a number */
                bug_id = 0;
            }
        }
    }

    mantisbt_issue_info_t *ii;
    if (!bug_id)
    {
        log_warning(_("Checking for duplicates"));

        int existing_id = -1;
        int crossver_id = -1;
        {
            /* Figure out whether we want to match category
             * when doing dup search.
             */
            const char *category_substitute = is_in_comma_separated_list(category, mbt_settings.m_DontMatchComponents) ? NULL : category;

            /* We don't do dup detection across versions (see below why),
             * but we do add a note if cross-version potential dup exists.
             * For that, we search for cross version dups first:
             */
            // SOAP API searching method is not in the final version, it's possible the project will be string
            GList *crossver_bugs_ids = mantisbt_search_duplicate_issues(&mbt_settings, category_substitute, /*version*/ NULL, duphash);

            unsigned crossver_bugs_count = g_list_length(crossver_bugs_ids);
            log_debug("MantisBT has %i reports with duphash '%s' including cross-version ones",
                    crossver_bugs_count, duphash);
            if (crossver_bugs_count > 0)
                crossver_id = atoi(g_list_first(crossver_bugs_ids)->data);

            if (crossver_bugs_count > 0)
            {
                // SOAP API searching method is not in the final version, it's possible the project will be string
                GList *dup_bugs_ids = mantisbt_search_duplicate_issues(&mbt_settings, category_substitute, mbt_settings.m_project_version, duphash);

                unsigned dup_bugs_count =  g_list_length(dup_bugs_ids);
                log_debug("MantisBT has %i reports with duphash '%s'",
                        dup_bugs_count, duphash);
                if (dup_bugs_count > 0)
                    existing_id = atoi(g_list_first(dup_bugs_ids)->data);
            }
        }

        if (existing_id < 0)
        {
            /* Create new issue */
            log_warning(_("Creating a new issue"));
            problem_formatter_t *pf = problem_formatter_new();
            problem_formatter_add_section(pf, PR_SEC_ADDITIONAL_INFO, 0);

            if (problem_formatter_load_file(pf, fmt_file))
                error_msg_and_die(_("Invalid format file: %s"), fmt_file);

            problem_report_t *pr = NULL;
            if (problem_formatter_generate_report(pf, problem_data, &pr))
                error_msg_and_die(_("Failed to format problem data"));

            if (crossver_id >= 0)
                problem_report_buffer_printf(
                        problem_report_get_buffer(pr, PR_SEC_DESCRIPTION),
                        "\nPotential duplicate: issue %u\n", crossver_id);

            problem_formatter_free(pf);

            /* get tracker URL if exists */
            struct dump_dir *dd = dd_opendir(dump_dir_name, 0);
            char *tracker_url = NULL;
            if (dd)
            {
                report_result_t *reported_to = find_in_reported_to(dd, tracker_str);
                dd_close(dd);

                if (reported_to && reported_to->url)
                {
                    log_warning(_("Adding External URL to issue"));
                    tracker_url = xstrdup(reported_to->url);
                    free_report_result(reported_to);
                }
            }

            int new_id = mantisbt_create_new_issue(&mbt_settings, problem_data, pr, tracker_url);

            free(tracker_url);

            if (new_id == -1)
                return EXIT_FAILURE;

            log_warning(_("Adding attachments to issue %i"), new_id);
            char *new_id_str = xasprintf("%u", new_id);

            for (GList *a = problem_report_get_attachments(pr); a != NULL; a = g_list_next(a))
            {
                const char *item_name = (const char *)a->data;
                struct problem_item *item = problem_data_get_item_or_NULL(problem_data, item_name);
                if (!item)
                    continue;
                else if (item->flags & CD_FLAG_TXT)
                    mantisbt_attach_data(&mbt_settings, new_id_str, item_name, item->content, strlen(item->content));
                else if (item->flags & CD_FLAG_BIN)
                    mantisbt_attach_file(&mbt_settings, new_id_str, item_name, item->content);
            }

            free(new_id_str);
            problem_report_free(pr);
            ii = mantisbt_issue_info_new();
            ii->mii_id = new_id;
            ii->mii_status = xstrdup("new");

            goto finish;
        }

        bug_id = existing_id;
    }

    ii = mantisbt_get_issue_info(&mbt_settings, bug_id);

    log_warning(_("Bug is already reported: %i"), ii->mii_id);

    /* Follow duplicates */
    if ((strcmp(ii->mii_status, "closed") == 0)
     && (strcmp(ii->mii_resolution, "duplicate") == 0)
    ) {
        mantisbt_issue_info_t *origin = mantisbt_find_origin_bug_closed_duplicate(&mbt_settings, ii);
        if (origin)
        {
            mantisbt_issue_info_free(ii);
            ii = origin;
        }
    }

    /* TODO CC list
     * Is no MantisBT SOAP API method which allows adding users to CC list
     * without updating issue.
     */

    /* Add comment and bt */
    const char *comment = problem_data_get_content_or_NULL(problem_data, FILENAME_COMMENT);
    if (comment && comment[0])
    {
        problem_formatter_t *pf = problem_formatter_new();

        if (problem_formatter_load_file(pf, fmt_file2))
            error_msg_and_die(_("Invalid duplicate format file: '%s"), fmt_file2);

        problem_report_t *pr;
        if (problem_formatter_generate_report(pf, problem_data, &pr))
            error_msg_and_die(_("Failed to format duplicate comment from problem data"));

        const char *mbtcomment = problem_report_get_description(pr);

        int dup_comment = is_comment_dup(ii->mii_notes, mbtcomment);
        if (!dup_comment)
        {
            log_warning(_("Adding new comment to issue %d"), ii->mii_id);
            mantisbt_add_issue_note(&mbt_settings, ii->mii_id, mbtcomment);

            const char *bt = problem_data_get_content_or_NULL(problem_data, FILENAME_BACKTRACE);
            unsigned rating = 0;
            const char *rating_str = problem_data_get_content_or_NULL(problem_data, FILENAME_RATING);
            /* python doesn't have rating file */
            if (rating_str)
                rating = xatou(rating_str);
            if (bt && rating > ii->mii_best_bt_rating)
            {
                char *bug_id_str = xasprintf("%i", ii->mii_id);

                log_warning(_("Attaching better backtrace"));

                // find unique filename of attachment
                char *name = NULL;
                for (int i = 0;; ++i)
                {
                    if (i == 0)
                        name = xasprintf("%s", FILENAME_BACKTRACE);
                    else
                        name = xasprintf("%s%d", FILENAME_BACKTRACE, i);

                    if (g_list_find_custom(ii->mii_attachments, name, (GCompareFunc) strcmp) == NULL)
                        break;

                    free(name);
                }
                mantisbt_attach_data(&mbt_settings, bug_id_str, name, bt, strlen(bt));

                free(name);
                free(bug_id_str);
            }
        }
        else
            log_warning(_("Found the same comment in the issue history, not adding a new one"));

        problem_report_free(pr);
        problem_formatter_free(pf);
    }

finish:
    log_warning(_("Status: %s%s%s %s/view.php?id=%u"),
                ii->mii_status,
                ii->mii_resolution ? " " : "",
                ii->mii_resolution ? ii->mii_resolution : "",
                mbt_settings.m_mantisbt_url,
                ii->mii_id);

    struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0);
    if (dd)
    {
        report_result_t rr = { .label = (char *)"MantisBT" };
        rr.url = xasprintf("%s/view.php?id=%u", mbt_settings.m_mantisbt_url, ii->mii_id);
        add_reported_to_entry(dd, &rr);
        free(rr.url);
        dd_close(dd);
    }

    mantisbt_settings_free(&mbt_settings);
    return 0;
}
static void
keyring_find_secrets_cb (GObject *source,
                         GAsyncResult *result,
                         gpointer user_data)
{
	Request *r = user_data;
	GError *error = NULL;
	GError *search_error = NULL;
	const char *connection_id = NULL;
	GVariantBuilder builder_setting, builder_connection;
	GVariant *settings = NULL;
	GList *list = NULL;
	GList *iter;
	gboolean hint_found = FALSE, ask = FALSE;

	r->keyring_calls--;
	if (g_cancellable_is_cancelled (r->cancellable)) {
		/* Callback already called by NM or dispose */
		request_free (r);
		return;
	}

	list = secret_service_search_finish (NULL, result, &search_error);
	connection_id = nm_connection_get_id (r->connection);

	if (g_error_matches (search_error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
		error = g_error_new_literal (NM_SECRET_AGENT_ERROR,
		                             NM_SECRET_AGENT_ERROR_USER_CANCELED,
		                             "The secrets request was canceled by the user");
		g_error_free (search_error);
		goto done;
	} else if (search_error) {
		error = g_error_new (NM_SECRET_AGENT_ERROR,
		                     NM_SECRET_AGENT_ERROR_FAILED,
		                     "%s.%d - failed to read secrets from keyring (%s)",
		                     __FILE__, __LINE__, search_error->message);
		g_error_free (search_error);
		goto done;
	}

	/* Only ask if we're allowed to, so that eg a connection editor which
	 * requests secrets for its UI, for a connection which doesn't have any
	 * secrets yet, doesn't trigger the applet secrets dialog.
	 */
	if (   (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION)
	    && g_list_length (list) == 0) {
		g_message ("No keyring secrets found for %s/%s; asking user.", connection_id, r->setting_name);
		ask_for_secrets (r);
		return;
	}

	g_variant_builder_init (&builder_setting, NM_VARIANT_TYPE_SETTING);

	/* Extract the secrets from the list of matching keyring items */
	for (iter = list; iter != NULL; iter = g_list_next (iter)) {
		SecretItem *item = iter->data;
		SecretValue *secret;
		const char *key_name;
		GHashTable *attributes;

		secret = secret_item_get_secret (item);
		if (secret) {
			attributes = secret_item_get_attributes (item);
			key_name = g_hash_table_lookup (attributes, KEYRING_SK_TAG);
			if (!key_name) {
				g_hash_table_unref (attributes);
				secret_value_unref (secret);
				continue;
			}

			g_variant_builder_add (&builder_setting, "{sv}", key_name,
			                       g_variant_new_string (secret_value_get (secret, NULL)));

			/* See if this property matches a given hint */
			if (r->hints && r->hints[0]) {
				if (!g_strcmp0 (r->hints[0], key_name) || !g_strcmp0 (r->hints[1], key_name))
					hint_found = TRUE;
			}

			g_hash_table_unref (attributes);
			secret_value_unref (secret);
			break;
		}
	}

	/* If there were hints, and none of the hints were returned by the keyring,
	 * get some new secrets.
	 */
	if (r->flags) {
		if (r->hints && r->hints[0] && !hint_found)
			ask = TRUE;
		else if (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW) {
			g_message ("New secrets for %s/%s requested; ask the user", connection_id, r->setting_name);
			ask = TRUE;
		} else if (   (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION)
			       && is_connection_always_ask (r->connection))
			ask = TRUE;
	}

	/* Returned secrets are a{sa{sv}}; this is the outer a{s...} hash that
	 * will contain all the individual settings hashes.
	 */
	g_variant_builder_init (&builder_connection, NM_VARIANT_TYPE_CONNECTION);
	g_variant_builder_add (&builder_connection, "{sa{sv}}", r->setting_name, &builder_setting);
	settings = g_variant_builder_end (&builder_connection);

done:
	g_list_free_full (list, g_object_unref);
	if (ask) {
		GVariantIter dict_iter;
		const char *setting_name;
		GVariant *setting_dict;

		/* Stuff all the found secrets into the connection for the UI to use */
		g_variant_iter_init (&dict_iter, settings);
		while (g_variant_iter_next (&dict_iter, "{s@a{sv}}", &setting_name, &setting_dict)) {
			nm_connection_update_secrets (r->connection,
			                              setting_name,
			                              setting_dict,
			                              NULL);
			g_variant_unref (setting_dict);
		}

		ask_for_secrets (r);
	} else {
		/* Otherwise send the secrets back to NetworkManager */
		r->get_callback (NM_SECRET_AGENT_OLD (r->agent), r->connection, error ? NULL : settings, error, r->callback_data);
		request_free (r);
	}

	if (settings)
		g_variant_unref (settings);
	g_clear_error (&error);
}
static void
set_changed(GtkComboBox* combo, MateDACapplet* capplet, GList* list, gint type)
{
	guint index;
	GAppInfo* item;

	index = gtk_combo_box_get_active(combo);

	if (index < g_list_length(list))
	{
		item = (GAppInfo*) g_list_nth_data(list, index);
	
		switch (type)
		{
			case DA_TYPE_WEB_BROWSER:
			
				/* establecemos el item */
				g_app_info_set_as_default_for_type(item, "x-scheme-handler/http", NULL);
				g_app_info_set_as_default_for_type(item, "x-scheme-handler/https", NULL);

				/* about:config es usado por mozilla firefox y algunos otros con
				 * webtoolkit */
				g_app_info_set_as_default_for_type(item, "x-scheme-handler/about", NULL);
				break;

			case DA_TYPE_EMAIL:
				/* por alguna extraña razon, solo se usa mailto, en vez de mail. */
				g_app_info_set_as_default_for_type(item, "x-scheme-handler/mailto", NULL);
				break;
			
			case DA_TYPE_FILE:
				/* falta agregar más mime-types */
				g_app_info_set_as_default_for_type(item, "inode/directory", NULL);
				break;
			
			case DA_TYPE_TEXT:
				/* falta agregar más mime-types */
				g_app_info_set_as_default_for_type(item, "text/plain", NULL);
				break;

			case DA_TYPE_MEDIA:
				/* por alguna extraña razon, solo se usa mailto, en vez de mail. */
				g_app_info_set_as_default_for_type(item, "audio/x-vorbis+ogg", NULL);
				g_app_info_set_as_default_for_type(item, "audio/x-scpls", NULL);
				g_app_info_set_as_default_for_type(item, "audio/mpeg", NULL);
				g_app_info_set_as_default_for_type(item, "audio/x-wav", NULL);
				g_app_info_set_as_default_for_type(item, "audio/x-mpegurl", NULL);
				g_app_info_set_as_default_for_type(item, "video/webm", NULL);
				break;
				
			case DA_TYPE_VIDEO:
				/* por alguna extraña razon, solo se usa mailto, en vez de mail. */
				g_app_info_set_as_default_for_type(item, "video/mpeg", NULL);
				g_app_info_set_as_default_for_type(item, "video/x-mpeg", NULL);
				g_app_info_set_as_default_for_type(item, "video/msvideo", NULL);
				g_app_info_set_as_default_for_type(item, "video/quicktime", NULL);
				g_app_info_set_as_default_for_type(item, "video/x-avi", NULL);
				g_app_info_set_as_default_for_type(item, "video/x-ogm+ogg", NULL);
				g_app_info_set_as_default_for_type(item, "video/x-matroska", NULL);
				g_app_info_set_as_default_for_type(item, "video/webm", NULL);
				g_app_info_set_as_default_for_type(item, "video/mp4", NULL);
				g_app_info_set_as_default_for_type(item, "video/x-flv", NULL);
				break;

			case DA_TYPE_IMAGE:
				/* por alguna extraña razon, solo se usa mailto, en vez de mail. */
				g_app_info_set_as_default_for_type(item, "image/png", NULL);
				g_app_info_set_as_default_for_type(item, "image/jpeg", NULL);
				g_app_info_set_as_default_for_type(item, "image/gif", NULL);
				g_app_info_set_as_default_for_type(item, "image/bmp", NULL);
				g_app_info_set_as_default_for_type(item, "image/tiff", NULL);
				break;
						
						
			default:;
				break;
		}
	}
}
static gboolean
save_codec_blueprint (int fd, CodecBlueprint *codec_blueprint) {
  gchar *caps;
  const gchar *factory_name;
  GList *walk;
  gint size;

  WRITE_CHECK (write_codec_blueprint_int
      (fd, codec_blueprint->codec->id));
  WRITE_CHECK (write_codec_blueprint_string
      (fd, codec_blueprint->codec->encoding_name));
  WRITE_CHECK (write_codec_blueprint_int
      (fd, codec_blueprint->codec->clock_rate));
  WRITE_CHECK (write_codec_blueprint_int
      (fd, codec_blueprint->codec->channels));

  size = g_list_length (codec_blueprint->codec->optional_params);
  WRITE_CHECK (write_codec_blueprint_int (fd, size));
  for (walk = codec_blueprint->codec->optional_params; walk;
       walk = g_list_next (walk)) {
    FsCodecParameter *param = walk->data;
    WRITE_CHECK (write_codec_blueprint_string (fd, param->name));
    WRITE_CHECK (write_codec_blueprint_string (fd, param->value));
  }

  caps = gst_caps_to_string (codec_blueprint->media_caps);
  WRITE_CHECK (write_codec_blueprint_string (fd, caps));
  g_free (caps);

  caps = gst_caps_to_string (codec_blueprint->rtp_caps);
  WRITE_CHECK (write_codec_blueprint_string (fd, caps));
  g_free (caps);

  walk = codec_blueprint->send_pipeline_factory;
  size = g_list_length (walk);
  if (write (fd, &size, sizeof (gint)) != sizeof (gint))
    return FALSE;

  for (; walk; walk = g_list_next (walk)) {
    GList *walk2 = walk->data;
    size = g_list_length (walk2);
    if (write (fd, &size, sizeof (gint)) != sizeof (gint))
      return FALSE;
    for (; walk2; walk2 = g_list_next (walk2)) {
      GstElementFactory *fact = walk2->data;
      factory_name = gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (fact));
      WRITE_CHECK (write_codec_blueprint_string (fd, factory_name));
    }
  }

  walk = codec_blueprint->receive_pipeline_factory;
  size = g_list_length (walk);
  if (write (fd, &size, sizeof (gint)) != sizeof (gint))
    return FALSE;

  for (; walk; walk = g_list_next (walk)) {
    GList *walk2 = walk->data;
    size = g_list_length (walk2);
    if (write (fd, &size, sizeof (gint)) != sizeof (gint))
      return FALSE;
    for (; walk2; walk2 = g_list_next (walk2)) {
      GstElementFactory *fact = walk2->data;
      factory_name = gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (fact));
      WRITE_CHECK (write_codec_blueprint_string (fd, factory_name));
    }
  }

  return TRUE;
}
Exemple #19
0
int thread_join(thread_t thread, void **retval) {

    int found = 0;
    unsigned int i;
    for(i = 0; i < g_list_length(ready_list); i++) {
	thread_t t = g_list_nth_data(ready_list, i);
	if(thread == t)
	    found = 1;
	else {
	    if(g_list_find(t->sleeping_list, thread) != NULL)
		found = 1;
	}
    }

    if (found){

	thread_t next, current = g_list_nth_data(ready_list, 0);

	ready_list = g_list_remove(ready_list, current);

	thread->sleeping_list = g_list_append(thread->sleeping_list, current);

	next = g_list_nth_data(ready_list, 0);

	if(swapcontext(&current->uc, &next->uc) == -1)
	    return -1;

	*retval = current->retval;
	
	thread_sigTreat(current);

	if (g_list_index(zombie_list, thread) != -1){
	    zombie_list = g_list_remove(zombie_list,thread);
	    free(thread->uc.uc_stack.ss_sp);
	    /* juste avant de libérer la pile */
	    VALGRIND_STACK_DEREGISTER(thread->stackid);

	    free(thread);

	}

	thread_t cur_t =  g_list_nth_data(ready_list, 0);
	if(g_list_length(ready_list)==1 && g_list_length(cur_t->sleeping_list)==0){
	    /* fprintf(stderr, "Total Annihilation\n"); */

	    g_list_free(cur_t->sleeping_list);

	    free(cur_t);

	    g_list_free(ready_list);
	    ready_list=NULL;
	}
    }
    else if (g_list_index(zombie_list,thread)!=-1){

	thread_t waiter = g_list_nth_data(zombie_list,(g_list_index(zombie_list,
								    thread)));
	*retval = waiter->retval;
	zombie_list = g_list_remove(zombie_list,thread);
	free(thread->uc.uc_stack.ss_sp);
	/* juste avant de libérer la pile */
	VALGRIND_STACK_DEREGISTER(thread->stackid);
	/* free(thread->retval); */
	free(thread);
    }
    else {
	*retval = NULL;
	fprintf(stderr, "le thread %p n'existe pas\n", thread);
	return -1;
    }
    return 0;
}
gboolean
save_codecs_cache (FsMediaType media_type, GList *blueprints)
{
  gchar *cache_path;
  GList *item;
  gchar *tmp_path;
  int fd;
  int size;
  gchar magic[8] = {0};

  cache_path = get_codecs_cache_path (media_type);
  if (!cache_path)
    return FALSE;


  GST_DEBUG ("Saving codecs cache to %s", cache_path);

  tmp_path = g_strconcat (cache_path, ".tmpXXXXXX", NULL);
  fd = g_mkstemp (tmp_path);
  if (fd == -1) {
    gchar *dir;

    /* oops, I bet the directory doesn't exist */
    dir = g_path_get_dirname (cache_path);
    g_mkdir_with_parents (dir, 0777);
    g_free (dir);

    /* the previous g_mkstemp call overwrote the XXXXXX placeholder ... */
    g_free (tmp_path);
    tmp_path = g_strconcat (cache_path, ".tmpXXXXXX", NULL);
    fd = g_mkstemp (tmp_path);

    if (fd == -1) {
      GST_DEBUG ("Unable to save codecs cache. g_mkstemp () failed: %s",
          g_strerror (errno));
      g_free (tmp_path);
      g_free (cache_path);
      return FALSE;
    }
  }

  magic[0] = 'F';
  magic[1] = 'S';
  magic[2] = '?';
  magic[3] = 'C';

  if (media_type == FS_MEDIA_TYPE_AUDIO) {
    magic[2] = 'A';
  } else if (media_type == FS_MEDIA_TYPE_VIDEO) {
    magic[2] = 'V';
  }

  /* version of the binary format */
  magic[4] = '1';
  magic[5] = '1';

  if (write (fd, magic, 8) != 8)
    return FALSE;


  size = g_list_length (blueprints);
  if (write (fd, &size, sizeof (gint)) != sizeof (gint))
    return FALSE;


  for (item = g_list_first (blueprints);
       item;
       item = g_list_next (item)) {
    CodecBlueprint *codec_blueprint = item->data;
    if (!save_codec_blueprint (fd, codec_blueprint)) {
      GST_WARNING ("Unable to save codec cache");
      close (fd);
      g_free (tmp_path);
      g_free (cache_path);
      return FALSE;
    }
  }


  if (close (fd) < 0) {
    GST_DEBUG ("Can't close codecs cache file : %s", g_strerror (errno));
      g_free (tmp_path);
      g_free (cache_path);
      return FALSE;
  }

  if (g_file_test (tmp_path, G_FILE_TEST_EXISTS)) {
#ifdef WIN32
    remove (cache_path);
#endif
    rename (tmp_path, cache_path);
  }

  g_free (tmp_path);
  g_free (cache_path);
  GST_DEBUG ("Wrote binary codecs cache");
  return TRUE;
}
Exemple #21
0
/**
 * @brief Fs_EnumerateFunc for map discovery.
 */
static void enumerateMaps(const char *path, void *data) {

	MapListCollectionView *this = (MapListCollectionView *) data;

	const Array *maps = (Array *) this->maps;
	for (size_t i = 0; i < maps->count; i++) {

		const Value *value = $(maps, objectAtIndex, i);
		const MapListItemInfo *info = value->value;

		if (g_strcmp0(info->mapname, path) == 0) {
			return;
		}
	}

	file_t *file = cgi.OpenFile(path);
	if (file) {

		bsp_header_t header;
		if (cgi.ReadFile(file, (void *) &header, sizeof(header), 1) == 1) {

			for (size_t i = 0; i < sizeof(header) / sizeof(int32_t); i++) {
				((int32_t *) &header)[i] = LittleLong(((int32_t *) &header)[i]);
			}

			if (header.version != BSP_VERSION && header.version != BSP_VERSION_QUETOO) {
				cgi.Warn("Invalid BSP header found in %s: %d\n", path, header.version);
				cgi.CloseFile(file);
				return;
			}

			MapListItemInfo *info = g_new0(MapListItemInfo, 1);

			g_strlcpy(info->mapname, path, sizeof(info->mapname));
			g_strlcpy(info->message, path, sizeof(info->message));

			char *entities = g_malloc(header.lumps[BSP_LUMP_ENTITIES].file_len);

			cgi.SeekFile(file, header.lumps[BSP_LUMP_ENTITIES].file_ofs);
			cgi.ReadFile(file, entities, 1, header.lumps[BSP_LUMP_ENTITIES].file_len);

			const char *ents = entities;

			while (true) {
				char *c = ParseToken(&ents);

				if (*c == '\0') {
					break;
				}

				if (g_strcmp0(c, "message") == 0) {

					c = ParseToken(&ents);
					StripColors(c, info->message);

					c = strstr(info->message, "\\n");
					if (c) {
						*c = '\0';
					}

					c = strstr(info->message, " - ");
					if (c) {
						*c = '\0';
					}

					c = strstr(info->message, " by ");
					if (c) {
						*c = '\0';
					}

					break;
				}
			}

			g_free(entities);

			GList *mapshots = cgi.Mapshots(path);

			const size_t len = g_list_length(mapshots);
			if (len) {
				const char *mapshot = g_list_nth_data(mapshots, rand() % len);

				SDL_Surface *surf;
				if (cgi.LoadSurface(mapshot, &surf)) {
					SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE);
					info->mapshot = SDL_CreateRGBSurface(0,
					                                     this->collectionView.itemSize.w * 2,
					                                     this->collectionView.itemSize.h * 2,
					                                     surf->format->BitsPerPixel,
					                                     surf->format->Rmask,
					                                     surf->format->Gmask,
					                                     surf->format->Bmask,
					                                     surf->format->Amask
					                                    );
					SDL_SetSurfaceBlendMode(info->mapshot, SDL_BLENDMODE_NONE);
					SDL_BlitScaled(surf, NULL, info->mapshot, NULL);
				} else {
					info->mapshot = NULL;
				}
			}

			g_list_free_full(mapshots, g_free);

			Value *value = $(alloc(Value), initWithValue, info);

			WithLock(this->lock, {
				$(this->maps, addObject, value);
				$(this->maps, sort, sortMaps);
			});
		}
Exemple #22
0
void pan_grid_compute(PanWindow *pw, FileData *dir_fd, gint *width, gint *height)
{
	GList *list;
	GList *work;
	gint x, y;
	gint grid_size;
	gint next_y;

	list = pan_list_tree(dir_fd, SORT_NAME, TRUE, pw->ignore_symlinks);

	grid_size = (gint)sqrt((gdouble)g_list_length(list));
	if (pw->size > PAN_IMAGE_SIZE_THUMB_LARGE)
		{
		grid_size = grid_size * (512 + PAN_THUMB_GAP) * pw->image_size / 100;
		}
	else
		{
		grid_size = grid_size * (PAN_THUMB_SIZE + PAN_THUMB_GAP);
		}

	next_y = 0;

	*width = PAN_BOX_BORDER * 2;
	*height = PAN_BOX_BORDER * 2;

	x = PAN_THUMB_GAP;
	y = PAN_THUMB_GAP;
	work = list;
	while (work)
		{
		FileData *fd;
		PanItem *pi;

		fd = work->data;
		work = work->next;

		if (pw->size > PAN_IMAGE_SIZE_THUMB_LARGE)
			{
			pi = pan_item_image_new(pw, fd, x, y, 10, 10);

			x += pi->width + PAN_THUMB_GAP;
			if (y + pi->height + PAN_THUMB_GAP > next_y) next_y = y + pi->height + PAN_THUMB_GAP;
			if (x > grid_size)
				{
				x = PAN_THUMB_GAP;
				y = next_y;
				}
			}
		else
			{
			pi = pan_item_thumb_new(pw, fd, x, y);

			x += PAN_THUMB_SIZE + PAN_THUMB_GAP;
			if (x > grid_size)
				{
				x = PAN_THUMB_GAP;
				y += PAN_THUMB_SIZE + PAN_THUMB_GAP;
				}
			}
		pan_item_size_coordinates(pi, PAN_THUMB_GAP, width, height);
		}

	g_list_free(list);
}
Exemple #23
0
void
build_table(charpick_data *p_curr_data)
{
  GtkWidget *box, *button_box, **row_box;
  GtkWidget *button, *arrow;
  gint i = 0, len = g_utf8_strlen (p_curr_data->charlist, -1);
  GtkWidget **toggle_button;
  gchar *charlist;
  gint max_width=1, max_height=1;
  gint size_ratio;

  toggle_button = g_new (GtkWidget *, len);
  
  if (p_curr_data->box)
    gtk_widget_destroy(p_curr_data->box);
    
  if (p_curr_data->panel_vertical)
    box = gtk_vbox_new (FALSE, 0);
  else 
    box = gtk_hbox_new (FALSE, 0);
  gtk_widget_show (box);
  p_curr_data->box = box;
  
  button = gtk_button_new ();
  if (g_list_length (p_curr_data->chartable) != 1)
  {
    gtk_widget_set_tooltip_text (button, _("Available palettes"));
  
    switch (mate_panel_applet_get_orient (MATE_PANEL_APPLET (p_curr_data->applet))) {
       	case MATE_PANEL_APPLET_ORIENT_DOWN:
          	arrow = gtk_arrow_new (GTK_ARROW_DOWN, GTK_SHADOW_OUT);
       		break;
       	case MATE_PANEL_APPLET_ORIENT_UP:
          	arrow = gtk_arrow_new (GTK_ARROW_UP, GTK_SHADOW_OUT);  
       		break;
       	case MATE_PANEL_APPLET_ORIENT_LEFT:
       		arrow = gtk_arrow_new (GTK_ARROW_LEFT, GTK_SHADOW_OUT);  
  		break;
       	case MATE_PANEL_APPLET_ORIENT_RIGHT:
       		arrow = gtk_arrow_new (GTK_ARROW_RIGHT, GTK_SHADOW_OUT);  
  		break;
    default:
  	  g_assert_not_reached ();
    }
    gtk_container_add (GTK_CONTAINER (button), arrow);
    gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
    /* FIXME : evil hack (see force_no_focus_padding) */
    force_no_focus_padding (button);
    gtk_box_pack_start (GTK_BOX (box), button, TRUE, TRUE, 0);
    g_signal_connect (G_OBJECT (button), "clicked",
                              G_CALLBACK (chooser_button_clicked),
			      p_curr_data);
    g_signal_connect (G_OBJECT (button), "button_press_event",
                               G_CALLBACK (button_press_hack),
			       p_curr_data->applet);
  
  }
  
  charlist = g_strdup (p_curr_data->charlist);
  for (i = 0; i < len; i++) {
    gchar label[7];
    GtkRequisition req;
    gchar *atk_desc;
    gchar *name;
    
    g_utf8_strncpy (label, charlist, 1);
    charlist = g_utf8_next_char (charlist);

#ifdef HAVE_MUCHARMAP
    /* TRANSLATOR: This sentance reads something like 'Insert "PILCROW SIGN"'
     *             hopefully, the name of the unicode character has already
     *             been translated.
     */
    name = g_strdup_printf (_("Insert \"%s\""),
		    mucharmap_get_unicode_name (g_utf8_get_char (label)));
#else
    name = g_strdup (_("Insert special character"));
#endif
   
    toggle_button[i] = gtk_toggle_button_new_with_label (label);
    atk_desc =  g_strdup_printf (_("insert special character %s"), label);
    set_atk_name_description (toggle_button[i], NULL, atk_desc);
    g_free (atk_desc);
    gtk_widget_show (toggle_button[i]);
    gtk_button_set_relief(GTK_BUTTON(toggle_button[i]), GTK_RELIEF_NONE);
    /* FIXME : evil hack (see force_no_focus_padding) */
    force_no_focus_padding (toggle_button[i]);
    gtk_widget_set_tooltip_text (toggle_button[i], name);
    g_free (name);
                      
    gtk_widget_size_request (toggle_button[i], &req);
    
    max_width = MAX (max_width, req.width);
    max_height = MAX (max_height, req.height-2);
  
    g_object_set_data (G_OBJECT (toggle_button[i]), "unichar", 
				GINT_TO_POINTER(g_utf8_get_char (label)));
    g_signal_connect (GTK_OBJECT (toggle_button[i]), "toggled",
		      G_CALLBACK (toggle_button_toggled_cb),
                        p_curr_data);
    g_signal_connect (GTK_OBJECT (toggle_button[i]), "button_press_event", 
                      G_CALLBACK (button_press_hack), p_curr_data->applet);
  }
  
  if (p_curr_data->panel_vertical) {
    size_ratio = p_curr_data->panel_size / max_width;
    button_box = gtk_hbox_new (TRUE, 0);
  } else {
    size_ratio = p_curr_data->panel_size / max_height;
    button_box = gtk_vbox_new (TRUE, 0);
  }

  gtk_box_pack_start (GTK_BOX (box), button_box, TRUE, TRUE, 0);
  
  size_ratio = MAX (size_ratio, 1);
  row_box = g_new0 (GtkWidget *, size_ratio);
  for (i=0; i < size_ratio; i++) {
  	if (!p_curr_data->panel_vertical) row_box[i] = gtk_hbox_new (TRUE, 0);
  	else row_box[i] = gtk_vbox_new (TRUE, 0);
  	gtk_box_pack_start (GTK_BOX (button_box), row_box[i], TRUE, TRUE, 0);
  }
  
  for (i = 0; i <len; i++) {  	
  	int delta = len/size_ratio;
  	int index;
  
	if (delta > 0)
	  	index = i / delta;
	else
		index = i;

	index = CLAMP (index, 0, size_ratio-1);	
  	gtk_box_pack_start (GTK_BOX (row_box[index]), toggle_button[i], TRUE, TRUE, 0);
  }
 
  g_free (toggle_button);
  
  gtk_container_add (GTK_CONTAINER(p_curr_data->applet), box);
  gtk_widget_show_all (p_curr_data->box);

  p_curr_data->last_index = NO_LAST_INDEX;
  p_curr_data->last_toggle_button = NULL;
  
}
Exemple #24
0
int32_t dt_camera_import_job_run(dt_job_t *job)
{
  dt_camera_import_t *t = (dt_camera_import_t *)job->param;
  dt_control_log(_("starting to import images from camera"));

  // Setup a new filmroll to import images to....
  t->film=(dt_film_t*)g_malloc(sizeof(dt_film_t));

  dt_film_init(t->film);

  gchar* fixed_path = dt_util_fix_path(t->path);
  g_free(t->path);
  t->path = fixed_path;
  dt_variables_expand( t->vp, t->path, FALSE );
  sprintf(t->film->dirname,"%s",dt_variables_get_result(t->vp));

  dt_pthread_mutex_lock(&t->film->images_mutex);
  t->film->ref++;
  dt_pthread_mutex_unlock(&t->film->images_mutex);

  // Create recursive directories, abort if no access
  if( g_mkdir_with_parents(t->film->dirname,0755) == -1 )
  {
    dt_control_log(_("failed to create import path `%s', import aborted."), t->film->dirname);
    return 1;
  }

  // Import path is ok, lets actually create the filmroll in database..
  if(dt_film_new(t->film,t->film->dirname) > 0)
  {
    int total = g_list_length( t->images );
    char message[512]= {0};
    sprintf(message, ngettext ("importing %d image from camera", "importing %d images from camera", total), total );
    t->bgj = dt_control_backgroundjobs_create(darktable.control, 0, message);

    // Switch to new filmroll
    dt_film_open(t->film->id);
    dt_ctl_switch_mode_to(DT_LIBRARY);

    // register listener
    dt_camctl_listener_t listener= {0};
    listener.data=t;
    listener.image_downloaded=_camera_image_downloaded;
    listener.request_image_path=_camera_import_request_image_path;
    listener.request_image_filename=_camera_import_request_image_filename;

    //  start download of images
    dt_camctl_register_listener(darktable.camctl,&listener);
    dt_camctl_import(darktable.camctl,t->camera,t->images,dt_conf_get_bool("plugins/capture/camera/import/delete_originals"));
    dt_camctl_unregister_listener(darktable.camctl,&listener);
    dt_control_backgroundjobs_destroy(darktable.control, t->bgj);
    dt_variables_params_destroy(t->vp);
  }
  else
    dt_control_log(_("failed to create filmroll for camera import, import aborted."));

  dt_pthread_mutex_lock(&t->film->images_mutex);
  t->film->ref--;
  dt_pthread_mutex_unlock(&t->film->images_mutex);
  return 0;
}
Exemple #25
0
void
scroll_right (void)
{
  if (Denemo.project->movement->leftmeasurenum < g_list_length (Denemo.project->movement->measurewidths))
    h_scroll (Denemo.project->movement->leftmeasurenum + 1.0, Denemo.project);
}
Exemple #26
0
int32_t dt_camera_capture_job_run(dt_job_t *job)
{
  dt_camera_capture_t *t=(dt_camera_capture_t*)job->param;
  int total = t->brackets ? t->count * t->brackets : t->count;
  char message[512]= {0};
  double fraction=0;
  snprintf(message, 512, ngettext ("capturing %d image", "capturing %d images", total), total );
  
  /* try to get exp program mode for nikon */
  char *expprogram = (char *)dt_camctl_camera_get_property(darktable.camctl, NULL, "expprogram");
  
  /* if fail, lets try fetching mode for cannon */
  if(!expprogram) 
    expprogram = (char *)dt_camctl_camera_get_property(darktable.camctl, NULL, "autoexposuremode");

  /* Fetch all values for shutterspeed and initialize current value */
  GList *values=NULL;
  gconstpointer orginal_value=NULL;
  const char *cvalue = dt_camctl_camera_get_property(darktable.camctl, NULL, "shutterspeed");
  const char *value = dt_camctl_camera_property_get_first_choice(darktable.camctl, NULL, "shutterspeed");
  
  /* get values for bracketing */
  if (t->brackets && expprogram && expprogram[0]=='M' && value && cvalue)
  {
    do
    {
      // Add value to list
      values = g_list_append(values, g_strdup(value));
      // Check if current values is the same as orginal value, then lets store item ptr
      if (strcmp(value,cvalue) == 0)
        orginal_value = g_list_last(values)->data;
    }
    while ((value = dt_camctl_camera_property_get_next_choice(darktable.camctl, NULL, "shutterspeed")) != NULL);
  }
  else
  {
    /* if this was an itended bracket capture bail out */
    if(t->brackets)
    {
      dt_control_log(_("please set your camera to manual mode first!"));
      return 1;
    }
  }

  /* create the bgjob plate */
  const guint *jid  = dt_control_backgroundjobs_create(darktable.control, 0, message);

  GList *current_value = g_list_find(values,orginal_value);
  for(int i=0; i<t->count; i++)
  {
    for(int b=0; b<(t->brackets*2)+1; b++)
    {
      // If bracket capture, lets set change shutterspeed
      if (t->brackets)
      {
        if (b == 0)
        {
          // First bracket, step down time with (steps*brackets), also check so we never set the longest shuttertime which would be bulb mode
          for(int s=0; s<(t->steps*t->brackets); s++)
            if (g_list_next(current_value) && g_list_next(g_list_next(current_value)))
              current_value = g_list_next(current_value);
        }
        else
        {
          // Step up with (steps)
          for(int s=0; s<t->steps; s++)
            if(g_list_previous(current_value))
              current_value = g_list_previous(current_value);
        }
      }

      // set the time property for bracked capture
      if (t->brackets && current_value)
        dt_camctl_camera_set_property(darktable.camctl, NULL, "shutterspeed", current_value->data);

      // Capture image
      dt_camctl_camera_capture(darktable.camctl,NULL);

      fraction += 1.0/total;
      dt_control_backgroundjobs_progress(darktable.control, jid, fraction);
    }

    // lets reset to orginal value before continue
    if (t->brackets)
    {
      current_value = g_list_find(values,orginal_value);
      dt_camctl_camera_set_property(darktable.camctl, NULL, "shutterspeed", current_value->data);
    }

    // Delay if active
    if(t->delay)
      g_usleep(t->delay*G_USEC_PER_SEC);

  }

  dt_control_backgroundjobs_destroy(darktable.control, jid);


  // free values
  if(values)
  {
    for(int i=0; i<g_list_length(values); i++)
      g_free(g_list_nth_data(values,i));

    g_list_free(values);
  }

  return 0;
}
Exemple #27
0
void
ipoddisk_build_ipod_node (struct ipoddisk_node *root, Itdb_iTunesDB *itdb)
{
        GList                *list;
        struct ipoddisk_node *genres;
        struct ipoddisk_node *albums;
        struct ipoddisk_node *artists;
        struct ipoddisk_node *compilations;
        struct ipoddisk_node *playlists;

        genres       = ipoddisk_new_node(root, "Genres", IPODDISK_NODE_DEFAULT);
        albums       = ipoddisk_new_node(root, "Albums", IPODDISK_NODE_DEFAULT);
        artists      = ipoddisk_new_node(root, "Artists", IPODDISK_NODE_DEFAULT);
        playlists    = ipoddisk_new_node(root, "Playlists", IPODDISK_NODE_DEFAULT);
        compilations = ipoddisk_new_node(root, "Compilations", IPODDISK_NODE_DEFAULT);

        /* Populate iPodDisk/(Artists|Albums|Genres) */
        list = itdb->tracks;
        while (list) {
                Itdb_Track           *itdbtrk = list->data;
                struct ipoddisk_node *comp;
                gchar                *comp_title;

                list = g_list_next(list);

                ipoddisk_encode_name(&itdbtrk->album);
                ipoddisk_encode_name(&itdbtrk->title);
                ipoddisk_encode_name(&itdbtrk->genre);
                ipoddisk_encode_name(&itdbtrk->artist);

                ipoddisk_add_track(itdbtrk, artists, albums,
                                   NULL, &root->nd_data.ipod);

                if (itdbtrk->genre != NULL && strlen(itdbtrk->genre) != 0) {
                        struct ipoddisk_node *genre;
                        
                        genre = g_datalist_get_data(&genres->nd_children, itdbtrk->genre);
                        if (genre == NULL)
                                genre = ipoddisk_new_node(genres, itdbtrk->genre,
                                                          IPODDISK_NODE_DEFAULT);
                        ipoddisk_add_track(itdbtrk, genre, NULL,
                                           (struct ipoddisk_node *) itdbtrk->userdata, NULL);
                }

                if (!itdbtrk->compilation || /* not part of a compilation */
                    itdbtrk->album == NULL || itdbtrk->title == NULL)
                        continue;

                comp = g_datalist_get_data(&compilations->nd_children, itdbtrk->album);
                if (comp == NULL)
                        comp = ipoddisk_new_node(compilations, itdbtrk->album,
                                                 IPODDISK_NODE_DEFAULT);

                comp_title = g_strconcat(itdbtrk->title,
                                         ipod_get_track_extension(itdbtrk->ipod_path), 
                                         NULL);
                assert (itdbtrk->userdata != NULL);
                ipoddisk_add_child(comp, itdbtrk->userdata, comp_title);
                g_free(comp_title);
        }

        /* Populate iPodDisk/Playlists */
        list = itdb->playlists;
        while (list) {
                Itdb_Playlist          *itdbpl = list->data;
                gchar                  *pl_name;
                guint                   cnt;
                struct ipoddisk_node   *pl;
                struct __add_member_arg arg;

                list = g_list_next(list);

                if (itdb_playlist_is_mpl(itdbpl)) {
                        pl_name = "Master Playlist";
                        continue; /* ignore mpl for now, make it optional in the future */
                } else {
                        ipoddisk_encode_name(&itdbpl->name);
                        pl_name = itdbpl->name ? itdbpl->name : "Unknown Playlist";
                }

                pl = g_datalist_get_data(&playlists->nd_children, pl_name);
                if (pl == NULL)
                        pl = ipoddisk_new_node(playlists, pl_name,
                                               IPODDISK_NODE_DEFAULT);

                cnt = g_list_length(itdbpl->members);
                if (cnt == 1) {
                        arg.prefixfmt = NULL;
                } else if (cnt < 10) {
                        arg.prefixfmt = "%d. ";
                } else if (cnt < 100) {
                        arg.prefixfmt = "%.2d. ";
                } else if (cnt < 1000) {
                        arg.prefixfmt = "%.3d. ";
                } else {
                        arg.prefixfmt = "%.4d. ";
                }

                arg.counter  = 1;
                arg.playlist = pl;
                arg.ipod     = root;

		g_list_foreach(itdbpl->members,
                               ipoddisk_add_playlist_member, &arg);
        }

        return;
}
Exemple #28
0
/**
 * xfae_model_add:
 * @model       : a #XfaeModel.
 * @name        : the user visible name of the new item.
 * @description : the description for the new item.
 * @command     : the command for the new item.
 * @error       : return locations for errors or %NULL.
 *
 * Attempts to add a new item with the given parameters
 * to @model.
 *
 * Return value: %TRUE if successfull, else %FALSE.
 **/
gboolean
xfae_model_add (XfaeModel   *model,
                const gchar *name,
                const gchar *description,
                const gchar *command,
                GError     **error)
{
  GtkTreePath *path;
  GtkTreeIter  iter;
  XfaeItem    *item;
  XfceRc      *rc;
  gchar       *file;
  gchar       *dir;
  gchar        relpath[4096];
  guint        n;

  g_return_val_if_fail (XFAE_IS_MODEL (model), FALSE);
  g_return_val_if_fail (name != NULL, FALSE);
  g_return_val_if_fail (description != NULL, FALSE);
  g_return_val_if_fail (command != NULL, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  dir = xfce_resource_save_location (XFCE_RESOURCE_CONFIG, "autostart/", TRUE);

  /* generate a unique file name */
  for (n = 0;; ++n)
    {
      file = (n == 0)
        ?  g_strdup_printf ("%s.desktop", name)
        : g_strdup_printf ("%s-%u.desktop", name, n);
      file = g_strdelimit (file, G_DIR_SEPARATOR_S, '-'); /* not a copy */

      g_snprintf (relpath, 4096, "%s%s", dir, file);
      if (!g_file_test (relpath, G_FILE_TEST_IS_REGULAR))
        break;

      g_free (file);
    }

  /* generate the file spec */
  g_snprintf (relpath, 4096, "autostart/%s", file);
  g_free (file);
  g_free (dir);

  /* generate the .desktop file */
  rc = xfce_rc_config_open (XFCE_RESOURCE_CONFIG, relpath, FALSE);
  if (G_UNLIKELY (rc == NULL))
    {
      g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (EIO),
                   _("Failed to create file %s"), relpath);
      return FALSE;
    }

  /* write the content */
  xfce_rc_set_group (rc, "Desktop Entry");
  xfce_rc_write_entry (rc, "Encoding", "UTF-8");
  xfce_rc_write_entry (rc, "Version", "0.9.4");
  xfce_rc_write_entry (rc, "Type", "Application");
  xfce_rc_write_entry (rc, "Name", name);
  xfce_rc_write_entry (rc, "Comment", description);
  xfce_rc_write_entry (rc, "Exec", command);
  xfce_rc_write_entry (rc, "OnlyShowIn", "XFCE;");
  xfce_rc_write_bool_entry (rc, "StartupNotify", FALSE);
  xfce_rc_write_bool_entry (rc, "Terminal", FALSE);
  xfce_rc_write_bool_entry (rc, "Hidden", FALSE);
  xfce_rc_close (rc);

  /* now load the matching item for the list */
  item = xfae_item_new (relpath);
  if (G_UNLIKELY (item == NULL))
    {
      g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (EIO),
                   _("Failed to write file %s"), relpath);
      return FALSE;
    }

  /* append it to our list */
  model->items = g_list_append (model->items, item);

  /* generate the iter for the newly appended item */
  iter.stamp = model->stamp;
  iter.user_data = g_list_last (model->items);

  /* tell the view about it */
  path = gtk_tree_path_new_from_indices (g_list_length (model->items) - 1, -1);
  gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter);
  gtk_tree_path_free (path);

  return TRUE;
}
static void
photos_selection_toolbar_set_item_visibility (PhotosSelectionToolbar *self)
{
  PhotosSelectionToolbarPrivate *priv = self->priv;
  GList *apps = NULL;
  GList *l;
  GList *selection;
  GtkWidget *image;
  gboolean has_selection;
  gboolean show_collection;
  gboolean show_favorite;
  gboolean show_open;
  gboolean show_print;
  gboolean show_properties;
  gboolean show_trash;
  gchar *favorite_label;
  gchar *open_label;
  guint fav_count = 0;
  guint apps_length;
  guint sel_length;

  priv->inside_refresh = TRUE;

  selection = photos_selection_controller_get_selection (priv->sel_cntrlr);
  sel_length = g_list_length (selection);
  has_selection = sel_length > 0;

  show_collection = has_selection;
  show_favorite = has_selection;
  show_open = has_selection;
  show_print = has_selection;
  show_properties = has_selection;
  show_trash = has_selection;

  for (l = selection; l != NULL; l = g_list_next (l))
    {
      PhotosBaseItem *item;
      const gchar *default_app_name;
      const gchar *urn = (gchar *) l->data;

      item = PHOTOS_BASE_ITEM (photos_base_manager_get_object_by_id (priv->item_mngr, urn));

      if (photos_base_item_is_favorite (item))
        fav_count++;

      default_app_name = photos_base_item_get_default_app_name (item);
      if (default_app_name != NULL && g_list_find (apps, default_app_name) == NULL)
        apps = g_list_prepend (apps, (gpointer) g_strdup (default_app_name));

      show_trash = show_trash && photos_base_item_can_trash (item);
      show_print = show_print && !photos_base_item_is_collection (item);
    }

  show_favorite = show_favorite && ((fav_count == 0) || (fav_count == sel_length));

  apps_length = g_list_length (apps);
  show_open = (apps_length > 0);

  if (sel_length > 1)
    {
      show_print = FALSE;
      show_properties = FALSE;
    }

  if (apps_length == 1)
    /* Translators: this is the Open action in a context menu */
    open_label = g_strdup_printf (_("Open with %s"), (gchar *) apps->data);
  else
    /* Translators: this is the Open action in a context menu */
    open_label = g_strdup (_("Open"));

  gtk_button_set_label (GTK_BUTTON (priv->toolbar_open), open_label);
  g_free (open_label);
  g_list_free_full (apps, g_free);

  if (show_favorite && fav_count == sel_length)
    {
      favorite_label = g_strdup (_("Remove from favorites"));
      image = gtk_image_new_from_icon_name (PHOTOS_ICON_FAVORITE_SYMBOLIC, GTK_ICON_SIZE_BUTTON);
    }
  else
    {
      favorite_label = g_strdup (_("Add to favorites"));
      image = gtk_image_new_from_icon_name (PHOTOS_ICON_NOT_FAVORITE_SYMBOLIC, GTK_ICON_SIZE_BUTTON);
    }

  gtk_button_set_image (GTK_BUTTON (priv->toolbar_favorite), image);
  gtk_widget_set_tooltip_text (priv->toolbar_favorite, favorite_label);
  g_free (favorite_label);

  gtk_widget_set_sensitive (priv->toolbar_collection, show_collection);
  gtk_widget_set_sensitive (priv->toolbar_print, show_print);
  gtk_widget_set_sensitive (priv->toolbar_properties, show_properties);
  gtk_widget_set_sensitive (priv->toolbar_trash, show_trash);
  gtk_widget_set_sensitive (priv->toolbar_open, show_open);
  gtk_widget_set_sensitive (priv->toolbar_favorite, show_favorite);

  priv->inside_refresh = FALSE;
}
void
gimp_image_convert_precision (GimpImage     *image,
                              GimpPrecision  precision,
                              GimpProgress  *progress)
{
  GList       *all_drawables;
  GList       *list;
  const gchar *undo_desc = NULL;
  gint         nth_drawable, n_drawables;

  g_return_if_fail (GIMP_IS_IMAGE (image));
  g_return_if_fail (precision != gimp_image_get_precision (image));
  g_return_if_fail (precision == GIMP_PRECISION_U8 ||
                    gimp_image_get_base_type (image) != GIMP_INDEXED);
  g_return_if_fail (progress == NULL || GIMP_IS_PROGRESS (progress));

  all_drawables = g_list_concat (gimp_image_get_layer_list (image),
                                 gimp_image_get_channel_list (image));

  n_drawables = g_list_length (all_drawables);

  switch (precision)
    {
    case GIMP_PRECISION_U8:
      undo_desc = C_("undo-type", "Convert Image to 8 bit integer");
      break;

    case GIMP_PRECISION_U16:
      undo_desc = C_("undo-type", "Convert Image to 16 bit integer");
      break;

    case GIMP_PRECISION_U32:
      undo_desc = C_("undo-type", "Convert Image to 32 bit integer");
      break;

    case GIMP_PRECISION_HALF:
      undo_desc = C_("undo-type", "Convert Image to 16 bit floating point");
      break;

    case GIMP_PRECISION_FLOAT:
      undo_desc = C_("undo-type", "Convert Image to 32 bit floating point");
      break;
    }

  if (progress)
    gimp_progress_start (progress, undo_desc, FALSE);

  g_object_freeze_notify (G_OBJECT (image));

  gimp_image_undo_group_start (image, GIMP_UNDO_GROUP_IMAGE_CONVERT,
                               undo_desc);

  /*  Push the image precision to the stack  */
  gimp_image_undo_push_image_precision (image, NULL);

  /*  Set the new precision  */
  g_object_set (image, "precision", precision, NULL);

  for (list = all_drawables, nth_drawable = 0;
       list;
       list = g_list_next (list), nth_drawable++)
    {
      GimpDrawable *drawable = list->data;

      gimp_drawable_convert_type (drawable, image,
                                  gimp_drawable_get_base_type (drawable),
                                  precision, TRUE);

      if (progress)
        gimp_progress_set_value (progress,
                                 (gdouble) nth_drawable / (gdouble) n_drawables);
    }

  /*  convert the selection mask  */
  {
    GimpChannel *mask = gimp_image_get_mask (image);
    GeglBuffer  *buffer;

    gimp_image_undo_push_mask_precision (image, NULL, mask);

    buffer = gimp_gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                                   gimp_image_get_width  (image),
                                                   gimp_image_get_height (image)),
                                   gimp_image_get_mask_format (image));

    gegl_buffer_copy (gimp_drawable_get_buffer (GIMP_DRAWABLE (mask)), NULL,
                      buffer, NULL);

    gimp_drawable_set_buffer (GIMP_DRAWABLE (mask), FALSE, NULL, buffer);
    g_object_unref (buffer);
  }

  gimp_image_undo_group_end (image);

  gimp_image_precision_changed (image);
  g_object_thaw_notify (G_OBJECT (image));

  if (progress)
    gimp_progress_end (progress);
}