Parser.cpp 27.2 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1
/*
Craig Watson's avatar
Craig Watson committed
2 3
 * Copyright (C) 2015-2016 Département de l'Instruction Publique (DIP-SEM)
 *
Claudio Valerio's avatar
Claudio Valerio committed
4
 * Copyright (C) 2013 Open Education Foundation
Claudio Valerio's avatar
Claudio Valerio committed
5
 *
Claudio Valerio's avatar
Claudio Valerio committed
6 7
 * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
 * l'Education Numérique en Afrique (GIP ENA)
8
 *
Claudio Valerio's avatar
Claudio Valerio committed
9 10 11
 * This file is part of OpenBoard.
 *
 * OpenBoard is free software: you can redistribute it and/or modify
Claudio Valerio's avatar
Claudio Valerio committed
12 13
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License,
14 15 16 17
 * with a specific linking exception for the OpenSSL project's
 * "OpenSSL" library (or with modified versions of it that use the
 * same license as the "OpenSSL" library).
 *
Claudio Valerio's avatar
Claudio Valerio committed
18
 * OpenBoard is distributed in the hope that it will be useful,
Claudio Valerio's avatar
Claudio Valerio committed
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Claudio Valerio's avatar
Claudio Valerio committed
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Claudio Valerio's avatar
Claudio Valerio committed
21
 * GNU General Public License for more details.
Claudio Valerio's avatar
Claudio Valerio committed
22
 *
Claudio Valerio's avatar
Claudio Valerio committed
23
 * You should have received a copy of the GNU General Public License
Claudio Valerio's avatar
Claudio Valerio committed
24
 * along with OpenBoard. If not, see <http://www.gnu.org/licenses/>.
Claudio Valerio's avatar
Claudio Valerio committed
25
 */
26

27

Claudio Valerio's avatar
Claudio Valerio committed
28

Claudio Valerio's avatar
Claudio Valerio committed
29

30
#include <QtGlobal>
Claudio Valerio's avatar
Claudio Valerio committed
31 32 33 34 35 36 37 38 39 40 41
#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <string.h>
#include "Parser.h"
#include "Object.h"
#include "Exception.h"
#include "Utils.h"

42 43
#include "core/memcheck.h"

Claudio Valerio's avatar
Claudio Valerio committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
using namespace merge_lib;
using namespace std;

const std::string Parser::WHITESPACES(" \t\f\v\n\r");
const std::string Parser::DELIMETERS("()<>{}/%][");
const std::string Parser::NUMBERS("0123456789");
const std::string Parser::WHITESPACES_AND_DELIMETERS = Parser::WHITESPACES + Parser::DELIMETERS;

Document * Parser::parseDocument(const char * fileName)
{
   _document = new Document(fileName);
   try
   {
      _createObjectTree(fileName);
      _createDocument(fileName);
   }
   catch( std::exception &)
   {
      _clearParser();
      delete _document;
      _document = NULL;
      throw;
   }
   return _document;
}

void Parser::_retrieveAllPages(Object * objectWithKids)
{
   std::string & objectContent = objectWithKids->getObjectContent();
   unsigned int startOfKids = objectContent.find("/Kids");
   unsigned int endOfKids = objectContent.find("]", startOfKids);
   if(
76 77
      ((int)startOfKids == -1) &&
      ((int)objectContent.find("/Page") != -1)
Claudio Valerio's avatar
Claudio Valerio committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
      )
   {
      unsigned int numberOfPages = _document->_pages.size() + 1;
      Page * newPage = new Page(numberOfPages);     
      newPage->_root = objectWithKids;
      _document->_pages.insert(std::pair<unsigned int, Page *>(numberOfPages, newPage));
      return;
   }

   const std::vector<Object *> & kids = objectWithKids->getSortedByPositionChildren(startOfKids, endOfKids);
   for(size_t i(0); i < kids.size(); ++i)
   {
      _retrieveAllPages(kids[i]);
   }
}

