Пример #1
0
// create HTTP headers and send first part of buffer
static gboolean s3http_client_send_initial_request (S3HttpClient *http)
{
    struct evbuffer *out_buf;
    GList *l;

    // output length must be set !
    /*
    if (!http->output_length) {
        LOG_err (HTTP_LOG, "Output length is not set !");
        return FALSE;
    }
    */

    out_buf = evbuffer_new ();

    // first line
    evbuffer_add_printf (out_buf, "%s %s HTTP/1.1\r\n", 
        s3http_client_method_to_string (http->method),
        evhttp_uri_get_path (http->http_uri)
    );

    // host
    // evbuffer_add_printf (out_buf, "Host: %s\r\n",
    //     evhttp_uri_get_host (http->http_uri)
    // );

    // length
    // XXX:
    
    // must be set by the user !!!
   // if (http->output_length > 0) {
        evbuffer_add_printf (out_buf, "Content-Length: %"G_GUINT64_FORMAT"\r\n",
            http->output_length
        );
    //}

    // add headers
    for (l = g_list_first (http->l_output_headers); l; l = g_list_next (l)) {
        S3HttpClientHeader *header = (S3HttpClientHeader *) l->data;
        evbuffer_add_printf (out_buf, "%s: %s\r\n",
            header->key, header->value
        );
    }

    // end line
    evbuffer_add_printf (out_buf, "\r\n");

    // add current data in the output buffer
    LOG_debug (HTTP_LOG, "OUTPUT len: %zd", evbuffer_get_length (http->output_buffer));
    evbuffer_add_buffer (out_buf, http->output_buffer);
    
    http->output_sent += evbuffer_get_length (out_buf);

    LOG_debug (HTTP_LOG, "Request is sent !");
   // g_printf ("\n==============================\n%s\n======================\n",
   //     evbuffer_pullup (out_buf, -1));

    // send it
    bufferevent_write_buffer (http->bev, out_buf);


    // free memory
    evbuffer_free (out_buf);

    return TRUE;
}
Пример #2
0
void dt_dev_read_history(dt_develop_t *dev)
{
  if(dev->image_storage.id <= 0) return;

  // maybe prepend auto-presets to history before loading it:
  auto_apply_presets(dev->image_storage.id);

  sqlite3_stmt *stmt;
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), 
      "select imgid, num, module, operation, op_params, enabled, blendop_params, blendop_version, multi_priority, multi_name from history where imgid = ?1 order by num", -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dev->image_storage.id);
  dev->history_end = 0;
  while(sqlite3_step(stmt) == SQLITE_ROW)
  {
    // db record:
    // 0-img, 1-num, 2-module_instance, 3-operation char, 4-params blob, 5-enabled, 6-blend_params, 7-blendop_version, 8 multi_priority, 9 multi_name
    dt_dev_history_item_t *hist = (dt_dev_history_item_t *)malloc(sizeof(dt_dev_history_item_t));
    hist->enabled = sqlite3_column_int(stmt, 5);

    GList *modules = dev->iop;
    const char *opname = (const char *)sqlite3_column_text(stmt, 3);
    int multi_priority = sqlite3_column_int(stmt, 8);
    const char *multi_name = (const char *)sqlite3_column_text(stmt, 9);
    if(!opname)
    {
      fprintf(stderr, "[dev_read_history] database history for image `%s' seems to be corrupted!\n", dev->image_storage.filename);
      free(hist);
      continue;
    }

    hist->module = NULL;
    dt_iop_module_t *find_op = NULL;
    while(opname && modules)
    {
      dt_iop_module_t *module = (dt_iop_module_t *)modules->data;
      if(!strcmp(module->op, opname))
      {
        if (module->multi_priority == multi_priority)
        {
          hist->module = module;
          break;
        }
        else if (multi_priority > 0)
        {
          //we just say that we find the name, so we just have to add new instance of this module
          find_op = module;
        }        
      }
      modules = g_list_next(modules);
    }
    if (!hist->module && find_op)
    {
      //we have to add a new instance of this module and set index to modindex
      dt_iop_module_t *new_module    = (dt_iop_module_t *)malloc(sizeof(dt_iop_module_t));
      if (!dt_iop_load_module(new_module, find_op->so, dev))
      {
        new_module->multi_priority = multi_priority;
        
        snprintf(new_module->multi_name,128,"%s",multi_name);
        
        dev->iop = g_list_insert_sorted(dev->iop, new_module, sort_plugins);
        
        new_module->instance = find_op->instance;
        hist->module = new_module;
      }
    }
    
    if(!hist->module && opname)
    {
      fprintf(stderr, "[dev_read_history] the module `%s' requested by image `%s' is not installed on this computer!\n", opname, dev->image_storage.filename);
      free(hist);
      continue;
    }
    int modversion = sqlite3_column_int(stmt, 2);
    assert(strcmp((char *)sqlite3_column_text(stmt, 3), hist->module->op) == 0);
    hist->params = malloc(hist->module->params_size);
    hist->blend_params = malloc(sizeof(dt_develop_blend_params_t));
    snprintf(hist->multi_name,128,"%s",multi_name);
    hist->multi_priority = multi_priority;
    if(hist->module->version() != modversion || hist->module->params_size != sqlite3_column_bytes(stmt, 4) ||
        strcmp((char *)sqlite3_column_text(stmt, 3), hist->module->op))
    {
      if(!hist->module->legacy_params ||
          hist->module->legacy_params(hist->module, sqlite3_column_blob(stmt, 4), labs(modversion), hist->params, labs(hist->module->version())))
      {
        free(hist->params);
        free(hist->blend_params);
        fprintf(stderr, "[dev_read_history] module `%s' version mismatch: history is %d, dt %d.\n", hist->module->op, modversion, hist->module->version());
        const char *fname = dev->image_storage.filename + strlen(dev->image_storage.filename);
        while(fname > dev->image_storage.filename && *fname != '/') fname --;
        if(fname > dev->image_storage.filename) fname++;
        dt_control_log(_("%s: module `%s' version mismatch: %d != %d"), fname, hist->module->op, hist->module->version(), modversion);
        free(hist);
        continue;
      }
    }
    else
    {
      memcpy(hist->params, sqlite3_column_blob(stmt, 4), hist->module->params_size);
    }

    const void *blendop_params = sqlite3_column_blob(stmt, 6);
    int bl_length = sqlite3_column_bytes(stmt, 6);
    int blendop_version = sqlite3_column_int(stmt, 7);

    if (blendop_params && (blendop_version == dt_develop_blend_version()) && (bl_length == sizeof(dt_develop_blend_params_t)))
    {
      memcpy(hist->blend_params, blendop_params, sizeof(dt_develop_blend_params_t));
    }
    else if (blendop_params && dt_develop_blend_legacy_params(hist->module, blendop_params, blendop_version, hist->blend_params, dt_develop_blend_version(), bl_length) == 0)
    {
      // do nothing
    }
    else
    {
      memcpy(hist->blend_params, hist->module->default_blendop_params, sizeof(dt_develop_blend_params_t));
    }

    // memcpy(hist->module->params, hist->params, hist->module->params_size);
    // hist->module->enabled = hist->enabled;
    // printf("[dev read history] img %d number %d for operation %d - %s params %f %f\n", sqlite3_column_int(stmt, 0), sqlite3_column_int(stmt, 1), instance, hist->module->op, *(float *)hist->params, *(((float*)hist->params)+1));
    dev->history = g_list_append(dev->history, hist);
    dev->history_end ++;
  }

  if(dev->gui_attached)
  {
    dev->pipe->changed |= DT_DEV_PIPE_SYNCH;
    dev->preview_pipe->changed |= DT_DEV_PIPE_SYNCH; // again, fixed topology for now.
    dt_dev_invalidate_all(dev);

    /* signal history changed */
    dt_control_signal_raise(darktable.signals,DT_SIGNAL_DEVELOP_HISTORY_CHANGE);
  }
  sqlite3_finalize (stmt);
}
Пример #3
0
static void
gimp_tag_popup_constructed (GObject *object)
{
  GimpTagPopup        *popup = GIMP_TAG_POPUP (object);
  GimpTaggedContainer *container;
  GtkWidget           *entry;
  GtkAllocation        entry_allocation;
  GtkStyle            *frame_style;
  gint                 x;
  gint                 y;
  gint                 width;
  gint                 height;
  gint                 popup_height;
  GHashTable          *tag_hash;
  GList               *tag_list;
  GList               *tag_iterator;
  gint                 i;
  gint                 max_height;
  gint                 screen_height;
  gchar              **current_tags;
  gint                 current_count;
  GdkRectangle         popup_rects[2]; /* variants of popup placement */
  GdkRectangle         popup_rect; /* best popup rect in screen coordinates */

  if (G_OBJECT_CLASS (parent_class)->constructed)
    G_OBJECT_CLASS (parent_class)->constructed (object);

  entry = GTK_WIDGET (popup->combo_entry);

  gtk_window_set_screen (GTK_WINDOW (popup), gtk_widget_get_screen (entry));

  popup->context = gtk_widget_create_pango_context (GTK_WIDGET (popup));
  popup->layout  = pango_layout_new (popup->context);

  gtk_widget_get_allocation (entry, &entry_allocation);

  gtk_widget_style_get (GTK_WIDGET (popup),
                        "scroll-arrow-vlength", &popup->scroll_arrow_height,
                        NULL);

  pango_layout_set_attributes (popup->layout,
                               popup->combo_entry->normal_item_attr);

  current_tags  = gimp_tag_entry_parse_tags (GIMP_TAG_ENTRY (popup->combo_entry));
  current_count = g_strv_length (current_tags);

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

  tag_hash = container->tag_ref_counts;
  tag_list = g_hash_table_get_keys (tag_hash);
  tag_list = g_list_sort (tag_list, gimp_tag_compare_func);

  popup->tag_count = g_list_length (tag_list);
  popup->tag_data  = g_new0 (PopupTagData, popup->tag_count);

  for (i = 0, tag_iterator = tag_list;
       i < popup->tag_count;
       i++, tag_iterator = g_list_next (tag_iterator))
    {
      PopupTagData *tag_data = &popup->tag_data[i];
      gint          j;

      tag_data->tag   = tag_iterator->data;
      tag_data->state = GTK_STATE_NORMAL;

      g_object_ref (tag_data->tag);

      for (j = 0; j < current_count; j++)
        {
          if (! gimp_tag_compare_with_string (tag_data->tag, current_tags[j]))
            {
              tag_data->state = GTK_STATE_SELECTED;
              break;
            }
        }
    }

  g_list_free (tag_list);
  g_strfreev (current_tags);

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

      gimp_container_foreach (GIMP_CONTAINER (container),
                              (GFunc) gimp_tag_popup_check_can_toggle,
                              popup);
    }

  frame_style = gtk_widget_get_style (popup->frame);

  width  = (entry_allocation.width -
            2 * frame_style->xthickness);
  height = (gimp_tag_popup_layout_tags (popup, width) +
            2 * frame_style->ythickness);

  gdk_window_get_origin (gtk_widget_get_window (entry), &x, &y);

  max_height = entry_allocation.height * 10;

  screen_height = gdk_screen_get_height (gtk_widget_get_screen (entry));

  popup_height = MIN (height, max_height);

  popup_rects[0].x      = x;
  popup_rects[0].y      = 0;
  popup_rects[0].width  = entry_allocation.width;
  popup_rects[0].height = y + entry_allocation.height;

  popup_rects[1].x      = x;
  popup_rects[1].y      = y;
  popup_rects[1].width  = popup_rects[0].width;
  popup_rects[1].height = screen_height - popup_rects[0].height;

  if (popup_rects[0].height >= popup_height)
    {
      popup_rect = popup_rects[0];
      popup_rect.y += popup_rects[0].height - popup_height;
      popup_rect.height = popup_height;
    }
  else if (popup_rects[1].height >= popup_height)
    {
      popup_rect = popup_rects[1];
      popup_rect.height = popup_height;
    }
  else
    {
      if (popup_rects[0].height >= popup_rects[1].height)
        {
          popup_rect = popup_rects[0];
          popup_rect.y += popup->scroll_arrow_height + frame_style->ythickness;
        }
      else
        {
          popup_rect = popup_rects[1];
          popup_rect.y -= popup->scroll_arrow_height + frame_style->ythickness;
        }

      popup_height = popup_rect.height;
    }

  if (popup_height < height)
    {
      popup->arrows_visible    = TRUE;
      popup->upper_arrow_state = GTK_STATE_INSENSITIVE;

      gtk_alignment_set_padding (GTK_ALIGNMENT (popup->alignment),
                                 popup->scroll_arrow_height + 2,
                                 popup->scroll_arrow_height + 2, 0, 0);

      popup_height -= 2 * popup->scroll_arrow_height + 4;

      popup->scroll_height = height - popup_rect.height;
      popup->scroll_y      = 0;
      popup->scroll_step   = 0;
    }

  gtk_widget_set_size_request (popup->tag_area, width, popup_height);

  gtk_window_move (GTK_WINDOW (popup), popup_rect.x, popup_rect.y);
  gtk_window_resize (GTK_WINDOW (popup), popup_rect.width, popup_rect.height);
}
Пример #4
0
static gboolean 
_awn_CPUicon_update_icon(gpointer object)
{  

  AwnCPUiconPrivate * priv;  
  AwnSysmoniconPrivate * sysmonicon_priv=NULL;  
  AwnCPUicon * icon = object;
  AwnGraphSinglePoint *point;
  GList * list = NULL;
  gchar *text;
  priv = AWN_CPUICON_GET_PRIVATE (object);
  sysmonicon_priv = AWN_SYSMONICON_GET_PRIVATE (object);

  g_object_set (object,
                "invalidate",TRUE,
                NULL);
  
  /*FIXME change this to some type of graph_type thing */
  if ( (AWN_IS_AREAGRAPH(sysmonicon_priv->graph)) ||
        (AWN_IS_CIRCLEGRAPH(sysmonicon_priv->graph) ))
  {   
    point = g_new0 (AwnGraphSinglePoint,1);    
    *point = awn_CPUicon_get_load (object);
    /* Translators: %2.0lf is a number, %% is a percent sign, do not change them */
    text = g_strdup_printf (_("CPU: %2.0lf%%"),point->value);
//    awn_tooltip_set_text (AWN_TOOLTIP(sysmonicon_priv->tooltip),text);
    awn_icon_set_tooltip_text (AWN_ICON(object),text);    
    g_free (text);
    text = g_strdup_printf("%.0lf%%",point->value);  
    g_object_set (priv->text_overlay,
                  "text", text,
                 NULL);  
    g_free (text);
    
    list = g_list_prepend (list,point);
   
    awn_graph_add_data (sysmonicon_priv->graph,list);
    awn_sysmonicon_update_icon (AWN_SYSMONICON (icon));
    g_free (point);
    g_list_free (list);
  }
  else if ( AWN_IS_BARGRAPH(sysmonicon_priv->graph))
  {
    
#undef NOW
#undef LAST
#define LAST (priv->times[priv->now])
#define NOW (priv->times[priv->now ^ 1])
    
    AwnGraphSinglePoint avg_point = awn_CPUicon_get_load (object);      
    gint i;
    GList * iter;    
    glibtop_cpu cpu;
    glibtop_get_cpu(&cpu);
    
    for (i = 0; i < priv->num_cpus; i++)
    {
      gint64 total;
      gint64 total_used;
      gdouble percent_used;
      total = NOW[i][CPU_TOTAL] - LAST[i][CPU_TOTAL];
      total_used = NOW[i][CPU_USED] - LAST[i][CPU_USED];
      percent_used = total_used / (gdouble) total * 100.0;
      point = g_new0 (AwnGraphSinglePoint,1);      
      point->value = percent_used;
      list = g_list_prepend (list,point); 
    }
    text = g_strdup_printf (_("CPU: %2.0lf%%"),
                            avg_point.value
                            );
//    awn_tooltip_set_text (AWN_TOOLTIP(sysmonicon_priv->tooltip),text);
    awn_icon_set_tooltip_text (AWN_ICON(object),text);
    g_free (text);
    text = g_strdup_printf("%.0lf%%",avg_point.value);
    g_object_set (priv->text_overlay,
                  "text", text,
                 NULL);  
    g_free (text);
    
    awn_graph_add_data (sysmonicon_priv->graph,list);
    awn_sysmonicon_update_icon (AWN_SYSMONICON (icon));
    for (iter = list; iter; iter=g_list_next(iter))
    {
      g_free(iter->data);
    }
    g_list_free (list);    
#undef NOW
#undef LAST
      
  }
  return TRUE;
}
Пример #5
0
void dt_dev_add_history_item(dt_develop_t *dev, dt_iop_module_t *module, gboolean enable)
{
  if(darktable.gui->reset) return;
  dt_pthread_mutex_lock(&dev->history_mutex);
  if(dev->gui_attached)
  {
    GList *history = g_list_nth (dev->history, dev->history_end);
    while(history)
    {
      GList *next = g_list_next(history);
      dt_dev_history_item_t *hist = (dt_dev_history_item_t *)(history->data);
      // printf("removing obsoleted history item: %s\n", hist->module->op);
      free(hist->params);
      free(hist->blend_params);
      free(history->data);
      dev->history = g_list_delete_link(dev->history, history);
      history = next;
    }
    history = g_list_nth(dev->history, dev->history_end-1);
    if(!history || module->instance != ((dt_dev_history_item_t *)history->data)->module->instance || 
        module->multi_priority != ((dt_dev_history_item_t *)history->data)->module->multi_priority)
    {
      // new operation, push new item
      // printf("adding new history item %d - %s\n", dev->history_end, module->op);
      // if(history) printf("because item %d - %s is different operation.\n", dev->history_end-1, ((dt_dev_history_item_t *)history->data)->module->op);
      dev->history_end++;
      dt_dev_history_item_t *hist = (dt_dev_history_item_t *)malloc(sizeof(dt_dev_history_item_t));
      if (enable)
      {
        module->enabled = TRUE;
        if(module->off)
        {
          darktable.gui->reset = 1;
          gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(module->off), module->enabled);
          darktable.gui->reset = 0;
        }
      }
      hist->enabled = module->enabled;
      hist->module = module;
      hist->params = malloc(module->params_size);
      hist->multi_priority = module->multi_priority;
      snprintf(hist->multi_name,128,"%s",module->multi_name);
      /* allocate and set hist blend_params */
      hist->blend_params = malloc(sizeof(dt_develop_blend_params_t));
      memset(hist->blend_params, 0, sizeof(dt_develop_blend_params_t));

      memcpy(hist->params, module->params, module->params_size);
      if(module->flags() & IOP_FLAGS_SUPPORTS_BLENDING)
        memcpy(hist->blend_params, module->blend_params, sizeof(dt_develop_blend_params_t));

      dev->history = g_list_append(dev->history, hist);
      dev->pipe->changed |= DT_DEV_PIPE_SYNCH;
      dev->preview_pipe->changed |= DT_DEV_PIPE_SYNCH; // topology remains, as modules are fixed for now.
    }
    else
    {
      // same operation, change params
      // printf("changing same history item %d - %s\n", dev->history_end-1, module->op);
      dt_dev_history_item_t *hist = (dt_dev_history_item_t *)history->data;
      memcpy(hist->params, module->params, module->params_size);

      if(module->flags() & IOP_FLAGS_SUPPORTS_BLENDING)
        memcpy(hist->blend_params, module->blend_params, sizeof(dt_develop_blend_params_t));

      // if the user changed stuff and the module is still not enabled, do it:
      if(!hist->enabled && !module->enabled)
      {
        module->enabled = 1;
        if(module->off)
        {
          darktable.gui->reset = 1;
          gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(module->off), module->enabled);
          darktable.gui->reset = 0;
        }
      }
      hist->multi_priority = module->multi_priority;
      memcpy(hist->multi_name, module->multi_name, sizeof(module->multi_name));
      hist->enabled = module->enabled;
      dev->pipe->changed |= DT_DEV_PIPE_TOP_CHANGED;
      dev->preview_pipe->changed |= DT_DEV_PIPE_TOP_CHANGED;
    }
  }
