File: NMR_OpcPackageReader.cpp

package info (click to toggle)
lib3mf 1.8.1%2Bds-6
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 12,652 kB
  • sloc: cpp: 34,988; ansic: 4,255; sh: 109; makefile: 12
file content (341 lines) | stat: -rw-r--r-- 10,745 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
/*++

Copyright (C) 2018 3MF Consortium

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Abstract:

NMR_OpcPackageReader.cpp defines an OPC Package reader in a portable way.

--*/

#include "Common/OPC/NMR_OpcPackageReader.h" 
#include "Common/OPC/NMR_OpcPackageRelationshipReader.h" 
#include "Common/OPC/NMR_OpcPackageContentTypesReader.h" 
#include "Common/Platform/NMR_ImportStream_ZIP.h" 
#include "Common/NMR_Exception.h" 
#include "Common/NMR_StringUtils.h" 

#include "Model/Classes/NMR_ModelConstants.h"

#include <iostream>

namespace NMR {
	
	// custom callbck function for reading from a CImportStream on the fly
	zip_int64_t custom_zip_source_callback(void *userData, void *data, zip_uint64_t len, zip_source_cmd_t cmd) {
		if (userData == nullptr)
			throw CNMRException(NMR_ERROR_INVALIDPARAM);

		CImportStream* pImportStream = (CImportStream*)(userData);

		switch (cmd) {
			case ZIP_SOURCE_SUPPORTS:
				zip_int64_t bitmap;
				bitmap = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE,
					ZIP_SOURCE_STAT, ZIP_SOURCE_FREE, ZIP_SOURCE_ERROR, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_SUPPORTS, -1);
				return bitmap;

			case ZIP_SOURCE_SEEK:
				zip_source_args_seek argsSeek;
				argsSeek = * ((zip_source_args_seek *)data);
				if (argsSeek.whence == SEEK_SET)
					pImportStream->seekPosition(argsSeek.offset, true);
				else if (argsSeek.whence == SEEK_CUR) {
					pImportStream->seekPosition(pImportStream->getPosition() + argsSeek.offset, true);
				}
				else if (argsSeek.whence == SEEK_END) {
					if (argsSeek.offset > 0)
						throw CNMRException(NMR_ERROR_ZIPCALLBACK);
					pImportStream->seekFromEnd(-argsSeek.offset, true);
				}
				else
					throw CNMRException(NMR_ERROR_ZIPCALLBACK);
				return 0;

			case ZIP_SOURCE_OPEN:
				return 0;

			case ZIP_SOURCE_READ:
				return pImportStream->readBuffer((nfByte*)data, len, true);

			case ZIP_SOURCE_CLOSE:
				return 0;

			case ZIP_SOURCE_TELL:
				return pImportStream->getPosition();

			case ZIP_SOURCE_FREE:
				return 0;

			case ZIP_SOURCE_STAT:
				zip_stat_t* zipStat;
				zipStat  = (zip_stat_t*)data;
				zip_stat_init(zipStat);
				zipStat->size = pImportStream->retrieveSize();
				zipStat->valid |= ZIP_STAT_SIZE;
				return sizeof(zip_stat_t);

			default:
				throw CNMRException(NMR_ERROR_ZIPCALLBACK);
		}
		return -1;
	}

	COpcPackageReader::COpcPackageReader(_In_ PImportStream pImportStream, _In_ PModelReaderWarnings pWarnings)
	{
		m_pWarnings = pWarnings;
		
		if (pImportStream.get() == nullptr)
			throw CNMRException(NMR_ERROR_INVALIDPARAM);

		m_ZIPError.str = nullptr;
		m_ZIPError.sys_err = 0;
		m_ZIPError.zip_err = 0;
		m_ZIParchive = nullptr;
		zip_source_t* pZIPsource = nullptr;

		try {
			// determine stream size
			nfUint64 nStreamSize = pImportStream->retrieveSize();
			pImportStream->seekPosition(0, true);

			if (nStreamSize == 0)
				throw CNMRException(NMR_ERROR_COULDNOTGETSTREAMPOSITION);

			// create ZIP objects
			zip_error_init(&m_ZIPError);

#ifdef NMR_COM_NATIVE
			bool bUseCallback = false;
#else
			bool bUseCallback = true;
#endif
			if (bUseCallback) {
				// read ZIP from callback: faster and requires less memory
				pZIPsource = zip_source_function_create(custom_zip_source_callback, pImportStream.get(), &m_ZIPError);
			}
			else {
				// read ZIP into memory
				m_Buffer.resize((size_t)nStreamSize);
				pImportStream->readBuffer(&m_Buffer[0], nStreamSize, true);
				pZIPsource = zip_source_buffer_create(&m_Buffer[0], (size_t)nStreamSize, 0, &m_ZIPError);
			}
			if (pZIPsource == nullptr)
				throw CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);

			m_ZIParchive = zip_open_from_source(pZIPsource, ZIP_RDONLY | ZIP_CHECKCONS, &m_ZIPError);
			if (m_ZIParchive == nullptr) {
				m_ZIParchive = zip_open_from_source(pZIPsource, ZIP_RDONLY, &m_ZIPError);
				if (m_ZIParchive == nullptr)
					throw CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);
				else
					m_pWarnings->addException(CNMRException(NMR_ERROR_ZIPCONTAINSINCONSISTENCIES), mrwInvalidMandatoryValue);
			}

			// Get ZIP Content
			nfInt64 nEntryCount = zip_get_num_entries(m_ZIParchive, ZIP_FL_UNCHANGED);
			if (nEntryCount < 0)
				throw CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);

			// List Entries
			nfInt64 nIndex;
			for (nIndex = 0; nIndex < nEntryCount; nIndex++) {
				const char * pszName = zip_get_name(m_ZIParchive, (nfUint64) nIndex, ZIP_FL_ENC_GUESS);
				m_ZIPEntries.insert(std::make_pair(pszName, nIndex));
			}

			readContentTypes();
			readRootRelationships();

		}
		catch (...)
		{
			releaseZIP();
			throw;
		}
	}

	COpcPackageReader::~COpcPackageReader()
	{
		releaseZIP();
	}

	_Ret_maybenull_ COpcPackageRelationship * COpcPackageReader::findRootRelation(_In_ std::string sRelationType, _In_ nfBool bMustBeUnique)
	{
		COpcPackageRelationship * pResultRelationship = nullptr;
		auto iIterator = m_RootRelationships.begin();
		while (iIterator != m_RootRelationships.end()) {
			POpcPackageRelationship pRelationship = *iIterator;

			std::string sType = pRelationship->getType();
			if (sType == sRelationType) {
				if (pResultRelationship == nullptr) {
					pResultRelationship = pRelationship.get();
				}
				else {
					if (bMustBeUnique)
						m_pWarnings->addException(CNMRException(NMR_ERROR_OPCRELATIONSHIPNOTUNIQUE), eModelReaderWarningLevel::mrwInvalidOptionalValue);
				}

			}
			iIterator++;
		}

		return pResultRelationship;
	}

	void COpcPackageReader::releaseZIP()
	{
		if (m_ZIParchive != nullptr)
			zip_close(m_ZIParchive);

		zip_error_fini(&m_ZIPError);
		m_Buffer.resize(0);

		m_ZIParchive = nullptr;
	}

	PImportStream COpcPackageReader::openZIPEntry(_In_ std::string sName)
	{
		auto iIterator = m_ZIPEntries.find(sName);
		if (iIterator == m_ZIPEntries.end()) {
			return nullptr;
		}

		return openZIPEntryIndexed(iIterator->second);


	}

	PImportStream COpcPackageReader::openZIPEntryIndexed(_In_ nfUint64 nIndex)
	{

		zip_stat_t Stat;
		nfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat);
		if (nResult != 0)
			throw CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);

		nfUint64 nSize = Stat.size;

		zip_file_t * pFile = zip_fopen_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED);
		if (pFile == nullptr)
			throw CNMRException(NMR_ERROR_COULDNOTOPENZIPENTRY);

		return std::make_shared<CImportStream_ZIP>(pFile, nSize);

	}


	void COpcPackageReader::readContentTypes()
	{
		PImportStream pContentStream = openZIPEntry(OPCPACKAGE_PATH_CONTENTTYPES);

		POpcPackageContentTypesReader pReader = std::make_shared<COpcPackageContentTypesReader>(pContentStream);

		nfUint32 nCount = pReader->getCount();
		nfUint32 nIndex;

		std::string modelExtension = "";
		std::string modelPart = "";
		m_relationShipExtension = "";
		for (nIndex = 0; nIndex < nCount; nIndex++) {
			POpcPackageContentType pContentType = pReader->getContentType(nIndex);
			if (pContentType->m_contentType == PACKAGE_3D_RELS_CONTENT_TYPE) {
				m_relationShipExtension = pContentType->m_extension;
			}
			if (pContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) {
				modelExtension = pContentType->m_extension;
			}
		}
		if (m_relationShipExtension.empty())
			throw CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_RELATIONSHIP);

		nCount = pReader->getOverrideCount();
		for (nIndex = 0; nIndex < nCount; nIndex++) {
			POpcPackageContentType_Override pOverrideContentType = pReader->getOverrideContentType(nIndex);
			if (pOverrideContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) {
				modelPart = pOverrideContentType->m_partName;
			}
		}

		if (modelExtension.empty() && modelPart.empty())
			throw CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_MODEL);
	}

	void COpcPackageReader::readRootRelationships()
	{
		PImportStream pRelStream = openZIPEntry(OPCPACKAGE_PATH_ROOTRELATIONSHIPS);

		POpcPackageRelationshipReader pReader = std::make_shared<COpcPackageRelationshipReader>(pRelStream);

		nfUint32 nCount = pReader->getCount();
		nfUint32 nIndex;

		for (nIndex = 0; nIndex < nCount; nIndex++) {
			m_RootRelationships.push_back(pReader->getRelationShip(nIndex));
		}
	}

	POpcPackagePart COpcPackageReader::createPart(_In_ std::string sPath)
	{
		std::string sRealPath = fnRemoveLeadingPathDelimiter (sPath);
		auto iPartIterator = m_Parts.find(sRealPath);
		if (iPartIterator != m_Parts.end()) {
			return iPartIterator->second;
		}
		
		PImportStream pStream = openZIPEntry(sRealPath);
		if (pStream.get() == nullptr)
			throw CNMRException(NMR_ERROR_COULDNOTCREATEOPCPART);

		POpcPackagePart pPart = std::make_shared<COpcPackagePart>(sRealPath, pStream);
		m_Parts.insert(std::make_pair(sRealPath, pPart));

		std::string sRelationShipName = fnExtractFileName(sRealPath);
		std::string sRelationShipPath = sRealPath.substr(0, sRealPath.length() - sRelationShipName.length());
		sRelationShipPath += "_rels/";
		sRelationShipPath += sRelationShipName;
		sRelationShipPath += "."+m_relationShipExtension;

		PImportStream pRelStream = openZIPEntry(sRelationShipPath);

		if (pRelStream.get() != nullptr) {
		    POpcPackageRelationshipReader pReader = std::make_shared<COpcPackageRelationshipReader>(pRelStream);

		    nfUint32 nCount = pReader->getCount();
		    nfUint32 nIndex;

		    for (nIndex = 0; nIndex < nCount; nIndex++) {
		    	POpcPackageRelationship pRelationShip = pReader->getRelationShip(nIndex);
		    	pPart->addRelationship(pRelationShip->getID(), pRelationShip->getType(), pRelationShip->getTargetPartURI());
		    }
		}


		return pPart;
	}


}