HierarchConfNamed *HierarchyInstaller::GetLeaf(const char *leafName, HierarchConfNamed *root, Registry *r) { StartTrace1(HierarchyInstaller.GetLeaf, (root ? "" : "root is null!")); HierarchConfNamed *leaf = Find(leafName, r); Trace("leaf [" << leafName << "] " << (leaf ? "" : "not ") << "found in registry"); String rootName("//"); if (!leaf) { if (root) { root->GetName(rootName); Trace("cloning [" << rootName << "]"); // configured cloning but without config loading yet, done below leaf = (HierarchConfNamed *) root->ConfiguredClone(GetCategory(), leafName, false); } if (leaf && (rootName != leafName)) { Trace("registering [" << leafName << "] in registry"); r->RegisterRegisterableObject(leafName, leaf); } } if (leaf) { DoInitializeLeaf(leafName, leaf); } SystemLog::WriteToStderr(".", 1); return leaf; }
bool MyApp::OnInit() { #if wxUSE_LIBPNG wxImage::AddHandler( new wxPNGHandler ); #endif wxImage image; if (image.LoadFile(_T("backgrnd.png"), wxBITMAP_TYPE_PNG)) { m_background = wxBitmap(image); } MyFrame *frame = new MyFrame(); wxString rootName(_T("shape0")); int i; for (i = 1; i < 4; i++) { wxString filename; filename.Printf(wxT("%s%d.png"), (const wxChar*)rootName, i); /* For some reason under wxX11, the 2nd LoadFile in this loop fails, with a BadMatch inside CreateFromImage (inside ConvertToBitmap). This happens even if you copy the first file over the second file. */ if (image.LoadFile(filename, wxBITMAP_TYPE_PNG)) { DragShape* newShape = new DragShape(wxBitmap(image)); newShape->SetPosition(wxPoint(i*50, i*50)); if (i == 2) newShape->SetDragMethod(SHAPE_DRAG_TEXT); else if (i == 3) newShape->SetDragMethod(SHAPE_DRAG_ICON); else newShape->SetDragMethod(SHAPE_DRAG_BITMAP); frame->GetCanvas()->GetDisplayList().Append(newShape); } } #if 0 // Under Motif or GTK, this demonstrates that // wxScreenDC only gets the root window content. // We need to be able to copy the overall content // for full-screen dragging to work. int w, h; wxDisplaySize(& w, & h); wxBitmap bitmap(w, h); wxScreenDC dc; wxMemoryDC memDC; memDC.SelectObject(bitmap); memDC.Blit(0, 0, w, h, & dc, 0, 0); memDC.SelectObject(wxNullBitmap); m_background = bitmap; #endif frame->Show( true ); return true; }
// Create the document bool ctConfigToolDoc::OnCreate(const wxString& path, long flags) { GetCommandProcessor()->SetEditMenu(wxGetApp().GetMainFrame()->GetEditMenu()); GetCommandProcessor()->Initialize(); GetCommandProcessor()->ClearCommands(); // wxGetApp().m_currentDoc = this; if (flags & wxDOC_NEW) { ctConfigItem* rootItem = new ctConfigItem(NULL, ctTypeGroup, _T("Configuration")); //rootItem->InitProperties(); rootItem->GetProperties().AddProperty( new ctProperty( wxT("The item description."), wxVariant(wxT(""), wxT("description")), wxT("multiline"))); rootItem->SetPropertyString(_T("description"), _T("<B>This is the top-level configuration item.</B>")); SetTopItem(rootItem); Modify(false); SetDocumentSaved(false); wxString rootName(wxT("untitled")); wxStripExtension(rootName); SetFilename(wxGetApp().GetSettings().GenerateFilename(rootName)); } // Creates the view, so do any view updating after this bool success = wxDocument::OnCreate(path, flags); if (success) { if (flags & wxDOC_NEW) { wxBusyCursor wait; ctConfigToolHint hint(NULL, ctInitialUpdate); UpdateAllViews (NULL, & hint); SetFilename(GetFilename(), true); } } return success; }
// returns true if all folders were visited or false if traversal was aborted bool MFolderTraversal::DoTraverse(const wxString& start, RecurseMode mode) { Profile_obj profile(start); CHECK( profile, false, _T("panic in MFolderTraversal: no profile") ); // enumerate all groups String name; Profile::EnumData cookie; wxString rootName(start); if ( !rootName.empty() ) rootName += _T('/'); //else: there should be no leading slash for ( bool cont = profile->GetFirstGroup(name, cookie); cont; cont = profile->GetNextGroup(name, cookie) ) { wxString fullname(rootName); fullname += name; // traverse the children before/after the parent or not at all depending // on the mode if ( mode != Recurse_ChildrenFirst ) { // we traverse the parent first or only the parent if ( !OnVisitFolder(fullname) ) return false; if ( mode == Recurse_No ) continue; } if ( !DoTraverse(fullname, mode) ) return false; if ( mode == Recurse_ChildrenFirst ) { if ( !OnVisitFolder(fullname) ) return false; } } return true; }
void HK_CALL hkDefaultDemo::setupSkyBox(hkDemoEnvironment* env, const char* skyBoxFileName) { if (!skyBoxFileName) { skyBoxFileName = "Resources/Common/Graphics/defaultskybox"; } hkString rootName (skyBoxFileName); hkString upName = rootName + "_UP.png"; hkString downName = rootName + "_DN.png"; hkString leftName = rootName + "_LF.png"; hkString rightName = rootName + "_RT.png"; hkString frontName = rootName + "_FR.png"; hkString backName = rootName + "_BK.png"; // see which way is 'up' hkgCamera* cam = env->m_window->getViewport(0)->getCamera(); float worldUp[3]; cam->getBestAlignedUpVector(worldUp); hkgSkyBox* sky = hkgSkyBox::create(); sky->setUpDirection( worldUp ); const char* names[] = { upName.cString(), downName.cString(), leftName.cString(), rightName.cString(), frontName.cString(), backName.cString() }; for (int i=0; i < 6; ++i) { hkIstream s(names[i]); if (!s.isOk()) continue; hkgTexture* t = hkgTexture::create(env->m_window->getContext()); t->loadFromPNG(s); t->realize(); t->setTextureWrapModeU(HKG_TEXTURE_CLAMP); t->setTextureWrapModeV(HKG_TEXTURE_CLAMP); sky->setTexture((HKG_SKYBOX_FACE)i, t, 0xffffffff ); t->release(); } env->m_window->getViewport(0)->setSkyBox(sky); sky->release(); }
int main(int argc, char *argv[]) { #include "setRootCase.H" #include "createTime.H" #include "createMesh.H" #include "createFields.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Info << "\n setting particle positions \n" << endl; word positioningType ( setParticlePositionsPelletDict.lookup("positioningType") ); if(positioningType == "pellet") { dictionary autoPelletPositionSubDict ( setParticlePositionsPelletDict.subDict("autoPelletPositionSubDict") ); scalar particleDiameter ( readScalar(autoPelletPositionSubDict.lookup("particleDiameter")) ); label particleNumber ( readLabel(autoPelletPositionSubDict.lookup("particleNumber")) ); scalar radius ( readScalar(autoPelletPositionSubDict.lookup("radius")) ); scalar length ( readScalar(autoPelletPositionSubDict.lookup("length")) ); vector origin ( autoPelletPositionSubDict.lookup("origin") ); label trialNum ( readLabel(autoPelletPositionSubDict.lookup("trialNumber")) ); label densityR ( readLabel(autoPelletPositionSubDict.lookup("densityRadius")) ); label densityT ( readLabel(autoPelletPositionSubDict.lookup("densityTheta")) ); label densityL ( readLabel(autoPelletPositionSubDict.lookup("densityLength")) ); // Min and Max of each variable were multiplied by densityR,T,L respectively to increase the resolution, since random function I made can only output integer. // by doing so, it can output decimal value. scalar thetaMin = 0*densityT; scalar thetaMax = 360 * densityT; scalar rMin = 0*densityR; scalar rMax = radius * densityR; scalar lMin = -(length-particleDiameter)*densityL/2; scalar lMax = (length-particleDiameter)*densityL/2; //dummy list to store particles in cylindrical coordinates x is r, y is theta, z is length List<vector> dummyCylindic(trialNum); //dummy list to store particles in rectangula coordinates List<vector> dummyRectangula(trialNum); //List for particles settled in cylindrical coordinates List<vector> cylindic(particleNumber); //List for particles transformed into rectangular coordinates List<vector> rectangula(particleNumber); // the first particle is stored in cylindic and rectangula list cylindic[0].x() = GetRandom(rMin,rMax)/densityR; cylindic[0].y() = GetRandom(thetaMin,thetaMax)/densityT; cylindic[0].z() = GetRandom(lMin,lMax)/densityL; Info << "r is" << cylindic[0].x() << endl; Info << "theta is" << cylindic[0].y() << endl; Info << "length is " << cylindic[0].z() << endl; // cylindic[0] is transormed into rectangular coordinates //inside sin is written in radian rectangula[0].x() = cylindic[0].x()*Foam::sin(constant::mathematical::pi*cylindic[0].y()/180); rectangula[0].y() = cylindic[0].z(); rectangula[0].z() = cylindic[0].x()*Foam::cos(constant::mathematical::pi*cylindic[0].y()/180); Info << "x is" << rectangula[0].x() << endl; Info << "y is" << rectangula[0].y() << endl; Info << "z is " << rectangula[0].z() << endl; label l = 0; forAll(dummyCylindic,i) { if( l< particleNumber-1 ) { dummyCylindic[i].x() = GetRandom(rMin,rMax)/densityR; dummyCylindic[i].y() = GetRandom(thetaMin,thetaMax)/densityT; dummyCylindic[i].z() = GetRandom(lMin,lMax)/densityL; Info << " dummyCylindic[ "<<i<<"].x()" << dummyCylindic[i].x() << endl; Info << " dummyCylindic[ "<<i<<"].y()" << dummyCylindic[i].y() << endl; Info << " dummyCylindic[ "<<i<<"].z()" << dummyCylindic[i].z() << endl; dummyRectangula[i].x() = dummyCylindic[i].x()*Foam::sin(constant::mathematical::pi*dummyCylindic[i].y()/180); dummyRectangula[i].y() = dummyCylindic[i].z(); dummyRectangula[i].z() = dummyCylindic[i].x()*Foam::cos(constant::mathematical::pi*dummyCylindic[i].y()/180); label counter = 0; label t; for(t=0; t<=l; t++) { scalar S; S = mag(dummyRectangula[i]-rectangula[t]); if(S>particleDiameter) { counter += 1; }else{ counter += 0; } } if(counter == l+1) { l = l+1; rectangula[l] = dummyRectangula[i]; } } } fileName rootName(runTime.path()); fileName fName("particlePositionsPellet"); OFstream os(rootName/fName); Info<< "Writing to the output file"<<endl; label k; for(k=0; k<=l; k++) { rectangula[k] += origin ; } for(k=0; k<=l; k++) { os <<"("<<rectangula[k].x()<<" "<<rectangula[k].y()<<" "<<rectangula[k].z()<<")"<<endl; } Info<< "End\n" << endl; }
bool Model_OBJ_Physics_Static::LoadAsset(const std::string &name) { assert(!m_loaded); std::ifstream fromFile(name); if(!fromFile.is_open()) { std::cerr << "Could not load model file " << name << std::endl; return false; } std::string rootName(GetRootName(name)); std::vector<Vec3f> filePositions; std::vector<Vec2f> fileTexCoords; std::vector<Vec3f> fileNormals; std::vector<Vec2f> texCoords; std::vector<Vec3f> normals; // Hash map for linking indices to vertex array index for attributes std::unordered_map<IndexSet, unsigned int, IndexSet> indexToVertex; // Initial extremes m_aabb.m_lowerBound = Vec3f(9999.0f, 9999.0f, 9999.0f); m_aabb.m_upperBound = Vec3f(-9999.0f, -9999.0f, -9999.0f); int currentObj = -1; std::unordered_map<std::string, unsigned int> matReferences; while(!fromFile.eof()) { // Read line header std::string line; getline(fromFile, line); std::stringstream ss(line); std::string header; ss >> header; if(header == "v") { // Add vertex float x, y, z; ss >> x >> y >> z; filePositions.push_back(Vec3f(x, y, z)); // Expand AABB if(x < m_aabb.m_lowerBound.x) m_aabb.m_lowerBound.x = x; if(y < m_aabb.m_lowerBound.y) m_aabb.m_lowerBound.y = y; if(z < m_aabb.m_lowerBound.z) m_aabb.m_lowerBound.z = z; if(x > m_aabb.m_upperBound.x) m_aabb.m_upperBound.x = x; if(y > m_aabb.m_upperBound.y) m_aabb.m_upperBound.y = y; if(z > m_aabb.m_upperBound.z) m_aabb.m_upperBound.z = z; } else if(header == "vt")
bool Package::Unpack() { PackagePtr sharedMe = shared_from_this(); // very basic sanity check xmlNodePtr root = xmlDocGetRootElement(_opf); string rootName(reinterpret_cast<const char*>(root->name)); rootName.tolower(); if ( rootName != "package" ) { HandleError(EPUBError::OPFInvalidPackageDocument); return false; // not an OPF file, innit? } if ( _getProp(root, "version").empty() ) { HandleError(EPUBError::OPFPackageHasNoVersion); } InstallPrefixesFromAttributeValue(_getProp(root, "prefix", ePub3NamespaceURI)); // go through children to determine the CFI index of the <spine> tag static const xmlChar* kSpineName = BAD_CAST "spine"; static const xmlChar* kManifestName = BAD_CAST "manifest"; static const xmlChar* kMetadataName = BAD_CAST "metadata"; _spineCFIIndex = 0; uint32_t idx = 0; xmlNodePtr child = xmlFirstElementChild(root); while ( child != nullptr ) { idx += 2; if ( xmlStrEqual(child->name, kSpineName) ) { _spineCFIIndex = idx; if ( _spineCFIIndex != 6 ) HandleError(EPUBError::OPFSpineOutOfOrder); } else if ( xmlStrEqual(child->name, kManifestName) && idx != 4 ) { HandleError(EPUBError::OPFManifestOutOfOrder); } else if ( xmlStrEqual(child->name, kMetadataName) && idx != 2 ) { HandleError(EPUBError::OPFMetadataOutOfOrder); } child = xmlNextElementSibling(child); } if ( _spineCFIIndex == 0 ) { HandleError(EPUBError::OPFNoSpine); return false; // spineless! } #if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS) XPathWrangler xpath(_opf, {{"opf", OPFNamespace}, {"dc", DCNamespace}}); #else XPathWrangler::NamespaceList __m; __m["opf"] = OPFNamespace; __m["dc"] = DCNamespace; XPathWrangler xpath(_opf, __m); #endif // simple things: manifest and spine items xmlNodeSetPtr manifestNodes = nullptr; xmlNodeSetPtr spineNodes = nullptr; try { manifestNodes = xpath.Nodes("/opf:package/opf:manifest/opf:item"); spineNodes = xpath.Nodes("/opf:package/opf:spine/opf:itemref"); if ( manifestNodes == nullptr ) { HandleError(EPUBError::OPFNoManifestItems); } if ( spineNodes == nullptr ) { HandleError(EPUBError::OPFNoSpineItems); } for ( int i = 0; i < manifestNodes->nodeNr; i++ ) { auto p = std::make_shared<ManifestItem>(sharedMe); if ( p->ParseXML(p, manifestNodes->nodeTab[i]) ) { #if EPUB_HAVE(CXX_MAP_EMPLACE) _manifest.emplace(p->Identifier(), p); #else _manifest[p->Identifier()] = p; #endif StoreXMLIdentifiable(p); } else { // TODO: Need an error here } } // check fallback chains typedef std::map<string, bool> IdentSet; IdentSet idents; for ( auto &pair : _manifest ) { ManifestItemPtr item = pair.second; if ( item->FallbackID().empty() ) continue; idents[item->XMLIdentifier()] = true; while ( !item->FallbackID().empty() ) { if ( idents[item->FallbackID()] ) { HandleError(EPUBError::OPFFallbackChainCircularReference); break; } item = item->Fallback(); } idents.clear(); } SpineItemPtr cur; for ( int i = 0; i < spineNodes->nodeNr; i++ ) { auto next = std::make_shared<SpineItem>(sharedMe); if ( next->ParseXML(next, spineNodes->nodeTab[i]) == false ) { // TODO: need an error code here continue; } // validation of idref auto manifestFound = _manifest.find(next->Idref()); if ( manifestFound == _manifest.end() ) { HandleError(EPUBError::OPFInvalidSpineIdref, _Str(next->Idref(), " does not correspond to a manifest item")); continue; } // validation of spine resource type w/fallbacks ManifestItemPtr manifestItem = next->ManifestItem(); bool isContentDoc = false; do { if ( manifestItem->MediaType() == "application/xhtml+xml" || manifestItem->MediaType() == "image/svg" ) { isContentDoc = true; break; } } while ( (manifestItem = manifestItem->Fallback()) ); if ( !isContentDoc ) HandleError(EPUBError::OPFFallbackChainHasNoContentDocument); StoreXMLIdentifiable(next); if ( cur != nullptr ) { cur->SetNextItem(next); } else { _spine = next; } cur = next; } } catch (const std::system_error& exc) { if ( manifestNodes != nullptr ) xmlXPathFreeNodeSet(manifestNodes); if ( spineNodes != nullptr ) xmlXPathFreeNodeSet(spineNodes); if ( exc.code().category() == epub_spec_category() ) throw; return false; } catch (...) { if ( manifestNodes != nullptr ) xmlXPathFreeNodeSet(manifestNodes); if ( spineNodes != nullptr ) xmlXPathFreeNodeSet(spineNodes); return false; } xmlXPathFreeNodeSet(manifestNodes); xmlXPathFreeNodeSet(spineNodes); // now the metadata, which is slightly more involved due to extensions xmlNodeSetPtr metadataNodes = nullptr; xmlNodeSetPtr refineNodes = xmlXPathNodeSetCreate(nullptr); try { shared_ptr<PropertyHolder> holderPtr = std::dynamic_pointer_cast<PropertyHolder>(sharedMe); metadataNodes = xpath.Nodes("/opf:package/opf:metadata/*"); if ( metadataNodes == nullptr ) HandleError(EPUBError::OPFNoMetadata); bool foundIdentifier = false, foundTitle = false, foundLanguage = false, foundModDate = false; string uniqueIDRef = _getProp(root, "unique-identifier"); if ( uniqueIDRef.empty() ) HandleError(EPUBError::OPFPackageUniqueIDInvalid); for ( int i = 0; i < metadataNodes->nodeNr; i++ ) { xmlNodePtr node = metadataNodes->nodeTab[i]; PropertyPtr p; if ( node->ns != nullptr && xmlStrcmp(node->ns->href, BAD_CAST DCNamespace) == 0 ) { // definitely a main node p = std::make_shared<Property>(holderPtr); } else if ( _getProp(node, "name").size() > 0 ) { // it's an ePub2 item-- ignore it continue; } else if ( _getProp(node, "refines").empty() ) { // not refining anything, so it's a main node p = std::make_shared<Property>(holderPtr); } else { // by elimination it's refining something-- we'll process it later when we know we've got all the main nodes in there xmlXPathNodeSetAdd(refineNodes, node); } if ( p && p->ParseMetaElement(node) ) { switch ( p->Type() ) { case DCType::Identifier: { foundIdentifier = true; if ( !uniqueIDRef.empty() && uniqueIDRef != p->XMLIdentifier() ) HandleError(EPUBError::OPFPackageUniqueIDInvalid); break; } case DCType::Title: { foundTitle = true; break; } case DCType::Language: { foundLanguage = true; break; } case DCType::Custom: { if ( p->PropertyIdentifier() == MakePropertyIRI("modified", "dcterms") ) foundModDate = true; break; } default: break; } AddProperty(p); StoreXMLIdentifiable(p); } } if ( !foundIdentifier ) HandleError(EPUBError::OPFMissingIdentifierMetadata); if ( !foundTitle ) HandleError(EPUBError::OPFMissingTitleMetadata); if ( !foundLanguage ) HandleError(EPUBError::OPFMissingLanguageMetadata); if ( !foundModDate ) HandleError(EPUBError::OPFMissingModificationDateMetadata); for ( int i = 0; i < refineNodes->nodeNr; i++ ) { xmlNodePtr node = refineNodes->nodeTab[i]; string ident = _getProp(node, "refines"); if ( ident.empty() ) { HandleError(EPUBError::OPFInvalidRefinementAttribute, "Empty IRI for 'refines' attribute"); continue; } if ( ident[0] == '#' ) { ident = ident.substr(1); } else { // validation only right now IRI iri(ident); if ( iri.IsEmpty() ) { HandleError(EPUBError::OPFInvalidRefinementAttribute, _Str("#", ident, " is not a valid IRI")); } else if ( iri.IsRelative() == false ) { HandleError(EPUBError::OPFInvalidRefinementAttribute, _Str(iri.IRIString(), " is not a relative IRI")); } continue; } auto found = _xmlIDLookup.find(ident); if ( found == _xmlIDLookup.end() ) { HandleError(EPUBError::OPFInvalidRefinementTarget, _Str("#", ident, " does not reference an item in this document")); continue; } PropertyPtr prop = std::dynamic_pointer_cast<Property>(found->second); if ( prop ) { // it's a property, so this is an extension PropertyExtensionPtr extPtr = std::make_shared<PropertyExtension>(prop); if ( extPtr->ParseMetaElement(node) ) prop->AddExtension(extPtr); } else { // not a property, so treat this as a plain property shared_ptr<PropertyHolder> ptr = std::dynamic_pointer_cast<PropertyHolder>(found->second); if ( ptr ) { prop = std::make_shared<Property>(ptr); if ( prop->ParseMetaElement(node) ) ptr->AddProperty(prop); } } } // now look at the <spine> element for properties xmlNodePtr spineNode = xmlFirstElementChild(root); for ( uint32_t i = 2; i < _spineCFIIndex; i += 2 ) spineNode = xmlNextElementSibling(spineNode); string value = _getProp(spineNode, "page-progression-direction"); if ( !value.empty() ) { PropertyPtr prop = std::make_shared<Property>(holderPtr); prop->SetPropertyIdentifier(MakePropertyIRI("page-progression-direction")); prop->SetValue(value); AddProperty(prop); } } catch (std::system_error& exc) { if ( metadataNodes != nullptr ) xmlXPathFreeNodeSet(metadataNodes); if ( refineNodes != nullptr ) xmlXPathFreeNodeSet(refineNodes); if ( exc.code().category() == epub_spec_category() ) throw; return false; } catch (...) { if ( metadataNodes != nullptr ) xmlXPathFreeNodeSet(metadataNodes); if ( refineNodes != nullptr ) xmlXPathFreeNodeSet(refineNodes); return false; } xmlXPathFreeNodeSet(metadataNodes); xmlXPathFreeNodeSet(refineNodes); // now any content type bindings xmlNodeSetPtr bindingNodes = nullptr; try { bindingNodes = xpath.Nodes("/opf:package/opf:bindings/*"); if ( bindingNodes != nullptr ) { for ( int i = 0; i < bindingNodes->nodeNr; i++ ) { xmlNodePtr node = bindingNodes->nodeTab[i]; if ( xmlStrcasecmp(node->name, MediaTypeElementName) != 0 ) continue; //////////////////////////////////////////////////////////// // ePub Publications 3.0 §3.4.16: The `mediaType` Element // The media-type attribute is required. string mediaType = _getProp(node, "media-type"); if ( mediaType.empty() ) { HandleError(EPUBError::OPFBindingHandlerNoMediaType); throw false; } // Each child mediaType of a bindings element must define a unique // content type in its media-type attribute, and the media type // specified must not be a Core Media Type. if ( _contentHandlers[mediaType].empty() == false ) { // user shouldn't have added manual things yet, but for safety we'll look anyway for ( auto ptr : _contentHandlers[mediaType] ) { if ( typeid(*ptr) == typeid(MediaHandler) ) { HandleError(EPUBError::OPFMultipleBindingsForMediaType); } } } if ( CoreMediaTypes.find(mediaType) != CoreMediaTypes.end() ) { HandleError(EPUBError::OPFCoreMediaTypeBindingEncountered); } // The handler attribute is required string handlerID = _getProp(node, "handler"); if ( handlerID.empty() ) { HandleError(EPUBError::OPFBindingHandlerNotFound); } // The required handler attribute must reference the ID [XML] of an // item in the manifest of the default implementation for this media // type. The referenced item must be an XHTML Content Document. ManifestItemPtr handlerItem = ManifestItemWithID(handlerID); if ( !handlerItem ) { HandleError(EPUBError::OPFBindingHandlerNotFound); } if ( handlerItem->MediaType() != "application/xhtml+xml" ) { HandleError(EPUBError::OPFBindingHandlerInvalidType, _Str("Media handlers must be XHTML content documents, but referenced item has type '", handlerItem->MediaType(), "'.")); } // All XHTML Content Documents designated as handlers must have the // `scripted` property set in their manifest item's `properties` // attribute. if ( handlerItem->HasProperty(ItemProperties::HasScriptedContent) == false ) { HandleError(EPUBError::OPFBindingHandlerNotScripted); } // all good-- install it now _contentHandlers[mediaType].push_back(std::make_shared<MediaHandler>(sharedMe, mediaType, handlerItem->AbsolutePath())); } } } catch (std::exception& exc) { std::cerr << "Exception processing OPF file: " << exc.what() << std::endl; if ( bindingNodes != nullptr ) xmlXPathFreeNodeSet(bindingNodes); throw; } catch (...) { if ( bindingNodes != nullptr ) xmlXPathFreeNodeSet(bindingNodes); return false; } xmlXPathFreeNodeSet(bindingNodes); // now the navigation tables for ( auto item : _manifest ) { if ( !item.second->HasProperty(ItemProperties::Navigation) ) continue; NavigationList tables = NavTablesFromManifestItem(sharedMe, item.second); for ( auto table : tables ) { // have to dynamic_cast these guys to get the right pointer type shared_ptr<class NavigationTable> navTable = std::dynamic_pointer_cast<class NavigationTable>(table); #if EPUB_HAVE(CXX_MAP_EMPLACE) _navigation.emplace(navTable->Type(), navTable); #else _navigation[navTable->Type()] = navTable; #endif } } // lastly, let's set the media support information InitMediaSupport(); return true; }
void CTestTreeView::OnOpenTLS() { CFileDialog OpenTlsDlg(TRUE,NULL, NULL,OFN_HIDEREADONLY, _T("Test List File(*.mas)|*.mas"));//open as CString defPath; defPath.Format(_T("%smastertls\\"),CMConfigCenter::GetConfigCenter().GetLocalPath().c_str()); OpenTlsDlg.m_ofn.lpstrInitialDir=defPath; if(OpenTlsDlg.DoModal()==IDOK) { m_wndTestTreeView.DeleteAllItems(); //FillTestTreeView(OpenTlsDlg.GetPathName()); // CFileDialog dlg(FALSE,NULL, "MyOrl.orl ",OFN_OVERWRITEPROMPT, "(*.orl)|*.orl| ");//save as // dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY, "AVI files(*.avi)|*.avi| ")//open wstring tmp(OpenTlsDlg.GetPathName()); string fileName= ws2s(tmp); m_TestTreeList.Init(fileName.c_str()); HTREEITEM hRoot = m_wndTestTreeView.InsertItem(_T("Root"), 0, 0); HTREEITEM hCommon = m_wndTestTreeView.InsertItem(_T("Common"), 0, 0, hRoot); //HTREEITEM hTest = m_wndFileView.InsertItem(_T("Test"), 0, 0,hRoot); std::list<CTlsData*>* testData = m_TestTreeList.GetTestList(); for (list<CTlsData*>::iterator testIt=testData->begin();testIt!=testData->end();testIt++) { switch ((*testIt)->GetType()) { case COMMON: { STLSDATA_COMMON* pCommon = (*testIt)->GetDataCommon(); CString commName (pCommon->commname.c_str()); m_wndTestTreeView.SetItemText(hCommon,commName); m_wndTestTreeView.SetItemData(hCommon,(DWORD_PTR)(*testIt)); break; } case SUBTEST: { if (!hCurrentTest) { break; } STLSDATA_SUBTEST* pSubTest = (*testIt)->GetDataSubtest(); CString testName(pSubTest->subTestName.c_str()); HTREEITEM hSubTest = m_wndTestTreeView.InsertItem(testName, 0, 0,hCurrentTest); m_wndTestTreeView.SetItemData(hSubTest,(DWORD_PTR)(*testIt)); break; } case TEST: { STLSDATA_TEST* pTest = (*testIt)->GetDataTest(); CString testName(pTest->testName.c_str()); HTREEITEM hTest = m_wndTestTreeView.InsertItem(testName, 0, 0,hRoot); hCurrentTest = hTest; m_wndTestTreeView.SetItemData(hTest,(DWORD_PTR)(*testIt)); break; } case ROOT: { STLSDATA_ROOT* pRoot = (*testIt)->GetDataRoot(); CString rootName(pRoot->name.c_str()); m_wndTestTreeView.SetItemText(hRoot,rootName); m_wndTestTreeView.SetItemData(hRoot,(DWORD_PTR)(*testIt)); break; } } m_wndTestTreeView.SetItemState(hRoot, TVIS_BOLD, TVIS_BOLD); m_wndTestTreeView.Expand(hRoot, TVE_EXPAND); } m_wndTestTreeView.Expand(hRoot, TVE_EXPAND); } OpenTlsDlg.DestroyWindow(); }
bool Package::Unpack() { // very basic sanity check xmlNodePtr root = xmlDocGetRootElement(_opf); string rootName(reinterpret_cast<const char*>(root->name)); rootName.tolower(); if ( rootName != "package" ) return false; // not an OPF file, innit? InstallPrefixesFromAttributeValue(_getProp(root, "prefix", ePub3NamespaceURI)); // go through children to determine the CFI index of the <spine> tag static const xmlChar* kSpineName = BAD_CAST "spine"; _spineCFIIndex = 0; xmlNodePtr child = root->children; while ( child != nullptr ) { if ( child->type == XML_ELEMENT_NODE ) { _spineCFIIndex += 2; if ( xmlStrEqual(child->name, kSpineName) ) break; } child = child->next; } if ( _spineCFIIndex == 0 ) return false; // spineless! XPathWrangler xpath(_opf, {{"opf", OPFNamespace}, {"dc", DCNamespace}}); // simple things: manifest and spine items xmlNodeSetPtr manifestNodes = nullptr; xmlNodeSetPtr spineNodes = nullptr; try { manifestNodes = xpath.Nodes("/opf:package/opf:manifest/opf:item"); spineNodes = xpath.Nodes("/opf:package/opf:spine/opf:itemref"); if ( manifestNodes == nullptr || spineNodes == nullptr ) throw false; // looks invalid, or at least unusable, to me for ( int i = 0; i < manifestNodes->nodeNr; i++ ) { ManifestItem *p = new ManifestItem(manifestNodes->nodeTab[i], this); _manifest.emplace(p->Identifier(), p); } SpineItem* cur = nullptr; for ( int i = 0; i < spineNodes->nodeNr; i++ ) { SpineItem* next = new SpineItem(spineNodes->nodeTab[i], this); if ( cur != nullptr ) { cur->SetNextItem(next); } else { _spine.reset(next); } cur = next; } } catch (...) { if ( manifestNodes != nullptr ) xmlXPathFreeNodeSet(manifestNodes); if ( spineNodes != nullptr ) xmlXPathFreeNodeSet(spineNodes); return false; } xmlXPathFreeNodeSet(manifestNodes); xmlXPathFreeNodeSet(spineNodes); // now the metadata, which is slightly more involved due to extensions xmlNodeSetPtr metadataNodes = nullptr; xmlNodeSetPtr refineNodes = xmlXPathNodeSetCreate(nullptr); try { metadataNodes = xpath.Nodes("/opf:package/opf:metadata/*"); if ( metadataNodes == nullptr ) throw false; std::map<string, class Metadata*> metadataByID; for ( int i = 0; i < metadataNodes->nodeNr; i++ ) { xmlNodePtr node = metadataNodes->nodeTab[i]; class Metadata* p = nullptr; if ( node->ns != nullptr && xmlStrcmp(node->ns->href, BAD_CAST DCNamespace) == 0 ) { // definitely a main node p = new class Metadata(node, this); } else if ( _getProp(node, "name").size() > 0 ) { // it's an ePub2 item-- ignore it continue; } else if ( _getProp(node, "refines").empty() ) { // not refining anything, so it's a main node p = new class Metadata(node, this); } else { // by elimination it's refining something-- we'll process it later when we know we've got all the main nodes in there xmlXPathNodeSetAdd(refineNodes, node); } if ( p != nullptr ) { _metadata.push_back(p); if ( !p->Identifier().empty() ) metadataByID[p->Identifier()] = p; } } for ( int i = 0; i < refineNodes->nodeNr; i++ ) { xmlNodePtr node = refineNodes->nodeTab[i]; string ident = _getProp(node, "refines"); if ( ident.empty() ) continue; if ( ident[0] == '#' ) ident = ident.substr(1); auto found = metadataByID.find(ident); if ( found == metadataByID.end() ) continue; found->second->AddExtension(node, this); } } catch (...) { if ( metadataNodes != nullptr ) xmlXPathFreeNodeSet(metadataNodes); if ( refineNodes != nullptr ) xmlXPathFreeNodeSet(refineNodes); return false; } xmlXPathFreeNodeSet(metadataNodes); xmlXPathFreeNodeSet(refineNodes); // now any content type bindings xmlNodeSetPtr bindingNodes = nullptr; try { bindingNodes = xpath.Nodes("/opf:package/opf:bindings/*"); if ( bindingNodes != nullptr ) { for ( int i = 0; i < bindingNodes->nodeNr; i++ ) { xmlNodePtr node = bindingNodes->nodeTab[i]; if ( xmlStrcasecmp(node->name, MediaTypeElementName) != 0 ) continue; //////////////////////////////////////////////////////////// // ePub Publications 3.0 §3.4.16: The `mediaType` Element // The media-type attribute is required. string mediaType = _getProp(node, "media-type"); if ( mediaType.empty() ) { throw std::invalid_argument("mediaType element has missing or empty media-type attribute."); } // Each child mediaType of a bindings element must define a unique // content type in its media-type attribute, and the media type // specified must not be a Core Media Type. if ( _contentHandlers[mediaType].empty() == false ) { // user shouldn't have added manual things yet, but for safety we'll look anyway for ( auto ptr : _contentHandlers[mediaType] ) { if ( typeid(*ptr) == typeid(MediaHandler) ) { throw std::invalid_argument(_Str("Duplicate media handler found for type '", mediaType, "'.")); } } } if ( CoreMediaTypes.find(mediaType) != CoreMediaTypes.end() ) { throw std::invalid_argument("mediaType element specifies an EPUB Core Media Type."); } // The handler attribute is required string handlerID = _getProp(node, "handler"); if ( handlerID.empty() ) { throw std::invalid_argument("mediaType element has missing or empty handler attribute."); } // The required handler attribute must reference the ID [XML] of an // item in the manifest of the default implementation for this media // type. The referenced item must be an XHTML Content Document. const ManifestItem* handlerItem = ManifestItemWithID(handlerID); if ( handlerItem == nullptr ) { throw std::invalid_argument(_Str("mediaType element references non-existent handler with ID '", handlerID, "'.")); } if ( handlerItem->MediaType() != "application/xhtml+xml" ) { throw std::invalid_argument(_Str("Media handlers must be XHTML content documents, but referenced item has type '", handlerItem->MediaType(), "'.")); } // All XHTML Content Documents designated as handlers must have the // `scripted` property set in their manifest item's `properties` // attribute. if ( handlerItem->HasProperty(ItemProperties::HasScriptedContent) == false ) { throw std::invalid_argument("Media handlers must have the `scripted` property."); } // all good-- install it now _contentHandlers[mediaType].push_back(new MediaHandler(this, mediaType, handlerItem->AbsolutePath())); } } } catch (std::exception& exc) { std::cerr << "Exception processing OPF file: " << exc.what() << std::endl; if ( bindingNodes != nullptr ) xmlXPathFreeNodeSet(bindingNodes); return false; } catch (...) { if ( bindingNodes != nullptr ) xmlXPathFreeNodeSet(bindingNodes); return false; } xmlXPathFreeNodeSet(bindingNodes); // now the navigation tables for ( auto item : _manifest ) { if ( !item.second->HasProperty(ItemProperties::Navigation) ) continue; NavigationList tables = NavTablesFromManifestItem(item.second); for ( auto table : tables ) { // have to dynamic_cast these guys to get the right pointer type class NavigationTable* navTable = dynamic_cast<class NavigationTable*>(table); _navigation.emplace(navTable->Type(), navTable); } } return true; }
void UnzipCache::newCache() { clc::Buffer rootName("."); m_root = new TreeDirectory(rootName); }