Ejemplo n.º 1
0
/* content-defined chunking */
int file_chunk_cdc(int fd_src,
                   CDCFileDescriptor *file_descr,
                   SeafileCrypt *crypt,
                   gboolean write_data)
{
    char *buf;
    uint32_t buf_sz;
    SHA_CTX file_ctx;
    CDCDescriptor chunk_descr;
    SHA1_Init (&file_ctx);

    SeafStat sb;
    if (seaf_fstat (fd_src, &sb) < 0) {
        return -1;
    }
    uint64_t expected_size = sb.st_size;

    init_cdc_file_descriptor (fd_src, expected_size, file_descr);
    uint32_t block_min_sz = file_descr->block_min_sz;
    uint32_t block_mask = file_descr->block_sz - 1;

    int fingerprint = 0;
    int offset = 0;
    int ret = 0;
    int tail, cur, rsize;

    buf_sz = file_descr->block_max_sz;
    buf = chunk_descr.block_buf = malloc (buf_sz);
    if (!buf)
        return -1;

    /* buf: a fix-sized buffer.
     * cur: data behind (inclusive) this offset has been scanned.
     *      cur + 1 is the bytes that has been scanned.
     * tail: length of data loaded into memory. buf[tail] is invalid.
     */
    tail = cur = 0;
    while (1) {
        if (cur < block_min_sz) {
            rsize = block_min_sz - cur + READ_SIZE;
        } else {
            rsize = (buf_sz - tail < READ_SIZE) ? (buf_sz - tail) : READ_SIZE;
        }
        ret = readn (fd_src, buf + tail, rsize);
        if (ret < 0) {
            free (buf);
            return -1;
        }
        tail += ret;
        file_descr->file_size += ret;

        if (file_descr->file_size > expected_size) {
            g_warning ("File size changed while chunking.\n");
            free (buf);
            return -1;
        }

        /* We've read all the data in this file. Output the block immediately
         * in two cases:
         * 1. The data left in the file is less than block_min_sz;
         * 2. We cannot find the break value until the end of this file.
         */
        if (tail < block_min_sz || cur >= tail) {
            if (tail > 0) {
                if (file_descr->block_nr == file_descr->max_block_nr) {
                    g_warning ("Block id array is not large enough, bail out.\n");
                    free (buf);
                    return -1;
                }
                WRITE_CDC_BLOCK (tail, write_data);
            }
            break;
        }

        /*
         * A block is at least of size block_min_sz.
         */
        if (cur < block_min_sz - 1)
            cur = block_min_sz - 1;

        while (cur < tail) {
            fingerprint = (cur == block_min_sz - 1) ?
                          finger(buf + cur - BLOCK_WIN_SZ + 1, BLOCK_WIN_SZ) :
                          rolling_finger (fingerprint, BLOCK_WIN_SZ,
                                          *(buf+cur-BLOCK_WIN_SZ), *(buf + cur));

            /* get a chunk, write block info to chunk file */
            if (((fingerprint & block_mask) ==  ((BREAK_VALUE & block_mask)))
                    || cur + 1 >= file_descr->block_max_sz)
            {
                if (file_descr->block_nr == file_descr->max_block_nr) {
                    g_warning ("Block id array is not large enough, bail out.\n");
                    free (buf);
                    return -1;
                }

                WRITE_CDC_BLOCK (cur + 1, write_data);
                break;
            } else {
                cur ++;
            }
        }
    }

    SHA1_Final (file_descr->file_sum, &file_ctx);

    free (buf);

    return 0;
}
Ejemplo n.º 2
0
static gboolean _ghwp_file_v3_parse_paragraph (GHWPDocument *doc)
{
    g_return_val_if_fail (doc != NULL, FALSE);

    GInputStream  *stream  = GHWP_FILE_V3 (doc->file)->priv->stream;
    GHWPContextV3 *context = ghwp_context_v3_new (stream);
    /* 문단 정보 */
    guint8  prev_paragraph_shape;
    guint16 n_chars;
    guint16 n_lines;
    guint8  char_shape_included;

    guint8 flag;
    int i;

    ghwp_context_v3_read_uint8  (context, &prev_paragraph_shape);
    ghwp_context_v3_read_uint16 (context, &n_chars);
    ghwp_context_v3_read_uint16 (context, &n_lines);
    ghwp_context_v3_read_uint8  (context, &char_shape_included);

    ghwp_context_v3_skip (context, 1 + 4 + 1 + 31);
    /* 여기까지 43 바이트 */

    if (prev_paragraph_shape == 0 && n_chars > 0) {
        ghwp_context_v3_skip (context, 187);
    }

    /* 빈문단이면 FALSE 반환 */
    if (n_chars == 0)
        return FALSE;

    /* 줄 정보 */
    ghwp_context_v3_skip (context, n_lines * 14);

    /* 글자 모양 정보 */
    if (char_shape_included != 0) {
        for (i = 0; i < n_chars; i++) {
            ghwp_context_v3_read_uint8 (context, &flag);
            if (flag != 1) {
                ghwp_context_v3_skip (context, 31);
            }
        }
    }

    GHWPParagraph *paragraph = ghwp_paragraph_new ();
    g_array_append_val (doc->paragraphs, paragraph);
    GString *string = g_string_new (NULL);
    /* 글자들 */
    guint16 n_chars_read = 0;
    guint16 c;

    while (n_chars_read < n_chars) {
        ghwp_context_v3_read_uint16 (context, &c);
        n_chars_read += 1;

        if (c == 6) {
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6 + 34);
            continue;
        } else if (c == 9) { /* tab */
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6);
            g_string_append (string, "\t");
            continue;
        } else if (c == 10) { /* table */
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6);
            /* 테이블 식별 정보 84 바이트 */
            ghwp_context_v3_skip (context, 80);

            guint16 n_cells;
            ghwp_context_v3_read_uint16 (context, &n_cells);

            ghwp_context_v3_skip (context, 2);
            ghwp_context_v3_skip (context, 27 * n_cells);

            /* <셀 문단 리스트>+ */
            for (i = 0; i < n_cells; i++) {
                /* <셀 문단 리스트> ::= <셀 문단>+ <빈문단> */
                while(_ghwp_file_v3_parse_paragraph(doc)) {
                }
            }

            /* <캡션 문단 리스트> ::= <캡션 문단>+ <빈문단> */
            while(_ghwp_file_v3_parse_paragraph(doc)) {
            }
            continue;
        } else if (c == 11) {
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6);
            guint32 len;
            ghwp_context_v3_read_uint32 (context, &len);
            ghwp_context_v3_skip (context, 344);
            ghwp_context_v3_skip (context, len);
            /* <캡션 문단 리스트> ::= <캡션 문단>+ <빈문단> */
            while(_ghwp_file_v3_parse_paragraph(doc)) {
            }
            continue;
        } else if (c == 13) { /* 글자들 끝 */
            g_string_append (string, "\n");
            continue;
        } else if (c == 16) {
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6);
            ghwp_context_v3_skip (context, 10);
            /* <문단 리스트> ::= <문단>+ <빈문단> */
            while(_ghwp_file_v3_parse_paragraph(doc)) {
            }
            continue;
        } else if (c == 17) { /* 각주/미주 */
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6);
            ghwp_context_v3_skip (context, 14);
            while(_ghwp_file_v3_parse_paragraph(doc)) {
            }
            continue;
        } else if (c == 18 || c == 19 || c == 20 || c == 21) {
            n_chars_read += 3;
            ghwp_context_v3_skip (context, 6);
            continue;
        } else if (c == 23) { /*글자 겹침 */
            n_chars_read += 4;
            ghwp_context_v3_skip (context, 8);
            continue;
        } else if (c == 24 || c == 25) {
            n_chars_read += 2;
            ghwp_context_v3_skip (context, 4);
            continue;
        } else if (c == 28) { /* 개요 모양/번호 */
            n_chars_read += 31;
            ghwp_context_v3_skip (context, 62);
            continue;
        } else if (c == 30 || c == 31) {
            n_chars_read += 1;
            ghwp_context_v3_skip (context, 2);
            continue;
        } else if (c >= 0x0020 && c <= 0xffff) {
            gchar *tmp = hnchar_to_utf8 (c);
            g_string_append (string, tmp);
            g_free (tmp);
            continue;
        } else {
            g_warning ("special character: %04x", c);
        } /* if */
    } /* while */
    gchar *tmp = g_string_free(string, FALSE);
    GHWPText *ghwp_text = ghwp_text_new (tmp);
    g_free (tmp);
    ghwp_paragraph_set_ghwp_text (paragraph, ghwp_text);

    static gdouble y   = 0.0;
    static guint   len = 0;

    /* 높이 계산 */
    len = g_utf8_strlen (ghwp_text->text, -1);
    y += 18.0 * ceil (len / 33.0);

    if (y > 842.0 - 80.0) {
        g_array_append_val (doc->pages, GHWP_FILE_V3 (doc->file)->page);
        GHWP_FILE_V3 (doc->file)->page = ghwp_page_new ();
        g_array_append_val (GHWP_FILE_V3 (doc->file)->page->paragraphs, paragraph);
        y = 0.0;
    } else {
        g_array_append_val (GHWP_FILE_V3 (doc->file)->page->paragraphs, paragraph);
    } /* if */

    g_object_unref (context);
    return TRUE;
}
static void
action_calendar_memopad_save_as_cb (GtkAction *action,
                                    ECalShellView *cal_shell_view)
{
	EShell *shell;
	EShellView *shell_view;
	EShellWindow *shell_window;
	EShellBackend *shell_backend;
	ECalShellContent *cal_shell_content;
	EMemoTable *memo_table;
	ECalModelComponent *comp_data;
	EActivity *activity;
	GSList *list;
	GFile *file;
	gchar *string;

	shell_view = E_SHELL_VIEW (cal_shell_view);
	shell_window = e_shell_view_get_shell_window (shell_view);
	shell_backend = e_shell_view_get_shell_backend (shell_view);
	shell = e_shell_window_get_shell (shell_window);

	cal_shell_content = cal_shell_view->priv->cal_shell_content;
	memo_table = e_cal_shell_content_get_memo_table (cal_shell_content);

	list = e_memo_table_get_selected (memo_table);
	g_return_if_fail (list != NULL);
	comp_data = list->data;
	g_slist_free (list);

	/* Translators: Default filename part saving a memo to a file when
	 * no summary is filed, the '.ics' extension is concatenated to it. */
	string = icalcomp_suggest_filename (comp_data->icalcomp, _("memo"));
	file = e_shell_run_save_dialog (
		shell, _("Save as iCalendar"), string,
		"*.ics:text/calendar", NULL, NULL);
	g_free (string);
	if (file == NULL)
		return;

	/* XXX We only save the first selected memo. */
	string = e_cal_client_get_component_as_string (
		comp_data->client, comp_data->icalcomp);
	if (string == NULL) {
		g_warning ("Could not convert memo to a string.");
		g_object_unref (file);
		return;
	}

	/* XXX No callback means errors are discarded. */
	activity = e_file_replace_contents_async (
		file, string, strlen (string), NULL, FALSE,
		G_FILE_CREATE_NONE, (GAsyncReadyCallback) NULL, NULL);
	e_shell_backend_add_activity (shell_backend, activity);

	/* Free the string when the activity is finalized. */
	g_object_set_data_full (
		G_OBJECT (activity),
		"file-content", string,
		(GDestroyNotify) g_free);

	g_object_unref (file);
}
Ejemplo n.º 4
0
Archivo: arc.c Proyecto: mpuels/dia
static void
arc_update_data(Arc *arc)
{
  Connection *conn = &arc->connection;
  LineBBExtras *extra =&conn->extra_spacing;
  DiaObject *obj = &conn->object;
  Point *endpoints;
  real x1,y1,x2,y2,xc,yc;
  real lensq, alpha, radius;
  real angle1, angle2;
  gboolean righthand;
  
  endpoints = &arc->connection.endpoints[0];
  x1 = endpoints[0].x;
  y1 = endpoints[0].y;
  x2 = endpoints[1].x;
  y2 = endpoints[1].y;

  lensq = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1);
  if (fabs(arc->curve_distance) > 0.01)
    radius = lensq/(8*arc->curve_distance) + arc->curve_distance/2.0;
  else
    radius = 0.0; /* not really but used for bbox calculation below */

  if (lensq == 0.0 || arc_is_line (arc))
    alpha = 1.0; /* arbitrary, but /not/ 1/0  */
  else
    alpha = (radius - arc->curve_distance) / sqrt(lensq);

  xc = (x1 + x2) / 2.0 + (y2 - y1)*alpha;
  yc = (y1 + y2) / 2.0 + (x1 - x2)*alpha;

  angle1 = -atan2(y1-yc, x1-xc)*180.0/M_PI;
  if (angle1<0)
    angle1+=360.0;
  angle2 = -atan2(y2-yc, x2-xc)*180.0/M_PI;
  if (angle2<0)
    angle2+=360.0;

  /* swap: draw_arc is not always counter-clockwise, but our member variables
   * stay counter-clockwise to keep all the internal calculations simple
   */
  if (radius<0.0) {
    real tmp;
    tmp = angle1;
    angle1 = angle2;
    angle2 = tmp;
    radius = -radius;
  }
  
  arc->radius = radius;
  arc->center.x = xc; arc->center.y = yc;
  arc->angle1 = angle1;
  arc->angle2 = angle2;

  /* LineBBExtras not applicable to calculate the arrows bounding box */
  extra->start_trans =
  extra->end_trans   =
  extra->start_long  =
  extra->end_long    = (arc->line_width / 2.0);

  /* updates midpoint */
  arc_update_handles(arc);
  /* startpoint, midpoint, endpoint */
  righthand = is_right_hand (&endpoints[0], &arc->middle_handle.pos, &endpoints[1]);
  /* there should be no need to calculate the direction once more */
  if (!(   (righthand && arc->curve_distance <= 0.0)
        || (!righthand && arc->curve_distance >= 0.0)))
    g_warning ("Standard - Arc: check invariant!");
  connection_update_boundingbox(conn);

  /* fix boundingbox for arc's special shape XXX find a more elegant way: */
  if (in_angle(0, arc->angle1, arc->angle2)) {
    /* rigth side, y does not matter if included */
    Point pt = { arc->center.x + arc->radius + (arc->line_width / 2.0), y1 };
    rectangle_add_point (&obj->bounding_box, &pt);
  }
  if (in_angle(90, arc->angle1, arc->angle2)) {
    /* top side, x does not matter if included */
    Point pt = {x1, arc->center.y - arc->radius - (arc->line_width / 2.0) };
    rectangle_add_point (&obj->bounding_box, &pt);
  }
  if (in_angle(180, arc->angle1, arc->angle2)) {
    /* left side, y does not matter if included */
    Point pt = { arc->center.x - arc->radius - (arc->line_width / 2.0), y1 };
    rectangle_add_point (&obj->bounding_box, &pt);
  }
  if (in_angle(270, arc->angle1, arc->angle2)) {
    /* bootom side, x does not matter if included */
    Point pt = { x1, arc->center.y + arc->radius + (arc->line_width / 2.0) };
    rectangle_add_point (&obj->bounding_box, &pt);
  }
  if (arc->start_arrow.type != ARROW_NONE) {
    /* a good from-point would be the chord of arrow length, but draw_arc_with_arrows
     * currently uses the tangent For big arcs the difference is not huge and the
     * minimum size of small arcs should be limited by the arror length.
     */
    Rectangle bbox = {0,};
    real tmp;
    Point move_arrow, move_line;
    Point to = arc->connection.endpoints[0]; 
    Point from = to;
    point_sub (&from, &arc->center);
    tmp = from.x;
    if (righthand)
      from.x = -from.y, from.y = tmp;
    else
      from.x = from.y, from.y = -tmp;
    point_add (&from, &to);

    calculate_arrow_point(&arc->start_arrow, &to, &from,
                          &move_arrow, &move_line, arc->line_width);
    /* move them */
    point_sub(&to, &move_arrow);
    point_sub(&from, &move_line);
    arrow_bbox(&arc->start_arrow, arc->line_width, &to, &from, &bbox);
    rectangle_union(&obj->bounding_box, &bbox);
  }
  if (arc->end_arrow.type != ARROW_NONE) {
    Rectangle bbox = {0,};
    real tmp;
    Point move_arrow, move_line;
    Point to = arc->connection.endpoints[1]; 
    Point from = to;
    point_sub (&from, &arc->center);
    tmp = from.x;
    if (righthand)
      from.x = from.y, from.y = -tmp;
    else
      from.x = -from.y, from.y = tmp;
    point_add (&from, &to);
    calculate_arrow_point(&arc->end_arrow, &to, &from,
                          &move_arrow, &move_line, arc->line_width);
    /* move them */
    point_sub(&to, &move_arrow);
    point_sub(&from, &move_line);
    arrow_bbox(&arc->end_arrow, arc->line_width, &to, &from, &bbox);
    rectangle_union(&obj->bounding_box, &bbox);
  }
  /* if selected put the centerpoint in the box, too. */
  obj->enclosing_box = obj->bounding_box;
  rectangle_add_point(&obj->enclosing_box, &arc->center);

  obj->position = conn->endpoints[0];
}
Ejemplo n.º 5
0
/**
 * Initialize the driver.
 *
 * @return NULL if there is an initialization problem.
 */
