AutoPtr<Element> MeshObj::getXMLElement(AutoPtr<Document> &doc) { AutoPtr<Element> aMesh = doc->createElement("MeshObj"); AutoPtr<Element> objectFilePath = doc->createElement("ObjectFilePath"); AutoPtr<Text> pathText = doc->createTextNode(this->ObjectFilePath); objectFilePath->appendChild(pathText); aMesh->appendChild(objectFilePath); AutoPtr<Element> rootDirPath = doc->createElement("RootDirPath"); AutoPtr<Text> rootPath = doc->createTextNode(this->RootDirPath); rootDirPath->appendChild(rootPath); aMesh->appendChild(rootDirPath); AutoPtr<Element> objectFileName = doc->createElement("ObjectFileName"); AutoPtr<Text> fileName = doc->createTextNode(this->ObjectFileName); objectFileName->appendChild(fileName); aMesh->appendChild(objectFileName); AutoPtr<Element> objectFileId = doc->createElement("Id"); AutoPtr<Text> fileId = doc->createTextNode(this->IdAsString); objectFileId->appendChild(fileId); aMesh->appendChild(objectFileId); AutoPtr<Element> meshType = doc->createElement("ModelType"); AutoPtr<Text> type = doc->createTextNode(this->MeshType); meshType->appendChild(type); aMesh->appendChild(meshType); return aMesh; }
void ElementTest::testElementsByTagNameNS() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElementNS("urn:ns1", "root"); AutoPtr<NodeList> pNL1 = pRoot->getElementsByTagNameNS("*", "*"); AutoPtr<NodeList> pNL2 = pRoot->getElementsByTagNameNS("*", "elem"); AutoPtr<NodeList> pNL3 = pRoot->getElementsByTagNameNS("urn:ns1", "elem"); assert (pNL1->length() == 0); assert (pNL2->length() == 0); AutoPtr<Element> pElem1 = pDoc->createElementNS("urn:ns1", "elem"); pRoot->appendChild(pElem1); assert (pNL1->length() == 1); assert (pNL2->length() == 1); assert (pNL3->length() == 1); assert (pNL1->item(0) == pElem1); assert (pNL2->item(0) == pElem1); assert (pNL3->item(0) == pElem1); AutoPtr<Element> pElem2 = pDoc->createElementNS("urn:ns1", "Elem"); pRoot->appendChild(pElem2); assert (pNL1->length() == 2); assert (pNL2->length() == 1); assert (pNL3->length() == 1); assert (pNL1->item(0) == pElem1); assert (pNL1->item(1) == pElem2); assert (pNL2->item(0) == pElem1); assert (pNL3->item(0) == pElem1); AutoPtr<Element> pElem3 = pDoc->createElementNS("urn:ns2", "elem"); pRoot->appendChild(pElem3); assert (pNL1->length() == 3); assert (pNL2->length() == 2); assert (pNL3->length() == 1); assert (pNL1->item(0) == pElem1); assert (pNL1->item(1) == pElem2); assert (pNL1->item(2) == pElem3); assert (pNL2->item(0) == pElem1); assert (pNL2->item(1) == pElem3); assert (pNL3->item(0) == pElem1); AutoPtr<Element> pElem11 = pDoc->createElementNS("urn:ns1", "elem"); pElem1->appendChild(pElem11); assert (pNL1->length() == 4); assert (pNL2->length() == 3); assert (pNL3->length() == 2); assert (pNL1->item(0) == pElem1); assert (pNL1->item(1) == pElem11); assert (pNL1->item(2) == pElem2); assert (pNL1->item(3) == pElem3); assert (pNL2->item(0) == pElem1); assert (pNL2->item(1) == pElem11); assert (pNL2->item(2) == pElem3); assert (pNL3->item(0) == pElem1); assert (pNL3->item(1) == pElem11); AutoPtr<Element> pElem12 = pDoc->createElementNS("urn:ns1", "Elem"); pElem1->appendChild(pElem12); assert (pNL1->length() == 5); assert (pNL2->length() == 3); assert (pNL3->length() == 2); assert (pNL1->item(0) == pElem1); assert (pNL1->item(1) == pElem11); assert (pNL1->item(2) == pElem12); assert (pNL1->item(3) == pElem2); assert (pNL1->item(4) == pElem3); assert (pNL2->item(0) == pElem1); assert (pNL2->item(1) == pElem11); assert (pNL2->item(2) == pElem3); assert (pNL3->item(0) == pElem1); assert (pNL3->item(1) == pElem11); AutoPtr<Element> pElem21 = pDoc->createElementNS("urn:ns1", "elem"); pElem2->appendChild(pElem21); assert (pNL1->length() == 6); assert (pNL2->length() == 4); assert (pNL3->length() == 3); assert (pNL1->item(0) == pElem1); assert (pNL1->item(1) == pElem11); assert (pNL1->item(2) == pElem12); assert (pNL1->item(3) == pElem2); assert (pNL1->item(4) == pElem21); assert (pNL1->item(5) == pElem3); assert (pNL2->item(0) == pElem1); assert (pNL2->item(1) == pElem11); assert (pNL2->item(2) == pElem21); assert (pNL2->item(3) == pElem3); assert (pNL3->item(0) == pElem1); assert (pNL3->item(1) == pElem11); assert (pNL3->item(2) == pElem21); }
void ElementTest::testNodeByPath() { /* <root> <elem1> <elemA/> <elemA/> </elem1> <elem2> <elemB attr1="value1"/> <elemB attr1="value2"/> <elemB attr1="value3"/> <elemC attr1="value1"> <elemC1 attr1="value1"/> <elemC2/> </elemC> <elemC attr1="value2"/> </elem2> </root> */ AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); AutoPtr<Element> pElem1 = pDoc->createElement("elem1"); AutoPtr<Element> pElem11 = pDoc->createElement("elemA"); AutoPtr<Element> pElem12 = pDoc->createElement("elemA"); AutoPtr<Element> pElem2 = pDoc->createElement("elem2"); AutoPtr<Element> pElem21 = pDoc->createElement("elemB"); AutoPtr<Element> pElem22 = pDoc->createElement("elemB"); AutoPtr<Element> pElem23 = pDoc->createElement("elemB"); AutoPtr<Element> pElem24 = pDoc->createElement("elemC"); AutoPtr<Element> pElem25 = pDoc->createElement("elemC"); pElem21->setAttribute("attr1", "value1"); pElem22->setAttribute("attr1", "value2"); pElem23->setAttribute("attr1", "value3"); pElem24->setAttribute("attr1", "value1"); pElem25->setAttribute("attr1", "value2"); AutoPtr<Element> pElem241 = pDoc->createElement("elemC1"); AutoPtr<Element> pElem242 = pDoc->createElement("elemC2"); pElem241->setAttribute("attr1", "value1"); pElem24->appendChild(pElem241); pElem24->appendChild(pElem242); pElem1->appendChild(pElem11); pElem1->appendChild(pElem12); pElem2->appendChild(pElem21); pElem2->appendChild(pElem22); pElem2->appendChild(pElem23); pElem2->appendChild(pElem24); pElem2->appendChild(pElem25); pRoot->appendChild(pElem1); pRoot->appendChild(pElem2); pDoc->appendChild(pRoot); Node* pNode = pRoot->getNodeByPath("/"); assert (pNode == pRoot); pNode = pRoot->getNodeByPath("/elem1"); assert (pNode == pElem1); pNode = pDoc->getNodeByPath("/root/elem1"); assert (pNode == pElem1); pNode = pRoot->getNodeByPath("/elem2"); assert (pNode == pElem2); pNode = pRoot->getNodeByPath("/elem1/elemA"); assert (pNode == pElem11); pNode = pRoot->getNodeByPath("/elem1/elemA[0]"); assert (pNode == pElem11); pNode = pRoot->getNodeByPath("/elem1/elemA[1]"); assert (pNode == pElem12); pNode = pRoot->getNodeByPath("/elem1/elemA[2]"); assert (pNode == 0); pNode = pRoot->getNodeByPath("/elem2/elemB"); assert (pNode == pElem21); pNode = pRoot->getNodeByPath("/elem2/elemB[0]"); assert (pNode == pElem21); pNode = pRoot->getNodeByPath("/elem2/elemB[1]"); assert (pNode == pElem22); pNode = pRoot->getNodeByPath("/elem2/elemB[2]"); assert (pNode == pElem23); pNode = pRoot->getNodeByPath("/elem2/elemB[3]"); assert (pNode == 0); pNode = pRoot->getNodeByPath("/elem2/elemB[@attr1]"); assert (pNode && pNode->nodeValue() == "value1"); pNode = pRoot->getNodeByPath("/elem2/elemB[@attr2]"); assert (pNode == 0); pNode = pRoot->getNodeByPath("/elem2/elemB[@attr1='value2']"); assert (pNode == pElem22); pNode = pRoot->getNodeByPath("/elem2/elemC[@attr1='value1']/elemC1"); assert (pNode == pElem241); pNode = pRoot->getNodeByPath("/elem2/elemC[@attr1='value1']/elemC1[@attr1]"); assert (pNode && pNode->nodeValue() == "value1"); pNode = pDoc->getNodeByPath("//elemB[@attr1='value1']"); assert (pNode == pElem21); pNode = pDoc->getNodeByPath("//elemB[@attr1='value2']"); assert (pNode == pElem22); pNode = pDoc->getNodeByPath("//elemB[@attr1='value3']"); assert (pNode == pElem23); pNode = pDoc->getNodeByPath("//elemB[@attr1='value4']"); assert (pNode == 0); pNode = pDoc->getNodeByPath("//[@attr1='value1']"); assert (pNode == pElem21); pNode = pDoc->getNodeByPath("//[@attr1='value2']"); assert (pNode == pElem22); }
void NodeTest::testAppendFragment3() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); AutoPtr<DocumentFragment> pFrag = pDoc->createDocumentFragment(); AutoPtr<Element> pChild1 = pDoc->createElement("child1"); AutoPtr<Element> pChild2 = pDoc->createElement("child2"); AutoPtr<Element> pChild3 = pDoc->createElement("child3"); pFrag->appendChild(pChild1); pFrag->appendChild(pChild2); pFrag->appendChild(pChild3); pRoot->appendChild(pFrag); assert (pFrag->firstChild() == 0); assert (pFrag->lastChild() == 0); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild3); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == 0); AutoPtr<Element> pChild4 = pDoc->createElement("child4"); AutoPtr<Element> pChild5 = pDoc->createElement("child5"); AutoPtr<Element> pChild6 = pDoc->createElement("child6"); pFrag->appendChild(pChild4); pFrag->appendChild(pChild5); pFrag->appendChild(pChild6); pRoot->appendChild(pFrag); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild6); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == pChild5); assert (pChild5->previousSibling() == pChild4); assert (pChild5->nextSibling() == pChild6); assert (pChild6->previousSibling() == pChild5); assert (pChild6->nextSibling() == 0); AutoPtr<Element> pChild7 = pDoc->createElement("child7"); AutoPtr<Element> pChild8 = pDoc->createElement("child8"); AutoPtr<Element> pChild9 = pDoc->createElement("child9"); pFrag->appendChild(pChild7); pFrag->appendChild(pChild8); pFrag->appendChild(pChild9); pRoot->appendChild(pFrag); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild9); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == pChild5); assert (pChild5->previousSibling() == pChild4); assert (pChild5->nextSibling() == pChild6); assert (pChild6->previousSibling() == pChild5); assert (pChild6->nextSibling() == pChild7); assert (pChild7->previousSibling() == pChild6); assert (pChild7->nextSibling() == pChild8); assert (pChild8->previousSibling() == pChild7); assert (pChild8->nextSibling() == pChild9); assert (pChild9->previousSibling() == pChild8); assert (pChild9->nextSibling() == 0); }
void ElementTest::testAttributesNS() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pElem = pDoc->createElementNS("urn:ns1", "p:elem"); assert (pElem->namespaceURI() == "urn:ns1"); assert (pElem->prefix() == "p"); assert (pElem->tagName() == "p:elem"); assert (pElem->localName() == "elem"); assert (!pElem->hasAttributes()); pElem->setAttributeNS("urn:ns1", "a1", "v1"); assert (pElem->hasAttributes()); assert (pElem->hasAttributeNS("urn:ns1", "a1")); assert (pElem->getAttributeNS("urn:ns1", "a1") == "v1"); Attr* pAttr1 = pElem->getAttributeNodeNS("urn:ns1", "a1"); assert (pAttr1 != 0); assert (pAttr1->name() == "a1"); assert (pAttr1->namespaceURI() == "urn:ns1"); assert (pAttr1->prefix().empty()); assert (pAttr1->localName() == "a1"); assert (pAttr1->nodeName() == "a1"); assert (pAttr1->value() == "v1"); assert (pAttr1->nodeValue() == "v1"); assert (pAttr1->ownerElement() == pElem); pAttr1->setValue("V1"); assert (pElem->getAttributeNS("urn:ns1", "a1") == "V1"); pElem->setAttributeNS("urn:ns1", "a2", "v2"); assert (pElem->hasAttributeNS("urn:ns1", "a1")); assert (pElem->getAttributeNS("urn:ns1", "a1") == "V1"); assert (pElem->hasAttributeNS("urn:ns1", "a2")); assert (pElem->getAttributeNS("urn:ns1", "a2") == "v2"); Attr* pAttr2 = pElem->getAttributeNodeNS("urn:ns1", "a2"); assert (pAttr2 != 0); assert (pAttr2->name() == "a2"); assert (pAttr2->namespaceURI() == "urn:ns1"); assert (pAttr2->prefix().empty()); assert (pAttr2->localName() == "a2"); assert (pAttr2->value() == "v2"); assert (pAttr2->ownerElement() == pElem); Attr* pAttr3 = pElem->getAttributeNodeNS("urn:ns2", "p:a3"); assert (pAttr3 == 0); pAttr3 = pDoc->createAttributeNS("urn:ns2", "p:a3"); pAttr3->setValue("v3"); pElem->setAttributeNodeNS(pAttr3); pAttr3->release(); assert (pElem->hasAttributeNS("urn:ns1", "a1")); assert (pElem->getAttributeNS("urn:ns1", "a1") == "V1"); assert (pElem->hasAttributeNS("urn:ns1", "a2")); assert (pElem->getAttributeNS("urn:ns1", "a2") == "v2"); assert (pElem->hasAttributeNS("urn:ns2", "a3")); assert (pElem->getAttributeNS("urn:ns2", "a3") == "v3"); pAttr2 = pDoc->createAttributeNS("urn:ns1", "a2"); pAttr2->setValue("V2"); pElem->setAttributeNodeNS(pAttr2); pAttr2->release(); assert (pElem->hasAttributeNS("urn:ns1", "a1")); assert (pElem->getAttributeNS("urn:ns1", "a1") == "V1"); assert (pElem->hasAttributeNS("urn:ns1", "a2")); assert (pElem->getAttributeNS("urn:ns1", "a2") == "V2"); assert (pElem->hasAttributeNS("urn:ns2", "a3")); assert (pElem->getAttributeNS("urn:ns2", "a3") == "v3"); pAttr1 = pDoc->createAttributeNS("urn:ns1", "a1"); pAttr1->setValue("v1"); pElem->setAttributeNodeNS(pAttr1); pAttr1->release(); assert (pElem->hasAttributeNS("urn:ns1", "a1")); assert (pElem->getAttributeNS("urn:ns1", "a1") == "v1"); assert (pElem->hasAttributeNS("urn:ns1", "a2")); assert (pElem->getAttributeNS("urn:ns1", "a2") == "V2"); assert (pElem->hasAttributeNS("urn:ns2", "a3")); assert (pElem->getAttributeNS("urn:ns2", "a3") == "v3"); pAttr3 = pDoc->createAttributeNS("urn:ns2", "q:a3"); pAttr3->setValue("V3"); pElem->setAttributeNodeNS(pAttr3); pAttr3->release(); assert (pElem->hasAttributeNS("urn:ns1", "a1")); assert (pElem->getAttributeNS("urn:ns1", "a1") == "v1"); assert (pElem->hasAttributeNS("urn:ns1", "a2")); assert (pElem->getAttributeNS("urn:ns1", "a2") == "V2"); assert (pElem->hasAttributeNS("urn:ns2", "a3")); assert (pElem->getAttributeNS("urn:ns2", "a3") == "V3"); pElem->removeAttributeNode(pAttr3); assert (!pElem->hasAttributeNS("urn:ns2", "a3")); pElem->removeAttributeNS("urn:ns1", "a1"); assert (!pElem->hasAttributeNS("urn:ns1", "a1")); pElem->removeAttributeNS("urn:ns1", "a2"); assert (!pElem->hasAttributeNS("urn:ns1", "a2")); assert (!pElem->hasAttributes()); }
void NodeTest::testReplace() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); AutoPtr<Element> pChild1 = pDoc->createElement("child1"); pRoot->appendChild(pChild1); AutoPtr<Element> pChild2 = pDoc->createElement("child2"); pRoot->appendChild(pChild2); AutoPtr<Element> pChild3 = pDoc->createElement("child3"); pRoot->appendChild(pChild3); AutoPtr<Element> pChild4 = pDoc->createElement("child4"); pRoot->appendChild(pChild4); AutoPtr<Element> pChild11 = pDoc->createElement("child11"); pRoot->replaceChild(pChild11, pChild1); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild4); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild11); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == 0); AutoPtr<Element> pChild22 = pDoc->createElement("child22"); pRoot->replaceChild(pChild22, pChild2); assert (pChild2->previousSibling() == 0); assert (pChild2->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild4); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild22); assert (pChild22->previousSibling() == pChild11); assert (pChild22->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild22); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == 0); AutoPtr<Element> pChild33 = pDoc->createElement("child33"); pRoot->replaceChild(pChild33, pChild3); assert (pChild3->previousSibling() == 0); assert (pChild3->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild4); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild22); assert (pChild22->previousSibling() == pChild11); assert (pChild22->nextSibling() == pChild33); assert (pChild33->previousSibling() == pChild22); assert (pChild33->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild33); assert (pChild4->nextSibling() == 0); AutoPtr<Element> pChild44 = pDoc->createElement("child44"); pRoot->replaceChild(pChild44, pChild4); assert (pChild4->previousSibling() == 0); assert (pChild4->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild44); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild22); assert (pChild22->previousSibling() == pChild11); assert (pChild22->nextSibling() == pChild33); assert (pChild33->previousSibling() == pChild22); assert (pChild33->nextSibling() == pChild44); assert (pChild44->previousSibling() == pChild33); assert (pChild44->nextSibling() == 0); }
void NodeTest::testAppendFragment1() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); AutoPtr<DocumentFragment> pFrag = pDoc->createDocumentFragment(); AutoPtr<Element> pChild1 = pDoc->createElement("child1"); pFrag->appendChild(pChild1); pRoot->appendChild(pFrag); assert (pFrag->firstChild() == 0); assert (pFrag->lastChild() == 0); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild1); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == 0); AutoPtr<Element> pChild2 = pDoc->createElement("child2"); pFrag->appendChild(pChild2); pRoot->appendChild(pFrag); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild2); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == 0); AutoPtr<Element> pChild3 = pDoc->createElement("child3"); pFrag->appendChild(pChild3); pRoot->appendChild(pFrag); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild3); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == 0); }
void Biharmonic::JR::residual_and_jacobian(const NumericVector<Number> &u, NumericVector<Number> *R, SparseMatrix<Number> *J, NonlinearImplicitSystem&) { #ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES if (!R && !J) return; // Declare a performance log. Give it a descriptive // string to identify what part of the code we are // logging, since there may be many PerfLogs in an // application. PerfLog perf_log ("Biharmonic Residual and Jacobian", false); // A reference to the \p DofMap object for this system. The \p DofMap // object handles the index translation from node and element numbers // to degree of freedom numbers. We will talk more about the \p DofMap // in future examples. const DofMap& dof_map = get_dof_map(); // Get a constant reference to the Finite Element type // for the first (and only) variable in the system. FEType fe_type = dof_map.variable_type(0); // Build a Finite Element object of the specified type. Since the // \p FEBase::build() member dynamically creates memory we will // store the object as an \p AutoPtr<FEBase>. This can be thought // of as a pointer that will clean up after itself. AutoPtr<FEBase> fe (FEBase::build(_biharmonic._dim, fe_type)); // Quadrature rule for numerical integration. // With 2D triangles, the Clough quadrature rule puts a Gaussian // quadrature rule on each of the 3 subelements AutoPtr<QBase> qrule(fe_type.default_quadrature_rule(_biharmonic._dim)); // Tell the finite element object to use our quadrature rule. fe->attach_quadrature_rule (qrule.get()); // Here we define some references to element-specific data that // will be used to assemble the linear system. // We begin with the element Jacobian * quadrature weight at each // integration point. const std::vector<Real>& JxW = fe->get_JxW(); // The element shape functions evaluated at the quadrature points. const std::vector<std::vector<Real> >& phi = fe->get_phi(); // The element shape functions' derivatives evaluated at the quadrature points. const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi(); // The element shape functions' second derivatives evaluated at the quadrature points. const std::vector<std::vector<RealTensor> >& d2phi = fe->get_d2phi(); // For efficiency we will compute shape function laplacians n times, // not n^2 std::vector<Real> Laplacian_phi_qp; // Define data structures to contain the element matrix // and right-hand-side vector contribution. Following // basic finite element terminology we will denote these // "Je" and "Re". More detail is in example 3. DenseMatrix<Number> Je; DenseVector<Number> Re; // This vector will hold the degree of freedom indices for // the element. These define where in the global system // the element degrees of freedom get mapped. std::vector<unsigned int> dof_indices; // Old solution const NumericVector<Number>& u_old = *old_local_solution; // Now we will loop over all the elements in the mesh. We will // compute the element matrix and right-hand-side contribution. See // example 3 for a discussion of the element iterators. MeshBase::const_element_iterator el = _biharmonic._mesh->active_local_elements_begin(); const MeshBase::const_element_iterator end_el = _biharmonic._mesh->active_local_elements_end(); for ( ; el != end_el; ++el) { // Store a pointer to the element we are currently // working on. This allows for nicer syntax later. const Elem* elem = *el; // Get the degree of freedom indices for the // current element. These define where in the global // matrix and right-hand-side this element will // contribute to. dof_map.dof_indices (elem, dof_indices); // Compute the element-specific data for the current // element. This involves computing the location of the // quadrature points (q_point) and the shape function // values/derivatives (phi, dphi,d2phi) for the current element. fe->reinit (elem); // Zero the element matrix, the right-hand side and the Laplacian matrix // before summing them. if (J) Je.resize(dof_indices.size(), dof_indices.size()); if (R) Re.resize(dof_indices.size()); Laplacian_phi_qp.resize(dof_indices.size()); for (unsigned int qp=0; qp<qrule->n_points(); qp++) { // AUXILIARY QUANTITIES: // Residual and Jacobian share a few calculations: // at the very least, in the case of interfacial energy only with a constant mobility, // both calculations use Laplacian_phi_qp; more is shared the case of a concentration-dependent // mobility and bulk potentials. Number u_qp = 0.0, u_old_qp = 0.0, Laplacian_u_qp = 0.0, Laplacian_u_old_qp = 0.0; Gradient grad_u_qp(0.0,0.0,0.0), grad_u_old_qp(0.0,0.0,0.0); Number M_qp = 1.0, M_old_qp = 1.0, M_prime_qp = 0.0, M_prime_old_qp = 0.0; for (unsigned int i=0; i<phi.size(); i++) { Laplacian_phi_qp[i] = d2phi[i][qp](0,0); grad_u_qp(0) += u(dof_indices[i])*dphi[i][qp](0); grad_u_old_qp(0) += u_old(dof_indices[i])*dphi[i][qp](0); if (_biharmonic._dim > 1) { Laplacian_phi_qp[i] += d2phi[i][qp](1,1); grad_u_qp(1) += u(dof_indices[i])*dphi[i][qp](1); grad_u_old_qp(1) += u_old(dof_indices[i])*dphi[i][qp](1); } if (_biharmonic._dim > 2) { Laplacian_phi_qp[i] += d2phi[i][qp](2,2); grad_u_qp(2) += u(dof_indices[i])*dphi[i][qp](2); grad_u_old_qp(2) += u_old(dof_indices[i])*dphi[i][qp](2); } u_qp += phi[i][qp]*u(dof_indices[i]); u_old_qp += phi[i][qp]*u_old(dof_indices[i]); Laplacian_u_qp += Laplacian_phi_qp[i]*u(dof_indices[i]); Laplacian_u_old_qp += Laplacian_phi_qp[i]*u_old(dof_indices[i]); } // for i if (_biharmonic._degenerate) { M_qp = 1.0 - u_qp*u_qp; M_old_qp = 1.0 - u_old_qp*u_old_qp; M_prime_qp = -2.0*u_qp; M_prime_old_qp = -2.0*u_old_qp; } // ELEMENT RESIDUAL AND JACOBIAN for (unsigned int i=0; i<phi.size(); i++) { // RESIDUAL if (R) { Number ri = 0.0, ri_old = 0.0; ri -= Laplacian_phi_qp[i]*M_qp*_biharmonic._kappa*Laplacian_u_qp; ri_old -= Laplacian_phi_qp[i]*M_old_qp*_biharmonic._kappa*Laplacian_u_old_qp; if (_biharmonic._degenerate) { ri -= (dphi[i][qp]*grad_u_qp)*M_prime_qp*(_biharmonic._kappa*Laplacian_u_qp); ri_old -= (dphi[i][qp]*grad_u_old_qp)*M_prime_old_qp*(_biharmonic._kappa*Laplacian_u_old_qp); } if (_biharmonic._cahn_hillard) { if (_biharmonic._energy == DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_WELL) { ri += Laplacian_phi_qp[i]*M_qp*_biharmonic._theta_c*(u_qp*u_qp - 1.0)*u_qp; ri_old += Laplacian_phi_qp[i]*M_old_qp*_biharmonic._theta_c*(u_old_qp*u_old_qp - 1.0)*u_old_qp; if (_biharmonic._degenerate) { ri += (dphi[i][qp]*grad_u_qp)*M_prime_qp*_biharmonic._theta_c*(u_qp*u_qp - 1.0)*u_qp; ri_old += (dphi[i][qp]*grad_u_old_qp)*M_prime_old_qp*_biharmonic._theta_c*(u_old_qp*u_old_qp - 1.0)*u_old_qp; } }// if(_biharmonic._energy == DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_WELL) if (_biharmonic._energy == DOUBLE_OBSTACLE || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) { ri -= Laplacian_phi_qp[i]*M_qp*_biharmonic._theta_c*u_qp; ri_old -= Laplacian_phi_qp[i]*M_old_qp*_biharmonic._theta_c*u_old_qp; if (_biharmonic._degenerate) { ri -= (dphi[i][qp]*grad_u_qp)*M_prime_qp*_biharmonic._theta_c*u_qp; ri_old -= (dphi[i][qp]*grad_u_old_qp)*M_prime_old_qp*_biharmonic._theta_c*u_old_qp; } } // if(_biharmonic._energy == DOUBLE_OBSTACLE || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) if (_biharmonic._energy == LOG_DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) { switch(_biharmonic._log_truncation) { case 2: break; case 3: break; default: break; }// switch(_biharmonic._log_truncation) }// if(_biharmonic._energy == LOG_DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) }// if(_biharmonic._cahn_hillard) Re(i) += JxW[qp]*((u_qp-u_old_qp)*phi[i][qp]-_biharmonic._dt*0.5*((2.0-_biharmonic._cnWeight)*ri + _biharmonic._cnWeight*ri_old)); } // if (R) // JACOBIAN if (J) { Number M_prime_prime_qp = 0.0; if(_biharmonic._degenerate) M_prime_prime_qp = -2.0; for (unsigned int j=0; j<phi.size(); j++) { Number ri_j = 0.0; ri_j -= Laplacian_phi_qp[i]*M_qp*_biharmonic._kappa*Laplacian_phi_qp[j]; if (_biharmonic._degenerate) { ri_j -= Laplacian_phi_qp[i]*M_prime_qp*phi[j][qp]*_biharmonic._kappa*Laplacian_u_qp + (dphi[i][qp]*dphi[j][qp])*M_prime_qp*(_biharmonic._kappa*Laplacian_u_qp) + (dphi[i][qp]*grad_u_qp)*(M_prime_prime_qp*phi[j][qp])*(_biharmonic._kappa*Laplacian_u_qp) + (dphi[i][qp]*grad_u_qp)*(M_prime_qp)*(_biharmonic._kappa*Laplacian_phi_qp[j]); } if (_biharmonic._cahn_hillard) { if(_biharmonic._energy == DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_WELL) { ri_j += Laplacian_phi_qp[i]*M_prime_qp*phi[j][qp]*_biharmonic._theta_c*(u_qp*u_qp - 1.0)*u_qp + Laplacian_phi_qp[i]*M_qp*_biharmonic._theta_c*(3.0*u_qp*u_qp - 1.0)*phi[j][qp] + (dphi[i][qp]*dphi[j][qp])*M_prime_qp*_biharmonic._theta_c*(u_qp*u_qp - 1.0)*u_qp + (dphi[i][qp]*grad_u_qp)*M_prime_prime_qp*_biharmonic._theta_c*(u_qp*u_qp - 1.0)*u_qp + (dphi[i][qp]*grad_u_qp)*M_prime_qp*_biharmonic._theta_c*(3.0*u_qp*u_qp - 1.0)*phi[j][qp]; }// if(_biharmonic._energy == DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_WELL) if (_biharmonic._energy == DOUBLE_OBSTACLE || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) { ri_j -= Laplacian_phi_qp[i]*M_prime_qp*phi[j][qp]*_biharmonic._theta_c*u_qp + Laplacian_phi_qp[i]*M_qp*_biharmonic._theta_c*phi[j][qp] + (dphi[i][qp]*dphi[j][qp])*M_prime_qp*_biharmonic._theta_c*u_qp + (dphi[i][qp]*grad_u_qp)*M_prime_prime_qp*_biharmonic._theta_c*u_qp + (dphi[i][qp]*grad_u_qp)*M_prime_qp*_biharmonic._theta_c*phi[j][qp]; } // if(_biharmonic._energy == DOUBLE_OBSTACLE || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) if (_biharmonic._energy == LOG_DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) { switch(_biharmonic._log_truncation) { case 2: break; case 3: break; default: break; }// switch(_biharmonic._log_truncation) }// if(_biharmonic._energy == LOG_DOUBLE_WELL || _biharmonic._energy == LOG_DOUBLE_OBSTACLE) }// if(_biharmonic._cahn_hillard) Je(i,j) += JxW[qp]*(phi[i][qp]*phi[j][qp] - 0.5*_biharmonic._dt*(2.0-_biharmonic._cnWeight)*ri_j); } // for j } // if (J) } // for i } // for qp // The element matrix and right-hand-side are now built // for this element. Add them to the global matrix and // right-hand-side vector. The \p SparseMatrix::add_matrix() // and \p NumericVector::add_vector() members do this for us. // Start logging the insertion of the local (element) // matrix and vector into the global matrix and vector if (R) { // If the mesh has hanging nodes (e.g., as a result of refinement), those need to be constrained. dof_map.constrain_element_vector(Re, dof_indices); R->add_vector(Re, dof_indices); } if (J) { // If the mesh has hanging nodes (e.g., as a result of refinement), those need to be constrained. dof_map.constrain_element_matrix(Je, dof_indices); J->add_matrix(Je, dof_indices); } } // for el #endif // LIBMESH_ENABLE_SECOND_DERIVATIVES }
void Biharmonic::JR::bounds(NumericVector<Number> &XL, NumericVector<Number>& XU, NonlinearImplicitSystem&) { // sys is actually ignored, since it should be the same as *this. // Declare a performance log. Give it a descriptive // string to identify what part of the code we are // logging, since there may be many PerfLogs in an // application. PerfLog perf_log ("Biharmonic bounds", false); // A reference to the \p DofMap object for this system. The \p DofMap // object handles the index translation from node and element numbers // to degree of freedom numbers. We will talk more about the \p DofMap // in future examples. const DofMap& dof_map = get_dof_map(); // Get a constant reference to the Finite Element type // for the first (and only) variable in the system. FEType fe_type = dof_map.variable_type(0); // Build a Finite Element object of the specified type. Since the // \p FEBase::build() member dynamically creates memory we will // store the object as an \p AutoPtr<FEBase>. This can be thought // of as a pointer that will clean up after itself. AutoPtr<FEBase> fe (FEBase::build(_biharmonic._dim, fe_type)); // Define data structures to contain the bound vectors contributions. DenseVector<Number> XLe, XUe; // These vector will hold the degree of freedom indices for // the element. These define where in the global system // the element degrees of freedom get mapped. std::vector<unsigned int> dof_indices; MeshBase::const_element_iterator el = _biharmonic._mesh->active_local_elements_begin(); const MeshBase::const_element_iterator end_el = _biharmonic._mesh->active_local_elements_end(); for ( ; el != end_el; ++el) { // Extract the shape function to be evaluated at the nodes const std::vector<std::vector<Real> >& phi = fe->get_phi(); // Get the degree of freedom indices for the current element. // They are in 1-1 correspondence with shape functions phi // and define where in the global vector this element will. dof_map.dof_indices (*el, dof_indices); // Resize the local bounds vectors (zeroing them out in the process). XLe.resize(dof_indices.size()); XUe.resize(dof_indices.size()); // Extract the element node coordinates in the reference frame std::vector<Point> nodes; fe->get_refspace_nodes((*el)->type(), nodes); // Evaluate the shape functions at the nodes fe->reinit(*el, &nodes); // Construct the bounds based on the value of the i-th phi at the nodes. // Observe that this doesn't really work in general: we rely on the fact // that for Hermite elements each shape function is nonzero at most at a // single node. // More generally the bounds must be constructed by inspecting a "mass-like" // matrix (m_{ij}) of the shape functions (i) evaluated at their corresponding nodes (j). // The constraints imposed on the dofs (d_i) are then are -1 \leq \sum_i d_i m_{ij} \leq 1, // since \sum_i d_i m_{ij} is the value of the solution at the j-th node. // Auxiliary variables will need to be introduced to reduce this to a "box" constraint. // Additional complications will arise since m might be singular (as is the case for Hermite, // which, however, is easily handled by inspection). for (unsigned int i=0; i<phi.size(); ++i) { // FIXME: should be able to define INF and pass it to the solve Real infinity = 1.0e20; Real bound = infinity; for(unsigned int j = 0; j < nodes.size(); ++j) { if(phi[i][j]) { bound = 1.0/fabs(phi[i][j]); break; } } // The value of the solution at this node must be between 1.0 and -1.0. // Based on the value of phi(i)(i) the nodal coordinate must be between 1.0/phi(i)(i) and its negative. XLe(i) = -bound; XUe(i) = bound; } // The element bound vectors are now built for this element. // Insert them into the global vectors, potentially overwriting // the same dof contributions from other elements: no matter -- // the bounds are always -1.0 and 1.0. XL.insert(XLe, dof_indices); XU.insert(XUe, dof_indices); } }
int CTest::test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition(int argc, char* argv[]) { // Test for method java.lang.StringBuffer // java.text.MessageFormat.format(java.lang.Object [], // java.lang.StringBuffer, java.text.FieldPosition) AutoPtr<IMessageFormat> format; ASSERT_SUCCEEDED(CMessageFormat::New(String("{1,number,integer}"), (IMessageFormat**)&format)); AutoPtr<IStringBuffer> buffer = new StringBuffer(); AutoPtr< ArrayOf<IInterface*> > objlst = ArrayOf<IInterface*>::Alloc(2); String zerostr("0"); AutoPtr<ICharSequence> charSeq; CStringWrapper::New(zerostr, (ICharSequence**)&charSeq); AutoPtr<IDouble> dinter; CDouble::New(53.863, (IDouble**)&dinter); objlst->Set(0, charSeq); objlst->Set(1, dinter); AutoPtr<IFieldPosition> sfp; AutoPtr<IMessageFormatField> ARGUMENT; CMessageFormatField::New(String("message argument field"), (IMessageFormatField**)&ARGUMENT); CFieldPosition::New(ARGUMENT, (IFieldPosition**)&sfp); AutoPtr<IStringBuffer> outbuf; format->FormatObjects(objlst, buffer, sfp, (IStringBuffer**)&outbuf); String outstr; outbuf->ToString(&outstr); // assertEquals("Wrong result", "54", buffer.toString()); assert(String("54").Equals(outstr)); format->FormatObjects(objlst, buffer, sfp, (IStringBuffer**)&outbuf); outbuf->ToString(&outstr); // assertEquals("Wrong result", "5454", buffer.toString()); assert(String("5454").Equals(outstr)); buffer = new StringBuffer(); format->ApplyPattern(String("{0,choice,0#zero|1#one '{1,choice,2#two {2,time}}'}")); AutoPtr<IDate> date; CDate::New((IDate**)&date); AutoPtr<IDateFormatHelper> dfh; CDateFormatHelper::AcquireSingleton((IDateFormatHelper**)&dfh); AutoPtr<IDateFormat> df; dfh->GetTimeInstance((IDateFormat**)&df); String datestr; df->FormatDate(date,&datestr); String expected = String("one two ") + datestr; CDouble::New(1.6, (IDouble**)&dinter); AutoPtr<IInteger32> iinter; CInteger32::New(3, (IInteger32**)&iinter); objlst = ArrayOf<IInterface*>::Alloc(3); objlst->Set(0, dinter); objlst->Set(1, iinter); objlst->Set(2, date); format->FormatObjects(objlst, buffer, sfp, (IStringBuffer**)&outbuf); outbuf->ToString(&outstr); // assertEquals("Choice not recursive:\n" + expected + "\n" + buffer, // expected, buffer.toString()); assert(outstr.Equals(expected)); CDouble::New(0.6, (IDouble**)&dinter); objlst = ArrayOf<IInterface*>::Alloc(2); objlst->Set(0, dinter); objlst->Set(1, iinter); format->FormatObjects(objlst, buffer, NULL, (IStringBuffer**)&outbuf); // assertEquals(expected + "zero", str.toString()); outbuf->ToString(&outstr); assert(outstr.Equals(expected + String("zero"))); // assertEquals(expected + "zero", buffer.toString()); buffer->ToString(&outstr); assert(outstr.Equals(expected + String("zero"))); // try { objlst = ArrayOf<IInterface*>::Alloc(3); String nullstr(""); CStringWrapper::New(nullstr, (ICharSequence**)&charSeq); CDouble::New(1, (IDouble**)&dinter); objlst->Set(0, (IInterface*)&zerostr); objlst->Set(1, dinter); objlst->Set(2, (IInterface*)&charSeq); ECode ec = format->FormatObjects(objlst, buffer, sfp, (IStringBuffer**)&outbuf); if (ec != NOERROR) { printf("IllegalArgumentException was not thrown.\n"); } // fail("IllegalArgumentException was not thrown."); // } catch(IllegalArgumentException iae) { // //expected // } // try { objlst = ArrayOf<IInterface*>::Alloc(2); objlst->Set(0, (IInterface*)&charSeq); objlst->Set(1, iinter); ec = format->FormatObjects(objlst, buffer, sfp, (IStringBuffer**)&outbuf); if (ec != NOERROR) { printf("IllegalArgumentException was not thrown.\n"); } // fail("IllegalArgumentException was not thrown."); // } catch(IllegalArgumentException iae) { // //expected // } return 0; }
int DNGWriter::convert() { d->cancel = false; try { if (inputFile().isEmpty()) { kDebug( 51000 ) << "DNGWriter: No input file to convert. Aborted..." << endl; return -1; } QFileInfo inputInfo(inputFile()); QString dngFilePath = outputFile(); if (dngFilePath.isEmpty()) { dngFilePath = QString(inputInfo.baseName() + QString(".dng")); } QFileInfo outputInfo(dngFilePath); QByteArray rawData; DcrawInfoContainer identify; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Loading RAW data from " << inputInfo.fileName() << endl; KDcraw rawProcessor; if (!rawProcessor.extractRAWData(inputFile(), rawData, identify)) { kDebug( 51000 ) << "DNGWriter: Loading RAW data failed. Aborted..." << endl; return -1; } if (d->cancel) return -2; int width = identify.imageSize.width(); int height = identify.imageSize.height(); int pixelRange = 16; kDebug( 51000 ) << "DNGWriter: Raw data loaded:" << endl; kDebug( 51000 ) << "--- Data Size: " << rawData.size() << " bytes" << endl; kDebug( 51000 ) << "--- Date: " << identify.dateTime.toString(Qt::ISODate) << endl; kDebug( 51000 ) << "--- Make: " << identify.make << endl; kDebug( 51000 ) << "--- Model: " << identify.model << endl; kDebug( 51000 ) << "--- Size: " << width << "x" << height << endl; kDebug( 51000 ) << "--- Orientation: " << identify.orientation << endl; kDebug( 51000 ) << "--- Top margin: " << identify.topMargin << endl; kDebug( 51000 ) << "--- Left margin: " << identify.leftMargin << endl; kDebug( 51000 ) << "--- Filter: " << identify.filterPattern << endl; kDebug( 51000 ) << "--- Colors: " << identify.rawColors << endl; kDebug( 51000 ) << "--- Black: " << identify.blackPoint << endl; kDebug( 51000 ) << "--- White: " << identify.whitePoint << endl; kDebug( 51000 ) << "--- CAM->XYZ:" << endl; QString matrixVal; for(int i=0; i<12; i+=3) { kDebug( 51000 ) << " " << QString().sprintf("%03.4f %03.4f %03.4f", identify.cameraXYZMatrix[0][ i ], identify.cameraXYZMatrix[0][i+1], identify.cameraXYZMatrix[0][i+2]) << endl; } // Check if CFA layout is supported by DNG SDK. int bayerMosaic; if (identify.filterPattern == QString("GRBGGRBGGRBGGRBG")) { bayerMosaic = 0; } else if (identify.filterPattern == QString("RGGBRGGBRGGBRGGB")) { bayerMosaic = 1; } else if (identify.filterPattern == QString("BGGRBGGRBGGRBGGR")) { bayerMosaic = 2; } else if (identify.filterPattern == QString("GBRGGBRGGBRGGBRG")) { bayerMosaic = 3; } else { kDebug( 51000 ) << "DNGWriter: Bayer mosaic not supported. Aborted..." << endl; return -1; } // Check if number of Raw Color components is supported. if (identify.rawColors != 3) { kDebug( 51000 ) << "DNGWriter: Number of Raw color components not supported. Aborted..." << endl; return -1; } /* // NOTE: code to hack RAW data extraction QString rawdataFilePath(inputInfo.baseName() + QString(".dat")); QFileInfo rawdataInfo(rawdataFilePath); QFile rawdataFile(rawdataFilePath); if (!rawdataFile.open(QIODevice::WriteOnly)) { kDebug( 51000 ) << "DNGWriter: Cannot open file to write RAW data. Aborted..." << endl; return -1; } QDataStream rawdataStream(&rawdataFile); rawdataStream.writeRawData(rawData.data(), rawData.size()); rawdataFile.close(); */ // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Formating RAW data to memory" << endl; std::vector<unsigned short> raw_data; raw_data.resize(rawData.size()); const unsigned short* dp = (const unsigned short*)rawData.data(); for (uint i = 0; i < raw_data.size()/2; i++) { raw_data[i] = *dp; *dp++; } if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG memory allocation and initialization" << endl; dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator); dng_memory_stream stream(memalloc); stream.Put(&raw_data.front(), raw_data.size()*sizeof(unsigned short)); dng_rect rect(height, width); DNGWriterHost host(d, &memalloc); // Unprocessed raw data. host.SetKeepStage1(true); // Linearized, tone curve processed data. host.SetKeepStage2(true); AutoPtr<dng_image> image(new dng_simple_image(rect, 1, ttShort, 1<<pixelRange, memalloc)); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG IFD structure creation" << endl; dng_ifd ifd; ifd.fUsesNewSubFileType = true; ifd.fNewSubFileType = 0; ifd.fImageWidth = width; ifd.fImageLength = height; ifd.fBitsPerSample[0] = pixelRange; ifd.fBitsPerSample[1] = 0; ifd.fBitsPerSample[2] = 0; ifd.fBitsPerSample[3] = 0; ifd.fCompression = ccUncompressed; ifd.fPredictor = 1; ifd.fCFALayout = 1; // Rectangular (or square) layout. ifd.fPhotometricInterpretation = piCFA; ifd.fFillOrder = 1; ifd.fOrientation = identify.orientation; ifd.fSamplesPerPixel = 1; ifd.fPlanarConfiguration = 1; ifd.fXResolution = 0.0; ifd.fYResolution = 0.0; ifd.fResolutionUnit = 0; ifd.fUsesStrips = true; ifd.fUsesTiles = false; ifd.fTileWidth = width; ifd.fTileLength = height; ifd.fTileOffsetsType = 4; ifd.fTileOffsetsCount = 0; ifd.fSubIFDsCount = 0; ifd.fSubIFDsOffset = 0; ifd.fExtraSamplesCount = 0; ifd.fSampleFormat[0] = 1; ifd.fSampleFormat[1] = 1; ifd.fSampleFormat[2] = 1; ifd.fSampleFormat[3] = 1; ifd.fLinearizationTableType = 0; ifd.fLinearizationTableCount = 0; ifd.fLinearizationTableOffset = 0; ifd.fBlackLevelRepeatRows = 1; ifd.fBlackLevelRepeatCols = 1; ifd.fBlackLevel[0][0][0] = identify.blackPoint; ifd.fBlackLevelDeltaHType = 0; ifd.fBlackLevelDeltaHCount = 0; ifd.fBlackLevelDeltaHOffset = 0; ifd.fBlackLevelDeltaVType = 0; ifd.fBlackLevelDeltaVCount = 0; ifd.fBlackLevelDeltaVOffset = 0; ifd.fWhiteLevel[0] = identify.whitePoint; ifd.fWhiteLevel[1] = identify.whitePoint; ifd.fWhiteLevel[2] = identify.whitePoint; ifd.fWhiteLevel[3] = identify.whitePoint; ifd.fDefaultScaleH = dng_urational(1, 1); ifd.fDefaultScaleV = dng_urational(1, 1); ifd.fBestQualityScale = dng_urational(1, 1); ifd.fCFARepeatPatternRows = 0; ifd.fCFARepeatPatternCols = 0; ifd.fBayerGreenSplit = 0; ifd.fChromaBlurRadius = dng_urational(0, 0); ifd.fAntiAliasStrength = dng_urational(100, 100); ifd.fActiveArea = rect; ifd.fDefaultCropOriginH = dng_urational(0, 1); ifd.fDefaultCropOriginV = dng_urational(0, 1); ifd.fDefaultCropSizeH = dng_urational(width, 1); ifd.fDefaultCropSizeV = dng_urational(height, 1); ifd.fMaskedAreaCount = 0; ifd.fLosslessJPEGBug16 = false; ifd.fSampleBitShift = 0; ifd.ReadImage(host, stream, *image.Get()); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG Negative structure creation" << endl; AutoPtr<dng_negative> negative(host.Make_dng_negative()); negative->SetDefaultScale(ifd.fDefaultScaleH, ifd.fDefaultScaleV); negative->SetDefaultCropOrigin(ifd.fDefaultCropOriginH, ifd.fDefaultCropOriginV); negative->SetDefaultCropSize(ifd.fDefaultCropSizeH, ifd.fDefaultCropSizeV); negative->SetActiveArea(ifd.fActiveArea); negative->SetModelName(identify.model.toAscii()); negative->SetLocalName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii()); negative->SetOriginalRawFileName(inputInfo.fileName().toAscii()); negative->SetColorChannels(3); negative->SetColorKeys(colorKeyRed, colorKeyGreen, colorKeyBlue); negative->SetBayerMosaic(bayerMosaic); negative->SetWhiteLevel(identify.whitePoint, 0); negative->SetWhiteLevel(identify.whitePoint, 1); negative->SetWhiteLevel(identify.whitePoint, 2); negative->SetBlackLevel(identify.blackPoint, 0); negative->SetBlackLevel(identify.blackPoint, 1); negative->SetBlackLevel(identify.blackPoint, 2); negative->SetBaselineExposure(0.0); negative->SetBaselineNoise(1.0); negative->SetBaselineSharpness(1.0); dng_orientation orientation; switch (identify.orientation) { case DcrawInfoContainer::ORIENTATION_180: orientation = dng_orientation::Rotate180(); break; case DcrawInfoContainer::ORIENTATION_90CCW: orientation = dng_orientation::Rotate90CCW(); break; case DcrawInfoContainer::ORIENTATION_90CW: orientation = dng_orientation::Rotate90CW(); break; default: // ORIENTATION_NONE orientation = dng_orientation::Normal(); break; } negative->SetBaseOrientation(orientation); negative->SetAntiAliasStrength(dng_urational(100, 100)); negative->SetLinearResponseLimit(1.0); negative->SetShadowScale( dng_urational(1, 1) ); negative->SetAnalogBalance(dng_vector_3(1.0, 1.0, 1.0)); // ------------------------------------------------------------------------------- // Set Camera->XYZ Color matrix as profile. dng_matrix_3by3 matrix(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); dng_matrix_3by3 camXYZ; AutoPtr<dng_camera_profile> prof(new dng_camera_profile); prof->SetName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii()); camXYZ[0][0] = identify.cameraXYZMatrix[0][0]; camXYZ[0][1] = identify.cameraXYZMatrix[0][1]; camXYZ[0][2] = identify.cameraXYZMatrix[0][2]; camXYZ[1][0] = identify.cameraXYZMatrix[0][3]; camXYZ[1][1] = identify.cameraXYZMatrix[1][0]; camXYZ[1][2] = identify.cameraXYZMatrix[1][1]; camXYZ[2][0] = identify.cameraXYZMatrix[1][2]; camXYZ[2][1] = identify.cameraXYZMatrix[1][3]; camXYZ[2][2] = identify.cameraXYZMatrix[2][0]; if (camXYZ.MaxEntry() == 0.0) kDebug( 51000 ) << "DNGWriter: Warning, camera XYZ Matrix is null" << endl; else matrix = camXYZ; prof->SetColorMatrix1((dng_matrix) matrix); prof->SetCalibrationIlluminant1(lsD65); negative->AddProfile(prof); // ------------------------------------------------------------------------------- // Clear "Camera WhiteXY" negative->SetCameraWhiteXY(dng_xy_coord()); // This settings break color on preview and thumbnail //negative->SetCameraNeutral(dng_vector_3(1.0, 1.0, 1.0)); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Updating metadata to DNG Negative" << endl; dng_exif *exif = negative->GetExif(); exif->fModel.Set_ASCII(identify.model.toAscii()); exif->fMake.Set_ASCII(identify.make.toAscii()); // Time from original shot dng_date_time dt; dt.fYear = identify.dateTime.date().year(); dt.fMonth = identify.dateTime.date().month(); dt.fDay = identify.dateTime.date().day(); dt.fHour = identify.dateTime.time().hour(); dt.fMinute = identify.dateTime.time().minute(); dt.fSecond = identify.dateTime.time().second(); dng_date_time_info dti; dti.SetDateTime(dt); exif->fDateTimeOriginal = dti; exif->fDateTimeDigitized = dti; negative->UpdateDateTime(dti); long int num, den; long val; QString str; KExiv2 meta; if (meta.load(inputFile())) { // String Tags str = meta.getExifTagString("Exif.Image.Software"); if (!str.isEmpty()) exif->fSoftware.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.ImageDescription"); if (!str.isEmpty()) exif->fImageDescription.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.Artist"); if (!str.isEmpty()) exif->fArtist.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.Copyright"); if (!str.isEmpty()) exif->fCopyright.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Photo.UserComment"); if (!str.isEmpty()) exif->fUserComment.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.CameraSerialNumber"); if (!str.isEmpty()) exif->fCameraSerialNumber.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSLatitudeRef"); if (!str.isEmpty()) exif->fGPSLatitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSLongitudeRef"); if (!str.isEmpty()) exif->fGPSLongitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSSatellites"); if (!str.isEmpty()) exif->fGPSSatellites.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSStatus"); if (!str.isEmpty()) exif->fGPSStatus.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSMeasureMode"); if (!str.isEmpty()) exif->fGPSMeasureMode.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef"); if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSTrackRef"); if (!str.isEmpty()) exif->fGPSTrackRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef"); if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSImgDirectionRef"); if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSMapDatum"); if (!str.isEmpty()) exif->fGPSMapDatum.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestLatitudeRef"); if (!str.isEmpty()) exif->fGPSDestLatitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestLongitudeRef"); if (!str.isEmpty()) exif->fGPSDestLongitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestBearingRef"); if (!str.isEmpty()) exif->fGPSDestBearingRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestDistanceRef"); if (!str.isEmpty()) exif->fGPSDestDistanceRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSProcessingMethod"); if (!str.isEmpty()) exif->fGPSProcessingMethod.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSAreaInformation"); if (!str.isEmpty()) exif->fGPSAreaInformation.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDateStamp"); if (!str.isEmpty()) exif->fGPSDateStamp.Set_ASCII(str.toAscii()); // Rational Tags if (meta.getExifTagRational("Exif.Photo.ExposureTime", num, den)) exif->fExposureTime = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FNumber", num, den)) exif->fFNumber = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.ShutterSpeedValue", num, den)) exif->fShutterSpeedValue = dng_srational(num, den); if (meta.getExifTagRational("Exif.Photo.ApertureValue", num, den)) exif->fApertureValue = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.BrightnessValue", num, den)) exif->fBrightnessValue = dng_srational(num, den); if (meta.getExifTagRational("Exif.Photo.ExposureBiasValue", num, den)) exif->fExposureBiasValue = dng_srational(num, den); if (meta.getExifTagRational("Exif.Photo.MaxApertureValue", num, den)) exif->fMaxApertureValue = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FocalLength", num, den)) exif->fFocalLength = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.DigitalZoomRatio", num, den)) exif->fDigitalZoomRatio = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.SubjectDistance", num, den)) exif->fSubjectDistance = dng_urational(num, den); if (meta.getExifTagRational("Exif.Image.BatteryLevel", num, den)) exif->fBatteryLevelR = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FocalPlaneXResolution", num, den)) exif->fFocalPlaneXResolution = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FocalPlaneYResolution", num, den)) exif->fFocalPlaneYResolution = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSAltitude", num, den)) exif->fGPSAltitude = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDOP", num, den)) exif->fGPSDOP = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSSpeed", num, den)) exif->fGPSSpeed = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSTrack", num, den)) exif->fGPSTrack = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSImgDirection", num, den)) exif->fGPSImgDirection = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestBearing", num, den)) exif->fGPSDestBearing = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestDistance", num, den)) exif->fGPSDestDistance = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSLatitude", num, den)) exif->fGPSLatitude[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSLongitude", num, den)) exif->fGPSLongitude[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSTimeStamp", num, den)) exif->fGPSTimeStamp[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLatitude", num, den)) exif->fGPSDestLatitude[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLongitude", num, den)) exif->fGPSDestLongitude[0] = dng_urational(num, den); // Integer Tags if (meta.getExifTagLong("Exif.Photo.ExposureProgram", val)) exif->fExposureProgram = (uint32)val; if (meta.getExifTagLong("Exif.Photo.MeteringMode", val)) exif->fMeteringMode = (uint32)val; if (meta.getExifTagLong("Exif.Photo.LightSource", val)) exif->fLightSource = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Flash", val)) exif->fFlash = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SensingMethod", val)) exif->fSensingMethod = (uint32)val; if (meta.getExifTagLong("Exif.Photo.FileSource", val)) exif->fFileSource = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SceneType", val)) exif->fSceneType = (uint32)val; if (meta.getExifTagLong("Exif.Photo.CustomRendered", val)) exif->fCustomRendered = (uint32)val; if (meta.getExifTagLong("Exif.Photo.ExposureMode", val)) exif->fExposureMode = (uint32)val; if (meta.getExifTagLong("Exif.Photo.WhiteBalance", val)) exif->fWhiteBalance = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SceneCaptureType", val)) exif->fSceneCaptureType = (uint32)val; if (meta.getExifTagLong("Exif.Photo.GainControl", val)) exif->fGainControl = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Contrast", val)) exif->fContrast = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Saturation", val)) exif->fSaturation = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Sharpness", val)) exif->fSharpness = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SubjectDistanceRange", val)) exif->fSubjectDistanceRange = (uint32)val; if (meta.getExifTagLong("Exif.Photo.FocalLengthIn35mmFilm", val)) exif->fFocalLengthIn35mmFilm = (uint32)val; if (meta.getExifTagLong("Exif.Photo.ComponentsConfiguration", val)) exif->fComponentsConfiguration = (uint32)val; if (meta.getExifTagLong("Exif.Photo.PixelXDimension", val)) exif->fPixelXDimension = (uint32)val; if (meta.getExifTagLong("Exif.Photo.PixelYDimension", val)) exif->fPixelYDimension = (uint32)val; if (meta.getExifTagLong("Exif.Photo.FocalPlaneResolutionUnit", val)) exif->fFocalPlaneResolutionUnit = (uint32)val; if (meta.getExifTagLong("Exif.GPSInfo.GPSVersionID", val)) exif->fGPSVersionID = (uint32)val; if (meta.getExifTagLong("Exif.GPSInfo.GPSAltitudeRef", val)) exif->fGPSAltitudeRef = (uint32)val; if (meta.getExifTagLong("Exif.GPSInfo.GPSDifferential", val)) exif->fGPSDifferential = (uint32)val; } // Markernote backup. QByteArray mkrnts = meta.getExifTagData("Exif.Photo.MakerNote"); if (!mkrnts.isEmpty()) { kDebug( 51000 ) << "DNGWriter: Backup Makernote (" << mkrnts.size() << " bytes)" << endl; dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator); dng_memory_stream stream(memalloc); stream.Put(mkrnts.data(), mkrnts.size()); AutoPtr<dng_memory_block> block(host.Allocate(mkrnts.size())); stream.SetReadPosition(0); stream.Get(block->Buffer(), mkrnts.size()); negative->SetMakerNote(block); negative->SetMakerNoteSafety(true); } if (d->backupOriginalRawFile) { kDebug( 51000 ) << "DNGWriter: Backup Original RAW file (" << inputInfo.size() << " bytes)" << endl; // Compress Raw file data to Zip archive. QTemporaryFile zipFile; if (!zipFile.open()) { kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write Zip Raw file. Aborted..." << endl; return -1; } KZip zipArchive(zipFile.fileName()); zipArchive.open(QIODevice::WriteOnly); zipArchive.setCompression(KZip::DeflateCompression); zipArchive.addLocalFile(inputFile(), inputFile()); zipArchive.close(); // Load Zip Archive in a byte array QFileInfo zipFileInfo(zipFile.fileName()); QByteArray zipRawFileData; zipRawFileData.resize(zipFileInfo.size()); QDataStream dataStream(&zipFile); dataStream.readRawData(zipRawFileData.data(), zipRawFileData.size()); kDebug( 51000 ) << "DNGWriter: Zipped RAW file size " << zipRawFileData.size() << " bytes" << endl; // Pass byte array to DNG sdk and compute MD5 fingerprint. dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator); dng_memory_stream stream(memalloc); stream.Put(zipRawFileData.data(), zipRawFileData.size()); AutoPtr<dng_memory_block> block(host.Allocate(zipRawFileData.size())); stream.SetReadPosition(0); stream.Get(block->Buffer(), zipRawFileData.size()); dng_md5_printer md5; md5.Process(block->Buffer(), block->LogicalSize()); negative->SetOriginalRawFileData(block); negative->SetOriginalRawFileDigest(md5.Result()); negative->ValidateOriginalRawFileDigest(); zipFile.remove(); } if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Build DNG Negative" << endl; // Assign Raw image data. negative->SetStage1Image(image); // Compute linearized and range mapped image negative->BuildStage2Image(host); // Compute demosaiced image (used by preview and thumbnail) negative->BuildStage3Image(host); negative->SynchronizeMetadata(); negative->RebuildIPTC(); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- dng_preview_list previewList; // NOTE: something is wrong with Qt < 4.4.0 to import TIFF data as stream in QImage. #if QT_VERSION >= 0x40400 if (d->previewMode != DNGWriter::NONE) { kDebug( 51000 ) << "DNGWriter: DNG preview image creation" << endl; // Construct a preview image as TIFF format. AutoPtr<dng_image> tiffImage; dng_render tiff_render(host, *negative); tiff_render.SetFinalSpace(dng_space_sRGB::Get()); tiff_render.SetFinalPixelType(ttByte); tiff_render.SetMaximumSize(d->previewMode == MEDIUM ? 1280 : width); tiffImage.Reset(tiff_render.Render()); dng_image_writer tiff_writer; AutoPtr<dng_memory_stream> dms(new dng_memory_stream(gDefaultDNGMemoryAllocator)); tiff_writer.WriteTIFF(host, *dms, *tiffImage.Get(), piRGB, ccUncompressed, negative.Get(), &tiff_render.FinalSpace()); // Write TIFF preview image data to a temp JPEG file std::vector<char> tiff_mem_buffer(dms->Length()); dms->SetReadPosition(0); dms->Get(&tiff_mem_buffer.front(), tiff_mem_buffer.size()); dms.Reset(); QImage pre_image; if (!pre_image.loadFromData((uchar*)&tiff_mem_buffer.front(), tiff_mem_buffer.size(), "TIFF")) { kDebug( 51000 ) << "DNGWriter: Cannot load TIFF preview data in memory. Aborted..." << endl; return -1; } QTemporaryFile previewFile; if (!previewFile.open()) { kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write JPEG preview. Aborted..." << endl; return -1; } if (!pre_image.save(previewFile.fileName(), "JPEG", 90)) { kDebug( 51000 ) << "DNGWriter: Cannot save file to write JPEG preview. Aborted..." << endl; return -1; } // Load JPEG preview file data in DNG preview container. AutoPtr<dng_jpeg_preview> jpeg_preview; jpeg_preview.Reset(new dng_jpeg_preview); jpeg_preview->fPhotometricInterpretation = piYCbCr; jpeg_preview->fPreviewSize.v = pre_image.height(); jpeg_preview->fPreviewSize.h = pre_image.width(); jpeg_preview->fCompressedData.Reset(host.Allocate(previewFile.size())); QDataStream previewStream( &previewFile ); previewStream.readRawData(jpeg_preview->fCompressedData->Buffer_char(), previewFile.size()); AutoPtr<dng_preview> pp( dynamic_cast<dng_preview*>(jpeg_preview.Release()) ); previewList.Append(pp); previewFile.remove(); } #endif /* QT_VERSION >= 0x40400 */ if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG thumbnail creation" << endl; dng_image_preview thumbnail; dng_render thumbnail_render(host, *negative); thumbnail_render.SetFinalSpace(dng_space_sRGB::Get()); thumbnail_render.SetFinalPixelType(ttByte); thumbnail_render.SetMaximumSize(256); thumbnail.fImage.Reset(thumbnail_render.Render()); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Creating DNG file " << outputInfo.fileName() << endl; dng_image_writer writer; dng_file_stream filestream(QFile::encodeName(dngFilePath), true); writer.WriteDNG(host, filestream, *negative.Get(), thumbnail, d->jpegLossLessCompression ? ccJPEG : ccUncompressed, &previewList); } catch (const dng_exception &exception) { int ret = exception.ErrorCode(); kDebug( 51000 ) << "DNGWriter: DNG SDK exception code (" << ret << ")" << endl; return ret; } catch (...) { kDebug( 51000 ) << "DNGWriter: DNG SDK exception code unknow" << endl; return dng_error_unknown; } kDebug( 51000 ) << "DNGWriter: DNG conversion complete..." << endl; return dng_error_none; }
int CTest::test_setFormat(int argc, char* argv[]) { AutoPtr<IMessageFormat> format1; AutoPtr<ILocale> Locale_US; CLocale::New(String("en"), String("US"), (ILocale**)&Locale_US); AutoPtr<ILocaleHelper> lh; CLocaleHelper::AcquireSingleton((ILocaleHelper**)&lh); lh->SetDefault(Locale_US); String pattern("A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}"); CMessageFormat::New(pattern, (IMessageFormat**)&format1); AutoPtr<IMessageFormat> f1 = format1; AutoPtr<IDateFormat> df; AutoPtr<IDateFormatHelper> dfh; CDateFormatHelper::AcquireSingleton((IDateFormatHelper **)&dfh); dfh->GetTimeInstance((IDateFormat **)&df); AutoPtr<INumberFormat> nf; AutoPtr<INumberFormatHelper> nfh; CNumberFormatHelper::AcquireSingleton((INumberFormatHelper **)&nfh); nfh->GetInstance((INumberFormat **)&nf); // case 1: Compare getFormats() results after calls to setFormat() f1->SetFormat(0, df); f1->SetFormat(1, df); f1->SetFormat(2, nf); AutoPtr<IChoiceFormat> cf1, cf2; CChoiceFormat::New(String("0#off|1#on") , (IChoiceFormat **)&cf1); CChoiceFormat::New(String("1#few|2#ok|3#a lot") , (IChoiceFormat **)&cf2); f1->SetFormat(3, cf1); f1->SetFormat(4, cf2); f1->SetFormat(5, df); AutoPtr<ArrayOf<IFormat*> > formats; f1->GetFormats((ArrayOf<IFormat*> **)&formats); AutoPtr<ArrayOf<AutoPtr<IFormat> > > correctFormats = ArrayOf<AutoPtr<IFormat> >::Alloc(6); (*correctFormats)[0] = df; (*correctFormats)[1] = df; (*correctFormats)[2] = nf; (*correctFormats)[3] = cf1; (*correctFormats)[4] = cf2; (*correctFormats)[5] = df; PFL_EX("correctFormats : %d == formats : %d " , correctFormats->GetLength() , formats->GetLength()) assert(correctFormats->GetLength() == formats->GetLength()); for (int i = 0; i < correctFormats->GetLength(); i++) { PFL_EX("index : %d , correctFormats : %p ,formats : %p " ,i ,(*correctFormats)[i].Get(), (*formats)[i] ) assert( (*correctFormats)[i] == (*formats)[i]); } // case 2: Try to setFormat using incorrect index f1->SetFormat(-1, df); ECode ec = f1->GetFormats((ArrayOf<IFormat*> **)&formats); if (ec != NOERROR) { PFL_EX("Expected ArrayIndexOutOfBoundsException was not thrown"); } AutoPtr<IDateFormat> df2; dfh->GetDateTimeInstance((IDateFormat **)&df2); ec = f1->SetFormat(formats->GetLength(), df2); if (ec != NOERROR) { PFL_EX("Expected ArrayIndexOutOfBoundsException was not thrown") } }
std::string MDHistoDimension::toXMLString() const { using namespace Poco::XML; // Create the root element for this fragment. AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pDimensionElement = pDoc->createElement("Dimension"); pDoc->appendChild(pDimensionElement); // Set the id. AutoPtr<Attr> idAttribute = pDoc->createAttribute("ID"); idAttribute->setNodeValue(this->getDimensionId()); pDimensionElement->setAttributeNode(idAttribute); // Set the name. AutoPtr<Element> nameElement = pDoc->createElement("Name"); AutoPtr<Text> nameText = pDoc->createTextNode(this->getName()); nameElement->appendChild(nameText); pDimensionElement->appendChild(nameElement); // Set the units. AutoPtr<Element> unitsElement = pDoc->createElement("Units"); AutoPtr<Text> unitsText = pDoc->createTextNode(this->getUnits()); unitsElement->appendChild(unitsText); pDimensionElement->appendChild(unitsElement); // Set the frame. AutoPtr<Element> frameElement = pDoc->createElement("Frame"); AutoPtr<Text> frameText = pDoc->createTextNode(this->getMDFrame().name()); frameElement->appendChild(frameText); pDimensionElement->appendChild(frameElement); // Set the upper bounds AutoPtr<Element> upperBoundsElement = pDoc->createElement("UpperBounds"); AutoPtr<Text> upperBoundsText = pDoc->createTextNode( boost::str(boost::format("%.4f") % this->getMaximum())); upperBoundsElement->appendChild(upperBoundsText); pDimensionElement->appendChild(upperBoundsElement); // Set the lower bounds AutoPtr<Element> lowerBoundsElement = pDoc->createElement("LowerBounds"); AutoPtr<Text> lowerBoundsText = pDoc->createTextNode( boost::str(boost::format("%.4f") % this->getMinimum())); lowerBoundsElement->appendChild(lowerBoundsText); pDimensionElement->appendChild(lowerBoundsElement); // Set the number of bins AutoPtr<Element> numberOfBinsElement = pDoc->createElement("NumberOfBins"); AutoPtr<Text> numberOfBinsText = pDoc->createTextNode( boost::str(boost::format("%.4d") % this->getNBins())); numberOfBinsElement->appendChild(numberOfBinsText); pDimensionElement->appendChild(numberOfBinsElement); // Provide upper and lower limits for integrated dimensions. if (this->getIsIntegrated()) { AutoPtr<Element> integratedElement = pDoc->createElement("Integrated"); // Set the upper limit AutoPtr<Element> upperLimitElement = pDoc->createElement("UpperLimit"); AutoPtr<Text> upperLimitText = pDoc->createTextNode(boost::str( boost::format("%.4f") % this->getMaximum())); // Dimension does not yet // provide integration // ranges. upperLimitElement->appendChild(upperLimitText); integratedElement->appendChild(upperLimitElement); // Set the lower limit AutoPtr<Element> lowerLimitElement = pDoc->createElement("LowerLimit"); AutoPtr<Text> lowerLimitText = pDoc->createTextNode(boost::str( boost::format("%.4f") % this->getMinimum())); // Dimension does not yet // provide integration // ranges. lowerLimitElement->appendChild(lowerLimitText); integratedElement->appendChild(lowerLimitElement); pDimensionElement->appendChild(integratedElement); } // Create a string representation of the DOM tree. std::stringstream xmlstream; DOMWriter writer; writer.writeNode(xmlstream, pDoc); return xmlstream.str().c_str(); }
void assemble_elasticity(EquationSystems& es, const std::string& system_name) { libmesh_assert (system_name == "Elasticity"); const MeshBase& mesh = es.get_mesh(); const unsigned int dim = mesh.mesh_dimension(); LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("Elasticity"); const unsigned int u_var = system.variable_number ("u"); const unsigned int v_var = system.variable_number ("v"); const unsigned int lambda_var = system.variable_number ("lambda"); const DofMap& dof_map = system.get_dof_map(); FEType fe_type = dof_map.variable_type(0); AutoPtr<FEBase> fe (FEBase::build(dim, fe_type)); QGauss qrule (dim, fe_type.default_quadrature_order()); fe->attach_quadrature_rule (&qrule); AutoPtr<FEBase> fe_face (FEBase::build(dim, fe_type)); QGauss qface(dim-1, fe_type.default_quadrature_order()); fe_face->attach_quadrature_rule (&qface); const std::vector<Real>& JxW = fe->get_JxW(); const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi(); DenseMatrix<Number> Ke; DenseVector<Number> Fe; DenseSubMatrix<Number> Kuu(Ke), Kuv(Ke), Kvu(Ke), Kvv(Ke); DenseSubMatrix<Number> Klambda_v(Ke), Kv_lambda(Ke); DenseSubVector<Number> Fu(Fe), Fv(Fe); std::vector<unsigned int> dof_indices; std::vector<unsigned int> dof_indices_u; std::vector<unsigned int> dof_indices_v; std::vector<unsigned int> dof_indices_lambda; MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { const Elem* elem = *el; dof_map.dof_indices (elem, dof_indices); dof_map.dof_indices (elem, dof_indices_u, u_var); dof_map.dof_indices (elem, dof_indices_v, v_var); dof_map.dof_indices (elem, dof_indices_lambda, lambda_var); const unsigned int n_dofs = dof_indices.size(); const unsigned int n_u_dofs = dof_indices_u.size(); const unsigned int n_v_dofs = dof_indices_v.size(); const unsigned int n_lambda_dofs = dof_indices_lambda.size(); fe->reinit (elem); Ke.resize (n_dofs, n_dofs); Fe.resize (n_dofs); Kuu.reposition (u_var*n_u_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs); Kuv.reposition (u_var*n_u_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs); Kvu.reposition (v_var*n_v_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs); Kvv.reposition (v_var*n_v_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs); // Also, add a row and a column to enforce the constraint Kv_lambda.reposition (v_var*n_u_dofs, v_var*n_u_dofs+n_v_dofs, n_v_dofs, 1); Klambda_v.reposition (v_var*n_v_dofs+n_v_dofs, v_var*n_v_dofs, 1, n_v_dofs); Fu.reposition (u_var*n_u_dofs, n_u_dofs); Fv.reposition (v_var*n_u_dofs, n_v_dofs); for (unsigned int qp=0; qp<qrule.n_points(); qp++) { for (unsigned int i=0; i<n_u_dofs; i++) for (unsigned int j=0; j<n_u_dofs; j++) { // Tensor indices unsigned int C_i, C_j, C_k, C_l; C_i=0, C_k=0; C_j=0, C_l=0; Kuu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=0; Kuu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=0, C_l=1; Kuu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=1; Kuu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); } for (unsigned int i=0; i<n_u_dofs; i++) for (unsigned int j=0; j<n_v_dofs; j++) { // Tensor indices unsigned int C_i, C_j, C_k, C_l; C_i=0, C_k=1; C_j=0, C_l=0; Kuv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=0; Kuv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=0, C_l=1; Kuv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=1; Kuv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); } for (unsigned int i=0; i<n_v_dofs; i++) for (unsigned int j=0; j<n_u_dofs; j++) { // Tensor indices unsigned int C_i, C_j, C_k, C_l; C_i=1, C_k=0; C_j=0, C_l=0; Kvu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=0; Kvu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=0, C_l=1; Kvu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=1; Kvu(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); } for (unsigned int i=0; i<n_v_dofs; i++) for (unsigned int j=0; j<n_v_dofs; j++) { // Tensor indices unsigned int C_i, C_j, C_k, C_l; C_i=1, C_k=1; C_j=0, C_l=0; Kvv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=0; Kvv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=0, C_l=1; Kvv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); C_j=1, C_l=1; Kvv(i,j) += JxW[qp]*(eval_elasticity_tensor(C_i,C_j,C_k,C_l) * dphi[i][qp](C_j)*dphi[j][qp](C_l)); } } { for (unsigned int side=0; side<elem->n_sides(); side++) if (elem->neighbor(side) == NULL) { boundary_id_type bc_id = mesh.boundary_info->boundary_id (elem,side); if (bc_id==BoundaryInfo::invalid_id) libmesh_error(); const std::vector<std::vector<Real> >& phi_face = fe_face->get_phi(); const std::vector<Real>& JxW_face = fe_face->get_JxW(); fe_face->reinit(elem, side); for (unsigned int qp=0; qp<qface.n_points(); qp++) { // Add the loading if( bc_id == 2 ) { for (unsigned int i=0; i<n_v_dofs; i++) { Fv(i) += JxW_face[qp]* (-1.) * phi_face[i][qp]; } } // Add the constraint contributions if( bc_id == 1 ) { for (unsigned int i=0; i<n_v_dofs; i++) for (unsigned int j=0; j<n_lambda_dofs; j++) { Kv_lambda(i,j) += JxW_face[qp]* (-1.) * phi_face[i][qp]; } for (unsigned int i=0; i<n_lambda_dofs; i++) for (unsigned int j=0; j<n_v_dofs; j++) { Klambda_v(i,j) += JxW_face[qp]* (-1.) * phi_face[j][qp]; } } } } } dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices); system.matrix->add_matrix (Ke, dof_indices); system.rhs->add_vector (Fe, dof_indices); } }
AutoPtr (AutoPtr& that) : m_p (that.release ()) {}
ECode ActionBarContextView::InitForMode( /* [in] */ IActionMode* mode) { AutoPtr<IViewParent> vp; if (mClose == NULL) { AutoPtr<ILayoutInflater> inflater; LayoutInflater::From(mContext, (ILayoutInflater**)&inflater); inflater->Inflate(R::layout::action_mode_close_item, THIS_PROBE(IViewGroup), FALSE, (IView**)&mClose); AddView(mClose); } else if ((mClose->GetParent((IViewParent**)&vp), vp) == NULL) { AddView(mClose); } AutoPtr<IView> closeButton; mClose->FindViewById(R::id::action_mode_close_button, (IView**)&closeButton); AutoPtr<IViewOnClickListener> l = new CloseButtonListener(mode); closeButton->SetOnClickListener(l); AutoPtr<IMenuBuilder> menu; mode->GetMenu((IMenu**)&menu); if (mActionMenuPresenter != NULL) { Boolean res = FALSE; mActionMenuPresenter->DismissPopupMenus(&res); } CActionMenuPresenter::New(mContext, (IActionMenuPresenter**)&mActionMenuPresenter); mActionMenuPresenter->SetReserveOverflow(TRUE); AutoPtr<IViewGroupLayoutParams> layoutParams; CViewGroupLayoutParams::New(IViewGroupLayoutParams::WRAP_CONTENT, IViewGroupLayoutParams::MATCH_PARENT, (IViewGroupLayoutParams**)&layoutParams); if (!mSplitActionBar) { menu->AddMenuPresenter(mActionMenuPresenter.Get()); AutoPtr<IMenuView> view; mActionMenuPresenter->GetMenuView(THIS_PROBE(IViewGroup), (IMenuView**)&view); mMenuView = IActionMenuView::Probe(view); mMenuView->SetBackgroundDrawable(NULL); AddView(mMenuView, layoutParams); } else { AutoPtr<IResources> rs; GetContext()->GetResources((IResources**)&rs); AutoPtr<IDisplayMetrics> dm; rs->GetDisplayMetrics((IDisplayMetrics**)&dm); // Allow full screen width in split mode. mActionMenuPresenter->SetWidthLimit( ((CDisplayMetrics*)dm.Get())->mWidthPixels, TRUE); // No limit to the item count; use whatever will fit. mActionMenuPresenter->SetItemLimit(Elastos::Core::Math::INT32_MAX_VALUE); // Span the whole width layoutParams->SetWidth(IViewGroupLayoutParams::MATCH_PARENT); layoutParams->SetHeight(mContentHeight); menu->AddMenuPresenter(mActionMenuPresenter.Get()); AutoPtr<IMenuView> view; mActionMenuPresenter->GetMenuView(THIS_PROBE(IViewGroup), (IMenuView**)&view); mMenuView = IActionMenuView::Probe(view); mMenuView->SetBackgroundDrawable(mSplitBackground); mSplitView->AddView(mMenuView, layoutParams); } mAnimateInOnLayout = TRUE; return NOERROR; }
ECode CSession::PerformDrag( /* [in] */ IIWindow* window, /* [in] */ IBinder* dragToken, /* [in] */ Float touchX, /* [in] */ Float touchY, /* [in] */ Float thumbCenterX, /* [in] */ Float thumbCenterY, /* [in] */ IClipData* data, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); // if (WindowManagerService.DEBUG_DRAG) { // Slog.d(WindowManagerService.TAG, "perform drag: win=" + window + " data=" + data); // } AutoLock lock(mService->mWindowMapLock); if (mService->mDragState == NULL) { Slogger::W(CWindowManagerService::TAG, "No drag prepared"); *result = false; return E_ILLEGAL_STATE_EXCEPTION; // throw new IllegalStateException("performDrag() without prepareDrag()"); } if (dragToken != mService->mDragState->mToken) { Slogger::W(CWindowManagerService::TAG, "Performing mismatched drag"); *result = false; return E_ILLEGAL_STATE_EXCEPTION; // throw new IllegalStateException("performDrag() does not match prepareDrag()"); } AutoPtr<WindowState> callingWin; mService->WindowForClientLocked(NULL, window, FALSE, (WindowState**)&callingWin); if (callingWin == NULL) { Slogger::W(CWindowManagerService::TAG, "Bad requesting window %p", window); *result = false; return NOERROR; // !!! TODO: throw here? } // !!! TODO: if input is not still focused on the initiating window, fail // the drag initiation (e.g. an alarm window popped up just as the application // called performDrag() mService->mH->RemoveMessages( CWindowManagerService::H::DRAG_START_TIMEOUT, window); // !!! TODO: extract the current touch (x, y) in screen coordinates. That // will let us eliminate the (touchX,touchY) parameters from the API. // !!! FIXME: put all this heavy stuff onto the mH looper, as well as // the actual drag event dispatch stuff in the dragstate AutoPtr<IDisplay> display = callingWin->mDisplayContent->GetDisplay(); mService->mDragState->Register(display); mService->mInputMonitor->UpdateInputWindowsLw(TRUE /*force*/); if (!mService->mInputManager->TransferTouchFocus(callingWin->mInputChannel, mService->mDragState->mServerChannel)) { Slogger::E(CWindowManagerService::TAG, "Unable to transfer touch focus"); mService->mDragState->Unregister(); mService->mDragState = NULL; mService->mInputMonitor->UpdateInputWindowsLw(TRUE /*force*/); *result = FALSE; return NOERROR; } mService->mDragState->mData = data; mService->mDragState->mCurrentX = touchX; mService->mDragState->mCurrentY = touchY; mService->mDragState->BroadcastDragStartedLw(touchX, touchY); // remember the thumb offsets for later mService->mDragState->mThumbOffsetX = thumbCenterX; mService->mDragState->mThumbOffsetY = thumbCenterY; // Make the surface visible at the proper location AutoPtr<ISurface> surface = mService->mDragState->mSurface; if (CWindowManagerService::SHOW_LIGHT_TRANSACTIONS) { Slogger::I(CWindowManagerService::TAG, ">>> OPEN TRANSACTION performDrag"); } AutoPtr<ISurfaceHelper> helper; CSurfaceHelper::AcquireSingleton((ISurfaceHelper**)&helper); helper->OpenTransaction(); // try { surface->SetPosition(touchX - thumbCenterX, touchY - thumbCenterY); surface->SetAlpha(0.7071); surface->SetLayer(mService->mDragState->GetDragLayerLw()); Int32 layerStack; display->GetLayerStack(&layerStack); surface->SetLayerStack(layerStack); ECode ec = surface->Show(); if (FAILED(ec)) { *result = FALSE; helper->CloseTransaction(); return ec; } // } finally { helper->CloseTransaction(); if (CWindowManagerService::SHOW_LIGHT_TRANSACTIONS) { Slogger::I(CWindowManagerService::TAG, "<<< CLOSE TRANSACTION performDrag"); } *result = TRUE; return NOERROR; }
void ActionBarContextView::OnMeasure( /* [in] */ Int32 widthMeasureSpec, /* [in] */ Int32 heightMeasureSpec) { Int32 widthMode = MeasureSpec::GetMode(widthMeasureSpec); if (widthMode != MeasureSpec::EXACTLY) { /*throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_width=\"match_parent\" (or fill_parent)");*/ } Int32 heightMode = MeasureSpec::GetMode(heightMeasureSpec); if (heightMode == MeasureSpec::UNSPECIFIED) { /*throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_height=\"wrap_content\"");*/ } Int32 contentWidth = MeasureSpec::GetSize(widthMeasureSpec); Int32 maxHeight = mContentHeight > 0 ? mContentHeight : MeasureSpec::GetSize(heightMeasureSpec); Int32 verticalPadding = GetPaddingTop() + GetPaddingBottom(); Int32 availableWidth = contentWidth - GetPaddingLeft() - GetPaddingRight(); Int32 height = maxHeight - verticalPadding; Int32 childSpecHeight = MeasureSpec::MakeMeasureSpec(height, MeasureSpec::AT_MOST); if (mClose != NULL) { availableWidth = MeasureChildView(mClose, availableWidth, childSpecHeight, 0); AutoPtr<IViewGroupMarginLayoutParams> lp; mClose->GetLayoutParams((IViewGroupLayoutParams**)&lp); availableWidth -= ((CViewGroupMarginLayoutParams*)lp.Get())->mLeftMargin + ((CViewGroupMarginLayoutParams*)lp.Get())->mRightMargin; } AutoPtr<IViewParent> vp; if (mMenuView != NULL && (mMenuView->GetParent((IViewParent**)&vp), vp.Get()) == THIS_PROBE(IViewParent)) { availableWidth = MeasureChildView(mMenuView, availableWidth, childSpecHeight, 0); } if (mTitleLayout != NULL && mCustomView == NULL) { if (mTitleOptional) { Int32 titleWidthSpec = MeasureSpec::MakeMeasureSpec(0, MeasureSpec::UNSPECIFIED); mTitleLayout->Measure(titleWidthSpec, childSpecHeight); Int32 titleWidth; mTitleLayout->GetMeasuredWidth(&titleWidth); Boolean titleFits = titleWidth <= availableWidth; if (titleFits) { availableWidth -= titleWidth; } mTitleLayout->SetVisibility(titleFits ? IView::VISIBLE : IView::GONE); } else { availableWidth = MeasureChildView(mTitleLayout, availableWidth, childSpecHeight, 0); } } if (mCustomView != NULL) { AutoPtr<IViewGroupLayoutParams> lp; mCustomView->GetLayoutParams((IViewGroupLayoutParams**)&lp); Int32 w; lp->GetWidth(&w); Int32 customWidthMode = w != IViewGroupLayoutParams::WRAP_CONTENT ? MeasureSpec::EXACTLY : MeasureSpec::AT_MOST; Int32 customWidth = w >= 0 ? Elastos::Core::Math::Min(w, availableWidth) : availableWidth; Int32 h; lp->GetHeight(&h); Int32 customHeightMode = h != IViewGroupLayoutParams::WRAP_CONTENT ? MeasureSpec::EXACTLY : MeasureSpec::AT_MOST; Int32 customHeight = h >= 0 ? Elastos::Core::Math::Min(h, height) : height; mCustomView->Measure(MeasureSpec::MakeMeasureSpec(customWidth, customWidthMode), MeasureSpec::MakeMeasureSpec(customHeight, customHeightMode)); } if (mContentHeight <= 0) { Int32 measuredHeight = 0; Int32 count = GetChildCount(); for (Int32 i = 0; i < count; i++) { AutoPtr<IView> v = GetChildAt(i); Int32 paddedViewHeight; v->GetMeasuredHeight(&paddedViewHeight); paddedViewHeight += verticalPadding; if (paddedViewHeight > measuredHeight) { measuredHeight = paddedViewHeight; } } SetMeasuredDimension(contentWidth, measuredHeight); } else { SetMeasuredDimension(contentWidth, maxHeight); } }
void NodeTest::testInsertFragment2() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); AutoPtr<DocumentFragment> pFrag = pDoc->createDocumentFragment(); assert (!pRoot->hasChildNodes()); assert (pRoot->firstChild() == 0); assert (pRoot->lastChild() == 0); AutoPtr<Element> pChild2 = pDoc->createElement("child2"); AutoPtr<Element> pChild3 = pDoc->createElement("child3"); pFrag->appendChild(pChild2); pFrag->appendChild(pChild3); pRoot->insertBefore(pFrag, 0); assert (pFrag->firstChild() == 0); assert (pFrag->lastChild() == 0); assert (pRoot->firstChild() == pChild2); assert (pRoot->lastChild() == pChild3); assert (pChild2->previousSibling() == 0); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == 0); AutoPtr<Element> pChild6 = pDoc->createElement("child6"); AutoPtr<Element> pChild7 = pDoc->createElement("child7"); pFrag->appendChild(pChild6); pFrag->appendChild(pChild7); pRoot->insertBefore(pFrag, 0); assert (pRoot->firstChild() == pChild2); assert (pRoot->lastChild() == pChild7); assert (pChild2->previousSibling() == 0); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild6); assert (pChild6->previousSibling() == pChild3); assert (pChild6->nextSibling() == pChild7); assert (pChild7->previousSibling() == pChild6); assert (pChild7->nextSibling() == 0); AutoPtr<Element> pChild0 = pDoc->createElement("child0"); AutoPtr<Element> pChild1 = pDoc->createElement("child1"); pFrag->appendChild(pChild0); pFrag->appendChild(pChild1); pRoot->insertBefore(pFrag, pChild2); assert (pRoot->firstChild() == pChild0); assert (pRoot->lastChild() == pChild7); assert (pChild0->previousSibling() == 0); assert (pChild0->nextSibling() == pChild1); assert (pChild1->previousSibling() == pChild0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild6); assert (pChild6->previousSibling() == pChild3); assert (pChild6->nextSibling() == pChild7); assert (pChild7->previousSibling() == pChild6); assert (pChild7->nextSibling() == 0); AutoPtr<Element> pChild4 = pDoc->createElement("child4"); AutoPtr<Element> pChild5 = pDoc->createElement("child5"); pFrag->appendChild(pChild4); pFrag->appendChild(pChild5); pRoot->insertBefore(pFrag, pChild6); assert (pRoot->firstChild() == pChild0); assert (pRoot->lastChild() == pChild7); assert (pChild0->previousSibling() == 0); assert (pChild0->nextSibling() == pChild1); assert (pChild1->previousSibling() == pChild0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == pChild5); assert (pChild5->previousSibling() == pChild4); assert (pChild5->nextSibling() == pChild6); assert (pChild6->previousSibling() == pChild5); assert (pChild6->nextSibling() == pChild7); assert (pChild7->previousSibling() == pChild6); assert (pChild7->nextSibling() == 0); }
AutoPtr<IAnimator> ActionBarContextView::MakeOutAnimation() { Int32 width = 0; mClose->GetWidth(&width); AutoPtr<IViewGroupMarginLayoutParams> layoutParams; mClose->GetLayoutParams((IViewGroupLayoutParams**)&layoutParams); Int32 leftMargin; layoutParams->GetLeftMargin(&leftMargin); AutoPtr<ArrayOf<Float> > tmpValues = ArrayOf<Float>::Alloc(1); (*tmpValues)[0] = -width - leftMargin; AutoPtr<IObjectAnimator> buttonAnimator = CObjectAnimator::OfFloat(mClose, String("translationX"), tmpValues); buttonAnimator->SetDuration(200); buttonAnimator->AddListener(THIS_PROBE(IAnimatorListener)); AutoPtr<IDecelerateInterpolator> decele; CDecelerateInterpolator::New((IDecelerateInterpolator**)&decele); buttonAnimator->SetInterpolator(decele); AutoPtr<IAnimatorSet> set; CAnimatorSet::New((IAnimatorSet**)&set); AutoPtr<IAnimatorSetBuilder> b; set->Play(buttonAnimator, (IAnimatorSetBuilder**)&b); if (mMenuView != NULL) { Int32 count; mMenuView->GetChildCount(&count); if (count > 0) { for (Int32 i = 0; i < 0; i++) { AutoPtr<IView> child; mMenuView->GetChildAt(i, (IView**)&child); child->SetScaleY(0); AutoPtr<ArrayOf<Float> > tmpValues = ArrayOf<Float>::Alloc(1); (*tmpValues)[0] = 0.f; AutoPtr<IObjectAnimator> a = CObjectAnimator::OfFloat(child, String("scaleY"), tmpValues); a->SetDuration(300); b->With(a); } } } return set; }
void NodeTest::testInsert() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); assert (!pRoot->hasChildNodes()); assert (pRoot->firstChild() == 0); assert (pRoot->lastChild() == 0); AutoPtr<Element> pChild1 = pDoc->createElement("child1"); pRoot->insertBefore(pChild1, 0); assert (pRoot->hasChildNodes()); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild1); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == 0); AutoPtr<Element> pChild3 = pDoc->createElement("child3"); pRoot->insertBefore(pChild3, 0); assert (pRoot->firstChild() == pChild1); assert (pRoot->lastChild() == pChild3); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild1); assert (pChild3->nextSibling() == 0); AutoPtr<Element> pChild0 = pDoc->createElement("child0"); pRoot->insertBefore(pChild0, pChild1); assert (pRoot->firstChild() == pChild0); assert (pRoot->lastChild() == pChild3); assert (pChild0->previousSibling() == 0); assert (pChild0->nextSibling() == pChild1); assert (pChild1->previousSibling() == pChild0); assert (pChild1->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild1); assert (pChild3->nextSibling() == 0); AutoPtr<Element> pChild2 = pDoc->createElement("child2"); pRoot->insertBefore(pChild2, pChild3); assert (pRoot->firstChild() == pChild0); assert (pRoot->lastChild() == pChild3); assert (pChild0->previousSibling() == 0); assert (pChild0->nextSibling() == pChild1); assert (pChild1->previousSibling() == pChild0); assert (pChild1->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild1); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == 0); }
void IconMenuView::PositionChildren( /* [in] */ Int32 menuWidth, /* [in] */ Int32 menuHeight) { // Clear the containers for the positions where the dividers should be drawn if (mHorizontalDivider != NULL) mHorizontalDividerRects.Clear(); if (mVerticalDivider != NULL) mVerticalDividerRects.Clear(); // Get the minimum number of rows needed const Int32 numRows = mLayoutNumRows; const Int32 numRowsMinus1 = numRows - 1; const ArrayOf<Int32>* numItemsForRow = mLayout; // The item position across all rows Int32 itemPos = 0; AutoPtr<IView> child; AutoPtr<IIconMenuViewLayoutParams> lp; // Use float for this to get precise positions (uniform item widths // instead of last one taking any slack), and then convert to ints at last opportunity Float itemLeft; Float itemTop = 0; // Since each row can have a different number of items, this will be computed per row Float itemWidth; // Subtract the space needed for the horizontal dividers Float itemHeight = (menuHeight - mHorizontalDividerHeight * (numRows - 1)) / (Float)numRows; for (Int32 row = 0; row < numRows; row++) { // Start at the left itemLeft = 0; // Subtract the space needed for the vertical dividers, and divide by the number of items itemWidth = (menuWidth - mVerticalDividerWidth * ((*numItemsForRow)[row] - 1)) / (Float)(*numItemsForRow)[row]; for (Int32 itemPosOnRow = 0; itemPosOnRow < (*numItemsForRow)[row]; itemPosOnRow++) { // Tell the child to be exactly this size child = GetChildAt(itemPos); child->Measure(MeasureSpec::MakeMeasureSpec((Int32)itemWidth, MeasureSpec::EXACTLY), MeasureSpec::MakeMeasureSpec((Int32)itemHeight, MeasureSpec::EXACTLY)); // Remember the child's position for layout child->GetLayoutParams((IViewGroupLayoutParams**)&lp); lp->SetLeft((Int32)itemLeft); lp->SetRight((Int32)(itemLeft + itemWidth)); lp->SetTop((Int32)itemTop); lp->SetBottom((Int32)(itemTop + itemHeight)); // Increment by item width itemLeft += itemWidth; itemPos++; // Add a vertical divider to draw if (mVerticalDivider != NULL) { AutoPtr<IRect> rect; CRect::New((Int32)itemLeft, (Int32)itemTop, (Int32)(itemLeft + mVerticalDividerWidth), (Int32)(itemTop + itemHeight), (IRect**)&rect); mVerticalDividerRects.PushBack(rect); } // Increment by divider width (even if we're not computing // dividers, since we need to leave room for them when // calculating item positions) itemLeft += mVerticalDividerWidth; } // Last child on each row should extend to very right edge if (lp != NULL) { lp->SetRight(menuWidth); } itemTop += itemHeight; // Add a horizontal divider to draw if ((mHorizontalDivider != NULL) && (row < numRowsMinus1)) { AutoPtr<IRect> rect; CRect::New(0, (Int32)itemTop, menuWidth, (Int32)(itemTop + mHorizontalDividerHeight), (IRect**)&rect); mHorizontalDividerRects.PushBack(rect); itemTop += mHorizontalDividerHeight; } } }
void NodeTest::testReplaceFragment3() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); AutoPtr<DocumentFragment> pFrag = pDoc->createDocumentFragment(); AutoPtr<Element> pChild1 = pDoc->createElement("child1"); pRoot->appendChild(pChild1); AutoPtr<Element> pChild2 = pDoc->createElement("child2"); pRoot->appendChild(pChild2); AutoPtr<Element> pChild3 = pDoc->createElement("child3"); pRoot->appendChild(pChild3); AutoPtr<Element> pChild4 = pDoc->createElement("child4"); pRoot->appendChild(pChild4); AutoPtr<Element> pChild11 = pDoc->createElement("child11"); AutoPtr<Element> pChild12 = pDoc->createElement("child12"); AutoPtr<Element> pChild13 = pDoc->createElement("child13"); pFrag->appendChild(pChild11); pFrag->appendChild(pChild12); pFrag->appendChild(pChild13); pRoot->replaceChild(pFrag, pChild1); assert (pFrag->firstChild() == 0); assert (pFrag->lastChild() == 0); assert (pChild1->previousSibling() == 0); assert (pChild1->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild4); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild12); assert (pChild12->previousSibling() == pChild11); assert (pChild12->nextSibling() == pChild13); assert (pChild13->previousSibling() == pChild12); assert (pChild13->nextSibling() == pChild2); assert (pChild2->previousSibling() == pChild13); assert (pChild2->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild2); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == 0); AutoPtr<Element> pChild21 = pDoc->createElement("child21"); AutoPtr<Element> pChild22 = pDoc->createElement("child22"); AutoPtr<Element> pChild23 = pDoc->createElement("child23"); pFrag->appendChild(pChild21); pFrag->appendChild(pChild22); pFrag->appendChild(pChild23); pRoot->replaceChild(pFrag, pChild2); assert (pChild2->previousSibling() == 0); assert (pChild2->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild4); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild12); assert (pChild12->previousSibling() == pChild11); assert (pChild12->nextSibling() == pChild13); assert (pChild13->previousSibling() == pChild12); assert (pChild13->nextSibling() == pChild21); assert (pChild21->previousSibling() == pChild13); assert (pChild21->nextSibling() == pChild22); assert (pChild22->previousSibling() == pChild21); assert (pChild22->nextSibling() == pChild23); assert (pChild23->previousSibling() == pChild22); assert (pChild23->nextSibling() == pChild3); assert (pChild3->previousSibling() == pChild23); assert (pChild3->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild3); assert (pChild4->nextSibling() == 0); AutoPtr<Element> pChild31 = pDoc->createElement("child31"); AutoPtr<Element> pChild32 = pDoc->createElement("child32"); AutoPtr<Element> pChild33 = pDoc->createElement("child33"); pFrag->appendChild(pChild31); pFrag->appendChild(pChild32); pFrag->appendChild(pChild33); pRoot->replaceChild(pFrag, pChild3); assert (pChild3->previousSibling() == 0); assert (pChild3->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild4); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild12); assert (pChild12->previousSibling() == pChild11); assert (pChild12->nextSibling() == pChild13); assert (pChild13->previousSibling() == pChild12); assert (pChild13->nextSibling() == pChild21); assert (pChild21->previousSibling() == pChild13); assert (pChild21->nextSibling() == pChild22); assert (pChild22->previousSibling() == pChild21); assert (pChild22->nextSibling() == pChild23); assert (pChild23->previousSibling() == pChild22); assert (pChild23->nextSibling() == pChild31); assert (pChild31->previousSibling() == pChild23); assert (pChild31->nextSibling() == pChild32); assert (pChild32->previousSibling() == pChild31); assert (pChild32->nextSibling() == pChild33); assert (pChild33->previousSibling() == pChild32); assert (pChild33->nextSibling() == pChild4); assert (pChild4->previousSibling() == pChild33); assert (pChild4->nextSibling() == 0); AutoPtr<Element> pChild41 = pDoc->createElement("child41"); AutoPtr<Element> pChild42 = pDoc->createElement("child42"); AutoPtr<Element> pChild43 = pDoc->createElement("child43"); pFrag->appendChild(pChild41); pFrag->appendChild(pChild42); pFrag->appendChild(pChild43); pRoot->replaceChild(pFrag, pChild4); assert (pChild4->previousSibling() == 0); assert (pChild4->nextSibling() == 0); assert (pRoot->firstChild() == pChild11); assert (pRoot->lastChild() == pChild43); assert (pChild11->previousSibling() == 0); assert (pChild11->nextSibling() == pChild12); assert (pChild12->previousSibling() == pChild11); assert (pChild12->nextSibling() == pChild13); assert (pChild13->previousSibling() == pChild12); assert (pChild13->nextSibling() == pChild21); assert (pChild21->previousSibling() == pChild13); assert (pChild21->nextSibling() == pChild22); assert (pChild22->previousSibling() == pChild21); assert (pChild22->nextSibling() == pChild23); assert (pChild23->previousSibling() == pChild22); assert (pChild23->nextSibling() == pChild31); assert (pChild31->previousSibling() == pChild23); assert (pChild31->nextSibling() == pChild32); assert (pChild32->previousSibling() == pChild31); assert (pChild32->nextSibling() == pChild33); assert (pChild33->previousSibling() == pChild32); assert (pChild33->nextSibling() == pChild41); assert (pChild41->previousSibling() == pChild33); assert (pChild41->nextSibling() == pChild42); assert (pChild42->previousSibling() == pChild41); assert (pChild42->nextSibling() == pChild43); assert (pChild43->previousSibling() == pChild42); assert (pChild43->nextSibling() == 0); }
void Preference::Init( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyle) { mContext = context; AutoPtr<ArrayOf<Int32> > attrIds = ArrayOf<Int32>::Alloc( const_cast<Int32 *>(R::styleable::Preference), ARRAY_SIZE(R::styleable::Preference)); AutoPtr<ITypedArray> a; context->ObtainStyledAttributes(attrs, attrIds, defStyle, 0, (ITypedArray**)&a); Int32 indexCount; a->GetIndexCount(&indexCount); for (Int32 i = indexCount; i >= 0; i--) { Int32 attr; a->GetIndex(i, &attr); switch (attr) { case R::styleable::Preference_icon: a->GetResourceId(attr, 0, &mIconResId); break; case R::styleable::Preference_key: a->GetString(attr, &mKey); break; case R::styleable::Preference_title: { a->GetResourceId(attr, 0, &mTitleRes); String str; a->GetString(attr, &str); CStringWrapper::New(str, (ICharSequence**)&mTitle); break; } case R::styleable::Preference_summary: { String str; a->GetString(attr, &str); CStringWrapper::New(str, (ICharSequence**)&mSummary); break; } case R::styleable::Preference_order: a->GetInt32(attr, mOrder, &mOrder); break; case R::styleable::Preference_fragment: a->GetString(attr, &mFragment); break; case R::styleable::Preference_layout: a->GetResourceId(attr, mLayoutResId, &mLayoutResId); break; case R::styleable::Preference_widgetLayout: a->GetResourceId(attr, mWidgetLayoutResId, &mWidgetLayoutResId); break; case R::styleable::Preference_enabled: a->GetBoolean(attr, TRUE, &mEnabled); break; case R::styleable::Preference_selectable: a->GetBoolean(attr, TRUE, &mSelectable); break; case R::styleable::Preference_persistent: a->GetBoolean(attr, mPersistent, &mPersistent); break; case R::styleable::Preference_dependency: a->GetString(attr, &mDependencyKey); break; case R::styleable::Preference_defaultValue: OnGetDefaultValue(a, attr, (IInterface**)&mDefaultValue); break; case R::styleable::Preference_shouldDisableView: a->GetBoolean(attr, mShouldDisableView, &mShouldDisableView); break; } } a->Recycle(); // ClassID clsId; // GetClassID(&clsId); // String clsName(clsId.pUunm); // if (!clsName.StartWith("Elastos.Droid.Core.eco")) { // // For subclasses not in this package, assume the worst and don't cache views // mHasSpecifiedLayout = TRUE; // } }
void ElementTest::testAttrMapNS() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pElem = pDoc->createElementNS("urn:ns1", "elem"); AutoPtr<NamedNodeMap> pNNM = pElem->attributes(); assert (pNNM->length() == 0); pElem->setAttributeNS("urn:ns1", "a1", "v1"); assert (pNNM->length() == 1); assert (pNNM->item(0)->nodeName() == "a1"); assert (pNNM->getNamedItemNS("urn:ns1", "a1")->nodeName() == "a1"); pElem->setAttributeNS("urn:ns1", "a2", "v2"); assert (pNNM->length() == 2); assert (pNNM->item(0)->nodeName() == "a1"); assert (pNNM->getNamedItem("a1")->nodeName() == "a1"); assert (pNNM->item(1)->nodeName() == "a2"); assert (pNNM->getNamedItem("a2")->nodeName() == "a2"); Attr* pAttr = pDoc->createAttributeNS("urn:ns2", "a3"); pNNM->setNamedItem(pAttr); pAttr->release(); assert (pNNM->length() == 3); assert (pNNM->item(0)->nodeName() == "a1"); assert (pNNM->getNamedItemNS("urn:ns1", "a1")->nodeName() == "a1"); assert (pNNM->item(1)->nodeName() == "a2"); assert (pNNM->getNamedItemNS("urn:ns1", "a2")->nodeName() == "a2"); assert (pNNM->item(2)->nodeName() == "a3"); assert (pNNM->getNamedItemNS("urn:ns2", "a3")->nodeName() == "a3"); pNNM->removeNamedItemNS("urn:ns1", "a2"); assert (pNNM->length() == 2); assert (!pElem->hasAttributeNS("urn:ns1", "a2")); pNNM->removeNamedItemNS("urn:ns2", "a3"); assert (pNNM->length() == 1); assert (!pElem->hasAttributeNS("urn:ns2", "a3")); pElem->removeAttributeNS("urn:ns1", "a1"); assert (pNNM->length() == 0); }
ECode CActivityOne::SetupViews() { AutoPtr<MyListener> l = new MyListener(this); AutoPtr<IView> view = FindViewById(R::id::InfoTextView); assert(view != NULL); mInfoTextView = ITextView::Probe(view); view = FindViewById(R::id::DisplayListView); assert(view != NULL); mDisplayListView = IListView::Probe(view); view = FindViewById(R::id::ScanButton); assert(view != NULL); view->SetOnClickListener(l.Get()); view = FindViewById(R::id::RenameButton); assert(view != NULL); view->SetOnClickListener(l.Get()); view = FindViewById(R::id::ConnectButton); assert(view != NULL); view->SetOnClickListener(l.Get()); view = FindViewById(R::id::DisconnectButton); assert(view != NULL); view->SetOnClickListener(l.Get()); view = FindViewById(R::id::ForgetButton); assert(view != NULL); view->SetOnClickListener(l.Get()); view = FindViewById(R::id::GetStatusButton); assert(view != NULL); view->SetOnClickListener(l.Get()); view = FindViewById(R::id::DisplayListView); mDisplayListView = IListView::Probe(view); assert(mDisplayListView != NULL); AutoPtr<IColorDrawable> drawable; CColorDrawable::New(0xFF0000FF, (IColorDrawable**)&drawable); assert(drawable != NULL); mDisplayListView->SetDivider(drawable); mDisplayListView->SetDividerHeight(1); mDisplayListView->SetOnItemClickListener(l); return NOERROR; }
void ElementTest::testAttributes() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pElem = pDoc->createElement("elem"); assert (!pElem->hasAttributes()); pElem->setAttribute("a1", "v1"); assert (pElem->hasAttributes()); assert (pElem->hasAttribute("a1")); assert (pElem->getAttribute("a1") == "v1"); Attr* pAttr1 = pElem->getAttributeNode("a1"); assert (pAttr1 != 0); assert (pAttr1->name() == "a1"); assert (pAttr1->nodeName() == "a1"); assert (pAttr1->value() == "v1"); assert (pAttr1->nodeValue() == "v1"); assert (pAttr1->ownerElement() == pElem); assert (pAttr1->ownerDocument() == pDoc); assert (pAttr1->innerText() == "v1"); assert (pAttr1->previousSibling() == 0); assert (pAttr1->nextSibling() == 0); pAttr1->setValue("V1"); assert (pElem->getAttribute("a1") == "V1"); pElem->setAttribute("a2", "v2"); assert (pElem->hasAttribute("a1")); assert (pElem->getAttribute("a1") == "V1"); assert (pElem->hasAttribute("a2")); assert (pElem->getAttribute("a2") == "v2"); Attr* pAttr2 = pElem->getAttributeNode("a2"); assert (pAttr2 != 0); assert (pAttr2->name() == "a2"); assert (pAttr2->value() == "v2"); assert (pAttr2->ownerElement() == pElem); assert (pAttr1->previousSibling() == 0); assert (pAttr1->nextSibling() == pAttr2); assert (pAttr2->previousSibling() == pAttr1); assert (pAttr2->nextSibling() == 0); Attr* pAttr3 = pElem->getAttributeNode("a3"); assert (pAttr3 == 0); pAttr3 = pDoc->createAttribute("a3"); pAttr3->setValue("v3"); pElem->setAttributeNode(pAttr3); pAttr3->release(); assert (pElem->hasAttribute("a1")); assert (pElem->getAttribute("a1") == "V1"); assert (pElem->hasAttribute("a2")); assert (pElem->getAttribute("a2") == "v2"); assert (pElem->hasAttribute("a3")); assert (pElem->getAttribute("a3") == "v3"); assert (pAttr1->previousSibling() == 0); assert (pAttr1->nextSibling() == pAttr2); assert (pAttr2->previousSibling() == pAttr1); assert (pAttr2->nextSibling() == pAttr3); assert (pAttr3->previousSibling() == pAttr2); assert (pAttr3->nextSibling() == 0); pAttr2 = pDoc->createAttribute("a2"); pAttr2->setValue("V2"); pElem->setAttributeNode(pAttr2); pAttr2->release(); assert (pElem->hasAttribute("a1")); assert (pElem->getAttribute("a1") == "V1"); assert (pElem->hasAttribute("a2")); assert (pElem->getAttribute("a2") == "V2"); assert (pElem->hasAttribute("a3")); assert (pElem->getAttribute("a3") == "v3"); pAttr1 = pDoc->createAttribute("a1"); pAttr1->setValue("v1"); pElem->setAttributeNode(pAttr1); pAttr1->release(); assert (pElem->hasAttribute("a1")); assert (pElem->getAttribute("a1") == "v1"); assert (pElem->hasAttribute("a2")); assert (pElem->getAttribute("a2") == "V2"); assert (pElem->hasAttribute("a3")); assert (pElem->getAttribute("a3") == "v3"); pAttr3 = pDoc->createAttribute("a3"); pAttr3->setValue("V3"); pElem->setAttributeNode(pAttr3); pAttr3->release(); assert (pElem->hasAttribute("a1")); assert (pElem->getAttribute("a1") == "v1"); assert (pElem->hasAttribute("a2")); assert (pElem->getAttribute("a2") == "V2"); assert (pElem->hasAttribute("a3")); assert (pElem->getAttribute("a3") == "V3"); pElem->removeAttributeNode(pAttr3); assert (!pElem->hasAttribute("a3")); pElem->removeAttribute("a1"); assert (!pElem->hasAttribute("a1")); pElem->removeAttribute("a2"); assert (!pElem->hasAttribute("a2")); assert (!pElem->hasAttributes()); }
AutoPtr<IIGeocodeProvider> GeocoderProxy::GetService() { AutoPtr<IBinder> binder = mServiceWatcher->GetBinder(); AutoPtr<IIGeocodeProvider> rst = (IIGeocodeProvider*)(binder->Probe(EIID_IIGeocodeProvider)); return rst; }
void ElementTest::testNodeByPathNS() { /* <ns1:root xmlns:ns1="urn:ns1"> <ns1:elem1> <ns2:elemA xmlns:ns2="urn:ns2"/> <ns3:elemA xmlns:ns3="urn:ns2"/> </ns1:elem1> <ns1:elem2> <ns2:elemB ns2:attr1="value1" xmlns:ns2="urn:ns2"/> <ns2:elemB ns2:attr1="value2" xmlns:ns2="urn:ns2"/> <ns2:elemB ns2:attr1="value3" xmlns:ns2="urn:ns2"/> <ns2:elemC ns2:attr1="value1" xmlns:ns2="urn:ns2"> <ns2:elemC1 ns2:attr1="value1"/> <ns2:elemC2/> </ns2:elemC> <ns2:elemC ns2:attr1="value2" xmlns:ns2="urn:ns2"/> </ns1:elem2> </ns1:root> */ AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElementNS("urn:ns1", "ns1:root"); AutoPtr<Element> pElem1 = pDoc->createElementNS("urn:ns1", "ns1:elem1"); AutoPtr<Element> pElem11 = pDoc->createElementNS("urn:ns2", "ns2:elemA"); AutoPtr<Element> pElem12 = pDoc->createElementNS("urn:ns2", "ns2:elemA"); AutoPtr<Element> pElem2 = pDoc->createElementNS("urn:ns1", "ns1:elem2"); AutoPtr<Element> pElem21 = pDoc->createElementNS("urn:ns2", "ns2:elemB"); AutoPtr<Element> pElem22 = pDoc->createElementNS("urn:ns2", "ns2:elemB"); AutoPtr<Element> pElem23 = pDoc->createElementNS("urn:ns2", "ns2:elemB"); AutoPtr<Element> pElem24 = pDoc->createElementNS("urn:ns2", "ns2:elemC"); AutoPtr<Element> pElem25 = pDoc->createElementNS("urn:ns2", "ns2:elemC"); pElem21->setAttributeNS("urn:ns2", "ns2:attr1", "value1"); pElem22->setAttributeNS("urn:ns2", "ns2:attr1", "value2"); pElem23->setAttributeNS("urn:ns2", "ns2:attr1", "value3"); pElem24->setAttributeNS("urn:ns2", "ns2:attr1", "value1"); pElem25->setAttributeNS("urn:ns2", "ns2:attr1", "value2"); AutoPtr<Element> pElem241 = pDoc->createElementNS("urn:ns2", "elemC1"); AutoPtr<Element> pElem242 = pDoc->createElementNS("urn:ns2", "elemC2"); pElem241->setAttributeNS("urn:ns2", "ns2:attr1", "value1"); pElem24->appendChild(pElem241); pElem24->appendChild(pElem242); pElem1->appendChild(pElem11); pElem1->appendChild(pElem12); pElem2->appendChild(pElem21); pElem2->appendChild(pElem22); pElem2->appendChild(pElem23); pElem2->appendChild(pElem24); pElem2->appendChild(pElem25); pRoot->appendChild(pElem1); pRoot->appendChild(pElem2); pDoc->appendChild(pRoot); Element::NSMap nsMap; nsMap.declarePrefix("ns1", "urn:ns1"); nsMap.declarePrefix("NS2", "urn:ns2"); Node* pNode = pRoot->getNodeByPathNS("/", nsMap); assert (pNode == pRoot); pNode = pRoot->getNodeByPathNS("/ns1:elem1", nsMap); assert (pNode == pElem1); pNode = pDoc->getNodeByPathNS("/ns1:root/ns1:elem1", nsMap); assert (pNode == pElem1); pNode = pRoot->getNodeByPathNS("/ns1:elem2", nsMap); assert (pNode == pElem2); pNode = pRoot->getNodeByPathNS("/ns1:elem1/NS2:elemA", nsMap); assert (pNode == pElem11); pNode = pRoot->getNodeByPathNS("/ns1:elem1/NS2:elemA[0]", nsMap); assert (pNode == pElem11); pNode = pRoot->getNodeByPathNS("/ns1:elem1/NS2:elemA[1]", nsMap); assert (pNode == pElem12); pNode = pRoot->getNodeByPathNS("/ns1:elem1/NS2:elemA[2]", nsMap); assert (pNode == 0); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB", nsMap); assert (pNode == pElem21); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[0]", nsMap); assert (pNode == pElem21); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[1]", nsMap); assert (pNode == pElem22); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[2]", nsMap); assert (pNode == pElem23); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[3]", nsMap); assert (pNode == 0); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[@NS2:attr1]", nsMap); assert (pNode && pNode->nodeValue() == "value1"); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[@NS2:attr2]", nsMap); assert (pNode == 0); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemB[@NS2:attr1='value2']", nsMap); assert (pNode == pElem22); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemC[@NS2:attr1='value1']/NS2:elemC1", nsMap); assert (pNode == pElem241); pNode = pRoot->getNodeByPathNS("/ns1:elem2/NS2:elemC[@NS2:attr1='value1']/NS2:elemC1[@NS2:attr1]", nsMap); assert (pNode && pNode->nodeValue() == "value1"); pNode = pRoot->getNodeByPathNS("/NS2:elem1", nsMap); assert (pNode == 0); pNode = pDoc->getNodeByPathNS("//NS2:elemB[@NS2:attr1='value1']", nsMap); assert (pNode == pElem21); pNode = pDoc->getNodeByPathNS("//NS2:elemB[@NS2:attr1='value2']", nsMap); assert (pNode == pElem22); pNode = pDoc->getNodeByPathNS("//NS2:elemB[@NS2:attr1='value3']", nsMap); assert (pNode == pElem23); pNode = pDoc->getNodeByPathNS("//NS2:elemB[@NS2:attr1='value4']", nsMap); assert (pNode == 0); pNode = pDoc->getNodeByPathNS("//[@NS2:attr1='value1']", nsMap); assert (pNode == pElem21); pNode = pDoc->getNodeByPathNS("//[@NS2:attr1='value2']", nsMap); assert (pNode == pElem22); }
int main (int, char**) { quit_global_flag = false; signal(SIGINT, killMe); signal(SIGTERM, killMe); #ifdef LEDS_ENABLED LEDControl::initLED(LED_LIME); LEDControl::initLED(LED_PAN); LEDControl::setLED(LED_LIME, false); LEDControl::setLED(LED_PAN, false); sleep(1); LEDControl::blinkLED(LED_LIME, 3); #endif long long int adapter_id = 0x0; bool mod_pan = false; bool mod_virtual_sensor = false; bool mod_pressure_sensor = false; bool mod_mqtt = false; bool mod_vpt = false; bool mod_openhab = false; AutoPtr<IniFileConfiguration> cfg; AutoPtr<IniFileConfiguration> cfg_pan; AutoPtr<IniFileConfiguration> cfg_virtual_sensor; AutoPtr<IniFileConfiguration> cfg_pressure_sensor; AutoPtr<IniFileConfiguration> cfg_vpt; AutoPtr<IniFileConfiguration> cfg_mqtt; AutoPtr<IniFileConfiguration> cfg_hab; Poco::Thread agg_thread("Aggregator"); Poco::Thread vsm_thread("VSM"); Poco::Thread srv_thread("TCP"); Poco::Thread vpt_thread("VPT"); Poco::Thread hab_thread("HAB"); Logger& log = Poco::Logger::get("Adaapp-MAIN"); // get logging utility log.setLevel("trace"); // set default lowest level cerr << "Loading AdaApp.ini from " << CONFIG_FILE << endl; /* Load main config file */ try { cfg = new IniFileConfiguration(CONFIG_FILE); } catch (Poco::Exception& ex) { cerr << "Error: Exception with config file reading:" << (string)ex.displayText() << endl; return EXIT_FAILURE; } setLoggingLevel(log, cfg); /* Set logging level from configuration file*/ setLoggingChannel(log, cfg); /* Set where to log (console, file, etc.)*/ cerr << "Loading modules configurations from " << MODULES_DIR << endl; try { cfg_pan = new IniFileConfiguration(string(MODULES_DIR)+string(MOD_PAN)+".ini"); mod_pan = cfg_pan->getBool(string(MOD_PAN)+".enabled", false); } catch (...) { } try { cfg_virtual_sensor = new IniFileConfiguration(string(MODULES_DIR)+string(MOD_VIRTUAL_SENSOR)+".ini"); mod_virtual_sensor = cfg_virtual_sensor->getBool(string(MOD_VIRTUAL_SENSOR)+".enabled", false); } catch (...) { } try { cfg_pressure_sensor = new IniFileConfiguration(string(MODULES_DIR)+string(MOD_PRESSURE_SENSOR)+".ini"); mod_pressure_sensor = cfg_pressure_sensor->getBool(string(MOD_PRESSURE_SENSOR)+".enabled", false); } catch (...) { } try { cfg_vpt = new IniFileConfiguration(string(MODULES_DIR)+string(MOD_VPT_SENSOR)+".ini"); mod_vpt = cfg_vpt->getBool(string(MOD_VPT_SENSOR)+".enabled", false); } catch (...) { } try { // OpenHAB cfg_hab = new IniFileConfiguration(string(MODULES_DIR)+string(MOD_OPENHAB)+".ini"); mod_openhab = cfg_hab->getBool(string(MOD_OPENHAB)+".enabled", false); } catch (...) { } try { cfg_mqtt = new IniFileConfiguration(string(MODULES_DIR)+string(MOD_MQTT)+".ini"); mod_mqtt = cfg_mqtt->getBool(string(MOD_MQTT)+".enabled", false); } catch (...) { } #ifndef PC_PLATFORM EEPROM_ITEMS eeprom = parseEEPROM(); for (auto item : eeprom.items) { if (item.first == 0x01) { adapter_id = item.second; break; } } #endif // Try to find adapter_id in configuration file // TODO this is temporal solution for PC platform if (adapter_id <= 0) adapter_id = toNumFromString(cfg->getString("adapter.id", "0x0")); // Fail if there is no valid adapter_id if (adapter_id <= 0) { log.fatal("Error: Adapter ID is not a valid number - quit! (ID = " + toStringFromLongHex(adapter_id) + ")"); return EXIT_FAILURE; } /* Print loaded modules */ log.information("Starting Adapter (ID: " + toStringFromLongHex(adapter_id) + ", FW_VERSION: " + FW_VERSION + ") with these modules:"); log.information(MOD_PAN + ": " + ((mod_pan) ? " ON" : "OFF")); log.information(MOD_PRESSURE_SENSOR + ": " + ((mod_pressure_sensor) ? " ON" : "OFF")); log.information(MOD_VIRTUAL_SENSOR + ": " + ((mod_virtual_sensor) ? " ON" : "OFF")); log.information(MOD_MQTT + ": " + ((mod_mqtt) ? " ON" : "OFF")); log.information(MOD_VPT_SENSOR + ": " + ((mod_vpt) ? " ON" : "OFF")); log.information(MOD_OPENHAB + ": " + ((mod_openhab) ? " ON" : "OFF")); srand(time(0)); /* Create default "header" for messages which are sent to server - these parameters are seldomly changed during runtime */ IOTMessage msg; msg.adapter_id = toStringFromLongHex(adapter_id); msg.fw_version = FW_VERSION; msg.protocol_version = cfg->getString("versions.protocol", "0.1"); msg.debug = false; msg.priority = MSG_PRIO_SENSOR; msg.valid = true; msg.offset = 0; msg.tt_version = 0; string IP_addr_out = cfg->getString("server.ip"); int port_out = cfg->getInt("server.port"); /* SSL stuff - Lukas Koszegy */ Poco::SharedPtr<PrivateKeyPassphraseHandler> pConsoleHandler = new KeyConsoleHandler(true); Poco::SharedPtr<InvalidCertificateHandler> pInvalidCertHandler = new ConsoleCertificateHandler(true); Context::Ptr pContext = NULL; try { pContext = new Context(Context::CLIENT_USE, cfg->getString("ssl.key", ""), cfg->getString("ssl.certificate", ""), cfg->getString("ssl.calocation", "./"), (Context::VerificationMode) cfg->getInt("ssl.verify_level", Context::VERIFY_RELAXED), 9, false, "ALL:ADH:!LOW:!EXP:!MD5:@STRENGTH"); } catch (Poco::Exception& ex) { log.fatal("Creating SSL failed! Please check cerficate file and configuration! (" + (string)ex.displayText() + ")"); return (EXIT_FAILURE); } SSLManager::instance().initializeClient(0, pInvalidCertHandler, pContext); initializeSSL(); /* Module initialization, start threads, wait in loop and test for termination of the app */ try { shared_ptr<MosqClient> mosq; shared_ptr<PanInterface> pan; shared_ptr<VPTSensor> vptsensor; shared_ptr<OpenHAB> hab; shared_ptr<PressureSensor> psm; shared_ptr<VirtualSensorModule> vsm; std::thread mq_t; if (mod_mqtt) { log.information("Starting MQTT module."); std::string mq_client_id = cfg_mqtt->getString("mqtt.client_id", "AdaApp"); std::string mq_main_topic = cfg_mqtt->getString("mqtt.main_topic", "BeeeOn/#"); std::string mq_host_addr = cfg_mqtt->getString("mqtt.host_addr", "localhost"); int mq_port = cfg_mqtt->getInt("mqtt.port", 1883); log.information("Starting Mosquitto Client."); mosq.reset(new MosqClient(mq_client_id, mq_main_topic, "AdaApp", mq_host_addr, mq_port)); mq_t = std::thread(mosq_thread, mosq); } /* Mandatory module for sending and receiving data */ shared_ptr<Aggregator> agg (new Aggregator(msg, mosq)); msg.state = "register"; msg.time = time(NULL); /* Mandatory component for receiving asynchronous messages from server */ shared_ptr<IOTReceiver> receiver (new IOTReceiver(agg, IP_addr_out, port_out, msg, adapter_id)); receiver->keepaliveInit(cfg); agg->setTCP(receiver); // BeeeOn PAN coordinator module if (mod_pan) { log.information("Creating PAN module."); pan.reset(new PanInterface(msg, agg)); pan->set_pan(pan); // XXX Function name should be same agg->setPAN(pan); } if (mod_vpt) { log.information("Creating VPT module."); vptsensor.reset(new VPTSensor(msg, agg, adapter_id)); agg->setVPT(vptsensor); } if (mod_openhab && mod_mqtt) { log.information("Creating OpenHAB module."); hab.reset(new OpenHAB(msg, agg)); agg->setHAB(hab); } if (mod_pressure_sensor) { log.information("Creating PressureSensors module."); psm.reset(new PressureSensor(msg, agg)); agg->setPSM(psm); } if (mod_virtual_sensor) { log.information("Creating VirtualSensors module."); vsm.reset(new VirtualSensorModule(msg, agg)); agg->setVSM(vsm); } agg_thread.start(*agg.get()); srv_thread.start(*receiver.get()); if (mod_vpt) { log.information("Starting VPT module."); vpt_thread.start(*vptsensor.get()); } if (mod_openhab && mod_mqtt) { log.information("Starting OpenHAB module."); hab_thread.start(*hab.get()); } if (mod_pressure_sensor) { log.information("Starting PressureSensors module."); psm.get()->start(); } if (mod_virtual_sensor) { log.information("Starting VirtualSensors module."); vsm_thread.start(*vsm.get()); } /* "Endless" loop waiting for SIGINT/SIGTERM */ while (!quit_global_flag) { sleep(1); } log.information("Stopping modules..."); if (mod_virtual_sensor) { log.information("Stopping Virtual Sensor module..."); vsm_thread.join(); } if (mod_pressure_sensor) { log.information("Stopping Pressure Sensor module..."); psm.get()->stop(); } if (mod_vpt) { log.information("Stopping VPT Sensor module..."); vpt_thread.join(); } if (mod_openhab && mod_mqtt) { log.information("Stopping OpenHAB module..."); hab_thread.join(); } if (mod_mqtt) { log.information("Stopping MQTT..."); mq_t.join(); } log.information("Stopping server..."); srv_thread.join(); log.information("Stopping aggregator..."); agg_thread.join(); uninitializeSSL(); } catch (Poco::Exception& ex) { log.fatal("Error: Poco exception!" + (string)ex.displayText()); return (EXIT_FAILURE); } catch (std::exception& ex) { log.fatal("Error: Standard expcetion!\n" + (string)ex.what()); return (EXIT_FAILURE); } log.information("Adapter finished"); return 0; }