void Parser::_createDocument(const char * docName)
{
96
    Q_UNUSED(docName);
Claudio Valerio's avatar
Claudio Valerio committed
97 98 99
   _document->_root = _root;
   std::string & rootContent = _root->getObjectContent();
   unsigned int startOfPages = rootContent.find("/Pages");
100
   if((int)startOfPages == -1)
Claudio Valerio's avatar
Claudio Valerio committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
      throw Exception("Some document is wrong");
   unsigned int endOfPages = rootContent.find("R", startOfPages);
   std::vector<Object *> objectWithKids = _root->getChildrenByBounds(startOfPages, endOfPages);
   if(objectWithKids.size() != 1)
      throw Exception("Some document is wrong");
   _retrieveAllPages(objectWithKids[0]);

   _root->retrieveMaxObjectNumber(_document->_maxObjectNumber);
   _clearParser();
}

void Parser::_clearParser()
{
   _root = 0;
   _fileContent.clear();
   _fileContent.reserve();
   _objects.clear();
}


void Parser::_getFileContent(const char * fileName)
{
   ifstream pdfFile;
   pdfFile.open (fileName, ios::binary );
   if (pdfFile.fail())
   {
      stringstream errorMessage("File ");
      errorMessage << fileName << " is absent" << "\0";
      throw Exception(errorMessage);
   }
   // get length of file:
   pdfFile.seekg (0, ios::end);
   int length = pdfFile.tellg();
   pdfFile.seekg (0, ios::beg);
   _fileContent.resize(length);
   pdfFile.read(&_fileContent[0], length);

   // check version
   const char *header = "%PDF-1.";
   size_t verPos = _fileContent.find(header);
   if( verPos == 0 )
   {
      verPos += strlen(header);
      char ver = _fileContent[verPos];
      if( ver < '0' || ver > '4' )
      {
         stringstream errorMsg;
         errorMsg<<" File with verion 1."<<ver<<" is not currently supported by merge library\n";
         throw Exception(errorMsg);
      }
   }
   else
   {
      throw Exception("Unrecognized header of PDF file");
   }
   pdfFile.close();
}


void Parser::_createObjectTree(const char * fileName)
{
   unsigned int rootObjectNumber = 0;
   try
   {
      _getFileContent(fileName);
      _readXRefAndCreateObjects();
      rootObjectNumber = _readTrailerAndReturnRoot();
   }
   catch (std::exception &)
   {
      std::map<unsigned int, Object *>::const_iterator it(_objects.begin());
      for(;it != _objects.end();it++)
      {
         delete (*it).second;
      }
      _objects.clear();
      throw;
   }

   std::map<unsigned int, Object *>::iterator objectsIterator;

   for ( objectsIterator = _objects.begin() ; objectsIterator != _objects.end(); objectsIterator++ )
   {
      Object * currentObject = (*objectsIterator).second;
      _document->_allObjects.push_back(currentObject);
      //key - object number :  value - positions in object content of this reference
      const std::map<unsigned int, Object::ReferencePositionsInContent> & refs = 
         _getReferences(currentObject->getObjectContent());      
      std::map<unsigned int, Object::ReferencePositionsInContent>::const_iterator refsIterator = refs.begin();
      for(; refsIterator !=  refs.end(); ++refsIterator)
      {        
         if(_objects.count((*refsIterator).first))
Claudio Valerio's avatar
Claudio Valerio committed
193
            currentObject->addChild(_objects[(*refsIterator).first], (*refsIterator).second);        
Claudio Valerio's avatar
Claudio Valerio committed
194 195 196 197 198 199 200 201 202 203 204 205
      }
   }   
   _root = _objects[rootObjectNumber];

}