static void *
tx_deflate_init(txdrv_t *tx, void *args)
{
	struct attr *attr;
	struct tx_deflate_args *targs = args;
	z_streamp outz;
	int ret;
	int i;

	g_assert(tx);
	g_assert(NULL != targs->cb);

	WALLOC(outz);
	outz->zalloc = zlib_alloc_func;
	outz->zfree = zlib_free_func;
	outz->opaque = NULL;

	/*
	 * Reduce memory requirements for deflation when running as an ultrapeer.
	 *
	 * Memory used for deflation is:
	 *
	 *	(1 << (window_bits +2)) +  (1 << (mem_level + 9))
	 *
	 * For leaves, we use window_bits = 15 and mem_level = 9, which makes
	 * for 128 KiB + 256 KiB = 384 KiB per connection (TX side).
	 *
	 * For ultra peers, we use window_bits = 14 and mem_level = 6, so this
	 * uses 64 KiB + 32 KiB = 96 KiB only.
	 *
	 * Since ultra peers have many more connections than leaves, the memory
	 * savings are drastic, yet compression levels remain around 50% (varies
	 * depending on the nature of the traffic, of course).
	 *
	 *		--RAM, 2009-04-09
	 *
	 * For Ultra <-> Ultra connections we use window_bits = 15 and mem_level = 9
	 * and request a best compression because the amount of ultra connections
	 * is far less than the number of leaf connections and modern machines
	 * can cope with a "best" compression overhead.
	 *
	 * This is now controlled with the "reduced" argument, so this layer does
	 * not need to know whether we're an ultra node or even what an ultra
	 * node is... It just knows whether we have to setup a fully compressed
	 * connection or a reduced one (both in terms of memory usage and level
	 * of compression).
	 *
	 *		--RAM, 2011-11-29
	 */

	{
		int window_bits = MAX_WBITS;		/* Must be 8 .. MAX_WBITS */
		int mem_level = MAX_MEM_LEVEL;		/* Must be 1 .. MAX_MEM_LEVEL */
		int level = Z_BEST_COMPRESSION;

		if (targs->reduced) {
			/* Ultra -> Leaf connection */
			window_bits = 14;
			mem_level = 6;
			level = Z_DEFAULT_COMPRESSION;
		}

		g_assert(window_bits >= 8 && window_bits <= MAX_WBITS);
		g_assert(mem_level >= 1 && mem_level <= MAX_MEM_LEVEL);
		g_assert(level == Z_DEFAULT_COMPRESSION ||
			(level >= Z_BEST_SPEED && level <= Z_BEST_COMPRESSION));

		ret = deflateInit2(outz, level, Z_DEFLATED,
				targs->gzip ? (-window_bits) : window_bits, mem_level,
				Z_DEFAULT_STRATEGY);
	}

	if (Z_OK != ret) {
		g_warning("unable to initialize compressor for peer %s: %s",
			gnet_host_to_string(&tx->host), zlib_strerror(ret));
		WFREE(outz);
		return NULL;
	}

	WALLOC0(attr);
	attr->cq = targs->cq;
	attr->cb = targs->cb;
	attr->buffer_size = targs->buffer_size;
	attr->buffer_flush = targs->buffer_flush;
	attr->nagle = booleanize(targs->nagle);
	attr->gzip.enabled = targs->gzip;

	attr->outz = outz;
	attr->tm_ev = NULL;

	for (i = 0; i < BUFFER_COUNT; i++) {
		struct buffer *b = &attr->buf[i];

		b->arena = b->wptr = b->rptr = walloc(attr->buffer_size);
		b->end = &b->arena[attr->buffer_size];
	}

	attr->fill_idx = 0;
	attr->send_idx = -1;		/* Signals: none ready */

	if (attr->gzip.enabled) {
		/* See RFC 1952 - GZIP file format specification version 4.3 */
		static const unsigned char header[] = {
			0x1f, 0x8b, /* gzip magic */
			0x08,		/* compression method: deflate */
			0,			/* flags: none */
			0, 0, 0, 0, /* modification time: unavailable */
			0,			/* extra flags: none */
			0xff,		/* filesystem: unknown */
		};
		struct buffer *b;

		b = &attr->buf[attr->fill_idx];	/* Buffer we fill */
		g_assert(sizeof header <= (size_t) (b->end - b->wptr));
		b->wptr = mempcpy(b->wptr, header, sizeof header);

		attr->gzip.crc = crc32(0, NULL, 0);
		attr->gzip.size = 0;
	}

	tx->opaque = attr;

	/*
	 * Register our service routine to the lower layer.
	 */

	tx_srv_register(tx->lower, deflate_service, tx);

	return tx;		/* OK */
}
Ejemplo n.º 6
0
GList *
ks_video_probe_filter_for_caps (HANDLE filter_handle)
{
  GList *ret = NULL;
  gulong pin_count;
  guint pin_id;

  if (!ks_filter_get_pin_property (filter_handle, 0, KSPROPSETID_Pin,
          KSPROPERTY_PIN_CTYPES, &pin_count, sizeof (pin_count), NULL))
    goto beach;

  GST_DEBUG ("pin_count = %d", pin_count);

  for (pin_id = 0; pin_id < pin_count; pin_id++) {
    KSPIN_COMMUNICATION pin_comm;
    KSPIN_DATAFLOW pin_flow;
    GUID pin_cat;

    if (!ks_filter_get_pin_property (filter_handle, pin_id, KSPROPSETID_Pin,
            KSPROPERTY_PIN_COMMUNICATION, &pin_comm, sizeof (pin_comm), NULL))
      continue;

    if (!ks_filter_get_pin_property (filter_handle, pin_id, KSPROPSETID_Pin,
            KSPROPERTY_PIN_DATAFLOW, &pin_flow, sizeof (pin_flow), NULL))
      continue;

    if (!ks_filter_get_pin_property (filter_handle, pin_id, KSPROPSETID_Pin,
            KSPROPERTY_PIN_CATEGORY, &pin_cat, sizeof (pin_cat), NULL))
      continue;

    GST_DEBUG ("pin[%u]: pin_comm=%d, pin_flow=%d", pin_id, pin_comm, pin_flow);

    if (pin_flow == KSPIN_DATAFLOW_OUT &&
        memcmp (&pin_cat, &PINNAME_CAPTURE, sizeof (GUID)) == 0) {
      KSMULTIPLE_ITEM *items;

      if (ks_filter_get_pin_property_multi (filter_handle, pin_id,
              KSPROPSETID_Pin, KSPROPERTY_PIN_DATARANGES, &items, NULL)) {
        KSDATARANGE *range = (KSDATARANGE *) (items + 1);
        guint i;

        for (i = 0; i < items->Count; i++) {
          if (IsEqualGUID (&range->MajorFormat, &KSDATAFORMAT_TYPE_VIDEO)) {
            KsVideoMediaType *entry;
            gpointer src_vscc, src_format;
            GstStructure *media_structure;

            entry = g_new0 (KsVideoMediaType, 1);
            entry->pin_id = pin_id;

            entry->range = g_malloc (range->FormatSize);
            memcpy ((gpointer) entry->range, range, range->FormatSize);

            if (IsEqualGUID (&range->Specifier, &FORMAT_VideoInfo)) {
              KS_DATARANGE_VIDEO *vr = (KS_DATARANGE_VIDEO *) entry->range;

              src_vscc = &vr->ConfigCaps;
              src_format = &vr->VideoInfoHeader;

              entry->format_size = sizeof (vr->VideoInfoHeader);
              entry->sample_size = vr->VideoInfoHeader.bmiHeader.biSizeImage;
            } else if (IsEqualGUID (&range->Specifier, &FORMAT_VideoInfo2)) {
              KS_DATARANGE_VIDEO2 *vr = (KS_DATARANGE_VIDEO2 *) entry->range;

              src_vscc = &vr->ConfigCaps;
              src_format = &vr->VideoInfoHeader;

              entry->format_size = sizeof (vr->VideoInfoHeader);
              entry->sample_size = vr->VideoInfoHeader.bmiHeader.biSizeImage;
            } else if (IsEqualGUID (&range->Specifier, &FORMAT_MPEGVideo)) {
              /* Untested and probably wrong... */
              KS_DATARANGE_MPEG1_VIDEO *vr =
                  (KS_DATARANGE_MPEG1_VIDEO *) entry->range;

              src_vscc = &vr->ConfigCaps;
              src_format = &vr->VideoInfoHeader;

              entry->format_size = sizeof (vr->VideoInfoHeader);
              entry->sample_size =
                  vr->VideoInfoHeader.hdr.bmiHeader.biSizeImage;
            } else if (IsEqualGUID (&range->Specifier, &FORMAT_MPEG2Video)) {
              /* Untested and probably wrong... */
              KS_DATARANGE_MPEG2_VIDEO *vr =
                  (KS_DATARANGE_MPEG2_VIDEO *) entry->range;

              src_vscc = &vr->ConfigCaps;
              src_format = &vr->VideoInfoHeader;

              entry->format_size = sizeof (vr->VideoInfoHeader);
              entry->sample_size =
                  vr->VideoInfoHeader.hdr.bmiHeader.biSizeImage;
            } else {
              gchar *guid_str;

              guid_str = ks_guid_to_string (&range->Specifier);
              GST_DEBUG ("pin[%u]: ignoring unknown specifier GUID %s",
                  pin_id, guid_str);
              g_free (guid_str);

              ks_video_media_type_free (entry);
              entry = NULL;
            }

            if (entry != NULL) {
              g_assert (entry->sample_size != 0);

              memcpy ((gpointer) & entry->vscc, src_vscc, sizeof (entry->vscc));

              entry->format = g_malloc (entry->format_size);
              memcpy (entry->format, src_format, entry->format_size);

              media_structure =
                  ks_video_format_to_structure (range->SubFormat,
                  range->MajorFormat);

              if (media_structure == NULL) {
                g_warning ("ks_video_format_to_structure returned NULL");
                ks_video_media_type_free (entry);
                entry = NULL;
              } else if (ks_video_append_video_stream_cfg_fields
                  (media_structure, &entry->vscc)) {
                entry->translated_caps = gst_caps_new_empty ();
                gst_caps_append_structure (entry->translated_caps,
                    media_structure);
              } else {
                gst_structure_free (media_structure);
                ks_video_media_type_free (entry);
                entry = NULL;
              }

              if (entry != NULL)
                ret = g_list_prepend (ret, entry);
            }
          }

          /* REVISIT: Each KSDATARANGE should start on a 64-bit boundary */
          range = (KSDATARANGE *) (((guchar *) range) + range->FormatSize);
        }

        g_free (items);
      }
    }
  }

  if (ret != NULL) {
    ret = g_list_reverse (ret);
    ret = ks_video_media_type_list_remove_duplicates (ret);
  }

beach:
  return ret;
}
Ejemplo n.º 7
0
static gboolean
st_background_effect_pre_paint (ClutterEffect *effect)
{
  StBackgroundEffect *self = ST_BACKGROUND_EFFECT (effect);
  ClutterEffectClass *parent_class;
  gfloat width;
  gfloat height;
  gfloat posx;
  gfloat posy;
  guchar *data;
  guint size;
  guint rowstride;
  glong new_time;
  gdouble time_used;
  ClutterActor *stage;
  gfloat stage_width;
  gfloat stage_height;

  if (self->bg_bumpmap == NULL)
    return FALSE;

  if (!clutter_actor_meta_get_enabled (CLUTTER_ACTOR_META (effect)))
    return FALSE;

  self->actor = clutter_actor_meta_get_actor (CLUTTER_ACTOR_META (effect));
  if (self->actor == NULL)
    return FALSE;

  if (!clutter_feature_available (CLUTTER_FEATURE_SHADERS_GLSL))
  {
    /* if we don't have support for GLSL shaders then we
     * forcibly disable the ActorMeta
     */
    g_warning ("Unable to use the ShaderEffect: the graphics hardware "
           "or the current GL driver does not implement support "
           "for the GLSL shading language.");
    clutter_actor_meta_set_enabled (CLUTTER_ACTOR_META (effect), FALSE);
    return FALSE;
  }

  new_time = clock();
  time_used = ((double) (new_time - self->old_time)*100) / (double) CLOCKS_PER_SEC;
  self->old_time = new_time;

  posx = 0.0f;
  posy = 0.0f;

  width = 0.0f;
  height = 0.0f;

  stage_width = 0.0f;
  stage_height = 0.0f;

  clutter_actor_get_transformed_position (self->actor, &posx, &posy);
  clutter_actor_get_transformed_size (self->actor, &width, &height);
  self->opacity = clutter_actor_get_paint_opacity (self->actor);
  stage = clutter_actor_get_stage (self->actor);
  clutter_actor_get_size (stage, &stage_width, &stage_height);

  if ((posx < 0) || (posy < 0) || ((posx + width) > stage_width) || ((posy + height) > stage_height))
    return FALSE;

  if  (( posx != self->posx_old)
       || ( posy != self->posy_old)
       || ( width != self->width_old)
       || ( height != self->height_old)
       || (time_used > 50.0))

  {
    self->posx_old = posx;
    self->posy_old = posy;
    self->width_old = width;
    self->height_old = height;

    self->bg_posx_i = round(posx)+2;
    self->bg_posy_i = round(posy)+2;
    self->bg_width_i = round(width)-4;
    self->bg_height_i = round(height)-4;

    size = (self->bg_width_i) * (self->bg_height_i) * 4;

    if (((self->opacity == 0xff) || (self->bg_texture == NULL)) && (size > 400))
      {
        rowstride = (self->bg_width_i) * 4;


        data = g_malloc (size);

        cogl_read_pixels (self->bg_posx_i,
                          self->bg_posy_i,
                          self->bg_width_i,
                          self->bg_height_i,
                          COGL_READ_PIXELS_COLOR_BUFFER,
                          COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                          data);

        if (data != NULL)
          {

            if (self->bg_texture != NULL)
              {
                cogl_handle_unref (self->bg_texture);
                self->bg_texture = NULL;
              }

            self->bg_texture = st_cogl_texture_new_from_data_wrapper  (self->bg_width_i,
                                                                       self->bg_height_i,
                                                                       COGL_TEXTURE_NO_SLICING,
                                                                       COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                                                                       COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                                                                       rowstride,
                                                                       data);

            g_free (data);

          }
      }
  }

  parent_class = CLUTTER_EFFECT_CLASS (st_background_effect_parent_class);

  if (parent_class->pre_paint (effect))
    {
      ClutterOffscreenEffect *offscreen_effect =  CLUTTER_OFFSCREEN_EFFECT (effect);
      CoglHandle fg_texture;

      fg_texture = clutter_offscreen_effect_get_texture (offscreen_effect);

      if (fg_texture != COGL_INVALID_HANDLE)
        {
          self->fg_width_i = cogl_texture_get_width (fg_texture);
          self->fg_height_i = cogl_texture_get_height (fg_texture);

          if ((self->bg_texture != NULL) && (self->opacity == 0xff))
            {


              if (self->pixel_step_uniform0 > -1)
                {
                  gfloat pixel_step[3];

                  pixel_step[0] = 1.0f / (self->bg_width_i);
                  pixel_step[1] = 1.0f / (self->bg_height_i);
                  pixel_step[2] = 0.0f;

                  cogl_pipeline_set_uniform_float (self->pipeline0,
                                                   self->pixel_step_uniform0,
                                                   3,
                                                   1,
                                                   pixel_step);
                }

              if (self->BumpTex_uniform > -1)
                {

                  cogl_pipeline_set_uniform_1i (self->pipeline0,
                                                self->BumpTex_uniform,
                                                1);
                }

              if (self->bump_step_uniform > -1)
                {
                  gfloat bump_step[2];

                  bump_step[0] = 1.0f / (self->bumptex_width_i);
                  bump_step[1] = 1.0f / (self->bumptex_height_i);

                  cogl_pipeline_set_uniform_float (self->pipeline0,
                                                   self->bump_step_uniform,
                                                   2,
                                                   1,
                                                   bump_step);
                }

              if (self->bg_sub_texture != NULL)
                {
                  cogl_handle_unref (self->bg_sub_texture);
                  self->bg_sub_texture = NULL;
                }

              self->bg_sub_texture = st_cogl_texture_new_with_size_wrapper (self->bg_width_i, self->bg_height_i,
                                                                            COGL_TEXTURE_NO_SLICING,
                                                                            COGL_PIXEL_FORMAT_RGBA_8888_PRE);

              cogl_pipeline_set_layer_texture (self->pipeline0, 0, self->bg_texture);

              if (self->pixel_step_uniform1 > -1)
                {
                  gfloat pixel_step[3];

                  pixel_step[0] = 1.0f / (self->bg_width_i);
                  pixel_step[1] = 1.0f / (self->bg_height_i);
                  pixel_step[2] = 1.0f;

                  cogl_pipeline_set_uniform_float (self->pipeline1,
                                                   self->pixel_step_uniform1,
                                                   3,
                                                   1,
                                                   pixel_step);
                }

              if (self->pixel_step_uniform2 > -1)
                {
                  gfloat pixel_step[3];

                  pixel_step[0] = 1.0f / (self->fg_width_i);
                  pixel_step[1] = 1.0f / (self->fg_height_i);
                  pixel_step[2] = 2.0f;

                  cogl_pipeline_set_uniform_float (self->pipeline3,
                                                   self->pixel_step_uniform2,
                                                   3,
                                                   1,
                                                   pixel_step);
                }

            }

          cogl_pipeline_set_layer_texture (self->pipeline2, 0, fg_texture);
          cogl_pipeline_set_layer_texture (self->pipeline3, 0, fg_texture);
          cogl_pipeline_set_layer_texture (self->pipeline4, 0, fg_texture);

        }
      return TRUE;
    }
  else
    {
      return FALSE;
    }
}
static int
stream_reset (GMimeStream *stream)
{
	d(g_warning ("Invoked default stream_reset implementation."));
	return 0;
}
static gint64
stream_seek (GMimeStream *stream, gint64 offset, GMimeSeekWhence whence)
{
	d(g_warning ("Invoked default stream_seek implementation."));
	return -1;
}
Ejemplo n.º 10
0
static ssize_t
stream_write (GMimeStream *stream, const char *buf, size_t len)
{
	d(g_warning ("Invoked default stream_write implementation."));
	return 0;
}
Ejemplo n.º 11
0
static gboolean
stream_eos (GMimeStream *stream)
{
	d(g_warning ("Invoked default stream_eos implementation."));
	return stream->position >= stream->bound_end;
}
static void
on_call_channel_get_all_properties_cb (TpProxy *proxy,
    GHashTable *properties,
    const GError *error,
    gpointer user_data,
    GObject *weak_object)
{
  TpyCallChannel *self = TPY_CALL_CHANNEL (proxy);
  GSimpleAsyncResult *result = user_data;
  GHashTable *hash_table;
  GPtrArray *contents;
  guint i;

  if (error != NULL)
    {
      g_warning ("Could not get the channel properties: %s", error->message);
      g_simple_async_result_set_from_error (result, error);
      goto out;
    }

  self->priv->state = tp_asv_get_uint32 (properties,
      "CallState", NULL);
  self->priv->flags = tp_asv_get_uint32 (properties,
      "CallFlags", NULL);
  self->priv->initial_audio = tp_asv_get_boolean (properties,
      "InitialAudio", NULL);
  self->priv->initial_video = tp_asv_get_boolean (properties,
      "InitialVideo", NULL);

  hash_table = tp_asv_get_boxed (properties,
      "CallStateDetails", TP_HASH_TYPE_STRING_VARIANT_MAP);
  if (hash_table != NULL)
    self->priv->details = g_boxed_copy (TP_HASH_TYPE_STRING_VARIANT_MAP,
        hash_table);

  hash_table = tp_asv_get_boxed (properties,
      "CallMembers", TPY_HASH_TYPE_CALL_MEMBER_MAP);
  update_call_members (self, hash_table, NULL);

  contents = tp_asv_get_boxed (properties,
      "Contents", TP_ARRAY_TYPE_OBJECT_PATH_LIST);

  for (i = 0; i < contents->len; i++)
    {
      const gchar *content_path = g_ptr_array_index (contents, i);
      TpyCallContent *content;

      DEBUG ("Content added: %s", content_path);

      content = g_object_new (TPY_TYPE_CALL_CONTENT,
              "bus-name", tp_proxy_get_bus_name (self),
              "dbus-daemon", tp_proxy_get_dbus_daemon (self),
              "dbus-connection", tp_proxy_get_dbus_connection (self),
              "object-path", content_path,
              NULL);

      if (content == NULL)
        {
          g_warning ("Could not create a CallContent for path %s", content_path);

          g_simple_async_result_set_error (result, TP_ERRORS, TP_ERROR_CONFUSED,
              "Could not create a CallContent for path %s", content_path);
          goto out;
        }

      g_ptr_array_add (self->priv->contents, content);

      tp_g_signal_connect_object (content, "notify::ready",
        G_CALLBACK (on_content_ready_cb), self, 0);
    }

  g_signal_emit (self, _signals[MEMBERS_CHANGED], 0, self->priv->members);

  self->priv->properties_retrieved = TRUE;

  maybe_go_to_ready (self);

out:
  /* TODO; ideally we should get rid of the ready property and complete once
   * all the contents have been prepared. Or maybe that should be another
   * feature? */
  g_simple_async_result_complete (result);
}
Ejemplo n.º 13
0
static void
clutter_stage_egl_realize (ClutterActor *actor)
{
  ClutterStageEGL     *stage_egl = CLUTTER_STAGE_EGL (actor);
  ClutterBackendEGL   *backend_egl;
  EGLConfig            configs[2];
  EGLint               config_count;
  EGLBoolean           status;
  gboolean             is_offscreen;

  CLUTTER_NOTE (BACKEND, "Realizing main stage");

  g_object_get (stage_egl->wrapper, "offscreen", &is_offscreen, NULL);

  backend_egl = CLUTTER_BACKEND_EGL (clutter_get_default_backend ());

  if (G_LIKELY (!is_offscreen))
    {
      EGLint cfg_attribs[] = { EGL_BUFFER_SIZE,     EGL_DONT_CARE,
			       EGL_RED_SIZE,        5,
			       EGL_GREEN_SIZE,      6,
			       EGL_BLUE_SIZE,       5,
			       EGL_DEPTH_SIZE,      16,
			       EGL_ALPHA_SIZE,      EGL_DONT_CARE,
			       EGL_STENCIL_SIZE,    2, 
#ifdef HAVE_COGL_GLES2
			       EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#else /* HAVE_COGL_GLES2 */
			       EGL_SURFACE_TYPE,    EGL_WINDOW_BIT,
#endif /* HAVE_COGL_GLES2 */
			       EGL_NONE };

      status = eglGetConfigs (backend_egl->edpy,
			      configs, 
			      2, 
			      &config_count);

      if (status != EGL_TRUE)
        {
	  g_critical ("eglGetConfigs failed");
          CLUTTER_ACTOR_UNSET_FLAGS (actor, CLUTTER_ACTOR_REALIZED);
          return;
        }

      status = eglChooseConfig (backend_egl->edpy,
				cfg_attribs,
				configs,
                                G_N_ELEMENTS (configs),
				&config_count);

      if (status != EGL_TRUE)
        {
          g_critical ("eglChooseConfig failed");
          CLUTTER_ACTOR_UNSET_FLAGS (actor, CLUTTER_ACTOR_REALIZED);
          return;
        }

      CLUTTER_NOTE (BACKEND, "Got %i configs", config_count); 

      if (stage_egl->egl_surface != EGL_NO_SURFACE)
        {
	  eglDestroySurface (backend_egl->edpy, stage_egl->egl_surface);
          stage_egl->egl_surface = EGL_NO_SURFACE;
        }

       if (backend_egl->egl_context)
         {
            eglDestroyContext (backend_egl->edpy, backend_egl->egl_context);
            backend_egl->egl_context = NULL;
         }

      stage_egl->egl_surface =
	eglCreateWindowSurface (backend_egl->edpy,
                                configs[0],
                                NULL,
                                NULL);

      if (stage_egl->egl_surface == EGL_NO_SURFACE)
        {
	  g_critical ("Unable to create an EGL surface");

          CLUTTER_ACTOR_UNSET_FLAGS (actor, CLUTTER_ACTOR_REALIZED);
          return;
        }

      eglQuerySurface (backend_egl->edpy,
		       stage_egl->egl_surface,
		       EGL_WIDTH,
		       &stage_egl->surface_width);

      eglQuerySurface (backend_egl->edpy,
		       stage_egl->egl_surface,
		       EGL_HEIGHT,
		       &stage_egl->surface_height);

      CLUTTER_NOTE (BACKEND, "EGL surface is %ix%i", 
		    stage_egl->surface_width,
                    stage_egl->surface_height);

      
      if (G_UNLIKELY (backend_egl->egl_context == NULL))
        {
#ifdef HAVE_COGL_GLES2
	  static const EGLint attribs[3]
	    = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };

          backend_egl->egl_context = eglCreateContext (backend_egl->edpy,
						       configs[0],
                                                       EGL_NO_CONTEXT,
                                                       attribs);
#else
          /* Seems some GLES implementations 1.x do not like attribs... */
          backend_egl->egl_context = eglCreateContext (backend_egl->edpy,
						       configs[0],
                                                       EGL_NO_CONTEXT,
                                                       NULL);
#endif

          if (backend_egl->egl_context == EGL_NO_CONTEXT)
            {
              g_critical ("Unable to create a suitable EGL context");

              CLUTTER_ACTOR_UNSET_FLAGS (actor, CLUTTER_ACTOR_REALIZED);
              return;
            }

          CLUTTER_NOTE (GL, "Created EGL Context");
        }

      CLUTTER_NOTE (BACKEND, "Setting context");

      /* eglnative can have only one stage */
      status = eglMakeCurrent (backend_egl->edpy,
                               stage_egl->egl_surface,
                               stage_egl->egl_surface,
                               backend_egl->egl_context);

      if (status != EGL_TRUE)
        {
          g_critical ("eglMakeCurrent failed");
          
          CLUTTER_ACTOR_UNSET_FLAGS (actor, CLUTTER_ACTOR_REALIZED);
          return;
        }

      /* since we only have one size and it cannot change, we
       * just need to update the GL viewport now that we have
       * been realized
       */
      CLUTTER_SET_PRIVATE_FLAGS (actor, CLUTTER_ACTOR_SYNC_MATRICES);
    }
  else
    {
      g_warning ("EGL Backend does not yet support offscreen rendering\n");
      CLUTTER_ACTOR_UNSET_FLAGS (actor, CLUTTER_ACTOR_REALIZED);
      return;
    }
}
Ejemplo n.º 14
0
gchar *get_proc_data(pid_t pid, gchar *file, gsize *length)
{
#ifdef FULL
	g_debug("! Launch get_proc_data() with pid = %d, file = %s", pid, file);
#endif
	// g_debug("proc_exist = %d", proc_exist);
	if (! proc_exist) return NULL;
	if (pid<1) return NULL;
#ifdef UNIT_TEST
	if (file==NULL) return NULL;
#endif
	gchar *contents=NULL;
	gint timeout=0;
	gchar *proc_path = g_strdup_printf("%s/%d", proc_file_system_path, (gint)pid);
	// g_debug("proc_path = %s", proc_path);
	gchar *file_path = g_strdup_printf("%s/%s", proc_path, file);
	// g_debug("file_path = %s", file_path);

#if defined(OUT_OF_MEMORY) || defined(UNIT_TEST)
	if (proc_path && file_path)
	{
#endif
		while (g_file_test(proc_path, G_FILE_TEST_EXISTS) &&
		       g_file_get_contents (file_path, &contents, length, NULL))
		{
			// g_debug("Got the contents length is %d for %s", *length, file_path);
			if (*length==0)
			{
				// gsize len = 0;
				// gchar *stat = NULL;
				// gchar *stat_path = g_strdup_printf("%s/%d/stat", proc_file_system_path, (gint)pid);
				// if (g_file_get_contents (stat_path, &contents, &len, NULL))
				// {
				//	g_debug("Got len = %d, stat = %s", len, stat);
				//	if (len && stat)
				//	{
				//		gchar **stats = split_string(stat, " ()", 6);
				//		if (stats && stats[4][0]=='Z')
				//		{
				//			g_warning("The child process \"(%s) %s\" has died. Abort.",
				//				  stats[0], stats[2]);
				//			g_free(stat);
				//			g_strfreev(stats);
				//
				//			g_free(contents);
				//			contents = NULL;
				//			break;
				//		}
				//		g_strfreev(stats);
				//	}
				// }
				// g_free(stat);
				g_message("Waiting for %s/%d/%s...", proc_file_system_path, (gint)pid, file);
				// we should wait until "/proc/%d/file" is not empty
				usleep(100000);
				timeout++;
				// contents = "" here
				g_free(contents);
				contents = NULL;
			}
			else
				break;

			// we only try for 3 times
			if (timeout>2)
			{
#ifdef FATAL
				g_message("Failed when waiting for %s/%d/%s. Abort!", proc_file_system_path, (gint)pid, file);
#else
				g_warning("Failed when waiting for %s/%d/%s. Abort!", proc_file_system_path, (gint)pid, file);
#endif
				break;
			}
		}
#if defined(OUT_OF_MEMORY) || defined(UNIT_TEST)
	}
#endif
	g_free(file_path);
	g_free(proc_path);
	// g_debug("contents = %s", contents);
	return contents;
}
Ejemplo n.º 15
0
gboolean
nautilus_list_model_add_file (NautilusListModel *model, NautilusFile *file,
			      NautilusDirectory *directory)
{
	GtkTreeIter iter;
	GtkTreePath *path;
	FileEntry *file_entry;
	GSequenceIter *ptr, *parent_ptr;
	GSequence *files;
	gboolean replace_dummy;
	GHashTable *parent_hash;

	parent_ptr = g_hash_table_lookup (model->details->directory_reverse_map,
					  directory);
	if (parent_ptr) {
		file_entry = g_sequence_get (parent_ptr);
		ptr = g_hash_table_lookup (file_entry->reverse_map, file);
	} else {
		file_entry = NULL;
		ptr = g_hash_table_lookup (model->details->top_reverse_map, file);
	}

	if (ptr != NULL) {
		g_warning ("file already in tree (parent_ptr: %p)!!!\n", parent_ptr);
		return FALSE;
	}
	
	file_entry = g_new0 (FileEntry, 1);
	file_entry->file = nautilus_file_ref (file);
	file_entry->parent = NULL;
	file_entry->subdirectory = NULL;
	file_entry->files = NULL;
	
	files = model->details->files;
	parent_hash = model->details->top_reverse_map;
	
	replace_dummy = FALSE;

	if (parent_ptr != NULL) {
		file_entry->parent = g_sequence_get (parent_ptr);
		/* At this point we set loaded. Either we saw
		 * "done" and ignored it waiting for this, or we do this
		 * earlier, but then we replace the dummy row anyway,
		 * so it doesn't matter */
		file_entry->parent->loaded = 1;
		parent_hash = file_entry->parent->reverse_map;
		files = file_entry->parent->files;
		if (g_sequence_get_length (files) == 1) {
			GSequenceIter *dummy_ptr = g_sequence_get_iter_at_pos (files, 0);
			FileEntry *dummy_entry = g_sequence_get (dummy_ptr);
			if (dummy_entry->file == NULL) {
				/* replace the dummy loading entry */
				model->details->stamp++;
				g_sequence_remove (dummy_ptr);
				
				replace_dummy = TRUE;
			}
		}
	}

	
	file_entry->ptr = g_sequence_insert_sorted (files, file_entry,
					    nautilus_list_model_file_entry_compare_func, model);

	g_hash_table_insert (parent_hash, file, file_entry->ptr);
	
	iter.stamp = model->details->stamp;
	iter.user_data = file_entry->ptr;

	path = gtk_tree_model_get_path (GTK_TREE_MODEL (model), &iter);
	if (replace_dummy) {
		gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter);
	} else {
		gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter);
	}

	if (nautilus_file_is_directory (file)) {
		file_entry->files = g_sequence_new ((GDestroyNotify)file_entry_free);

		add_dummy_row (model, file_entry);

		gtk_tree_model_row_has_child_toggled (GTK_TREE_MODEL (model),
						      path, &iter);
	}
	gtk_tree_path_free (path);
	
	return TRUE;
}
Ejemplo n.º 16
0
static gint64
stream_tell (GMimeStream *stream)
{
	d(g_warning ("Invoked default stream_tell implementation."));
	return stream->position;
}
Ejemplo n.º 17
0
static void
tp_kqueue_wait (gpointer p)
{
	SocketIOData *socket_io_data;
	int kfd;
	struct kevent *events, *evt;
	int ready = 0, i;
	gpointer async_results [KQUEUE_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
	gint nresults;
	tp_kqueue_data *data;

	socket_io_data = p;
	data = socket_io_data->event_data;
	kfd = data->fd;
	events = g_new0 (struct kevent, KQUEUE_NEVENTS);

	while (1) {
	
		mono_gc_set_skip_thread (TRUE);

		do {
			if (ready == -1) {
				check_for_interruption_critical ();
			}
			ready = kevent (kfd, NULL, 0, events, KQUEUE_NEVENTS, NULL);
		} while (ready == -1 && errno == EINTR);

		mono_gc_set_skip_thread (FALSE);

		if (ready == -1) {
			int err = errno;
			g_free (events);
			if (err != EBADF)
				g_warning ("kevent wait: %d %s", err, g_strerror (err));

			return;
		}

		mono_mutex_lock (&socket_io_data->io_lock);
		if (socket_io_data->inited == 3) {
			g_free (events);
			mono_mutex_unlock (&socket_io_data->io_lock);
			return; /* cleanup called */
		}

		nresults = 0;
		for (i = 0; i < ready; i++) {
			int fd;
			MonoMList *list;
			MonoObject *ares;

			evt = &events [i];
			fd = evt->ident;
			list = mono_g_hash_table_lookup (socket_io_data->sock_to_state, GINT_TO_POINTER (fd));
			if (list != NULL && (evt->filter == EVFILT_READ || (evt->flags & EV_ERROR) != 0)) {
				ares = get_io_event (&list, MONO_POLLIN);
				if (ares != NULL)
					async_results [nresults++] = ares;
			}
			if (list != NULL && (evt->filter == EVFILT_WRITE || (evt->flags & EV_ERROR) != 0)) {
				ares = get_io_event (&list, MONO_POLLOUT);
				if (ares != NULL)
					async_results [nresults++] = ares;
			}

			if (list != NULL) {
				int p;

				mono_g_hash_table_replace (socket_io_data->sock_to_state, GINT_TO_POINTER (fd), list);
				p = get_events_from_list (list);
				if (evt->filter == EVFILT_READ && (p & MONO_POLLIN) != 0) {
					EV_SET (evt, fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_ONESHOT, 0, 0, 0);
					kevent_change (kfd, evt, "READD read");
				}

				if (evt->filter == EVFILT_WRITE && (p & MONO_POLLOUT) != 0) {
					EV_SET (evt, fd, EVFILT_WRITE, EV_ADD | EV_ENABLE | EV_ONESHOT, 0, 0, 0);
					kevent_change (kfd, evt, "READD write");
				}
			} else {
				mono_g_hash_table_remove (socket_io_data->sock_to_state, GINT_TO_POINTER (fd));
			}
		}
		mono_mutex_unlock (&socket_io_data->io_lock);
		threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
		mono_gc_bzero_aligned (async_results, sizeof (gpointer) * nresults);
	}
}
Ejemplo n.º 18
0
static GMimeStream *
stream_substream (GMimeStream *stream, gint64 start, gint64 end)
{
	d(g_warning ("Invoked default stream_tell implementation."));
	return NULL;
}
Ejemplo n.º 19
0
static void
run_add_edit_dialog (LogviewFilterManager *manager, LogviewFilter *filter)
{
  int response;
  GError *error;
  gchar *name, *regex;
  const gchar *title;
  GtkWidget *dialog, *entry_name, *entry_regex, *radio_color;
  GtkWidget *radio_visible, *check_foreground, *check_background;
  GtkWidget *color_foreground, *color_background, *vbox_color;
  gboolean foreground_set, background_set, invisible;
  GtkTextTag *tag;
  GtkBuilder* builder;

  builder = manager->priv->builder;

  error = NULL;
  name = NULL;
  
  gtk_builder_add_from_file (builder, UI_FILE, &error);

  if (error) {
    g_warning ("Could not load filter ui: %s", error->message);
    g_error_free (error);
    return;
  }

  title = (filter != NULL ? _("Edit filter") : _("Add new filter"));

  dialog = GTK_WIDGET (gtk_builder_get_object (builder,
                                               "dialog_filter"));

  entry_name = GTK_WIDGET (gtk_builder_get_object (builder,
                                                   "entry_name"));
  entry_regex = GTK_WIDGET (gtk_builder_get_object (builder,
                                                    "entry_regex"));
  radio_color = GTK_WIDGET (gtk_builder_get_object (builder,
                                                    "radio_color"));
  radio_visible = GTK_WIDGET (gtk_builder_get_object (builder,
                                                      "radio_visible"));

  gtk_radio_button_set_group (GTK_RADIO_BUTTON (radio_color),
                              gtk_radio_button_get_group (GTK_RADIO_BUTTON (radio_visible)));

  check_foreground = GTK_WIDGET (gtk_builder_get_object (builder,
                                                         "check_foreground"));
  check_background = GTK_WIDGET (gtk_builder_get_object (builder,
                                                         "check_background"));
  color_foreground = GTK_WIDGET (gtk_builder_get_object (builder,
                                                         "color_foreground"));
  color_background = GTK_WIDGET (gtk_builder_get_object (builder,
                                                         "color_background"));
  g_signal_connect (check_foreground, "toggled", G_CALLBACK (on_check_toggled),
                    color_foreground);
  g_signal_connect (check_background, "toggled", G_CALLBACK (on_check_toggled),
                    color_background);

  on_check_toggled (GTK_TOGGLE_BUTTON (check_foreground),
                    color_foreground);
  on_check_toggled (GTK_TOGGLE_BUTTON (check_background),
                    color_background);

  vbox_color = GTK_WIDGET (gtk_builder_get_object (builder, "vbox_color"));
  g_signal_connect (radio_color, "toggled", G_CALLBACK (on_check_toggled),
                    vbox_color);
  on_check_toggled (GTK_TOGGLE_BUTTON (radio_color),
                    vbox_color);

  if (filter) {
    g_object_get (filter,
                  "name", &name,
                  "regex", &regex,
                  "texttag", &tag,
                  NULL);
    g_object_get (tag,
                  "foreground-set", &foreground_set,
                  "paragraph-background-set", &background_set,
                  "invisible", &invisible, NULL);
    gtk_entry_set_text (GTK_ENTRY(entry_name), name);
    gtk_entry_set_text (GTK_ENTRY(entry_regex), regex);

    if (foreground_set) {
      GdkColor *foreground;

      g_object_get (tag, "foreground-gdk", &foreground, NULL);
      gtk_color_button_set_color (GTK_COLOR_BUTTON (color_foreground),
                                  foreground);
      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (check_foreground),
                                    TRUE);

      gdk_color_free (foreground);
    }

    if (background_set) {
      GdkColor *background;

      g_object_get (tag, "paragraph-background-gdk", &background, NULL);
      gtk_color_button_set_color (GTK_COLOR_BUTTON (color_background),
                                  background);
      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (check_background),
                                    TRUE);

      gdk_color_free (background);
    }

    if (background_set || foreground_set) {
      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (radio_color), TRUE);
    } else if (invisible) {
      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (radio_visible), TRUE);
    }

    g_free (regex);
    g_object_unref (tag);
  }

  g_object_set_data_full (G_OBJECT (manager), "old_name", name, g_free);

  g_signal_connect (G_OBJECT (dialog), "response",
                    G_CALLBACK (on_dialog_add_edit_reponse), manager);
  gtk_window_set_transient_for (GTK_WINDOW (dialog),
                                GTK_WINDOW (manager));
  gtk_window_set_modal (GTK_WINDOW (dialog),
                        TRUE);

  gtk_widget_show (GTK_WIDGET (dialog));
}
Ejemplo n.º 20
0
static gboolean
RpcInSend(RpcChannel *chan,
          char const *data,
          size_t dataLen,
          char **result,
          size_t *resultLen)
{
   gboolean ret = FALSE;
   const char *reply;
   size_t replyLen;
   BackdoorChannel *bdoor = chan->_private;

   g_static_mutex_lock(&bdoor->outLock);
   if (!bdoor->outStarted) {
      goto exit;
   }

   ret = RpcOut_send(bdoor->out, data, dataLen, &reply, &replyLen);

   /*
    * This is a hack to try to work around bug 393650 without having to revert
    * to the old behavior of opening and closing an RpcOut channel for every
    * outgoing message. The issue here is that it's possible for the code to
    * try to write to the channel when a "reset" has just happened. In these
    * cases, the current RpcOut channel is not valid anymore, and we'll get an
    * error. The RpcOut lib doesn't really reply with a useful error, but it
    * does have consistent error messages starting with "RpcOut:".
    *
    * So, if the error is one of those messages, restart the RpcOut channel and
    * try to send the message again. If this second attempt fails, then give up.
    *
    * This is not 100% break-proof: a reset can still occur after we open the
    * new channel and before we try to re-send the message. But that's a race
    * that we can't easily fix, and exists even in code that just uses the
    * RpcOut_SendOne() API. Also, if some host handler returns an error that
    * starts with "RpcOut:", it will trigger this; but I don't think we have
    * any such handlers.
    */
   if (!ret && reply != NULL && replyLen > sizeof "RpcOut: " &&
       g_str_has_prefix(reply, "RpcOut: ")) {
      g_debug("RpcOut failure, restarting channel.\n");
      RpcOut_stop(bdoor->out);
      if (RpcOut_start(bdoor->out)) {
         ret = RpcOut_send(bdoor->out, data, dataLen, &reply, &replyLen);
      } else {
         g_warning("Couldn't restart RpcOut channel; bad things may happen "
                   "until the RPC channel is reset.\n");
         bdoor->outStarted = FALSE;
      }
   }

   /*
    * A lot of this logic is just replicated from rpcout.c:RpcOut_SendOneRaw().
    * Look there for comments about a few details.
    */
   if (result != NULL) {
      if (reply != NULL) {
         *result = Util_SafeMalloc(replyLen + 1);
         memcpy(*result, reply, replyLen);
         (*result)[replyLen] = '\0';
      } else {
         *result = NULL;
      }
   }

   if (resultLen != NULL) {
      *resultLen = replyLen;
   }

exit:
   g_static_mutex_unlock(&bdoor->outLock);
   return ret;
}
Ejemplo n.º 21
0
Archivo: glarea.c Proyecto: GNOME/gtk
/* Initialize the shaders and link them into a program */
static void
init_shaders (const char *vertex_path,
              const char *fragment_path,
              GLuint *program_out,
              GLuint *mvp_out)
{
  GLuint vertex, fragment;
  GLuint program = 0;
  GLuint mvp = 0;
  int status;
  GBytes *source;

  source = g_resources_lookup_data (vertex_path, 0, NULL);
  vertex = create_shader (GL_VERTEX_SHADER, g_bytes_get_data (source, NULL));
  g_bytes_unref (source);

  if (vertex == 0)
    {
      *program_out = 0;
      return;
    }

  source = g_resources_lookup_data (fragment_path, 0, NULL);
  fragment = create_shader (GL_FRAGMENT_SHADER, g_bytes_get_data (source, NULL));
  g_bytes_unref (source);

  if (fragment == 0)
    {
      glDeleteShader (vertex);
      *program_out = 0;
      return;
    }

  program = glCreateProgram ();
  glAttachShader (program, vertex);
  glAttachShader (program, fragment);

  glLinkProgram (program);

  glGetProgramiv (program, GL_LINK_STATUS, &status);
  if (status == GL_FALSE)
    {
      int log_len;
      char *buffer;

      glGetProgramiv (program, GL_INFO_LOG_LENGTH, &log_len);

      buffer = g_malloc (log_len + 1);
      glGetProgramInfoLog (program, log_len, NULL, buffer);

      g_warning ("Linking failure:\n%s", buffer);

      g_free (buffer);

      glDeleteProgram (program);
      program = 0;

      goto out;
    }

  /* Get the location of the "mvp" uniform */
  mvp = glGetUniformLocation (program, "mvp");

  glDetachShader (program, vertex);
  glDetachShader (program, fragment);

out:
  glDeleteShader (vertex);
  glDeleteShader (fragment);

  if (program_out != NULL)
    *program_out = program;

  if (mvp_out != NULL)
    *mvp_out = mvp;
}
Ejemplo n.º 22
0
font_instance *font_factory::Face(PangoFontDescription *descr, bool canFail)
{
#ifdef USE_PANGO_WIN32
    // damn Pango fudges the size, so we need to unfudge. See source of pango_win32_font_map_init()
    pango_font_description_set_size(descr, (int) (fontSize*PANGO_SCALE*72/GetDeviceCaps(pango_win32_get_dc(),LOGPIXELSY))); // mandatory huge size (hinting workaround)
#else
    pango_font_description_set_size(descr, (int) (fontSize*PANGO_SCALE)); // mandatory huge size (hinting workaround)
#endif

    font_instance *res = NULL;

    FaceMapType& loadedFaces = *static_cast<FaceMapType*>(loadedPtr);
    if ( loadedFaces.find(descr) == loadedFaces.end() ) {
        // not yet loaded
        PangoFont *nFace = NULL;

        // workaround for bug #1025565.
        // fonts without families blow up Pango.
        if (sp_font_description_get_family(descr) != NULL) {
            nFace = pango_font_map_load_font(fontServer,fontContext,descr);
        }
        else {
            g_warning("%s", _("Ignoring font without family that will crash Pango"));
        }

        if ( nFace ) {
            // duplicate FcPattern, the hard way
            res = new font_instance();
            // store the descr of the font we asked for, since this is the key where we intend
            // to put the font_instance at in the unordered_map.  the descr of the returned
            // pangofont may differ from what was asked, so we don't know (at this
            // point) whether loadedFaces[that_descr] is free or not (and overwriting
            // an entry will bring deallocation problems)
            res->descr = pango_font_description_copy(descr);
            res->parent = this;
            res->InstallFace(nFace);
            if ( res->pFont == NULL ) {
                // failed to install face -> bitmap font
                // printf("face failed\n");
                res->parent = NULL;
                delete res;
                res = NULL;
                if ( canFail ) {
                    char *tc = pango_font_description_to_string(descr);
                    PANGO_DEBUG("falling back from %s to 'sans-serif' because InstallFace failed\n",tc);
                    g_free(tc);
                    pango_font_description_set_family(descr,"sans-serif");
                    res = Face(descr,false);
                }
            } else {
                loadedFaces[res->descr]=res;
                res->Ref();
                AddInCache(res);
            }
        } else {
            // no match
            if ( canFail ) {
                PANGO_DEBUG("falling back to 'sans-serif'\n");
                descr = pango_font_description_new();
                pango_font_description_set_family(descr,"sans-serif");
                res = Face(descr,false);
                pango_font_description_free(descr);
            }
        }
    } else {
        // already here
        res = loadedFaces[descr];
        res->Ref();
        AddInCache(res);
    }
    if (res) {
        res->InitTheFace();
    }
    return res;
}
Ejemplo n.º 23
0
static void
gpk_log_startup_cb (GtkApplication *application, gpointer user_data)
{
	g_autoptr(GError) error = NULL;
	GtkTreeSelection *selection;
	GtkWidget *widget;
	GtkWindow *window;
	guint retval;

	client = pk_client_new ();
	g_object_set (client,
		      "background", FALSE,
		      NULL);

	/* get UI */
	builder = gtk_builder_new ();
	retval = gtk_builder_add_from_resource (builder,
						"/org/gnome/packagekit/gpk-log.ui",
						&error);
	if (retval == 0) {
		g_warning ("failed to load ui: %s", error->message);
		goto out;
	}

	window = GTK_WINDOW (gtk_builder_get_object (builder, "dialog_simple"));
	gtk_window_set_icon_name (window, GPK_ICON_SOFTWARE_LOG);
	gtk_window_set_application (window, application);

	/* set a size, as the screen allows */
	gpk_window_set_size_request (window, 1200, 1200);

	/* if command line arguments are set, then setup UI */
	if (filter != NULL) {
		widget = GTK_WIDGET (gtk_builder_get_object (builder, "entry_package"));
		gtk_entry_set_text (GTK_ENTRY(widget), filter);
	}

	widget = GTK_WIDGET (gtk_builder_get_object (builder, "button_refresh"));
	g_signal_connect (widget, "clicked", G_CALLBACK (gpk_log_button_refresh_cb), NULL);
	gtk_widget_hide (widget);
	widget = GTK_WIDGET (gtk_builder_get_object (builder, "button_filter"));
	g_signal_connect (widget, "clicked", G_CALLBACK (gpk_log_button_filter_cb), NULL);

	/* hit enter in the search box for filter */
	widget = GTK_WIDGET (gtk_builder_get_object (builder, "entry_package"));
	g_signal_connect (widget, "activate", G_CALLBACK (gpk_log_button_filter_cb), NULL);

	/* autocompletion can be turned off as it's slow */
	g_signal_connect (widget, "key-release-event", G_CALLBACK (gpk_log_entry_filter_cb), NULL);

	/* create list stores */
	list_store = gtk_list_store_new (GPK_LOG_COLUMN_LAST, G_TYPE_STRING, G_TYPE_STRING,
					 G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
					 G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN);

	/* create transaction_id tree view */
	widget = GTK_WIDGET (gtk_builder_get_object (builder, "treeview_simple"));
	gtk_tree_view_set_model (GTK_TREE_VIEW (widget),
				 GTK_TREE_MODEL (list_store));

	selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget));
	g_signal_connect (selection, "changed",
			  G_CALLBACK (gpk_log_treeview_clicked_cb), NULL);

	/* add columns to the tree view */
	pk_treeview_add_general_columns (GTK_TREE_VIEW (widget));
	gtk_tree_view_columns_autosize (GTK_TREE_VIEW (widget));

	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (list_store),
					      GPK_LOG_COLUMN_TIMESPEC, GTK_SORT_DESCENDING);

	/* show */
	widget = GTK_WIDGET (gtk_builder_get_object (builder, "dialog_simple"));
	gtk_widget_show (widget);

	/* set the parent window if it is specified */
	if (xid != 0) {
		g_debug ("Setting xid %i", xid);
		gpk_window_set_parent_xid (GTK_WINDOW (widget), xid);
	}

	/* get the update list */
	gpk_log_refresh ();
