Parser.cpp 26.8 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1 2 3
/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
Claudio Valerio's avatar
Claudio Valerio committed
4
 * the Free Software Foundation, either version 2 of the License, or
Claudio Valerio's avatar
Claudio Valerio committed
5 6 7 8 9 10 11 12 13 14
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
15 16

#include <QtGlobal>
Claudio Valerio's avatar
Claudio Valerio committed
17 18 19 20 21 22 23 24 25 26 27
#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"

28 29
#include "core/memcheck.h"

Claudio Valerio's avatar
Claudio Valerio committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
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(
62 63
      ((int)startOfKids == -1) &&
      ((int)objectContent.find("/Page") != -1)
Claudio Valerio's avatar
Claudio Valerio committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
      )
   {
      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)
{
82
    Q_UNUSED(docName);
Claudio Valerio's avatar
Claudio Valerio committed
83 84 85
   _document->_root = _root;
   std::string & rootContent = _root->getObjectContent();
   unsigned int startOfPages = rootContent.find("/Pages");
86
   if((int)startOfPages == -1)
Claudio Valerio's avatar
Claudio Valerio committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
      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))
            currentObject->addChild(_objects[(*refsIterator).first], (*refsIterator).second);		
      }
   }   
   _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");
192
   if((int)streamStart == -1)
Claudio Valerio's avatar
Claudio Valerio committed
193 194 195 196 197 198
      streamStart = objectContent.size();
   while(startOfNextSearch < streamStart)
   {
      //try to find reference. reference example is 15 0 R
      startOfNextSearch = objectContent.find(" R", startOfNextSearch);
      currentPosition = startOfNextSearch;
199
      if((int)currentPosition != -1)
Claudio Valerio's avatar
Claudio Valerio committed
200 201 202
      {         
         //check that next character of " R" is WHITESPACE. 

203 204
         if(((int)WHITESPACES.find(objectContent[currentPosition + 2]) == -1) &&
            ((int)DELIMETERS.find(objectContent[currentPosition + 2]) == -1)
Claudio Valerio's avatar
Claudio Valerio committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            )
         {
            //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;    
262
   while(((int)NUMBERS.find(str[numberSearchCounter]) != -1) && --numberSearchCounter)
Claudio Valerio's avatar
Claudio Valerio committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
   {}

   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)
      {
286
         Utils::stringToInt(_getNextToken(currentPostion));
Claudio Valerio's avatar
Claudio Valerio committed
287 288 289 290 291 292 293 294
         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));
295
               Utils::stringToInt(_getNextToken(currentPostion));
Claudio Valerio's avatar
Claudio Valerio committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 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
               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);
371
   if((int)bounds.first == -1)
Claudio Valerio's avatar
Claudio Valerio committed
372 373
      bounds.first = 0;
   bounds.second = str.find('\n', fromPosition);
374
   if((int)bounds.second == -1)
Claudio Valerio's avatar
Claudio Valerio committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
      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);
409
      if ((int)position != -1)
Claudio Valerio's avatar
Claudio Valerio committed
410 411 412 413 414 415 416 417 418 419
         ++tokensCount;
      //start search from next symbol
      ++position;
   }
   return tokensCount;
}