const std::map<unsigned int, Object::ReferencePositionsInContent> & Parser::_getReferences(const std::string & objectContent)
{
   unsigned int currentPosition(0), startOfNextSearch(0);
   static std::map<unsigned int, std::vector<unsigned int> >  searchResult;
   searchResult.clear();
   unsigned int streamStart = objectContent.find("stream");
206
   if((int)streamStart == -1)
Claudio Valerio's avatar
Claudio Valerio committed
207 208 209 210 211 212
      streamStart = objectContent.size();
   while(startOfNextSearch < streamStart)
   {
      //try to find reference. reference example is 15 0 R
      startOfNextSearch = objectContent.find(" R", startOfNextSearch);
      currentPosition = startOfNextSearch;
213
      if((int)currentPosition != -1)
Claudio Valerio's avatar
Claudio Valerio committed
214 215 216
      {         
         //check that next character of " R" is WHITESPACE. 

217 218
         if(((int)WHITESPACES.find(objectContent[currentPosition + 2]) == -1) &&
            ((int)DELIMETERS.find(objectContent[currentPosition + 2]) == -1)
Claudio Valerio's avatar
Claudio Valerio committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
            )
         {
            //this is not reference. this is something looks like "0 0 0 RG"
            ++startOfNextSearch;
            continue;
         }
         //get previos symbol and check that it is a number
         unsigned int numberSearchCounter = _skipNumber(objectContent, --currentPosition);

         //previos symbol is not a number
         if(numberSearchCounter == currentPosition)
         {
            ++startOfNextSearch;
            continue;
         }
         else
         {
            currentPosition = numberSearchCounter;
         }

         bool isFound(false);
         //previos symbols should be whitespaces
         while((objectContent[currentPosition] == ' ') && --currentPosition) 
         {
            isFound = true;
         }

         //previos symbol is not a whitespace
         if(!isFound)
         {
            ++startOfNextSearch;
            continue;
         }
         //check that this and may be previos symbols are a numbers     
         numberSearchCounter = _skipNumber(objectContent, currentPosition);
         if(numberSearchCounter == currentPosition)
         {
            ++startOfNextSearch;
            continue;
         }
         unsigned int objectNumber = Utils::stringToInt(objectContent.substr(numberSearchCounter + 1, currentPosition - numberSearchCounter));

         searchResult[objectNumber].push_back(numberSearchCounter + 1);


         ++startOfNextSearch;

      }
      else
         break;      
   }
   return searchResult;
}

unsigned int Parser::_skipNumber(const std::string & str, unsigned int currentPosition)
{
   unsigned int numberSearchCounter = currentPosition;    
276
   while(((int)NUMBERS.find(str[numberSearchCounter]) != -1) && --numberSearchCounter)
Claudio Valerio's avatar
Claudio Valerio committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
   {}

   return numberSearchCounter;
}
void Parser::_readXRefAndCreateObjects()
{      
   unsigned int currentPostion = _getStartOfXrefWithRoot();
   do
   {
      const std::string & currentToken = _getNextToken(currentPostion);
      if(currentToken != "xref")
      {
         throw Exception("Wrong xref in some document");
      }
      unsigned int endOfLine = _getEndOfLineFromContent(currentPostion );
      if(_countTokens(currentPostion, endOfLine) != 2)
      {
         throw Exception("Wrong xref in some document");

      }
      //now we are reading the xref
      while(1)
      {
300
         Utils::stringToInt(_getNextToken(currentPostion));
Claudio Valerio's avatar
Claudio Valerio committed
301 302 303 304 305 306 307 308
         unsigned int objectCount = Utils::stringToInt(_getNextToken(currentPostion));
         for(unsigned int i(0); i < objectCount; i++)
         {
            unsigned long  first;

            if(_countTokens(currentPostion, _getEndOfLineFromContent(currentPostion)) == 3)
            {
               first  = Utils::stringToInt(_getNextToken(currentPostion));
309
               Utils::stringToInt(_getNextToken(currentPostion));
Claudio Valerio's avatar
Claudio Valerio committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
               const string & use         = _getNextToken(currentPostion);
               if(!use.compare("n"))
               {
                  unsigned int objectNumber;

                  try               
                  {
                     std::pair<unsigned int, unsigned int> streamBounds;
                     bool hasObjectStream;
                     unsigned int generationNumber;
                     const std::string content = _getObjectContent(first, objectNumber, generationNumber, streamBounds, hasObjectStream);
                     if(!_objects.count(objectNumber))
                     {
                        Object * newObject = new Object(objectNumber, generationNumber, content, _document->_documentName ,streamBounds, hasObjectStream);
                        _objects[objectNumber] = newObject;
                     }
                  }
                  catch(std::exception &)
                  {
                  }

               }
            }
            else
            {
               ;
            }
            ++currentPostion;


         }
         unsigned int previosPostion = currentPostion;
         const std::string & isTrailer = _getNextToken(currentPostion);

         std::string trailer("trailer");
         if(isTrailer == trailer)
         {
            currentPostion -= trailer.size();
            break;
         }
         else
            currentPostion = previosPostion;

      }
   }
   while(_readTrailerAndRterievePrev(currentPostion, currentPostion));


}

