1/*
2 * Copyright 2006-2007, Haiku. 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 "SourceExporter.h"
10
11#include <stdio.h>
12#include <string.h>
13
14#include <DataIO.h>
15
16// constructor
17SourceExporter::SourceExporter()
18	: FlatIconExporter()
19{
20}
21
22// destructor
23SourceExporter::~SourceExporter()
24{
25}
26
27// Export
28status_t
29SourceExporter::Export(const Icon* icon, BPositionIO* stream)
30{
31	BMallocIO buffer;
32	status_t ret = FlatIconExporter::Export(icon, &buffer);
33	if (ret < B_OK)
34		return ret;
35
36	return _Export((const uint8*)buffer.Buffer(), buffer.BufferLength(),
37		stream);
38}
39
40// MIMEType
41const char*
42SourceExporter::MIMEType()
43{
44	return "text/x-source-code";
45}
46
47// #pragma mark -
48
49// _Export
50status_t
51SourceExporter::_Export(const uint8* source, size_t sourceSize,
52	BPositionIO* stream) const
53{
54	char buffer[2048];
55	// write header
56	sprintf(buffer, "\nconst unsigned char kIconName[] = {\n");
57	size_t size = strlen(buffer);
58
59	ssize_t written = stream->Write(buffer, size);
60	if (written < 0)
61		return (status_t)written;
62	if (written < (ssize_t)size)
63		return B_ERROR;
64
65	status_t ret = B_OK;
66	const uint8* b = source;
67
68	// print one line (12 values)
69	while (sourceSize > 12) {
70		sprintf(buffer, "	0x%.2x, 0x%.2x, 0x%.2x, 0x%.2x"
71						", 0x%.2x, 0x%.2x, 0x%.2x, 0x%.2x"
72						", 0x%.2x, 0x%.2x, 0x%.2x, 0x%.2x,\n",
73						b[0], b[1], b[2], b[3],
74						b[4], b[5], b[6], b[7],
75						b[8], b[9], b[10], b[11]);
76
77		size = strlen(buffer);
78		written = stream->Write(buffer, size);
79		if (written != (ssize_t)size) {
80			if (written >= 0)
81				ret = B_ERROR;
82			else
83				ret = (status_t)written;
84			break;
85		}
86
87		sourceSize -= 12;
88		b += 12;
89	}
90	// last line (up to 12 values)
91	if (ret >= B_OK && sourceSize > 0) {
92		for (size_t i = 0; i < sourceSize; i++) {
93			if (i == 0)
94				sprintf(buffer, "	0x%.2x", b[i]);
95			else
96				sprintf(buffer, ", 0x%.2x", b[i]);
97			size = strlen(buffer);
98			written = stream->Write(buffer, size);
99			if (written != (ssize_t)size) {
100				if (written >= 0)
101					ret = B_ERROR;
102				else
103					ret = (status_t)written;
104				break;
105			}
106		}
107	}
108	if (ret >= B_OK) {
109		// finish
110		sprintf(buffer, "\n};\n");
111		size = strlen(buffer);
112		written = stream->Write(buffer, size);
113		if (written != (ssize_t)size) {
114			if (written >= 0)
115				ret = B_ERROR;
116			else
117				ret = (status_t)written;
118		}
119	}
120
121	return ret;
122}
123
124