summaryrefslogtreecommitdiff
path: root/pluma/pluma-document-input-stream.c
blob: 82e60acd5c38270a5b97f888e41dee6103958a4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/*
 * pluma-document-input-stream.c
 * This file is part of pluma
 *
 * Copyright (C) 2010 - Ignacio Casal Quinteiro
 *
 * pluma is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * pluma is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with pluma; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, 
 * Boston, MA  02110-1301  USA
 */

#include "config.h"

#include <glib.h>
#include <gio/gio.h>
#include <string.h>
#include "pluma-document-input-stream.h"
#include "pluma-enum-types.h"

/* NOTE: never use async methods on this stream, the stream is just
 * a wrapper around GtkTextBuffer api so that we can use GIO Stream
 * methods, but the undelying code operates on a GtkTextBuffer, so
 * there is no I/O involved and should be accessed only by the main
 * thread */


G_DEFINE_TYPE (PlumaDocumentInputStream, pluma_document_input_stream, G_TYPE_INPUT_STREAM);

struct _PlumaDocumentInputStreamPrivate
{
	GtkTextBuffer *buffer;
	GtkTextMark   *pos;
	gint           bytes_partial;

	PlumaDocumentNewlineType newline_type;

	guint newline_added : 1;
	guint is_initialized : 1;
};

enum
{
	PROP_0,
	PROP_BUFFER,
	PROP_NEWLINE_TYPE
};

static gssize     pluma_document_input_stream_read     (GInputStream      *stream,
							void              *buffer,
							gsize              count,
							GCancellable      *cancellable,
							GError           **error);
static gboolean   pluma_document_input_stream_close    (GInputStream      *stream,
							GCancellable      *cancellable,
							GError           **error);

static void
pluma_document_input_stream_set_property (GObject      *object,
					  guint         prop_id,
					  const GValue *value,
					  GParamSpec   *pspec)
{
	PlumaDocumentInputStream *stream = PLUMA_DOCUMENT_INPUT_STREAM (object);

	switch (prop_id)
	{
		case PROP_BUFFER:
			stream->priv->buffer = GTK_TEXT_BUFFER (g_value_get_object (value));
			break;

		case PROP_NEWLINE_TYPE:
			stream->priv->newline_type = g_value_get_enum (value);
			break;

		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
pluma_document_input_stream_get_property (GObject    *object,
					  guint       prop_id,
					  GValue     *value,
					  GParamSpec *pspec)
{
	PlumaDocumentInputStream *stream = PLUMA_DOCUMENT_INPUT_STREAM (object);

	switch (prop_id)
	{
		case PROP_BUFFER:
			g_value_set_object (value, stream->priv->buffer);
			break;

		case PROP_NEWLINE_TYPE:
			g_value_set_enum (value, stream->priv->newline_type);
			break;

		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
pluma_document_input_stream_class_init (PlumaDocumentInputStreamClass *klass)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
	GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);

	g_type_class_add_private (klass, sizeof (PlumaDocumentInputStreamPrivate));

	gobject_class->get_property = pluma_document_input_stream_get_property;
	gobject_class->set_property = pluma_document_input_stream_set_property;

	stream_class->read_fn = pluma_document_input_stream_read;
	stream_class->close_fn = pluma_document_input_stream_close;

	g_object_class_install_property (gobject_class,
					 PROP_BUFFER,
					 g_param_spec_object ("buffer",
							      "Buffer",
							      "The buffer which is read",
							      GTK_TYPE_TEXT_BUFFER,
							      G_PARAM_READWRITE |
							      G_PARAM_CONSTRUCT_ONLY));

	/**
	 * PlumaDocumentInputStream:newline-type:
	 *
	 * The :newline-type property determines what is considered
	 * as a line ending when reading complete lines from the stream.
	 */ 
	g_object_class_install_property (gobject_class,
					 PROP_NEWLINE_TYPE,
					 g_param_spec_enum ("newline-type",
							    "Newline type",
							    "The accepted types of line ending",
							    PLUMA_TYPE_DOCUMENT_NEWLINE_TYPE,
							    PLUMA_DOCUMENT_NEWLINE_TYPE_LF,
							    G_PARAM_READWRITE |
							    G_PARAM_STATIC_NAME |
							    G_PARAM_STATIC_BLURB |
							    G_PARAM_CONSTRUCT_ONLY));
}

static void
pluma_document_input_stream_init (PlumaDocumentInputStream *stream)
{
	stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
						    PLUMA_TYPE_DOCUMENT_INPUT_STREAM,
						    PlumaDocumentInputStreamPrivate);
}

static gsize
get_new_line_size (PlumaDocumentInputStream *stream)
{
	gsize ret;

	switch (stream->priv->newline_type)
	{
		case PLUMA_DOCUMENT_NEWLINE_TYPE_CR:
		case PLUMA_DOCUMENT_NEWLINE_TYPE_LF:
			ret = 1;
			break;

		case PLUMA_DOCUMENT_NEWLINE_TYPE_CR_LF:
			ret = 2;
			break;

		default:
			g_warn_if_reached ();
			ret = 1;
			break;
	}

	return ret;
}

/**
 * pluma_document_input_stream_new:
 * @buffer: a #GtkTextBuffer
 *
 * Reads the data from @buffer.
 *
 * Returns: a new #GInputStream to read @buffer
 */
GInputStream *
pluma_document_input_stream_new (GtkTextBuffer           *buffer,
				 PlumaDocumentNewlineType type)
{
	PlumaDocumentInputStream *stream;

	g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);

	stream = g_object_new (PLUMA_TYPE_DOCUMENT_INPUT_STREAM,
			       "buffer", buffer,
			       "newline-type", type,
			       NULL);

	return G_INPUT_STREAM (stream);
}