unsigned int Parser::_getStartOfXrefWithRoot()
{
   unsigned int leftBoundOfStartOfXref = _fileContent.rfind("startxref");
   leftBoundOfStartOfXref = _fileContent.find_first_of(NUMBERS, leftBoundOfStartOfXref);

   unsigned int rightBoundOfStartOfXref = _fileContent.find_first_not_of(NUMBERS, leftBoundOfStartOfXref + 1);

   std::string  startOfXref = _fileContent.substr(leftBoundOfStartOfXref, rightBoundOfStartOfXref - leftBoundOfStartOfXref);
   int integerStartOfXref = Utils::stringToInt(startOfXref);
   return integerStartOfXref;
}

unsigned int Parser::_getEndOfLineFromContent(unsigned int fromPosition)
{
   fromPosition = _skipWhiteSpacesFromContent(fromPosition);
   unsigned int endOfLine = _fileContent.find_first_of("\n\r", fromPosition);
   endOfLine = _fileContent.find_last_of("\n\r", endOfLine);
   return endOfLine;

}

const std::pair<unsigned int, unsigned int> & Parser::_getLineBounds(const std::string & str, unsigned int fromPosition)
{
   static std::pair<unsigned int, unsigned int> bounds;
   bounds.first = str.rfind('\n', fromPosition);
385
   if((int)bounds.first == -1)
Claudio Valerio's avatar
Claudio Valerio committed
386 387
      bounds.first = 0;
   bounds.second = str.find('\n', fromPosition);
388
   if((int)bounds.second == -1)
Claudio Valerio's avatar
Claudio Valerio committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
      bounds.second = str.size();    
   return bounds;
}

const std::string & Parser::_getNextToken(unsigned int & fromPosition)
{
   fromPosition = _skipWhiteSpacesFromContent(fromPosition);
   unsigned int position = _fileContent.find_first_of(WHITESPACES, fromPosition);

   static std::string token;
   if(position > fromPosition)
   {        
      unsigned int tokenSize = position - fromPosition;
      token.resize(tokenSize);
      memcpy(&token[0], &_fileContent[fromPosition], tokenSize);
      fromPosition = position;
      return token;
   }
   else
   {
      //TODO throw exception
   }
   token = "";
   return token;
}

unsigned int Parser::_countTokens(unsigned int leftBound, unsigned int rightBount)
{
   unsigned int position = _skipWhiteSpacesFromContent(leftBound);
   unsigned int tokensCount = 0;

   while (position < rightBount)
   {
      position = _fileContent.find_first_of(WHITESPACES, position);
423
      if ((int)position != -1)
Claudio Valerio's avatar
Claudio Valerio committed
424 425 426 427 428 429 430 431 432 433
         ++tokensCount;
      //start search from next symbol
      ++position;
   }
   return tokensCount;
}

