summaryrefslogtreecommitdiffstats
path: root/src/sp-factory.cpp
blob: 272584ca63ac5f0c629f007f29b2dd5c34fd9c56 (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
#include "sp-factory.h"

#include <stdexcept>

#include "sp-object.h"
#include "xml/node.h"


SPFactory::TypeNotRegistered::TypeNotRegistered(const std::string& type)
	: std::exception(), type(type) {
}

const char* SPFactory::TypeNotRegistered::what() const noexcept {
	return type.c_str();
}

SPFactory& SPFactory::instance() {
	static SPFactory factory;
	return factory;
}

bool SPFactory::registerObject(const std::string& id, std::function<SPObject* ()> createFunction) {
	return this->objectMap.insert(std::make_pair(id, createFunction)).second;

	// replace when gcc supports this
	//return this->objectMap.emplace(id, createFunction).second;
}

SPObject* SPFactory::createObject(const Inkscape::XML::Node& id) const {
	std::string name;

	switch (id.type()) {
		case Inkscape::XML::TEXT_NODE:
			name = "string";
			break;

		case Inkscape::XML::ELEMENT_NODE: {
			gchar const* const sptype = id.attribute("sodipodi:type");

			if (sptype) {
				name = sptype;
			} else {
				name = id.name();
			}
			break;
		}
		default:
			break;
	}

	try {
		std::function<SPObject* ()> createFunction = this->objectMap.at(name);
		return createFunction();
	} catch (const std::out_of_range& ex) {
		std::throw_with_nested(TypeNotRegistered(name));
	}
}