예제 #1
0
QDomDocumentType QDomDocumentProto::doctype() const
{
    QDomDocument *item = qscriptvalue_cast<QDomDocument*>(thisObject());
    if (item)
        return item->doctype();
    return QDomDocumentType();
}
예제 #2
0
QFile::FileError QLCFixtureDef::loadXML(const QString& fileName)
{
    QFile::FileError error = QFile::NoError;

    if (fileName.isEmpty() == true)
        return QFile::OpenError;

    QDomDocument doc = QLCFile::readXML(fileName);
    if (doc.isNull() == true)
    {
        qWarning() << Q_FUNC_INFO << "Unable to read from" << fileName;
        return QFile::ReadError;
    }

    if (doc.doctype().name() == KXMLQLCFixtureDefDocument)
    {
        if (loadXML(doc) == true)
            error = QFile::NoError;
        else
            error = QFile::ReadError;
    }
    else
    {
        error = QFile::ReadError;
        qWarning() << Q_FUNC_INFO << fileName
                   << "is not a fixture definition file";
    }

    return error;
}
예제 #3
0
extern "C" void qdom_do_doc_type( struct qdom_doc *doc, char **name )
{
    if ( !doc )
    {
        *name = 0;
        return;
    }
    QDomDocument *document = (QDomDocument *)doc->Document;
    QString str = document->doctype().name();
    const char *q_name = str.latin1();
    if ( q_name )
    {
        *name = new char[strlen(q_name)+1];
        strcpy( *name, q_name );
    }
    else
    {
        *name = 0;
    }
}
예제 #4
0
void QLCFile_Test::getXMLHeader()
{
    bool insideCreatorTag = false, author = false, appname = false,
         appversion = false;
    QDomDocument doc;

    doc = QLCFile::getXMLHeader(QString());
    QVERIFY(doc.isNull() == true);

    doc = QLCFile::getXMLHeader("Settings");
    QVERIFY(doc.isNull() == false);
    QCOMPARE(doc.doctype().name(), QString("Settings"));

    QDomNode node(doc.firstChild());
    QCOMPARE(node.toElement().tagName(), QString("Settings"));
    node = node.firstChild();
    QCOMPARE(node.toElement().tagName(), QString("Creator"));
    node = node.firstChild();
    while (node.isNull() == false)
    {
        // Verify that program enters this while loop
        insideCreatorTag = true;

        QDomElement tag(node.toElement());
        if (tag.tagName() == KXMLQLCCreatorAuthor)
            author = true; // User might not have a full name so don't check the contents
        else if (tag.tagName() == KXMLQLCCreatorName)
            appname = true;
        else if (tag.tagName() == KXMLQLCCreatorVersion)
            appversion = true;
        else
            QFAIL(QString("Unrecognized tag: %1").arg(tag.tagName()).toUtf8().constData());

        node = node.nextSibling();
    }

    QCOMPARE(insideCreatorTag, true);
    QCOMPARE(author, true);
    QCOMPARE(appname, true);
    QCOMPARE(appversion, true);
}
예제 #5
0
bool CAnm2DXml::load(const QDomDocument &xml)
{
	if ( xml.doctype().name() != kAnmXML_ID_Anm2D ) {
		return false ;
	}

	QDomElement root = xml.documentElement() ;
	if ( root.isNull() ) {
		return false ;
	}
	if ( root.nodeName() != kAnmXML_ID_Root ) {
		return false ;
	}

	QDomNamedNodeMap nodeMap = root.attributes() ;
	if ( nodeMap.isEmpty() ) {
		return false ;
	}
	if ( nodeMap.namedItem(kAnmXML_Attr_Version).isNull() ) {
		return false ;
	}
	int version = nodeMap.namedItem(kAnmXML_Attr_Version).toAttr().value().toInt() ;
	if ( version != kAnmXML_Version ) {
		return false ;
	}

	if ( nodeMap.namedItem(kAnmXML_Attr_ObjNum).isNull() ) {
		return false ;
	}
	if ( nodeMap.namedItem(kAnmXML_Attr_ImageNum).isNull() ) {
		return false ;
	}
	int objNum = nodeMap.namedItem(kAnmXML_Attr_ObjNum).toAttr().value().toInt() ;
	int imageNum = nodeMap.namedItem(kAnmXML_Attr_ImageNum).toAttr().value().toInt() ;

	QDomNode n = root.firstChild() ;
	return loadElement(n, objNum, imageNum) ;
}
예제 #6
0
OldSoundThemeProvider::OldSoundThemeProvider(const QString &name, const QString &path, QString variant)
{
	m_themeName = name;
	const Notification::Type xmlEventTypes[] = {
		Notification::IncomingMessage,
		Notification::OutgoingMessage,
		Notification::AppStartup,
		Notification::BlockedMessage,
		Notification::ChatUserJoined,
		Notification::ChatUserLeft,
		Notification::ChatIncomingMessage,
		Notification::ChatOutgoingMessage,
		Notification::FileTransferCompleted,
		Notification::UserOnline,
		Notification::UserOffline,
		Notification::UserChangedStatus,
		Notification::UserHasBirthday,
		Notification::UserTyping,
		Notification::System,
		Notification::Attention,
	    // And again some of them for legacy names
		Notification::UserOnline,
		Notification::UserOffline,
		Notification::UserChangedStatus,
		Notification::UserHasBirthday,
		Notification::AppStartup,
		Notification::IncomingMessage,
		Notification::ChatIncomingMessage,
		Notification::OutgoingMessage,
		Notification::ChatOutgoingMessage,
		Notification::System,
		Notification::UserTyping,
		Notification::BlockedMessage
	};
	const char* const xmlEventNames[] = {
		"IncomingMessage",
		"OutgoingMessage",
		"AppStartup",
		"BlockedMessage",
		"ChatUserJoined",
		"ChatUserLeft",
		"ChatIncomingMessage",
		"ChatOutgoingMessage",
		"FileTransferCompleted",
		"UserOnline",
		"UserOffline",
		"UserChangedStatus",
		"UserHasBirthday",
		"UserTyping",
		"System",
		"Attention",
		"c_online",
		"c_offline",
		"c_changed_status",
		"c_birth",
		"start",
		"m_get",
		"m_chat_get",
		"m_send",
		"m_chat_send",
		"sys_event",
		"c_typing",
		"c_blocked_message"
	};
	const int eventsCount = sizeof(xmlEventTypes) / sizeof(xmlEventTypes[0]);

	Q_ASSERT(sizeof(xmlEventTypes) / sizeof(xmlEventTypes[0]) == sizeof(xmlEventNames) / sizeof(xmlEventNames[0]));

	QDir dir(path);
	if (variant.isEmpty())
		variant = dir.entryList(QStringList("*.xml"), QDir::Files).value(0);
	else
		variant += ".xml";
	QFile file(dir.filePath(variant));
	if (file.open(QIODevice::ReadOnly)) {
		QDomDocument doc;
		doc.setContent(&file);
		if (doc.doctype().name() != QLatin1String("qutimsounds"))
			return;
		QDomElement rootElement = doc.documentElement();
		QDomNodeList soundsNodeList = rootElement.elementsByTagName("sounds");
		if (soundsNodeList.count() != 1)
			return;
		QDomElement soundsElement = soundsNodeList.at(0).toElement();
		soundsNodeList = soundsElement.elementsByTagName("sound");
		QDomElement soundElement;
		QString eventName, soundFileName;

		for (int i = 0; i < soundsNodeList.count(); i++) {
			soundElement = soundsNodeList.at(i).toElement();
			eventName = soundElement.attribute("event");
			if (eventName.isEmpty() || !soundElement.elementsByTagName("file").count())
				continue;
			soundFileName = dir.filePath(soundElement.elementsByTagName("file").at(0).toElement().text());
			if (!QFile::exists(soundFileName)) 
				continue;
			for (int i = 0; i < eventsCount; i++) {
				if (eventName == QLatin1String(xmlEventNames[i])) {
					m_map.insert(xmlEventTypes[i], soundFileName);
					break;
				}
			}
		}
		m_filePath = file.fileName();
	}
}
예제 #7
0
bool MainWindow2::openObject( QString strFilePath )
{
    QProgressDialog progress( tr("Opening document..."), tr("Abort"), 0, 100, this );
    progress.setWindowModality( Qt::WindowModal );
    progress.show();

    editor->setCurrentLayer( 0 );
    editor->layerManager()->setCurrentFrameIndex( 1 );
    editor->fps = 12;
    m_pTimeLine->setFps( editor->fps );
    m_pScribbleArea->setMyView( QMatrix() );

    ObjectSaveLoader objectLoader( this );
    Object* pObject = objectLoader.loadFromFile( strFilePath );

    if ( pObject != NULL && objectLoader.error().code() == PCL_OK )
    {
        SafeDelete( m_object );
        m_object = pObject;

        pObject->setFilePath( strFilePath );
        QSettings settings( "Pencil", "Pencil" );
        settings.setValue( "lastFilePath", QVariant( pObject->filePath() ) );

        editor->setObject( pObject );
        editor->updateObject();

        m_recentFileMenu->addRecentFile( pObject->filePath() );
        m_recentFileMenu->saveToDisk();

        qDebug() << "Current File Path=" << pObject->filePath();
        setWindowTitle( pObject->filePath() );
    }
    else
    {
        return false;
    }
    return true;

    //-------------------
    QString filePath = strFilePath;

    bool openingTheOLDWAY = true;
    QString realXMLFilePath = filePath;
    QString tmpFilePath;

    // ---- test before opening ----
    QStringList zippedFileList = JlCompress::getFileList( filePath );
    if ( !zippedFileList.empty() )
    {
        qDebug() << "Recognized New zipped Pencil File Format !";
        openingTheOLDWAY = false;

        // ---- now decompress PFF -----
        QFileInfo fileInfo( filePath );
        QDir dir( QDir::tempPath() );
        tmpFilePath = QDir::tempPath() + "/" + fileInfo.completeBaseName() + PFF_TMP_DECOMPRESS_EXT;
        if ( fileInfo.exists() ) {
            dir.rmpath( tmpFilePath ); // --removes an old decompression directory
            removePFFTmpDirectory( tmpFilePath ); // --removes an old decompression directory - better approach
        }
        dir.mkpath( tmpFilePath ); // --creates a new decompression directory

        JlCompress::extractDir( filePath, tmpFilePath );

        realXMLFilePath = tmpFilePath + "/" + PFF_XML_FILE_NAME;
    }
    else
    {
        qDebug() << "Recognized Old Pencil File Format !";
    }

    QScopedPointer<QFile> file( new QFile( realXMLFilePath ) );

    //QFile* file = new QFile(filePath);
    if ( !file->open( QFile::ReadOnly ) )
    {
        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        return false;
    }

    QDomDocument doc;
    if ( !doc.setContent( file.data() ) )
    {
        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        return false; // this is not a XML file
    }
    QDomDocumentType type = doc.doctype();
    if ( type.name() != "PencilDocument" && type.name() != "MyObject" )
    {
        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        return false; // this is not a Pencil document
    }

    // delete old object @sent foreward -> if (ok)
    /*if (m_object != NULL)
    {
    m_object->deleteLater();
    }*/

    // -----------------------------


    //QSettings settings("Pencil","Pencil");
    //settings.setValue("lastFilePath", QVariant(object->strCurrentFilePath) );

    QString dataLayersDir;
    if ( openingTheOLDWAY )
    {
        dataLayersDir = filePath + "." + PFF_LAYERS_DIR;
    }
    else
    {
        dataLayersDir = tmpFilePath + "/" + PFF_LAYERS_DIR;
    }

    Object* newObject = new Object();
    if ( !newObject->loadPalette( dataLayersDir ) )
    {
        newObject->loadDefaultPalette();
    }
    editor->setObject( newObject );

    newObject->setFilePath( filePath );

    // ------- reads the XML file -------
    bool ok = true;
    int progVal = 0;
    QDomElement docElem = doc.documentElement();
    if ( docElem.isNull() )
    {
        return false;
    }

    if ( docElem.tagName() == "document" )
    {
        qDebug( "Object Loader: start." );

        qreal rProgressValue = 0;
        qreal rProgressDelta = 100 / docElem.childNodes().count();

        QDomNode tag = docElem.firstChild();

        while ( !tag.isNull() )
        {
            QDomElement element = tag.toElement(); // try to convert the node to an element.
            if ( !element.isNull() )
            {
                progVal = qMin( (int)rProgressValue, 100 );
                progress.setValue( progVal );
                rProgressValue += rProgressDelta;

                if ( element.tagName() == "editor" )
                {
                    qDebug( "  Load editor" );
                    loadDomElement( element, filePath );
                }
                else if ( element.tagName() == "object" )
                {
                    qDebug( "  Load object" );
                    ok = newObject->loadDomElement( element, dataLayersDir );
                    qDebug() << "    dataDir:" << dataLayersDir;
                }
            }
            tag = tag.nextSibling();
        }
    }
    else
    {
        if ( docElem.tagName() == "object" || docElem.tagName() == "MyOject" )   // old Pencil format (<=0.4.3)
        {
            ok = newObject->loadDomElement( docElem, filePath );
        }
    }

    // ------------------------------
    if ( ok )
    {
        editor->updateObject();

        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }

        m_recentFileMenu->addRecentFile( filePath );
        m_recentFileMenu->saveToDisk();

        //qDebug() << "Current File Path=" << newObject->strCurrentFilePath;
        setWindowTitle( newObject->filePath() );

        // FIXME: need to free the old object. but delete object will crash app, don't know why.
        // fixed by shoshon... don't know if it's right
        Object* objectToDelete = m_object;
        m_object = newObject;
        if ( objectToDelete != NULL )
        {
            delete objectToDelete;
        }
    }

    progress.setValue( 100 );
    return true;
}
예제 #8
0
bool MainWindow2::openObject(QString filePath)
{
    // ---- test before opening ----
    QScopedPointer<QFile> file(new QFile(filePath));

    //QFile* file = new QFile(filePath);
    if (!file->open(QFile::ReadOnly))
    {
        return false;
    }

    QDomDocument doc;
    if (!doc.setContent(file.data()))
    {
        return false; // this is not a XML file
    }
    QDomDocumentType type = doc.doctype();
    if (type.name() != "PencilDocument" && type.name() != "MyObject")
    {
        return false; // this is not a Pencil document
    }

    // delete old object
    if (m_object != NULL)
    {
        m_object->deleteLater();
    }

    // -----------------------------

    QProgressDialog progress("Opening document...", "Abort", 0, 100, this);
    progress.setWindowModality(Qt::WindowModal);
    progress.show();

    //QSettings settings("Pencil","Pencil");
    //settings.setValue("lastFilePath", QVariant(object->strCurrentFilePath) );

    Object* newObject = new Object();
    if (!newObject->loadPalette(filePath+".data"))
    {
        newObject->loadDefaultPalette();
    }
    editor->setObject(newObject);

    newObject->strCurrentFilePath = filePath;

    // ------- reads the XML file -------
    bool ok = true;
    int prog = 0;
    QDomElement docElem = doc.documentElement();
    if (docElem.isNull())
    {
        return false;
    }

    if (docElem.tagName() == "document")
    {
        qDebug("Object Loader: start.");

        QDomNode tag = docElem.firstChild();
        while (!tag.isNull())
        {
            QDomElement element = tag.toElement(); // try to convert the node to an element.
            if (!element.isNull())
            {
                prog += std::min(prog + 10, 100);
                progress.setValue(prog);

                if (element.tagName() == "editor")
                {
                    qDebug("  Load editor");
                    loadDomElement(element, filePath);
                }
                else if (element.tagName() == "object")
                {
                    qDebug("  Load object");
                    ok = newObject->loadDomElement(element, filePath);
                    qDebug() << "    filePath:" << filePath;
                }
            }
            tag = tag.nextSibling();
        }
    }
    else
    {
        if (docElem.tagName() == "object" || docElem.tagName() == "MyOject")   // old Pencil format (<=0.4.3)
        {
            ok = newObject->loadDomElement(docElem, filePath);
        }
    }

    // ------------------------------
    if (ok)
    {
        editor->updateObject();

        qDebug() << "Current File Path=" << newObject->strCurrentFilePath;
        setWindowTitle(newObject->strCurrentFilePath);

        // FIXME: need to free the old object. but delete object will crash app, don't know why.
        m_object = newObject;
    }

    progress.setValue(100);
    return ok;
}
예제 #9
0
void Autocorrect::readAutocorrectXmlEntry()
{
    // Taken from KOffice 1.x KoAutoFormat.cpp
    KLocale *locale = KGlobal::locale();
    QString kdelang = locale->languageList().first();
    kdelang.remove(QRegExp("@.*"));

    QString fname;
    if (!m_autocorrectLang.isEmpty())
        fname = KGlobal::dirs()->findResource("data", "koffice/autocorrect/" + m_autocorrectLang + ".xml");
    if (m_autocorrectLang != "all_languages") {
        if (fname.isEmpty() && !kdelang.isEmpty())
            fname = KGlobal::dirs()->findResource("data", "koffice/autocorrect/" + kdelang + ".xml");
        if (fname.isEmpty() && kdelang.contains("_")) {
            kdelang.remove( QRegExp( "_.*" ) );
            fname = KGlobal::dirs()->findResource("data", "koffice/autocorrect/" + kdelang + ".xml");
        }
        if (fname.isEmpty())
            fname = KGlobal::dirs()->findResource("data", "koffice/autocorrect/autocorrect.xml");
    }
    if (m_autocorrectLang.isEmpty())
        m_autocorrectLang = kdelang;

    if (fname.isEmpty())
        return;

    QFile xmlFile(fname);
    if (!xmlFile.open(QIODevice::ReadOnly))
        return;

    QDomDocument doc;
    if (!doc.setContent(&xmlFile))
        return;

    if (doc.doctype().name() != "autocorrection")
        return;

    QDomElement de = doc.documentElement();

    QDomElement upper = de.namedItem("UpperCaseExceptions").toElement();
    if (!upper.isNull()) {
        QDomNodeList nl = upper.childNodes();
        for (int i = 0; i < nl.count(); i++)
            m_upperCaseExceptions += nl.item(i).toElement().attribute("exception");
    }

    QDomElement twoUpper = de.namedItem("TwoUpperLetterExceptions").toElement();
    if (!twoUpper.isNull()) {
        QDomNodeList nl = twoUpper.childNodes();
        for(int i = 0; i < nl.count(); i++)
            m_twoUpperLetterExceptions += nl.item(i).toElement().attribute("exception");
    }

    QDomElement superScript = de.namedItem("SuperScript").toElement();
    if (!superScript.isNull()) {
        QDomNodeList nl = superScript.childNodes();
        for(int i = 0; i < nl.count() ; i++)
            m_superScriptEntries.insert(nl.item(i).toElement().attribute("find"), nl.item(i).toElement().attribute("super"));
    }

    /* Load advanced autocorrect entry, including the format */
    QDomElement item = de.namedItem("items").toElement();
    if (!item.isNull())
    {
        QDomNodeList nl = item.childNodes();
        for (int i = 0; i < nl.count(); i++) {
            QDomElement element = nl.item(i).toElement();
            QString find = element.attribute("find");
            QString replace = element.attribute("replace");
            /* AutocorrectEntry entry;
            entry.replace = element.attribute("replace");
            if (element.hasAttribute("FONT"))
                entry.format.setFontFamily(element.attribute("FONT"));
            if (element.hasAttribute("SIZE"))
                entry.format.setFontPointSize(element.attribute("SIZE").toInt());
            if (element.hasAttribute("BOLD"))
                entry.format.setFontWeight(QFont::Bold);
            if (element.hasAttribute("ITALIC"))
                entry.format.setFontItalic(true);
            if (element.hasAttribute("UNDERLINE"))
                entry.format.setFontUnderline(true);
            if (element.hasAttribute("STRIKEOUT"))
                entry.format.setFontStrikeOut(true);
            if (element.hasAttribute("VERTALIGN"))
                entry.format.setVerticalAlignment(static_cast<QTextCharFormat::VerticalAlignment>(element.attribute("VERTALIGN").toInt()));
            if (element.hasAttribute("TEXTCOLOR"))
                ; // entry.format.setForeground(QBrush(QColor::(element.attribute("TEXTCOLOR"))));
            if (element.hasAttribute("TEXTBGCOLOR"))
                ; // entry.format.setBackground(QBrush(QColor(element.attribute("TEXTBGCOLOR"))));
            */
            m_autocorrectEntries.insert(find, replace);
        }
    }
}
예제 #10
0
Object* FileManager::load( QString strFileName )
{
    if ( !QFile::exists( strFileName ) )
    {
        qCDebug( mLog ) << "ERROR - File doesn't exist.";
        return cleanUpWithErrorCode( Status::FILE_NOT_FOUND );
    }

    emit progressUpdated( 0.f );

    Object* obj = new Object;
    obj->setFilePath( strFileName );
    obj->createWorkingDir();

    QString strMainXMLFile;	
    QString strDataFolder;

    // Test file format: new zipped .pclx or old .pcl?
    bool oldFormat = isOldForamt( strFileName );

    if ( oldFormat )
    {
        qCDebug( mLog ) << "Recognized Old Pencil File Format (*.pcl) !";

        strMainXMLFile = strFileName;
        strDataFolder  = strMainXMLFile + "." + PFF_OLD_DATA_DIR;
    }
    else
    {
        qCDebug( mLog ) << "Recognized New zipped Pencil File Format (*.pclx) !";

        unzip( strFileName, obj->workingDir() );

        strMainXMLFile = QDir( obj->workingDir() ).filePath( PFF_XML_FILE_NAME );
        strDataFolder  = QDir( obj->workingDir() ).filePath( PFF_DATA_DIR );
    }

    qDebug() << "XML=" << strMainXMLFile;
    qDebug() << "Data Folder=" << strDataFolder;
    qDebug() << "Working Folder=" << obj->workingDir();

    obj->setDataDir( strDataFolder );
    obj->setMainXMLFile( strMainXMLFile );

    QFile file( strMainXMLFile );
    if ( !file.open( QFile::ReadOnly ) )
    {
        return cleanUpWithErrorCode( Status::ERROR_FILE_CANNOT_OPEN );
    }

    qCDebug( mLog ) << "Checking main XML file...";
    QDomDocument xmlDoc;
    if ( !xmlDoc.setContent( &file ) )
    {
        return cleanUpWithErrorCode( Status::ERROR_INVALID_XML_FILE );
    }

    QDomDocumentType type = xmlDoc.doctype();
    if ( !( type.name() == "PencilDocument" || type.name() == "MyObject" ) )
    {
        return cleanUpWithErrorCode( Status::ERROR_INVALID_PENCIL_FILE );
    }

    QDomElement root = xmlDoc.documentElement();
    if ( root.isNull() )
    {
        return cleanUpWithErrorCode( Status::ERROR_INVALID_PENCIL_FILE );
    }
    
    // Create object.
    qCDebug( mLog ) << "Start to load object..";

    loadPalette( obj );

    bool ok = true;
    
    if ( root.tagName() == "document" )
    {
        ok = loadObject( obj, root );
    }
    else if ( root.tagName() == "object" || root.tagName() == "MyOject" ) // old Pencil format (<=0.4.3)
    {
        ok = loadObjectOldWay( obj, root );
    }

    if ( !ok )
    {
        delete obj;
        return cleanUpWithErrorCode( Status::ERROR_INVALID_PENCIL_FILE );
    }
    
    verifyObject( obj );
    
    return obj;
}
예제 #11
0
Object* ObjectSaveLoader::loadFromFile( QString strFilename )
{
    // ---- test before opening ----

    if ( !isFileExists( strFilename ) )
    {
        m_error = PencilError( PCL_ERROR_FILE_NOT_EXIST );
        return NULL;
    }

    QString strMainXMLFilePath = strFilename;
    QStringList zippedFileList = JlCompress::getFileList( strFilename );

    // -- Test file format: new zipped pclx or old pcl ?
    bool bIsOldPencilFile = zippedFileList.empty();
    if ( !bIsOldPencilFile )
    {
        strMainXMLFilePath = extractZipToTempFolder( strFilename );
        qDebug() << "Recognized New zipped Pencil File Format !";
    }
    else
    {
        qDebug() << "Recognized Old Pencil File Format !";
    }

    // -- test before opening
    QScopedPointer<QFile> file( new QFile( strMainXMLFilePath ) );

    if ( !file->open( QFile::ReadOnly ) )
    {
        //m_strLastErrorMessage = tr("Cannot open file.");
        m_error = PencilError( PCL_ERROR_FILE_CANNOT_OPEN );
        cleanUpTempFolder();
        return NULL;
    }

    QDomDocument xmlDoc;
    if ( !xmlDoc.setContent( file.data() ) )
    {
        //m_strLastErrorMessage = tr("This file is not a valid XML document.");
        m_error = PencilError( PCL_ERROR_INVALID_XML_FILE );
        cleanUpTempFolder();
        return NULL;
    }

    QDomDocumentType type = xmlDoc.doctype();
    if ( type.name() != "PencilDocument" && type.name() != "MyObject" )
    {
        //m_strLastErrorMessage = tr("This file is not a Pencil2D document.");
        m_error = PencilError( PCL_ERROR_INVALID_PENCIL_FILE );
        cleanUpTempFolder();
        return NULL; // this is not a Pencil document
    }

    Object* pObject = new Object();

    QString strDataLayersDirPath;
    if ( bIsOldPencilFile )
    {
        // ex. aaa.pcl  => aaa.pcl.data
        strDataLayersDirPath = strMainXMLFilePath + "." + PFF_LAYERS_DIR;
    }
    else
    {
        QDir workingDir = QFileInfo( strMainXMLFilePath ).dir(); // get the parent folder
        workingDir.cd( PFF_LAYERS_DIR );
        strDataLayersDirPath = workingDir.absolutePath();
    }

    Object* newObject = pObject;
    if ( !newObject->loadPalette( strDataLayersDirPath ) )
    {
        newObject->loadDefaultPalette();
    }

    // ------- reads the XML file -------
    bool ok = true;
    int prog = 0;
    QDomElement docElem = xmlDoc.documentElement();
    if ( docElem.isNull() )
    {
        return NULL;
    }

    if ( docElem.tagName() == "document" )
    {
        qDebug( "Object Loader: start." );

        QDomNode tag = docElem.firstChild();
        while ( !tag.isNull() )
        {
            QDomElement element = tag.toElement(); // try to convert the node to an element.
            if ( !element.isNull() )
            {
                prog += std::min( prog + 10, 100 );
                //progress.setValue(prog);
                emit progressValueChanged( prog );

                if ( element.tagName() == "editor" )
                {
                    qDebug( "  Load editor" );
                    //loadDomElement( element );
                }
                else if ( element.tagName() == "object" )
                {
                    qDebug( "  Load object" );
                    ok = newObject->loadDomElement( element, strDataLayersDirPath );
                    qDebug() << "    dataDir:" << strDataLayersDirPath;
                }
            }
            tag = tag.nextSibling();
        }
    }
    else
    {
        if ( docElem.tagName() == "object" || docElem.tagName() == "MyOject" )   // old Pencil format (<=0.4.3)
        {
            ok = newObject->loadDomElement( docElem, strFilename );
        }
    }

    if ( ok )
    {
        /*
        if (!openingTheOLDWAY)
        {
        removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        */
    }
    else
    {
        return NULL;
    }

    return pObject;
}
예제 #12
0
void
OpenBalances::slotImport()
{
    QString start = "";
    QString filter = "Import Files (*.xml)";

    QString filePath = QFileDialog::getOpenFileName(start, filter, this);
    if (filePath.isEmpty()) return;

    QFile file(filePath);
    if (!file.open(IO_ReadOnly)) {
	QString message = tr("Can't open import file: %1").arg(filePath);
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    QApplication::setOverrideCursor(waitCursor);
    qApp->processEvents();

    QDomDocument doc;
    QString errorMsg;
    int errorLine, errorCol;
    if (!doc.setContent(&file, &errorMsg, &errorLine, &errorCol)) {
	QApplication::restoreOverrideCursor();
	qApp->beep();

	QString message = tr("Error processing the import file on line\n"
			     "%1, column %2:\n\n%3").arg(errorLine)
			     .arg(errorCol).arg(errorMsg);

	QMessageBox::critical(this, tr("Error"), message);
	return;
    }
    if (doc.doctype().name() != "BALANCES") {
	QApplication::restoreOverrideCursor();
	qApp->beep();

	QString message = tr("The import file is not the right type of\n"
			     "XML file for Quasar to use.");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }
    file.close();

    _errors = 0;
    _customers->clear();
    _vendors->clear();
    _items->clear();
    _accounts->clear();

    QDomElement root = doc.documentElement();
    unsigned int i;
    for (i = 0; i < root.childNodes().count(); ++i) {
	QDomNode node = root.childNodes().item(i);
	if (node.isNull()) continue;

	QDomElement e = node.toElement();
	if (e.isNull()) continue;

	QString tag = e.tagName();
	QString text = e.text();

	QDomNodeList nodes = e.childNodes();

	if (tag == "account") {
	    QDomNodeList nodes = e.childNodes();
	    importAccount(nodes);
	} else if (tag == "customer") {
	    QDomNodeList nodes = e.childNodes();
	    importCustomer(nodes);
	} else if (tag == "vendor") {
	    QDomNodeList nodes = e.childNodes();
	    importVendor(nodes);
	} else if (tag == "item") {
	    QDomNodeList nodes = e.childNodes();
	    importItem(nodes);
	} else {
	    warning("Unknown tag: " + tag);
	}
    }

    _customers->appendRow(new VectorRow(_customers->columns()));
    _vendors->appendRow(new VectorRow(_vendors->columns()));
    _items->appendRow(new VectorRow(_items->columns()));
    _accounts->appendRow(new VectorRow(_accounts->columns()));

    recalculate();

    QApplication::restoreOverrideCursor();
    qApp->beep();

    if (_errors == 0) {
	QString message = tr("Import completed successfully");
	QMessageBox::information(this, tr("Status"), message);
    } else {
	QString message;
	if (_errors == 1)
	    message = tr("Import completed with %1 error").arg(_errors);
	else
	    message = tr("Import completed with %1 errors").arg(_errors);
	QMessageBox::critical(this, tr("Status"), message);
    }
}