out:
	g_object_unref (list_store);
	g_object_unref (client);
	g_free (transaction_id);
	g_free (filter);
	if (transactions != NULL)
		g_ptr_array_unref (transactions);
}
Ejemplo n.º 24
0
Archivo: wmf.cpp Proyecto: mpuels/dia
static void
draw_bezier(DiaRenderer *self, 
	    BezPoint *points,
	    int numpoints,
	    Color *colour)
{
#ifndef DIRECT_WMF
    _bezier(self, points, numpoints, colour, FALSE, FALSE);
#else
    WmfRenderer *renderer = WMF_RENDERER (self);
    W32::HPEN    hPen;
    W32::POINT * pts;
    int i;

    DIAG_NOTE(renderer, "draw_bezier n:%d %fx%f ...\n", 
              numpoints, points->p1.x, points->p1.y);

    pts = g_new(W32::POINT, (numpoints-1) * 3 + 1);

    pts[0].x = SCX(points[0].p1.x);
    pts[0].y = SCY(points[0].p1.y);

    for (i = 1; i < numpoints; i++)
    {
        switch(points[i].type)
        {
        case _BezPoint::BEZ_MOVE_TO:
            g_warning("only first BezPoint can be a BEZ_MOVE_TO");
	  break;
        case _BezPoint::BEZ_LINE_TO:
            /* everyhing the same ?*/
            pts[i*3-2].x = pts[i*3-1].x = 
            pts[i*3  ].x = SCX(points[i].p1.x);
            pts[i*3-2].y = pts[i*3-1].y = 
            pts[i*3  ].y = SCY(points[i].p1.y);
          break;
        case _BezPoint::BEZ_CURVE_TO:
            /* control points */
            pts[i*3-2].x = SCX(points[i].p1.x);
            pts[i*3-2].y = SCY(points[i].p1.y);
            pts[i*3-1].x = SCX(points[i].p2.x);
            pts[i*3-1].y = SCY(points[i].p2.y);
            /* end point */
            pts[i*3  ].x = SCX(points[i].p3.x);
            pts[i*3  ].y = SCY(points[i].p3.y);
	  break;
        default:
        break;
        }
    }

    hPen = UsePen(renderer, colour);

    W32::PolyBezier(renderer->hFileDC,
		    pts, (numpoints-1)*3+1);

    DonePen(renderer, hPen);

    g_free(pts);
#endif
}
Ejemplo n.º 25
0
static gboolean
gst_dshowvideosrc_set_caps (GstBaseSrc * bsrc, GstCaps * caps)
{
  HRESULT hres;
  IPin *input_pin = NULL;
  GstDshowVideoSrc *src = GST_DSHOWVIDEOSRC (bsrc);
  GstStructure *s = gst_caps_get_structure (caps, 0);

  /* search the negociated caps in our caps list to get its index and the corresponding mediatype */
  if (gst_caps_is_subset (caps, src->caps)) {
    guint i = 0;
    gint res = -1;

    for (; i < gst_caps_get_size (src->caps) && res == -1; i++) {
      GstCaps *capstmp = gst_caps_copy_nth (src->caps, i);

      if (gst_caps_is_subset (caps, capstmp)) {
        res = i;
      }
      gst_caps_unref (capstmp);
    }

    if (res != -1 && src->pins_mediatypes) {
      /* get the corresponding media type and build the dshow graph */
      GList *type_pin_mediatype = g_list_nth (src->pins_mediatypes, res);

      if (type_pin_mediatype) {
        GstCapturePinMediaType *pin_mediatype =
            (GstCapturePinMediaType *) type_pin_mediatype->data;
        gchar *caps_string = NULL;
        gchar *src_caps_string = NULL;

        /* retrieve the desired video size */
        VIDEOINFOHEADER *video_info = NULL;
        gint width = 0;
        gint height = 0;
        gint numerator = 0;
        gint denominator = 0;
        gst_structure_get_int (s, "width", &width);
        gst_structure_get_int (s, "height", &height);
        gst_structure_get_fraction (s, "framerate", &numerator, &denominator);

        /* check if the desired video size is valid about granularity  */
        /* This check will be removed when GST_TYPE_INT_RANGE_STEP exits */
        /* See remarks in gst_dshow_new_video_caps function */
        if (pin_mediatype->granularityWidth != 0
            && width % pin_mediatype->granularityWidth != 0)
          g_warning ("your desired video size is not valid : %d mod %d !=0\n",
              width, pin_mediatype->granularityWidth);
        if (pin_mediatype->granularityHeight != 0
            && height % pin_mediatype->granularityHeight != 0)
          g_warning ("your desired video size is not valid : %d mod %d !=0\n",
              height, pin_mediatype->granularityHeight);

        /* update mediatype */
        video_info = (VIDEOINFOHEADER *) pin_mediatype->mediatype->pbFormat;
        video_info->bmiHeader.biWidth = width;
        video_info->bmiHeader.biHeight = height;
        video_info->AvgTimePerFrame =
            (LONGLONG) (10000000 * denominator / (double) numerator);
        video_info->bmiHeader.biSizeImage = DIBSIZE (video_info->bmiHeader);
        pin_mediatype->mediatype->lSampleSize = DIBSIZE (video_info->bmiHeader);

        src->dshow_fakesink->gst_set_media_type (pin_mediatype->mediatype);
        src->dshow_fakesink->gst_set_buffer_callback (
            (push_buffer_func) gst_dshowvideosrc_push_buffer, src);

        gst_dshow_get_pin_from_filter (src->dshow_fakesink, PINDIR_INPUT,
            &input_pin);
        if (!input_pin) {
          GST_ERROR ("Can't get input pin from our dshow fakesink");
          goto error;
        }

        hres = src->filter_graph->ConnectDirect (pin_mediatype->capture_pin,
            input_pin, pin_mediatype->mediatype);
        input_pin->Release ();

        if (hres != S_OK) {
          GST_ERROR
              ("Can't connect capture filter with fakesink filter (error=0x%x)",
              hres);
          goto error;
        }

        /* save width and height negociated */
        gst_structure_get_int (s, "width", &src->width);
        gst_structure_get_int (s, "height", &src->height);

        src->is_rgb = FALSE;
        caps_string = gst_caps_to_string (caps);
        if (caps_string) {
          if (strstr (caps_string, "video/x-raw-rgb")) {
            src->is_rgb = TRUE;
          } else {
            src->is_rgb = FALSE;
          }
          g_free (caps_string);
        }
      }
    }
  }

  return TRUE;

error:
  return FALSE;
}
Ejemplo n.º 26
0
/* converts a ISO 8601 time string to a time_t value */
time_t parseISO8601Date(gchar *date) {
	struct tm	tm;
	time_t		t, t2, offset = 0;
	gboolean	success = FALSE;
#ifdef G_OS_WIN32
	gchar *tmp = g_strdup(date);
	gint result, year, month, day, hour, minute, second;
#else
	gchar *pos;
#endif	
	g_assert(date != NULL);
	
	memset(&tm, 0, sizeof(struct tm));
	
#ifdef G_OS_WIN32
	g_strstrip(tmp);
	result = sscanf((const char *)date, "%d-%d-%dT%d:%d:%d", 
			&year, &month, &day, &hour, &minute, &second);
	if (result < 6)
		second = 0;
	if (result < 5)
		minute = 0;
	if (result < 4)
		hour = 0;
	if (result >= 3) {
		tm.tm_sec = second;
		tm.tm_min = minute;
		tm.tm_hour = hour;
		tm.tm_mday = day;
		tm.tm_mon = month - 1;
		tm.tm_year = year - 1900;
		tm.tm_wday = 0;
		tm.tm_yday = 0;
		tm.tm_isdst = -1;
		success = TRUE;
	}
#else
	/* we expect at least something like "2003-08-07T15:28:19" and
	   don't require the second fractions and the timezone info

	   the most specific format:   YYYY-MM-DDThh:mm:ss.sTZD
	 */
	 
	/* full specified variant */
	if(NULL != (pos = strptime((const char *)date, "%t%Y-%m-%dT%H:%M%t", &tm))) {
		/* Parse seconds */
		if (*pos == ':')
			pos++;
		if (isdigit(pos[0]) && !isdigit(pos[1])) {
			tm.tm_sec = pos[0] - '0';
			pos++;
		} else if (isdigit(pos[0]) && isdigit(pos[1])) {
			tm.tm_sec = 10*(pos[0]-'0') + pos[1] - '0';
			pos +=2;
		}
		/* Parse timezone */
		if (*pos == 'Z')
			offset = 0;
		else if ((*pos == '+' || *pos == '-') && isdigit(pos[1]) && isdigit(pos[2]) && strlen(pos) >= 3) {
			offset = (10*(pos[1] - '0') + (pos[2] - '0')) * 60 * 60;
			
			if (pos[3] == ':' && isdigit(pos[4]) && isdigit(pos[5]))
				offset +=  (10*(pos[4] - '0') + (pos[5] - '0')) * 60;
			else if (isdigit(pos[3]) && isdigit(pos[4]))
				offset +=  (10*(pos[3] - '0') + (pos[4] - '0')) * 60;
			
			offset *= (pos[0] == '+') ? 1 : -1;

		}
		success = TRUE;
	/* only date */
	} else if(NULL != strptime((const char *)date, "%t%Y-%m-%d", &tm))
		success = TRUE;
	/* there were others combinations too... */
#endif
	if(TRUE == success) {
		if((time_t)(-1) != (t = mktime(&tm))) {
			struct tm buft;
			/* Correct for the local timezone*/
			t = t - offset;
			t2 = mktime(gmtime_r(&t, &buft));
			t = t - (t2 - t);
			
			return t;
		} else {
			g_warning("internal error! time conversion error! mktime failed!\n");
		}
	} else {
		g_warning("Invalid ISO8601 date format! Ignoring <dc:date> information!\n");
	}
	
	return 0;
}
Ejemplo n.º 27
0
static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
{
	static struct sr_output *o = NULL;
	static int logic_probelist[SR_MAX_NUM_PROBES] = { 0 };
	static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
	static uint64_t received_samples = 0;
	static int unitsize = 0;
	static int triggered = 0;
	static FILE *outfile = NULL;
	static int num_analog_probes = 0;
	struct sr_probe *probe;
	struct sr_datafeed_logic *logic;
	struct sr_datafeed_meta_logic *meta_logic;
	struct sr_datafeed_analog *analog;
	struct sr_datafeed_meta_analog *meta_analog;
	static int num_enabled_analog_probes = 0;
	int num_enabled_probes, sample_size, ret, i;
	uint64_t output_len, filter_out_len;
	uint8_t *output_buf, *filter_out;

	/* If the first packet to come in isn't a header, don't even try. */
	if (packet->type != SR_DF_HEADER && o == NULL)
		return;

	sample_size = -1;
	switch (packet->type) {
	case SR_DF_HEADER:
		g_debug("cli: Received SR_DF_HEADER");
		/* Initialize the output module. */
		if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
			g_critical("Output module malloc failed.");
			exit(1);
		}
		o->format = output_format;
		o->dev = dev;
		o->param = output_format_param;
		if (o->format->init) {
			if (o->format->init(o) != SR_OK) {
				g_critical("Output format initialization failed.");
				exit(1);
			}
		}
		break;

	case SR_DF_END:
		g_debug("cli: Received SR_DF_END");
		if (!o) {
			g_debug("cli: double end!");
			break;
		}
		if (o->format->event) {
			o->format->event(o, SR_DF_END, &output_buf, &output_len);
			if (output_buf) {
				if (outfile)
					fwrite(output_buf, 1, output_len, outfile);
				g_free(output_buf);
				output_len = 0;
			}
		}
		if (limit_samples && received_samples < limit_samples)
			g_warning("Device only sent %" PRIu64 " samples.",
			       received_samples);
		if (opt_continuous)
			g_warning("Device stopped after %" PRIu64 " samples.",
			       received_samples);
		sr_session_stop();
		if (outfile && outfile != stdout)
			fclose(outfile);
		g_free(o);
		o = NULL;
		break;

	case SR_DF_TRIGGER:
		g_debug("cli: received SR_DF_TRIGGER");
		if (o->format->event)
			o->format->event(o, SR_DF_TRIGGER, &output_buf,
					 &output_len);
		triggered = 1;
		break;

	case SR_DF_META_LOGIC:
		g_message("cli: Received SR_DF_META_LOGIC");
		meta_logic = packet->payload;
		num_enabled_probes = 0;
		for (i = 0; i < meta_logic->num_probes; i++) {
			probe = g_slist_nth_data(dev->probes, i);
			if (probe->enabled)
				logic_probelist[num_enabled_probes++] = probe->index;
		}
		/* How many bytes we need to store num_enabled_probes bits */
		unitsize = (num_enabled_probes + 7) / 8;

		outfile = stdout;
		if (opt_output_file) {
			if (default_output_format) {
				/* output file is in session format, which means we'll
				 * dump everything in the datastore as it comes in,
				 * and save from there after the session. */
				outfile = NULL;
				ret = sr_datastore_new(unitsize, &(dev->datastore));
				if (ret != SR_OK) {
					printf("Failed to create datastore.\n");
					exit(1);
				}
			} else {
				/* saving to a file in whatever format was set
				 * with --format, so all we need is a filehandle */
				outfile = g_fopen(opt_output_file, "wb");
			}
		}
		if (opt_pds)
			srd_session_start(num_enabled_probes, unitsize,
					meta_logic->samplerate);
		break;

	case SR_DF_LOGIC:
		logic = packet->payload;
		g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
		sample_size = logic->unitsize;
		if (logic->length == 0)
			break;

		/* Don't store any samples until triggered. */
		if (opt_wait_trigger && !triggered)
			break;

		if (limit_samples && received_samples >= limit_samples)
			break;

		ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
					   logic->data, logic->length,
					   &filter_out, &filter_out_len);
		if (ret != SR_OK)
			break;

		/* what comes out of the filter is guaranteed to be packed into the
		 * minimum size needed to support the number of samples at this sample
		 * size. however, the driver may have submitted too much -- cut off
		 * the buffer of the last packet according to the sample limit.
		 */
		if (limit_samples && (received_samples + logic->length / sample_size >
				limit_samples * sample_size))
			filter_out_len = limit_samples * sample_size - received_samples;

		if (dev->datastore)
			sr_datastore_put(dev->datastore, filter_out,
					 filter_out_len, sample_size, logic_probelist);

		if (opt_output_file && default_output_format)
			/* saving to a session file, don't need to do anything else
			 * to this data for now. */
			goto cleanup;

		if (opt_pds) {
			if (srd_session_send(received_samples, (uint8_t*)filter_out,
					filter_out_len) != SRD_OK)
				sr_session_stop();
		} else {
			output_len = 0;
			if (o->format->data && packet->type == o->format->df_type)
				o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
			if (output_buf) {
				fwrite(output_buf, 1, output_len, outfile);
				fflush(outfile);
				g_free(output_buf);
			}
		}

		cleanup:
		g_free(filter_out);
		received_samples += logic->length / sample_size;
		break;

	case SR_DF_META_ANALOG:
		g_message("cli: Received SR_DF_META_ANALOG");
		meta_analog = packet->payload;
		num_analog_probes = meta_analog->num_probes;
		num_enabled_analog_probes = 0;
		for (i = 0; i < num_analog_probes; i++) {
			probe = g_slist_nth_data(dev->probes, i);
			if (probe->enabled)
				analog_probelist[num_enabled_analog_probes++] = probe;
		}

		outfile = stdout;
		if (opt_output_file) {
			if (default_output_format) {
				/* output file is in session format, which means we'll
				 * dump everything in the datastore as it comes in,
				 * and save from there after the session. */
				outfile = NULL;
				ret = sr_datastore_new(unitsize, &(dev->datastore));
				if (ret != SR_OK) {
					printf("Failed to create datastore.\n");
					exit(1);
				}
			} else {
				/* saving to a file in whatever format was set
				 * with --format, so all we need is a filehandle */
				outfile = g_fopen(opt_output_file, "wb");
			}
		}
		break;

	case SR_DF_ANALOG:
		analog = packet->payload;
		g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
		if (analog->num_samples == 0)
			break;

		if (limit_samples && received_samples >= limit_samples)
			break;

		if (o->format->data && packet->type == o->format->df_type) {
			o->format->data(o, (const uint8_t *)analog->data,
					analog->num_samples * sizeof(float),
					&output_buf, &output_len);
			if (output_buf) {
				fwrite(output_buf, 1, output_len, outfile);
				fflush(outfile);
				g_free(output_buf);
			}
		}

		received_samples += analog->num_samples;
		break;

	case SR_DF_FRAME_BEGIN:
		g_debug("cli: received SR_DF_FRAME_BEGIN");
		if (o->format->event) {
			o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
					 &output_len);
			if (output_buf) {
				fwrite(output_buf, 1, output_len, outfile);
				fflush(outfile);
				g_free(output_buf);
			}
		}
		break;

	case SR_DF_FRAME_END:
		g_debug("cli: received SR_DF_FRAME_END");
		if (o->format->event) {
			o->format->event(o, SR_DF_FRAME_END, &output_buf,
					 &output_len);
			if (output_buf) {
				fwrite(output_buf, 1, output_len, outfile);
				fflush(outfile);
				g_free(output_buf);
			}
		}
		break;

	default:
		g_message("received unknown packet type %d", packet->type);
	}

}
Ejemplo n.º 28
0
/**
 * gimp_config_deserialize_property:
 * @config: a #GimpConfig.
 * @scanner: a #GScanner.
 * @nest_level: the nest level
 *
 * This function deserializes a single property of @config. You
 * shouldn't need to call this function directly. If possible, use
 * gimp_config_deserialize_properties() instead.
 *
 * Return value: %G_TOKEN_RIGHT_PAREN on success, otherwise the
 * expected #GTokenType or %G_TOKEN_NONE if the expected token was
 * found but couldn't be parsed.
 *
 * Since: 2.4
 **/