#if 0
  {
    // debug:
    printf("remaining %d history items:\n", dev->history_end);
    GList *history = dev->history;
    int i = 0;
    while(history)
    {
      dt_dev_history_item_t *hist = (dt_dev_history_item_t *)(history->data);
      printf("%d %s\n", i, hist->module->op);
      history = g_list_next(history);
      i++;
    }
  }
#endif

  /* invalidate image data*/
  dt_similarity_image_dirty(dev->image_storage.id);

  // invalidate buffers and force redraw of darkroom
  dt_dev_invalidate_all(dev);
  dt_pthread_mutex_unlock(&dev->history_mutex);

  if(dev->gui_attached)
  {
    /* signal that history has changed */
    dt_control_signal_raise(darktable.signals, DT_SIGNAL_DEVELOP_HISTORY_CHANGE);

    /* redraw */
    dt_control_queue_redraw_center();
  }
}
Пример #6
0
GList *a_select_geoname_from_list(GtkWindow *parent, GList *geonames, gboolean multiple_selection_allowed, const gchar *title, const gchar *msg)
{
  GtkTreeIter iter;
  GtkCellRenderer *renderer;
  GtkCellRenderer *toggle_render;
  GtkWidget *view;
  found_geoname *geoname;
  gchar *latlon_string;
  int column_runner;
  gboolean checked;
  gboolean to_copy;

  GtkWidget *dialog = gtk_dialog_new_with_buttons (title,
                                                  parent,
                                                  GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                                  GTK_STOCK_CANCEL,
                                                  GTK_RESPONSE_REJECT,
                                                  GTK_STOCK_OK,
                                                  GTK_RESPONSE_ACCEPT,
                                                  NULL);
  GtkWidget *label = gtk_label_new ( msg );
  GtkTreeStore *store;
  if (multiple_selection_allowed)
  {
    store = gtk_tree_store_new(4, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
  }
  else
  {
    store = gtk_tree_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
  }
  GList *geoname_runner = geonames;
  while (geoname_runner)
  { 
    geoname = (found_geoname *)geoname_runner->data;
    latlon_string = g_strdup_printf("(%f,%f)", geoname->ll.lat, geoname->ll.lon);
    gtk_tree_store_append(store, &iter, NULL);
    if (multiple_selection_allowed)
    {
      gtk_tree_store_set(store, &iter, 0, FALSE, 1, geoname->name, 2, geoname->country, 3, latlon_string, -1);
    }
    else
    {
      gtk_tree_store_set(store, &iter, 0, geoname->name, 1, geoname->country, 2, latlon_string, -1);
    }
    geoname_runner = g_list_next(geoname_runner);
    g_free(latlon_string);
  }
  view = gtk_tree_view_new();
  renderer = gtk_cell_renderer_text_new();
  column_runner = 0;
  if (multiple_selection_allowed)
  {
    toggle_render = gtk_cell_renderer_toggle_new();
    g_object_set(toggle_render, "activatable", TRUE, NULL);
    g_signal_connect(toggle_render, "toggled", (GCallback) buttonToggled, GTK_TREE_MODEL(store));
    gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW(view), -1, "Select", toggle_render, "active", column_runner, NULL);
    column_runner++;
  }
  gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW(view), -1, "Name", renderer, "text", column_runner, NULL);
  column_runner++;
  gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW(view), -1, "Country", renderer, "text", column_runner, NULL);
  column_runner++;
  gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW(view), -1, "Lat/Lon", renderer, "text", column_runner, NULL);
  gtk_tree_view_set_headers_visible( GTK_TREE_VIEW(view), TRUE);
  gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store));
  gtk_tree_selection_set_mode( gtk_tree_view_get_selection(GTK_TREE_VIEW(view)),
      multiple_selection_allowed ? GTK_SELECTION_MULTIPLE : GTK_SELECTION_BROWSE );
  g_object_unref(store);

  gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), label, FALSE, FALSE, 0);
  gtk_widget_show ( label );
  gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), view, FALSE, FALSE, 0);
  gtk_widget_show ( view );
  while ( gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT )
  {
    GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
    GList *selected_geonames = NULL;

    gtk_tree_model_get_iter_first( GTK_TREE_MODEL(store), &iter);
    geoname_runner = geonames;
    while (geoname_runner)
    {
      to_copy = FALSE;
      if (multiple_selection_allowed)
      {
        gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &checked, -1);
        if (checked) {
          to_copy = TRUE;
        }
      }
      else
      {
        if (gtk_tree_selection_iter_is_selected(selection, &iter))
        {
          to_copy = TRUE;
        }
      }
      if (to_copy) {
        found_geoname *copied = copy_found_geoname(geoname_runner->data);
        selected_geonames = g_list_prepend(selected_geonames, copied);
      }
      geoname_runner = g_list_next(geoname_runner);
      gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
    }
    if (selected_geonames)
    { 
      gtk_widget_destroy ( dialog );
      return (selected_geonames);
    }
    a_dialog_error_msg(parent, _("Nothing was selected"));
  }
  gtk_widget_destroy ( dialog );
  return NULL;
}
Пример #7
0
/**
 * gst_registry_binary_write_cache:
 * @registry: a #GstRegistry
 * @location: a filename
 *
 * Write the @registry to a cache to file at given @location.
 *
 * Returns: %TRUE on success.
 */
