PolyObject.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. Copyright (C) 2011 by Ivan Safrin
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #include "PolyObject.h"
  20. #include "tinyxml.h"
  21. #include <sstream>
  22. #include <stdio.h>
  23. #include <string.h>
  24. using namespace Polycode;
  25. ObjectEntry::ObjectEntry() :
  26. type(UNKNOWN_ENTRY),
  27. NumberVal(0.0),
  28. length(0),
  29. intVal(0)
  30. {
  31. }
  32. ObjectEntry::~ObjectEntry() {
  33. for(int i=0; i < children.size(); i++) {
  34. delete children[i];
  35. }
  36. }
  37. void ObjectEntry::Clear() {
  38. for(int i=0; i < children.size(); i++) {
  39. children[i]->Clear();
  40. delete children[i];
  41. }
  42. children.clear();
  43. }
  44. String ObjectEntry::getTypedName() const {
  45. const String _name = name.size() > 0 ? name : String("nil");
  46. if (type == ObjectEntry::ARRAY_ENTRY)
  47. return String("polyarray:") + _name;
  48. if (type == ObjectEntry::STRING_ENTRY && stringVal.size() == 0)
  49. return String("polystring:") + _name;
  50. // TODO: In interest of consistency, make sure that STRING_ENTRYs stay STRING_ENTRYs (etc) if they're ambiguous (i.e. contain numbers)
  51. return _name;
  52. }
  53. void ObjectEntry::setTypedName(const String &str) {
  54. size_t firstColon = str.find(":");
  55. // Note: This will split up a:b:c as having type "a" and name "b:c". Is this appropriate?
  56. if (firstColon == -1) {
  57. name = str;
  58. } else { // There was a namespace
  59. name = str.substr(firstColon+1);
  60. String sty = str.substr(0,firstColon);
  61. if (sty == "polyfloat")
  62. type = ObjectEntry::FLOAT_ENTRY;
  63. else if (sty == "polyint")
  64. type = ObjectEntry::INT_ENTRY;
  65. else if (sty == "polybool")
  66. type = ObjectEntry::BOOL_ENTRY;
  67. else if (sty == "polyarray")
  68. type = ObjectEntry::ARRAY_ENTRY;
  69. else if (sty == "polystring")
  70. type = ObjectEntry::STRING_ENTRY;
  71. else if (sty == "polycontainer")
  72. type = ObjectEntry::CONTAINER_ENTRY;
  73. }
  74. if (name == "nil")
  75. name.contents.clear();
  76. }
  77. Object::Object() {
  78. }
  79. Object::~Object() {
  80. }
  81. void Object::saveToXML(const String& fileName) {
  82. TiXmlDocument doc;
  83. TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  84. doc.LinkEndChild( decl );
  85. TiXmlElement * rootElement = createElementFromObjectEntry(&root);
  86. doc.LinkEndChild(rootElement);
  87. doc.SaveFile(fileName.c_str());
  88. }
  89. TiXmlElement *Object::createElementFromObjectEntry(ObjectEntry *entry) {
  90. TiXmlElement *newElement = new TiXmlElement(entry->getTypedName().c_str());
  91. switch(entry->type) {
  92. case ObjectEntry::BOOL_ENTRY: {
  93. newElement->LinkEndChild(new TiXmlText( entry->boolVal ? "true" : "false" ));
  94. } break;
  95. case ObjectEntry::FLOAT_ENTRY: case ObjectEntry::INT_ENTRY: {
  96. std::ostringstream o;
  97. if (entry->type == ObjectEntry::FLOAT_ENTRY)
  98. o << entry->NumberVal;
  99. else
  100. o << entry->intVal;
  101. newElement->LinkEndChild(new TiXmlText( o.str().c_str() ));
  102. } break;
  103. case ObjectEntry::STRING_ENTRY: {
  104. newElement->LinkEndChild(new TiXmlText( entry->stringVal.c_str() ));
  105. } break;
  106. }
  107. for(int i=0; i < entry->children.size(); i++) {
  108. ObjectEntry *childEntry = entry->children[i];
  109. bool needLinkChild = (childEntry->children.size() > 0) || (entry->type == ObjectEntry::ARRAY_ENTRY);
  110. if (!needLinkChild) {
  111. const String &childTypedName = childEntry->getTypedName();
  112. switch(childEntry->type) {
  113. case ObjectEntry::BOOL_ENTRY:
  114. if(childEntry->boolVal)
  115. newElement->SetAttribute(childTypedName.c_str(), "true");
  116. else
  117. newElement->SetAttribute(childTypedName.c_str(), "false");
  118. break;
  119. case ObjectEntry::FLOAT_ENTRY: {
  120. std::ostringstream o; // Avoid NumberToString, it truncates
  121. o << std::fixed;
  122. o << childEntry->NumberVal;
  123. newElement->SetAttribute(childTypedName.c_str(), o.str().c_str());
  124. } break;
  125. case ObjectEntry::INT_ENTRY:
  126. newElement->SetAttribute(childTypedName.c_str(), childEntry->intVal);
  127. break;
  128. case ObjectEntry::STRING_ENTRY:
  129. {
  130. newElement->SetAttribute(childTypedName.c_str(), childEntry->stringVal.c_str());
  131. } break;
  132. default:
  133. needLinkChild = true;
  134. break;
  135. }
  136. }
  137. if (needLinkChild) {
  138. TiXmlElement *childElement = createElementFromObjectEntry(childEntry);
  139. newElement->LinkEndChild(childElement);
  140. }
  141. }
  142. return newElement;
  143. }
  144. bool Object::loadFromXMLString(const String &xmlString) {
  145. if(xmlString.length() < 2) {
  146. return false;
  147. }
  148. TiXmlDocument doc;
  149. doc.Parse((const char*)xmlString.c_str(), 0, TIXML_ENCODING_UTF8);
  150. if(doc.Error()) {
  151. Logger::log("Error loading xml string: %s\n", doc.ErrorDesc());
  152. return false;
  153. }
  154. TiXmlElement *rootElement = doc.RootElement();
  155. createFromXMLElement(rootElement, &root);
  156. return true;
  157. }
  158. bool Object::loadFromXML(const String& fileName) {
  159. TiXmlDocument doc(fileName.c_str());
  160. doc.LoadFile();
  161. if(doc.Error()) {
  162. Logger::log("Error loading xml file: %s\n", doc.ErrorDesc());
  163. return false;
  164. }
  165. TiXmlElement *rootElement = doc.RootElement();
  166. createFromXMLElement(rootElement, &root);
  167. return true;
  168. }
  169. void Object::createFromXMLElement(TiXmlElement *element, ObjectEntry *entry) {
  170. entry->type = ObjectEntry::CONTAINER_ENTRY;
  171. int ival;
  172. double dval;
  173. // run through the attributes
  174. TiXmlAttribute* pAttrib=element->FirstAttribute();
  175. int i=0;
  176. while (pAttrib)
  177. {
  178. ObjectEntry *newEntry = new ObjectEntry();
  179. newEntry->type = ObjectEntry::STRING_ENTRY;
  180. newEntry->stringVal = pAttrib->Value();
  181. if (newEntry->stringVal.find(".") == -1 && pAttrib->QueryIntValue(&ival)==TIXML_SUCCESS) {
  182. newEntry->intVal = ival;
  183. newEntry->NumberVal = (Number)ival;
  184. newEntry->type = ObjectEntry::INT_ENTRY;
  185. } else if (pAttrib->QueryDoubleValue(&dval)==TIXML_SUCCESS) {
  186. newEntry->NumberVal = dval;
  187. newEntry->intVal = dval;
  188. newEntry->type = ObjectEntry::FLOAT_ENTRY;
  189. }
  190. if(newEntry->stringVal == "true") {
  191. newEntry->boolVal = true;
  192. newEntry->intVal = 1;
  193. newEntry->NumberVal = 1;
  194. newEntry->type = ObjectEntry::BOOL_ENTRY;
  195. }
  196. if(newEntry->stringVal == "false") {
  197. newEntry->boolVal = false;
  198. newEntry->intVal = 0;
  199. newEntry->NumberVal = 0;
  200. newEntry->type = ObjectEntry::BOOL_ENTRY;
  201. }
  202. newEntry->setTypedName(pAttrib->Name()); // Set name last because we might override type
  203. entry->children.push_back(newEntry);
  204. i++;
  205. pAttrib=pAttrib->Next();
  206. }
  207. // check if has a value
  208. if(element->GetText()) {
  209. entry->stringVal = element->GetText();
  210. entry->type = ObjectEntry::STRING_ENTRY;
  211. const char *rawVal = entry->stringVal.c_str();
  212. char *endResult = NULL; const char *success = rawVal + entry->stringVal.size();
  213. entry->intVal = strtol(rawVal, &endResult, 10);
  214. if (endResult == success) { // If integer part exhausts string
  215. entry->type = ObjectEntry::INT_ENTRY;
  216. entry->NumberVal = entry->intVal;
  217. entry->boolVal = entry->intVal != 0;
  218. } else {
  219. entry->NumberVal = strtod(rawVal, &endResult);
  220. entry->intVal = entry->NumberVal;
  221. entry->boolVal = entry->NumberVal != 0.0;
  222. if (endResult == success) {
  223. entry->type = ObjectEntry::FLOAT_ENTRY;
  224. }
  225. }
  226. if(entry->stringVal == "true") {
  227. entry->boolVal = true;
  228. entry->type = ObjectEntry::BOOL_ENTRY;
  229. }
  230. if(entry->stringVal == "false") {
  231. entry->boolVal = false;
  232. entry->type = ObjectEntry::BOOL_ENTRY;
  233. }
  234. } else {
  235. // then through the children
  236. TiXmlNode* pChild;
  237. String lastName = "";
  238. int count = 0;
  239. for (pChild = element->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
  240. TiXmlElement *pChildElement = pChild->ToElement();
  241. if (!pChildElement) continue; // Skip comment nodes
  242. ObjectEntry *newEntry = new ObjectEntry();
  243. createFromXMLElement(pChildElement, newEntry);
  244. entry->children.push_back(newEntry);
  245. if(newEntry->name == lastName) { // Keys cannot repeat in a CONTAINER
  246. entry->type = ObjectEntry::ARRAY_ENTRY;
  247. }
  248. lastName = newEntry->name;
  249. count++;
  250. }
  251. entry->length = count;
  252. }
  253. entry->setTypedName(element->Value()); // Set name last because we might override type
  254. }
  255. bool Object::loadFromBinary(const String& fileName) {
  256. BinaryObjectReader objectReader(fileName, this);
  257. bool success = objectReader.success;
  258. return success;
  259. }
  260. BinaryObjectReader::BinaryObjectReader(const String& fileName, Object *object) {
  261. this->object = object;
  262. success = false;
  263. inFile = OSBasics::open(fileName, "rb");
  264. if(inFile) {
  265. success = readFile();
  266. OSBasics::close(inFile);
  267. }
  268. }
  269. String BinaryObjectReader::getKeyByIndex(unsigned int index) {
  270. if(index < keys.size()) {
  271. return keys[index];
  272. } else {
  273. return "nil";
  274. }
  275. }
  276. bool BinaryObjectReader::parseEntryFromFile(ObjectEntry *entry) {
  277. uint16_t keyIndex;
  278. OSBasics::read(&keyIndex, sizeof(uint16_t), 1, inFile);
  279. entry->name = getKeyByIndex(keyIndex);
  280. uint8_t type;
  281. OSBasics::read(&type, sizeof(uint8_t), 1, inFile);
  282. entry->type = type;
  283. // printf("Loading %s of type %u\n", entry->name.c_str(), entry->type);
  284. uint32_t data32;
  285. switch(entry->type) {
  286. case ObjectEntry::STRING_ENTRY:
  287. {
  288. OSBasics::read(&data32, sizeof(uint32_t), 1, inFile);
  289. char *buffer = (char*) malloc(data32 + 1);
  290. OSBasics::read(buffer, 1, data32, inFile);
  291. buffer[data32] = '\0';
  292. entry->stringVal = String(buffer);
  293. free(buffer);
  294. }
  295. break;
  296. case ObjectEntry::FLOAT_ENTRY:
  297. {
  298. float val;
  299. OSBasics::read(&val, sizeof(uint32_t), 1, inFile);
  300. entry->intVal = val;
  301. entry->NumberVal = val;
  302. }
  303. break;
  304. case ObjectEntry::INT_ENTRY:
  305. {
  306. int32_t intval;
  307. OSBasics::read(&intval, sizeof(int32_t), 1, inFile);
  308. entry->intVal = intval;
  309. entry->NumberVal = intval;
  310. }
  311. break;
  312. case ObjectEntry::BOOL_ENTRY:
  313. {
  314. OSBasics::read(&data32, sizeof(uint32_t), 1, inFile);
  315. if(data32 == 0) {
  316. entry->boolVal = false;
  317. entry->intVal = data32;
  318. entry->NumberVal = data32;
  319. } else {
  320. entry->boolVal = true;
  321. entry->NumberVal = data32;
  322. }
  323. }
  324. break;
  325. default:
  326. OSBasics::read(&data32, sizeof(uint32_t), 1, inFile);
  327. break;
  328. }
  329. OSBasics::read(&data32, sizeof(uint32_t), 1, inFile);
  330. bool retVal = true;
  331. // if(data32 > 0){
  332. // printf("Loading %u children\n", data32);
  333. // }
  334. for(int i=0; i < data32; i++) {
  335. ObjectEntry *childEntry = entry->addChild("nil");
  336. retVal = parseEntryFromFile(childEntry);
  337. }
  338. return retVal;
  339. }
  340. bool BinaryObjectReader::readFile() {
  341. char header[5];
  342. OSBasics::read(header, 1, 4, inFile);
  343. header[4] = '\0';
  344. // printf("HEADER: [%s]\n", header);
  345. if(String(header) != "PBOF") {
  346. return false;
  347. }
  348. uint32_t data32;
  349. OSBasics::read(&data32, sizeof(uint32_t), 1, inFile);
  350. for(int i=0; i < data32; i++) {
  351. uint16_t data16;
  352. OSBasics::read(&data16, sizeof(uint16_t), 1, inFile);
  353. char *buffer = (char*)malloc(data16+1);
  354. OSBasics::read(buffer, 1, data16, inFile);
  355. buffer[data16] = '\0';
  356. keys.push_back(String(buffer));
  357. free(buffer);
  358. }
  359. OSBasics::read(&data32, sizeof(uint32_t), 1, inFile);
  360. return parseEntryFromFile(&object->root);
  361. }
  362. BinaryObjectReader::~BinaryObjectReader() {
  363. }
  364. void Object::saveToBinary(const String& fileName) {
  365. BinaryObjectWriter objectWriter(this);
  366. objectWriter.writeToFile(fileName);
  367. }
  368. BinaryObjectWriter::BinaryObjectWriter(Object *object) {
  369. this->object = object;
  370. parseKeysFromObjectEntry(&object->root);
  371. }
  372. unsigned int BinaryObjectWriter::addKey(const String &key) {
  373. for(int i=0; i < keys.size(); i++) {
  374. if(keys[i] == key)
  375. return i;
  376. }
  377. keys.push_back(key);
  378. return keys.size()-1;
  379. }
  380. unsigned int BinaryObjectWriter::getKeyIndex(const String &key) {
  381. for(int i=0; i < keys.size(); i++) {
  382. if(keys[i] == key)
  383. return i;
  384. }
  385. return 0;
  386. }
  387. void BinaryObjectWriter::parseKeysFromObjectEntry(ObjectEntry *entry) {
  388. addKey(entry->name);
  389. for(int i=0; i < entry->children.size(); i++) {
  390. parseKeysFromObjectEntry(entry->children[i]);
  391. }
  392. }
  393. BinaryObjectWriter::~BinaryObjectWriter() {
  394. }
  395. void BinaryObjectWriter::writeEntryToFile(ObjectEntry *entry) {
  396. uint16_t keyIndex = getKeyIndex(entry->name);
  397. OSBasics::write(&keyIndex, sizeof(uint16_t), 1, outFile);
  398. uint8_t type = (uint8_t)entry->type;
  399. OSBasics::write(&type, sizeof(uint8_t), 1, outFile);
  400. uint32_t data32;
  401. switch(entry->type) {
  402. case ObjectEntry::STRING_ENTRY:
  403. data32 = entry->stringVal.length();
  404. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  405. OSBasics::write(entry->stringVal.c_str(), 1, data32, outFile);
  406. break;
  407. case ObjectEntry::FLOAT_ENTRY:
  408. {
  409. float val = (float)entry->NumberVal;
  410. OSBasics::write(&val, sizeof(uint32_t), 1, outFile);
  411. }
  412. break;
  413. case ObjectEntry::INT_ENTRY:
  414. {
  415. int32_t intval = (int32_t)entry->intVal;
  416. OSBasics::write(&intval, sizeof(int32_t), 1, outFile);
  417. }
  418. break;
  419. case ObjectEntry::BOOL_ENTRY:
  420. if(entry->boolVal) {
  421. data32 = 1;
  422. } else {
  423. data32 = 0;
  424. }
  425. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  426. break;
  427. default:
  428. data32 = 0;
  429. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  430. break;
  431. }
  432. data32 = entry->children.size();
  433. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  434. for(int i=0; i < entry->children.size(); i++) {
  435. writeEntryToFile(entry->children[i]);
  436. }
  437. numEntriesWritten++;
  438. }
  439. bool BinaryObjectWriter::writeToFile(const String& fileName) {
  440. outFile = OSBasics::open(fileName, "wb");
  441. OSBasics::write("PBOF", 1, 4, outFile);
  442. uint32_t data32 = keys.size();
  443. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  444. for(int i=0; i < keys.size(); i++) {
  445. uint16_t data16 = keys[i].length();
  446. OSBasics::write(&data16, sizeof(uint16_t), 1, outFile);
  447. OSBasics::write(keys[i].c_str(), 1, data16, outFile);
  448. }
  449. size_t offset = OSBasics::tell(outFile);
  450. numEntriesWritten = 0;
  451. data32 = 0;
  452. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  453. writeEntryToFile(&object->root);
  454. OSBasics::seek(outFile, offset, SEEK_SET);
  455. data32 = numEntriesWritten;
  456. OSBasics::write(&data32, sizeof(uint32_t), 1, outFile);
  457. OSBasics::close(outFile);
  458. return true;
  459. }