GTokenType
gimp_config_deserialize_property (GimpConfig *config,
                                  GScanner   *scanner,
                                  gint        nest_level)
{
  GimpConfigInterface *config_iface = NULL;
  GimpConfigInterface *parent_iface = NULL;
  GParamSpec          *prop_spec;
  GTokenType           token        = G_TOKEN_RIGHT_PAREN;
  GValue               value        = G_VALUE_INIT;
  guint                old_scope_id;

  old_scope_id = g_scanner_set_scope (scanner, 0);

  prop_spec = G_PARAM_SPEC (scanner->value.v_symbol);

  g_value_init (&value, prop_spec->value_type);

  if (G_TYPE_IS_OBJECT (prop_spec->owner_type))
    {
      GTypeClass *owner_class = g_type_class_peek (prop_spec->owner_type);

      config_iface = g_type_interface_peek (owner_class, GIMP_TYPE_CONFIG);

      /*  We must call deserialize_property() *only* if the *exact* class
       *  which implements it is param_spec->owner_type's class.
       *
       *  Therefore, we ask param_spec->owner_type's immediate parent class
       *  for it's GimpConfigInterface and check if we get a different
       *  pointer.
       *
       *  (if the pointers are the same, param_spec->owner_type's
       *   GimpConfigInterface is inherited from one of it's parent classes
       *   and thus not able to handle param_spec->owner_type's properties).
       */
      if (config_iface)
        {
          GTypeClass *owner_parent_class;

          owner_parent_class = g_type_class_peek_parent (owner_class);

          parent_iface = g_type_interface_peek (owner_parent_class,
                                                GIMP_TYPE_CONFIG);
        }
    }

  if (config_iface                       &&
      config_iface != parent_iface       && /* see comment above */
      config_iface->deserialize_property &&
      config_iface->deserialize_property (config,
                                          prop_spec->param_id,
                                          &value,
                                          prop_spec,
                                          scanner,
                                          &token))
    {
      /* nop */
    }
  else
    {
      if (G_VALUE_HOLDS_OBJECT (&value) &&
          G_VALUE_TYPE (&value) != G_TYPE_FILE)
        {
          token = gimp_config_deserialize_object (&value,
                                                  config, prop_spec,
                                                  scanner, nest_level);
        }
      else
        {
          token = gimp_config_deserialize_value (&value,
                                                 config, prop_spec, scanner);
        }
    }

  if (token == G_TOKEN_RIGHT_PAREN &&
      g_scanner_peek_next_token (scanner) == token)
    {
      if (! (G_VALUE_HOLDS_OBJECT (&value) &&
             (prop_spec->flags & GIMP_CONFIG_PARAM_AGGREGATE)))
        g_object_set_property (G_OBJECT (config), prop_spec->name, &value);
    }
#ifdef CONFIG_DEBUG
  else
    {
      g_warning ("%s: couldn't deserialize property %s::%s of type %s",
                 G_STRFUNC,
                 g_type_name (G_TYPE_FROM_INSTANCE (config)),
                 prop_spec->name,
                 g_type_name (prop_spec->value_type));
    }
#endif

  g_value_unset (&value);

  g_scanner_set_scope (scanner, old_scope_id);

  return token;
}
Ejemplo n.º 29
0
int main (int argc, char * argv[])
{
  GtsSurface * s;
  gboolean verbose = FALSE;
  int c = 0;

  if (!setlocale (LC_ALL, "POSIX"))
    g_warning ("cannot set locale to POSIX");

  /* parse options using getopt */
  while (c != EOF) {
#ifdef HAVE_GETOPT_LONG
    static struct option long_options[] = {
      {"help", no_argument, NULL, 'h'},
      {"verbose", no_argument, NULL, 'v'},
    };
    int option_index = 0;
    switch ((c = getopt_long (argc, argv, "hv",
			      long_options, &option_index))) {
#else /* not HAVE_GETOPT_LONG */
    switch ((c = getopt (argc, argv, "hv"))) {
#endif /* not HAVE_GETOPT_LONG */
    case 'v': /* verbose */
      verbose = TRUE;
      break;
    case 'h': /* help */
      fprintf (stderr,
             "Usage: merge [OPTION] file1.gts file2.gts ...\n"
	     "Merges files and outputs the resulting GTS surface.\n"
	     "\n"
	     "  -v        --verbose       print statistics about the surface\n"
	     "  -h        --help          display this help and exit\n"
	     "\n"
	     "Reports bugs to %s\n",
	     GTS_MAINTAINER);
      return 0; /* success */
      break;
    case '?': /* wrong options */
      fprintf (stderr, "Try `merge --help' for more information.\n");
      return 1; /* failure */
    }
  }

  s = GTS_SURFACE (gts_object_new (GTS_OBJECT_CLASS (gts_surface_class ())));

  while (optind < argc) {
    FILE * f = fopen (argv[optind], "r");
    GtsFile * fp;
    GtsSurface * s1;

    if (f == NULL) {
      fprintf (stderr, "merge: can not open file `%s'\n", argv[optind]);
      return 1;
    }
    fp = gts_file_new (f);
    s1 = GTS_SURFACE (gts_object_new (GTS_OBJECT_CLASS (gts_surface_class ())));
    if (gts_surface_read (s1, fp)) {
      fprintf (stderr, "merge: `%s' is not a valid GTS surface file\n", 
	       argv[optind]);
      fprintf (stderr, "%s:%d:%d: %s\n", argv[optind], fp->line, fp->pos, fp->error);
      return 1;
    }
    gts_surface_merge (s, s1);
    gts_object_destroy (GTS_OBJECT (s1));
    gts_file_destroy (fp);
    fclose (f);
    optind++;
  }

  if (verbose)
    gts_surface_print_stats (s, stderr);

  gts_surface_write (s, stdout);

  return 0;
}
Ejemplo n.º 30
0
G_MODULE_EXPORT gboolean
tracker_extract_get_metadata (TrackerExtractInfo *info)
{
    TrackerConfig *config;
    GTime creation_date;
    GError *error = NULL;
    TrackerResource *metadata;
    TrackerXmpData *xd = NULL;
    PDFData pd = { 0 }; /* actual data */
    PDFData md = { 0 }; /* for merging */
    PopplerDocument *document;
    gchar *xml = NULL;
    gchar *content, *uri;
    guint n_bytes;
    GPtrArray *keywords;
    guint i;
    GFile *file;
    gchar *filename;
    int fd;
    gchar *contents = NULL;
    gsize len;
    struct stat st;

    file = tracker_extract_info_get_file (info);
    filename = g_file_get_path (file);

    fd = tracker_file_open_fd (filename);

    if (fd == -1) {
        g_warning ("Could not open pdf file '%s': %s\n",
                   filename,
                   g_strerror (errno));
        g_free (filename);
        return FALSE;
    }

    if (fstat (fd, &st) == -1) {
        g_warning ("Could not fstat pdf file '%s': %s\n",
                   filename,
                   g_strerror (errno));
        close (fd);
        g_free (filename);
        return FALSE;
    }

    if (st.st_size == 0) {
        contents = NULL;
        len = 0;
    } else {
        contents = (gchar *) mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
        if (contents == NULL || contents == MAP_FAILED) {
            g_warning ("Could not mmap pdf file '%s': %s\n",
                       filename,
                       g_strerror (errno));
            close (fd);
            g_free (filename);
            return FALSE;
        }
        len = st.st_size;
    }

    g_free (filename);
    uri = g_file_get_uri (file);

    document = poppler_document_new_from_data (contents, len, NULL, &error);

    if (error) {
        if (error->code == POPPLER_ERROR_ENCRYPTED) {
            metadata = tracker_resource_new (NULL);

            tracker_resource_add_uri (metadata, "rdf:type", "nfo:PaginatedTextDocument");
            tracker_resource_set_boolean (metadata, "nfo:isContentEncrypted", TRUE);

            tracker_extract_info_set_resource (info, metadata);
            g_object_unref (metadata);

            g_error_free (error);
            g_free (uri);
            close (fd);

            return TRUE;
        } else {
            g_warning ("Couldn't create PopplerDocument from uri:'%s', %s",
                       uri,
                       error->message ? error->message : "no error given");

            g_error_free (error);
            g_free (uri);
            close (fd);

            return FALSE;
        }
    }

    if (!document) {
        g_warning ("Could not create PopplerDocument from uri:'%s', "
                   "NULL returned without an error",
                   uri);
        g_free (uri);
        close (fd);
        return FALSE;
    }

    metadata = tracker_resource_new (NULL);
    tracker_resource_add_uri (metadata, "rdf:type", "nfo:PaginatedTextDocument");

    g_object_get (document,
                  "title", &pd.title,
                  "author", &pd.author,
                  "subject", &pd.subject,
                  "keywords", &pd.keywords,
                  "creation-date", &creation_date,
                  "metadata", &xml,
                  NULL);

    if (creation_date > 0) {
        pd.creation_date = tracker_date_to_string ((time_t) creation_date);
    }

    keywords = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);

    if (xml && *xml &&
            (xd = tracker_xmp_new (xml, strlen (xml), uri)) != NULL) {
        /* The casts here are well understood and known */
        md.title = (gchar *) tracker_coalesce_strip (4, pd.title, xd->title, xd->title2, xd->pdf_title);
        md.subject = (gchar *) tracker_coalesce_strip (2, pd.subject, xd->subject);
        md.date = (gchar *) tracker_coalesce_strip (3, pd.creation_date, xd->date, xd->time_original);
        md.author = (gchar *) tracker_coalesce_strip (2, pd.author, xd->creator);

        write_pdf_data (md, metadata, keywords);

        if (xd->keywords) {
            tracker_keywords_parse (keywords, xd->keywords);
        }

        if (xd->pdf_keywords) {
            tracker_keywords_parse (keywords, xd->pdf_keywords);
        }

        if (xd->publisher) {
            TrackerResource *publisher = tracker_extract_new_contact (xd->publisher);
            tracker_resource_set_relation (metadata, "nco:publisher", publisher);
            g_object_unref (publisher);
        }

        if (xd->type) {
            tracker_resource_set_string (metadata, "dc:type", xd->type);
        }

        if (xd->format) {
            tracker_resource_set_string (metadata, "dc:format", xd->format);
        }

        if (xd->identifier) {
            tracker_resource_set_string (metadata, "dc:identifier", xd->identifier);
        }

        if (xd->source) {
            tracker_resource_set_string (metadata, "dc:source", xd->source);
        }

        if (xd->language) {
            tracker_resource_set_string (metadata, "dc:language", xd->language);
        }

        if (xd->relation) {
            tracker_resource_set_string (metadata, "dc:relation", xd->relation);
        }

        if (xd->coverage) {
            tracker_resource_set_string (metadata, "dc:coverage", xd->coverage);
        }

        if (xd->license) {
            tracker_resource_set_string (metadata, "nie:license", xd->license);
        }

        if (xd->make || xd->model) {
            TrackerResource *equipment = tracker_extract_new_equipment (xd->make, xd->model);
            tracker_resource_set_relation (metadata, "nfo:equipment", equipment);
            g_object_unref (equipment);
        }

        if (xd->orientation) {
            tracker_resource_set_string (metadata, "nfo:orientation", xd->orientation);
        }

        if (xd->rights) {
            tracker_resource_set_string (metadata, "nie:copyright", xd->rights);
        }

        if (xd->white_balance) {
            tracker_resource_set_string (metadata, "nmm:whiteBalance", xd->white_balance);
        }

        if (xd->fnumber) {
            gdouble value;

            value = g_strtod (xd->fnumber, NULL);
            tracker_resource_set_double (metadata, "nmm:fnumber", value);
        }

        if (xd->flash) {
            tracker_resource_set_string (metadata, "nmm:flash", xd->flash);
        }

        if (xd->focal_length) {
            gdouble value;

            value = g_strtod (xd->focal_length, NULL);
            tracker_resource_set_double (metadata, "nmm:focalLength", value);
        }

        /* Question: Shouldn't xd->Artist be merged with md.author instead? */

        if (xd->artist || xd->contributor) {
            TrackerResource *artist;
            const gchar *artist_name;

            artist_name = tracker_coalesce_strip (2, xd->artist, xd->contributor);

            artist = tracker_extract_new_contact (artist_name);

            tracker_resource_set_relation (metadata, "nco:contributor", artist);

            g_object_unref (artist);
        }

        if (xd->exposure_time) {
            gdouble value;

            value = g_strtod (xd->exposure_time, NULL);
            tracker_resource_set_double (metadata, "nmm:exposureTime", value);
        }

        if (xd->iso_speed_ratings) {
            gdouble value;

            value = g_strtod (xd->iso_speed_ratings, NULL);
            tracker_resource_set_double (metadata, "nmm:isoSpeed", value);
        }

        if (xd->description) {
            tracker_resource_set_string (metadata, "nie:description", xd->description);
        }

        if (xd->metering_mode) {
            tracker_resource_set_string (metadata, "nmm:meteringMode", xd->metering_mode);
        }

        if (xd->address || xd->state || xd->country || xd->city ||
                xd->gps_altitude || xd->gps_latitude || xd-> gps_longitude) {

            TrackerResource *location = tracker_extract_new_location (xd->address,
                                        xd->state, xd->city, xd->country, xd->gps_altitude,
                                        xd->gps_latitude, xd->gps_longitude);

            tracker_resource_set_relation (metadata, "slo:location", location);

            g_object_unref (location);
        }

        if (xd->regions) {
            tracker_xmp_apply_regions_to_resource (metadata, xd);
        }

        tracker_xmp_free (xd);
    } else {
        /* So if we are here we have NO XMP data and we just
         * write what we know from Poppler.
         */
        write_pdf_data (pd, metadata, keywords);
    }

    for (i = 0; i < keywords->len; i++) {
        TrackerResource *tag;
        const gchar *p;

        p = g_ptr_array_index (keywords, i);
        tag = tracker_extract_new_tag (p);

        tracker_resource_add_relation (metadata, "nao:hasTag", tag);

        g_object_unref (tag);
    }
    g_ptr_array_free (keywords, TRUE);

    tracker_resource_set_int64 (metadata, "nfo:pageCount", poppler_document_get_n_pages(document));

    config = tracker_main_get_config ();
    n_bytes = tracker_config_get_max_bytes (config);
    content = extract_content_text (document, n_bytes);

    if (content) {
        tracker_resource_set_string (metadata, "nie:plainTextContent", content);
        g_free (content);
    }

    read_outline (document, metadata);

    g_free (xml);
    g_free (pd.keywords);
    g_free (pd.title);
    g_free (pd.subject);
    g_free (pd.creation_date);
    g_free (pd.author);
    g_free (pd.date);
    g_free (uri);

    g_object_unref (document);

    if (contents) {
        munmap (contents, len);
    }

    close (fd);

    tracker_extract_info_set_resource (info, metadata);
    g_object_unref (metadata);

    return TRUE;
}