unsigned int Parser::_skipWhiteSpaces(const std::string & str, unsigned int fromPosition)
{
   unsigned int position = fromPosition;
434
   if((int)WHITESPACES.find(str[0]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
435 436 437 438 439 440 441
      position = str.find_first_not_of(WHITESPACES, position);
   return position;
}

unsigned int Parser::_skipWhiteSpacesFromContent(unsigned int fromPosition)
{
   unsigned int position = fromPosition;
442
   if((int)WHITESPACES.find(_fileContent[position]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
      position = _fileContent.find_first_not_of(WHITESPACES, position);// + 1;

   return position;
}

const std::string & Parser::_getObjectContent(unsigned int objectPosition, unsigned int & objectNumber, unsigned int & generationNumber, std::pair<unsigned int, unsigned int> & streamBounds, bool & hasObjectStream)
{
   hasObjectStream = false;
   unsigned int currentPosition = objectPosition;

   std::string token = _getNextToken(currentPosition);  // number of object
   objectNumber = Utils::stringToInt(token);

   token = _getNextToken(currentPosition);  // generation number - not interesting
   generationNumber = Utils::stringToInt(token);

   token = Parser::getNextToken(_fileContent,currentPosition);

   if( token != "obj" )
   {
      std::stringstream strOut;
      strOut<<"Wrong object in PDF, in position "<<currentPosition<<" cannot continue!\n";
      throw Exception(strOut.str());
   }

   static std::string objectContent;

   size_t contentStart = _fileContent.find_first_not_of(Parser::WHITESPACES,currentPosition);
471
   if((int) contentStart == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
472 473 474 475 476 477 478
   {
      std::stringstream strOut;
      strOut<<"Wrong object "<< objectNumber<< "in PDF, cannot find content for it\n";
      throw Exception(strOut.str());
   }
   currentPosition = contentStart;
   unsigned int endOfContent = _fileContent.find("endobj", contentStart);
479
   if((int) endOfContent == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
480 481 482 483 484
   {
      stringstream errorMessage("Corrupted PDF file, obj does not have matching endobj");
      throw Exception(errorMessage);
   }
   unsigned int endOfStream = _fileContent.find("endstream", currentPosition);
485
   if(((int)endOfStream != -1) && (endOfStream < endOfContent))
Claudio Valerio's avatar
Claudio Valerio committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
   {
      std::string stream("stream");
      unsigned int beginOfStream = _fileContent.find(stream, currentPosition) + stream.size();
      while(_fileContent[beginOfStream] == '\r')
      {
         ++beginOfStream;
      }
      if( _fileContent[beginOfStream] == '\n')
      {
         ++beginOfStream;
      }
      streamBounds.first = beginOfStream;

      // try to use Length field to determine end of stream.
      std::string lengthToken = "/Length";
      size_t lengthBegin = Parser::findTokenName(_fileContent,lengthToken,contentStart);
502
      if ((int) lengthBegin != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
      {
         std::string lengthStr;
         size_t lenPos = lengthBegin + lengthToken.size();
         bool useContentLength = false;
         if( Parser::getNextWord(lengthStr,_fileContent,lenPos) )
         {
            useContentLength = true;
            std::string refStr;
            if( Parser::getNextWord(refStr,_fileContent,lenPos))
            {
               if( Parser::getNextWord(refStr,_fileContent,lenPos))
               {
                  if( refStr == "R" )
                  {
                     useContentLength = false;
                     //it is reference
                  }
               }
            }
         }
         if( useContentLength )
         {
            std::stringstream strin(lengthStr);
            unsigned int streamEnd = 0;
            strin>>streamEnd;
            streamEnd += beginOfStream;
            unsigned int streamEndBegin = _fileContent.find("endstream",streamEnd);
530
            if((int) streamEndBegin != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
            {
               endOfStream = streamEndBegin;
            }
         }
      }
      streamBounds.second = endOfStream;
      endOfContent = beginOfStream;
      hasObjectStream = true;

   }
   unsigned int contentSize = endOfContent - currentPosition;

   objectContent.resize(contentSize);
   memcpy(&objectContent[0], &_fileContent[currentPosition], contentSize);
   return objectContent;

}

unsigned int Parser::_readTrailerAndReturnRoot()
{

   unsigned int startOfTrailer = Parser::findToken(_fileContent,"trailer", _getStartOfXrefWithRoot());
   std::string rootStr("/Root");
   unsigned int startOfRoot = Parser::findToken(_fileContent,rootStr.data(), startOfTrailer);
555
   if((int) startOfRoot == -1)
Claudio Valerio's avatar
Claudio Valerio committed
556 557 558 559
   {
      throw Exception("Cannot find Root object !");
   }
   std::string encryptStr("/Encrypt");
560
   if((int) Parser::findToken(_fileContent,encryptStr,startOfTrailer) != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
561 562 563 564 565
   {
      throw Exception("Encrypted PDF is not supported!");
   }
   startOfRoot += rootStr.size()+1; //"/Root + ' ' 
   unsigned int endOfRoot = startOfRoot;
566
   while((int)NUMBERS.find(_fileContent[endOfRoot++]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
567 568 569 570 571 572 573 574
   {}
   --endOfRoot;
   return Utils::stringToInt(_fileContent.substr(startOfRoot, endOfRoot - startOfRoot));   
}

unsigned int Parser::_readTrailerAndRterievePrev(const unsigned int startPositionForSearch, unsigned int & previosXref)
{
   unsigned int startOfTrailer = Parser::findToken(_fileContent,"trailer", startPositionForSearch);
575
   if((int) startOfTrailer == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
576 577 578 579 580 581
   {
      throw Exception("Cannot find trailer!");
   }

   unsigned int startOfPrev = _fileContent.find("Prev ", startOfTrailer);
   unsigned int startxref = _fileContent.find("startxref", startOfTrailer);
582
   if((int)startOfPrev == -1 || (startOfPrev > startxref))
Claudio Valerio's avatar
Claudio Valerio committed
583 584 585 586 587 588
      return false;
   //"Prev "s length = 5
   else
      startOfPrev += 5;

   unsigned int endOfPrev = startOfPrev;
589
   while((int)NUMBERS.find(_fileContent[endOfPrev++]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
   {}
   --endOfPrev;
   previosXref = Utils::stringToInt(_fileContent.substr(startOfPrev, endOfPrev - startOfPrev));   
   return true;
}

//Method finds the token from current position from string
// It uses PDF whitespaces and delimeters to recognize
// Returned string without begin/end spaces
std::string Parser::getNextToken(const std::string &str, unsigned int  &position)
{
   if( position >= str.size() )
   {
      return "";
   }
   //skip first spaces
   size_t beg_pos = str.find_first_not_of(Parser::WHITESPACES,position);
607
   if ((int) beg_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
608 609 610 611 612
   {   
      // it is empty string!
      return "";
   }
   size_t end_pos = str.find_first_of(Parser::WHITESPACES_AND_DELIMETERS,beg_pos);
613
   if ((int) end_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
   {
      end_pos = str.size();
   }
   position = end_pos;

   std::string out = str.substr(beg_pos,end_pos - beg_pos);
   Parser::trim(out);
   return out;
}
/** @brief getNextWord
*
* method finds and returns next word from the string
* For example: " 1 0 R \n" will return "1" , then "0" then "R"
*/
bool Parser::getNextWord(std::string &out, const std::string &str, size_t &nextPosition, size_t  *found)
{
   if( found )
   {
632
      *found = -1;
Claudio Valerio's avatar
Claudio Valerio committed
633 634 635 636 637 638 639 640
   }
   //trace("position = %d",position);
   if( nextPosition >= str.size() )
   {
      return false;
   }
   //skip first spaces
   size_t beg_pos = str.find_first_not_of(Parser::WHITESPACES,nextPosition);
641
   if ((int) beg_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
642 643 644 645 646 647 648 649 650 651
   {   
      // it is empty string!
      return false;
   }
   if( found )
   {
      *found = beg_pos;
   }
   size_t end_pos = str.find_first_of(Parser::WHITESPACES,beg_pos);

652
   if ((int) end_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
   {
      end_pos = str.size();
   }
   nextPosition = end_pos;
   out = str.substr(beg_pos,end_pos - beg_pos);
   Parser::trim(out);
   if( out.empty() )
   {
      return false;
   }
   return true;
}

/** @brief trim
*
* @todo: document this function
*/
void Parser::trim(std::string &str)
{
   std::string::size_type pos1 = str.find_first_not_of(WHITESPACES);
   std::string::size_type pos2 = str.find_last_not_of(WHITESPACES);
674 675
   str = str.substr((int)pos1 == -1 ? 0 : pos1,
      (int)pos2 == -1 ? str.length() - 1 : pos2 - pos1 + 1);
Claudio Valerio's avatar
Claudio Valerio committed
676 677 678 679 680 681 682
}

// Method tries to find the PDF token from the content 
// The token is "/L 12 0R" or /Length 123
std::string Parser::findTokenStr(const std::string &content, const std::string &pattern, size_t start, size_t &foundStart, size_t &foundEnd)
{
   size_t cur_pos  = Parser::findToken(content,pattern,start);
683
   if((int) cur_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
684 685 686 687 688 689 690
   {
      return "";
   }
   foundStart = cur_pos;
   cur_pos += pattern.size();
   // then lets parse the content of remaining part
   size_t end_pos = content.find_first_of(Parser::DELIMETERS,cur_pos);
691
   if((int) end_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
   {
      end_pos = content.size();
   }
   std::string token = content.substr(cur_pos,end_pos-cur_pos);
   foundEnd = end_pos -1;
   return token;
}

// Method tries to find token in the string from specified position,
// returns position of first occurent or npos if not found
// It properly handles cases when content contains strings which 
// contains token but not euqal to it
// Example: content "/Transparency/ ..." pattern "/Trans
//          will return npos.
size_t Parser::findToken(const std::string &content, const std::string &keyword,size_t start)
{
   size_t cur_pos  = start;
   // lets find pattern first
710
   size_t foundStart = -1;
Claudio Valerio's avatar
Claudio Valerio committed
711 712 713 714
   size_t savedPos = 0;
   while( 1 )
   {
      cur_pos = content.find(keyword,cur_pos);
715
      if((int) cur_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
716 717 718 719 720 721 722
      {
         break;
      }
      savedPos = cur_pos;
      cur_pos += keyword.size();
      if( cur_pos < content.size() )
      {
723 724
          if((int) Parser::WHITESPACES.find(content[cur_pos]) != -1 ||
            (int)Parser::DELIMETERS.find(content[cur_pos]) != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
         {
            foundStart = savedPos;
            break;
         }
      }
      else
      {
         foundStart = savedPos;
         // end of line is reached
         break;
      }
   }
   return foundStart;
}

// Method checks if token at current position can be a Name or it is not name but value
// Example
// /H /P /P 12 0 R
// the tag /P can be a name (and a value also), while 12 cannot
// start defines the position of token content
bool Parser::tokenIsAName(const std::string &content, size_t start )
{
   std::string openBraces = "<[({";
   bool found = false;
   while(1)
   {
      size_t foundNonWhite = content.find_first_not_of(Parser::WHITESPACES,start);
      size_t foundDelim = content.find_first_of(Parser::DELIMETERS,start);

754 755
      if( (int)foundNonWhite != -1 &&
          (int)foundDelim != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
756
      {
757
         if( (foundNonWhite < foundDelim )  || ( (int)openBraces.find(content[foundDelim]) != -1) )
Claudio Valerio's avatar
Claudio Valerio committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
         {
            if( found )
            {
               return false;
            }
            else
            {
               return true;
            }
         }
         else
         {
            if( found )
            {
               return true;
            }
            else
            {
               found = true;
               start = content.find_first_of(Parser::WHITESPACES_AND_DELIMETERS,foundDelim+1);
            }
         }
      }
      else
      {
         return true;
      }
   }
}

// Method tries to find token name in the string from specified position,
// For example, the string contains /H /P /P 12 0 R.
// If search for /P then it will return position of /P 12 0 R, not value of 
// /H /P
size_t Parser::findTokenName(const std::string &content, const std::string &keyword,size_t start)
{
   size_t cur_pos  = start;
   // lets find pattern first
796
   size_t foundStart = -1;
Claudio Valerio's avatar
Claudio Valerio committed
797 798 799 800 801
   size_t savedPos = 0;
   std::string braces = "<[({";
   while( 1 )
   {
      cur_pos = content.find(keyword,cur_pos);
802
      if((int) cur_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
803 804 805 806 807 808 809
      {
         break;
      }
      savedPos = cur_pos;
      cur_pos += keyword.size();
      if( cur_pos < content.size() )
      {
810
          if((int) Parser::WHITESPACES_AND_DELIMETERS.find(content[cur_pos]) != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
         {
            if( tokenIsAName(content,cur_pos ) )
            {
               foundStart = savedPos;
               break;
            }
         }
      }
      else
      {
         foundStart = savedPos;
         // end of line is reached
         break;
      }
   }
   return foundStart;
}

unsigned int Parser::findEndOfElementContent(const std::string &content,unsigned int startOfPageElement)
{
831
   unsigned int foundEnd = -1;
Claudio Valerio's avatar
Claudio Valerio committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
   std::stack<std::string> delimStack;
   std::string endDelim = "/]>)}";
   unsigned int curPos = startOfPageElement;
   std::string openDict("<");
   std::string openArray("[");
   std::string delimeter = endDelim;

   delimStack.push(delimeter); //initial delimeter

   bool compensation = true;
   while(1)
   {
      unsigned int nonWhiteSpace = content.find_first_not_of(Parser::WHITESPACES,curPos);

      unsigned int foundDelimeter = content.find_first_of(delimeter,curPos);
      unsigned int foundOpenBrace = content.find("[",curPos);
      unsigned int foundOpenDict = content.find("<",curPos);

850
      if((int) foundDelimeter == -1 && (int)foundOpenBrace == -1 && (int)foundOpenDict == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
      {
         if( !delimStack.empty() )
         {
            delimStack.pop();
         }
      }
      else if( (foundDelimeter <= foundOpenBrace && foundDelimeter <= foundOpenDict ) )
      {
         if( !delimStack.empty() )
         {
            delimStack.pop();
         }
         if( nonWhiteSpace == foundDelimeter  && delimeter == endDelim )
         {
            curPos = foundDelimeter;
            if(content[foundDelimeter] == '/' && compensation )
            {
               curPos ++;
               compensation = false;
            }
         }
         else
         {
            compensation = false;
            if( delimeter == endDelim )
            {
               curPos = foundDelimeter;
            }
            else
            {
               curPos = foundDelimeter + delimeter.size();
            }
         }
      }
      else if( foundOpenBrace <= foundDelimeter && foundOpenBrace <= foundOpenDict )
      {
         compensation = false;
         delimStack.push("]");
         curPos = foundOpenBrace + openArray.size();
      }
      else if( foundOpenDict <= foundDelimeter && foundOpenDict <= foundOpenBrace )
      {
         compensation = false;
         delimStack.push(">");
         curPos = foundOpenDict + openDict.size();
      }
      if( delimStack.empty() )
      {
         foundEnd = content.find_first_of(delimeter,curPos);
900
         if((int) foundEnd == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
901 902 903 904 905 906 907 908 909 910 911
         {
            foundEnd = curPos;
         }
         break;
      }
      delimeter = delimStack.top();

   }
   return foundEnd;
}