Exemplo n.º 1
0
//read form fp,and write to tcpSocket
void sendStreamData(QTcpSocket* tcpSocket,QDataStream &in,long long streamLength){
    char *buffer;
    buffer = new (std::nothrow) char[STREAMBLOCKSIZE];
    if(!buffer){
        std::cerr << "can not allocat memeory" << std::endl;
        return;
    }
    if(streamLength==0){
        while(!in.atEnd()){
            unsigned short len = in.readRawData(buffer,STREAMBLOCKSIZE);
            if(tcpSocket->bytesToWrite()>16384 && !tcpSocket->waitForBytesWritten())
                return;
            tcpSocket->write((char*)&len,sizeof(unsigned short));
            if(len!=0)
                tcpSocket->write(buffer,len);
            if(len!=STREAMBLOCKSIZE){
                len=STREAMBLOCKSIZE;
                tcpSocket->write((char*)&len,sizeof(unsigned short));
                //break;
            }
        }
    }
    else{
        while(streamLength>0){
            unsigned short len = in.readRawData(buffer,STREAMBLOCKSIZE);
            if(tcpSocket->bytesToWrite()>16384 && !tcpSocket->waitForBytesWritten())
                return;
            tcpSocket->write(buffer,len);
            streamLength -= len;
        }
    }
    delete[] buffer;
}
Exemplo n.º 2
0
QString readString(QDataStream &stream)
{
	QString res = "";
	while(true || !stream.atEnd())
	{
		char data[2];
		stream.readRawData(data, 2);
		
		if (data[0] == 0x00)
			break;
	
		if(data[0] != 0x00)
            res += QChar::fromLatin1(data[0]);
        /*
         * короче не знает он что такое этот фром аски, пробовал инклюды разные и доставлял либы, не помогло
         * sea-kg: беда... метод в ку5 морально устарел... может попробовать res += QChar::fromLatin1(data[0]) ???
         * или res += QChar(QLatin1Char(data[0]).unicode());
         * http://qt-project.org/doc/qt-5.0/qtcore/qchar.html
         * Static Public Method
         * QChar 	fromAscii(char c) (deprecated)
         * Converts the ASCII character c to it's equivalent QChar. This is mainly useful for non-internationalized software.
         * An alternative is to use QLatin1Char.
         */
    }
	return res;
}
bool Index::readDict( QDataStream& stream )
{
	dict.clear();
	docList.clear();
	
	QString key;
	int version, numOfDocs;
	
	stream >> version;
	
	if ( version < 2 )
		return false;
	
	stream >> m_charssplit;
	stream >> m_charsword;
	
	// Read the document list
	stream >> docList;
	
	while ( !stream.atEnd() )
	{
		stream >> key;
		stream >> numOfDocs;
		
		QVector<Document> docs( numOfDocs );
		
		stream >> docs;
		dict.insert( key, new Entry( docs ) );
	}
	
	return dict.size() > 0;
}
Exemplo n.º 4
0
bool QPixmapIconEngine::read(QDataStream &in)
{
    int num_entries;
    QPixmap pm;
    QString fileName;
    QSize sz;
    uint mode;
    uint state;

    in >> num_entries;
    for (int i=0; i < num_entries; ++i) {
        if (in.atEnd()) {
            pixmaps.clear();
            return false;
        }
        in >> pm;
        in >> fileName;
        in >> sz;
        in >> mode;
        in >> state;
        if (pm.isNull()) {
            addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
        } else {
            QPixmapIconEngineEntry pe(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
            pe.pixmap = pm;
            pixmaps += pe;
        }
    }
    return true;
}
Exemplo n.º 5
0
void Prg::ReadBytes(QDataStream& stream, int index)
{
    while(!stream.atEnd())
    {
         stream >> _byteCode[index++];
    }
}
Exemplo n.º 6
0
Cornu::PolylineConstPtr Document::_readPts(QDataStream &stream)
{
    unsigned int sz = 0;
    stream >> sz;
    if(stream.atEnd() || sz > 10000)
        return Cornu::PolylineConstPtr();

    Cornu::VectorC<Vector2d> pt(sz, Cornu::NOT_CIRCULAR);
    for(int i = 0; i < pt.size(); ++i) {
        if(stream.atEnd())
            return Cornu::PolylineConstPtr();
        stream >> pt[i][0] >> pt[i][1];
    }

    return new Cornu::Polyline(pt);
}
Exemplo n.º 7
0
void read_cstring(QDataStream & stream, QString & v)
{
    quint8 c;
    while (!stream.atEnd()) {
        stream >> c;
        if (c == 0)
            break;
        v.append(c);
    }
}
Exemplo n.º 8
0
static qint32 find_sample_count_v6(QDataStream & abr, AbrInfo *abr_info)
{
    qint64 origin;
    qint32 sample_section_size;
    qint32 sample_section_end;
    qint32 samples = 0;
    qint32 data_start;

    qint32 brush_size;
    qint32 brush_end;

    if (!abr_supported_content(abr_info))
        return 0;

    origin = abr.device()->pos();

    if (!abr_reach_8BIM_section(abr, "samp")) {
        // reset to origin
        abr.device()->seek(origin);
        return 0;
    }

    // long
    abr >> sample_section_size;
    sample_section_end = sample_section_size + abr.device()->pos();

    if(sample_section_end < 0 || sample_section_end > abr.device()->size())
        return 0;

    data_start = abr.device()->pos();

    while ((!abr.atEnd()) && (abr.device()->pos() < sample_section_end)) {
        // read long
        abr >> brush_size;
        brush_end = brush_size;
        // complement to 4
        while (brush_end % 4 != 0) brush_end++;

        qint64 newPos = abr.device()->pos() + brush_end;
        if(newPos > 0 && newPos < abr.device()->size()) {
            abr.device()->seek(newPos);
        }
        else
            return 0;

        samples++;
    }

    // set stream to samples data
    abr.device()->seek(data_start);

    //dbgKrita <<"samples : "<< samples;
    return samples;
}
Exemplo n.º 9
0
bool CoreProtocol::okToProceed( QDataStream &din)
{
	if ( din.atEnd() )
	{
		m_state = NeedMore;
		kDebug(YAHOO_RAW_DEBUG) << " saved message prematurely";
		return false;
	}
	else
		return true;
}
Exemplo n.º 10
0
void Sequence::decodeData(QDataStream &inputStream, quint8 length)
{
    quint32 bytesRead = 0;
    while (!inputStream.atEnd() && bytesRead++ < length) {
        quint8 type = 0;
        inputStream >> type;
        AbstractSyntaxNotationOne *asnType = DataTypeFactory::createType(static_cast<Type::AbstractSyntaxNotationOneType>(type), this);
        bytesRead += asnType->decode(inputStream);

        sequenceData.append(asnType);
    }
}
Exemplo n.º 11
0
void SessionManager::read()
{
    QFile f(_sessionsPath);
    QDataStream in;
    QVariant tmp;
    Session *session(0);

    // Opening the saving file
    if (!f.open(QIODevice::ReadOnly))
        return;

    in.setDevice(&f);

    // Reading of all sessions
    while (!in.atEnd())
    {
        session = new Session();

        // Retrieving of the access token
        in >> tmp;

        session->setAccessToken(tmp.toString());
        tmp.clear();

        // Retrieving of the client token
        in >> tmp;

        session->setClientToken(tmp.toString());
        tmp.clear();

        // Retrieving of the player's uuid
        in >> tmp;

        session->setUuid(tmp.toString());
        tmp.clear();

        // Retrieving of the player's username
        in >> tmp;

        session->setName(tmp.toString());
        tmp.clear();

        // Retrieving of the player's legacy
        in >> tmp;

        session->setLegacy(tmp.toBool());
        tmp.clear();
    }

    f.close();
}
Exemplo n.º 12
0
void
KCmdLineArgs::loadAppArgs( QDataStream &ds)
{
   s->parsed = true; // don't reparse argc/argv!

   // Remove Qt and KDE options.
   s->removeArgs("qt");
   s->removeArgs("kde");
   s->removeArgs("kuniqueapp");

   KCmdLineArgsList::Iterator args;
   if ( s->argsList ) {
      for(args = s->argsList->begin(); args != s->argsList->end(); ++args)
      {
         (*args)->clear();
      }
   }

   if (ds.atEnd())
      return;

   QByteArray qCwd;
   ds >> qCwd;

   s->mCwd = qCwd;

   uint count;
   ds >> count;

   while(count--)
   {
     QByteArray id;
     ds >> id;
     Q_ASSERT( s->argsList );
     bool found = false;
     for(args = s->argsList->begin(); args != s->argsList->end(); ++args)
     {
       if ((*args)->d->id  == id)
       {
          (*args)->d->load(ds);
          found = true;
          break;
       }
     }
     if (!found) {
         kWarning() << "Argument definitions for" << id << "not found!";
         // The next ds >> id will do nonsensical things...
     }
   }
   s->parsed = true;
}
Exemplo n.º 13
0
void MPSimpleBoard::dataIn(QDataStream &s)
{
	if ( s.atEnd() ) return; // no data

	IO_Flag f;
	s >> f;
	switch ( f.value() ) {
	 case IO_Flag::Init:      initFlag(s);    break;
	 case IO_Flag::Play:      playFlag(s);    break;
	 case IO_Flag::Pause:     pauseFlag();    break;
	 case IO_Flag::GameOver:  gameOverFlag(); break;
	 case IO_Flag::Stop:      stopFlag();     break;
	}
}
Exemplo n.º 14
0
/** Loads group fields from the stream. Returns true on success, false in case of error. */
bool PwGroupV3::readFromStream(QDataStream& stream) {
    quint16 fieldType;
    qint32 fieldSize;
    while (!stream.atEnd()) {
        stream >> fieldType >> fieldSize;
        switch(fieldType) {
        case FIELD_RESERVED:
            stream.skipRawData(fieldSize);
            break;
        case FIELD_GROUP_ID:
            this->setId(PwStreamUtilsV3::readInt32(stream));
            break;
        case FIELD_NAME:
            this->setName(PwStreamUtilsV3::readString(stream, fieldSize));
            break;
        case FIELD_CREATION_TIME:
            this->setCreationTime(PwStreamUtilsV3::readTimestamp(stream));
            break;
        case FIELD_LAST_MODIFIED_TIME:
            this->setLastModificationTime(PwStreamUtilsV3::readTimestamp(stream));
            break;
        case FIELD_LAST_ACCESS_TIME:
            this->setLastAccessTime(PwStreamUtilsV3::readTimestamp(stream));
            break;
        case FIELD_EXPIRATION_TIME:
            this->setExpiryTime(PwStreamUtilsV3::readTimestamp(stream));
            break;
        case FIELD_ICON_ID:
            this->setIconId(PwStreamUtilsV3::readInt32(stream));
            break;
        case FIELD_GROUP_LEVEL:
            this->setLevel(PwStreamUtilsV3::readUInt16(stream));
            break;
        case FIELD_GROUP_FLAGS:
            this->setFlags(PwStreamUtilsV3::readInt32(stream));
            break;
        case FIELD_END:
            // group fields finished
            stream.skipRawData(fieldSize);
            // a "Backup" group in the root is equivalent of V4's "Recycle Bin"
            if ((this->getLevel() == 0) && (BACKUP_GROUP_NAME == this->getName())) {
                this->setDeleted(true);
            }
            return true;
        }
    }
    // something went wrong, there was no FIELD_END marker
    return false;
}
Exemplo n.º 15
0
/** Load a QByteArray from a stream with only one leading byte instead of 4. */
void ShortLoad (QDataStream &s, QByteArray &str)
{
  str.detach();
  quint8 len;
  s >> len;			    // read size of string

  if ( len == 0 || s.atEnd() ) {  // end of file reached
    str.resize( 0 );
    return;
  }

  str.resize( len );
  s.readRawData( str.data(), len );
  return;
}
Exemplo n.º 16
0
void IntegerColumn::loadFromStream(QDataStream &aStream)
{
    init();

    QString aMagicWord;

    while (!aStream.atEnd())
    {
        aStream >> aMagicWord;

        if (aMagicWord=="Default")
        {
            aStream >> mDefaultValue;
        }
        else
        if (aMagicWord=="Decimals")
Exemplo n.º 17
0
void cTelnet::_loadReplay()
{
    if( ! replayStream.atEnd() )
    {
        int offset;
        int amount;
        replayStream >> offset;
        replayStream >> amount;

        char * pB = &loadBuffer[0];
        loadedBytes = replayStream.readRawData ( pB, amount );
        qDebug()<<"loaded:"<<loadedBytes<<"/"<<amount<<" bytes"<<" waiting for "<<offset<<" milliseconds";
        loadBuffer[loadedBytes+1] = '\0';
        QTimer::singleShot( offset/mudlet::self()->mReplaySpeed, this, SLOT(readPipe()));
        mudlet::self()->mReplayTime = mudlet::self()->mReplayTime.addMSecs(offset);
    }
Exemplo n.º 18
0
//-----------------------------------------------------------------------------
//
bool QEMenuButtonModel::dropMimeData (const QMimeData* data, Qt::DropAction action,
                                      int /* row */, int column,
                                      const QModelIndex& parentIndex)
{
   if (action == Qt::IgnoreAction) {
      DEBUG << "action == Qt::IgnoreAction";
      return true;
   }

   if (!data->hasFormat (mineType)) {
      DEBUG << QString ("not '%1'").arg (mineType);
      return false;
   }

   if (column > 0) {
      DEBUG << "column > 0 , i.e." << column;
      return false;
   }

   QByteArray encodedData = data->data (mineType);
   QDataStream stream (&encodedData, QIODevice::ReadOnly);

   if (stream.atEnd ()) {
      DEBUG << "Empty stream";
      return false;
   }

   QEMenuButtonItem* attachTo = NULL;
   int attachPosition = -1; // i.e. at end
   attachTo = this->getItem (parentIndex);
   if (!attachTo->getIsSubMenuContainer ()) {
      // Item has not been dropped on a submenu, so we attach to this menu item's
      // parent at the current position.
      //
      attachPosition = attachTo->childPosition ();
      attachTo = attachTo->getParent();
   }

   // We currently expect only one item (albeit a submenu container with its own
   // child menu items).
   //
   QEMenuButtonItem* item = new QEMenuButtonItem ("", false);
   stream >> *item;
   this->addItemToModel (item, attachTo, attachPosition);

   return true;
}
Exemplo n.º 19
0
void Server::collectResult(QDataStream& ds)
{
  int start, end;
  ds >> start;
  end = start;
  
  // mutexes

    
  // STL insert/copy
  while(!ds.atEnd()) ds >> frame[end++];

  received_pixels += (end - start);
  if(received_pixels >= vres * hres) {
    std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count() << std::endl;
    sendFrame();
  }
}
Exemplo n.º 20
0
QString readLinefromDataStream(QDataStream &s)
{
    QString ret = "";
    uchar charData;
    while (!s.atEnd())
    {
        s >> charData;
        if (charData == '\x0A')
            break;
        if (charData == '\x0D')
        {
            quint64 oldPos = s.device()->pos();
            s >> charData;
            if (charData != '\x0A')
                s.device()->seek(oldPos);
            break;
        }
        ret += QChar(charData);
    }
Exemplo n.º 21
0
static bool abr_reach_8BIM_section(QDataStream & abr, const QString name)
{
    char tag[4];
    char tagname[5];
    qint32 section_size = 0;
    int r;

    // find 8BIMname section
    while (!abr.atEnd()) {
        r = abr.readRawData(tag, 4);

        if (r != 4) {
            warnKrita << "Error: Cannot read 8BIM tag ";
            return false;
        }

        if (strncmp(tag, "8BIM", 4)) {
            warnKrita << "Error: Start tag not 8BIM but " << (int)tag[0] << (int)tag[1] << (int)tag[2] << (int)tag[3] << " at position " << abr.device()->pos();
            return false;
        }

        r = abr.readRawData(tagname, 4);

        if (r != 4) {
            warnKrita << "Error: Cannot read 8BIM tag name";
            return false;
        }
        tagname[4] = '\0';

        QString s1 = QString::fromLatin1(tagname, 4);

        if (!s1.compare(name)) {
            return true;
        }

        // long
        abr >> section_size;
        abr.device()->seek(abr.device()->pos() + section_size);
    }
    return true;
}
Exemplo n.º 22
0
	bool CLModel::TryDropContact (const QMimeData *mime, int row, const QModelIndex& parent)
	{
		if (!mime->hasFormat (CLEntryFormat))
			return false;

		if (parent.data (Core::CLREntryType).value<Core::CLEntryType> () != Core::CLETAccount)
			return false;

		QObject *accObj = parent.data (Core::CLRAccountObject).value<QObject*> ();
		IAccount *acc = qobject_cast<IAccount*> (accObj);
		if (!acc)
			return false;

		const QString& newGrp = parent.child (row, 0)
				.data (Core::CLREntryCategory).toString ();

		QDataStream stream (mime->data (CLEntryFormat));
		while (!stream.atEnd ())
		{
			QString id;
			QString oldGroup;
			stream >> id >> oldGroup;

			if (oldGroup == newGrp)
				continue;

			QObject *entryObj = Core::Instance ().GetEntry (id);
			ICLEntry *entry = qobject_cast<ICLEntry*> (entryObj);
			if (!entry)
				continue;

			QStringList groups = entry->Groups ();
			groups.removeAll (oldGroup);
			groups << newGrp;

			entry->SetGroups (groups);
		}

		return true;
	}
Exemplo n.º 23
0
void QNodesEditor::load(QDataStream &ds)
{
	scene->clear();

	QMap<quint64, QNEPort*> portMap;

	while (!ds.atEnd())
	{
		int type;
		ds >> type;
		if (type == QNEBlock::Type)
		{
            QNEBlock *block = new QNEBlock(0);
            scene->addItem(block);
			block->load(ds, portMap);
		} else if (type == QNEConnection::Type)
		{
            QNEConnection *conn = new QNEConnection(0);
            scene->addItem(conn);
			conn->load(ds, portMap);
		}
	}
}
Exemplo n.º 24
0
  bool dropMimeData (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
  {
    if (action == Qt::IgnoreAction) return true;
    if (!data->hasFormat("application/kmuddy.object.info")) return false;
    if (column > 0) return false;

    cListObject *grp = parent.isValid() ? static_cast<cListObject *>(parent.internalPointer()) : lst->rootGroup();
    if (!grp->isGroup()) {  // we dropped onto an end-object - can this ever happen ?
      // will insert after this item
      row = grp->positionInGroup() + 1;
      grp = grp->parentGroup ();
    }
    cListGroup *group = (cListGroup *) grp;
    QByteArray encodedData = data->data ("application/kmuddy.object.info");
    QDataStream stream (&encodedData, QIODevice::ReadOnly);
    
    cListManager *lm = cListManager::self();
    while (!stream.atEnd()) {
      // fetch an object ID from the dropped data
      int id;
      stream >> id;
      cListObject *obj = lm->object (id);
      // ensure that the object is valid and belongs to the same list
      if (!obj) continue;
      if (obj->list() != lst) continue;

      // alright, we need to move this object to the designated position
      // also adjust the designated position if needed, so that the next object is placed correctly
      bool sameGroup = (group == obj->parentGroup ());
      if (!sameGroup) lst->addToGroup (group, obj);
      // adjust row number so that everything works well when moving within the same group
      if (sameGroup && obj->positionInGroup() < row) row--;
      if (row >= 0)
        group->moveObjectToPosition (obj, row++);
    }
    return true;
  }
Exemplo n.º 25
0
bool QtopiaSvgIconEngine::read(QDataStream &in)
{
    QString fname;
    int num_entries;

    in >> fname;
    d->filename = fname;
    in >> num_entries;
    for (int i=0; i<num_entries; ++i) {
        if (in.atEnd()) {
            if (d->pixmaps)
                d->pixmaps->clear();
            return false;
        }
        QString key;
        QPixmap pixmap;
        in >> pixmap;
        in >> key;
        if (!d->pixmaps)
            d->pixmaps = new QMap<QString,QPixmap>;
        d->pixmaps->insert(key, pixmap);
    }
    return true;
}
Exemplo n.º 26
0
static bool decodeFolder(KWallet::Wallet *_wallet, QDataStream& ds) {
	quint32 magic;
	ds >> magic;
	if (magic != KWALLETFOLDERMAGIC) {
		kDebug() << "bad magic" ;
		return false;
	}
	QString folder;
	ds >> folder;
	if (_wallet->hasFolder(folder)) {
		int rc = KMessageBox::warningYesNoCancel(0L, i18n("A folder by the name '%1' already exists.  What would you like to do?", folder), QString(), KStandardGuiItem::cont(), KGuiItem(i18n("Replace")));
		if (rc == KMessageBox::Cancel) {
			return false;
		}
		if (rc == KMessageBox::No) {
			_wallet->removeFolder(folder);
			_wallet->createFolder(folder);
		}
	} else {
		_wallet->createFolder(folder);
	}

	_wallet->setFolder(folder);
	while (!ds.atEnd()) {
		QString name;
		QByteArray value;
		KWallet::Wallet::EntryType et;
		ds >> name;
		qint32 l;
		ds >> l;
		et = KWallet::Wallet::EntryType(l);
		ds >> value;
		_wallet->writeEntry(name, value, et);
	}
	return true;
}
Exemplo n.º 27
0
bool SwapFile::recover(QDataStream& stream, bool checkDigest)
{
  if (!isValidSwapFile(stream, checkDigest)) {
    return false;
  }

  // disconnect current signals
  setTrackingEnabled(false);

  // replay swapfile
  bool editStarted = false;
  bool brokenSwapFile = false;
  while (!stream.atEnd()) {
    if (brokenSwapFile)
      break;

    qint8 type;
    stream >> type;
    switch (type) {
      case EA_StartEditing: {
        m_document->editStart();
        editStarted = true;
        break;
      }
      case EA_FinishEditing: {
        m_document->editEnd();
        editStarted = false;
        break;
      }
      case EA_WrapLine: {
        if (!editStarted) {
          brokenSwapFile = true;
          break;
        }

        int line = 0, column = 0;
        stream >> line >> column;
        
        // emulate buffer unwrapLine with document
        m_document->editWrapLine(line, column, true);
        break;
      }
      case EA_UnwrapLine: {
        if (!editStarted) {
          brokenSwapFile = true;
          break;
        }

        int line = 0;
        stream >> line;
        
        // assert valid line
        Q_ASSERT (line > 0);
        
        // emulate buffer unwrapLine with document
        m_document->editUnWrapLine(line - 1, true, 0);
        break;
      }
      case EA_InsertText: {
        if (!editStarted) {
          brokenSwapFile = true;
          break;
        }

        int line, column;
        QByteArray text;
        stream >> line >> column >> text;
        m_document->insertText(KTextEditor::Cursor(line, column), QString::fromUtf8 (text.data (), text.size()));
        break;
      }
      case EA_RemoveText: {
        if (!editStarted) {
          brokenSwapFile = true;
          break;
        }

        int line, startColumn, endColumn;
        stream >> line >> startColumn >> endColumn;
        m_document->removeText (KTextEditor::Range(KTextEditor::Cursor(line, startColumn), KTextEditor::Cursor(line, endColumn)));
        break;
      }
      default: {
        kWarning( 13020 ) << "Unknown type:" << type;
      }
    }
  }

  // balance editStart and editEnd
  if (editStarted) {
    brokenSwapFile = true;
    m_document->editEnd();
  }

  // warn the user if the swap file is not complete
  if (brokenSwapFile) {
    kWarning ( 13020 ) << "Some data might be lost";
  }
  
  // reconnect the signals
  setTrackingEnabled(true);
  
  return true;
}
Exemplo n.º 28
0
Map
Reader::parse( QDataStream &raw, uint containerLength, bool first )
{
//DEBUG_BLOCK
/* http://daap.sourceforge.net/docs/index.html
0-3     Content code    OSType (unsigned long), description of the contents of this chunk
4-7     Length  Length of the contents of this chunk (not the whole chunk)
8-      Data    The data contained within the chunk */
    Map childMap;
    uint index = 0;
    while( (first ? !raw.atEnd() : ( index < containerLength ) ) )
    {
    //    debug() << "at index " << index << " of a total container size " << containerLength << endl;
        char tag[5];
        Q_UINT32 tagLength = getTagAndLength( raw, tag );
        if( tagLength == 0 )
        {
//             debug() << "tag " << tag << " has 0 length." << endl;
            index += 8;
            continue;
        }
//#define DEBUGTAG( VAR ) debug() << tag << " has value " << VAR << endl;
#define DEBUGTAG( VAR )
        switch( s_codes[tag].type )
        {
            case CHAR: {
                Q_INT8 charData;
                raw >> charData; DEBUGTAG( charData )
                addElement( childMap, tag, QVariant( static_cast<int>(charData) ) );
                }
                break;
            case SHORT: {
                Q_INT16 shortData;
                raw >> shortData; DEBUGTAG( shortData )
                addElement( childMap, tag, QVariant( static_cast<int>(shortData) ) );
                }
                break;
            case LONG: {
                Q_INT32 longData;
                raw >> longData; DEBUGTAG( longData )
                addElement( childMap, tag, QVariant( longData ) );
                }
                break;
            case LONGLONG: {
                Q_INT64 longlongData;
                raw >> longlongData; DEBUGTAG( longlongData )
                addElement( childMap, tag, QVariant( longlongData ) );
                }
                break;
            case STRING: {
                QByteArray stringData(tagLength);
                raw.readRawBytes( stringData.data(), tagLength ); DEBUGTAG( QString::fromUtf8( stringData, tagLength ) )
                addElement( childMap, tag, QVariant( QString::fromUtf8( stringData, tagLength ) ) );
                }
                break;
            case DATE: {
                Q_INT64 dateData;
                QDateTime date;
                raw >> dateData; DEBUGTAG( dateData )
                date.setTime_t(dateData);
                addElement( childMap, tag, QVariant( date ) );
                }
                break;
            case DVERSION: {
                Q_INT16 major;
                Q_INT8 minor;
                Q_INT8 patchLevel;
                raw >> major >> minor >> patchLevel; DEBUGTAG( patchLevel )
                QString version("%1.%2.%3");
                version.arg(major, minor, patchLevel);
                addElement( childMap, tag, QVariant(version) );
                }
                break;
            case CONTAINER: {
                DEBUGTAG( 11 )
                addElement( childMap, tag, QVariant( parse( raw, tagLength ) ) );
                }
                break;
            default:
                warning() << tag << " doesn't work" << endl;
            break;
        }
        index += tagLength + 8;
    }
    return childMap;
}
Exemplo n.º 29
0
bool SwapFile::recover(QDataStream& stream, bool checkDigest)
{
  if (!isValidSwapFile(stream, checkDigest)) {
    return false;
  }

  // disconnect current signals
  setTrackingEnabled(false);

  // needed to set undo/redo cursors in a sane way
  bool firstEditInGroup = false;
  KTextEditor::Cursor undoCursor = KTextEditor::Cursor::invalid();
  KTextEditor::Cursor redoCursor = KTextEditor::Cursor::invalid();

  // replay swapfile
  bool editRunning = false;
  bool brokenSwapFile = false;
  while (!stream.atEnd()) {
    if (brokenSwapFile)
      break;

    qint8 type;
    stream >> type;
    switch (type) {
      case EA_StartEditing: {
        m_document->editStart();
        editRunning = true;
        firstEditInGroup = true;
        undoCursor = KTextEditor::Cursor::invalid();
        redoCursor = KTextEditor::Cursor::invalid();
        break;
      }
      case EA_FinishEditing: {
        m_document->editEnd();
        
        // empty editStart() / editEnd() groups exist: only set cursor if required
        if (!firstEditInGroup) {
          // set undo/redo cursor of last KateUndoGroup of the undo manager
          m_document->undoManager()->setUndoRedoCursorsOfLastGroup(undoCursor, redoCursor);
          m_document->undoManager()->undoSafePoint();
        }
        firstEditInGroup = false;
        editRunning = false;
        break;
      }
      case EA_WrapLine: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line = 0, column = 0;
        stream >> line >> column;
        
        // emulate buffer unwrapLine with document
        m_document->editWrapLine(line, column, true);

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, column);
        }
        redoCursor = KTextEditor::Cursor(line + 1, 0);

        break;
      }
      case EA_UnwrapLine: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line = 0;
        stream >> line;
        
        // assert valid line
        Q_ASSERT (line > 0);

        const int undoColumn = m_document->lineLength(line - 1);

        // emulate buffer unwrapLine with document
        m_document->editUnWrapLine(line - 1, true, 0);

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, 0);
        }
        redoCursor = KTextEditor::Cursor(line - 1, undoColumn);

        break;
      }
      case EA_InsertText: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line, column;
        QByteArray text;
        stream >> line >> column >> text;
        m_document->insertText(KTextEditor::Cursor(line, column), QString::fromUtf8 (text.data (), text.size()));

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, column);
        }
        redoCursor = KTextEditor::Cursor(line, column + text.size());

        break;
      }
      case EA_RemoveText: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line, startColumn, endColumn;
        stream >> line >> startColumn >> endColumn;
        m_document->removeText (KTextEditor::Range(KTextEditor::Cursor(line, startColumn), KTextEditor::Cursor(line, endColumn)));

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, endColumn);
        }
        redoCursor = KTextEditor::Cursor(line, startColumn);

        break;
      }
      default: {
        kWarning( 13020 ) << "Unknown type:" << type;
      }
    }
  }

  // balanced editStart and editEnd?
  if (editRunning) {
    brokenSwapFile = true;
    m_document->editEnd();
  }

  // warn the user if the swap file is not complete
  if (brokenSwapFile) {
    kWarning ( 13020 ) << "Some data might be lost";
  } else {
    // set sane final cursor, if possible
    KTextEditor::View * view = m_document->activeView();
    redoCursor = m_document->undoManager()->lastRedoCursor();
    if (view && redoCursor.isValid()) {
      view->setCursorPosition(redoCursor);
    }
  }

  // reconnect the signals
  setTrackingEnabled(true);

  return true;
}