gsize
pluma_document_input_stream_get_total_size (PlumaDocumentInputStream *stream)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT_INPUT_STREAM (stream), 0);

	return gtk_text_buffer_get_char_count (stream->priv->buffer);
}

gsize
pluma_document_input_stream_tell (PlumaDocumentInputStream *stream)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT_INPUT_STREAM (stream), 0);

	/* FIXME: is this potentially inefficient? If yes, we could keep
	   track of the offset internally, assuming the mark doesn't move
	   during the operation */
	if (!stream->priv->is_initialized)
	{
		return 0;
	}
	else
	{
		GtkTextIter iter;

		gtk_text_buffer_get_iter_at_mark (stream->priv->buffer,
						  &iter,
						  stream->priv->pos);
		return gtk_text_iter_get_offset (&iter);
	}
}

static const gchar *
get_new_line (PlumaDocumentInputStream *stream)
{
	const gchar *ret;

	switch (stream->priv->newline_type)
	{
		case PLUMA_DOCUMENT_NEWLINE_TYPE_CR:
			ret = "\r";
			break;

		case PLUMA_DOCUMENT_NEWLINE_TYPE_LF:
			ret = "\n";
			break;

		case PLUMA_DOCUMENT_NEWLINE_TYPE_CR_LF:
			ret = "\r\n";
			break;

		default:
			g_warn_if_reached ();
			ret = "\n";
			break;
	}

	return ret;
}

