File: pps-document-factory.c

package info (click to toggle)
papers 49.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 21,044 kB
  • sloc: ansic: 37,728; sh: 197; xml: 127; makefile: 113
file content (426 lines) | stat: -rw-r--r-- 12,382 bytes parent folder | download | duplicates (2)
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
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 *  Copyright (C) 2005, Red Hat, Inc.
 *  Copyright © 2018 Christian Persch
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>

#include <gio/gio.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <gtk/gtk.h>

#include "pps-backend-info.h"
#include "pps-document-factory.h"
#include "pps-file-helpers.h"

/* Backends manager */

#define BACKEND_DATA_KEY "pps-backend-info"

static GList *pps_backends_list = NULL;
static GHashTable *pps_module_hash = NULL;
static gchar *pps_backends_dir = NULL;

static PpsDocument *pps_document_factory_new_document_for_mime_type (const char *mime_type,
                                                                     GError **error);

static PpsBackendInfo *
get_backend_info_for_mime_type (const gchar *mime_type)
{
	GList *l;
	g_autofree gchar *content_type = g_content_type_from_mime_type (mime_type);

	for (l = pps_backends_list; l; l = l->next) {
		PpsBackendInfo *info = (PpsBackendInfo *) l->data;
		char **mime_types = info->mime_types;
		guint i;

		for (i = 0; mime_types[i] != NULL; ++i)
			if (g_content_type_is_mime_type (content_type, mime_types[i]))
				return info;
	}

	return NULL;
}

static PpsBackendInfo *
get_backend_info_for_document (PpsDocument *document)
{
	PpsBackendInfo *info;

	info = g_object_get_data (G_OBJECT (document), BACKEND_DATA_KEY);

	g_warn_if_fail (info != NULL);
	return info;
}

static PpsDocument *
pps_document_factory_new_document_for_mime_type (const gchar *mime_type,
                                                 GError **error)
{
	PpsDocument *document;
	PpsBackendInfo *info;
	GModule *module = NULL;
	GType backend_type;
	GType (*query_type_function) (void) = NULL;

	g_return_val_if_fail (mime_type != NULL, NULL);

	info = get_backend_info_for_mime_type (mime_type);
	if (info == NULL) {
		char *content_type, *mime_desc = NULL;

		content_type = g_content_type_from_mime_type (mime_type);
		if (content_type)
			mime_desc = g_content_type_get_description (content_type);

		g_set_error (error,
		             PPS_DOCUMENT_ERROR,
		             PPS_DOCUMENT_ERROR_INVALID,
		             _ ("File type %s (%s) is not supported"),
		             mime_desc ? mime_desc : "(unknown)", mime_type);
		g_free (mime_desc);
		g_free (content_type);

		return NULL;
	}

	if (pps_module_hash != NULL) {
		module = g_hash_table_lookup (pps_module_hash, info->module_name);
	}
	if (module == NULL) {
		g_autofree gchar *path = NULL;

		path = g_strconcat (pps_backends_dir, G_DIR_SEPARATOR_S,
		                    info->module_name, NULL);

		module = g_module_open (path, 0);

		if (!g_module_symbol (module, "pps_backend_query_type",
		                      (void *) &query_type_function)) {
			const char *err = g_module_error ();
			g_set_error (error, PPS_DOCUMENT_ERROR, PPS_DOCUMENT_ERROR_INVALID,
			             "Failed to load backend for '%s': %s",
			             mime_type, err ? err : "unknown error");
			g_module_close (module);
			return NULL;
		}

		/* Make the module resident so it can’t be unloaded: without using a
		 * full #GTypePlugin implementation for the modules, it’s not safe to
		 * re-load a module and re-register its types with GObject, as that will
		 * confuse the GType system. */
		g_module_make_resident (module);

		if (pps_module_hash == NULL) {
			pps_module_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
			                                         g_free,
			                                         NULL /* leaked on purpose */);
		}
		g_hash_table_insert (pps_module_hash, g_strdup (info->module_name), module);
	}

	if (!query_type_function && !g_module_symbol (module, "pps_backend_query_type",
	                                              (void *) &query_type_function)) {
		const char *err = g_module_error ();
		g_set_error (error, PPS_DOCUMENT_ERROR, PPS_DOCUMENT_ERROR_INVALID,
		             "Failed to load backend for '%s': %s",
		             mime_type, err ? err : "unknown error");
		return NULL;
	}

	backend_type = query_type_function ();
	g_assert (g_type_is_a (backend_type, PPS_TYPE_DOCUMENT));

	document = g_object_new (backend_type, NULL);

	g_object_set_data (G_OBJECT (document), BACKEND_DATA_KEY, info);

	return document;
}

