KisAutoSaveRecoveryDialog::KisAutoSaveRecoveryDialog(const QStringList &filenames, QWidget *parent) :
    KoDialog(parent)
{
    setCaption(i18nc("@title:window", "Recover Files"));
    setButtons( KoDialog::Ok | KoDialog::Cancel | KoDialog::User1 );
    setButtonText(KoDialog::User1, i18n("Discard All"));
    setMinimumSize(650, 500);
    QWidget *page = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(page);
    if (filenames.size() == 1) {
        layout->addWidget(new QLabel(i18n("The following autosave file can be recovered:")));
    }
    else {
        layout->addWidget(new QLabel(i18n("The following autosave files can be recovered:")));
    }

    m_listView = new QListView();
    m_listView->setAcceptDrops(false);
    KWidgetItemDelegate *delegate = new FileItemDelegate(m_listView, this);
    m_listView->setItemDelegate(delegate);

    QList<FileItem*> fileItems;
    Q_FOREACH (const QString &filename, filenames) {

        FileItem *file = new FileItem();
        file->name = filename;

#ifdef Q_OS_WIN
        QString path = QDir::tempPath() + "/" + filename;
#else
        QString path = QDir::homePath() + "/" + filename;
#endif

        // get thumbnail -- all calligra apps save a thumbnail
        KoStore* store = KoStore::createStore(path, KoStore::Read);

        if (store && (store->open(QString("Thumbnails/thumbnail.png"))
                          || store->open(QString("preview.png")))) {
            // Hooray! No long delay for the user...
            QByteArray bytes = store->read(store->size());
            store->close();
            delete store;
            QImage img;
            img.loadFromData(bytes);
            file->thumbnail = img.scaled(QSize(200,200), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }

        // get the date
        QDateTime date = QFileInfo(path).lastModified();
        file->date = "(" + date.toString(Qt::LocalDate) + ")";

        fileItems.append(file);
    }
Example #2
0
bool KOfficePlugin::readInfo( KFileMetaInfo& info, uint what)
{
    if ( info.path().isEmpty() ) // remote file
        return false;

    KFileMetaInfoGroup group = appendGroup(info, "DocumentInfo");

    KoStore* store = KoStore::createStore(info.path(), KoStore::Read);
    if ( store && store->open( QString("documentinfo.xml") ) )
    {
        KoStoreDevice dev( store );
        QDomDocument doc;
        doc.setContent( &dev );

        QDomNode authorNode = doc.namedItem("document-info").namedItem("author");
        QDomNode aboutNode = doc.namedItem("document-info").namedItem("about");

        QString author = stringFromNode(authorNode, "full-name");
        QString title = stringFromNode(aboutNode, "title");
        QString abstract = stringFromNode(aboutNode, "abstract");

        appendItem(group, "Author", author);
        appendItem(group, "Title", title);
        appendItem(group, "Abstract", abstract);

        store->close();
        delete store;
        return true;
    }
    delete store;
    return false;
}
Example #3
0
void KisPaintDeviceTest::testStore()
{

    const KoColorSpace * cs = KoColorSpaceRegistry::instance()->rgb8();
    KisPaintDeviceSP dev = new KisPaintDevice(cs);

    KoStore * readStore =
        KoStore::createStore(QString(FILES_DATA_DIR) + QDir::separator() + "store_test.kra", KoStore::Read);
    readStore->open("built image/layers/layer0");
    QVERIFY(dev->read(readStore->device()));
    readStore->close();
    delete readStore;

    QVERIFY(dev->exactBounds() == QRect(0, 0, 100, 100));

    KoStore * writeStore =
        KoStore::createStore(QString(FILES_OUTPUT_DIR) + QDir::separator() + "store_test_out.kra", KoStore::Write);
    KisFakePaintDeviceWriter fakeWriter(writeStore);
    writeStore->open("built image/layers/layer0");
    QVERIFY(dev->write(fakeWriter));
    writeStore->close();
    delete writeStore;

    KisPaintDeviceSP dev2 = new KisPaintDevice(cs);
    readStore =
        KoStore::createStore(QString(FILES_OUTPUT_DIR) + QDir::separator() + "store_test_out.kra", KoStore::Read);
    readStore->open("built image/layers/layer0");
    QVERIFY(dev2->read(readStore->device()));
    readStore->close();
    delete readStore;

    QVERIFY(dev2->exactBounds() == QRect(0, 0, 100, 100));

    QPoint pt;
    if (!TestUtil::comparePaintDevices(pt, dev, dev2)) {
        QFAIL(QString("Loading a saved image is not pixel perfect, first different pixel: %1,%2 ").arg(pt.x()).arg(pt.y()).toLatin1());
    }

}
Example #4
0
QObject *KoScriptingOdfStore::open(const QString &fileName)
{
    delete m_reader; m_reader = 0;
    KoStore *store = getReadStore();
    if (! store)
        return 0;
    if (store->isOpen())
        store->close();
    if (! store->open(fileName)) {
        kWarning(32010) <<"KoScriptingOdfStore::openFile() Failed to open file:"<<fileName;
        return 0;
    }
    //kDebug(32010) <<"KoScriptingOdfStore::openFile() fileName="<<fileName<<" store->isOpen="<<store->isOpen()<<endl;
    Q_ASSERT(store->device());

    //KoOasisStore oasisStore(store);
    KoXmlDocument doc;

    QString errorMsg;
    int errorLine, errorColumn;
    if (! doc.setContent(store->device(), &errorMsg, &errorLine, &errorColumn)) {
       kWarning(32010) << "Parse-Error message" << errorMsg << "line" << errorLine << "col" << errorColumn;
       return 0;
    }

    const QString tagName = doc.documentElement().tagName();
    kDebug(32010) <<"KoScriptingOdfStore::open documentElement.tagName="<<tagName;
    if (tagName == "office:document-content")
        m_reader = new KoScriptingOdfContentReader(this, doc);
    if (tagName == "office:document-styles")
        m_reader = new KoScriptingOdfStylesReader(this, doc);
    else if (tagName == "manifest:manifest")
        m_reader = new KoScriptingOdfManifestReader(this, doc);
    else
        m_reader = new KoScriptingOdfReader(this, doc);
    return m_reader;
}
Example #5
0
bool DocBase::saveOdfHelper(SavingContext & documentContext, SaveFlag saveFlag,
                            QString* /*plainText*/)
{
    Q_UNUSED(saveFlag);
    KoStore * store = documentContext.odfStore.store();
    KoXmlWriter * manifestWriter = documentContext.odfStore.manifestWriter();

    KoStoreDevice dev(store);
    KoGenStyles mainStyles;//for compile

    KoXmlWriter* contentWriter = documentContext.odfStore.contentWriter();

    KoXmlWriter* bodyWriter = documentContext.odfStore.bodyWriter();
    KoShapeSavingContext savingContext(*bodyWriter, mainStyles, documentContext.embeddedSaver);

    //todo fixme just add a element for testing saving content.xml
    bodyWriter->startElement("office:body");
    bodyWriter->startElement("office:spreadsheet");

    // Saving the map.
    map()->saveOdf(*contentWriter, savingContext);

    bodyWriter->endElement(); ////office:spreadsheet
    bodyWriter->endElement(); ////office:body

    // Done with writing out the contents to the tempfile, we can now write out the automatic styles
    mainStyles.saveOdfStyles(KoGenStyles::DocumentAutomaticStyles, contentWriter);

    documentContext.odfStore.closeContentWriter();

    //add manifest line for content.xml
    manifestWriter->addManifestEntry("content.xml",  "text/xml");

    mainStyles.saveOdfStylesDotXml(store, manifestWriter);

    if (!store->open("settings.xml"))
        return false;

    KoXmlWriter* settingsWriter = KoOdfWriteStore::createOasisXmlWriter(&dev, "office:document-settings");
    settingsWriter->startElement("office:settings");
    settingsWriter->startElement("config:config-item-set");
    settingsWriter->addAttribute("config:name", "view-settings");

    saveUnitOdf(settingsWriter);

    saveOdfSettings(*settingsWriter);

    settingsWriter->endElement(); // config:config-item-set

    settingsWriter->startElement("config:config-item-set");
    settingsWriter->addAttribute("config:name", "configuration-settings");
    settingsWriter->addConfigItem("SpellCheckerIgnoreList", d->spellListIgnoreAll.join(","));
    settingsWriter->endElement(); // config:config-item-set
    settingsWriter->endElement(); // office:settings
    settingsWriter->endElement(); // Root:element
    settingsWriter->endDocument();
    delete settingsWriter;

    if (!store->close())
        return false;

    if (!savingContext.saveDataCenter(store, manifestWriter)) {
        return false;
    }

    manifestWriter->addManifestEntry("settings.xml", "text/xml");

    setModified(false);

    return true;
}
Example #6
0
KoFilter::ConversionStatus ExportHtml::convert(const QByteArray &from, const QByteArray &to)
{
    // Check mimetypes
    if (from != "application/vnd.oasis.opendocument.text" || to != "text/html") {
        return KoFilter::NotImplemented;
    }

    // Open the infile and return an error if it fails.
    KoStore *odfStore = KoStore::createStore(m_chain->inputFile(), KoStore::Read,
                                             "", KoStore::Auto);
    if (!odfStore->open("mimetype")) {
        kError(30503) << "Unable to open input file!" << endl;
        delete odfStore;
        return KoFilter::FileNotFound;
    }
    odfStore->close();

    // Start the conversion
    KoFilter::ConversionStatus  status;

    // ----------------------------------------------------------------
    // Parse input files

    OdfParser        odfParser;

    // Parse meta.xml into m_metadata
    status = odfParser.parseMetadata(odfStore, m_metadata);
    if (status != KoFilter::OK) {
        delete odfStore;
        return status;
    }

    // Parse manifest
    status = odfParser.parseManifest(odfStore, m_manifest);
    if (status != KoFilter::OK) {
        delete odfStore;
        return status;
    }

    // ----------------------------------------------------------------
    // Create content files.

    // Create html contents.
    // m_imagesSrcList is an output parameter from the conversion.
    HtmlFile html;
    html.setPathPrefix("./");
    const QString outputFileName = m_chain->outputFile().section('/', -1);
    const int dotPosition = outputFileName.indexOf('.');
    html.setFilePrefix(outputFileName.left(dotPosition));
    html.setFileSuffix(dotPosition != -1 ? outputFileName.mid(dotPosition) : QString());
    OdtHtmlConverter converter;
    OdtHtmlConverter::ConversionOptions options = {
        false,                   // don't put styles in css file
        false,                    // don't break into chapters
        false                     // It is not mobi.
    };
    QHash<QString, QString> mediaFilesList;
    status = converter.convertContent(odfStore, m_metadata, &m_manifest, &options, &html,
                                      m_imagesSrcList, mediaFilesList);
    if (status != KoFilter::OK) {
        delete odfStore;
        return status;
    }

    // Extract images
    status = extractImages(odfStore, &html);
    if (status != KoFilter::OK) {
        delete odfStore;
        return status;
    }

    // ----------------------------------------------------------------
    // Write the finished html file to disk

    html.writeHtml(m_chain->outputFile());

    delete odfStore;

    return KoFilter::OK;
}
KoFilter::ConversionStatus KoOdfExporter::convert(const QByteArray& from, const QByteArray& to)
{
    // check for proper conversion
    if (!acceptsSourceMimeType(from)) {
        kWarning(30003) << "Invalid source mimetype" << from;
        return KoFilter::NotImplemented;
    }
    if (!acceptsDestinationMimeType(to)) {
        kWarning(30003) << "Invalid destination mimetype" << to;
        return KoFilter::NotImplemented;
    }

    //create output files
    KoStore *outputStore = KoStore::createStore(m_chain->outputFile(), KoStore::Write, to, KoStore::Zip);
    if (!outputStore || outputStore->bad()) {
        kWarning(30003) << "Unable to open output file!";
        delete outputStore;
        return KoFilter::FileNotFound;
    }
    outputStore->disallowNameExpansion();
    kDebug(30003) << "created outputStore.";
    KoOdfWriteStore oasisStore(outputStore);

    kDebug(30003) << "created oasisStore.";

    // KoGenStyles for writing styles while we're parsing
    KoGenStyles mainStyles;

    KoOdfWriters writers;
    writers.mainStyles = &mainStyles;

    // create a writer for meta.xml
    QBuffer buf;
    buf.open(QIODevice::WriteOnly);
    KoXmlWriter metaWriter(&buf);
    writers.meta = &metaWriter;

    // create a writer for manifest.xml
    QBuffer manifestBuf;
    manifestBuf.open(QIODevice::WriteOnly);
    KoXmlWriter manifestWriter(&manifestBuf);
    writers.manifest = &manifestWriter;

    //open contentWriter & bodyWriter *temp* writers
    //so we can write picture files while we parse
    QBuffer contentBuf;
    KoXmlWriter contentWriter(&contentBuf);
    writers.content = &contentWriter;
    QBuffer bodyBuf;
    KoXmlWriter bodyWriter(&bodyBuf);
    writers.body = &bodyWriter;

    // open main tags
    bodyWriter.startElement("office:body");
    bodyWriter.startElement(d->bodyContentElement.constData());

    RETURN_IF_ERROR( createDocument(outputStore, &writers) )

    //save the office:automatic-styles & and fonts in content.xml
    mainStyles.saveOdfStyles(KoGenStyles::FontFaceDecls, &contentWriter);
    mainStyles.saveOdfStyles(KoGenStyles::DocumentAutomaticStyles, &contentWriter);

    //close tags in body
    bodyWriter.endElement();//office:*
    bodyWriter.endElement();//office:body

    //now create real content/body writers & dump the information there
    KoXmlWriter* realContentWriter = oasisStore.contentWriter();
    if (!realContentWriter) {
        kWarning(30003) << "Error creating the content writer.";
        delete outputStore;
        return KoFilter::CreationError;
    }
    realContentWriter->addCompleteElement(&contentBuf);

    KoXmlWriter* realBodyWriter = oasisStore.bodyWriter();
    if (!realBodyWriter) {
        kWarning(30003) << "Error creating the body writer.";
        delete outputStore;
        return KoFilter::CreationError;
    }
    realBodyWriter->addCompleteElement(&bodyBuf);

    //now close content & body writers
    if (!oasisStore.closeContentWriter()) {
        kWarning(30003) << "Error closing content.";
        delete outputStore;
        return KoFilter::CreationError;
    }

    kDebug(30003) << "closed content & body writers.";

    //create the manifest file
    KoXmlWriter* realManifestWriter = oasisStore.manifestWriter(to);
    //create the styles.xml file
    mainStyles.saveOdfStylesDotXml(outputStore, realManifestWriter);
    realManifestWriter->addManifestEntry("content.xml", "text/xml");
    realManifestWriter->addCompleteElement(&manifestBuf);

    kDebug(30003) << "created manifest and styles.xml";

    // create settings.xml, apparently it is used to note calligra that msoffice files should
    // have different behavior with some things
    if (!outputStore->open("settings.xml")) {
        delete outputStore;
        return KoFilter::CreationError;
    }

    KoStoreDevice settingsDev(outputStore);
    KoXmlWriter* settings = KoOdfWriteStore::createOasisXmlWriter(&settingsDev, "office:document-settings");
    settings->startElement("office:settings");
    settings->startElement("config:config-item-set");
    settings->addAttribute("config:name", "ooo:configuration-settings");
    writeConfigurationSettings(settings);
    settings->endElement(); // config:config-item-set
    settings->endElement(); // office:settings
    settings->endElement(); // office:document-settings
    settings->endDocument();
    delete settings;
    realManifestWriter->addManifestEntry("settings.xml", "text/xml");
    if (!outputStore->close()) {
        delete outputStore;
        return KoFilter::CreationError;
    }

    //create meta.xml
    if (!outputStore->open("meta.xml")) {
        delete outputStore;
        return KoFilter::CreationError;
    }
    KoStoreDevice metaDev(outputStore);
    KoXmlWriter* meta = KoOdfWriteStore::createOasisXmlWriter(&metaDev, "office:document-meta");
    meta->startElement("office:meta");
    meta->addCompleteElement(&buf);
    meta->endElement(); //office:meta
    meta->endElement(); //office:document-meta
    meta->endDocument();
    delete meta;
    if (!outputStore->close()) {
        delete outputStore;
        return KoFilter::CreationError;
    }
    realManifestWriter->addManifestEntry("meta.xml", "text/xml");
    oasisStore.closeManifestWriter();
    delete outputStore;

    return KoFilter::OK;
}
Example #8
0
void KugarPart::slotPreferredTemplate( const QString &tpl )
{
    KURL url( tpl );
    QString localtpl;
    bool isTemp = false;

    if ( !url.isValid() )
    {
/*        kdDebug() << "mailformed url" << endl;*/
        if ( tpl.find( '/' ) >= 0 )
        {
            if ( tpl.startsWith( "." ) )
            {
                KURL tmpURL( m_docURL );
                tmpURL.setFileName( "" );
                tmpURL.addPath( tpl );
                if ( KIO::NetAccess::download( tmpURL, localtpl ) )
                    isTemp = true;
                else
                    KMessageBox::sorry( 0, i18n( "Unable to download template file: %1" ).arg( url.prettyURL() ) );
            }
            else
                localtpl = tpl;
        }
        else
        {
            QString former_localtpl = localtpl;
            localtpl = kapp -> dirs() -> findResource( "data", "kugar/templates/" + tpl );
            if ( localtpl.isEmpty() )
            {
                KURL tmpURL( m_docURL );
                tmpURL.setFileName( "" );
                tmpURL.addPath( tpl );
                if ( KIO::NetAccess::download( tmpURL, localtpl ) )
                    isTemp = true;
                else
                    KMessageBox::sorry( 0, i18n( "Unable to download template file: %1" ).arg( url.prettyURL() ) );
            }
        }
    }
    else
    {
        if ( KIO::NetAccess::download( url, localtpl ) )
            isTemp = true;
        else
            KMessageBox::sorry( 0, i18n( "Unable to download template file: %1" ).arg( url.prettyURL() ) );
    }

/*    kdDebug() << "localtpl: " << localtpl.latin1() << endl;*/
    if ( !localtpl.isEmpty() )
    {
        QFile f( localtpl );

        if ( f.open( IO_ReadOnly ) )
        {
/*            kdDebug() << "localtpl opened" << endl;*/
            // Try to find out whether it is a mime multi part file
            char buf[ 5 ];
            if ( f.readBlock( buf, 4 ) == 4 )
            {
                bool isRawXML = ( strncasecmp( buf, "<?xm", 4 ) == 0 );
                f.close();

                if ( isRawXML )
                {
/*                    kdDebug() << "RawXML" << endl;*/
                    f.open( IO_ReadOnly );
                    if ( !m_reportEngine -> setReportTemplate( &f ) )
                        KMessageBox::sorry( 0, i18n( "Invalid template file: %1" ).arg( localtpl ) );
                    else
                    {
                        m_templateOk = true;
/*                        kdDebug() << "Setting m_templateOk" << endl;*/
                    }
                    f.close();
                }
                else
                {
                    KoStore *tmpStore = KoStore::createStore( localtpl, KoStore::Read );
                    if ( tmpStore->open( "maindoc.xml" ) )
                    {
                        if ( !m_reportEngine -> setReportTemplate( tmpStore->device() ) )
                            KMessageBox::sorry( 0, i18n( "%1 is not a valid Kugar Designer template file." ).arg( localtpl ) );
                        else
                            m_templateOk = true;
                        tmpStore->close();
                    }
                    else
                        KMessageBox::sorry( 0, i18n( "%1 is not a valid Kugar Designer template file." ).arg( localtpl ) );

                    delete tmpStore;
                }

            }
            else
            {
                f.close();
                KMessageBox::sorry( 0, i18n( "Couldn't read the beginning of the template file: %1" ).arg( localtpl ) );
            }

        }
        else
            KMessageBox::sorry( 0, i18n( "Unable to open template file: %1" ).arg( localtpl ) );

        if ( isTemp )
            KIO::NetAccess::removeTempFile( localtpl );
    }
}
Example #9
0
KoFilter::ConversionStatus AsciiImport::convert(const QByteArray& from, const QByteArray& to)
{
    // check for proper conversion
    if (to != "application/vnd.oasis.opendocument.text" || from != "text/plain") {
        return KoFilter::NotImplemented;
    }

    QFile in(m_chain->inputFile());
    if (!in.open(QIODevice::ReadOnly)) {
        kError(30502) << "Unable to open input file!" << endl;
        in.close();
        return KoFilter::FileNotFound;
    }

#ifdef OUTPUT_AS_ODT_FILE
    
#else
    KoDocument* document = m_chain->outputDocument();
    if (!document)
        return KoFilter::StupidError;
    KWDocument *outputDoc = qobject_cast<KWDocument*>(document);
    outputDoc->setOutputMimeType(to);
    //outputDoc->setSaveInBatchMode(true);

    QPointer<KoUpdater> loadUpdater = outputDoc->progressUpdater()->startSubtask(2, "load");
    loadUpdater->setRange(0, in.size());

    QPointer<KoUpdater> layoutUpdater = outputDoc->progressUpdater()->startSubtask(3, "layout");
#endif

    // try to read 100000 bytes so we can be quite sure the guessed encoding is correct.
    // this code is inspired by the kate encoding guessing first try UTF-8
    QByteArray data = in.read(100000);
    in.seek(0);
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    if (!checkEncoding(codec, data)) {
        KEncodingProber prober(KEncodingProber::Universal);
        prober.feed(data);
        kDebug(30502) << "guessed" << prober.encoding() << prober.confidence();
        if (prober.confidence() > 0.5)
            codec = QTextCodec::codecForName(prober.encoding());
        if (!codec || !checkEncoding(codec, data )) {
            codec = QTextCodec::codecForName("ISO 8859-15");
            if (!checkEncoding(codec, data))
                codec = QTextCodec::codecForName("UTF-8");
        }
    }

    int paragraphStrategy = 0;
    if (!m_chain->manager()->getBatchMode()) {
        QPointer<AsciiImportDialog> dialog = new AsciiImportDialog(codec->name(), QApplication::activeWindow());
        if (!dialog) { in.close(); return KoFilter::StupidError; }
        if (!dialog->exec()) { in.close(); return KoFilter::UserCancelled; }
        codec = dialog->getCodec();
        paragraphStrategy = dialog->getParagraphStrategy();
    }
    if (!codec) return KoFilter::StupidError;
    kDebug(30502) << "Charset used:" << codec->name();

#ifdef OUTPUT_AS_ODT_FILE
    KoStore *store = KoStore::createStore(m_chain->outputFile(), KoStore::Write, to, KoStore::Zip);
    if (!store || store->bad()) {
        kWarning(30502) << "Unable to open output file!";
        delete store;
        return KoFilter::FileNotFound;
    }
    store->disallowNameExpansion();
    kDebug(30502) << "created store.";
    KoOdfWriteStore odfStore(store);
    odfStore.manifestWriter(to);

    KoXmlWriter* contentWriter = odfStore.contentWriter();
    if (!contentWriter) {
        delete store;
        return KoFilter::CreationError;
    }

    KoGenStyles mainStyles;
    KoXmlWriter *bodyWriter = odfStore.bodyWriter();

    bodyWriter->startElement("office:body");
    bodyWriter->startElement("office:text");

    QString styleName("txt");
    KoGenStyle style(KoGenStyle::ParagraphStyle, "paragraph");
    style.addAttribute("style:display-name", styleName);
    style.addProperty("fo:font-family", "dejavu sans mono", KoGenStyle::TextType);
    style.addProperty("fo:font-family-generic", "modern", KoGenStyle::TextType);
    style.addProperty("fo:font-size", "10pt", KoGenStyle::TextType);

    style.addProperty("fo:font-weight", "normal", KoGenStyle::TextType);
    QString name(QString(QUrl::toPercentEncoding(styleName, "", " ")).replace('%', '_'));

    name = mainStyles.insert(style, name, KoGenStyles::DontAddNumberToName);
#else
    KoStyleManager *styleManager = outputDoc->resourceManager()->resource(KoText::StyleManager).value<KoStyleManager*>();
    KoParagraphStyle *p = styleManager->defaultParagraphStyle();
    p->setFontFamily("dejavu sans mono");
    p->setFontPointSize(10);
    p->setFontStyleHint(QFont::TypeWriter);

    outputDoc->appendPage();
    QTextDocument *doc = outputDoc->mainFrameSet()->document();
    //doc->setDefaultFont(p->font());

    KoTextDocumentLayout *lay = dynamic_cast<KoTextDocumentLayout*>(doc->documentLayout());
    Q_ASSERT(lay);
    lay->setBlockLayout(true);
    connect(lay, SIGNAL(layoutProgressChanged(int)), layoutUpdater, SLOT(setProgress(int)));

    QTextCursor cursor(doc);
    cursor.beginEditBlock();

    QTextCharFormat charFormat;
    ((KoCharacterStyle*)p)->applyStyle(charFormat);
    cursor.setCharFormat(charFormat);
#endif

    QTextStream stream(&in);
    Q_ASSERT(codec);
    stream.setCodec(codec);

    switch (paragraphStrategy) {
    case 1: { // Sentence: Line-break at the end of a sentence.
        QString stoppingPunctuation(".!?");
        QString skippingEnd(" \"')");
        while (!stream.atEnd()) {
            QString paragraph;
            for (;;) {
                const QString line = stream.readLine();
                if (line.isEmpty())
                    break;
                paragraph += line + ' ';
                int lastPos = line.length() - 1;
                int maxCheck = lastPos >= 10 ? 10: lastPos + 1;
                QChar lastChar;
                // Skip a maximum of 10 quotes (or similar) at the end of the line
                for (int i = 0; i < maxCheck; ++i, --lastPos) {
                    lastChar = line[lastPos];
                    if (lastPos == 0 || lastChar.isNull() || skippingEnd.indexOf(lastChar) == -1)
                        break;
                }
                lastChar = line[lastPos];
                if (lastChar.isNull())
                    continue;
                if (stoppingPunctuation.indexOf(lastChar) != -1)
                    break;
            }
            if (!paragraph.isNull()) {
                QString s = paragraph.simplified();
#ifdef OUTPUT_AS_ODT_FILE
                bodyWriter->startElement("text:p");
                bodyWriter->addAttribute("text:style-name", styleName);
                if (!s.isEmpty())
                    bodyWriter->addTextSpan(s);
                bodyWriter->endElement();
#else
                if (!s.isEmpty())
                    cursor.insertText(s /*, charFormat*/);
                cursor.insertBlock();
                loadUpdater->setValue(stream.device()->pos());
#endif
            }
        }
    } break;
    case 2: { // Empty Line: Line-break if the line is empty.  
        while (!stream.atEnd()) {
            QString paragraph;
            do {
                const QString line = stream.readLine();
                if (line.isEmpty())
                    break;
                paragraph.append(line + ' ');
            } while(true);
            if (!paragraph.isNull()) {
                QString s = paragraph.simplified();
#ifdef OUTPUT_AS_ODT_FILE
                bodyWriter->startElement("text:p");
                bodyWriter->addAttribute("text:style-name", styleName);
                if (!s.isEmpty())
                    bodyWriter->addTextSpan(s);
                bodyWriter->endElement();
#else
                if (!s.isEmpty()) {
                    cursor.insertText(s /*, charFormat*/);
                    cursor.insertBlock();
                    loadUpdater->setValue(stream.device()->pos());
                }
#endif
            }
        }
    } break;
    default: { // As Is: Line-break at the end of line.
        while (!stream.atEnd()) {
            QString s = stream.readLine();
#ifdef OUTPUT_AS_ODT_FILE
            bodyWriter->startElement("text:p");
            bodyWriter->addAttribute("text:style-name", styleName);
            if (!s.isEmpty())
                bodyWriter->addTextSpan(s);
            bodyWriter->endElement();
#else
            if (!s.isEmpty())
                cursor.insertText(s /*, charFormat*/);
            cursor.insertBlock();
            loadUpdater->setValue(stream.device()->pos());
#endif
        }
    } break;
    }

#ifdef OUTPUT_AS_ODT_FILE
    bodyWriter->endElement(); // office:text
    bodyWriter->endElement(); // office:body
    
    mainStyles.saveOdfStyles(KoGenStyles::DocumentAutomaticStyles, contentWriter);
    odfStore.closeContentWriter();

    odfStore.manifestWriter()->addManifestEntry("content.xml", "text/xml");
    if (!mainStyles.saveOdfStylesDotXml(odfStore.store(), odfStore.manifestWriter())) {
        delete store;
        return KoFilter::CreationError;
    }
    if (store->open("meta.xml")) {
        KoStoreDevice dev(store);
        KoXmlWriter* xmlWriter = KoOdfWriteStore::createOasisXmlWriter(&dev, "office:document-meta");
        xmlWriter->startElement("office:meta");
        xmlWriter->startElement("meta:generator");
        xmlWriter->addTextNode(QString("Calligra %1").arg(CALLIGRA_VERSION_STRING));
        xmlWriter->endElement();
        xmlWriter->startElement("meta:creation-date");
        xmlWriter->addTextNode(QDateTime::currentDateTime().toString(Qt::ISODate));
        xmlWriter->endElement();
        xmlWriter->endElement(); // office:meta
        xmlWriter->endElement(); // root element
        xmlWriter->endDocument();
        delete xmlWriter;
        if (store->close())
            odfStore.manifestWriter()->addManifestEntry("meta.xml", "text/xml" );
    }
    if (!odfStore.closeManifestWriter()) {
        kWarning() << "Error while trying to write 'META-INF/manifest.xml'. Partition full?";
        delete store;
        return KoFilter::CreationError;
    }
    delete store;
#else
    cursor.endEditBlock();
    lay->setBlockLayout(false);
    lay->layout();
#endif

    return KoFilter::OK;
}
Example #10
0
KoFilter::ConversionStatus HancomWordImport::convert( const QByteArray& from, const QByteArray& to )
{
  if ( from != "application/x-hwp" )
    return KoFilter::NotImplemented;

  if ( to != "application/vnd.oasis.opendocument.text" )
    return KoFilter::NotImplemented;

  d->inputFile = m_chain->inputFile();
  d->outputFile = m_chain->outputFile();
  d->paragraphs.clear();

  POLE::Storage storage( QFile::encodeName(d->inputFile) );
  if( !storage.open() )
    return KoFilter::WrongFormat;

  POLE::Stream* stream;
  stream = new POLE::Stream( &storage, "/PrvText" );
  if( stream->fail() || (stream->size() == 0) )
  {
    delete stream;
    return KoFilter::WrongFormat;
  }

  int len = stream->size() / 2;
  QString plaindoc;
  plaindoc.reserve( len );

  unsigned char* buf = new unsigned char [stream->size()];
  stream->read( buf, stream->size());
  for(int i = 0; i < len; i++ )
    plaindoc.append( QChar((int)readU16(buf + i*2) ) );
  delete[] buf;
  delete stream;

  // split into paragraphs
  d->paragraphs = QStringList::split( "\n", plaindoc, true );

  // create output store
  KoStore* storeout;
  storeout = KoStore::createStore( d->outputFile, KoStore::Write,
    "application/vnd.oasis.opendocument.text", KoStore::Zip );

  if ( !storeout )
  {
    kWarning() << "Couldn't open the requested file.";
    return KoFilter::FileNotFound;
  }

  if ( !storeout->open( "styles.xml" ) )
  {
    kWarning() << "Couldn't open the file 'styles.xml'.";
    return KoFilter::CreationError;
  }
  storeout->write( d->createStyles() );
  storeout->close();

  if ( !storeout->open( "content.xml" ) )
  {
    kWarning() << "Couldn't open the file 'content.xml'.";
    return KoFilter::CreationError;
  }
  storeout->write( d->createContent() );
  storeout->close();

  // store document manifest
  storeout->enterDirectory( "META-INF" );
  if ( !storeout->open( "manifest.xml" ) )
  {
     kWarning() << "Couldn't open the file 'META-INF/manifest.xml'.";
     return KoFilter::CreationError;
  }
  storeout->write( d->createManifest() );
  storeout->close();

  // we are done!
  d->inputFile.clear();
  d->outputFile.clear();
  delete storeout;

  return KoFilter::OK;
}
Example #11
0
bool OdfReader::readContent(OdfReaderBackend *backend, OdfReaderContext *context)
{
    debugOdfReader << "entering";

    m_backend = backend;
    m_context = context;

    if (m_textReader) {
        m_textReader->setContext(context);
    }

    // ----------------------------------------------------------------
    // Read the body from content.xml

    KoStore *odfStore = m_context->odfStore();

    if (!odfStore->open("content.xml")) {
        errorOdfReader << "Unable to open input file content.xml" << endl;
        return false;
    }
    debugOdfReader << "open content.xml ok";

    KoXmlStreamReader reader;
    prepareForOdfInternal(reader);

    reader.setDevice(odfStore->device());
    bool  foundContent = false;
    while (!reader.atEnd()) {
        reader.readNext();

        if (reader.isStartElement() && reader.qualifiedName() == "office:document-content") {
            foundContent = true;
            break;
        }
    }
    if (!foundContent) {
        errorOdfReader << "Couldn't find the content in content.xml" << endl;
    }

    m_backend->elementOfficeDocumentcontent(reader, m_context);

    // <office:document-content> has the following children in ODF 1.2:
    //          <office:automatic-styles> 3.15.3
    //   [done] <office:body> 3.3
    //          <office:font-face-decls> 3.14
    //          <office:scripts> 3.12.
    while (reader.readNextStartElement()) {
        QString tagName = reader.qualifiedName().toString();
        
        if (tagName == "office:automatic-styles") {
            // We already have the styles in the context.  No need to read them again.
            reader.skipCurrentElement();
        }
        else if (tagName == "office:body") {
            // This is the big one.
            readElementOfficeBody(reader);
        }
        else if (tagName == "office:font-face-decls") {
            // FIXME: Not yet implemented
            reader.skipCurrentElement();
        }
        else if (tagName == "office:scripts") {
            // FIXME: Not yet implemented
            reader.skipCurrentElement();
        }
        else {
            reader.skipCurrentElement();
        }
    }

    m_backend->elementOfficeDocumentcontent(reader, m_context);
    odfStore->close();

    return true;
}
Example #12
0
KoFilter::ConversionStatus KWord13Import::convert( const QByteArray& from, const QByteArray& to )
{
    if ( to != "application/vnd.oasis.opendocument.text"
        || from != "application/x-kword" )
    {
        return KoFilter::NotImplemented;
    }

    // We need KimageIO's help in OOWriterWorker::convertUnknownImage


    KWord13Document kwordDocument;

    const QString fileName( m_chain->inputFile() );
    if ( fileName.isEmpty() )
    {
        kError(30520) << "No input file name!";
        return KoFilter::StupidError;
    }

    KoStore* store = KoStore::createStore( fileName, KoStore::Read );
    if ( store && store->hasFile( "maindoc.xml" ) )
    {
        kDebug(30520) <<"Maindoc.xml found in KoStore!";

        // We do not really care about errors while reading/parsing documentinfo
        store->open( "documentinfo.xml" );
        KoStoreDevice ioInfo( store );
        ioInfo.open( QIODevice::ReadOnly );
        kDebug (30520) <<"Processing document info...";
        if ( ! parseInfo ( &ioInfo, kwordDocument ) )
        {
            kWarning(30520) << "Parsing documentinfo.xml has failed. Ignoring!";
        }
        ioInfo.close();
        store->close();

        // ### TODO: error return values
        if ( ! store->open( "maindoc.xml" ) )
        {
            kError(30520) << "Opening root has failed";
            delete store;
            return KoFilter::StupidError;
        }
        KoStoreDevice ioMain( store );
        ioMain.open( QIODevice::ReadOnly );
        kDebug (30520) <<"Processing root...";
        if ( ! parseRoot ( &ioMain, kwordDocument ) )
        {
            kWarning(30520) << "Parsing maindoc.xml has failed! Aborting!";
            delete store;
            return KoFilter::StupidError;
        }
        ioMain.close();
        store->close();

        if ( store->open( "preview.png" ) )
        {

            kDebug(30520) <<"Preview found!";
            KoStoreDevice ioPreview( store );
            ioPreview.open( QIODevice::ReadOnly );
            const QByteArray image ( ioPreview.readAll() );
            if ( image.isNull() )
            {
                kWarning(30520) << "Loading of preview failed! Ignoring!";
            }
            else
            {
                kwordDocument.m_previewFile = new KTemporaryFile();
                kwordDocument.m_previewFile->setSuffix(".png");
                kwordDocument.m_previewFile->open(); // ### TODO check KTemporaryFile
                // ### TODO: check if file is correctly written
                kwordDocument.m_previewFile->write( image );
                kwordDocument.m_previewFile->close();
            }
            ioPreview.close();
            store->close();
        }
        else
        {
            kDebug(30520) <<"No preview found!";
        }
    }
    else
    {
        kWarning(30520) << "Opening store has failed. Trying raw XML file!";
        // Be sure to undefine store
        delete store;
        store = 0;

        QFile file( fileName );
        file.open( QIODevice::ReadOnly );
        if ( ! parseRoot( &file, kwordDocument ) )
        {
            kError(30520) << "Could not process document! Aborting!";
            file.close();
            return KoFilter::StupidError;
        }
        file.close();
    }

    if ( store && ! postParse( store, kwordDocument ) )
    {
        kError(30520) << "Error during post-parsing! Aborting!";
        return  KoFilter::StupidError;
    }

    // We have finished with the input store/file, so close the store (already done for a raw XML file)
    kDebug(30520) <<"Deleting input store...";
    delete store;
    store = 0;
    kDebug(30520) <<"Input store deleted!";

    KWord13OasisGenerator generator;

    kDebug(30520) << __FILE__ <<":" << __LINE__;

    if ( ! generator.prepare( kwordDocument ) )
    {
        kError(30520) << "Could not prepare the OASIS document! Aborting!";
        return KoFilter::StupidError;
    }

    const QString filenameOut ( m_chain->outputFile() );

    if ( filenameOut.isEmpty() )
    {
        kError(30520) << "Empty file name for saving as OASIS! Aborting!";
        return KoFilter::StupidError;
    }

    if ( ! generator.generate( filenameOut, kwordDocument ) )
    {
        kError(30520) << "Could not save as OASIS! Aborting!";
        return KoFilter::StupidError;
    }

    kDebug(30520) <<"Filter has finished!";

    return KoFilter::OK;
}
Example #13
0
KoFilter::ConversionStatus WPGImport::convert( const QByteArray& from, const QByteArray& to )
{
  if ( from != "application/x-wpg" )
    return KoFilter::NotImplemented;

  if ( to != "application/vnd.oasis.opendocument.graphics" )
    return KoFilter::NotImplemented;


  WPXInputStream* input = new libwpg::WPGFileStream( m_chain->inputFile().toLocal8Bit() );
  if (input->isOLEStream())
  {
    WPXInputStream* olestream = input->getDocumentOLEStream();
    if (olestream)
    {
      delete input;
      input = olestream;
    }
  }

  if (!libwpg::WPGraphics::isSupported(input))
  {
    std::cerr << "ERROR: Unsupported file format (unsupported version) or file is encrypted!" << std::endl;
    delete input;
    return KoFilter::NotImplemented;
  }

  // do the conversion
  std::ostringstream tmpStringStream;
  FileOutputHandler tmpHandler(tmpStringStream);
  OdgExporter exporter(&tmpHandler);
  libwpg::WPGraphics::parse(input, &exporter);
  delete input;


  // create output store
  KoStore* storeout;
  storeout = KoStore::createStore( m_chain->outputFile(), KoStore::Write,
    "application/vnd.oasis.opendocument.graphics", KoStore::Zip );

  if ( !storeout )
  {
    kWarning() << "Couldn't open the requested file.";
    return KoFilter::FileNotFound;
  }

#if 0
  if ( !storeout->open( "styles.xml" ) )
  {
    kWarning() << "Couldn't open the file 'styles.xml'.";
    return KoFilter::CreationError;
  }
  //storeout->write( createStyles() );
  storeout->close();
#endif

  if ( !storeout->open( "content.xml" ) )
  {
    kWarning() << "Couldn't open the file 'content.xml'.";
    return KoFilter::CreationError;
  }
  storeout->write(tmpStringStream.str().c_str());
  storeout->close();

  // store document manifest
  storeout->enterDirectory( "META-INF" );
  if ( !storeout->open( "manifest.xml" ) )
  {
     kWarning() << "Couldn't open the file 'META-INF/manifest.xml'.";
     return KoFilter::CreationError;
  }
  storeout->write( createManifest() );
  storeout->close();

  // we are done!
  delete storeout;

  return KoFilter::OK;
}