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