static PpsCompressionType
get_compression_from_mime_type (const gchar *mime_type)
{
	gchar type[3];
	gchar *p;

	if (!(p = g_strrstr (mime_type, "/")))
		return PPS_COMPRESSION_NONE;

	if (sscanf (++p, "x-%2s%*s", type) == 1) {
		if (g_ascii_strcasecmp (type, "gz") == 0)
			return PPS_COMPRESSION_GZIP;
		else if (g_ascii_strcasecmp (type, "bz") == 0)
			return PPS_COMPRESSION_BZIP2;
		else if (g_ascii_strcasecmp (type, "xz") == 0)
			return PPS_COMPRESSION_LZMA;
	}

	return PPS_COMPRESSION_NONE;
}

/*
 * new_document_for_uri:
 * @uri: the document URI
 * @fast: whether to use fast MIME type detection
 * @compression: a location to store the document's compression type
 * @error: a #GError location to store an error, or %NULL
 *
 * Creates a #PpsDocument instance for the document at @uri, using either
 * fast or slow MIME type detection. If a document could be created,
 * @compression is filled in with the document's compression type.
 * On error, %NULL is returned and @error filled in.
 *
 * Returns: a new #PpsDocument instance, or %NULL on error with @error filled in
 */
static PpsDocument *
new_document_for_uri (const char *uri,
                      gboolean fast,
                      PpsCompressionType *compression,
                      GError **error)
{
	PpsDocument *document = NULL;
	g_autofree gchar *mime_type;

	*compression = PPS_COMPRESSION_NONE;

	mime_type = pps_file_get_mime_type (uri, fast, error);
	if (mime_type == NULL)
		return NULL;

	document = pps_document_factory_new_document_for_mime_type (mime_type, error);
	if (document == NULL)
		return NULL;

	*compression = get_compression_from_mime_type (mime_type);

	return document;
}

static void
free_uncompressed_uri (gchar *uri_unc)
{
	if (!uri_unc)
		return;

	pps_tmp_uri_unlink (uri_unc);
	g_free (uri_unc);
}

/*
 * _pps_document_factory_init:
 *
 * Initializes the papers document factory.
 *
 * Returns: %TRUE if there were any backends found; %FALSE otherwise
 */
gboolean
_pps_document_factory_init (void)
{
	if (pps_backends_list)
		return TRUE;

	if (g_getenv ("PPS_BACKENDS_DIR") != NULL)
		pps_backends_dir = g_strdup (g_getenv ("PPS_BACKENDS_DIR"));

	if (!pps_backends_dir) {
		pps_backends_dir = g_strdup (PPS_BACKENDSDIR);
	}

	pps_backends_list = _pps_backend_info_load_from_dir (pps_backends_dir);

	return pps_backends_list != NULL;
}

/*
 * _pps_document_factory_shutdown:
 *
 * Shuts the papers document factory down.
 */
void
_pps_document_factory_shutdown (void)
{
	g_clear_list (&pps_backends_list, (GDestroyNotify) _pps_backend_info_free);

	g_clear_pointer (&pps_module_hash, g_hash_table_unref);
	g_clear_pointer (&pps_backends_dir, g_free);
}

/**
 * pps_document_factory_get_document:
 * @uri: an URI
 * @error: a #GError location to store an error, or %NULL
 *
 * Creates a #PpsDocument for the document at @uri; or, if no backend handling
 * the document's type is found, or an error occurred on opening the document,
 * returns %NULL and fills in @error.
 * If the document is encrypted, it is returned but also @error is set to
 * %PPS_DOCUMENT_ERROR_ENCRYPTED.
 *
 * Returns: (transfer full): a new #PpsDocument, or %NULL
 */
PpsDocument *
pps_document_factory_get_document (const char *uri,
                                   GError **error)
{
	g_autoptr (PpsDocument) document = NULL;
	PpsCompressionType compression;
	gchar *uri_unc = NULL;
	GError *err = NULL;
	gboolean fast = TRUE;

	g_return_val_if_fail (uri != NULL, NULL);

	// Run twice, once with fast=TRUE, one with fast=FALSE
	for (int i = 0; i < 2; i++, fast = !fast) {
		document = new_document_for_uri (uri, fast, &compression, &err);
		g_assert (document != NULL || err != NULL);

		if (err != NULL) {
			if (i == 0)
				g_clear_error (&err);

			continue;
		}

		uri_unc = pps_file_uncompress (uri, compression, &err);
		if (err != NULL) {
			/* Error uncompressing file */
			g_propagate_error (error, err);
			return NULL;
		}
		if (uri_unc)
			g_object_set_data_full (G_OBJECT (document),
			                        "uri-uncompressed",
			                        uri_unc,
			                        (GDestroyNotify) free_uncompressed_uri);

		return g_steal_pointer (&document);
	}

	g_assert (err != NULL);
	g_propagate_error (error, err);
	return NULL;
}