gboolean
priv_gst_registry_binary_write_cache (GstRegistry * registry, GList * plugins,
    const char *location)
{
  GList *walk;
  GstBinaryRegistryMagic magic;
  GList *to_write = NULL;
  unsigned long file_position = 0;
  BinaryRegistryCache *cache;

  GST_INFO ("Building binary registry cache image");

  g_return_val_if_fail (GST_IS_REGISTRY (registry), FALSE);

  if (!gst_registry_binary_initialize_magic (&magic))
    goto fail;

  /* iterate trough the list of plugins and fit them into binary structures */
  for (walk = plugins; walk != NULL; walk = walk->next) {
    GstPlugin *plugin = GST_PLUGIN (walk->data);

    if (!plugin->filename)
      continue;

    if (GST_OBJECT_FLAG_IS_SET (plugin, GST_PLUGIN_FLAG_CACHED)) {
      GStatBuf statbuf;

      if (g_stat (plugin->filename, &statbuf) < 0 ||
          plugin->file_mtime != statbuf.st_mtime ||
          plugin->file_size != statbuf.st_size)
        continue;
    }

    if (!_priv_gst_registry_chunks_save_plugin (&to_write, registry, plugin)) {
      GST_ERROR ("Can't write binary plugin information for \"%s\"",
          plugin->filename);
    }
  }

  _priv_gst_registry_chunks_save_global_header (&to_write, registry,
      priv_gst_plugin_loading_get_whitelist_hash ());

  GST_INFO ("Writing binary registry cache");

  cache = gst_registry_binary_cache_init (registry, location);
  if (!cache)
    goto fail_free_list;

  /* write magic */
  if (gst_registry_binary_cache_write (cache, file_position,
          &magic, sizeof (GstBinaryRegistryMagic)) !=
      sizeof (GstBinaryRegistryMagic)) {
    GST_ERROR ("Failed to write binary registry magic");
    goto fail_free_list;
  }
  file_position += sizeof (GstBinaryRegistryMagic);

  /* write out data chunks */
  for (walk = to_write; walk; walk = g_list_next (walk)) {
    GstRegistryChunk *cur = walk->data;
    gboolean res;

    res = gst_registry_binary_write_chunk (cache, cur, &file_position);

    _priv_gst_registry_chunk_free (cur);
    walk->data = NULL;
    if (!res)
      goto fail_free_list;
  }
  g_list_free (to_write);

  if (!gst_registry_binary_cache_finish (cache, TRUE))
    return FALSE;

  return TRUE;

  /* Errors */
fail_free_list:
  {
    for (walk = to_write; walk; walk = g_list_next (walk)) {
      GstRegistryChunk *cur = walk->data;

      if (cur)
        _priv_gst_registry_chunk_free (cur);
    }
    g_list_free (to_write);

    if (cache)
      (void) gst_registry_binary_cache_finish (cache, FALSE);
    /* fall through */
  }
fail:
  {
    return FALSE;
  }
}
Пример #8
0
/** Creates a list of transactions from parsed data. Transactions that
 * could be created from rows are placed in parse_data->transactions;
 * rows that fail are placed in parse_data->error_lines. (Note: there
 * is no way for this function to "fail," i.e. it only returns 0, so
 * it may be changed to a void function in the future.)
 * @param parse_data Data that is being parsed
 * @param account Account with which transactions are created
 * @param redo_errors TRUE to convert only error data, FALSE for all data
 * @return 0 on success, 1 on failure
 */
int gnc_csv_parse_to_trans(GncCsvParseData* parse_data, Account* account,
                           gboolean redo_errors)
{
    gboolean hasBalanceColumn;
    int i, j, max_cols = 0;
    GArray* column_types = parse_data->column_types;
    GList *error_lines = NULL, *begin_error_lines = NULL;

    /* last_transaction points to the last element in
     * parse_data->transactions, or NULL if it's empty. */
    GList* last_transaction = NULL;

    /* Free parse_data->error_lines and parse_data->transactions if they
     * already exist. */
    if (redo_errors) /* If we're redoing errors, we save freeing until the end. */
    {
        begin_error_lines = error_lines = parse_data->error_lines;
    }
    else
    {
        if (parse_data->error_lines != NULL)
        {
            g_list_free(parse_data->error_lines);
        }
        if (parse_data->transactions != NULL)
        {
            g_list_free(parse_data->transactions);
        }
    }
    parse_data->error_lines = NULL;

    if (redo_errors) /* If we're looking only at error data ... */
    {
        if (parse_data->transactions == NULL)
        {
            last_transaction = NULL;
        }
        else
        {
            /* Move last_transaction to the end. */
            last_transaction = parse_data->transactions;
            while (g_list_next(last_transaction) != NULL)
            {
                last_transaction = g_list_next(last_transaction);
            }
        }
        /* ... we use only the lines in error_lines. */
        if (error_lines == NULL)
            i = parse_data->orig_lines->len; /* Don't go into the for loop. */
        else
            i = GPOINTER_TO_INT(error_lines->data);
    }
    else /* Otherwise, we look at all the data. */
    {
        /* The following while-loop effectively behaves like the following for-loop:
         * for(i = 0; i < parse_data->orig_lines->len; i++). */
        i = parse_data->start_row;
        last_transaction = NULL;
    }

    /* set parse_data->end_row to number of lines */
    if (parse_data->end_row > parse_data->orig_lines->len)
        parse_data->end_row = parse_data->orig_lines->len;

    while (i < parse_data->end_row)
    {
        GPtrArray* line = parse_data->orig_lines->pdata[i];
        /* This flag is TRUE if there are any errors in this row. */
        gboolean errors = FALSE;
        gchar* error_message = NULL;
        TransPropertyList* list = trans_property_list_new(account, parse_data->date_format, parse_data->currency_format );
        GncCsvTransLine* trans_line = NULL;

        for (j = 0; j < line->len; j++)
        {
            /* We do nothing in "None" or "Account" columns. */
            if ((column_types->data[j] != GNC_CSV_NONE) && (column_types->data[j] != GNC_CSV_ACCOUNT))
            {
                /* Affect the transaction appropriately. */
                TransProperty* property = trans_property_new(column_types->data[j], list);
                gboolean succeeded = trans_property_set(property, line->pdata[j]);

                /* TODO Maybe move error handling to within TransPropertyList functions? */
                if (succeeded)
                {
                    trans_property_list_add(property);
                }
                else
                {
                    errors = TRUE;
                    error_message = g_strdup_printf(_("%s column could not be understood."),
                                                    _(gnc_csv_column_type_strs[property->type]));
                    trans_property_free(property);
                    break;
                }
            }
        }

        /* If we had success, add the transaction to parse_data->transaction. */
        if (!errors)
        {
            trans_line = trans_property_list_to_trans(list, &error_message);
            errors = trans_line == NULL;
        }

        trans_property_list_free(list);

        /* If there were errors, add this line to parse_data->error_lines. */
        if (errors)
        {
            parse_data->error_lines = g_list_append(parse_data->error_lines,
                                                    GINT_TO_POINTER(i));
            /* If there's already an error message, we need to replace it. */
            if (line->len > (int)(parse_data->orig_row_lengths->data[i]))
            {
                g_free(line->pdata[line->len - 1]);
                line->pdata[line->len - 1] = error_message;
            }
            else
            {
                /* Put the error message at the end of the line. */
                g_ptr_array_add(line, error_message);
            }
        }
        else
        {
            /* If all went well, add this transaction to the list. */
            trans_line->line_no = i;

            /* We keep the transactions sorted by date. We start at the end
             * of the list and go backward, simply because the file itself
             * is probably also sorted by date (but we need to handle the
             * exception anyway). */

            /* If we can just put it at the end, do so and increment last_transaction. */
            if (last_transaction == NULL ||
                    xaccTransGetDate(((GncCsvTransLine*)(last_transaction->data))->trans) <= xaccTransGetDate(trans_line->trans))
            {
                parse_data->transactions = g_list_append(parse_data->transactions, trans_line);
                /* If this is the first transaction, we need to get last_transaction on track. */
                if (last_transaction == NULL)
                    last_transaction = parse_data->transactions;
                else /* Otherwise, we can just continue. */
                    last_transaction = g_list_next(last_transaction);
            }
            /* Otherwise, search backward for the correct spot. */
            else
            {
                GList* insertion_spot = last_transaction;
                while (insertion_spot != NULL &&
                        xaccTransGetDate(((GncCsvTransLine*)(insertion_spot->data))->trans) > xaccTransGetDate(trans_line->trans))
                {
                    insertion_spot = g_list_previous(insertion_spot);
                }
                /* Move insertion_spot one location forward since we have to
                 * use the g_list_insert_before function. */
                if (insertion_spot == NULL) /* We need to handle the case of inserting at the beginning of the list. */
                    insertion_spot = parse_data->transactions;
                else
                    insertion_spot = g_list_next(insertion_spot);

                parse_data->transactions = g_list_insert_before(parse_data->transactions, insertion_spot, trans_line);
            }
        }

        /* Increment to the next row. */
        if (redo_errors)
        {
            /* Move to the next error line in the list. */
            error_lines = g_list_next(error_lines);
            if (error_lines == NULL)
                i = parse_data->orig_lines->len; /* Don't continue the for loop. */
            else
                i = GPOINTER_TO_INT(error_lines->data);
        }
        else
        {
            i++;
        }
    }

    /* If we have a balance column, set the appropriate amounts on the transactions. */
    hasBalanceColumn = FALSE;
    for (i = 0; i < parse_data->column_types->len; i++)
    {
        if (parse_data->column_types->data[i] == GNC_CSV_BALANCE)
        {
            hasBalanceColumn = TRUE;
            break;
        }
    }

    if (hasBalanceColumn)
    {
        GList* transactions = parse_data->transactions;

        /* balance_offset is how much the balance currently in the account
         * differs from what it will be after the transactions are
         * imported. This will be sum of all the previous transactions for
         * any given transaction. */
        gnc_numeric balance_offset = double_to_gnc_numeric(0.0,
                                     xaccAccountGetCommoditySCU(account),
                                     GNC_HOW_RND_ROUND_HALF_UP);
        while (transactions != NULL)
        {
            GncCsvTransLine* trans_line = (GncCsvTransLine*)transactions->data;
            if (trans_line->balance_set)
            {
                time64 date = xaccTransGetDate(trans_line->trans);
                /* Find what the balance should be by adding the offset to the actual balance. */
                gnc_numeric existing_balance = gnc_numeric_add(balance_offset,
                                               xaccAccountGetBalanceAsOfDate(account, date),
                                               xaccAccountGetCommoditySCU(account),
                                               GNC_HOW_RND_ROUND_HALF_UP);

                /* The amount of the transaction is the difference between the new and existing balance. */
                gnc_numeric amount = gnc_numeric_sub(trans_line->balance,
                                                     existing_balance,
                                                     xaccAccountGetCommoditySCU(account),
                                                     GNC_HOW_RND_ROUND_HALF_UP);

                SplitList* splits = xaccTransGetSplitList(trans_line->trans);
                while (splits)
                {
                    SplitList* next_splits = g_list_next(splits);
                    xaccSplitDestroy((Split*)splits->data);
                    splits = next_splits;
                }

                trans_add_split(trans_line->trans, account,
                                gnc_account_get_book(account), amount, trans_line->num);
                if (trans_line->num)
                    g_free(trans_line->num);

                /* This new transaction needs to be added to the balance offset. */
                balance_offset = gnc_numeric_add(balance_offset,
                                                 amount,
                                                 xaccAccountGetCommoditySCU(account),
                                                 GNC_HOW_RND_ROUND_HALF_UP);
            }
            transactions = g_list_next(transactions);
        }
    }

    if (redo_errors) /* Now that we're at the end, we do the freeing. */
    {
        g_list_free(begin_error_lines);
    }

    /* We need to resize parse_data->column_types since errors may have added columns. */
    for (i = 0; i < parse_data->orig_lines->len; i++)
    {
        if (max_cols < ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len)
            max_cols = ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len;
    }
    i = parse_data->column_types->len;
    parse_data->column_types = g_array_set_size(parse_data->column_types, max_cols);
    for (; i < max_cols; i++)
    {
        parse_data->column_types->data[i] = GNC_CSV_NONE;
    }

    return 0;
}
Пример #9
0
/** Tests a TransPropertyList for having enough essential properties.
 * Essential properties are "Date" and one of the following: "Balance", "Deposit", or
 * "Withdrawal".
 * @param list The list we are checking
 * @param error Contains an error message on failure
 * @return TRUE if there are enough essentials; FALSE otherwise
 */
