Exemplo n.º 1
0
QList<StyleName> SMTableStyle::styles(bool reloadFromDoc)
{
	QList<StyleName> stylesList;

	if (!m_doc)
		return stylesList; // No document available.

	if (reloadFromDoc)
		updateStylesCache(); // Update cache.

	// Return a list of names of cached styles.
	for (int i = 0; i < m_cachedStyles.count(); ++i)
	{
		if (m_cachedStyles[i].hasName())
		{
			QString styleName(m_cachedStyles[i].displayName());
			QString parentName(QString::null);

			if (m_cachedStyles[i].hasParent())
			{
				const Style* parentStyle = m_cachedStyles[i].parentStyle();
				if (parentStyle)
					parentName = parentStyle->displayName();
			}

			stylesList << StyleName(styleName, parentName);
		}
	}

	return stylesList;
}
Exemplo n.º 2
0
PassRefPtr<JSONObject> LoggingCanvas::objectForSkPaint(const SkPaint& paint)
{
    RefPtr<JSONObject> paintItem = JSONObject::create();
    paintItem->setNumber("textSize", paint.getTextSize());
    paintItem->setNumber("textScaleX", paint.getTextScaleX());
    paintItem->setNumber("textSkewX", paint.getTextSkewX());
    if (SkShader* shader = paint.getShader())
        paintItem->setObject("shader", objectForSkShader(*shader));
    paintItem->setString("color", stringForSkColor(paint.getColor()));
    paintItem->setNumber("strokeWidth", paint.getStrokeWidth());
    paintItem->setNumber("strokeMiter", paint.getStrokeMiter());
    paintItem->setString("flags", stringForSkPaintFlags(paint));
    paintItem->setString("filterLevel", filterQualityName(paint.getFilterQuality()));
    paintItem->setString("textAlign", textAlignName(paint.getTextAlign()));
    paintItem->setString("strokeCap", strokeCapName(paint.getStrokeCap()));
    paintItem->setString("strokeJoin", strokeJoinName(paint.getStrokeJoin()));
    paintItem->setString("styleName", styleName(paint.getStyle()));
    paintItem->setString("textEncoding", textEncodingName(paint.getTextEncoding()));
    paintItem->setString("hinting", hintingName(paint.getHinting()));
    return paintItem.release();
}
Exemplo n.º 3
0
App::App(int &argc, char **argv)
: QApplication(argc, argv), d(new Data(this)) {
#ifdef Q_OS_LINUX
    setlocale(LC_NUMERIC,"C");
#endif
    setOrganizationName(u"xylosper"_q);
    setOrganizationDomain(u"xylosper.net"_q);
    setApplicationName(_L(name()));
    setApplicationVersion(_L(version()));

    Record r(APP_GROUP);
    QVariant vLocale;
    r.read(vLocale, u"locale"_q);
    setLocale(Locale::fromVariant(vLocale));

    d->addOption(LineCmd::Open, u"open"_q,
                 tr("Open given %1 for file path or URL."), u"mrl"_q);
    d->addOption(LineCmd::Wake, u"wake"_q,
                 tr("Bring the application window in front."));
    d->addOption(LineCmd::Action, u"action"_q,
                 tr("Exectute %1 action or open %1 menu."), u"id"_q);
    d->addOption(LineCmd::LogLevel, u"log-level"_q,
                 tr("Maximum verbosity for log. %1 should be one of nexts:")
                 % "\n    "_a % Log::options().join(u", "_q), u"lv"_q);
    d->addOption(LineCmd::OpenGLDebug, u"opengl-debug"_q,
                 tr("Turn on OpenGL debug logger."));
    d->addOption(LineCmd::Debug, u"debug"_q,
                 tr("Turn on options for debugging."));
    d->getCommandParser(&d->cmdParser)->process(arguments());
    d->getCommandParser(&d->msgParser);
    d->execute(&d->cmdParser);

#if defined(Q_OS_MAC) && defined(CMPLAYER_RELEASE)
    static const auto path = QApplication::applicationDirPath().toLocal8Bit();
    _Debug("Set $LIBQUVI_SCRIPTSDIR=\"%%\"", path);
    if (setenv("LIBQUVI_SCRIPTSDIR", path.data(), 1) < 0)
        _Error("Cannot set $LIBQUVI_SCRIPTSDIR. "
               "Some streaming functions won't work.");
#endif

    setQuitOnLastWindowClosed(false);
#ifndef Q_OS_MAC
    setWindowIcon(defaultIcon());
#endif

    auto makeStyle = [&]() {
        auto name = r.value(u"style"_q, styleName()).toString();
        if (style()->objectName().compare(name, QCI) == 0)
            return;
        if (!d->styleNames.contains(name, QCI))
            return;
        setStyle(QStyleFactory::create(name));
    };
    d->styleNames = [this] () {
        auto names = QStyleFactory::keys();
        const auto defaultName = style()->objectName();
        for (auto it = ++names.begin(); it != names.end(); ++it) {
            if (defaultName.compare(*it, QCI) == 0) {
                const auto name = *it;
                names.erase(it);
                names.prepend(name);
                break;
            }
        }
        return names;
    }();
    makeStyle();
    connect(&d->connection, &LocalConnection::messageReceived,
             this, &App::handleMessage);
    const auto map = r.value(u"open_folders"_q).toMap();
    QMap<QString, QString> folders;
    for (auto it = map.begin(); it != map.end(); ++it)
        folders.insert(it.key(), it->toString());
    set_open_folders(folders);
}
Exemplo n.º 4
0
void DateFormatRoundTripTest::test(const Locale& loc) 
{
    UnicodeString temp;
#if !INFINITE
    logln("Locale: " + loc.getDisplayName(temp));
#endif

    // Total possibilities = 24
    //  4 date
    //  4 time
    //  16 date-time
    UBool TEST_TABLE [24];//= new boolean[24];
    int32_t i = 0;
    for(i = 0; i < 24; ++i) 
        TEST_TABLE[i] = TRUE;

    // If we have some sparseness, implement it here.  Sparseness decreases
    // test time by eliminating some tests, up to 23.
    for(i = 0; i < SPARSENESS; ) {
        int random = (int)(randFraction() * 24);
        if (random >= 0 && random < 24 && TEST_TABLE[i]) {
            TEST_TABLE[i] = FALSE;
            ++i;
        }
    }

    int32_t itable = 0;
    int32_t style = 0;
    for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) {
        if(TEST_TABLE[itable++]) {
            logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style)));
            DateFormat *df = DateFormat::createDateInstance((DateFormat::EStyle)style, loc);
            if(df == NULL) {
              errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) +      " Locale: " + loc.getDisplayName(temp));
            } else {
              test(df, loc);
              delete df;
            }
        }
    }
    
    for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) {
        if (TEST_TABLE[itable++]) {
          logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style)));
            DateFormat *df = DateFormat::createTimeInstance((DateFormat::EStyle)style, loc);
            if(df == NULL) {
              errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp));
            } else {
              test(df, loc, TRUE);
              delete df;
            }
        }
    }
    
    for(int32_t dstyle = DateFormat::FULL; dstyle <= DateFormat::SHORT; ++dstyle) {
        for(int32_t tstyle = DateFormat::FULL; tstyle <= DateFormat::SHORT; ++tstyle) {
            if(TEST_TABLE[itable++]) {
                logln("Testing dstyle" + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) );
                DateFormat *df = DateFormat::createDateTimeInstance((DateFormat::EStyle)dstyle, (DateFormat::EStyle)tstyle, loc);
                if(df == NULL) {
                    dataerrln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle))    + "Locale: " + loc.getDisplayName(temp));
                } else {
                    test(df, loc);
                    delete df;
                }
            }
        }
    }
}
void OXMLi_ListenerState_Table::startElement (OXMLi_StartElementRequest * rqst)
{
	if (nameMatches(rqst->pName, NS_W_KEY, "tbl"))
	{
		OXML_Element_Table* pTable = new OXML_Element_Table("");
		m_tableStack.push(pTable);
		OXML_SharedElement table(pTable);
		rqst->stck->push(table);
		rqst->handled = true;
		pTable->setCurrentRowNumber(-1);
		pTable->setCurrentColNumber(-1);
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tr"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();
		OXML_Element_Row* pRow = new OXML_Element_Row("", table);
		m_rowStack.push(pRow);
		OXML_SharedElement row(pRow);
		rqst->stck->push(row);
		rqst->handled = true;
		table->incrementCurrentRowNumber();
		table->setCurrentColNumber(0);
		pRow->setRowNumber(table->getCurrentRowNumber());
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tc"))
	{
		if(m_tableStack.empty() || m_rowStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		OXML_Element_Row* row = m_rowStack.top();				
		OXML_Element_Cell* pCell = new OXML_Element_Cell("", table, row, 
								table->getCurrentColNumber(), table->getCurrentColNumber()+1, //left right
								table->getCurrentRowNumber(), table->getCurrentRowNumber()+1); //top,bottom
		m_cellStack.push(pCell);
		OXML_SharedElement cell(pCell);
		rqst->stck->push(cell);
		rqst->handled = true;
		table->incrementCurrentColNumber();
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "gridSpan"))
	{
		if(m_tableStack.empty() || m_cellStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val)
		{
			int span = atoi(val);
			int left = table->getCurrentColNumber()-1;
			int right = left + span;
			//change current cell's right index
			OXML_Element_Cell* cell = m_cellStack.top();
			cell->setRight(right);
			//update column index of current table			
			table->setCurrentColNumber(right);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "vMerge"))
	{
		if(m_cellStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Cell* cell = m_cellStack.top();				
		cell->setVerticalMergeStart(false); //default to continue if the attribute is missing
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val && !strcmp(val, "restart")) 
		{
			cell->setVerticalMergeStart(true);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "hMerge"))
	{
		if(m_cellStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Cell* cell = m_cellStack.top();				
		cell->setHorizontalMergeStart(false); //default to continue if the attribute is missing
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val && !strcmp(val, "restart")) 
		{
			cell->setHorizontalMergeStart(true);
		}
		rqst->handled = true;
	}

	//Table Properties
	else if(nameMatches(rqst->pName, NS_W_KEY, "gridCol") && 
			contextMatches(rqst->context->back(), NS_W_KEY, "tblGrid"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* w = attrMatches(NS_W_KEY, "w", rqst->ppAtts);
		if(w) 
		{
			//append this width to table-column-props property
			const gchar* tableColumnProps = NULL;
			UT_Error ret = table->getProperty("table-column-props", tableColumnProps);
			if((ret != UT_OK) || !tableColumnProps)
				tableColumnProps = "";				
			std::string cols(tableColumnProps);
			cols += _TwipsToPoints(w);
			cols += "pt/";
			ret = table->setProperty("table-column-props", cols);
			if(ret != UT_OK)
			{	
				UT_DEBUGMSG(("FRT:OpenXML importer can't set table-column-props:%s\n", cols.c_str()));
			}
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "trHeight") && 
			contextMatches(rqst->context->back(), NS_W_KEY, "trPr"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val) 
		{
			const gchar* tableRowHeights = NULL;
			UT_Error ret = table->getProperty("table-row-heights", tableRowHeights);
			if((ret != UT_OK) || !tableRowHeights)
				tableRowHeights = "";				
			std::string rowHeights(tableRowHeights);
			rowHeights += _TwipsToPoints(val);
			rowHeights += "pt/";
			ret = table->setProperty("table-row-heights", rowHeights);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set table-row-heights:%s\n", rowHeights.c_str()));
			}
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "left") ||
			nameMatches(rqst->pName, NS_W_KEY, "right") ||
			nameMatches(rqst->pName, NS_W_KEY, "top") ||
			nameMatches(rqst->pName, NS_W_KEY, "bottom"))
	{
		rqst->handled = true;
		const gchar* color = attrMatches(NS_W_KEY, "color", rqst->ppAtts);
		const gchar* sz = attrMatches(NS_W_KEY, "sz", rqst->ppAtts);
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);

		UT_Error ret = UT_OK;

		std::string borderName(rqst->pName);
		borderName = borderName.substr(strlen(NS_W_KEY)+1);
		if(!borderName.compare("bottom"))
			borderName = "bot";

		std::string borderStyle = borderName + "-style";
		std::string borderColor = borderName + "-color";
		std::string borderThickness = borderName + "-thickness";

		OXML_Element* element = NULL;

		if(rqst->context->empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(contextMatches(rqst->context->back(), NS_W_KEY, "tcBorders"))
			element = m_cellStack.empty() ? NULL : m_cellStack.top();
		else if(contextMatches(rqst->context->back(), NS_W_KEY, "tblBorders"))
			element = m_tableStack.empty() ? NULL : m_tableStack.top();

		if(!element)
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(color && strcmp(color, "auto")) 
		{
			ret = element->setProperty(borderColor, color);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set %s:%s\n", borderColor.c_str(), color));
			}
		}
		if(sz) 
		{
			std::string szVal(_EighthPointsToPoints(sz));
			szVal += "pt";
			ret = element->setProperty(borderThickness, szVal);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set %s:%s\n", borderThickness.c_str(), color));
			}
		}

		std::string styleValue = "1"; //single line border by default
		if(val)
		{
			if(!strcmp(val, "dashed"))
				styleValue = "0"; 
		}

		ret = element->setProperty(borderStyle, styleValue);
		if(ret != UT_OK)
		{
			UT_DEBUGMSG(("FRT:OpenXML importer can't set %s:0\n", borderStyle.c_str()));
		}
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "shd"))
	{
		const gchar* fill = attrMatches(NS_W_KEY, "fill", rqst->ppAtts);

		UT_Error ret = UT_OK;
		OXML_Element* element = NULL;

		if(rqst->context->empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(contextMatches(rqst->context->back(), NS_W_KEY, "tcPr"))
			element = m_cellStack.empty() ? NULL : m_cellStack.top();
		else if(contextMatches(rqst->context->back(), NS_W_KEY, "tblPr"))
			element = m_tableStack.empty() ? NULL : m_tableStack.top();

		if(!element)
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(fill && strcmp(fill, "auto")) 
		{
			ret = element->setProperty("background-color", fill);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set background-color:%s\n", fill));	
			}
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tblStyle"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val && table) 
		{
			std::string styleName(val);
			OXML_Document* doc = OXML_Document::getInstance();
			if(doc)
				table->applyStyle(doc->getStyleById(styleName));
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tblPr"))
	{
		if(m_tableStack.empty())
		{
			//we must be in tblStyle in styles, so let's push the table instance to m_tableStack
			OXML_Element_Table* tbl = static_cast<OXML_Element_Table*>(get_pointer(rqst->stck->top()));
			m_tableStack.push(tbl);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "trPr"))
	{
		if(m_rowStack.empty())
		{
			//we must be in styles, so let's push the row instance to m_rowStack
			OXML_Element_Row* row = static_cast<OXML_Element_Row*>(get_pointer(rqst->stck->top()));
			m_rowStack.push(row);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tcPr"))
	{
		if(m_cellStack.empty())
		{
			//we must be in styles, so let's push the cell instance to m_cellStack
			OXML_Element_Cell* cell = static_cast<OXML_Element_Cell*>(get_pointer(rqst->stck->top()));
			m_cellStack.push(cell);
		}
		rqst->handled = true;
	}
	//TODO: more coming here
}
Exemplo n.º 6
0
App::App(int &argc, char **argv)
: QApplication(argc, argv), d(new Data(this)) {
#ifdef Q_OS_LINUX
	setlocale(LC_NUMERIC,"C");
#endif
	setOrganizationName("xylosper");
	setOrganizationDomain("xylosper.net");
	setApplicationName(Info::name());
	setApplicationVersion(Info::version());
	setLocale(Record(APP_GROUP).value("locale", QLocale::system()).toLocale());

	d->addOption(LineCmd::Open, "open", tr("Open given %1 for file path or URL."), "mrl");
	d->addOption(LineCmd::Wake, QStringList() << "wake", tr("Bring the application window in front."));
	d->addOption(LineCmd::Action, "action", tr("Exectute %1 action or open %1 menu."), "id");
	d->addOption(LineCmd::LogLevel, "log-level", tr("Maximum verbosity for log. %1 should be one of nexts:")
				 % "\n    " % Log::options().join(", "), "lv");
	d->addOption(LineCmd::OpenGLDebug, "opengl-debug", tr("Turn on OpenGL debug logger."));
	d->addOption(LineCmd::Debug, "debug", tr("Turn on options for debugging."));
	d->getCommandParser(&d->cmdParser)->process(arguments());
	d->getCommandParser(&d->msgParser);
	d->execute(&d->cmdParser);

#if defined(Q_OS_MAC) && defined(CMPLAYER_RELEASE)
	static const QByteArray path = QApplication::applicationDirPath().toLocal8Bit();
	_Debug("Set $LIBQUVI_SCRIPTSDIR=\"%%\"", QApplication::applicationDirPath());
	if (setenv("LIBQUVI_SCRIPTSDIR", path.data(), 1) < 0)
		_Error("Cannot set $LIBQUVI_SCRIPTSDIR. Some streaming functions won't work.");
#endif

	setQuitOnLastWindowClosed(false);
#ifndef Q_OS_MAC
	setWindowIcon(defaultIcon());
#endif
	auto makeStyleNameList = [this] () {
		auto names = QStyleFactory::keys();
		const auto defaultName = style()->objectName();
		for (auto it = ++names.begin(); it != names.end(); ++it) {
			if (defaultName.compare(*it, Qt::CaseInsensitive) == 0) {
				const auto name = *it;
				names.erase(it);
				names.prepend(name);
				break;
			}
		}
		return names;
	};
	auto makeStyle = [this]() {
		Record r(APP_GROUP);
		auto name = r.value("style", styleName()).toString();
		if (style()->objectName().compare(name, Qt::CaseInsensitive) == 0)
			return;
		if (!d->styleNames.contains(name, Qt::CaseInsensitive))
			return;
		setStyle(QStyleFactory::create(name));
	};
	d->styleNames = makeStyleNameList();
	makeStyle();
	connect(&d->connection, &LocalConnection::messageReceived, [this] (const QString &message) {
		d->msgParser.parse(message.split("[:sep:]")); d->execute(&d->msgParser);
	});
}
QString MAbstractLayoutPolicy::objectName() const
{
    mWarning("MAbstractLayoutPolicy") << Q_FUNC_INFO << "is deprecated. Use styleName() instead.";
    return styleName();
}
Exemplo n.º 8
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;
}