xref: /haiku/src/apps/icon-o-matic/import_export/svg/SVGImporter.cpp (revision 204dee708a999d5a71d0cb9497650ee7cef85d0a)
1 /*
2  * Copyright 2006-2009, Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Stephan Aßmus <superstippi@gmx.de>
7  */
8 
9 #include "SVGImporter.h"
10 
11 #include <Alert.h>
12 #include <Catalog.h>
13 #include <Entry.h>
14 #include <File.h>
15 #include <Locale.h>
16 #include <Path.h>
17 
18 #include "DocumentBuilder.h"
19 #include "SVGParser.h"
20 
21 
22 #undef B_TRANSLATION_CONTEXT
23 #define B_TRANSLATION_CONTEXT "Icon-O-Matic-SVGImport"
24 
25 
26 // constructor
27 SVGImporter::SVGImporter()
28 {
29 }
30 
31 // destructor
32 SVGImporter::~SVGImporter()
33 {
34 }
35 
36 // Import
37 status_t
38 SVGImporter::Import(Icon* icon, const entry_ref* ref)
39 {
40 	status_t ret = Init(icon);
41 	if (ret < B_OK) {
42 		printf("SVGImporter::Import() - "
43 			   "Init() error: %s\n", strerror(ret));
44 		return ret;
45 	}
46 
47 	BPath path(ref);
48 	ret = path.InitCheck();
49 	if (ret < B_OK)
50 		return ret;
51 
52 	// peek into file to see if this could be an SVG file at all
53 	BFile file(path.Path(), B_READ_ONLY);
54 	ret = file.InitCheck();
55 	if (ret < B_OK)
56 		return ret;
57 
58 	ssize_t size = 5;
59 	char buffer[size + 1];
60 	if (file.Read(buffer, size) != size)
61 		return B_ERROR;
62 
63 	// 0 terminate
64 	buffer[size] = 0;
65 	if (strcasecmp(buffer, "<?xml") != 0) {
66 		// we might be  stretching it a bit, but what the heck
67 		return B_ERROR;
68 	}
69 
70     try {
71 		agg::svg::DocumentBuilder builder;
72 		agg::svg::Parser parser(builder);
73 		parser.parse(path.Path());
74 		ret = builder.GetIcon(icon, this, ref->name);
75 	} catch(agg::svg::exception& e) {
76 		char error[1024];
77 		sprintf(error, B_TRANSLATE("Failed to open the file '%s' as "
78 					   "an SVG document.\n\n"
79 					   "Error: %s"), ref->name, e.msg());
80 		BAlert* alert = new BAlert(B_TRANSLATE("load error"),
81 								   error, B_TRANSLATE("OK"), NULL, NULL,
82 								   B_WIDTH_AS_USUAL, B_WARNING_ALERT);
83 		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
84 		alert->Go(NULL);
85 		ret = B_ERROR;
86 	}
87 
88 	return ret;
89 }
90