unsigned int Parser::_skipWhiteSpaces(const std::string & str, unsigned int fromPosition)
{
   unsigned int position = fromPosition;
420
   if((int)WHITESPACES.find(str[0]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
421 422 423 424 425 426 427
      position = str.find_first_not_of(WHITESPACES, position);
   return position;
}

unsigned int Parser::_skipWhiteSpacesFromContent(unsigned int fromPosition)
{
   unsigned int position = fromPosition;
428
   if((int)WHITESPACES.find(_fileContent[position]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
      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);
457
   if((int) contentStart == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
458 459 460 461 462 463 464
   {
      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);
465
   if((int) endOfContent == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
466 467 468 469 470
   {
      stringstream errorMessage("Corrupted PDF file, obj does not have matching endobj");
      throw Exception(errorMessage);
   }
   unsigned int endOfStream = _fileContent.find("endstream", currentPosition);
471
   if(((int)endOfStream != -1) && (endOfStream < endOfContent))
Claudio Valerio's avatar
Claudio Valerio committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
   {
      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);
488
      if ((int) lengthBegin != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
      {
         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);
516
            if((int) streamEndBegin != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
            {
               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);
541
   if((int) startOfRoot == -1)
Claudio Valerio's avatar
Claudio Valerio committed
542 543 544 545
   {
      throw Exception("Cannot find Root object !");
   }
   std::string encryptStr("/Encrypt");
546
   if((int) Parser::findToken(_fileContent,encryptStr,startOfTrailer) != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
547 548 549 550 551
   {
      throw Exception("Encrypted PDF is not supported!");
   }
   startOfRoot += rootStr.size()+1; //"/Root + ' ' 
   unsigned int endOfRoot = startOfRoot;
552
   while((int)NUMBERS.find(_fileContent[endOfRoot++]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
553 554 555 556 557 558 559 560
   {}
   --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);
561
   if((int) startOfTrailer == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
562 563 564 565 566 567
   {
      throw Exception("Cannot find trailer!");
   }

   unsigned int startOfPrev = _fileContent.find("Prev ", startOfTrailer);
   unsigned int startxref = _fileContent.find("startxref", startOfTrailer);
568
   if((int)startOfPrev == -1 || (startOfPrev > startxref))
Claudio Valerio's avatar
Claudio Valerio committed
569 570 571 572 573 574
      return false;
   //"Prev "s length = 5
   else
      startOfPrev += 5;

   unsigned int endOfPrev = startOfPrev;
575
   while((int)NUMBERS.find(_fileContent[endOfPrev++]) != -1)
Claudio Valerio's avatar
Claudio Valerio committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
   {}
   --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);
593
   if ((int) beg_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
594 595 596 597 598
   {   
      // it is empty string!
      return "";
   }
   size_t end_pos = str.find_first_of(Parser::WHITESPACES_AND_DELIMETERS,beg_pos);
599
   if ((int) end_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
   {
      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 )
   {
618
      *found = -1;
Claudio Valerio's avatar
Claudio Valerio committed
619 620 621 622 623 624 625 626
   }
   //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);
627
   if ((int) beg_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
628 629 630 631 632 633 634 635 636 637
   {   
      // it is empty string!
      return false;
   }
   if( found )
   {
      *found = beg_pos;
   }
   size_t end_pos = str.find_first_of(Parser::WHITESPACES,beg_pos);

638
   if ((int) end_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
   {
      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);
660 661
   str = str.substr((int)pos1 == -1 ? 0 : pos1,
      (int)pos2 == -1 ? str.length() - 1 : pos2 - pos1 + 1);
Claudio Valerio's avatar
Claudio Valerio committed
662 663 664 665 666 667 668
}

// 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);
669
   if((int) cur_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
670 671 672 673 674 675 676
   {
      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);
677
   if((int) end_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
   {
      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
696
   size_t foundStart = -1;
Claudio Valerio's avatar
Claudio Valerio committed
697 698 699 700
   size_t savedPos = 0;
   while( 1 )
   {
      cur_pos = content.find(keyword,cur_pos);
701
      if((int) cur_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
702 703 704 705 706 707 708
      {
         break;
      }
      savedPos = cur_pos;
      cur_pos += keyword.size();
      if( cur_pos < content.size() )
      {
709 710
          if((int) Parser::WHITESPACES.find(content[cur_pos]) != -1 ||
            (int)Parser::DELIMETERS.find(content[cur_pos]) != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
         {
            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);

740 741
      if( (int)foundNonWhite != -1 &&
          (int)foundDelim != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
742
      {
743
         if( (foundNonWhite < foundDelim )  || ( (int)openBraces.find(content[foundDelim]) != -1) )
Claudio Valerio's avatar
Claudio Valerio committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
         {
            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
782
   size_t foundStart = -1;
Claudio Valerio's avatar
Claudio Valerio committed
783 784 785 786 787
   size_t savedPos = 0;
   std::string braces = "<[({";
   while( 1 )
   {
      cur_pos = content.find(keyword,cur_pos);
788
      if((int) cur_pos == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
789 790 791 792 793 794 795
      {
         break;
      }
      savedPos = cur_pos;
      cur_pos += keyword.size();
      if( cur_pos < content.size() )
      {
796
          if((int) Parser::WHITESPACES_AND_DELIMETERS.find(content[cur_pos]) != -1 )
Claudio Valerio's avatar
Claudio Valerio committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
         {
            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)
{
817
   unsigned int foundEnd = -1;
Claudio Valerio's avatar
Claudio Valerio committed
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
   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);

836
      if((int) foundDelimeter == -1 && (int)foundOpenBrace == -1 && (int)foundOpenDict == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 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
      {
         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);
886
         if((int) foundEnd == -1 )
Claudio Valerio's avatar
Claudio Valerio committed
887 888 889 890 891 892 893 894 895 896 897
         {
            foundEnd = curPos;
         }
         break;
      }
      delimeter = delimStack.top();

   }
   return foundEnd;
}