static gboolean trans_property_list_verify_essentials(TransPropertyList* list, gchar** error)
{
    int i;
    /* possible_errors lists the ways in which a list can fail this test. */
    enum PossibleErrorTypes {NO_DATE, NO_AMOUNT, NUM_OF_POSSIBLE_ERRORS};
    gchar* possible_errors[NUM_OF_POSSIBLE_ERRORS] =
    {
        N_("No date column."),
        N_("No balance, deposit, or withdrawal column.")
    };
    int possible_error_lengths[NUM_OF_POSSIBLE_ERRORS] = {0};
    GList *properties_begin = list->properties, *errors_list = NULL;

    /* Go through each of the properties and erase possible errors. */
    while (list->properties)
    {
        switch (((TransProperty*)(list->properties->data))->type)
        {
        case GNC_CSV_DATE:
            possible_errors[NO_DATE] = NULL;
            break;

        case GNC_CSV_BALANCE:
        case GNC_CSV_DEPOSIT:
        case GNC_CSV_WITHDRAWAL:
            possible_errors[NO_AMOUNT] = NULL;
            break;
        }
        list->properties = g_list_next(list->properties);
    }
    list->properties = properties_begin;

    /* Accumulate a list of the actual errors. */
    for (i = 0; i < NUM_OF_POSSIBLE_ERRORS; i++)
    {
        if (possible_errors[i] != NULL)
        {
            errors_list = g_list_append(errors_list, GINT_TO_POINTER(i));
            /* Since we added an error, we want to also store its length for
             * when we construct the full error string. */
            possible_error_lengths[i] = strlen(_(possible_errors[i]));
        }
    }

    /* If there are no errors, we can quit now. */
    if (errors_list == NULL)
        return TRUE;
    else
    {
        /* full_error_size is the full length of the error message. */
        int full_error_size = 0, string_length = 0;
        GList* errors_list_begin = errors_list;
        gchar *error_message, *error_message_begin;

        /* Find the value for full_error_size. */
        while (errors_list)
        {
            /* We add an extra 1 to account for spaces in between messages. */
            full_error_size += possible_error_lengths[GPOINTER_TO_INT(errors_list->data)] + 1;
            errors_list = g_list_next(errors_list);
        }
        errors_list = errors_list_begin;

        /* Append the error messages one after another. */
        error_message = error_message_begin = g_new(gchar, full_error_size);
        while (errors_list)
        {
            i = GPOINTER_TO_INT(errors_list->data);
            string_length = possible_error_lengths[i];

            /* Copy the error message and put a space after it. */
            strncpy(error_message, _(possible_errors[i]), string_length);
            error_message += string_length;
            *error_message = ' ';
            error_message++;

            errors_list = g_list_next(errors_list);
        }
        *error_message = '\0'; /* Replace the last space with the null byte. */
        g_list_free(errors_list_begin);

        *error = error_message_begin;
        return FALSE;
    }
}
Пример #10
0
static void
port_probe_run_ready (MMPortProbe *probe,
                      GAsyncResult *probe_result,
                      PortProbeRunContext *ctx)
{
    GError *error = NULL;

    if (!mm_port_probe_run_finish (probe, probe_result, &error)) {
        /* Probing failed saying the port is unsupported. This is not to be
         * treated as a generic error, the plugin is just telling us as nicely
         * as it can that the port is not supported, so don't warn these cases.
         */
        if (g_error_matches (error,
                             MM_CORE_ERROR,
                             MM_CORE_ERROR_UNSUPPORTED)) {
            g_simple_async_result_set_op_res_gpointer (ctx->result,
                                                       GUINT_TO_POINTER (MM_PLUGIN_SUPPORTS_PORT_UNSUPPORTED),
                                                       NULL);
        }
        /* Probing failed but the plugin tells us to retry; so we'll defer the
         * probing a bit */
        else if (g_error_matches (error,
                                  MM_CORE_ERROR,
                                  MM_CORE_ERROR_RETRY)) {
            g_simple_async_result_set_op_res_gpointer (ctx->result,
                                                       GUINT_TO_POINTER (MM_PLUGIN_SUPPORTS_PORT_DEFER),
                                                       NULL);
        }
        /* For remaining errors, just propagate them */
        else {
            g_simple_async_result_take_error (ctx->result, error);
        }
    } else {
        /* Probing succeeded */
        MMPluginSupportsResult supports_result;

        if (!apply_post_probing_filters (ctx->self, ctx->flags, probe)) {
            /* Port is supported! */
            supports_result = MM_PLUGIN_SUPPORTS_PORT_SUPPORTED;

            /* If we were looking for AT ports, and the port is AT,
             * and we were told that only one AT port is expected, cancel AT
             * probings in the other available support tasks of the SAME
             * device. */
            if (ctx->self->priv->single_at &&
                ctx->flags & MM_PORT_PROBE_AT &&
                mm_port_probe_is_at (probe)) {
                GList *l;

                for (l = mm_device_peek_port_probe_list (ctx->device); l; l = g_list_next (l)) {
                    if (l->data != probe) {
                        mm_port_probe_run_cancel_at_probing (MM_PORT_PROBE (l->data));
                    }
                }
            }
        } else {
            /* Unsupported port, remove from internal tracking HT */
            supports_result = MM_PLUGIN_SUPPORTS_PORT_UNSUPPORTED;
        }

        g_simple_async_result_set_op_res_gpointer (ctx->result,
                                                   GUINT_TO_POINTER (supports_result),
                                                   NULL);
    }

    /* Complete the async supports port request */
    g_simple_async_result_complete_in_idle (ctx->result);

    g_object_unref (ctx->device);
    g_object_unref (ctx->result);
    g_object_unref (ctx->self);
    g_free (ctx);
}
Пример #11
0
MMBaseModem *
mm_plugin_create_modem (MMPlugin  *self,
                        MMDevice *device,
                        GError   **error)
{
    MMBaseModem *modem = NULL;
    GList *port_probes, *l;

    port_probes = mm_device_peek_port_probe_list (device);

    /* Let the plugin create the modem from the port probe results */
    modem = MM_PLUGIN_GET_CLASS (self)->create_modem (MM_PLUGIN (self),
                                                      mm_device_get_path (device),
                                                      mm_device_get_drivers (device),
                                                      mm_device_get_vendor (device),
                                                      mm_device_get_product (device),
                                                      port_probes,
                                                      error);
    if (modem) {
        /* Grab each port */
        for (l = port_probes; l; l = g_list_next (l)) {
            GError *inner_error = NULL;
            MMPortProbe *probe = MM_PORT_PROBE (l->data);
            gboolean grabbed;

            /* If grabbing a port fails, just warn. We'll decide if the modem is
             * valid or not when all ports get organized */

            /* We apply again the subsystem filter, as the port may have been
             * probed and accepted by the generic plugin, which is overwritten
             * by the specific one when needed. */
            if (apply_subsystem_filter (self, mm_port_probe_peek_port (probe))) {
                grabbed = FALSE;
                inner_error = g_error_new (MM_CORE_ERROR,
                                           MM_CORE_ERROR_UNSUPPORTED,
                                           "unsupported subsystem: '%s'",
                                           mm_port_probe_get_port_subsys (probe));
            }
#if !defined WITH_QMI
            else if (mm_port_probe_get_port_type (probe) == MM_PORT_TYPE_NET &&
                     g_str_equal (mm_device_utils_get_port_driver (mm_port_probe_peek_port (probe)),
                                  "qmi_wwan")) {
                grabbed = FALSE;
                inner_error = g_error_new (MM_CORE_ERROR,
                                           MM_CORE_ERROR_UNSUPPORTED,
                                           "ignoring QMI net port");
            }
#endif
            else if (MM_PLUGIN_GET_CLASS (self)->grab_port)
                grabbed = MM_PLUGIN_GET_CLASS (self)->grab_port (MM_PLUGIN (self),
                                                                 modem,
                                                                 probe,
                                                                 &inner_error);
            else
                grabbed = mm_base_modem_grab_port (modem,
                                                   mm_port_probe_get_port_subsys (probe),
                                                   mm_port_probe_get_port_name (probe),
                                                   mm_port_probe_get_port_type (probe),
                                                   MM_AT_PORT_FLAG_NONE,
                                                   &inner_error);
            if (!grabbed) {
                mm_warn ("Could not grab port (%s/%s): '%s'",
                         mm_port_probe_get_port_subsys (MM_PORT_PROBE (l->data)),
                         mm_port_probe_get_port_name (MM_PORT_PROBE (l->data)),
                         inner_error ? inner_error->message : "unknown error");
                g_clear_error (&inner_error);
            }
        }

        /* If organizing ports fails, consider the modem invalid */
        if (!mm_base_modem_organize_ports (modem, error))
            g_clear_object (&modem);
    }

    return modem;
}
Пример #12
0
static gboolean spectool_channel_mouse_move(GtkWidget *widget,
										GdkEventMotion *event,
										gpointer *aux) {
	int x, y;
	int ch;
	GdkModifierType state;
	SpectoolChannel *channel;
	SpectoolWidget *wwidget;
	GList *upd_iter;

	g_return_if_fail(aux != NULL);
	g_return_if_fail(IS_SPECTOOL_CHANNEL(aux));
	g_return_if_fail(IS_SPECTOOL_WIDGET(aux));

	channel = SPECTOOL_CHANNEL(aux);
	wwidget = SPECTOOL_WIDGET(aux);

	g_return_if_fail(wwidget->sweepcache != NULL);
	g_return_if_fail(wwidget->sweepcache->latest != NULL);

	if (event->is_hint) {
		gdk_window_get_pointer(event->window, &x, &y, &state);
	} else {
		x = (int) event->x;
		y = (int) event->y;
		state = event->state;
	}

	/* Search for the channel positions, update the graph if we've changed
	 * the highlighted channel */
	g_return_if_fail(wwidget->chanopts != NULL);
	g_return_if_fail(wwidget->chanopts->chanset != NULL);

	if ((ch = spectool_channel_find_chan_pt(channel, x, y)) >= -1) {
		if (ch != wwidget->chanopts->hi_chan) {
			wwidget->chanopts->hi_chan = ch;
			spectool_widget_update(GTK_WIDGET(wwidget));

			upd_iter = channel->update_list;
			while (upd_iter != NULL) {
				spectool_widget_update(GTK_WIDGET(upd_iter->data));

				upd_iter = g_list_next(upd_iter);
				continue;
			}
		}
	} else if (wwidget->chanopts->hi_chan > -1) {
		wwidget->chanopts->hi_chan = -1;
		spectool_widget_update(GTK_WIDGET(wwidget));

		upd_iter = channel->update_list;
		while (upd_iter != NULL) {
			spectool_widget_update(GTK_WIDGET(upd_iter->data));

			upd_iter = g_list_next(upd_iter);
			continue;
		}
	}

	return TRUE;
}
Пример #13
0
static int
FontSave (int argc, char **argv, Coord Ux, Coord Uy)
{
  FontType *font;
  SymbolType *symbol;
  int i;
  GList *ii;
  LayerType *lfont, *lwidth;

  font = &PCB->Font;
  lfont = PCB->Data->Layer + 0;
  lwidth = PCB->Data->Layer + 2;

  for (i = 0; i <= MAX_FONTPOSITION; i++)
    {
      font->Symbol[i].LineN = 0;
      font->Symbol[i].Valid = 0;
      font->Symbol[i].Width = 0;
    }

  for (ii = lfont->Line; ii != NULL; ii = g_list_next (ii))
    {
      LineType *l = ii->data;
      int x1 = l->Point1.X;
      int y1 = l->Point1.Y;
      int x2 = l->Point2.X;
      int y2 = l->Point2.Y;
      int ox, oy, s;

      s = XYtoSym (x1, y1);
      ox = (s % 16 + 1) * CELL_SIZE;
      oy = (s / 16 + 1) * CELL_SIZE;
      symbol = &PCB->Font.Symbol[s];

      x1 -= ox;
      y1 -= oy;
      x2 -= ox;
      y2 -= oy;

      if (symbol->Width < x1)
	symbol->Width = x1;
      if (symbol->Width < x2)
	symbol->Width = x2;
      symbol->Valid = 1;

      CreateNewLineInSymbol (symbol, x1, y1, x2, y2, l->Thickness);
    }

  for (ii = lwidth->Line; ii != NULL; ii = g_list_next (ii))
    {
      LineType *l = ii->data;
      Coord x1 = l->Point1.X;
      Coord y1 = l->Point1.Y;
      Coord ox, s;

      s = XYtoSym (x1, y1);
      ox = (s % 16 + 1) * CELL_SIZE;
      symbol = &PCB->Font.Symbol[s];

      x1 -= ox;

      symbol->Delta = x1 - symbol->Width;
    }

  SetFontInfo (font);
  
  return 0;
}
Пример #14
0
/**
 * gegl_graph_process:
 * @path: The traversal path
 * 
 * Process the prepared request. This will return the
 * resulting buffer from the final node, or NULL if
 * that node is a sink.
 *
 * If gegl_graph_prepare_request has not been called
 * the behavior of this function is undefined.
 *
 * Return value: (transfer full): The result of the graph, or NULL if
 * there is no output pad.
 */