/**
 * pps_document_factory_get_document_for_fd:
 * @fd: a file descriptor
 * @mime_type: the mime type
 * @error: (allow-none): a #GError location to store an error, or %NULL
 *
 * Synchronously creates a #PpsDocument for the document from @fd using the backend
 * for loading documents of type @mime_type; or, if the backend does not support
 * loading from file descriptors, or an error occurred on opening the document,
 * returns %NULL and fills in @error.
 * If the document is encrypted, it is returned but also @error is set to
 * %PPS_DOCUMENT_ERROR_ENCRYPTED.
 *
 * If the mime type cannot be inferred from the file descriptor, and @mime_type is %NULL,
 * an error is returned.
 *
 * Note that this function takes ownership of @fd; you must not ever
 * operate on it again. It will be closed automatically if the document
 * is destroyed, or if this function returns %NULL.
 *
 * Returns: (transfer full): a new #PpsDocument, or %NULL
 *
 * Since: 42.0
 */
PpsDocument *
pps_document_factory_get_document_for_fd (int fd,
                                          const char *mime_type,
                                          GError **error)
{
	g_return_val_if_fail (fd != -1, NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

	if (mime_type == NULL) {
		g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
		                     "Cannot query mime type from file descriptor");
		return NULL;
	}

	return pps_document_factory_new_document_for_mime_type (mime_type, error);
}

static void
file_filter_add_mime_types (PpsBackendInfo *info, GtkFileFilter *filter)
{
	char **mime_types;
	guint i;

	mime_types = info->mime_types;
	if (mime_types == NULL)
		return;

	for (i = 0; mime_types[i] != NULL; ++i)
		gtk_file_filter_add_mime_type (filter, mime_types[i]);
}

/**
 * pps_document_factory_add_filters:
 * @dialog: a #GtkFileDialog
 * @document: (nullable): a #PpsDocument, or %NULL
 *
 * Adds some file filters to @dialog.

 * Always add a "All documents" format.
 *
 * If @document is not %NULL, adds a #GtkFileFilter for @document's MIME type.
 *
 * If @document is %NULL, adds a #GtkFileFilter for each document type that papers
 * can handle.
 */
void
pps_document_factory_add_filters (GtkFileDialog *dialog, PpsDocument *document)
{
	GtkFileFilter *all_documents_filter, *default_filter, *all_files_filter;
	GListStore *filters = g_list_store_new (GTK_TYPE_FILTER);

	g_return_if_fail (GTK_IS_FILE_DIALOG (dialog));
	g_return_if_fail (document == NULL || PPS_IS_DOCUMENT (document));

	default_filter = all_documents_filter = gtk_file_filter_new ();
	gtk_file_filter_set_name (all_documents_filter, _ ("All Documents"));
	g_list_foreach (pps_backends_list, (GFunc) file_filter_add_mime_types,
	                all_documents_filter);
	g_list_store_append (filters, all_documents_filter);

	if (document) {
		PpsBackendInfo *info;

		info = get_backend_info_for_document (document);
		g_assert (info != NULL);
		default_filter = gtk_file_filter_new ();
		gtk_file_filter_set_name (default_filter, info->type_desc);
		file_filter_add_mime_types (info, default_filter);
		g_list_store_append (filters, default_filter);
	} else {
		GList *l;

		for (l = pps_backends_list; l; l = l->next) {
			GtkFileFilter *filter = gtk_file_filter_new ();
			PpsBackendInfo *info = (PpsBackendInfo *) l->data;

			gtk_file_filter_set_name (filter, info->type_desc);
			file_filter_add_mime_types (info, filter);
			g_list_store_append (filters, filter);
		}
	}

	all_files_filter = gtk_file_filter_new ();
	gtk_file_filter_set_name (all_files_filter, _ ("All Files"));
	gtk_file_filter_add_pattern (all_files_filter, "*");
	g_list_store_append (filters, all_files_filter);

	gtk_file_dialog_set_filters (dialog, G_LIST_MODEL (filters));
	gtk_file_dialog_set_default_filter (dialog, default_filter);
}