static gsize
read_line (PlumaDocumentInputStream *stream,
	   gchar                    *outbuf,
	   gsize                     space_left)
{
	GtkTextIter start, next, end;
	gchar *buf;
	gint bytes; /* int since it's what iter_get_offset returns */
	gsize bytes_to_write, newline_size, read;
	const gchar *newline;
	gboolean is_last;

	gtk_text_buffer_get_iter_at_mark (stream->priv->buffer,
					  &start,
					  stream->priv->pos);

	if (gtk_text_iter_is_end (&start))
		return 0;

	end = next = start;
	newline = get_new_line (stream);

	/* Check needed for empty lines */
	if (!gtk_text_iter_ends_line (&end))
		gtk_text_iter_forward_to_line_end (&end);

	gtk_text_iter_forward_line (&next);

	buf = gtk_text_iter_get_slice (&start, &end);

	/* the bytes of a line includes also the newline, so with the
	   offsets we remove the newline and we add the new newline size */
	bytes = gtk_text_iter_get_bytes_in_line (&start) - stream->priv->bytes_partial;

	/* bytes_in_line includes the newlines, so we remove that assuming that
	   they are single byte characters */
	bytes = bytes - (gtk_text_iter_get_offset (&next) - gtk_text_iter_get_offset (&end));
	is_last = gtk_text_iter_is_end (&end);

	/* bytes_to_write contains the amount of bytes we would like to write.
	   This means its the amount of bytes in the line (without the newline
	   in the buffer) + the amount of bytes for the newline we want to
	   write (newline_size) */
	bytes_to_write = bytes;

	/* do not add the new newline_size for the last line */
	newline_size = get_new_line_size (stream);
	if (!is_last)
		bytes_to_write += newline_size;

	if (bytes_to_write > space_left)
	{
		gchar *ptr;
		gint char_offset;
		gint written;
		gsize to_write;

		/* Here the line does not fit in the buffer, we thus write
		   the amount of bytes we can still fit, storing the position
		   for the next read with the mark. Do not try to write the
		   new newline in this case, it will be handled in the next
		   iteration */
		to_write = MIN (space_left, bytes);
		ptr = buf;
		written = 0;
		char_offset = 0;

		while (written < to_write)
		{
			gint w;

			ptr = g_utf8_next_char (ptr);
			w = (ptr - buf);
			if (w > to_write)
			{
				break;
			}
			else
			{
				written = w;
				++char_offset;
			}
		}

		memcpy (outbuf, buf, written);

		/* Note: offset is one past what we wrote */
		gtk_text_iter_forward_chars (&start, char_offset);
		stream->priv->bytes_partial += written;
		read = written;
	}
	else
	{
		/* First just copy the bytes without the newline */
		memcpy (outbuf, buf, bytes);

		/* Then add the newline, but not for the last line */
		if (!is_last)
		{
			memcpy (outbuf + bytes, newline, newline_size);
		}

		start = next;
		stream->priv->bytes_partial = 0;
		read = bytes_to_write;
	}

	gtk_text_buffer_move_mark (stream->priv->buffer,
				   stream->priv->pos,
				   &start);

	g_free (buf);
	return read;
}

static gssize
pluma_document_input_stream_read (GInputStream  *stream,
				  void          *buffer,
				  gsize          count,
				  GCancellable  *cancellable,
				  GError       **error)
{
	PlumaDocumentInputStream *dstream;
	GtkTextIter iter;
	gssize space_left, read, n;

	dstream = PLUMA_DOCUMENT_INPUT_STREAM (stream);

	if (count < 6)
	{
		g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NO_SPACE,
				     "Not enougth space in destination");
		return -1;
	}

	if (g_cancellable_set_error_if_cancelled (cancellable, error))
		return -1;

	/* Initialize the mark to the first char in the text buffer */
	if (!dstream->priv->is_initialized)
	{
		gtk_text_buffer_get_start_iter (dstream->priv->buffer, &iter);
		dstream->priv->pos = gtk_text_buffer_create_mark (dstream->priv->buffer,
								 NULL,
								 &iter,
								 FALSE);

		dstream->priv->is_initialized = TRUE;
	}

	space_left = count;
	read = 0;

	do
	{
		n = read_line (dstream, (void *) ((gsize) buffer + read), space_left);
		read += n;
		space_left -= n;
	} while (space_left > 0 && n != 0 && dstream->priv->bytes_partial == 0);

	/* Make sure that non-empty files are always terminated with \n (see bug #95676).
	 * Note that we strip the trailing \n when loading the file */
	gtk_text_buffer_get_iter_at_mark (dstream->priv->buffer,
					  &iter,
					  dstream->priv->pos);

	if (gtk_text_iter_is_end (&iter) &&
	    !gtk_text_iter_is_start (&iter))
	{
		gssize newline_size;

		newline_size = get_new_line_size (dstream);

		if (space_left >= newline_size &&
		    !dstream->priv->newline_added)
		{
			const gchar *newline;

			newline = get_new_line (dstream);

			memcpy ((void *) ((gsize) buffer + read), newline, newline_size);

			read += newline_size;
			dstream->priv->newline_added = TRUE;
		}
	}

	return read;
}

static gboolean
pluma_document_input_stream_close (GInputStream  *stream,
				   GCancellable  *cancellable,
				   GError       **error)
{
	PlumaDocumentInputStream *dstream = PLUMA_DOCUMENT_INPUT_STREAM (stream);

	dstream->priv->newline_added = FALSE;

	if (dstream->priv->is_initialized)
	{
		gtk_text_buffer_delete_mark (dstream->priv->buffer, dstream->priv->pos);
	}

	return TRUE;
}