GeglBuffer *
gegl_graph_process (GeglGraphTraversal *path,
                    gint                level)
{
  GList *list_iter = NULL;
  GeglBuffer *result = NULL;
  GeglOperationContext *context = NULL;
  GeglOperationContext *last_context = NULL;
  GeglBuffer *operation_result = NULL;

  for (list_iter = path->dfs_path; list_iter; list_iter = list_iter->next)
    {
      GeglNode *node = GEGL_NODE (list_iter->data);
      GeglOperation *operation = node->operation;
      g_return_val_if_fail (node, NULL);
      g_return_val_if_fail (operation, NULL);
      
      GEGL_INSTRUMENT_START();

      operation_result = NULL;

      if (last_context)
        gegl_operation_context_purge (last_context);
      
      context = g_hash_table_lookup (path->contexts, node);
      g_return_val_if_fail (context, NULL);

      GEGL_NOTE (GEGL_DEBUG_PROCESS,
                 "Will process %s result_rect = %d, %d %d×%d",
                 gegl_node_get_debug_name (node),
                 context->result_rect.x, context->result_rect.y, context->result_rect.width, context->result_rect.height);
      
      if (context->need_rect.width > 0 && context->need_rect.height > 0)
        {
          if (context->cached)
            {
              GEGL_NOTE (GEGL_DEBUG_PROCESS,
                         "Using cached result for %s",
                         gegl_node_get_debug_name (node));
              operation_result = GEGL_BUFFER (node->cache);
            }
          else
            {
              /* Guarantee input pad */
              if (gegl_node_has_pad (node, "input") &&
                  !gegl_operation_context_get_object (context, "input"))
                {
                  gegl_operation_context_set_object (context, "input", G_OBJECT (gegl_graph_get_shared_empty(path)));
                }

              context->level = level;
              gegl_operation_process (operation, context, "output", &context->need_rect, context->level);
              operation_result = GEGL_BUFFER (gegl_operation_context_get_object (context, "output"));

              if (operation_result && operation_result == (GeglBuffer *)operation->node->cache)
                gegl_cache_computed (operation->node->cache, &context->need_rect, level);
            }
        }
      else
        {
          operation_result = NULL;
        }

      if (operation_result)
        {
          GeglPad *output_pad = gegl_node_get_pad (node, "output");
          GList   *targets = gegl_graph_get_connected_output_contexts (path, output_pad);
          GList   *targets_iter;

          GEGL_NOTE (GEGL_DEBUG_PROCESS,
                     "Will deliver the results of %s:%s to %d targets",
                     gegl_node_get_debug_name (node),
                     "output",
                     g_list_length (targets));
          
          if (g_list_length (targets) > 1)
            gegl_object_set_has_forked (G_OBJECT (operation_result));

          for (targets_iter = targets; targets_iter; targets_iter = g_list_next (targets_iter))
            {
              ContextConnection *target_con = targets_iter->data;
              gegl_operation_context_set_object (target_con->context, target_con->name, G_OBJECT (operation_result));
            }
          
          g_list_free_full (targets, free_context_connection);
        }
      
      last_context = context;

      GEGL_INSTRUMENT_END ("process", gegl_node_get_operation (node));
    }
  
  if (last_context)
    {
      if (operation_result)
        result = g_object_ref (operation_result);
      else if (gegl_node_has_pad (last_context->operation->node, "output"))
        result = g_object_ref (gegl_graph_get_shared_empty (path));
      gegl_operation_context_purge (last_context);
    }

  return result;
}
Пример #15
0
static void 
iprovider_populate (IAnjutaProvider *obj, IAnjutaIterable* iter, GError **err)
{
	static GList *trash = NULL;
	JSLang *plugin = (JSLang*)obj;

	if (plugin->last) {
		g_object_unref (plugin->last);
	}

        plugin->last = ianjuta_iterable_clone(iter, NULL);

	if (!plugin->current_editor)
		return;
	gint depth;
	GList *suggestions = NULL;
	gchar *str = code_completion_get_str (IANJUTA_EDITOR (plugin->current_editor), FALSE);

	if (trash)
	{
		g_list_foreach (trash, (GFunc)g_free, NULL);
		g_list_free (trash);
		trash = NULL;
	}

	if (!str)
		return;

	g_assert (plugin->prefs);

	if (strlen (str) < g_settings_get_int (plugin->prefs, MIN_CODECOMPLETE))
	{
		ianjuta_editor_assist_proposals ( IANJUTA_EDITOR_ASSIST (plugin->current_editor), obj,  NULL,  TRUE, NULL);
		return;
	}

	gchar *file = file_completion (IANJUTA_EDITOR (plugin->current_editor), &depth);
	gint i;
	DEBUG_PRINT ("JSLang: Auto complete for %s (TMFILE=%s)", str, file);
	for (i = strlen (str) - 1; i; i--)
	{
		if (str[i] == '.')
			break;
	}
	if (i > 0)
	{
		suggestions = code_completion_get_list (plugin, file, g_strndup (str, i), depth);
	}
	else
		suggestions = code_completion_get_list (plugin, file, NULL, depth);
	if (suggestions)
	{
		GList *nsuggest = NULL;
                gint k;
		if (i > 0)
		{
			suggestions = filter_list (suggestions, str + i + 1);
			k = strlen (str + i + 1);
		} else
		{
			suggestions = filter_list (suggestions, str);
			k = strlen (str);
		}
		GList *i;
		for (; k > 0; k--)
			ianjuta_iterable_previous (plugin->last, NULL);

		for (i = suggestions; i; i = g_list_next(i)) {
			IAnjutaEditorAssistProposal* proposal = g_new0(IAnjutaEditorAssistProposal, 1);

			if (!i->data)
				continue;
	
			proposal->label = i->data;
			proposal->data = i->data;
			nsuggest = g_list_prepend (nsuggest, proposal);
		}
		ianjuta_editor_assist_proposals ( IANJUTA_EDITOR_ASSIST (plugin->current_editor), obj,  nsuggest,  TRUE, NULL);
		g_list_free (nsuggest);
                trash = suggestions;
		return;
	}
	ianjuta_editor_assist_proposals ( IANJUTA_EDITOR_ASSIST (plugin->current_editor), obj,  NULL,  TRUE, NULL);
}
Пример #16
0
/** Create a Transaction from a TransPropertyList.
 * @param list The list of properties
 * @param error Contains an error on failure
 * @return On success, a GncCsvTransLine; on failure, the trans pointer is NULL
 */
static GncCsvTransLine* trans_property_list_to_trans(TransPropertyList* list, gchar** error)
{
    GncCsvTransLine* trans_line = g_new(GncCsvTransLine, 1);
    GList* properties_begin = list->properties;
    QofBook* book = gnc_account_get_book(list->account);
    gnc_commodity* currency = xaccAccountGetCommodity(list->account);
    gnc_numeric amount = double_to_gnc_numeric(0.0, xaccAccountGetCommoditySCU(list->account),
                         GNC_HOW_RND_ROUND_HALF_UP);
    gchar *num = NULL;

    /* This flag is set to TRUE if we can use the "Deposit" or "Withdrawal" column. */
    gboolean amount_set = FALSE;

    /* The balance is 0 by default. */
    trans_line->balance_set = FALSE;
    trans_line->balance = amount;
    trans_line->num = NULL;

    /* We make the line_no -1 just to mark that it hasn't been set. We
     * may get rid of line_no soon anyway, so it's not particularly
     * important. */
    trans_line->line_no = -1;

    /* Make sure this is a transaction with all the columns we need. */
    if (!trans_property_list_verify_essentials(list, error))
    {
        g_free(trans_line);
        return NULL;
    }

    trans_line->trans = xaccMallocTransaction(book);
    xaccTransBeginEdit(trans_line->trans);
    xaccTransSetCurrency(trans_line->trans, currency);

    /* Go through each of the properties and edit the transaction accordingly. */
    list->properties = properties_begin;
    while (list->properties != NULL)
    {
        TransProperty* prop = (TransProperty*)(list->properties->data);
        switch (prop->type)
        {
        case GNC_CSV_DATE:
            xaccTransSetDatePostedSecsNormalized(trans_line->trans, *((time64*)(prop->value)));
            break;

        case GNC_CSV_DESCRIPTION:
            xaccTransSetDescription(trans_line->trans, (char*)(prop->value));
            break;

        case GNC_CSV_NOTES:
            xaccTransSetNotes(trans_line->trans, (char*)(prop->value));
            break;

        case GNC_CSV_NUM:
            /* the 'num' is saved and passed to 'trans_add_split' below where
             * 'gnc_set_num_action' is used to set tran-num and/or split-action
             * per book option */
            num = g_strdup ((char*)(prop->value));
            /* the 'num' is also saved and used in 'gnc_csv_parse_to_trans' when
             * it calls 'trans_add_split' after deleting the splits added below
             * when a balance is used by the user */
            trans_line->num = g_strdup ((char*)(prop->value));
            break;

        case GNC_CSV_DEPOSIT: /* Add deposits to the existing amount. */
            if (prop->value != NULL)
            {
                amount = gnc_numeric_add(*((gnc_numeric*)(prop->value)),
                                         amount,
                                         xaccAccountGetCommoditySCU(list->account),
                                         GNC_HOW_RND_ROUND_HALF_UP);
                amount_set = TRUE;
                /* We will use the "Deposit" and "Withdrawal" columns in preference to "Balance". */
                trans_line->balance_set = FALSE;
            }
            break;

        case GNC_CSV_WITHDRAWAL: /* Withdrawals are just negative deposits. */
            if (prop->value != NULL)
            {
                amount = gnc_numeric_add(gnc_numeric_neg(*((gnc_numeric*)(prop->value))),
                                         amount,
                                         xaccAccountGetCommoditySCU(list->account),
                                         GNC_HOW_RND_ROUND_HALF_UP);
                amount_set = TRUE;
                /* We will use the "Deposit" and "Withdrawal" columns in preference to "Balance". */
                trans_line->balance_set = FALSE;
            }
            break;

        case GNC_CSV_BALANCE: /* The balance gets stored in a separate field in trans_line. */
            /* We will use the "Deposit" and "Withdrawal" columns in preference to "Balance". */
            if (!amount_set && prop->value != NULL)
            {
                /* This gets put into the actual transaction at the end of gnc_csv_parse_to_trans. */
                trans_line->balance = *((gnc_numeric*)(prop->value));
                trans_line->balance_set = TRUE;
            }
            break;
        }
        list->properties = g_list_next(list->properties);
    }

    /* Add a split with the cumulative amount value. */
    trans_add_split(trans_line->trans, list->account, book, amount, num);
    if (num)
        g_free(num);

    return trans_line;
}
Пример #17
0
static GList *
process_boundaries_finish(GList *boundaries_list)
{
	GList *l,*sl;
	GList *ret=NULL;
	l=boundaries_list;
	while (l) {
		struct boundary *boundary=l->data;
		int first=1;
		FILE *f=NULL,*fu=NULL;
		if (boundary->country) {
			char *name=g_strdup_printf("country_%s_poly",boundary->iso2);
			f=tempfile("",name,1);
			g_free(name);
		}
		boundary->sorted_segments=geom_poly_segments_sort(boundary->segments, geom_poly_segment_type_way_right_side);
		sl=boundary->sorted_segments;
		while (sl) {
			struct geom_poly_segment *gs=sl->data;
			struct coord *c=gs->first;
			while (c <= gs->last) {
				if (first) {
					boundary->r.l=*c;
					boundary->r.h=*c;
					first=0;
				} else
					bbox_extend(c, &boundary->r);
				c++;
			}
			if (f) {
				struct item_bin *ib=tmp_item_bin;
				item_bin_init(ib, type_selected_line);
				item_bin_add_coord(ib, gs->first, gs->last-gs->first+1);
				item_bin_write(ib, f);
			}
			if (boundary->country) {
				if (!coord_is_equal(*gs->first,*gs->last)) {
					struct item_bin *ib;
					if (!fu) {
						char *name=g_strdup_printf("country_%s_broken",boundary->iso2);
						fu=tempfile("",name,1);
						g_free(name);
					}
					ib=tmp_item_bin;
					item_bin_init(ib, type_selected_point);
					item_bin_add_coord(ib, gs->first, 1);
					item_bin_write(ib, fu);
					item_bin_init(ib, type_selected_point);
					item_bin_add_coord(ib, gs->last, 1);
					item_bin_write(ib, fu);
				}
			}
			sl=g_list_next(sl);
		}	
		ret=process_boundaries_insert(ret, boundary);
		l=g_list_next(l);
		if (f) 
			fclose(f);
		if (fu) {
			if (boundary->country)
				osm_warning("relation",item_bin_get_relationid(boundary->ib),0,"Broken country polygon '%s'\n",boundary->iso2);
			fclose(fu);
		}
		
	}
#if 0
	printf("hierarchy\n");
#endif
#if 0
	boundaries_list=g_list_sort(boundaries_list, boundary_bbox_compare);
	l=boundaries_list;
	while (l) {
		struct boundary *boundary=l->data;
		GList *l2,*ln;
		ln=l2=g_list_next(l);
		while (l2) {
			struct boundary *boundary2=l2->data;
			if (bbox_contains_bbox(&boundary2->r, &boundary->r)) {
				boundaries_list=g_list_remove(boundaries_list, boundary);
				boundary2->children=g_list_append(boundary2->children, boundary);
#if 0
				printf("found\n");
#endif
				break;
			}
			l2=g_list_next(l2);
		}
		l=ln;
	}
	dump_hierarchy(boundaries_list,"");
#if 0
	printf("hierarchy done\n");
	printf("test\n");
	test(boundaries_list);
#endif
#endif
	return ret;
}
Пример #18
0
/*! \brief Find page hierarchy below a page.
 *  \par Function Description
 *  This function traverses the hierarchy tree of pages and returns a
 *  flat list of pages that are below \a p_current. There are two \a
 *  flags that can be used to control the way that the return value is
 *  constructed: <B>HIERARCHY_NODUPS</B> returns a list without
 *  duplicate pages, and <B>HIERARCHY_POSTORDER</B> traverses the
 *  hierarchy tree and returns a postorder list instead of preorder.
 *
 *  \param toplevel The TOPLEVEL structure.
 *  \param p_current The PAGE to traverse hierarchy for.
 *  \param flags Flags controlling form of return value.
 *  \return A GList of PAGE pointers.
 *
 *  \warning
 *  Caller must destroy returned GList with g_list_free().
 */
GList *
s_hierarchy_traversepages (TOPLEVEL *toplevel, PAGE *p_current, gint flags)
{
  OBJECT *o_current;
  PAGE *child_page;
  char *filename = NULL;
  static GList *pages = NULL;
  const GList *iter;

  g_return_val_if_fail ((toplevel != NULL), NULL);
  g_return_val_if_fail ((p_current != NULL), NULL);

  /* init static variables the first time*/
  if (!(flags & HIERARCHY_INNERLOOP)) {
    pages = NULL;
  }

  /* preorder traversing */
  if (!(flags & HIERARCHY_POSTORDER)) {
    /* check whether we already visited this page */
    if ((flags & HIERARCHY_NODUPS)
        && (g_list_find (pages, p_current) != NULL)) {
      return pages;  /* drop the page subtree */
      }
    pages = g_list_append (pages, p_current);
  }

  /* walk throught the page objects and search for underlaying schematics */
  for (iter = s_page_objects (p_current);
       iter != NULL ;
       iter = g_list_next (iter)) {
    o_current = (OBJECT *)iter->data;

    /* only complex things like symbols can contain attributes */
    if (o_current->type != OBJ_COMPLEX) continue;

    filename =
      o_attrib_search_attached_attribs_by_name (o_current, "source", 0);

    /* if above is NULL, then look inside symbol */
    if (filename == NULL) {
      filename =
        o_attrib_search_inherited_attribs_by_name (o_current, "source", 0);
    }

    if (filename == NULL) continue;

    /* we got a schematic source attribute
       lets load the page and dive into it */
    GError *err = NULL;
    child_page =
      s_hierarchy_down_schematic_single (toplevel, filename, p_current, 0,
                                         HIERARCHY_NORMAL_LOAD, &err);
    if (child_page != NULL) {
      /* call the recursive function */
      s_hierarchy_traversepages (toplevel, child_page, flags | HIERARCHY_INNERLOOP);
    } else {
      s_log_message (_("Failed to descend hierarchy into '%s': %s\n"),
                     filename, err->message);
      g_error_free (err);
    }

    g_free (filename);
    filename = NULL;
  }

  /* postorder traversing */
  if (flags & HIERARCHY_POSTORDER) {
    /* check whether we already visited this page */
    if ((flags & HIERARCHY_NODUPS)
        && (g_list_find (pages, p_current) != NULL)) {
      return pages;  /* don't append it */
    }
    pages = g_list_append (pages, p_current);
  }

  return pages;
}
Пример #19
0
static GList*
fs_rtp_dtmf_event_source_class_add_blueprint (FsRtpSpecialSourceClass *klass,
        GList *blueprints)
{
    GList *item;
    GList *already_done = NULL;
    GstElementFactory *fact = NULL;
    GList *new_blueprints = NULL;

    fact = gst_element_factory_find ("rtpdtmfsrc");
    if (fact)
    {
        gst_object_unref (fact);
    }
    else
    {
        GST_CAT_WARNING (fsrtpconference_disco,
                         "Could not find rtpdtmfsrc, will not offer DTMF events");
        return blueprints;
    }

    fact = gst_element_factory_find ("rtpdtmfdepay");
    if (!fact)
        GST_CAT_WARNING (fsrtpconference_disco,
                         "Could not find rtpdtmfdepay, will not be able to receive DTMF events");

    for (item = g_list_first (blueprints);
            item;
            item = g_list_next (item))
    {
        CodecBlueprint *bp = item->data;
        GList *done_item = NULL;
        gboolean skip = FALSE;
        CodecBlueprint *new_bp = NULL;

        if (bp->codec->media_type != FS_MEDIA_TYPE_AUDIO)
            continue;

        if (!g_ascii_strcasecmp (bp->codec->encoding_name, "telephone-event"))
            continue;

        if (bp->codec->clock_rate == 0)
            continue;

        for (done_item = g_list_first (already_done);
                done_item;
                done_item = g_list_next (done_item))
        {
            if (GPOINTER_TO_UINT (done_item->data) == bp->codec->clock_rate)
            {
                skip = TRUE;
                break;
            }
        }
        if (skip)
            continue;

        new_bp = g_slice_new0 (CodecBlueprint);

        new_bp->codec = fs_codec_new (FS_CODEC_ID_ANY, "telephone-event",
                                      FS_MEDIA_TYPE_AUDIO, bp->codec->clock_rate);
        fs_codec_add_optional_parameter (new_bp->codec, "events", "0-15");
        new_bp->rtp_caps = fs_codec_to_gst_caps (new_bp->codec);
        new_bp->media_caps = gst_caps_new_any ();

        if (fact)
            new_bp->receive_pipeline_factory = g_list_prepend (NULL,
                                               g_list_prepend (NULL, gst_object_ref (fact)));

        new_blueprints = g_list_append (new_blueprints, new_bp);

        already_done = g_list_prepend (already_done,
                                       GUINT_TO_POINTER (bp->codec->clock_rate));
    }

    if (fact)
        gst_object_unref (fact);

    g_list_free (already_done);

    blueprints = g_list_concat (blueprints, new_blueprints);

    return blueprints;
}
Пример #20
0
void
read_connections(GList *objects, xmlNodePtr layer_node,
		 GHashTable *objects_hash)
{
  ObjectNode obj_node;
  GList *list;
  xmlNodePtr connections;
  xmlNodePtr connection;
  char *handlestr;
  char *tostr;
  char *connstr;
  int handle, conn;
  Object *to;
  
  list = objects;
  obj_node = layer_node->childs;
  while (list != NULL) {
    Object *obj = (Object *) list->data;

    if IS_GROUP(obj) {
      read_connections(group_objects(obj), obj_node, objects_hash);
    } else {
      connections = obj_node->childs;
      while ((connections!=NULL) &&
	     (strcmp(connections->name, "connections")!=0))
	connections = connections->next;
      if (connections != NULL) {
	connection = connections->childs;
	while (connection != NULL) {
	  handlestr = xmlGetProp(connection, "handle");
	  tostr = xmlGetProp(connection, "to");
	  connstr = xmlGetProp(connection, "connection");
	  
	  handle = atoi(handlestr);
	  conn = atoi(connstr);
	  
	  to = g_hash_table_lookup(objects_hash, tostr);

	  if (handlestr) free(handlestr);
	  if (connstr) free(connstr);
	  if (tostr) free(tostr);

	  if (to == NULL) {
	    message_error(_("Error loading diagram.\n"
			    "Linked object not found in document."));
	  } else if (conn >= 0 && conn >= to->num_connections) {
	    message_error(_("Error loading diagram.\n"
			    "connection point does not exist."));
	  } else if (handle >= 0 && handle >= obj->num_handles) {
	    message_error(_("Error loading diagram.\n"
			    "connection handle does not exist."));
	  } else {
	    object_connect(obj, obj->handles[handle],
			   to->connections[conn]);
	  }

	  connection = connection->next;
	}
      }
      
    }
    
    list = g_list_next(list);
    obj_node = obj_node->next;
  }
Пример #21
0
static GstFlowReturn
mpegtsmux_collected (GstCollectPads2 * pads, MpegTsMux * mux)
{
  GstFlowReturn ret = GST_FLOW_OK;
  MpegTsPadData *best = NULL;

  GST_DEBUG_OBJECT (mux, "Pads collected");

  if (G_UNLIKELY (mux->first)) {
    ret = mpegtsmux_create_streams (mux);
    if (G_UNLIKELY (ret != GST_FLOW_OK))
      return ret;

    mpegtsdemux_prepare_srcpad (mux);

    mux->first = FALSE;
  }

  best = mpegtsmux_choose_best_stream (mux);

  if (best != NULL) {
    TsMuxProgram *prog = best->prog;
    GstBuffer *buf = best->queued_buf;
    gint64 pts = -1;
    gboolean delta = TRUE;

    if (prog == NULL) {
      GST_ELEMENT_ERROR (mux, STREAM, MUX,
          ("Stream on pad %" GST_PTR_FORMAT
              " is not associated with any program", COLLECT_DATA_PAD (best)),
          (NULL));
      return GST_FLOW_ERROR;
    }

    if (mux->force_key_unit_event != NULL && best->stream->is_video_stream) {
      GstEvent *event;

      event = check_pending_key_unit_event (mux->force_key_unit_event,
          &best->collect.segment, GST_BUFFER_TIMESTAMP (buf),
          GST_BUFFER_FLAGS (buf), mux->pending_key_unit_ts);
      if (event) {
        GstClockTime running_time;
        guint count;
        GList *cur;

        mux->pending_key_unit_ts = GST_CLOCK_TIME_NONE;
        gst_event_replace (&mux->force_key_unit_event, NULL);

        gst_video_event_parse_downstream_force_key_unit (event,
            NULL, NULL, &running_time, NULL, &count);

        GST_INFO_OBJECT (mux, "pushing downstream force-key-unit event %d "
            "%" GST_TIME_FORMAT " count %d", gst_event_get_seqnum (event),
            GST_TIME_ARGS (running_time), count);
        gst_pad_push_event (mux->srcpad, event);

        /* output PAT */
        mux->tsmux->last_pat_ts = -1;

        /* output PMT for each program */
        for (cur = g_list_first (mux->tsmux->programs); cur != NULL;
            cur = g_list_next (cur)) {
          TsMuxProgram *program = (TsMuxProgram *) cur->data;

          program->last_pmt_ts = -1;
        }
        tsmux_program_set_pcr_stream (prog, NULL);
      }
    }

    if (G_UNLIKELY (prog->pcr_stream == NULL)) {
      /* Take the first data stream for the PCR */
      GST_DEBUG_OBJECT (COLLECT_DATA_PAD (best),
          "Use stream (pid=%d) from pad as PCR for program (prog_id = %d)",
          MPEG_TS_PAD_DATA (best)->pid, MPEG_TS_PAD_DATA (best)->prog_id);

      /* Set the chosen PCR stream */
      tsmux_program_set_pcr_stream (prog, best->stream);
    }

    g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
    if (best->stream->is_video_stream)
      delta = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
    GST_DEBUG_OBJECT (mux, "delta: %d", delta);

    GST_DEBUG_OBJECT (COLLECT_DATA_PAD (best),
        "Chose stream for output (PID: 0x%04x)", best->pid);

    if (GST_CLOCK_TIME_IS_VALID (best->cur_ts)) {
      pts = GSTTIME_TO_MPEGTIME (best->cur_ts);
      GST_DEBUG_OBJECT (mux, "Buffer has TS %" GST_TIME_FORMAT " pts %"
          G_GINT64_FORMAT, GST_TIME_ARGS (best->cur_ts), pts);
    }

    tsmux_stream_add_data (best->stream, GST_BUFFER_DATA (buf),
        GST_BUFFER_SIZE (buf), buf, pts, -1, !delta);
    best->queued_buf = NULL;

    mux->is_delta = delta;
    while (tsmux_stream_bytes_in_buffer (best->stream) > 0) {
      if (!tsmux_write_stream_packet (mux->tsmux, best->stream)) {
        /* Failed writing data for some reason. Set appropriate error */
        GST_DEBUG_OBJECT (mux, "Failed to write data packet");
        GST_ELEMENT_ERROR (mux, STREAM, MUX,
            ("Failed writing output data to stream %04x", best->stream->id),
            (NULL));
        goto write_fail;
      }
    }
    if (prog->pcr_stream == best->stream) {
      mux->last_ts = best->last_ts;
    }
  } else {
    /* FIXME: Drain all remaining streams */
    /* At EOS */
    gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
  }

  return ret;
write_fail:
  return mux->last_flow_ret;
}
Пример #22
0
/*
* Print address folder item.
*/
void addritem_print_item_folder( ItemFolder *folder, FILE *stream ) {
	GList *node;
	/* ItemPerson *person; */
	ItemFolder *parent;

	g_return_if_fail( folder != NULL );

	fprintf( stream, "Folder:\n" );
	fprintf( stream, "\tt/u: %d : '%s'\n", ADDRITEM_TYPE(folder), ADDRITEM_ID(folder) );
	fprintf( stream, "\tsub: %d\n", ADDRITEM_SUBTYPE(folder) );
	fprintf( stream, "\tnam: '%s'\n", ADDRITEM_NAME(folder) );
	fprintf( stream, "\trem: '%s'\n", folder->remarks );
	fprintf( stream, "\t---\n" );
	parent = ( ItemFolder * ) ADDRITEM_PARENT(folder);
	if( parent ) {
		fprintf( stream, "\tpar: %s : %s\n", ADDRITEM_ID(parent), ADDRITEM_NAME(parent) );
	}
	else {
		fprintf( stream, "\tpar: NULL\n" );
	}
	node = folder->listFolder;
	while( node ) {
		AddrItemObject *aio = node->data;
		if( aio ) {
			if( aio->type == ITEMTYPE_FOLDER ) {
				ItemFolder *item = ( ItemFolder * ) aio;
				addritem_print_item_folder( item, stream );
			}
		}
		else {
			fprintf( stream, "\t\tpid : ???\n" );
		}

		node = g_list_next( node );
	}

	node = folder->listPerson;
	while( node ) {
		AddrItemObject *aio = node->data;
		if( aio ) {
			if( aio->type == ITEMTYPE_PERSON ) {
				ItemPerson *item = ( ItemPerson * ) aio;
				addritem_print_item_person( item, stream );
			}
		}
		else {
			fprintf( stream, "\t\tpid : ???\n" );
		}

		node = g_list_next( node );
	}

	node = folder->listGroup;
	while( node ) {
		AddrItemObject *aio = node->data;
		if( aio ) {
			if( aio->type == ITEMTYPE_GROUP ) {
				ItemGroup *item = ( ItemGroup * ) aio;
				addritem_print_item_group( item, stream );
			}
		}
		else {
			fprintf( stream, "\t\tpid : ???\n" );
		}
		node = g_list_next( node );
	}
	fprintf( stream, "\t###\n" );
}
Пример #23
0
static gint
lua_util_tokenize_text (lua_State *L)
{
	const gchar *in = NULL;
	gsize len, pos, ex_len, i;
	GList *exceptions = NULL, *cur;
	struct rspamd_lua_text *t;
	struct process_exception *ex;
	GArray *res;
	rspamd_fstring_t *w;
	gboolean compat = FALSE;

	if (lua_type (L, 1) == LUA_TSTRING) {
		in = luaL_checklstring (L, 1, &len);
	}
	else if (lua_type (L, 1) == LUA_TTABLE) {
		t = lua_check_text (L, 1);

		if (t) {
			in = t->start;
			len = t->len;
		}
	}

	if (in == NULL) {
		lua_pushnil (L);
		return 1;
	}

	if (lua_gettop (L) > 1 && lua_type (L, 2) == LUA_TTABLE) {
		lua_pushvalue (L, 2);
		lua_pushnil (L);

		while (lua_next (L, -2) != 0) {
			if (lua_type (L, -1) == LUA_TTABLE) {
				lua_rawgeti (L, -1, 1);
				pos = luaL_checknumber (L, -1);
				lua_pop (L, 1);
				lua_rawgeti (L, -1, 2);
				ex_len = luaL_checknumber (L, -1);
				lua_pop (L, 1);

				if (ex_len > 0) {
					ex = g_slice_alloc (sizeof (*ex));
					ex->pos = pos;
					ex->len = ex_len;
					exceptions = g_list_prepend (exceptions, ex);
				}
			}
			lua_pop (L, 1);
		}

		lua_pop (L, 1);
	}

	if (lua_gettop (L) > 2 && lua_type (L, 3) == LUA_TBOOLEAN) {
		compat = lua_toboolean (L, 3);
	}

	if (exceptions) {
		exceptions = g_list_reverse (exceptions);
	}

	res = rspamd_tokenize_text ((gchar *)in, len, TRUE, 0, exceptions, compat);

	if (res == NULL) {
		lua_pushnil (L);
	}
	else {
		lua_newtable (L);

		for (i = 0; i < res->len; i ++) {
			w = &g_array_index (res, rspamd_fstring_t, i);
			lua_pushlstring (L, w->begin, w->len);
			lua_rawseti (L, -2, i + 1);
		}
	}

	cur = exceptions;
	while (cur) {
		ex = cur->data;
		g_slice_free1 (sizeof (*ex), ex);
		cur = g_list_next (cur);
	}

	g_list_free (exceptions);

	return 1;
}
Пример #24
0
int
dt_history_copy_and_paste_on_image (int32_t imgid, int32_t dest_imgid, gboolean merge, GList *ops)
{
  sqlite3_stmt *stmt;
  if(imgid==dest_imgid) return 1;

  if(imgid==-1)
  {
    dt_control_log(_("you need to copy history from an image before you paste it onto another"));
    return 1;
  }

  /* if merge onto history stack, lets find history offest in destination image */
  int32_t offs = 0;
  if (merge)
  {
    /* apply on top of history stack */
    DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "SELECT MAX(num)+1 FROM history WHERE imgid = ?1", -1, &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid);
    if (sqlite3_step (stmt) == SQLITE_ROW) offs = sqlite3_column_int (stmt, 0);
  }
  else
  {
    /* replace history stack */
    DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "delete from history where imgid = ?1", -1, &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid);
    sqlite3_step (stmt);
  }
  sqlite3_finalize (stmt);

  //  prepare SQL request
  char req[2048];
  strcpy (req, "insert into history (imgid, num, module, operation, op_params, enabled, blendop_params, blendop_version, multi_name, multi_priority) select ?1, num+?2, module, operation, op_params, enabled, blendop_params, blendop_version, multi_name, multi_priority from history where imgid = ?3");

  //  Add ops selection if any format: ... and num in (val1, val2)
  if (ops)
  {
    GList *l = ops;
    int first = 1;
    strcat (req, " and num in (");

    while (l)
    {
      long unsigned int value = (long unsigned int)l->data;
      char v[30];

      if (!first) strcat (req, ",");
      snprintf (v, 30, "%lu", value);
      strcat (req, v);
      first=0;
      l = g_list_next(l);
    }
    strcat (req, ")");
  }

  /* add the history items to stack offest */
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), req, -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, offs);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 3, imgid);
  sqlite3_step (stmt);
  sqlite3_finalize (stmt);

  if (merge && ops)
    _dt_history_cleanup_multi_instance(dest_imgid, offs);

  //we have to copy masks too
  //what to do with existing masks ?
  if (merge)
  {
    //there's very little chance that we will have same shapes id.
    //but we may want to handle this case anyway
    //and it's not trivial at all !
  }
  else
  {
    //let's remove all existing shapes
    DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "delete from mask where imgid = ?1", -1, &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid);
    sqlite3_step (stmt);
    sqlite3_finalize (stmt);
  }

  //let's copy now
  strcpy (req, "insert into mask (imgid, formid, form, name, version, points, points_count, source) select ?1, formid, form, name, version, points, points_count, source from mask where imgid = ?2");
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), req, -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, imgid);
  sqlite3_step (stmt);
  sqlite3_finalize (stmt);
  
  /* if current image in develop reload history */
  if (dt_dev_is_current_image(darktable.develop, dest_imgid))
  {
    dt_dev_reload_history_items (darktable.develop);
    dt_dev_modulegroups_set(darktable.develop, dt_dev_modulegroups_get(darktable.develop));
  }

  /* update xmp file */
  dt_image_synch_xmp(dest_imgid);

  dt_mipmap_cache_remove(darktable.mipmap_cache, dest_imgid);

  return 0;
}
Пример #25
0
void dt_dev_reload_history_items(dt_develop_t *dev)
{
  dt_dev_pop_history_items(dev, 0);
  // remove unused history items:
  GList *history = g_list_nth(dev->history, dev->history_end);
  while(history)
  {
    GList *next = g_list_next(history);
    dt_dev_history_item_t *hist = (dt_dev_history_item_t *)(history->data);
    free(hist->params);
    free(hist->blend_params);
    free(history->data);
    dev->history = g_list_delete_link(dev->history, history);
    history = next;
  }
  dt_dev_read_history(dev);
  
  //we have to add new module instances first
  GList *modules = dev->iop;
  while(modules)
  {
    dt_iop_module_t *module = (dt_iop_module_t *)(modules->data);
    if (module->multi_priority > 0)
    {
      if (!dt_iop_is_hidden(module) && !module->expander)
      {
        module->gui_init(module);
        //we search the base iop corresponding
        GList *mods = g_list_first(dev->iop);
        dt_iop_module_t *base = NULL;
        int pos_module = 0;
        int pos_base = 0;
        int pos = 0;
        while (mods)
        {
          dt_iop_module_t *mod = (dt_iop_module_t *)(mods->data);
          if (mod->multi_priority == 0 && mod->instance == module->instance)
          {
            base = mod;
            pos_base = pos;
          }
          else if (mod == module) pos_module = pos;
          mods = g_list_next(mods);
          pos++;
        }
        if (!base) continue;
        
        /* add module to right panel */
        GtkWidget *expander = dt_iop_gui_get_expander(module);
        dt_ui_container_add_widget(darktable.gui->ui,
                                   DT_UI_CONTAINER_PANEL_RIGHT_CENTER, expander);
        GValue gv = G_VALUE_INIT;
        g_value_init(&gv,G_TYPE_INT);
        gtk_container_child_get_property(GTK_CONTAINER(dt_ui_get_container(darktable.gui->ui, DT_UI_CONTAINER_PANEL_RIGHT_CENTER)),base->expander,"position",&gv);
        gtk_box_reorder_child (dt_ui_get_container(darktable.gui->ui, DT_UI_CONTAINER_PANEL_RIGHT_CENTER),expander,g_value_get_int(&gv)+pos_base-pos_module);
        dt_iop_gui_set_expanded(module, TRUE);
        dt_iop_gui_update_blending(module);
        
        //the pipe need to be reconstruct
        dev->pipe->changed |= DT_DEV_PIPE_REMOVE;
        dev->preview_pipe->changed |= DT_DEV_PIPE_REMOVE;
      }
    }
    modules = g_list_next(modules);
  }

  dt_dev_pop_history_items(dev, dev->history_end);
}
Пример #26
0
static GstFlowReturn
gst_wavenc_write_toc (GstWavEnc * wavenc)
{
  GList *list;
  GstToc *toc;
  GstTocEntry *entry, *subentry;
  GstBuffer *buf;
  GstMapInfo map;
  guint8 *data;
  guint32 ncues, size, cues_size, labls_size, notes_size;

  if (!wavenc->toc) {
    GST_DEBUG_OBJECT (wavenc, "have no toc, checking toc_setter");
    wavenc->toc = gst_toc_setter_get_toc (GST_TOC_SETTER (wavenc));
  }
  if (!wavenc->toc) {
    GST_WARNING_OBJECT (wavenc, "have no toc");
    return GST_FLOW_OK;
  }

  toc = gst_toc_ref (wavenc->toc);
  size = 0;
  cues_size = 0;
  labls_size = 0;
  notes_size = 0;

  /* check if the TOC entries is valid */
  list = gst_toc_get_entries (toc);
  entry = list->data;
  if (gst_toc_entry_is_alternative (entry)) {
    list = gst_toc_entry_get_sub_entries (entry);
    while (list) {
      subentry = list->data;
      if (!gst_toc_entry_is_sequence (subentry))
        return FALSE;
      list = g_list_next (list);
    }
    list = gst_toc_entry_get_sub_entries (entry);
  }
  if (gst_toc_entry_is_sequence (entry)) {
    while (list) {
      entry = list->data;
      if (!gst_toc_entry_is_sequence (entry))
        return FALSE;
      list = g_list_next (list);
    }
    list = gst_toc_get_entries (toc);
  }

  ncues = g_list_length (list);
  GST_DEBUG_OBJECT (wavenc, "number of cue entries: %d", ncues);

  while (list) {
    guint32 id = 0;
    gint64 id64;
    const gchar *uid;

    entry = list->data;
    uid = gst_toc_entry_get_uid (entry);
    id64 = g_ascii_strtoll (uid, NULL, 0);
    /* check if id unique compatible with guint32 else generate random */
    if (id64 >= 0 && gst_wavenc_is_cue_id_unique (id64, wavenc->cues)) {
      id = (guint32) id64;
    } else {
      do {
        id = g_random_int ();
      } while (!gst_wavenc_is_cue_id_unique (id, wavenc->cues));
    }
    gst_wavenc_parse_cue (wavenc, id, entry);
    gst_wavenc_parse_labl (wavenc, id, entry);
    gst_wavenc_parse_note (wavenc, id, entry);
    list = g_list_next (list);
  }

  /* count cues size */
  if (wavenc->cues) {
    cues_size = 24 * g_list_length (wavenc->cues);
    size += 12 + cues_size;
  } else {
    GST_WARNING_OBJECT (wavenc, "cue's not found");
    return FALSE;
  }
  /* count labls size */
  if (wavenc->labls) {
    list = wavenc->labls;
    while (list) {
      GstWavEncLabl *labl;
      labl = list->data;
      labls_size += 8 + GST_ROUND_UP_2 (labl->chunk_data_size);
      list = g_list_next (list);
    }
    size += labls_size;
  }
  /* count notes size */
  if (wavenc->notes) {
    list = wavenc->notes;
    while (list) {
      GstWavEncNote *note;
      note = list->data;
      notes_size += 8 + GST_ROUND_UP_2 (note->chunk_data_size);
      list = g_list_next (list);
    }
    size += notes_size;
  }
  if (wavenc->labls || wavenc->notes) {
    size += 12;
  }

  buf = gst_buffer_new_and_alloc (size);
  gst_buffer_map (buf, &map, GST_MAP_WRITE);
  data = map.data;
  memset (data, 0, size);

  /* write Cue Chunk */
  if (wavenc->cues) {
    memcpy (data, (gchar *) "cue ", 4);
    GST_WRITE_UINT32_LE (data + 4, 4 + cues_size);
    GST_WRITE_UINT32_LE (data + 8, ncues);
    data += 12;
    gst_wavenc_write_cues (&data, wavenc->cues);

    /* write Associated Data List Chunk */
    if (wavenc->labls || wavenc->notes) {
      memcpy (data, (gchar *) "LIST", 4);
      GST_WRITE_UINT32_LE (data + 4, 4 + labls_size + notes_size);
      memcpy (data + 8, (gchar *) "adtl", 4);
      data += 12;
      if (wavenc->labls)
        gst_wavenc_write_labls (&data, wavenc->labls);
      if (wavenc->notes)
        gst_wavenc_write_notes (&data, wavenc->notes);
    }
  }

  /* free resources */
  if (toc)
    gst_toc_unref (toc);
  if (wavenc->cues)
    g_list_free_full (wavenc->cues, g_free);
  if (wavenc->labls)
    g_list_free_full (wavenc->labls, g_free);
  if (wavenc->notes)
    g_list_free_full (wavenc->notes, g_free);

  gst_buffer_unmap (buf, &map);
  wavenc->meta_length += gst_buffer_get_size (buf);

  return gst_pad_push (wavenc->srcpad, buf);
}
Пример #27
0
void vis_send_data(gint16 pcm_data[2][512], int nch, int length)
{
	GList *node = vp_data->enabled_list;
	VisPlugin *vp;
	gint16 mono_freq[2][256], stereo_freq[2][256];
	gboolean mono_freq_calced = FALSE, stereo_freq_calced = FALSE;
	gint16 mono_pcm[2][512], stereo_pcm[2][512];
	gboolean mono_pcm_calced = FALSE, stereo_pcm_calced = FALSE;
	gint8 intern_vis_data[512];
	gint i;

	if (!pcm_data || nch < 1)
	{
		if (cfg.vis_type != VIS_OFF)
		{
			if (cfg.player_shaded && cfg.player_visible)
				svis_timeout_func(mainwin_svis, NULL);
			else
				vis_timeout_func(active_vis, NULL);
		}
		return;
	}

	while (node)
	{
		vp = node->data;
		if (vp->num_pcm_chs_wanted > 0 && vp->render_pcm)
		{
			if (vp->num_pcm_chs_wanted == 1)
			{
				if (!mono_pcm_calced)
				{
					calc_mono_pcm(mono_pcm, pcm_data, nch);
					mono_pcm_calced = TRUE;
				}
				vp->render_pcm(mono_pcm);
			}
			else
			{
				if (!stereo_pcm_calced)
				{
					calc_stereo_pcm(stereo_pcm, pcm_data, nch);
					stereo_pcm_calced = TRUE;
				}
				vp->render_pcm(stereo_pcm);
			}
		}
		if (vp->num_freq_chs_wanted > 0 && vp->render_freq)
		{
			if (vp->num_freq_chs_wanted == 1)
			{
				if (!mono_freq_calced)
				{
					calc_mono_freq(mono_freq, pcm_data, nch);
					mono_freq_calced = TRUE;
				}
				vp->render_freq(mono_freq);
			}
			else
			{
				if (!stereo_freq_calced)
				{
					calc_stereo_freq(stereo_freq, pcm_data, nch);
					stereo_freq_calced = TRUE;
				}
				vp->render_freq(stereo_freq);
			}
		}
		node = g_list_next(node);
	}

	if (cfg.vis_type == VIS_OFF)
		return;

	if (cfg.vis_type == VIS_ANALYZER)
	{
		if (cfg.player_shaded && cfg.player_visible)
		{
			/* VU */
			gint vu ,val;

			if (!stereo_pcm_calced)
				calc_stereo_pcm(stereo_pcm, pcm_data, nch);
			vu = 0;
			for (i = 0; i < 512; i++)
			{
				val = abs(stereo_pcm[0][i]);
				if (val > vu)
					vu = val;
			}
			intern_vis_data[0] = (vu * 37) >> 15;
			if (intern_vis_data[0] > 37)
				intern_vis_data[0] = 37;
			if (nch == 2)
			{
				vu = 0;
				for (i = 0; i < 512; i++)
				{
					val = abs(stereo_pcm[1][i]);
					if (val > vu)
						vu = val;
				}
				intern_vis_data[1] = (vu * 37) >> 15;
				if (intern_vis_data[1] > 37)
					intern_vis_data[1] = 37;
			}
			else
Пример #28
0
gboolean
rspamd_client_command (struct rspamd_client_connection *conn,
		const gchar *command, GQueue *attrs,
		FILE *in, rspamd_client_callback cb,
		gpointer ud, gboolean compressed,
		const gchar *comp_dictionary,
		const gchar *filename,
		GError **err)
{
	struct rspamd_client_request *req;
	struct rspamd_http_client_header *nh;
	gchar *p;
	gsize remain, old_len;
	GList *cur;
	GString *input = NULL;
	rspamd_fstring_t *body;
	guint dict_id = 0;
	gsize dict_len = 0;
	void *dict = NULL;
	ZSTD_CCtx *zctx;

	req = g_malloc0 (sizeof (struct rspamd_client_request));
	req->conn = conn;
	req->cb = cb;
	req->ud = ud;

	req->msg = rspamd_http_new_message (HTTP_REQUEST);
	if (conn->key) {
		req->msg->peer_key = rspamd_pubkey_ref (conn->key);
	}

	if (in != NULL) {
		/* Read input stream */
		input = g_string_sized_new (BUFSIZ);

		while (!feof (in)) {
			p = input->str + input->len;
			remain = input->allocated_len - input->len - 1;
			if (remain == 0) {
				old_len = input->len;
				g_string_set_size (input, old_len * 2);
				input->len = old_len;
				continue;
			}
			remain = fread (p, 1, remain, in);
			if (remain > 0) {
				input->len += remain;
				input->str[input->len] = '\0';
			}
		}
		if (ferror (in) != 0) {
			g_set_error (err, RCLIENT_ERROR, ferror (
					in), "input IO error: %s", strerror (ferror (in)));
			g_free (req);
			g_string_free (input, TRUE);
			return FALSE;
		}

		if (!compressed) {
			body = rspamd_fstring_new_init (input->str, input->len);
		}
		else {
			if (comp_dictionary) {
				dict = rspamd_file_xmap (comp_dictionary, PROT_READ, &dict_len,
						TRUE);

				if (dict == NULL) {
					g_set_error (err, RCLIENT_ERROR, errno,
							"cannot open dictionary %s: %s",
							comp_dictionary,
							strerror (errno));
					g_free (req);
					g_string_free (input, TRUE);

					return FALSE;
				}

				dict_id = ZDICT_getDictID (comp_dictionary, dict_len);

				if (dict_id == 0) {
					g_set_error (err, RCLIENT_ERROR, errno,
							"cannot open dictionary %s: %s",
							comp_dictionary,
							strerror (errno));
					g_free (req);
					g_string_free (input, TRUE);
					munmap (dict, dict_len);

					return FALSE;
				}
			}

			body = rspamd_fstring_sized_new (ZSTD_compressBound (input->len));
			zctx = ZSTD_createCCtx ();
			body->len = ZSTD_compress_usingDict (zctx, body->str, body->allocated,
					input->str, input->len,
					dict, dict_len,
					1);

			munmap (dict, dict_len);

			if (ZSTD_isError (body->len)) {
				g_set_error (err, RCLIENT_ERROR, ferror (
						in), "compression error");
				g_free (req);
				g_string_free (input, TRUE);
				rspamd_fstring_free (body);
				ZSTD_freeCCtx (zctx);

				return FALSE;
			}

			ZSTD_freeCCtx (zctx);
		}

		rspamd_http_message_set_body_from_fstring_steal (req->msg, body);
		req->input = input;
	}
	else {
		req->input = NULL;
	}

	/* Convert headers */
	cur = attrs->head;
	while (cur != NULL) {
		nh = cur->data;

		rspamd_http_message_add_header (req->msg, nh->name, nh->value);
		cur = g_list_next (cur);
	}

	if (compressed) {
		rspamd_http_message_add_header (req->msg, "Compression", "zstd");

		if (dict_id != 0) {
			gchar dict_str[32];

			rspamd_snprintf (dict_str, sizeof (dict_str), "%ud", dict_id);
			rspamd_http_message_add_header (req->msg, "Dictionary", dict_str);
		}
	}

	if (filename) {
		rspamd_http_message_add_header (req->msg, "Filename", filename);
	}

	req->msg->url = rspamd_fstring_append (req->msg->url, "/", 1);
	req->msg->url = rspamd_fstring_append (req->msg->url, command, strlen (command));

	conn->req = req;
	conn->start_time = rspamd_get_ticks (FALSE);

	if (compressed) {
		rspamd_http_connection_write_message (conn->http_conn, req->msg, NULL,
				"application/x-compressed", req,
				&conn->timeout);
	}
	else {
		rspamd_http_connection_write_message (conn->http_conn, req->msg, NULL,
				"text/plain", req, &conn->timeout);
	}

	return TRUE;
}
static void
mnb_home_new_widget_dialog_init (MnbHomeNewWidgetDialog *self)
{
  ClutterActor *table, *itemview;
  MnbHomeNewWidgetDialogItemFactory *factory;
  MnbHomePluginsEngine *engine;
  const GList *l;

  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
      MNB_TYPE_HOME_NEW_WIDGET_DIALOG, MnbHomeNewWidgetDialogPrivate);

  /* set up model and view */
  self->priv->items = clutter_list_model_new (ITEMS_N_COLUMNS,
      G_TYPE_STRING, "Module", /* ITEMS_MODULE */
      G_TYPE_STRING, "Name", /* ITEMS_NAME */
      G_TYPE_STRING, "Icon" /* ITEMS_ICON */);

  table = mx_table_new ();
  mx_bin_set_child (MX_BIN (self), table);

  factory = g_object_new (MNB_TYPE_HOME_NEW_WIDGET_DIALOG_ITEM_FACTORY, NULL);
  factory->dialog = self;

  itemview = mx_item_view_new ();
  mx_table_add_actor (MX_TABLE (table), itemview, 0, 1);
  mx_item_view_set_model (MX_ITEM_VIEW (itemview), self->priv->items);
  mx_item_view_set_factory (MX_ITEM_VIEW (itemview), MX_ITEM_FACTORY (factory));

  mx_item_view_add_attribute (MX_ITEM_VIEW (itemview), "module", ITEMS_MODULE);
  mx_item_view_add_attribute (MX_ITEM_VIEW (itemview), "label", ITEMS_NAME);
  mx_item_view_add_attribute (MX_ITEM_VIEW (itemview), "icon", ITEMS_ICON);

  clutter_actor_show_all (table);

  /* find plugins */
  /* FIXME: should we monitor for new plugins on the fly? */
  engine = mnb_home_plugins_engine_dup ();

  for (l = peas_engine_get_plugin_list (PEAS_ENGINE (engine));
       l != NULL;
       l = g_list_next (l))
    {
      PeasPluginInfo *info = l->data;
      char *icon;

      if (!peas_plugin_info_is_available (info, NULL))
        continue;

      icon = g_build_filename (
          peas_plugin_info_get_module_dir (info),
          peas_plugin_info_get_icon_name (info),
          NULL);

      clutter_model_append (self->priv->items,
          ITEMS_MODULE, peas_plugin_info_get_module_name (info),
          ITEMS_NAME, peas_plugin_info_get_name (info),
          ITEMS_ICON, icon,
          -1);

      g_free (icon);
    }

  /* add actions */
  mx_dialog_add_action (MX_DIALOG (self),
      mx_action_new_full ("cancel", _("Cancel"),
        G_CALLBACK (home_new_widget_dialog_cancel),
        self));

  g_object_unref (engine);
  g_object_unref (factory);
}
Пример #30
0
/**
 * Calculates background selection B, at the position represented
 * by the provided BkgdPoint structure. The B-value and first and
 * second derivatives of B are all set on the provided point.
 *
 * cons_list must point to a list of conserved blocks, and next_cons
 * should point to the element in the list which is the next conserved
 * block (or currently overlapping block) on the chromosome.
 */
void bkgd_calc_b(BkgdPoint *bpoint, GList *cons_list, GList *next_cons, 
		 BkgdParam *parm, double r_chr_len) {
  double sum, b, max_sum;
  double drv1_sum, drv1_term;
  double drv2_sum, drv2_term;
  GList *cur;
  ConsBlock *cblk;
  
  sum = drv1_sum = drv2_sum = 0.0;


  /* first consider conserved blocks to left of current site */
  if(next_cons == NULL) {
    cur = g_list_last(cons_list);
  } else {
    cur = g_list_previous(next_cons);
  }
  while(cur != NULL) {
    cblk = cur->data;

    if(cblk->end > bpoint->pos) {
      g_error("expected pos (%ld) to be >= cblk (%ld-%ld) when moving"
	      " leftwards on chr", bpoint->pos, cblk->start, cblk->end);
    }
    
    sum += get_blk_term(cblk, bpoint, &drv1_term, &drv2_term, parm);

    drv1_sum += drv1_term;
    drv2_sum += drv2_term;

    if(parm->apprx_sum) {
      /* calculate the maximum sum remaining in this direction */
      max_sum = calc_sum_up_bound(bpoint, cur, parm);
      
      if(max_sum < parm->max_sum_thresh) {
	/* contrib from remaining terms is very small.
	 * estimate contribution and terminate sum
	 */
	sum += calc_sum_remaining(bpoint, cur, r_chr_len, parm);
	/* TODO: should add remainder for  1st/2nd derivatives */
	break;
      }
    }

    cur = g_list_previous(cur);
  }

  /* now consider conserved blocks to right of current site */
  cur = next_cons;
  while(cur != NULL) {
    cblk = cur->data;

    if(cblk->end < bpoint->pos) {
      g_error("expected pos (%ld) to be < cblk->end (%ld) when moving"
	      " rigthwards on chr", bpoint->pos, cblk->end);
    }

    sum += get_blk_term(cblk, bpoint, &drv1_term, &drv2_term, parm);
    drv1_sum += drv1_term;
    drv2_sum += drv2_term;


    if(parm->apprx_sum) {
      /* calculate the maximum sum remaining in this direction */
      max_sum = calc_sum_up_bound(bpoint, cur, parm);
      
      if(max_sum < parm->max_sum_thresh) {
	/* contrib from remaining terms is very small.
	 * estimate contribution and terminate sum
	 */
	sum += calc_sum_remaining(bpoint, cur, r_chr_len, parm);
	/* TODO: should add remainder for  1st/2nd derivatives */
	break;
      }
    }

    cur = g_list_next(cur);
  }

  /* calculate b */
  b = exp(-parm->u * sum);
  bpoint->b = b;

  /* calculate first derivative of b */
  bpoint->b_drv1 = 2.0 * parm->u * b * drv1_sum;

  /* calculate second derivative */
  bpoint->b_drv2 = (bpoint->b_drv1 * bpoint->b_drv1)/b - parm->u * b*drv2_sum;

  return;
}