r16682 by jghali - some minor refactoring

scribus-commit scribus-commit at lists.scribus.net
Mon Jun 20 20:43:58 UTC 2011


Author: jghali
Date: Mon Jun 20 20:43:58 2011
New Revision: 16682

URL: http://scribus.net/websvn/listing.php?repname=Scribus&sc=1&rev=16682
Log:
some minor refactoring

Modified:
    trunk/Scribus/scribus/plugins/fileloader/scribus150format/scribus150format_save.cpp
    trunk/Scribus/scribus/plugins/import/ai/importai.cpp
    trunk/Scribus/scribus/plugins/import/wmf/wmfimport.cpp
    trunk/Scribus/scribus/plugins/import/wpg/importwpg.cpp
    trunk/Scribus/scribus/plugins/import/xfig/importxfig.cpp
    trunk/Scribus/scribus/scribusdoc.cpp
    trunk/Scribus/scribus/scribusdoc.h

Modified: trunk/Scribus/scribus/plugins/fileloader/scribus150format/scribus150format_save.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/plugins/fileloader/scribus150format/scribus150format_save.cpp
==============================================================================
--- trunk/Scribus/scribus/plugins/fileloader/scribus150format/scribus150format_save.cpp (original)
+++ trunk/Scribus/scribus/plugins/fileloader/scribus150format/scribus150format_save.cpp Mon Jun 20 20:43:58 2011
@@ -569,11 +569,8 @@
 	{
 		putPStyle(docu, m_Doc->paragraphStyles()[styleList[a]], "STYLE");
 	}
-	//	if (m_Doc->docParagraphStyles.count() > 5)
-//	{
-//		for (int ff = 0; ff < m_Doc->paragraphStyles().count(); ++ff)
-//			putPStyle(docu, m_Doc->paragraphStyles()[ff], "STYLE");
-//	}
+//	for (int ff = 0; ff < m_Doc->paragraphStyles().count(); ++ff)
+//		putPStyle(docu, m_Doc->paragraphStyles()[ff], "STYLE");
 }
 
 void Scribus150Format::putPStyle(ScXmlStreamWriter & docu, const ParagraphStyle & style, const QString &nodeName)

Modified: trunk/Scribus/scribus/plugins/import/ai/importai.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/plugins/import/ai/importai.cpp
==============================================================================
--- trunk/Scribus/scribus/plugins/import/ai/importai.cpp (original)
+++ trunk/Scribus/scribus/plugins/import/ai/importai.cpp Mon Jun 20 20:43:58 2011
@@ -1,3414 +1,3414 @@
-/*
-For general Scribus (>=1.3.2) copyright and licensing information please refer
-to the COPYING file provided with the program. Following this notice may exist
-a copyright and/or license notice that predates the release of Scribus 1.3.2
-for which a new license (GPL+exception) is in place.
-*/
-
-#include <QByteArray>
-#include <QCursor>
-#include <QDrag>
-#include <QFile>
-#include <QList>
-#include <QMimeData>
-#include <QRegExp>
-#include <QStack>
-#include <QTemporaryFile>
-#include <QDebug>
-
-#include <cstdlib>
-#include <tiffio.h>
-#include <zlib.h>
-
-#include "commonstrings.h"
-
-#include "importai.h"
-#include "loadsaveplugin.h"
-#include "prefscontext.h"
-#include "prefsfile.h"
-#include "prefsmanager.h"
-#include "prefstable.h"
-#include "rawimage.h"
-#include "sccolorengine.h"
-#include "scconfig.h"
-#include "scclocale.h"
-#include "scmimedata.h"
-#include "scpaths.h"
-#include "scpattern.h"
-#include "scribus.h"
-#include "scribusXml.h"
-#include "scribuscore.h"
-#include "scribusdoc.h"
-#include "sctextstream.h"
-#include "selection.h"
-#include "text/specialchars.h"
-#include "ui/customfdialog.h"
-#include "ui/missing.h"
-#include "ui/multiprogressdialog.h"
-#include "ui/propertiespalette.h"
-#include "undomanager.h"
-#include "util.h"
-#include "util_color.h"
-#include "util_file.h"
-#include "util_formats.h"
-#include "util_icon.h"
-#include "util_math.h"
-#include "util_ghostscript.h"
-
-#include <cairo.h>
-
-#ifdef HAVE_PODOFO
-	#include <podofo/podofo.h>
-#endif
-
-extern SCRIBUS_API ScribusQApp * ScQApp;
-
-AIPlug::AIPlug(ScribusDoc* doc, int flags)
-{
-	tmpSel=new Selection(this, false);
-	m_Doc=doc;
-	importerFlags = flags;
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-	progressDialog = NULL;
-}
-
-QImage AIPlug::readThumbnail(QString fNameIn)
-{
-	QString fName = fNameIn;
-	double x, y, b, h;
-	CustColors.clear();
-	importedColors.clear();
-	importedGradients.clear();
-	importedPatterns.clear();
-	QFileInfo fi = QFileInfo(fName);
-/* Check if the file is an old style AI or one of the newer PDF wrapped ones */
-	QFile fT(fName);
-	if (fT.open(QIODevice::ReadOnly))
-	{
-		QByteArray tempBuf(9, ' ');
-		fT.read(tempBuf.data(), 8);
-		fT.close();
-		if (tempBuf.startsWith("%PDF"))
-		{
-			QString tmp, cmd1, cmd2;
-			QString pdfFile = QDir::toNativeSeparators(fName);
-			QString tmpFile = QDir::toNativeSeparators(ScPaths::getTempFileDir() + "sc.png");
-			int ret = -1;
-			tmp.setNum(1);
-			QStringList args;
-			args.append("-r72");
-			args.append("-sOutputFile="+tmpFile);
-			args.append("-dFirstPage="+tmp);
-			args.append("-dLastPage="+tmp);
-			args.append(pdfFile);
-			ret = callGS(args);
-			if (ret == 0)
-			{
-				QImage image;
-				image.load(tmpFile);
-				QFile::remove(tmpFile);
-				image.setText("XSize", QString("%1").arg(image.width()));
-				image.setText("YSize", QString("%1").arg(image.height()));
-				return image;
-			}
-			else
-				return QImage();
-		}
-	}
-	QFile fT2(fName);
-	if (fT2.open(QIODevice::ReadOnly))
-	{
-		QByteArray tempBuf(25, ' ');
-		fT2.read(tempBuf.data(), 20);
-		fT2.close();
-		/* Illustrator CS files might be compressed
-			the compressed Data starts right after the "%AI12_CompressedData" comment
-			Compression is a simple zlib compression */
-		if (tempBuf.startsWith("%AI12_CompressedData"))
-			decompressAIData(fName);
-	}
-	progressDialog = NULL;
-/* Set default Page to size defined in Preferences */
-	x = 0.0;
-	y = 0.0;
-	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	parseHeader(fName, x, y, b, h);
-	if (b == 0)
-		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	if (h == 0)
-		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	docX = x;
-	docY = y;
-	docWidth = b - x;
-	docHeight = h - y;
-	baseX = 0;
-	baseY = 0;
-	m_Doc = new ScribusDoc();
-	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
-	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
-	m_Doc->addPage(0);
-	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
-	baseX = m_Doc->currentPage()->xOffset();
-	baseY = m_Doc->currentPage()->yOffset();
-	ColorList::Iterator it;
-	for (it = CustColors.begin(); it != CustColors.end(); ++it)
-	{
-		if (!m_Doc->PageColors.contains(it.key()))
-		{
-			m_Doc->PageColors.insert(it.key(), it.value());
-			importedColors.append(it.key());
-		}
-	}
-	Elements.clear();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	m_Doc->scMW()->setScriptRunning(true);
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	QImage tmpImage;
-	if (convert(fName))
-	{
-		tmpSel->clear();
-		QDir::setCurrent(CurDirP);
-		if (Elements.count() > 1)
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->m_Selection->delaySignalsOn();
-		for (int dre=0; dre<Elements.count(); ++dre)
-		{
-			tmpSel->addItem(Elements.at(dre), true);
-		}
-		tmpSel->setGroupRect();
-		double xs = tmpSel->width();
-		double ys = tmpSel->height();
-		tmpImage = Elements.at(0)->DrawObj_toImage(500);
-		tmpImage.setText("XSize", QString("%1").arg(xs));
-		tmpImage.setText("YSize", QString("%1").arg(ys));
-		m_Doc->m_Selection->delaySignalsOff();
-	}
-	else
-		tmpImage = QImage();
-	m_Doc->scMW()->setScriptRunning(false);
-	m_Doc->setLoading(false);
-	delete m_Doc;
-	QDir::setCurrent(CurDirP);
-	return tmpImage;
-}
-
-bool AIPlug::readColors(const QString& fNameIn, ColorList & colors)
-{
-	QString fName = fNameIn;
-	bool success = false;
-	cancel = false;
-	double x, y, b, h;
-	convertedPDF = false;
-	CustColors.clear();
-	importedColors.clear();
-	importedGradients.clear();
-	importedPatterns.clear();
-	QFileInfo fi = QFileInfo(fName);
-/* Check if the file is an old style AI or one of the newer PDF wrapped ones */
-	QFile fT(fName);
-	if (fT.open(QIODevice::ReadOnly))
-	{
-		QByteArray tempBuf(9, ' ');
-		fT.read(tempBuf.data(), 8);
-		fT.close();
-		if (tempBuf.startsWith("%PDF"))
-		{
-			QFileInfo bF2(fName);
-			QString tmpFile = ScPaths::getTempFileDir()+ "/"+bF2.baseName()+"_tmp.ai";
-			if (!extractFromPDF(fName, tmpFile))
-				return false;
-			convertedPDF = true;
-			fName = tmpFile;
-		}
-	}
-	QFile fT2(fName);
-	if (fT2.open(QIODevice::ReadOnly))
-	{
-		QByteArray tempBuf(25, ' ');
-		fT2.read(tempBuf.data(), 20);
-		fT2.close();
-		/* Illustrator CS files might be compressed
-			the compressed Data starts right after the "%AI12_CompressedData" comment
-			Compression is a simple zlib compression */
-		if (tempBuf.startsWith("%AI12_CompressedData"))
-			decompressAIData(fName);
-	}
-	progressDialog = NULL;
-/* Set default Page to size defined in Preferences */
-	x = 0.0;
-	y = 0.0;
-	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	parseHeader(fName, x, y, b, h);
-	docX = x;
-	docY = y;
-	docWidth = b - x;
-	docHeight = h - y;
-	m_Doc = new ScribusDoc();
-	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
-	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
-	m_Doc->addPage(0);
-	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
-	baseX = m_Doc->currentPage()->xOffset();
-	baseY = m_Doc->currentPage()->yOffset();
-	ColorList::Iterator it;
-	for (it = CustColors.begin(); it != CustColors.end(); ++it)
-	{
-		if (!m_Doc->PageColors.contains(it.key()))
-		{
-			m_Doc->PageColors.insert(it.key(), it.value());
-			importedColors.append(it.key());
-		}
-	}
-	Elements.clear();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	m_Doc->scMW()->setScriptRunning(true);
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	convert(fName);
-	if (importedColors.count() != 0)
-	{
-		colors = m_Doc->PageColors;
-		success = true;
-	}
-	m_Doc->scMW()->setScriptRunning(false);
-	m_Doc->setLoading(false);
-	delete m_Doc;
-	QDir::setCurrent(CurDirP);
-	if (convertedPDF)
-		QFile::remove(fName);
-	return success;
-}
-
-bool AIPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
-{
-	QString fName = fNameIn;
-	bool success = false;
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-	importerFlags = flags;
-	cancel = false;
-	double x, y, b, h;
-	bool ret = false;
-	convertedPDF = false;
-	CustColors.clear();
-	importedColors.clear();
-	importedGradients.clear();
-	importedPatterns.clear();
-	QFileInfo fi = QFileInfo(fName);
-//	QString ext = fi.suffix().toLower();
-	if ( !ScCore->usingGUI() )
-	{
-		interactive = false;
-		showProgress = false;
-	}
-	
-/* Check if the file is an old style AI or one of the newer PDF wrapped ones */
-	QFile fT(fName);
-	if (fT.open(QIODevice::ReadOnly))
-	{
-		QByteArray tempBuf(9, ' ');
-		fT.read(tempBuf.data(), 8);
-		fT.close();
-		if (tempBuf.startsWith("%PDF"))
-		{
-			QFileInfo bF2(fName);
-			QString tmpFile = ScPaths::getTempFileDir()+ "/"+bF2.baseName()+"_tmp.ai";
-			if (!extractFromPDF(fName, tmpFile))
-				return false;
-			convertedPDF = true;
-			fName = tmpFile;
-		}
-	}
-	QFile fT2(fName);
-	if (fT2.open(QIODevice::ReadOnly))
-	{
-		QByteArray tempBuf(25, ' ');
-		fT2.read(tempBuf.data(), 20);
-		fT2.close();
-		/* Illustrator CS files might be compressed
-			the compressed Data starts right after the "%AI12_CompressedData" comment
-			Compression is a simple zlib compression */
-		if (tempBuf.startsWith("%AI12_CompressedData"))
-			decompressAIData(fName);
-	}
-	if ( showProgress )
-	{
-		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
-		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
-		QStringList barNames, barTexts;
-		barNames << "GI";
-		barTexts << tr("Analyzing File:");
-		QList<bool> barsNumeric;
-		barsNumeric << false;
-		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
-		progressDialog->setOverallTotalSteps(3);
-		progressDialog->setOverallProgress(0);
-		progressDialog->setProgress("GI", 0);
-		progressDialog->show();
-		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
-		qApp->processEvents();
-	}
-	else
-		progressDialog = NULL;
-/* Set default Page to size defined in Preferences */
-	x = 0.0;
-	y = 0.0;
-	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	if (progressDialog)
-	{
-		progressDialog->setOverallProgress(1);
-		qApp->processEvents();
-	}
-	parseHeader(fName, x, y, b, h);
-	if (b == 0)
-		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	if (h == 0)
-		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	docX = x;
-	docY = y;
-	docWidth = b - x;
-	docHeight = h - y;
-	baseX = 0;
-	baseY = 0;
-	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
-	{
-		m_Doc->setPage(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false);
-		m_Doc->addPage(0);
-		m_Doc->view()->addPage(0, true);
-		baseX = 0;
-		baseY = 0;
-	}
-	else
-	{
-		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
-		{
-			m_Doc=ScCore->primaryMainWindow()->doFileNew(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
-			ScCore->primaryMainWindow()->HaveNewDoc();
-			ret = true;
-			baseX = 0;
-			baseY = 0;
-		}
-	}
-	if (flags & LoadSavePlugin::lfCreateDoc)
-	{
-		m_Doc->documentInfo().setAuthor(docCreator);
-		m_Doc->documentInfo().setPublisher(docOrganisation);
-		m_Doc->documentInfo().setTitle(docTitle);
-		m_Doc->documentInfo().setDate(docDate+" "+docTime);
-	}
-	if ((!ret) && (interactive))
-	{
-		baseX = m_Doc->currentPage()->xOffset();
-		baseY = m_Doc->currentPage()->yOffset();
-	}
-	if ((ret) || (!interactive))
-	{
-		if (b-x > h-y)
-			m_Doc->setPageOrientation(1);
-		else
-			m_Doc->setPageOrientation(0);
-		m_Doc->setPageSize("Custom");
-	}
-	ColorList::Iterator it;
-	for (it = CustColors.begin(); it != CustColors.end(); ++it)
-	{
-		if (!m_Doc->PageColors.contains(it.key()))
-		{
-			m_Doc->PageColors.insert(it.key(), it.value());
-			importedColors.append(it.key());
-		}
-	}
+/*
+For general Scribus (>=1.3.2) copyright and licensing information please refer
+to the COPYING file provided with the program. Following this notice may exist
+a copyright and/or license notice that predates the release of Scribus 1.3.2
+for which a new license (GPL+exception) is in place.
+*/
+
+#include <QByteArray>
+#include <QCursor>
+#include <QDrag>
+#include <QFile>
+#include <QList>
+#include <QMimeData>
+#include <QRegExp>
+#include <QStack>
+#include <QTemporaryFile>
+#include <QDebug>
+
+#include <cstdlib>
+#include <tiffio.h>
+#include <zlib.h>
+
+#include "commonstrings.h"
+
+#include "importai.h"
+#include "loadsaveplugin.h"
+#include "prefscontext.h"
+#include "prefsfile.h"
+#include "prefsmanager.h"
+#include "prefstable.h"
+#include "rawimage.h"
+#include "sccolorengine.h"
+#include "scconfig.h"
+#include "scclocale.h"
+#include "scmimedata.h"
+#include "scpaths.h"
+#include "scpattern.h"
+#include "scribus.h"
+#include "scribusXml.h"
+#include "scribuscore.h"
+#include "scribusdoc.h"
+#include "sctextstream.h"
+#include "selection.h"
+#include "text/specialchars.h"
+#include "ui/customfdialog.h"
+#include "ui/missing.h"
+#include "ui/multiprogressdialog.h"
+#include "ui/propertiespalette.h"
+#include "undomanager.h"
+#include "util.h"
+#include "util_color.h"
+#include "util_file.h"
+#include "util_formats.h"
+#include "util_icon.h"
+#include "util_math.h"
+#include "util_ghostscript.h"
+
+#include <cairo.h>
+
+#ifdef HAVE_PODOFO
+	#include <podofo/podofo.h>
+#endif
+
+extern SCRIBUS_API ScribusQApp * ScQApp;
+
+AIPlug::AIPlug(ScribusDoc* doc, int flags)
+{
+	tmpSel=new Selection(this, false);
+	m_Doc=doc;
+	importerFlags = flags;
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+	progressDialog = NULL;
+}
+
+QImage AIPlug::readThumbnail(QString fNameIn)
+{
+	QString fName = fNameIn;
+	double x, y, b, h;
+	CustColors.clear();
+	importedColors.clear();
+	importedGradients.clear();
+	importedPatterns.clear();
+	QFileInfo fi = QFileInfo(fName);
+/* Check if the file is an old style AI or one of the newer PDF wrapped ones */
+	QFile fT(fName);
+	if (fT.open(QIODevice::ReadOnly))
+	{
+		QByteArray tempBuf(9, ' ');
+		fT.read(tempBuf.data(), 8);
+		fT.close();
+		if (tempBuf.startsWith("%PDF"))
+		{
+			QString tmp, cmd1, cmd2;
+			QString pdfFile = QDir::toNativeSeparators(fName);
+			QString tmpFile = QDir::toNativeSeparators(ScPaths::getTempFileDir() + "sc.png");
+			int ret = -1;
+			tmp.setNum(1);
+			QStringList args;
+			args.append("-r72");
+			args.append("-sOutputFile="+tmpFile);
+			args.append("-dFirstPage="+tmp);
+			args.append("-dLastPage="+tmp);
+			args.append(pdfFile);
+			ret = callGS(args);
+			if (ret == 0)
+			{
+				QImage image;
+				image.load(tmpFile);
+				QFile::remove(tmpFile);
+				image.setText("XSize", QString("%1").arg(image.width()));
+				image.setText("YSize", QString("%1").arg(image.height()));
+				return image;
+			}
+			else
+				return QImage();
+		}
+	}
+	QFile fT2(fName);
+	if (fT2.open(QIODevice::ReadOnly))
+	{
+		QByteArray tempBuf(25, ' ');
+		fT2.read(tempBuf.data(), 20);
+		fT2.close();
+		/* Illustrator CS files might be compressed
+			the compressed Data starts right after the "%AI12_CompressedData" comment
+			Compression is a simple zlib compression */
+		if (tempBuf.startsWith("%AI12_CompressedData"))
+			decompressAIData(fName);
+	}
+	progressDialog = NULL;
+/* Set default Page to size defined in Preferences */
+	x = 0.0;
+	y = 0.0;
+	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	parseHeader(fName, x, y, b, h);
+	if (b == 0)
+		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	if (h == 0)
+		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	docX = x;
+	docY = y;
+	docWidth = b - x;
+	docHeight = h - y;
+	baseX = 0;
+	baseY = 0;
+	m_Doc = new ScribusDoc();
+	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
+	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
+	m_Doc->addPage(0);
+	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
+	baseX = m_Doc->currentPage()->xOffset();
+	baseY = m_Doc->currentPage()->yOffset();
+	ColorList::Iterator it;
+	for (it = CustColors.begin(); it != CustColors.end(); ++it)
+	{
+		if (!m_Doc->PageColors.contains(it.key()))
+		{
+			m_Doc->PageColors.insert(it.key(), it.value());
+			importedColors.append(it.key());
+		}
+	}
+	Elements.clear();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	m_Doc->scMW()->setScriptRunning(true);
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	QImage tmpImage;
+	if (convert(fName))
+	{
+		tmpSel->clear();
+		QDir::setCurrent(CurDirP);
+		if (Elements.count() > 1)
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->m_Selection->delaySignalsOn();
+		for (int dre=0; dre<Elements.count(); ++dre)
+		{
+			tmpSel->addItem(Elements.at(dre), true);
+		}
+		tmpSel->setGroupRect();
+		double xs = tmpSel->width();
+		double ys = tmpSel->height();
+		tmpImage = Elements.at(0)->DrawObj_toImage(500);
+		tmpImage.setText("XSize", QString("%1").arg(xs));
+		tmpImage.setText("YSize", QString("%1").arg(ys));
+		m_Doc->m_Selection->delaySignalsOff();
+	}
+	else
+		tmpImage = QImage();
+	m_Doc->scMW()->setScriptRunning(false);
+	m_Doc->setLoading(false);
+	delete m_Doc;
+	QDir::setCurrent(CurDirP);
+	return tmpImage;
+}
+
+bool AIPlug::readColors(const QString& fNameIn, ColorList & colors)
+{
+	QString fName = fNameIn;
+	bool success = false;
+	cancel = false;
+	double x, y, b, h;
+	convertedPDF = false;
+	CustColors.clear();
+	importedColors.clear();
+	importedGradients.clear();
+	importedPatterns.clear();
+	QFileInfo fi = QFileInfo(fName);
+/* Check if the file is an old style AI or one of the newer PDF wrapped ones */
+	QFile fT(fName);
+	if (fT.open(QIODevice::ReadOnly))
+	{
+		QByteArray tempBuf(9, ' ');
+		fT.read(tempBuf.data(), 8);
+		fT.close();
+		if (tempBuf.startsWith("%PDF"))
+		{
+			QFileInfo bF2(fName);
+			QString tmpFile = ScPaths::getTempFileDir()+ "/"+bF2.baseName()+"_tmp.ai";
+			if (!extractFromPDF(fName, tmpFile))
+				return false;
+			convertedPDF = true;
+			fName = tmpFile;
+		}
+	}
+	QFile fT2(fName);
+	if (fT2.open(QIODevice::ReadOnly))
+	{
+		QByteArray tempBuf(25, ' ');
+		fT2.read(tempBuf.data(), 20);
+		fT2.close();
+		/* Illustrator CS files might be compressed
+			the compressed Data starts right after the "%AI12_CompressedData" comment
+			Compression is a simple zlib compression */
+		if (tempBuf.startsWith("%AI12_CompressedData"))
+			decompressAIData(fName);
+	}
+	progressDialog = NULL;
+/* Set default Page to size defined in Preferences */
+	x = 0.0;
+	y = 0.0;
+	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	parseHeader(fName, x, y, b, h);
+	docX = x;
+	docY = y;
+	docWidth = b - x;
+	docHeight = h - y;
+	m_Doc = new ScribusDoc();
+	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
+	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
+	m_Doc->addPage(0);
+	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
+	baseX = m_Doc->currentPage()->xOffset();
+	baseY = m_Doc->currentPage()->yOffset();
+	ColorList::Iterator it;
+	for (it = CustColors.begin(); it != CustColors.end(); ++it)
+	{
+		if (!m_Doc->PageColors.contains(it.key()))
+		{
+			m_Doc->PageColors.insert(it.key(), it.value());
+			importedColors.append(it.key());
+		}
+	}
+	Elements.clear();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	m_Doc->scMW()->setScriptRunning(true);
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	convert(fName);
+	if (importedColors.count() != 0)
+	{
+		colors = m_Doc->PageColors;
+		success = true;
+	}
+	m_Doc->scMW()->setScriptRunning(false);
+	m_Doc->setLoading(false);
+	delete m_Doc;
+	QDir::setCurrent(CurDirP);
+	if (convertedPDF)
+		QFile::remove(fName);
+	return success;
+}
+
+bool AIPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
+{
+	QString fName = fNameIn;
+	bool success = false;
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+	importerFlags = flags;
+	cancel = false;
+	double x, y, b, h;
+	bool ret = false;
+	convertedPDF = false;
+	CustColors.clear();
+	importedColors.clear();
+	importedGradients.clear();
+	importedPatterns.clear();
+	QFileInfo fi = QFileInfo(fName);
+//	QString ext = fi.suffix().toLower();
+	if ( !ScCore->usingGUI() )
+	{
+		interactive = false;
+		showProgress = false;
+	}
+	
+/* Check if the file is an old style AI or one of the newer PDF wrapped ones */
+	QFile fT(fName);
+	if (fT.open(QIODevice::ReadOnly))
+	{
+		QByteArray tempBuf(9, ' ');
+		fT.read(tempBuf.data(), 8);
+		fT.close();
+		if (tempBuf.startsWith("%PDF"))
+		{
+			QFileInfo bF2(fName);
+			QString tmpFile = ScPaths::getTempFileDir()+ "/"+bF2.baseName()+"_tmp.ai";
+			if (!extractFromPDF(fName, tmpFile))
+				return false;
+			convertedPDF = true;
+			fName = tmpFile;
+		}
+	}
+	QFile fT2(fName);
+	if (fT2.open(QIODevice::ReadOnly))
+	{
+		QByteArray tempBuf(25, ' ');
+		fT2.read(tempBuf.data(), 20);
+		fT2.close();
+		/* Illustrator CS files might be compressed
+			the compressed Data starts right after the "%AI12_CompressedData" comment
+			Compression is a simple zlib compression */
+		if (tempBuf.startsWith("%AI12_CompressedData"))
+			decompressAIData(fName);
+	}
+	if ( showProgress )
+	{
+		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
+		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
+		QStringList barNames, barTexts;
+		barNames << "GI";
+		barTexts << tr("Analyzing File:");
+		QList<bool> barsNumeric;
+		barsNumeric << false;
+		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
+		progressDialog->setOverallTotalSteps(3);
+		progressDialog->setOverallProgress(0);
+		progressDialog->setProgress("GI", 0);
+		progressDialog->show();
+		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
+		qApp->processEvents();
+	}
+	else
+		progressDialog = NULL;
+/* Set default Page to size defined in Preferences */
+	x = 0.0;
+	y = 0.0;
+	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	if (progressDialog)
+	{
+		progressDialog->setOverallProgress(1);
+		qApp->processEvents();
+	}
+	parseHeader(fName, x, y, b, h);
+	if (b == 0)
+		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	if (h == 0)
+		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	docX = x;
+	docY = y;
+	docWidth = b - x;
+	docHeight = h - y;
+	baseX = 0;
+	baseY = 0;
+	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
+	{
+		m_Doc->setPage(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false);
+		m_Doc->addPage(0);
+		m_Doc->view()->addPage(0, true);
+		baseX = 0;
+		baseY = 0;
+	}
+	else
+	{
+		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
+		{
+			m_Doc=ScCore->primaryMainWindow()->doFileNew(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
+			ScCore->primaryMainWindow()->HaveNewDoc();
+			ret = true;
+			baseX = 0;
+			baseY = 0;
+		}
+	}
+	if (flags & LoadSavePlugin::lfCreateDoc)
+	{
+		m_Doc->documentInfo().setAuthor(docCreator);
+		m_Doc->documentInfo().setPublisher(docOrganisation);
+		m_Doc->documentInfo().setTitle(docTitle);
+		m_Doc->documentInfo().setDate(docDate+" "+docTime);
+	}
+	if ((!ret) && (interactive))
+	{
+		baseX = m_Doc->currentPage()->xOffset();
+		baseY = m_Doc->currentPage()->yOffset();
+	}
+	if ((ret) || (!interactive))
+	{
+		if (b-x > h-y)
+			m_Doc->setPageOrientation(1);
+		else
+			m_Doc->setPageOrientation(0);
+		m_Doc->setPageSize("Custom");
+	}
+	ColorList::Iterator it;
+	for (it = CustColors.begin(); it != CustColors.end(); ++it)
+	{
+		if (!m_Doc->PageColors.contains(it.key()))
+		{
+			m_Doc->PageColors.insert(it.key(), it.value());
+			importedColors.append(it.key());
+		}
+	}
 	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->Deselect();
-	Elements.clear();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->updatesOn(false);
-	m_Doc->scMW()->setScriptRunning(true);
-	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	if (convert(fName))
-	{
-		if (Elements.count() == 0)
-		{
-			if ((importedColors.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients) || (flags & LoadSavePlugin::lfKeepColors) || (flags & LoadSavePlugin::lfKeepPatterns))))
-			{
-				for (int cd = 0; cd < importedColors.count(); cd++)
-				{
-					m_Doc->PageColors.remove(importedColors[cd]);
-				}
-			}
-			if ((importedGradients.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients || (flags & LoadSavePlugin::lfKeepPatterns)))))
-			{
-				for (int cd = 0; cd < importedGradients.count(); cd++)
-				{
-					m_Doc->docGradients.remove(importedGradients[cd]);
-				}
-			}
-			if ((importedPatterns.count() != 0) && (!(flags & LoadSavePlugin::lfKeepPatterns)))
-			{
-				for (int cd = 0; cd < importedPatterns.count(); cd++)
-				{
-					m_Doc->docPatterns.remove(importedPatterns[cd]);
-				}
-			}
-		}
-		tmpSel->clear();
-		QDir::setCurrent(CurDirP);
-		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->setLoading(false);
-		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-		if ((Elements.count() > 0) && (!ret) && (interactive))
-		{
-			if (flags & LoadSavePlugin::lfScripted)
-			{
-				bool loadF = m_Doc->isLoading();
-				m_Doc->setLoading(false);
-				m_Doc->changed();
-				m_Doc->setLoading(loadF);
-				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-				{
-					m_Doc->m_Selection->delaySignalsOn();
-					for (int dre=0; dre<Elements.count(); ++dre)
-					{
-						m_Doc->m_Selection->addItem(Elements.at(dre), true);
-					}
-					m_Doc->m_Selection->delaySignalsOff();
-					m_Doc->m_Selection->setGroupRect();
-					m_Doc->view()->updatesOn(true);
-				}
-			}
-			else
-			{
-				m_Doc->DragP = true;
-				m_Doc->DraggedElem = 0;
-				m_Doc->DragElements.clear();
-				m_Doc->m_Selection->delaySignalsOn();
-				for (int dre=0; dre<Elements.count(); ++dre)
-				{
-					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
-					tmpSel->addItem(Elements.at(dre), true);
-				}
-				tmpSel->setGroupRect();
-				ScriXmlDoc *ss = new ScriXmlDoc();
-				ScElemMimeData* md = new ScElemMimeData();
-				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
-				delete ss;
-/*#ifndef Q_WS_MAC*/
-// see #2196
-				m_Doc->itemSelection_DeleteItem(tmpSel);
-/*#else
-				qDebug("aiimport: leaving items on page");
-#endif*/
-				m_Doc->view()->updatesOn(true);
-				if ((importedColors.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients) || (flags & LoadSavePlugin::lfKeepColors) || (flags & LoadSavePlugin::lfKeepPatterns))))
-				{
-					for (int cd = 0; cd < importedColors.count(); cd++)
-					{
-						m_Doc->PageColors.remove(importedColors[cd]);
-					}
-				}
-				if ((importedGradients.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients || (flags & LoadSavePlugin::lfKeepPatterns)))))
-				{
-					for (int cd = 0; cd < importedGradients.count(); cd++)
-					{
-						m_Doc->docGradients.remove(importedGradients[cd]);
-					}
-				}
-				if ((importedPatterns.count() != 0) && (!(flags & LoadSavePlugin::lfKeepPatterns)))
-				{
-					for (int cd = 0; cd < importedPatterns.count(); cd++)
-					{
-						m_Doc->docPatterns.remove(importedPatterns[cd]);
-					}
-				}
-				m_Doc->m_Selection->delaySignalsOff();
-				// We must copy the TransationSettings object as it is owned
-				// by handleObjectImport method afterwards
-				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
-				m_Doc->view()->handleObjectImport(md, transacSettings);
-				m_Doc->DragP = false;
-				m_Doc->DraggedElem = 0;
-				m_Doc->DragElements.clear();
-			}
-		}
-		else
-		{
-			m_Doc->changed();
-			m_Doc->reformPages();
-			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-				m_Doc->view()->updatesOn(true);
-		}
-		success = true;
-	}
-	else
-	{
-		QDir::setCurrent(CurDirP);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->view()->updatesOn(true);
-		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-	}
-	if (interactive)
-		m_Doc->setLoading(false);
-	//CB If we have a gui we must refresh it if we have used the progressbar
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-	{
-		if ((showProgress) && (!interactive))
-			m_Doc->view()->DrawNew();
-	}
-	if (convertedPDF)
-		QFile::remove(fName);
-	return success;
-}
-
-AIPlug::~AIPlug()
-{
-	if (progressDialog)
-		delete progressDialog;
-	delete tmpSel;
-}
-
-bool AIPlug::extractFromPDF(QString infile, QString outfile)
-{
-	bool ret = false;
-#ifdef HAVE_PODOFO
-	QFile outf(outfile);
-	outf.open(QIODevice::WriteOnly);
-	try
-	{
-		PoDoFo::PdfError::EnableDebug( false );
-#if (PODOFO_VERSION == 0 && PODOFO_MINOR > 6)
-		PoDoFo::PdfError::EnableLogging( false );
-#endif
-#if (PODOFO_VERSION == 0 && PODOFO_MINOR == 5 && PODOFO_REVISION == 99) || PODOFO_MINOR > 5
-		PoDoFo::PdfMemDocument doc( infile.toLocal8Bit().data() );
-#else
-		PoDoFo::PdfDocument doc( infile.toLocal8Bit().data() );
-#endif
-		PoDoFo::PdfPage *curPage = doc.GetPage(0);
-		if (curPage != NULL)
-		{
-			PoDoFo::PdfObject *piece = curPage->GetObject()->GetIndirectKey("PieceInfo");
-			if (piece != NULL)
-			{
-				PoDoFo::PdfObject *illy = piece->GetIndirectKey("Illustrator");
-				if (illy != NULL)
-				{
-					PoDoFo::PdfObject *priv = illy->GetIndirectKey("Private");
-					if (priv == NULL)
-						priv = illy;
-					int num = 0;
-					PoDoFo::PdfObject *numBl = priv->GetIndirectKey("NumBlock");
-					if (numBl != NULL)
-						num = numBl->GetNumber() + 1;
-					if (num == 0)
-						num = 99999;
-					QString name = "AIPrivateData%1";
-					QString Key = name.arg(1);
-					PoDoFo::PdfObject *data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
-					if (data == NULL)
-					{
-						name = "AIPDFPrivateData%1";
-						Key = name.arg(1);
-						data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
-					}
-					if (data != NULL)
-					{
-						if (num == 2)
-						{
-							Key = name.arg(1);
-							data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
-							PoDoFo::PdfStream const *stream = data->GetStream();
-							PoDoFo::PdfMemoryOutputStream oStream(1);
-							stream->GetFilteredCopy(&oStream);
-							oStream.Close();
-							long bLen = oStream.GetLength();
-							char *Buffer = oStream.TakeBuffer();
-							outf.write(Buffer, bLen);
-							free( Buffer );
-						}
-						else
-						{
-							for (int a = 2; a < num; a++)
-							{
-								Key = name.arg(a);
-								data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
-								if (data == NULL)
-									break;
-								PoDoFo::PdfStream const *stream = data->GetStream();
-								PoDoFo::PdfMemoryOutputStream oStream(1);
-								stream->GetFilteredCopy(&oStream);
-								oStream.Close();
-								long bLen = oStream.GetLength();
-								char *Buffer = oStream.TakeBuffer();
-								outf.write(Buffer, bLen);
-								free( Buffer );
-							}
-						}
-					}
-					ret = true;
-				}
-			}
-		}
-		outf.close();
-	}
-	catch (PoDoFo::PdfError& e)
-	{
-		outf.close();
-		qDebug("Scribus caught and handled the following exception from PoDoFo while processing a PDF format ai file:\n----\n");
-		e.PrintErrorMsg();
-		qDebug("----\nThe ai file could not be imported.\n");
-		QFile::remove(outfile);
-		return false;
-	}
-#endif
-	return ret;
-}
-
-bool AIPlug::decompressAIData(QString &fName)
-{
-	QString f2 = fName+"_decom.ai";
-	FILE *source = fopen(fName.toLocal8Bit().constData(), "rb");
-	fseek(source, 20, SEEK_SET);
-	FILE *dest = fopen(f2.toLocal8Bit().constData(), "wb");
-	int ret;
-	unsigned have;
-	z_stream strm;
-	char in[4096];
-	char out[4096];
-	strm.zalloc = Z_NULL;
-	strm.zfree = Z_NULL;
-	strm.opaque = Z_NULL;
-	strm.avail_in = 0;
-	strm.next_in = Z_NULL;
-	ret = inflateInit(&strm);
-	if (ret != Z_OK)
-		return false;
-	do
-	{
-		strm.avail_in = fread(in, 1, 4096, source);
-		if (ferror(source))
-		{
-			(void)inflateEnd(&strm);
-			return false;
-		}
-		if (strm.avail_in == 0)
-			break;
-		strm.next_in = (Bytef*)in;
-		do
-		{
-			strm.avail_out = 4096;
-			strm.next_out = (Bytef*)out;
-			ret = inflate(&strm, Z_NO_FLUSH);
-			assert(ret != Z_STREAM_ERROR);
-			switch (ret)
-			{
-				case Z_NEED_DICT:
-					ret = Z_DATA_ERROR;
-				case Z_DATA_ERROR:
-				case Z_MEM_ERROR:
-					(void)inflateEnd(&strm);
-					return false;
-			}
-			have = 4096 - strm.avail_out;
-			if (fwrite(out, 1, have, dest) != have || ferror(dest))
-			{
-				(void)inflateEnd(&strm);
-				return false;
-			}
-		}
-		while (strm.avail_out == 0);
-	}
-	while (ret != Z_STREAM_END);
-	(void)inflateEnd(&strm);
-	fclose(source);
-	fclose(dest);
-	if (!convertedPDF)
-	{
-		QFileInfo bF2(fName);
-		QString tmpFile = ScPaths::getTempFileDir()+ "/"+bF2.baseName()+"_tmp.ai";
-		moveFile(f2, tmpFile);
-		fName = tmpFile;
-		convertedPDF = true;
-	}
-	else
-	{
-		QFile::remove(fName);
-		fName = f2;
-	}
-	return true;
-}
-
-bool AIPlug::parseHeader(QString fName, double &x, double &y, double &b, double &h)
-{
-	QString tmp, BBox, tmp2, FarNam;
-	ScColor cc;
-	double c, m, yc, k;
-	bool found = false;
-	QFile f(fName);
-	if (f.open(QIODevice::ReadOnly))
-	{
-/* Try to find Bounding Box */
-		bool isAtend = false;
-		QDataStream ts(&f);
-		while (!ts.atEnd())
-		{
-			tmp = readLinefromDataStream(ts);
-			if (tmp.startsWith("%%BoundingBox:"))
-			{
-				found = true;
-				BBox = tmp.remove("%%BoundingBox:");
-			}
-			if (!found)
-			{
-				if (tmp.startsWith("%%BoundingBox"))
-				{
-					found = true;
-					BBox = tmp.remove("%%BoundingBox");
-				}
-			}
-			if (tmp.startsWith("%%HiResBoundingBox:"))
-			{
-				found = true;
-				BBox = tmp.remove("%%HiResBoundingBox:");
-			}
-		//	if (tmp.startsWith("%AI3_TileBox:"))
-		//	{
-		//		found = true;
-		//		BBox = tmp.remove("%AI3_TileBox:");
-		//	}
-			if (tmp.startsWith("%%For"))
-			{
-				QStringList res = getStrings(tmp);
-				if (res.count() > 1)
-				{
-					docCreator = res[0];
-					docOrganisation = res[1];
-				}
-			}
-			if (tmp.startsWith("%%CreationDate:"))
-			{
-				QStringList res = getStrings(tmp);
-				if (res.count() > 1)
-				{
-					docDate = res[0];
-					docTime = res[1];
-				}
-				else
-				{
-					docDate = tmp.remove("%%CreationDate: ");
-					docTime = "";
-				}
-			}
-			if (tmp.startsWith("%%Title"))
-			{
-				QStringList res = getStrings(tmp);
-				if (res.count() > 0)
-					docTitle = res[0];
-			}
-			if ((tmp.startsWith("%%CMYKCustomColor")) || (tmp.startsWith("%%CMYKProcessColor")))
-			{
-				if (tmp.contains("(atend)"))
-					isAtend = true;
-				else
-				{
-					if (tmp.startsWith("%%CMYKCustomColor"))
-						tmp = tmp.remove(0,18);
-					else if (tmp.startsWith("%%CMYKProcessColor"))
-						tmp = tmp.remove(0,19);
-					ScTextStream ts2(&tmp, QIODevice::ReadOnly);
-					ts2 >> c >> m >> yc >> k;
-					FarNam = ts2.readAll();
-					FarNam = FarNam.trimmed();
-					FarNam = FarNam.remove(0,1);
-					FarNam = FarNam.remove(FarNam.length()-1,1);
-					FarNam = FarNam.simplified();
-					QByteArray farN;
-					for (int a = 0; a < FarNam.length(); a++)
-					{
-						QChar ch = FarNam.at(a);
-						uint chc = ch.unicode();
-						if (chc > 255)
-							farN.append(chc >> 8);
-						farN.append(chc & 0x00FF);
-					}
-					FarNam = QString::fromUtf8(farN.constData());
-					cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc), qRound(255 * k));
-					cc.setSpotColor(true);
-					if (!FarNam.isEmpty())
-						CustColors.tryAddColor(FarNam, cc);
-					while (!ts.atEnd())
-					{
-						quint64 oldPos = ts.device()->pos();
-						tmp = readLinefromDataStream(ts);
-						if (!tmp.startsWith("%%+"))
-						{
-							ts.device()->seek(oldPos);
-							break;
-						}
-						tmp = tmp.remove(0,3);
-						ScTextStream ts2(&tmp, QIODevice::ReadOnly);
-						ts2 >> c >> m >> yc >> k;
-						FarNam = ts2.readAll();
-						FarNam = FarNam.trimmed();
-						FarNam = FarNam.remove(0,1);
-						FarNam = FarNam.remove(FarNam.length()-1,1);
-						FarNam = FarNam.simplified();
-						QByteArray farN;
-						for (int a = 0; a < FarNam.length(); a++)
-						{
-							QChar ch = FarNam.at(a);
-							uint chc = ch.unicode();
-							if (chc > 255)
-								farN.append(chc >> 8);
-							farN.append(chc & 0x00FF);
-						}
-						FarNam = QString::fromUtf8(farN.constData());
-						cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc), qRound(255 * k));
-						cc.setSpotColor(true);
-						if (!FarNam.isEmpty())
-							CustColors.tryAddColor(FarNam, cc);
-					}
-				}
-			}
-			if ((tmp.startsWith("%%RGBCustomColor")) || (tmp.startsWith("%%RGBProcessColor")))
-			{
-				if (tmp.contains("(atend)"))
-					isAtend = true;
-				else
-				{
-					if (tmp.startsWith("%%RGBCustomColor"))
-						tmp = tmp.remove(0,17);
-					else if (tmp.startsWith("%%RGBProcessColor"))
-						tmp = tmp.remove(0,18);
-					ScTextStream ts2(&tmp, QIODevice::ReadOnly);
-					ts2 >> c >> m >> yc;
-					FarNam = ts2.readAll();
-					FarNam = FarNam.trimmed();
-					FarNam = FarNam.remove(0,1);
-					FarNam = FarNam.remove(FarNam.length()-1,1);
-					FarNam = FarNam.simplified();
-					QByteArray farN;
-					for (int a = 0; a < FarNam.length(); a++)
-					{
-						QChar ch = FarNam.at(a);
-						uint chc = ch.unicode();
-						if (chc > 255)
-							farN.append(chc >> 8);
-						farN.append(chc & 0x00FF);
-					}
-					FarNam = QString::fromUtf8(farN.constData());
-					cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc));
-					if (!FarNam.isEmpty())
-						CustColors.tryAddColor(FarNam, cc);
-					while (!ts.atEnd())
-					{
-						quint64 oldPos = ts.device()->pos();
-						tmp = readLinefromDataStream(ts);
-						if (!tmp.startsWith("%%+"))
-						{
-							ts.device()->seek(oldPos);
-							break;
-						}
-						tmp = tmp.remove(0,3);
-						ScTextStream ts2(&tmp, QIODevice::ReadOnly);
-						ts2 >> c >> m >> yc;
-						FarNam = ts2.readAll();
-						FarNam = FarNam.trimmed();
-						FarNam = FarNam.remove(0,1);
-						FarNam = FarNam.remove(FarNam.length()-1,1);
-						FarNam = FarNam.simplified();
-						QByteArray farN;
-						for (int a = 0; a < FarNam.length(); a++)
-						{
-							QChar ch = FarNam.at(a);
-							uint chc = ch.unicode();
-							if (chc > 255)
-								farN.append(chc >> 8);
-							farN.append(chc & 0x00FF);
-						}
-						FarNam = QString::fromUtf8(farN.constData());
-						cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc));
-						if (!FarNam.isEmpty())
-							CustColors.tryAddColor(FarNam, cc);
-					}
-				}
-			}
-			if (tmp.startsWith("%%EndComments"))
-			{
-				while (!ts.atEnd())
-				{
-					bool isX = false;
-					tmp = readLinefromDataStream(ts);
-					if ((tmp.endsWith("Xa") || tmp.endsWith(" k") || tmp.endsWith(" x")) && (tmp.length() > 4))
-					{
-						ScTextStream ts2(&tmp, QIODevice::ReadOnly);
-						ts2 >> c >> m >> yc >> k;
-						if (tmp.endsWith(" x"))
-						{
-							isX = true;
-							int an = tmp.indexOf("(");
-							int en = tmp.lastIndexOf(")");
-							FarNam = tmp.mid(an+1, en-an-1);
-							FarNam = FarNam.simplified();
-							QByteArray farN;
-							for (int a = 0; a < FarNam.length(); a++)
-							{
-								QChar ch = FarNam.at(a);
-								uint chc = ch.unicode();
-								if (chc > 255)
-									farN.append(chc >> 8);
-								farN.append(chc & 0x00FF);
-							}
-							FarNam = QString::fromUtf8(farN.constData());
-						}
-						tmp = readLinefromDataStream(ts);
-						if (tmp.endsWith("Pc"))
-						{
-							if (!isX)
-							{
-								tmp = tmp.trimmed();
-								tmp = tmp.remove(0,1);
-								int en = tmp.indexOf(")");
-								FarNam = tmp.mid(0, en);
-								FarNam = FarNam.simplified();
-								QByteArray farN;
-								for (int a = 0; a < FarNam.length(); a++)
-								{
-									QChar ch = FarNam.at(a);
-									uint chc = ch.unicode();
-									if (chc > 255)
-										farN.append(chc >> 8);
-									farN.append(chc & 0x00FF);
-								}
-								FarNam = QString::fromUtf8(farN.constData());
-							}
-							cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc), qRound(255 * k));
-							cc.setSpotColor(true);
-							CustColors.tryAddColor(FarNam, cc);
-						}
-					}
-				}
-				if (!isAtend)
-					break;
-			}
-		}
-		f.close();
-		if (found)
-		{
-			QStringList bb = BBox.split(" ", QString::SkipEmptyParts);
-			if (bb.count() == 4)
-			{
-				x = ScCLocale::toDoubleC(bb[0]);
-				y = ScCLocale::toDoubleC(bb[1]);
-				b = ScCLocale::toDoubleC(bb[2]);
-				h = ScCLocale::toDoubleC(bb[3]);
-			}
-		}
-	}
-	return found;
-}
-
-QString AIPlug::removeAIPrefix(QString comment)
-{
-	QString tmp;
-	if (comment.startsWith("%AI"))
-	{
-		int an = comment.indexOf("_");
-		tmp = comment.remove(0, an+1);
-	}
-	else
-		tmp = comment;
-	return tmp;
-}
-
-QString AIPlug::parseColor(QString data)
-{
-	QString ret = CommonStrings::None;
-	if (data.isEmpty())
-		return ret;
-	double c, m, y, k;
-	ScColor tmp;
-	ScTextStream Code(&data, QIODevice::ReadOnly);
-	Code >> c;
-	Code >> m;
-	Code >> y;
-	Code >> k;
-	int Cc = qRound(c * 255);
-	int Mc = qRound(m * 255);
-	int Yc = qRound(y * 255);
-	int Kc = qRound(k * 255);
-	tmp.setColor(Cc, Mc, Yc, Kc);
-	tmp.setSpotColor(false);
-	tmp.setRegistrationColor(false);
-	QString namPrefix = "FromAI";
-	QString fNam = m_Doc->PageColors.tryAddColor(namPrefix+tmp.name(), tmp);
-	if (fNam == namPrefix+tmp.name())
-		importedColors.append(fNam);
-	ret = fNam;
-	meshColorMode = 0;
-	return ret;
-}
-
-QString AIPlug::parseColorGray(QString data)
-{
-	QString ret = CommonStrings::None;
-	if (data.isEmpty())
-		return ret;
-	double k;
-	ScColor tmp;
-	ColorList::Iterator it;
-	ScTextStream Code(&data, QIODevice::ReadOnly);
-	Code >> k;
-	int Kc = 255 - qRound(k * 255);
-	tmp.setColor(0, 0, 0, Kc);
-	tmp.setSpotColor(false);
-	tmp.setRegistrationColor(false);
-	QString namPrefix = "FromAI";
-	QString fNam = m_Doc->PageColors.tryAddColor(namPrefix+tmp.name(), tmp);
-	if (fNam == namPrefix+tmp.name())
-		importedColors.append(fNam);
-	ret = fNam;
-	meshColorMode = 2;
-	return ret;
-}
-
-QString AIPlug::parseColorRGB(QString data)
-{
-	QString ret = CommonStrings::None;
-	if (data.isEmpty())
-		return ret;
-	double r, g, b;
-	ScColor tmp;
-	ScTextStream Code(&data, QIODevice::ReadOnly);
-	Code >> r;
-	Code >> g;
-	Code >> b;
-	int Rc = qRound(r * 255);
-	int Gc = qRound(g * 255);
-	int Bc = qRound(b * 255);
-	tmp.setColorRGB(Rc, Gc, Bc);
-	tmp.setSpotColor(false);
-	tmp.setRegistrationColor(false);
-	QString namPrefix = "FromAI";
-	QString fNam = m_Doc->PageColors.tryAddColor(namPrefix+tmp.name(), tmp);
-	if (fNam == namPrefix+tmp.name())
-		importedColors.append(fNam);
-	ret = fNam;
-	meshColorMode = 1;
-	return ret;
-}
-
-QString AIPlug::parseCustomColor(QString data, double &shade)
-{
-	QString ret = CommonStrings::None;
-	if (data.isEmpty())
-		return ret;
-	double c, m, y, k, sh;
-	ScColor tmp;
-	ScTextStream Code(&data, QIODevice::ReadOnly);
-	Code >> c;
-	Code >> m;
-	Code >> y;
-	Code >> k;
-	QString tmpS = data;
-	int an = data.indexOf("(");
-	int en = data.lastIndexOf(")");
-	QString FarNam = data.mid(an+1, en-an-1);
-	FarNam.remove("\\");
-	QString FarSha = data.mid(en+1, data.size() - en);
-	ScTextStream Val(&FarSha, QIODevice::ReadOnly);
-	Val >> sh;
-	shade = (1.0 - sh) * 100.0;
-	int Cc = qRound(c * 255);
-	int Mc = qRound(m * 255);
-	int Yc = qRound(y * 255);
-	int Kc = qRound(k * 255);
-	tmp.setColor(Cc, Mc, Yc, Kc);
-	tmp.setSpotColor(true);
-	tmp.setRegistrationColor(false);
-	QString fNam = m_Doc->PageColors.tryAddColor(FarNam, tmp);
-	if (fNam == FarNam)
-		importedColors.append(FarNam);
-	ret = fNam;
-	meshColorMode = 0;
-	return ret;
-}
-
-QString AIPlug::parseCustomColorX(QString data, double &shade, QString type)
-{
-	QString ret = CommonStrings::None;
-	if (data.isEmpty())
-		return ret;
-	double c, m, y, k, sh, r, g, b;
-	ScColor tmp;
-	ScTextStream Code(&data, QIODevice::ReadOnly);
-	if (type == "1")
-	{
-		Code >> r;
-		Code >> g;
-		Code >> b;
-		int Rc = qRound(r * 255);
-		int Gc = qRound(g * 255);
-		int Bc = qRound(b * 255);
-		tmp.setColorRGB(Rc, Gc, Bc);
-		meshColorMode = 1;
-	}
-	else
-	{
-		Code >> c;
-		Code >> m;
-		Code >> y;
-		Code >> k;
-		int Cc = qRound(c * 255);
-		int Mc = qRound(m * 255);
-		int Yc = qRound(y * 255);
-		int Kc = qRound(k * 255);
-		tmp.setColor(Cc, Mc, Yc, Kc);
-		meshColorMode = 0;
-	}
-	QString tmpS = data;
-	int an = data.indexOf("(");
-	int en = data.lastIndexOf(")");
-	QString FarNam = data.mid(an+1, en-an-1);
-	FarNam.remove("\\");
-	QString FarSha = data.mid(en+1, data.size() - en);
-	ScTextStream Val(&FarSha, QIODevice::ReadOnly);
-	Val >> sh;
-	shade = (1.0 - sh) * 100.0;
-	if (type == "0")
-		tmp.setSpotColor(true);
-	tmp.setRegistrationColor(false);
-	QString fNam = m_Doc->PageColors.tryAddColor(FarNam, tmp);
-	if (fNam == FarNam)
-		importedColors.append(FarNam);
-	ret = fNam;
-	return ret;
-}
-
-QStringList AIPlug::getStrings(QString data)
-{
-	QStringList result;
-	result.clear();
-	QChar tmp;
-	QString tmp2 = "";
-	QString tmp3 = "";
-	bool paran = false;
-	bool skip = false;
-	int digitCount = 0;
-	for (int a = 0; a < data.count(); a++)
-	{
-		tmp = data[a];
-		if (skip)
-		{
-			if (paran)
-			{
-				if (tmp.isDigit())
-				{
-					tmp3 += tmp;
-					digitCount++;
-					if (digitCount == 3)
-					{
-						bool ok = false;
-						int code = tmp3.toInt(&ok, 8);
-						if (ok)
-							tmp2 += QChar(code);
-						digitCount = 0;
-						tmp3 = "";
-						skip = false;
-					}
-				}
-				else
-				{
-					if (tmp == 'r')
-						tmp = SpecialChars::PARSEP;
-					tmp2 += tmp;
-					skip = false;
-				}
-			}
-			continue;
-		}
-		if (tmp == '(')
-		{
-			paran = true;
-			continue;
-		}
-		if (tmp == ')')
-		{
-			paran = false;
-			result.append(tmp2);
-			tmp2 = "";
-			continue;
-		}
-		if (tmp == '\\')
-		{
-			skip = true;
-			continue;
-		}
-		if (paran)
-			tmp2 += tmp;
-	}
-	return result;
-}
-
-void AIPlug::getCommands(QString data, QStringList &commands)
-{
-	QString tmp;
-	QString tmp2;
-	QString tmp3;
-	bool paran = false;
-	bool arra = false;
-	bool skip = false;
-	for (int a = 0; a < data.count(); a++)
-	{
-		tmp = data[a];
-		if (skip)
-		{
-			tmp2 += tmp;
-			skip = false;
-			continue;
-		}
-		if (tmp == "(")
-		{
-			paran = true;
-			tmp2 += tmp;
-			continue;
-		}
-		if (tmp == ")")
-		{
-			paran = false;
-			tmp2 += tmp;
-			continue;
-		}
-		if (tmp == "[")
-		{
-			arra = true;
-			tmp2 += tmp;
-			continue;
-		}
-		if (tmp == "]")
-		{
-			arra = false;
-			tmp2 += tmp;
-			continue;
-		}
-//		if (tmp == "\\")
-//		{
-//			skip = true;
-//			continue;
-//		}
-		if (!paran)
-		{
-			if (tmp == " ")
-			{
-				tmp3 += " " + tmp2;
-				if (commandList.contains(tmp2))
-				{
-					commands.append(tmp3);
-					tmp3 = "";
-				}
-				tmp2 = "";
-				continue;
-			}
-		}
-		tmp2 += tmp;
-	}
-	if (!tmp2.isEmpty())
-	{
-		tmp3 += " " + tmp2;
-		commands.append(tmp3);
-	}
-}
-
-void AIPlug::decodeA85(QByteArray &psdata, QString tmp)
-{
-	uchar byte;
-	ushort data;
-	unsigned long sum = 0;
-	int quintet = 0;
-	for (int c = 0; c < tmp.length(); c++)
-	{
-		byte = QChar(tmp.at(c)).cell();
-		if (byte >= '!' && byte <= 'u')
-		{
-			sum = sum * 85 + ((unsigned long)byte - '!');
-			quintet++;
-			if (quintet == 5)
-			{
-				psdata.resize(psdata.size()+4);
-				data = (sum >> 24) & 0xFF;
-				psdata[psdata.size()-4] = data;
-				data = (sum >> 16) & 0xFF;
-				psdata[psdata.size()-3] = data;
-				data = (sum >> 8) & 0xFF;
-				psdata[psdata.size()-2] = data;
-				data = sum & 0xFF;
-				psdata[psdata.size()-1] = data;
-				quintet = 0;
-				sum = 0;
-			}
-		}
-		else if (byte == 'z')
-		{
-			psdata.resize(psdata.size()+4);
-			psdata[psdata.size()-4] = 0;
-			psdata[psdata.size()-3] = 0;
-			psdata[psdata.size()-2] = 0;
-			psdata[psdata.size()-1] = 0;
-		}
-		else if (byte == '~')
-		{
-			if (quintet)
-			{
-				int i;
-				for (i = 0; i < 5 - quintet; i++)
-					sum *= 85;
-				if (quintet > 1)
-					sum += (0xFFFFFF >> ((quintet - 2) * 8));
-				for (i = 0; i < quintet - 1; i++)
-				{
-					data = (sum >> (24 - 8 * i)) & 0xFF;
-					psdata.resize(psdata.size()+1);
-					psdata[psdata.size()-1] = data;
-				}
-				quintet = 0;
-			}
-			break;
-		}
-	}
-}
-
-void AIPlug::processData(QString data)
-{
-	double x, y, x1, y1, x2, y2;
-	int z, tmpInt;
-	PageItem *ite;
-	QString command = "";
-	QString Cdata = "";
-	QStringList da;
-	if (dataMode && fObjectMode)
-	{
-		if (data.contains("~>"))
-		{
-			dataString += data.mid(1);
-			dataMode = false;
-			QByteArray fData;
-			decodeA85(fData, dataString);
-			dataString = "";
-			if (fObjectMode)
-			{
-				FPoint wh = currentSpecialPath.WidthHeight();
-				if ((currentSpecialPath.size() > 3) && (wh.x() != 0.0) && (wh.y() != 0.0))
-				{
-					z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
-					ite = m_Doc->Items->at(z);
-					ite->PoLine = currentSpecialPath.copy();
-					ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-					ite->ClipEdited = true;
-					ite->FrameType = 3;
-					ite->setFillShade(CurrFillShade);
-					ite->setLineShade(CurrStrokeShade);
-					ite->setFillEvenOdd(fillRule);
-					ite->setFillTransparency(1.0 - Opacity);
-					ite->setLineTransparency(1.0 - Opacity);
-#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
-					ite->setFillBlendmode(blendMode);
-					ite->setLineBlendmode(blendMode);
-#endif
-					ite->setLineEnd(CapStyle);
-					ite->setLineJoin(JoinStyle);
-					wh = getMaxClipF(&ite->PoLine);
-					ite->setWidthHeight(wh.x(),wh.y());
-					ite->setTextFlowMode(PageItem::TextFlowDisabled);
-					m_Doc->AdjustItemSize(ite);
-					ite->tempImageFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_ai_XXXXXX.pdf");
-					ite->tempImageFile->open();
-					ite->tempImageFile->write(fData);
-					QString imgName = getLongPathName(ite->tempImageFile->fileName());
-					ite->tempImageFile->close();
-					ite->isInlineImage = true;
-					m_Doc->LoadPict(imgName, z);
-					if (ite->PictureIsAvailable)
-						ite->setImageXYScale(ite->width() / ite->pixm.width(), ite->height() / ite->pixm.height());
-					ite->setImageFlippedV(true);
-					ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
-					ite->setRedrawBounding();
-					if (importerFlags & LoadSavePlugin::lfCreateDoc)
-						ite->setLocked(itemLocked);
-					if (patternMode)
-						PatternElements.append(ite);
-					else
-						Elements.append(ite);
-					if (groupStack.count() != 0)
-						groupStack.top().append(ite);
-				}
-			}
-			fObjectMode = false;
-			currentSpecialPath.resize(0);
-			currentSpecialPath.svgInit();
-		}
-		else
-		{
-			dataString += data.mid(1);
-		}
-		return;
-	}
-	getCommands(data, da);
-	for (int a = 0; a < da.count(); a++)
-	{
-		Cdata = da[a];
-		if (((Cdata.startsWith("%")) || (Cdata.startsWith(" %"))) && (!meshMode))
-			continue;
-		if (Cdata.contains("SymbolInstance"))
-		{
-			symbolMode = true;
-			return;
-		}
-		if (symbolMode)
-		{
-			if (Cdata.contains("SymbolRef"))
-			{
-				int an = Cdata.indexOf("(");
-				int en = Cdata.lastIndexOf(")");
-				if ((an != -1) && (en != -1))
-				{
-					currentSymbolName = Cdata.mid(an+1, en-an-1);
-					currentSymbolName.remove("\\");
-					currentSymbolName = "S_"+currentSymbolName.trimmed().simplified().replace(" ", "_");
-				}
-			}
-			else if (Cdata.contains("TransformMatrix"))
-			{
-				ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-				ts2 >> x >> y >> x1 >> y1 >> x2 >> y2;
-				QTransform symTrans = QTransform(x, y, x1, y1, x2, y2);
-				double rotation = getRotationFromMatrix(symTrans, 0.0);
-				QTransform symT;
-				symT.translate(x2, y2);
-				QPointF pos1 = importedSymbols[currentSymbolName];
-				pos1 = symT.map(pos1);
-				double xp = pos1.x();
-				double yp = pos1.y();
-			//	xp += m_Doc->currentPage()->xOffset();
-			//	yp += m_Doc->currentPage()->yOffset();
-				int z = m_Doc->itemAdd(PageItem::Symbol, PageItem::Unspecified, baseX + xp, baseY + yp, 1, 1, 0, CommonStrings::None, CommonStrings::None, true);
-				PageItem *b = m_Doc->Items->at(z);
-				b->LayerID = m_Doc->activeLayer();
-				ScPattern pat = m_Doc->docPatterns[currentSymbolName];
-				b->setWidth(pat.width * symTrans.m11());
-				b->setHeight(pat.height * symTrans.m22());
-				b->OldB2 = b->width();
-				b->OldH2 = b->height();
-				b->setPattern(currentSymbolName);
-				double xoffset = 0.0, yoffset = 0.0;
-			//	if (rotation != 0.0)
-			//	{
-			//		double temp = -b->height();
-			//		xoffset = sin(-rotation) * temp;
-			//		yoffset = cos(-rotation) * temp;
-			//	}
-				b->setXPos(xp + xoffset);
-				b->setYPos(yp + yoffset);
-				m_Doc->RotMode(3);
-				m_Doc->RotateItem(rotation * 180 / M_PI, b);
-				m_Doc->RotMode(0);
-//				b->setRotation(rotation * 180 / M_PI);
-				b->setTextFlowMode(PageItem::TextFlowDisabled);
-				b->setFillTransparency(1.0 - Opacity);
-				b->setLineTransparency(1.0 - Opacity);
-	#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
-				b->setFillBlendmode(blendMode);
-				b->setLineBlendmode(blendMode);
-	#endif
-				b->updateClip();
-				if (patternMode)
-					PatternElements.append(b);
-				else
-					Elements.append(b);
-				if (groupStack.count() != 0)
-					groupStack.top().append(b);
-				symbolMode = false;
-			}
-		}
-		QStringList da2 = Cdata.split(" ", QString::SkipEmptyParts);
-		if (da2.count() == 0)
-			return;
-		command = da2[da2.count()-1];
-/* Start Path construction commands */
-		if (command == "m")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> x >> y;
-			Coords.svgMoveTo(x - docX, docHeight - (y - docY));
-			currentPoint = FPoint(x - docX, docHeight - (y - docY));
-		}
-		else if ((command == "L") || (command == "l"))
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> x >> y;
-			Coords.svgLineTo(x - docX, docHeight - (y - docY));
-			currentPoint = FPoint(x - docX, docHeight - (y - docY));
-		}
-		else if ((command == "C") || (command == "c"))
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> x >> y >> x1 >> y1 >> x2 >> y2;
-			Coords.svgCurveToCubic(x - docX, docHeight - (y - docY),
-								   x1 - docX, docHeight - (y1 - docY),
-								   x2 - docX, docHeight - (y2 - docY));
-			currentPoint = FPoint(x2 - docX, docHeight - (y2 - docY));
-		}
-		else if ((command == "Y") || (command == "y"))
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> x1 >> y1 >> x2 >> y2;
-			Coords.svgCurveToCubic(x1 - docX, docHeight - (y1 - docY), x2 - docX, docHeight - (y2 - docY), x2 - docX, docHeight - (y2 - docY));
-			currentPoint = FPoint(x2 - docX, docHeight - (y2 - docY));
-		}
-		else if ((command == "V") || (command == "v"))
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> x >> y >> x2 >> y2;
-			Coords.svgCurveToCubic(currentPoint.x(), currentPoint.y(), x - docX, docHeight - (y - docY), x2 - docX, docHeight - (y2 - docY));
-			currentPoint = FPoint(x2 - docX, docHeight - (y2 - docY));
-		}
-/* End Path construction commands */
-/* Start Object creation commands */
-		else if ((command == "b") || (command == "B") || (command == "f") || (command == "F") || (command == "s") || (command == "S"))
-		{
-			FPoint wh = Coords.WidthHeight();
-			if ((Coords.size() > 3) && (wh.x() != 0.0) && (wh.y() != 0.0))
-			{
-				if ((!WasU) || ((WasU) && (FirstU)))
-				{
-					if ((command == "B") || (command == "F") || (command == "S"))
-					{
-						if (command == "F")
-							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CommonStrings::None, true);
-						else if (command == "B")
-							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-						else
-							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColorStroke, true);
-					}
-					else
-					{
-						if (command == "f")
-							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CommonStrings::None, true);
-						else if (command == "b")
-							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-						else
-							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColorStroke, true);
-					}
-					ite = m_Doc->Items->at(z);
-					ite->PoLine = Coords.copy();
-					ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-					ite->ClipEdited = true;
-					ite->FrameType = 3;
-					ite->setFillShade(CurrFillShade);
-					ite->setLineShade(CurrStrokeShade);
-					ite->setFillEvenOdd(fillRule);
-					ite->setFillTransparency(1.0 - Opacity);
-					ite->setLineTransparency(1.0 - Opacity);
-	#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
-					ite->setFillBlendmode(blendMode);
-					ite->setLineBlendmode(blendMode);
-	#endif
-					if (!currentPatternName.isEmpty())
-					{
-						ite->setPattern(currentPatternName);
-						ite->setPatternTransform(currentPatternXScale * 100, currentPatternYScale * 100, currentPatternX, currentPatternY, currentPatternRotation, 0.0, 0.0);
-						ite->GrType = 8;
-						currentPatternName = "";
-					}
-					if (!currentStrokePatternName.isEmpty())
-					{
-						ite->setStrokePattern(currentStrokePatternName);
-						ite->setStrokePatternTransform(currentStrokePatternXScale * 100, currentStrokePatternYScale * 100, currentStrokePatternX, currentStrokePatternY, currentStrokePatternRotation, 0.0, 0.0, 1.0);
-						currentStrokePatternName = "";
-					}
-					ite->setLineEnd(CapStyle);
-					ite->setLineJoin(JoinStyle);
-					if (!WasU)
-					{
-						FPoint wh = getMaxClipF(&ite->PoLine);
-						ite->setWidthHeight(wh.x(),wh.y());
-						ite->setTextFlowMode(PageItem::TextFlowDisabled);
-						m_Doc->AdjustItemSize(ite);
-					}
-					if (patternMode)
-						PatternElements.append(ite);
-					else
-						Elements.append(ite);
-					if (groupStack.count() != 0)
-						groupStack.top().append(ite);
-					if (importerFlags & LoadSavePlugin::lfCreateDoc)
-						ite->setLocked(itemLocked);
-					
-				}
-				else
-				{
-					ite = m_Doc->Items->at(m_Doc->Items->count()-1);
-					ite->PoLine.setMarker();
-					Coords.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-					ite->PoLine.putPoints(ite->PoLine.size(), Coords.size(), Coords);
-				}
-				FirstU = false;
-				itemRendered = true;
-				CurrFillShade = 100.0;
-				CurrStrokeShade = 100.0;
-			}
-			Coords.resize(0);
-			Coords.svgInit();
-		}
-		else if (command == "*u")
-		{
-			FirstU = true;
-			WasU = true;
-		}
-		else if (command == "*U")
-		{
-			WasU = false;
-			ite = m_Doc->Items->at(m_Doc->Items->count()-1);
-			FPoint wh = getMaxClipF(&ite->PoLine);
-			ite->setWidthHeight(wh.x(),wh.y());
-			m_Doc->AdjustItemSize(ite);
-		}
-		else if ((command == "u") || (command == "q"))
-		{
-			QList<PageItem*> gElements;
-			groupStack.push(gElements);
-			clipStack.push(clipCoords);
-		}
-		else if ((command == "U") || (command == "Q"))
-		{
-			if (groupStack.count() != 0)
-			{
-				QList<PageItem*> gElements = groupStack.pop();
-				clipCoords = clipStack.pop();
-				tmpSel->clear();
-				if (gElements.count() > 0)
-				{
-					for (int dre = 0; dre < gElements.count(); ++dre)
-					{
-						tmpSel->addItem(gElements.at(dre), true);
-						if (patternMode)
-							PatternElements.removeAll(gElements.at(dre));
-						else
-							Elements.removeAll(gElements.at(dre));
-					}
-					ite = m_Doc->groupObjectsSelection(tmpSel);
-					if ((clipCoords.size() > 4) && (command == "Q"))
-					{
-						clipCoords.translate(m_Doc->currentPage()->xOffset()-ite->xPos(), m_Doc->currentPage()->yOffset()-ite->yPos());
-						ite->PoLine = clipCoords.copy();
-						ite->PoLine.translate(baseX, baseY);
-					}
-					for (int as = 0; as < tmpSel->count(); ++as)
-					{
-						if (patternMode)
-							PatternElements.append(tmpSel->itemAt(as));
-						else
-							Elements.append(tmpSel->itemAt(as));
-					}
-				}
-				if (groupStack.count() != 0)
-				{
-					for (int as = 0; as < tmpSel->count(); ++as)
-					{
-						groupStack.top().append(tmpSel->itemAt(as));
-					}
-				}
-				tmpSel->clear();
-			}
-			if (command == "Q")
-			{
-				clipCoords.resize(0);
-				clipCoords.svgInit();
-			}
-		}
-		else if (command == "W")
-		{
-			if (clipStack.count() != 0)
-			{
-				if (clipStack.top().size() > 3)
-				{
-					clipStack.top().setMarker();
-					clipStack.top().putPoints(clipStack.top().size(), Coords.size(), Coords);
-				}
-				else
-					clipStack.top() = Coords.copy();
-			}
-		}
-		else if ((command == "N") || (command == "n"))
-		{
-			if (command == "n")
-				Coords.svgClosePath();
-			currentSpecialPath = Coords.copy();
-			Coords.resize(0);
-			Coords.svgInit();
-		}
-/* End Object construction commands */
-/* Start Graphics state commands */
-		else if (command == "A")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> tmpInt;
-			if (tmpInt == 1)
-				itemLocked = true;
-			else
-				itemLocked = false;
-		}
-		else if (command == "w")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> LineW;
-		}
-		else if (command == "j")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> tmpInt;
-			if (tmpInt == 0)
-				JoinStyle = Qt::MiterJoin;
-			else if (tmpInt == 1)
-				JoinStyle = Qt::RoundJoin;
-			else if (tmpInt == 1)
-				JoinStyle = Qt::BevelJoin;
-		}
-		else if (command == "J")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> tmpInt;
-			if (tmpInt == 0)
-				CapStyle = Qt::FlatCap;
-			else if (tmpInt == 1)
-				CapStyle = Qt::RoundCap;
-			else if (tmpInt == 1)
-				CapStyle = Qt::SquareCap;
-		}
-		/* undocumented Command Xy
-			- has up to 5 Parameters
-			- first Parameter might be the Blendmode
-			- second Parameter is the Opacity
-		*/
-		else if (command == "Xy")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> blendMode >> Opacity;
-		}
-		else if (command == "XR")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> tmpInt;
-			if (tmpInt == 1)
-				fillRule = true;
-			else
-				fillRule = false;
-		}
-		else if (command == "Bb")
-		{
-			gradientMode = true;
-			wasBC = false;
-			itemRendered = false;
-			startMatrix = QTransform();
-			endMatrix = QTransform();
-		}
-		else if (command == "Xm")
-		{
-			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-			double m1, m2, m3, m4, m5, m6;
-			gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
-			startMatrix.translate(m5, -m6);
-			endMatrix.scale(m1, m4);
-			wasBC = true;
-		}
-		else if (command == "Bm")
-		{
-			if (m_gradients[currentGradientName].type() == 1)
-			{
-				ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-				double m1, m2, m3, m4, m5, m6;
-				gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
-				startMatrix.translate(m5, -m6);
-//				endMatrix.scale(m1, m4);
-				endMatrix *= QTransform(m1, m2, m3, m4, 0, 0);
-//				endMatrix = QTransform(m1, m2, m3, m4, m5, m6);
-				wasBC = true;
-			}
-		}
-		else if (command == "BB")
-		{
-			if (itemRendered)
-			{
-				gradientMode = false;
-				ite = m_Doc->Items->at(m_Doc->Items->count()-1);
-				ite->fill_gradient = m_gradients[currentGradientName];
-				ite->setGradient(currentGradientName);
-				if (ite->fill_gradient.type() == 0)
-					ite->GrType = 6;
-				else
-					ite->GrType = 7;
-				QTransform m1;
-				m1.translate(currentGradientOrigin.x() - ite->xPos(), currentGradientOrigin.y() - ite->yPos());
-				m1.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-				m1.rotate(-currentGradientAngle);
-				ite->GrStartX = currentGradientOrigin.x() - ite->xPos() + m_Doc->currentPage()->xOffset();
-				ite->GrStartY = currentGradientOrigin.y() - ite->yPos() + m_Doc->currentPage()->yOffset();
-				QPointF target = m1.map(QPointF(currentGradientLenght, 0.0));
-				ite->GrEndX = target.x();
-				ite->GrEndY = target.y();
-				if (wasBC)
-				{
-					QPointF newS = startMatrix.map(QPointF(ite->GrStartX, ite->GrStartY));
-					ite->GrStartX = newS.x();
-					ite->GrStartY = newS.y();
-					QTransform m2;
-					m2.rotate(-currentGradientAngle);
-					m2 *= endMatrix;
-					QPointF target = m2.map(QPointF(currentGradientLenght, 0.0));
-					ite->GrEndX = target.x();
-					ite->GrEndY = target.y();
-				}
-			}
-			wasBC = false;
-			currentGradientMatrix = QTransform();
-			currentGradientOrigin = QPointF(0.0, 0.0);
-			currentGradientAngle = 0.0;
-			currentGradientLenght = 1.0;
-			itemRendered = false;
-		}
-		else if (command == "Bg")
-		{
-			int an = Cdata.indexOf("(");
-			int en = Cdata.lastIndexOf(")");
-			currentGradientName = Cdata.mid(an+1, en-an-1);
-			currentGradientName.remove("\\");
-			QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
-			ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
-			double xOrig, yOrig, m1, m2, m3, m4, m5, m6;
-			gVals >> xOrig >> yOrig >> currentGradientAngle >> currentGradientLenght >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
-			currentGradientOrigin = QPointF(xOrig - docX, docHeight - (yOrig - docY));
-			currentGradientMatrix = QTransform(m1, m2, m3, m4, m5, m6);
-		}
-/* End Graphics state commands */
-/* Start Color commands */
-		else if ((command == "G") || (command == "g"))
-		{
-			if (command == "G")
-				CurrColorStroke = parseColorGray(Cdata);
-			else
-				CurrColorFill = parseColorGray(Cdata);
-			meshColorMode = 2;
-		}
-		else if ((command == "K") || (command == "k"))
-		{
-			if (command == "K")
-				CurrColorStroke = parseColor(Cdata);
-			else
-				CurrColorFill = parseColor(Cdata);
-		}
-		else if ((command == "XA") || (command == "Xa"))
-		{
-			QString Xdata = da2[da2.count()-4] + " " + da2[da2.count()-3] + " " + da2[da2.count()-2];
-			if (command == "XA")
-				CurrColorStroke = parseColorRGB(Xdata);
-			else
-				CurrColorFill = parseColorRGB(Xdata);
-			meshColorMode = 1;
-		}
-		else if ((command == "XX") || (command == "Xx") || (command == "Xk"))
-		{
-			if (command == "XX")
-				CurrColorStroke = parseCustomColorX(Cdata, CurrStrokeShade, da2[da2.count()-2]);
-			else
-				CurrColorFill = parseCustomColorX(Cdata, CurrFillShade, da2[da2.count()-2]);
-		}
-		else if ((command == "X") || (command == "x"))
-		{
-			if (command == "X")
-				CurrColorStroke = parseCustomColor(Cdata, CurrStrokeShade);
-			else
-				CurrColorFill = parseCustomColor(Cdata, CurrFillShade);
-		}
-		else if (command == "p")
-		{
-			int an = Cdata.indexOf("(");
-			int en = Cdata.lastIndexOf(")");
-			currentPatternName = Cdata.mid(an+1, en-an-1);
-			currentPatternName.remove("\\");
-			currentPatternName = currentPatternName.trimmed().simplified().replace(" ", "_");
-			QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
-			ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
-			gVals >> currentPatternX >> currentPatternY >> currentPatternXScale >> currentPatternYScale >> currentPatternRotation;
-		}
-		else if (command == "P")
-		{
-			int an = Cdata.indexOf("(");
-			int en = Cdata.lastIndexOf(")");
-			currentStrokePatternName = Cdata.mid(an+1, en-an-1);
-			currentStrokePatternName.remove("\\");
-			currentStrokePatternName = currentPatternName.trimmed().simplified().replace(" ", "_");
-			QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
-			ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
-			gVals >> currentStrokePatternX >> currentStrokePatternY >> currentStrokePatternXScale >> currentStrokePatternYScale >> currentStrokePatternRotation;
-		}
-		else if (command == "X!")
-		{
-			if (Cdata.contains("/Mesh"))
-			{
-				meshMode = true;
-				meshNodeCounter = 0;
-//				meshColorMode = 0;
-				meshGradientArray.clear();
-			}
-			if (Cdata.contains("/End"))
-			{
-				meshMode = false;
-				if (meshGradientArray.count() != 0)
-				{
-					z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
-					ite = m_Doc->Items->at(z);
-					for (int x = 0; x < meshGradientArray.count(); x++)
-					{
-						for (int y = 0; y < meshGradientArray[x].count(); y++)
-						{
-							meshGradientArray[x][y].moveRel(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-						}
-					}
-					ite->meshGradientArray = meshGradientArray;
-					ite->GrType = 11;
-					ite->meshToShape();
-					for (int grow = 0; grow < ite->meshGradientArray.count(); grow++)
-					{
-						for (int gcol = 0; gcol < ite->meshGradientArray[grow].count(); gcol++)
-						{
-							meshPoint mp = ite->meshGradientArray[grow][gcol];
-							ite->setMeshPointColor(grow, gcol, mp.colorName, mp.shade, mp.transparency);
-						}
-					}
-					ite->setFillShade(CurrFillShade);
-					ite->setLineShade(CurrFillShade);
-					ite->setFillEvenOdd(fillRule);
-					ite->setFillTransparency(1.0 - Opacity);
-					ite->setLineTransparency(1.0 - Opacity);
-	#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
-					ite->setFillBlendmode(blendMode);
-					ite->setLineBlendmode(blendMode);
-	#endif
-					ite->setLineEnd(CapStyle);
-					ite->setLineJoin(JoinStyle);
-					if (importerFlags & LoadSavePlugin::lfCreateDoc)
-						ite->setLocked(itemLocked);
-					if (patternMode)
-						PatternElements.append(ite);
-					else
-						Elements.append(ite);
-					if (groupStack.count() != 0)
-						groupStack.top().append(ite);
-				}
-			}
-		}
-		else if (command == "X#")
-		{
-			int an = Cdata.indexOf("_");
-			QString cmdLine = Cdata.remove(0, an+1);
-			an = cmdLine.lastIndexOf("/");
-			QString tmpS = cmdLine.mid(an+1, Cdata.size());
-			ScTextStream mVals(&tmpS, QIODevice::ReadOnly);
-			QString mKey;
-			mVals >> mKey;
-			if (mKey == "Size")
-			{
-				meshGradientArray.clear();
-				int ans = cmdLine.indexOf("[");
-				int ens = cmdLine.lastIndexOf("]");
-				QString sizeVals = cmdLine.mid(ans+1, ens-ans-1);
-				ScTextStream mVals2(&sizeVals, QIODevice::ReadOnly);
-				mVals2 >> meshXSize >> meshYSize;
-				for (int mgr = 0; mgr < meshYSize+1; mgr++)
-				{
-					QList<meshPoint> ml;
-					for (int mgc = 0; mgc < meshXSize+1; mgc++)
-					{
-						meshPoint mp;
-						ml.append(mp);
-					}
-					meshGradientArray.append(ml);
-				}
-			}
-			if (mKey == "P")
-			{
-				int ans = cmdLine.indexOf("[");
-				int ens = cmdLine.lastIndexOf("]");
-				QString posVals = cmdLine.mid(ans+1, ens-ans-1);
-				ScTextStream mVals3(&posVals, QIODevice::ReadOnly);
-				mVals3 >> currentMeshXPos >> currentMeshYPos;
-			}
-			if (mKey == "CS")
-			{
-				if (Cdata.contains("CMYK"))
-					meshColorMode = 0;
-				else if (Cdata.contains("RGB"))
-					meshColorMode = 1;
-				else if (Cdata.contains("Gray"))
-					meshColorMode = 2;
-			}
-			if (mKey == "E")
-			{
-				int indY = meshYSize - currentMeshYPos - 1;
-				int indX = currentMeshXPos;
-				FPoint p2 = FPoint(meshNode1PointX, meshNode1PointY);
-				FPoint p1 = FPoint(meshNode2PointX, meshNode2PointY);
-				FPoint p4 = FPoint(meshNode3PointX, meshNode3PointY);
-				FPoint p3 = FPoint(meshNode4PointX, meshNode4PointY);
-				meshGradientArray[indY+1][indX+1].gridPoint   = FPoint(meshNode2PointX, meshNode2PointY);
-				meshGradientArray[indY+1][indX+1].controlTop  = FPoint(meshNode2Control2X, meshNode2Control2Y);
-				meshGradientArray[indY+1][indX+1].controlLeft = FPoint(meshNode2Control1X, meshNode2Control1Y);
-				meshGradientArray[indY+1][indX+1].colorName = meshColor2;
-				meshGradientArray[indY+1][indX+1].shade = 100;
-				meshGradientArray[indY+1][indX+1].transparency = 1.0;
-				meshGradientArray[indY+1][indX].gridPoint    = FPoint(meshNode1PointX, meshNode1PointY);
-				meshGradientArray[indY+1][indX].controlRight = FPoint(meshNode1Control2X, meshNode1Control2Y);
-				meshGradientArray[indY+1][indX].controlTop   = FPoint(meshNode1Control1X, meshNode1Control1Y);
-				meshGradientArray[indY+1][indX].colorName = meshColor1;
-				meshGradientArray[indY+1][indX].shade = 100;
-				meshGradientArray[indY+1][indX].transparency = 1.0;
-				meshGradientArray[indY][indX].gridPoint     = FPoint(meshNode4PointX, meshNode4PointY);
-				meshGradientArray[indY][indX].controlBottom = FPoint(meshNode4Control2X, meshNode4Control2Y);
-				meshGradientArray[indY][indX].controlRight  = FPoint(meshNode4Control1X, meshNode4Control1Y);
-				meshGradientArray[indY][indX].colorName = meshColor4;
-				meshGradientArray[indY][indX].shade = 100;
-				meshGradientArray[indY][indX].transparency = 1.0;
-				meshGradientArray[indY][indX+1].gridPoint     = FPoint(meshNode3PointX, meshNode3PointY);
-				meshGradientArray[indY][indX+1].controlLeft   = FPoint(meshNode3Control2X, meshNode3Control2Y);
-				meshGradientArray[indY][indX+1].controlBottom = FPoint(meshNode3Control1X, meshNode3Control1Y);
-				meshGradientArray[indY][indX+1].colorName = meshColor3;
-				meshGradientArray[indY][indX+1].shade = 100;
-				meshGradientArray[indY][indX+1].transparency = 1.0;
-				meshNodeCounter = 0;
-			}
-			if (mKey == "N")
-			{
-				double cVal, mVal, yVal, kVal, coorX1, coorY1, coorX2, coorY2, coorX3, coorY3;
-				int dummy;
-				meshNodeCounter++;
-				int ans = cmdLine.indexOf("[");
-				int ens = cmdLine.lastIndexOf("]");
-				QString nodeVals = cmdLine.mid(ans+1, ens-ans-1);
-				ScTextStream mVals4(&nodeVals, QIODevice::ReadOnly);
-				kVal = 0.0;
-				if (meshColorMode == 0)
-					mVals4 >> cVal >> mVal >> yVal >> kVal >> coorX1 >> coorY1 >> coorX2 >> coorY2 >> dummy >> coorX3 >> coorY3;
-				else if (meshColorMode == 1)
-					mVals4 >> cVal >> mVal >> yVal >> coorX1 >> coorY1 >> coorX2 >> coorY2 >> dummy >> coorX3 >> coorY3;
-				else if (meshColorMode == 2)
-					mVals4 >> cVal >> coorX1 >> coorY1 >> coorX2 >> coorY2 >> dummy >> coorX3 >> coorY3;
-				QString nodeColor;
-				ScColor tmpColor;
-				ColorList::Iterator it;
-				int Cc = qRound(cVal * 255);
-				int Mc = qRound(mVal * 255);
-				int Yc = qRound(yVal * 255);
-				int Kc = qRound(kVal * 255);
-				int hC, hM, hY, hK;
-				bool found = false;
-				if (meshColorMode == 0)
-				{
-					tmpColor.setColor(Cc, Mc, Yc, Kc);
-					for (it = m_Doc->PageColors.begin(); it != m_Doc->PageColors.end(); ++it)
-					{
-						if (it.value().getColorModel() == colorModelCMYK)
-						{
-							it.value().getCMYK(&hC, &hM, &hY, &hK);
-							if ((Cc == hC) && (Mc == hM) && (Yc == hY) && (Kc == hK))
-							{
-								nodeColor = it.key();
-								found = true;
-								break;
-							}
-						}
-					}
-				}
-				else if (meshColorMode == 1)
-				{
-					tmpColor.setColorRGB(Cc, Mc, Yc);
-					for (it = m_Doc->PageColors.begin(); it != m_Doc->PageColors.end(); ++it)
-					{
-						if (it.value().getColorModel() == colorModelRGB)
-						{
-							it.value().getRGB(&hC, &hM, &hY);
-							if ((Cc == hC) && (Mc == hM) && (Yc == hY))
-							{
-								nodeColor = it.key();
-								found = true;
-								break;
-							}
-						}
-					}
-				}
-				else if (meshColorMode == 2)
-				{
-					tmpColor.setColor(0, 0, 0, Cc);
-					for (it = m_Doc->PageColors.begin(); it != m_Doc->PageColors.end(); ++it)
-					{
-						if (it.value().getColorModel() == colorModelCMYK)
-						{
-							it.value().getCMYK(&hC, &hM, &hY, &hK);
-							if ((Cc == hC) && (Mc == hM) && (Yc == hY) && (Kc == hK))
-							{
-								nodeColor = it.key();
-								found = true;
-								break;
-							}
-						}
-					}
-				}
-				if (!found)
-				{
-					tmpColor.setSpotColor(false);
-					tmpColor.setRegistrationColor(false);
-					QString namPrefix = "FromAI";
-					m_Doc->PageColors.insert(namPrefix+tmpColor.name(), tmpColor);
-					nodeColor = namPrefix+tmpColor.name();
-				}
-				if (meshNodeCounter == 1)
-				{
-					meshNode1PointX = coorX1 - docX;
-					meshNode1PointY = docHeight - (coorY1 - docY);
-					meshNode1Control2X = coorX2 - docX;
-					meshNode1Control2Y = docHeight - (coorY2 - docY);
-					meshNode1Control1X = coorX3 - docX;
-					meshNode1Control1Y = docHeight - (coorY3 - docY);
-					meshColor1 = nodeColor;
-				}
-				if (meshNodeCounter == 2)
-				{
-					meshNode2PointX = coorX1 - docX;
-					meshNode2PointY = docHeight - (coorY1 - docY);
-					meshNode2Control2X = coorX2 - docX;
-					meshNode2Control2Y = docHeight - (coorY2 - docY);
-					meshNode2Control1X = coorX3 - docX;
-					meshNode2Control1Y = docHeight - (coorY3 - docY);
-					meshColor2 = nodeColor;
-				}
-				if (meshNodeCounter == 3)
-				{
-					meshNode3PointX = coorX1 - docX;
-					meshNode3PointY = docHeight - (coorY1 - docY);
-					meshNode3Control2X = coorX2 - docX;
-					meshNode3Control2Y = docHeight - (coorY2 - docY);
-					meshNode3Control1X = coorX3 - docX;
-					meshNode3Control1Y = docHeight - (coorY3 - docY);
-					meshColor3 = nodeColor;
-				}
-				if (meshNodeCounter == 4)
-				{
-					meshNode4PointX = coorX1 - docX;
-					meshNode4PointY = docHeight - (coorY1 - docY);
-					meshNode4Control2X = coorX2 - docX;
-					meshNode4Control2Y = docHeight - (coorY2 - docY);
-					meshNode4Control1X = coorX3 - docX;
-					meshNode4Control1Y = docHeight - (coorY3 - docY);
-					meshColor4 = nodeColor;
-				}
-			}
-		}
-/* End Color commands */
-/* Start Layer commands */
-		else if (command == "Lb")
-		{
-			if (importerFlags & LoadSavePlugin::lfCreateDoc)
-			{
-				int visible, preview, enabled, printing, dummy, rc, gc, bc;
-				ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-				ts2 >> visible >> preview >> enabled >> printing >> dummy >> dummy >> dummy >> rc >> gc >> bc;
-				if (!firstLayer)
-					currentLayer = m_Doc->addLayer("Layer", true);
-				m_Doc->setLayerVisible(currentLayer, static_cast<bool>(visible));
-				m_Doc->setLayerOutline(currentLayer, static_cast<bool>(!preview));
-				m_Doc->setLayerLocked(currentLayer, static_cast<bool>(!enabled));
-				m_Doc->setLayerPrintable(currentLayer, static_cast<bool>(printing));
-				m_Doc->setLayerMarker(currentLayer, QColor(rc, gc, bc));
-				QList<PageItem*> gElements;
-				groupStack.push(gElements);
-				clipStack.push(clipCoords);
-				firstLayer = false;
-			}
-			Coords.resize(0);
-			Coords.svgInit();
-		}
-		else if (command == "LB")
-		{
-			if (importerFlags & LoadSavePlugin::lfCreateDoc)
-			{
-				if (groupStack.count() != 0)
-				{
-					QList<PageItem*> gElements = groupStack.pop();
-					clipStack.pop();
-					tmpSel->clear();
-					if (gElements.count() > 0)
-					{
-						for (int dre = 0; dre < gElements.count(); ++dre)
-						{
-							tmpSel->addItem(gElements.at(dre), true);
-							if (patternMode)
-								PatternElements.removeAll(gElements.at(dre));
-							else
-								Elements.removeAll(gElements.at(dre));
-						}
-						m_Doc->groupObjectsSelection(tmpSel);
-						ite = tmpSel->itemAt(0);
-						if (Coords.size() > 3)
-						{
-							Coords.translate(m_Doc->currentPage()->xOffset()-ite->xPos(), m_Doc->currentPage()->yOffset()-ite->yPos());
-							ite->PoLine = Coords.copy();
-							ite->PoLine.translate(baseX, baseY);
-						}
-						for (int as = 0; as < tmpSel->count(); ++as)
-						{
-							if (patternMode)
-								PatternElements.append(tmpSel->itemAt(as));
-							else
-								Elements.append(tmpSel->itemAt(as));
-						}
-						ite->setItemName( tr("Group%1").arg(m_Doc->layerName(currentLayer)));
-					}
-					if (groupStack.count() != 0)
-					{
-						for (int as = 0; as < tmpSel->count(); ++as)
-						{
-							groupStack.top().append(tmpSel->itemAt(as));
-						}
-					}
-					tmpSel->clear();
-				}
-			}
-			Coords.resize(0);
-			Coords.svgInit();
-		}
-		else if (command == "Ln")
-		{
-			if (importerFlags & LoadSavePlugin::lfCreateDoc)
-			{
-				int an = Cdata.indexOf("(");
-				int en = Cdata.lastIndexOf(")");
-				QString LayerNam = Cdata.mid(an+1, en-an-1);
-				LayerNam.remove("\\");
-				m_Doc->changeLayerName(currentLayer, LayerNam);
-			}
-		}
-/* End Layer commands */
-/* Start Text commands */
-		else if (command == "To")
-		{
-			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
-			ts2 >> textMode;
-			textData.clear();
-			textMatrix = QTransform();
-			maxWidth = 0;
-			tempW = 0;
-			maxHeight = 0;
-			textKern = 0;
-			startCurrentTextRange = 0;
-			endCurrentTextRange = 0;
-			textScaleH = 1000;
-			textScaleV = 1000;
-		}
-		else if (command == "Tp")
-		{
-			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-			double m1, m2, m3, m4, m5, m6;
-			gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
-			textMatrix = QTransform(m1, m2, m3, m4, m5, m6);
-		}
-		else if (command == "Tx") // || (command == "TX"))
-		{
-			QStringList res = getStrings(Cdata);
-			if (res.count() > 0)
-			{
-				QString tex = res[0];
-				double tempH = 0;
-				startCurrentTextRange = textData.length();
-				for (int tt = 0; tt < tex.length(); ++tt)
-				{
-					CharStyle nstyle;
-					QString ch = tex.mid(tt,1);
-					nstyle.setFont((*m_Doc->AllFonts)[textFont]);
-					nstyle.setFontSize(textSize);
-					nstyle.setFillColor(CurrColorFill);
-					nstyle.setTracking(textKern);
-					nstyle.setFillShade(100);
-					nstyle.setStrokeColor(CurrColorStroke);
-					nstyle.setStrokeShade(100);
-					nstyle.setScaleH(textScaleH);
-					nstyle.setScaleV(textScaleV);
-					nstyle.setBaselineOffset(0);
-					nstyle.setShadowXOffset(50);
-					nstyle.setShadowYOffset(-50);
-					nstyle.setOutlineWidth(10);
-					nstyle.setUnderlineOffset(-1);
-					nstyle.setUnderlineWidth(-1);
-					nstyle.setStrikethruOffset(-1);
-					nstyle.setStrikethruWidth(-1);
-					nstyle.setFeatures(StyleFlag(ScStyle_Default).featureList());
-					int pot = textData.length();
-					textData.insertChars(pot, ch);
-					textData.applyCharStyle(pot, 1, nstyle);
-					tempW += nstyle.font().realCharWidth(ch[0], nstyle.fontSize() / 10.0)+1;
-					tempH  = qMax(tempH, nstyle.font().height(nstyle.fontSize() / 10.0) + 2.0);
-					maxWidth  = qMax(tempW, maxWidth);
-					maxHeight = qMax(tempH, maxHeight);
-					if ((ch == SpecialChars::PARSEP) || (ch == SpecialChars::LINEBREAK))
-					{
-						maxHeight += nstyle.font().height(nstyle.fontSize() / 10.0);
-						tempW = 0;
-					}
-					endCurrentTextRange = pot;
-				}
-			}
-		}
-		else if (command == "Tk")
-		{
-			int flag;
-			double val;
-			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-			gVals >> flag >> val;
-			if (flag == 1)
-				val = 0;
-			double oldval = textData.charStyle(startCurrentTextRange).tracking();
-			CharStyle nstyle = textData.charStyle(startCurrentTextRange);
-			nstyle.setTracking(oldval + val);
-			textData.applyCharStyle(startCurrentTextRange, 1, nstyle);
-		}
-		else if (command == "Tc")
-		{
-			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-			gVals >> textKern;
-			textKern *= 100.0;
-		}
-		else if (command == "Tz")
-		{
-			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-			gVals >> textScaleH >> textScaleV;
-			textScaleH *= 10.0;
-			textScaleV *= 10.0;
-		}
-		else if (command == "T*")
-		{
-			CharStyle nstyle;
-			QString ch = SpecialChars::LINEBREAK;
-			nstyle.setFont((*m_Doc->AllFonts)[textFont]);
-			nstyle.setFontSize(textSize);
-			nstyle.setFillColor(CurrColorFill);
-			nstyle.setTracking(textKern);
-			nstyle.setFillShade(100);
-			nstyle.setStrokeColor(CurrColorStroke);
-			nstyle.setStrokeShade(100);
-			nstyle.setScaleH(textScaleH);
-			nstyle.setScaleV(textScaleV);
-			nstyle.setBaselineOffset(0);
-			nstyle.setShadowXOffset(50);
-			nstyle.setShadowYOffset(-50);
-			nstyle.setOutlineWidth(10);
-			nstyle.setUnderlineOffset(-1);
-			nstyle.setUnderlineWidth(-1);
-			nstyle.setStrikethruOffset(-1);
-			nstyle.setStrikethruWidth(-1);
-			nstyle.setFeatures(StyleFlag(ScStyle_Default).featureList());
-			int pot = textData.length();
-			textData.insertChars(pot, ch);
-			textData.applyCharStyle(pot, 1, nstyle);
-			maxHeight += nstyle.font().height(nstyle.fontSize() / 10.0) + 2.0;
-			tempW = 0;
-		}
-		else if (command == "Tf")
-		{
-			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-			gVals >> textFont >> textSize;
-			textFont.remove(0, 2);
-			QString family = textFont;
-			QString ret = "";
-			family.replace( QRegExp( "'" ) , QChar( ' ' ) );
-			textFont = m_Doc->itemToolPrefs().textFont;
-			bool found = false;
-			SCFontsIterator it(PrefsManager::instance()->appPrefs.fontPrefs.AvailFonts);
-			for ( ; it.hasNext(); it.next())
-			{
-				QString fam;
-				QString fn = it.current().scName();
-				int pos = fn.indexOf(" ");
-				fam = fn.left(pos);
-				if (fam == family)
-				{
-					found = true;
-					ret = fn;
-				}
-			}
-			if (found)
-				textFont = family;
-			else
-			{
-				if (importerFlags & LoadSavePlugin::lfCreateThumbnail)
-					textFont = PrefsManager::instance()->appPrefs.itemToolPrefs.textFont;
-				else
-				{
-					if (!PrefsManager::instance()->appPrefs.fontPrefs.GFontSub.contains(family))
-					{
-						qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-						MissingFont *dia = new MissingFont(0, family, m_Doc);
-						dia->exec();
-						QString tmpf = dia->getReplacementFont();
-						delete dia;
-						qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
-						PrefsManager::instance()->appPrefs.fontPrefs.GFontSub[family] = tmpf;
-					}
-					else
-						textFont = PrefsManager::instance()->appPrefs.fontPrefs.GFontSub[family];
-				}
-			}
-			textSize *= 10.0;
-		}
-		else if (command == "TO")
-		{
-			if (textData.length() > 0)
-			{
-				if (!((textData.length() == 1) && (textData.text(0) == SpecialChars::PARSEP)))
-				{
-					QPointF pos = QPointF(textMatrix.dx(), textMatrix.dy());
-					pos += QPointF(m_Doc->currentPage()->xOffset(), -m_Doc->currentPage()->yOffset());
-					pos += QPointF(0.0, textSize / 10.0 + 2.0);
-					z = m_Doc->itemAdd(PageItem::TextFrame, PageItem::Unspecified, pos.x() - docX, docHeight - (pos.y() - docY), 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
-					ite = m_Doc->Items->at(z);
-					ite->setTextToFrameDist(0.0, 0.0, 0.0, 0.0);
-					ite->itemText.append(textData);
-					double xpos = ite->xPos();
-					double ypos = ite->yPos();
-					ite->setWidthHeight(qMax(ite->width(), maxWidth), qMax(ite->height(), maxHeight));
-					double xoffset = 0.0, yoffset = 0.0;
-					double rotation = getRotationFromMatrix(textMatrix, 0.0);
-					if (rotation != 0.0)
-					{
-						double temp = textSize / 10.0 + 2.0;
-						xoffset = sin(rotation) * temp;
-						yoffset = cos(rotation) * temp;
-					}
-					ite->setXPos(xpos + xoffset);
-					ite->setYPos(ypos + yoffset);
-					ite->setRotation(rotation * 180 / M_PI);
-					ite->SetRectFrame();
-					m_Doc->setRedrawBounding(ite);
-					ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
-					ite->setTextFlowMode(PageItem::TextFlowDisabled);
-					ite->setFillShade(CurrFillShade);
-					ite->setLineShade(CurrStrokeShade);
-					ite->setFillEvenOdd(fillRule);
-					ite->setFillTransparency(1.0 - Opacity);
-					ite->setLineTransparency(1.0 - Opacity);
-					ite->setLineEnd(CapStyle);
-					ite->setLineJoin(JoinStyle);
-					if (importerFlags & LoadSavePlugin::lfCreateDoc)
-						ite->setLocked(itemLocked);
-					if (patternMode)
-						PatternElements.append(ite);
-					else
-						Elements.append(ite);
-					if (groupStack.count() != 0)
-						groupStack.top().append(ite);
-				}
-			}
-		}
-/* End Text commands */
-/* Start special Commands */
-		else if (command == "*")
-		{
-			Coords.resize(0);
-			Coords.svgInit();
-		}
-		else if (command == "[")
-		{
-			Coords.resize(0);
-			Coords.svgInit();
-			int an = Cdata.indexOf("(");
-			int en = Cdata.lastIndexOf(")");
-			if ((an != -1) && (en != -1))
-			{
-				patternMode = true;
-				currentPatternDefName = Cdata.mid(an+1, en-an-1);
-				currentPatternDefName.remove("\\");
-				currentPatternDefName = currentPatternDefName.trimmed().simplified().replace(" ", "_");
-				QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
-				ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
-				gVals >> patternX1 >> patternY1 >> patternX2 >> patternY2;
-			}
-		}
-		else if (command == ",")
-		{
-			if (Cdata.contains("/Data"))
-			{
-				dataMode = true;
-				dataString = "";
-			}
-		}
-		else if (command == ":")
-		{
-			fObjectMode = true;
-		}
-/* End special Commands */
-/* Skip everything else */
-//		else
-//			qDebug() << command;
-	}
-}
-
-void AIPlug::processGradientData(QString data)
-{
-	QString command = "";
-	QString Cdata = "";
-	QStringList da;
-	getCommands(data, da);
-	for (int a = 0; a < da.count(); a++)
-	{
-		Cdata = da[a];
-		QStringList da2 = Cdata.split(" ", QString::SkipEmptyParts);
-		command = da2[da2.count()-1];
-		if (command == "Bd")
-		{
-			QString tmpS = Cdata;
-			int an = Cdata.indexOf("(");
-			int en = Cdata.lastIndexOf(")");
-			currentGradientName = Cdata.mid(an+1, en-an-1);
-			currentGradientName.remove("\\");
-			if (da2[da2.count()-3] == "0")
-				currentGradient = VGradient(VGradient::linear);
-			else
-				currentGradient = VGradient(VGradient::radial);
-			currentGradient.clearStops();
-		}
-		else if ((command == "%_Bs") || (command == "%_BS"))
-		{
-			QString stopName = "";
-			double stop = ScCLocale::toDoubleC(da2[da2.count()-2]) / 100.0;
-			double colorShade = 100.0;
-			int colortype = da2[da2.count()-4].toInt();
-			if (colortype == 0)
-			{
-				stopName = parseColorGray(Cdata);
-				const ScColor& gradC = m_Doc->PageColors[stopName];
-				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
-			}
-			else if (colortype == 1)
-			{
-				stopName = parseColor(Cdata);
-				const ScColor& gradC = m_Doc->PageColors[stopName];
-				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
-			}
-			else if (colortype == 2)
-			{
-				stopName = parseColor(Cdata);
-				const ScColor& gradC = m_Doc->PageColors[stopName];
-				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
-			}
-			else if (colortype == 3)
-			{
-				stopName = parseCustomColor(Cdata, colorShade);
-				const ScColor& gradC = m_Doc->PageColors[stopName];
-				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, qRound(colorShade));
-			}
-			else if (colortype == 4)
-			{
-				stopName = parseCustomColorX(Cdata, colorShade, "0");
-				const ScColor& gradC = m_Doc->PageColors[stopName];
-				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, qRound(colorShade));
-			}
-			else if (colortype == 6)
-			{
-				stopName = parseColor(Cdata);
-				const ScColor& gradC = m_Doc->PageColors[stopName];
-				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
-			}
-		}
-		else if (command == "BD")
-		{
-			m_gradients.insert(currentGradientName, currentGradient);
-			if (m_Doc->addGradient(currentGradientName, currentGradient))
-				importedGradients.append(currentGradientName);
-			currentGradient = VGradient(VGradient::linear);
-			currentGradient.clearStops();
-			currentGradient.setRepeatMethod( VGradient::none );
-			currentGradientName = "";
-		}
-	}
-}
-
-void AIPlug::processPattern(QDataStream &ts)
-{
-	QString tmp = "";
-	QString tmpData = "";
-	while (!ts.atEnd())
-	{
-		tmp = removeAIPrefix(readLinefromDataStream(ts));
-		if (importerFlags & LoadSavePlugin::lfKeepPatterns)
-		{
-			if (tmp.startsWith("%_"))
-				tmp.remove(0, 2);
-		}
-		if (patternMode)
-		{
-			if (tmp == "EndPattern")
-			{
-				tmpSel->clear();
-				if (PatternElements.count() > 0)
-				{
-					for (int dre = 0; dre < PatternElements.count(); ++dre)
-					{
-						tmpSel->addItem(PatternElements.at(dre), true);
-						if (groupStack.count() != 0)
-							groupStack.top().removeAll(PatternElements.at(dre));
-					}
-					if (PatternElements.count() > 1)
-						m_Doc->itemSelection_GroupObjects(false, false, tmpSel);
-					if ((tmpSel->width() > 1) && (tmpSel->height() > 1))
-					{
-						ScPattern pat = ScPattern();
-						pat.setDoc(m_Doc);
-						PageItem* currItem = tmpSel->itemAt(0);
-						currItem->setItemName(currentPatternDefName);
-						m_Doc->DoDrawing = true;
-						QImage tmpImg = currItem->DrawObj_toImage(qMax(qRound(patternX2 - patternX1), qRound(patternY2 - patternY1)));
-						if (!tmpImg.isNull())
-						{
-							QImage retImg = QImage(qRound(patternX2 - patternX1), qRound(patternY2 - patternY1), QImage::Format_ARGB32_Premultiplied);
-							retImg.fill( qRgba(255, 255, 255, 0) );
-							QPainter p;
-							p.begin(&retImg);
-							if (PatternElements.count() > 1)
-								p.drawImage(qRound(-patternX1), qRound(-patternY1), tmpImg);
-							else
-								p.drawImage(0, 0, tmpImg);
-							p.end();
-							pat.pattern = retImg;
-		//					pat.pattern = currItem->DrawObj_toImage();
-							m_Doc->DoDrawing = false;
-							//			pat.width = currItem->gWidth;
-							//			pat.height = currItem->gHeight;
-							pat.width = patternX2 - patternX1;
-							pat.height = patternY2 - patternY1;
-							pat.xoffset = -patternX1;
-							pat.yoffset = -patternY1;
-							for (int as = 0; as < tmpSel->count(); ++as)
-							{
-								PageItem* Neu = tmpSel->itemAt(as);
-								Neu->moveBy(-patternX1, -patternY1, true);
-								Neu->gXpos -= patternX1;
-								Neu->gYpos -= patternY1;
-								pat.items.append(Neu);
-							}
-							m_Doc->addPattern(currentPatternDefName, pat);
-							importedPatterns.append(currentPatternDefName);
-						}
-					}
-					m_Doc->itemSelection_DeleteItem(tmpSel);
-				}
-				PatternElements.clear();
-				currentPatternDefName = "";
-				break;
-			}
-			else if (tmp.startsWith("Tile"))
-				continue;
-			else if (tmp.contains(") @"))
-			{
-				tmpData += tmp;
-				tmpData.remove(") @");
-				processData(tmpData);
-				tmpData = "";
-			}
-			else if (tmp.contains(") &"))
-			{
-				tmpData += tmp;
-				tmpData.remove(") &");
-				processData(tmpData);
-				tmpData = "";
-			}
-			else if (tmp.startsWith("("))
-			{
-				if (tmp.startsWith("("))
-					tmp.remove(0, 1);
-				tmpData += " "+tmp;
-			}
-			else
-				processData(tmp);
-		}
-		else if (tmp == "EndPattern")
-		{
-			PatternElements.clear();
-			currentPatternDefName = "";
-			break;
-		}
-		else if (tmp.contains("BeginRaster") && (tmp.startsWith("%")))
-		{
-			while (!ts.atEnd())
-			{
-				tmp = readLinefromDataStream(ts);
-				if (tmp.contains("EndRaster"))
-					break;
-				if(progressDialog)
-				{
-					progressDialog->setProgress("GI", ts.device()->pos());
-					qApp->processEvents();
-				}
-			}
-		}
-		else
-		{
-			Coords.resize(0);
-			Coords.svgInit();
-			int an = tmp.indexOf("(");
-			int en = tmp.lastIndexOf(")");
-			if ((an != -1) && (en != -1))
-			{
-				patternMode = true;
-				currentPatternDefName = tmp.mid(an+1, en-an-1);
-				currentPatternDefName.remove("\\");
-				currentPatternDefName = currentPatternDefName.trimmed().simplified().replace(" ", "_");
-				QString tmpS = tmp.mid(en+1, tmp.size() - en);
-				ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
-				gVals >> patternX1 >> patternY1 >> patternX2 >> patternY2;
-			}
-		}
-	//		processData(tmp);
-	}
-	patternMode = false;
-}
-
-void AIPlug::processSymbol(QDataStream &ts, bool sym)
-{
-	QString tmp = "";
-	QString tmpData = "";
-	while (!ts.atEnd())
-	{
-		tmp = removeAIPrefix(readLinefromDataStream(ts));
-		if (!patternMode)
-		{
-			int an = tmp.indexOf("(");
-			int en = tmp.lastIndexOf(")");
-			if ((an != -1) && (en != -1))
-			{
-				patternMode = true;
-				currentPatternDefName = tmp.mid(an+1, en-an-1);
-				currentPatternDefName.remove("\\");
-				if (sym)
-					currentPatternDefName = "S_"+currentPatternDefName.trimmed().simplified().replace(" ", "_");
-				else
-					currentPatternDefName = currentPatternDefName.trimmed().simplified().replace(" ", "_");
-			}
-		}
-		else if ((tmp == "EndSymbol") || (tmp == "EndBrushPattern"))
-		{
-			tmpSel->clear();
-			if (PatternElements.count() > 0)
-			{
-				for (int dre = 0; dre < PatternElements.count(); ++dre)
-				{
-					tmpSel->addItem(PatternElements.at(dre), true);
-					groupStack.top().removeAll(PatternElements.at(dre));
-				}
-				if (PatternElements.count() > 1)
-					m_Doc->itemSelection_GroupObjects(false, false, tmpSel);
-				if ((tmpSel->width() > 1) && (tmpSel->height() > 1))
-				{
-					ScPattern pat = ScPattern();
-					pat.setDoc(m_Doc);
-					PageItem* currItem = tmpSel->itemAt(0);
-					currItem->setItemName(currentPatternDefName);
-					m_Doc->DoDrawing = true;
-					pat.pattern = currItem->DrawObj_toImage(qMax(tmpSel->width(), tmpSel->height()));
-					if (!pat.pattern.isNull())
-					{
-						pat.width = currItem->gWidth;
-						pat.height = currItem->gHeight;
-						m_Doc->DoDrawing = false;
-						for (int as = 0; as < tmpSel->count(); ++as)
-						{
-							PageItem* Neu = tmpSel->itemAt(as);
-							pat.items.append(Neu);
-						}
-						importedPatterns.append(currentPatternDefName);
-						importedSymbols.insert(currentPatternDefName, QPointF(currItem->xPos(), currItem->yPos()));
-						m_Doc->addPattern(currentPatternDefName, pat);
-					}
-				}
-				m_Doc->itemSelection_DeleteItem(tmpSel);
-			}
-			PatternElements.clear();
-			currentPatternDefName = "";
-			break;
-		}
-		else if (tmp.contains("BeginRaster") && (tmp.startsWith("%")))
-		{
-			while (!ts.atEnd())
-			{
-				tmp = readLinefromDataStream(ts);
-				if (tmp.contains("EndRaster"))
-					break;
-				if(progressDialog)
-				{
-					progressDialog->setProgress("GI", ts.device()->pos());
-					qApp->processEvents();
-				}
-			}
-		}
-		else
-		{
-			processData(tmp);
-		}
-	}
-	patternMode = false;
-}
-
-void AIPlug::processRaster(QDataStream &ts)
-{
-	double m1, m2, m3, m4, m5, m6, x1, y1, x2, y2, dummy;
-	int w, h, type, alpha, bin, bits;
-	QString tmp = "";
-	QString cumulated = "";
-	while (!ts.atEnd())
-	{
-		tmp = readLinefromDataStream(ts);
-		if (tmp.startsWith("%"))
-			break;
-		tmp.remove("[");
-		tmp.remove("]");
-		if (!tmp.isEmpty())
-			cumulated += " " + tmp;
-	}
-	QString Cdata = "";
-	QStringList da;
-	getCommands(cumulated, da);
-	Cdata = da[da.count()-1];
-	ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
-	gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6 >> x1 >> y1 >> x2 >> y2 >> w >> h >> bits >> type >> alpha >> dummy >> bin;
-//	qDebug() << QString("Matrix: %1 %2 %3 %4 %5 %6").arg(m1).arg(m2).arg(m3).arg(m4).arg(m5).arg(m6);
-//	qDebug() << QString("Bounds: %1 %2 %3 %4").arg(x1).arg(y1).arg(x2).arg(y2);
-//	qDebug() << QString("Size: %1 %2").arg(w).arg(h);
-//	qDebug() << QString("Bits: %1").arg(bits);
-//	qDebug() << QString("Typ: %1").arg(type);
-//	qDebug() << QString("Alpha-Channels: %1").arg(alpha);
-//	qDebug() << QString("Encoding: %1").arg(bin);
-	uint dataSize = w * h * (type + alpha);
-	uint alphaData = w * h * type;
-	bool cmyk = false;
-	if (type == 4)
-		cmyk = true;
-	if (tmp.startsWith("%%BeginData"))
-	{
-		QString dummyS;
-		ScTextStream gVals2(&tmp, QIODevice::ReadOnly);
-		tmp = readLinefromDataStream(ts);
-	}
-	QByteArray psdata;
-	psdata.resize(dataSize);
-	RawImage m_image;
-	if (type == 4)
-	{
-		if (alpha > 0)
-			m_image.create(w, 1, 5);
-		else
-			m_image.create(w, 1, 4);
-	}
-	else
-	{
-		if (alpha > 0)
-			m_image.create(w, 1, 4);
-		else
-			m_image.create(w, 1, 3);
-	}
-	bool first = false;
-	if (bin == 0) // 0 = ASCII encoded data
-	{
-		uint dataPointer = 0;
-		while (!ts.atEnd())
-		{
-			if (first)
-				tmp = readLinefromDataStream(ts);
-			first = true;
-			if (tmp.startsWith("%AI5_EndRaster"))
-				break;
-			for (int a = 1; a < tmp.length(); a += 2)
-			{
-				bool ok;
-				ushort data = tmp.mid(a, 2).toUShort(&ok, 16);
-				psdata[dataPointer++] = data;
-			}
-		}
-	}
-	else
-	{
-		psdata.resize(dataSize);
-		ts.readRawData(psdata.data(), dataSize);
-	}
-	QTransform imgMatrix = QTransform(m1, m2, m3, m4, m5, m6);
-	QPointF pos = QPointF(imgMatrix.dx(), imgMatrix.dy());
-	pos += QPointF(m_Doc->currentPage()->xOffset(), -m_Doc->currentPage()->yOffset());
-	pos += QPointF(baseX, -baseY);
-	int z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, pos.x() - docX, docHeight - (pos.y() - docY), 10, 10, 0, CurrColorFill, CurrColorStroke, true);
-	PageItem* ite = m_Doc->Items->at(z);
-	ite->setWidthHeight(fabs(w * m1), fabs(h * m4));
-	double rotation = getRotationFromMatrix(imgMatrix, 0.0);
-	ite->setRotation(rotation * 180 / M_PI);
-	ite->SetRectFrame();
-	m_Doc->setRedrawBounding(ite);
-	ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
-	ite->setTextFlowMode(PageItem::TextFlowDisabled);
-	ite->setFillShade(CurrFillShade);
-	ite->setLineShade(CurrStrokeShade);
-	ite->setFillEvenOdd(fillRule);
-	ite->setFillTransparency(1.0 - Opacity);
-	ite->setLineTransparency(1.0 - Opacity);
-#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
-	ite->setFillBlendmode(blendMode);
-	ite->setLineBlendmode(blendMode);
-#endif
-	ite->setLineEnd(CapStyle);
-	ite->setLineJoin(JoinStyle);
-	uchar *p;
-	uint yCount = 0;
-	quint16 eTag = EXTRASAMPLE_UNASSALPHA;
-	ite->tempImageFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_ai_XXXXXX.tif");
-	ite->tempImageFile->open();
-	QString imgName = getLongPathName(ite->tempImageFile->fileName());
-	ite->tempImageFile->close();
-	ite->isInlineImage = true;
-	TIFF* tif = TIFFOpen(imgName.toLocal8Bit().data(), "w");
-	if (tif)
-	{
-		TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, w);
-		TIFFSetField(tif, TIFFTAG_IMAGELENGTH, h);
-		TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
-		TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, m_image.channels());
-		if (alpha == 1)
-			TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, 1, &eTag);
-		TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
-		if (type == 4)
-			TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
-		else
-			TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
-		TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
-		for (int y = 0; y < h; ++y)
-		{
-			p = m_image.scanLine( 0 );
-			for (int xh = 0; xh < m_image.width(); ++xh )
-			{
-				p[0] = psdata[yCount++];
-				if (type > 1)
-				{
-					p[1] = psdata[yCount++];
-					p[2] = psdata[yCount++];
-					if (type == 4)
-						p[3] = psdata[yCount++];
-				}
-				else
-				{
-					p[1] = p[0];
-					p[2] = p[0];
-				}
-				if (alpha == 1)
-				{
-					if (type == 4)
-						p[4] = psdata[alphaData++];
-					else
-						p[3] = psdata[alphaData++];
-				}
-				p += m_image.channels();
-			}
-			TIFFWriteScanline(tif, m_image.scanLine(0), y);
-		}
-		TIFFClose(tif);
-	}
-	m_Doc->LoadPict(imgName, z);
-	if (ite->PictureIsAvailable)
-		ite->setImageXYScale(ite->width() / ite->pixm.width(), ite->height() / ite->pixm.height());
-	if (importerFlags & LoadSavePlugin::lfCreateDoc)
-		ite->setLocked(itemLocked);
-	if (patternMode)
-		PatternElements.append(ite);
-	else
-		Elements.append(ite);
-	if (groupStack.count() != 0)
-		groupStack.top().append(ite);
-}
-
-void AIPlug::processComment(QDataStream &ts, QString comment)
-{
-	QString tmp = removeAIPrefix(comment);
-	if (tmp.startsWith("Begin_NonPrinting"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("BeginGradient"))
-			{
-				while (!ts.atEnd())
-				{
-					tmp = removeAIPrefix(readLinefromDataStream(ts));
-					if (tmp.startsWith("EndGradient"))
-						break;
-					else
-						processGradientData(tmp);
-				}
-			}
-			if (tmp.startsWith("BeginPattern:"))
-				processPattern(ts);
-			if (tmp == "BeginSymbol")
-				processSymbol(ts, true);
-			if (tmp == "BeginBrushPattern")
-				processSymbol(ts, false);
-			if (tmp.startsWith("End_NonPrinting"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginPattern:"))
-		processPattern(ts);
-	else if (tmp.startsWith("BeginGradient"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndGradient"))
-				break;
-			else
-				processGradientData(tmp);
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginPalette"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndPalette"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp == "BeginSymbol")
-		processSymbol(ts, true);
-	else if (tmp == "BeginBrushPattern")
-		processSymbol(ts, false);
-/*	{
-		while (!ts.atEnd())
-		{
-			processSymbol(ts);
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndSymbol"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	} */
-	else if (tmp.startsWith("BeginDocumentData"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndDocumentData"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginTextDocument"))
-	{
-		QString dataStringT = "";
-		tmp = removeAIPrefix(readLinefromDataStream(ts));
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndTextDocument"))
-			{
-			//	QByteArray fData;
-			//	decodeA85(fData, dataStringT);
-				break;
-			}
-		//	else
-		//		dataStringT += tmp.mid(1);
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("%%BeginProlog"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("%%EndProlog"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("%%BeginData"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("%%EndData"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("%%BeginCrops"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("%%EndCrops"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginRaster"))
-	{
-		processRaster(ts);
-		if(progressDialog)
-		{
-			progressDialog->setProgress("GI", ts.device()->pos());
-			qApp->processEvents();
-		}
-	}
-	else if (tmp.contains("BeginRaster") && (tmp.startsWith("%")))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = readLinefromDataStream(ts);
-			if (tmp.contains("EndRaster"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginSVGFilter"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndSVGFilter"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginArtStyles"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndArtStyles"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginPluginObject"))
-	{
-		while (!ts.atEnd())
-		{
-			tmp = removeAIPrefix(readLinefromDataStream(ts));
-			if (tmp.startsWith("EndPluginObject"))
-				break;
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-	else if (tmp.startsWith("BeginLayer"))
-	{
-		while (!ts.atEnd())
-		{
-			QString rl = readLinefromDataStream(ts);
-			tmp = removeAIPrefix(rl);
-			if (tmp.startsWith("BeginRaster"))
-			{
-				processRaster(ts);
-				continue;
-			}
-			if (tmp.startsWith("EndLayer"))
-				break;
-			else
-				processData(rl);
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-	}
-}
-
-bool AIPlug::convert(QString fn)
-{
-	QString tmp;
-	LineW = 1.0;
-	Opacity = 1.0;
-	blendMode = 0;
-	CurrColorFill = "White";
-	CurrFillShade = 100.0;
-	CurrColorStroke = "Black";
-	CurrStrokeShade = 100.0;
-	JoinStyle = Qt::MiterJoin;
-	CapStyle = Qt::FlatCap;
-	DashPattern.clear();
-	DashOffset = 0.0;
-	fillRule = false;
-	FirstU = false;
-	WasU = false;
-	firstLayer = true;
-	patternMode = false;
-	symbolMode = false;
-	meshMode = false;
-	dataMode = false;
-	fObjectMode = false;
-	dataString = "";
-	itemLocked = false;
-	patternX1 = 0.0;
-	patternY1 = 0.0;
-	patternX2 = 0.0;
-	patternY2 = 0.0;
-	Coords.resize(0);
-	Coords.svgInit();
-	clipCoords.resize(0);
-	clipCoords.svgInit();
-	currentSpecialPath.resize(0);
-	currentSpecialPath.svgInit();
-	currentPoint = FPoint(0.0, 0.0);
-	currentLayer = 0;
-	currentGradient = VGradient(VGradient::linear);
-	currentGradient.clearStops();
-	currentGradient.setRepeatMethod( VGradient::none );
-	currentGradientName = "";
-	currentGradientMatrix = QTransform();
-	currentGradientOrigin = QPointF(0.0, 0.0);
-	currentGradientAngle = 0.0;
-	currentGradientLenght = 1.0;
-	currentPatternName = "";
-	currentPatternX = 0.0;
-	currentPatternY = 0.0;
-	currentPatternXScale = 1.0;
-	currentPatternYScale = 1.0;
-	currentPatternRotation = 0.0;
-	currentStrokePatternName = "";
-	currentStrokePatternX = 0.0;
-	currentStrokePatternY = 0.0;
-	currentStrokePatternXScale = 1.0;
-	currentStrokePatternYScale = 1.0;
-	currentStrokePatternRotation = 0.0;
-	QList<PageItem*> gElements;
-	groupStack.push(gElements);
-	clipStack.push(clipCoords);
-	commandList << "m" << "l" << "L" << "c" << "C" << "v" << "V" << "y" << "Y";		// Path construction
-	commandList << "b" << "B" << "f" << "F" << "s" << "S" << "*u" << "*U";			// Object creation
-	commandList << "u" << "U" << "W" << "q" << "Q";									// Object creation
-	commandList << "A" << "w" << "j" << "J" << "Xy" << "XR";						// Graphic state
-	commandList << "k" << "K" << "Xa" << "XA" << "x" << "X" << "XX" << "Xx";		// Color commands
-	commandList << "Xk" << "g" << "G" << "p" << "P";								// Color commands
-	commandList << "Ln" << "Lb" << "LB";											// Layer commands
-	commandList << "Bd" << "BD" << "%_Bs" << "Bg" << "Bb" << "BB" << "Bm" << "Xm";	// Gradient commands
-	commandList << "To" << "TO" << "Tf" << "Tp" << "Tx" << "TX" << "T*" << "Tk";	// Text commands
-	commandList << "Tc" << "Tz";													// Text commands
-	commandList << "XI" << "XG" << "Xh";											// Image commands
-	commandList << "n" << "N" << "*" << "[";										// Special commands
-	commandList << "X!" << "X#";													// Mesh commands
-	commandList << "M" << "d" << "D" << "E";										// unimplemented
-	commandList << "h" << "H" << "i" << "I" << "Np" << "O";							// unimplemented
-	commandList << "P" << "R";														// unimplemented
-	commandList << "XI" << "XF" << "XG" << "XT" << "Z" << "`" << "~" << "_" << "@";	// unimplemented
-	commandList << "&" << "*w" << "*W" << "Ap" << "Ar";								// unimplemented
-	if(progressDialog)
-	{
-		progressDialog->setOverallProgress(2);
-		progressDialog->setLabel("GI", tr("Generating Items"));
-		qApp->processEvents();
-	}
-	QFile f(fn);
-	if (f.open(QIODevice::ReadOnly))
-	{
-		int fSize = (int) f.size();
-		if (progressDialog)
-		{
-			progressDialog->setTotalSteps("GI", fSize);
-			qApp->processEvents();
-		}
-		QDataStream ts(&f);
-		while (!ts.atEnd())
-		{
-			tmp = readLinefromDataStream(ts);
-			if (tmp.startsWith("%"))
-				processComment(ts, tmp);
-			else
-				processData(tmp);
-			if(progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-		f.close();
-	}
-	if (progressDialog)
-		progressDialog->close();
-	return true;
-}
+		m_Doc->view()->Deselect();
+	Elements.clear();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+		m_Doc->view()->updatesOn(false);
+	m_Doc->scMW()->setScriptRunning(true);
+	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	if (convert(fName))
+	{
+		if (Elements.count() == 0)
+		{
+			if ((importedColors.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients) || (flags & LoadSavePlugin::lfKeepColors) || (flags & LoadSavePlugin::lfKeepPatterns))))
+			{
+				for (int cd = 0; cd < importedColors.count(); cd++)
+				{
+					m_Doc->PageColors.remove(importedColors[cd]);
+				}
+			}
+			if ((importedGradients.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients || (flags & LoadSavePlugin::lfKeepPatterns)))))
+			{
+				for (int cd = 0; cd < importedGradients.count(); cd++)
+				{
+					m_Doc->docGradients.remove(importedGradients[cd]);
+				}
+			}
+			if ((importedPatterns.count() != 0) && (!(flags & LoadSavePlugin::lfKeepPatterns)))
+			{
+				for (int cd = 0; cd < importedPatterns.count(); cd++)
+				{
+					m_Doc->docPatterns.remove(importedPatterns[cd]);
+				}
+			}
+		}
+		tmpSel->clear();
+		QDir::setCurrent(CurDirP);
+		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->setLoading(false);
+		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+		if ((Elements.count() > 0) && (!ret) && (interactive))
+		{
+			if (flags & LoadSavePlugin::lfScripted)
+			{
+				bool loadF = m_Doc->isLoading();
+				m_Doc->setLoading(false);
+				m_Doc->changed();
+				m_Doc->setLoading(loadF);
+				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+				{
+					m_Doc->m_Selection->delaySignalsOn();
+					for (int dre=0; dre<Elements.count(); ++dre)
+					{
+						m_Doc->m_Selection->addItem(Elements.at(dre), true);
+					}
+					m_Doc->m_Selection->delaySignalsOff();
+					m_Doc->m_Selection->setGroupRect();
+					m_Doc->view()->updatesOn(true);
+				}
+			}
+			else
+			{
+				m_Doc->DragP = true;
+				m_Doc->DraggedElem = 0;
+				m_Doc->DragElements.clear();
+				m_Doc->m_Selection->delaySignalsOn();
+				for (int dre=0; dre<Elements.count(); ++dre)
+				{
+					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
+					tmpSel->addItem(Elements.at(dre), true);
+				}
+				tmpSel->setGroupRect();
+				ScriXmlDoc *ss = new ScriXmlDoc();
+				ScElemMimeData* md = new ScElemMimeData();
+				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
+				delete ss;
+/*#ifndef Q_WS_MAC*/
+// see #2196
+				m_Doc->itemSelection_DeleteItem(tmpSel);
+/*#else
+				qDebug("aiimport: leaving items on page");
+#endif*/
+				m_Doc->view()->updatesOn(true);
+				if ((importedColors.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients) || (flags & LoadSavePlugin::lfKeepColors) || (flags & LoadSavePlugin::lfKeepPatterns))))
+				{
+					for (int cd = 0; cd < importedColors.count(); cd++)
+					{
+						m_Doc->PageColors.remove(importedColors[cd]);
+					}
+				}
+				if ((importedGradients.count() != 0) && (!((flags & LoadSavePlugin::lfKeepGradients || (flags & LoadSavePlugin::lfKeepPatterns)))))
+				{
+					for (int cd = 0; cd < importedGradients.count(); cd++)
+					{
+						m_Doc->docGradients.remove(importedGradients[cd]);
+					}
+				}
+				if ((importedPatterns.count() != 0) && (!(flags & LoadSavePlugin::lfKeepPatterns)))
+				{
+					for (int cd = 0; cd < importedPatterns.count(); cd++)
+					{
+						m_Doc->docPatterns.remove(importedPatterns[cd]);
+					}
+				}
+				m_Doc->m_Selection->delaySignalsOff();
+				// We must copy the TransationSettings object as it is owned
+				// by handleObjectImport method afterwards
+				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
+				m_Doc->view()->handleObjectImport(md, transacSettings);
+				m_Doc->DragP = false;
+				m_Doc->DraggedElem = 0;
+				m_Doc->DragElements.clear();
+			}
+		}
+		else
+		{
+			m_Doc->changed();
+			m_Doc->reformPages();
+			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+				m_Doc->view()->updatesOn(true);
+		}
+		success = true;
+	}
+	else
+	{
+		QDir::setCurrent(CurDirP);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->view()->updatesOn(true);
+		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+	}
+	if (interactive)
+		m_Doc->setLoading(false);
+	//CB If we have a gui we must refresh it if we have used the progressbar
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+	{
+		if ((showProgress) && (!interactive))
+			m_Doc->view()->DrawNew();
+	}
+	if (convertedPDF)
+		QFile::remove(fName);
+	return success;
+}
+
+AIPlug::~AIPlug()
+{
+	if (progressDialog)
+		delete progressDialog;
+	delete tmpSel;
+}
+
+bool AIPlug::extractFromPDF(QString infile, QString outfile)
+{
+	bool ret = false;
+#ifdef HAVE_PODOFO
+	QFile outf(outfile);
+	outf.open(QIODevice::WriteOnly);
+	try
+	{
+		PoDoFo::PdfError::EnableDebug( false );
+#if (PODOFO_VERSION == 0 && PODOFO_MINOR > 6)
+		PoDoFo::PdfError::EnableLogging( false );
+#endif
+#if (PODOFO_VERSION == 0 && PODOFO_MINOR == 5 && PODOFO_REVISION == 99) || PODOFO_MINOR > 5
+		PoDoFo::PdfMemDocument doc( infile.toLocal8Bit().data() );
+#else
+		PoDoFo::PdfDocument doc( infile.toLocal8Bit().data() );
+#endif
+		PoDoFo::PdfPage *curPage = doc.GetPage(0);
+		if (curPage != NULL)
+		{
+			PoDoFo::PdfObject *piece = curPage->GetObject()->GetIndirectKey("PieceInfo");
+			if (piece != NULL)
+			{
+				PoDoFo::PdfObject *illy = piece->GetIndirectKey("Illustrator");
+				if (illy != NULL)
+				{
+					PoDoFo::PdfObject *priv = illy->GetIndirectKey("Private");
+					if (priv == NULL)
+						priv = illy;
+					int num = 0;
+					PoDoFo::PdfObject *numBl = priv->GetIndirectKey("NumBlock");
+					if (numBl != NULL)
+						num = numBl->GetNumber() + 1;
+					if (num == 0)
+						num = 99999;
+					QString name = "AIPrivateData%1";
+					QString Key = name.arg(1);
+					PoDoFo::PdfObject *data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
+					if (data == NULL)
+					{
+						name = "AIPDFPrivateData%1";
+						Key = name.arg(1);
+						data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
+					}
+					if (data != NULL)
+					{
+						if (num == 2)
+						{
+							Key = name.arg(1);
+							data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
+							PoDoFo::PdfStream const *stream = data->GetStream();
+							PoDoFo::PdfMemoryOutputStream oStream(1);
+							stream->GetFilteredCopy(&oStream);
+							oStream.Close();
+							long bLen = oStream.GetLength();
+							char *Buffer = oStream.TakeBuffer();
+							outf.write(Buffer, bLen);
+							free( Buffer );
+						}
+						else
+						{
+							for (int a = 2; a < num; a++)
+							{
+								Key = name.arg(a);
+								data = priv->GetIndirectKey(PoDoFo::PdfName(Key.toUtf8().data()));
+								if (data == NULL)
+									break;
+								PoDoFo::PdfStream const *stream = data->GetStream();
+								PoDoFo::PdfMemoryOutputStream oStream(1);
+								stream->GetFilteredCopy(&oStream);
+								oStream.Close();
+								long bLen = oStream.GetLength();
+								char *Buffer = oStream.TakeBuffer();
+								outf.write(Buffer, bLen);
+								free( Buffer );
+							}
+						}
+					}
+					ret = true;
+				}
+			}
+		}
+		outf.close();
+	}
+	catch (PoDoFo::PdfError& e)
+	{
+		outf.close();
+		qDebug("Scribus caught and handled the following exception from PoDoFo while processing a PDF format ai file:\n----\n");
+		e.PrintErrorMsg();
+		qDebug("----\nThe ai file could not be imported.\n");
+		QFile::remove(outfile);
+		return false;
+	}
+#endif
+	return ret;
+}
+
+bool AIPlug::decompressAIData(QString &fName)
+{
+	QString f2 = fName+"_decom.ai";
+	FILE *source = fopen(fName.toLocal8Bit().constData(), "rb");
+	fseek(source, 20, SEEK_SET);
+	FILE *dest = fopen(f2.toLocal8Bit().constData(), "wb");
+	int ret;
+	unsigned have;
+	z_stream strm;
+	char in[4096];
+	char out[4096];
+	strm.zalloc = Z_NULL;
+	strm.zfree = Z_NULL;
+	strm.opaque = Z_NULL;
+	strm.avail_in = 0;
+	strm.next_in = Z_NULL;
+	ret = inflateInit(&strm);
+	if (ret != Z_OK)
+		return false;
+	do
+	{
+		strm.avail_in = fread(in, 1, 4096, source);
+		if (ferror(source))
+		{
+			(void)inflateEnd(&strm);
+			return false;
+		}
+		if (strm.avail_in == 0)
+			break;
+		strm.next_in = (Bytef*)in;
+		do
+		{
+			strm.avail_out = 4096;
+			strm.next_out = (Bytef*)out;
+			ret = inflate(&strm, Z_NO_FLUSH);
+			assert(ret != Z_STREAM_ERROR);
+			switch (ret)
+			{
+				case Z_NEED_DICT:
+					ret = Z_DATA_ERROR;
+				case Z_DATA_ERROR:
+				case Z_MEM_ERROR:
+					(void)inflateEnd(&strm);
+					return false;
+			}
+			have = 4096 - strm.avail_out;
+			if (fwrite(out, 1, have, dest) != have || ferror(dest))
+			{
+				(void)inflateEnd(&strm);
+				return false;
+			}
+		}
+		while (strm.avail_out == 0);
+	}
+	while (ret != Z_STREAM_END);
+	(void)inflateEnd(&strm);
+	fclose(source);
+	fclose(dest);
+	if (!convertedPDF)
+	{
+		QFileInfo bF2(fName);
+		QString tmpFile = ScPaths::getTempFileDir()+ "/"+bF2.baseName()+"_tmp.ai";
+		moveFile(f2, tmpFile);
+		fName = tmpFile;
+		convertedPDF = true;
+	}
+	else
+	{
+		QFile::remove(fName);
+		fName = f2;
+	}
+	return true;
+}
+
+bool AIPlug::parseHeader(QString fName, double &x, double &y, double &b, double &h)
+{
+	QString tmp, BBox, tmp2, FarNam;
+	ScColor cc;
+	double c, m, yc, k;
+	bool found = false;
+	QFile f(fName);
+	if (f.open(QIODevice::ReadOnly))
+	{
+/* Try to find Bounding Box */
+		bool isAtend = false;
+		QDataStream ts(&f);
+		while (!ts.atEnd())
+		{
+			tmp = readLinefromDataStream(ts);
+			if (tmp.startsWith("%%BoundingBox:"))
+			{
+				found = true;
+				BBox = tmp.remove("%%BoundingBox:");
+			}
+			if (!found)
+			{
+				if (tmp.startsWith("%%BoundingBox"))
+				{
+					found = true;
+					BBox = tmp.remove("%%BoundingBox");
+				}
+			}
+			if (tmp.startsWith("%%HiResBoundingBox:"))
+			{
+				found = true;
+				BBox = tmp.remove("%%HiResBoundingBox:");
+			}
+		//	if (tmp.startsWith("%AI3_TileBox:"))
+		//	{
+		//		found = true;
+		//		BBox = tmp.remove("%AI3_TileBox:");
+		//	}
+			if (tmp.startsWith("%%For"))
+			{
+				QStringList res = getStrings(tmp);
+				if (res.count() > 1)
+				{
+					docCreator = res[0];
+					docOrganisation = res[1];
+				}
+			}
+			if (tmp.startsWith("%%CreationDate:"))
+			{
+				QStringList res = getStrings(tmp);
+				if (res.count() > 1)
+				{
+					docDate = res[0];
+					docTime = res[1];
+				}
+				else
+				{
+					docDate = tmp.remove("%%CreationDate: ");
+					docTime = "";
+				}
+			}
+			if (tmp.startsWith("%%Title"))
+			{
+				QStringList res = getStrings(tmp);
+				if (res.count() > 0)
+					docTitle = res[0];
+			}
+			if ((tmp.startsWith("%%CMYKCustomColor")) || (tmp.startsWith("%%CMYKProcessColor")))
+			{
+				if (tmp.contains("(atend)"))
+					isAtend = true;
+				else
+				{
+					if (tmp.startsWith("%%CMYKCustomColor"))
+						tmp = tmp.remove(0,18);
+					else if (tmp.startsWith("%%CMYKProcessColor"))
+						tmp = tmp.remove(0,19);
+					ScTextStream ts2(&tmp, QIODevice::ReadOnly);
+					ts2 >> c >> m >> yc >> k;
+					FarNam = ts2.readAll();
+					FarNam = FarNam.trimmed();
+					FarNam = FarNam.remove(0,1);
+					FarNam = FarNam.remove(FarNam.length()-1,1);
+					FarNam = FarNam.simplified();
+					QByteArray farN;
+					for (int a = 0; a < FarNam.length(); a++)
+					{
+						QChar ch = FarNam.at(a);
+						uint chc = ch.unicode();
+						if (chc > 255)
+							farN.append(chc >> 8);
+						farN.append(chc & 0x00FF);
+					}
+					FarNam = QString::fromUtf8(farN.constData());
+					cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc), qRound(255 * k));
+					cc.setSpotColor(true);
+					if (!FarNam.isEmpty())
+						CustColors.tryAddColor(FarNam, cc);
+					while (!ts.atEnd())
+					{
+						quint64 oldPos = ts.device()->pos();
+						tmp = readLinefromDataStream(ts);
+						if (!tmp.startsWith("%%+"))
+						{
+							ts.device()->seek(oldPos);
+							break;
+						}
+						tmp = tmp.remove(0,3);
+						ScTextStream ts2(&tmp, QIODevice::ReadOnly);
+						ts2 >> c >> m >> yc >> k;
+						FarNam = ts2.readAll();
+						FarNam = FarNam.trimmed();
+						FarNam = FarNam.remove(0,1);
+						FarNam = FarNam.remove(FarNam.length()-1,1);
+						FarNam = FarNam.simplified();
+						QByteArray farN;
+						for (int a = 0; a < FarNam.length(); a++)
+						{
+							QChar ch = FarNam.at(a);
+							uint chc = ch.unicode();
+							if (chc > 255)
+								farN.append(chc >> 8);
+							farN.append(chc & 0x00FF);
+						}
+						FarNam = QString::fromUtf8(farN.constData());
+						cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc), qRound(255 * k));
+						cc.setSpotColor(true);
+						if (!FarNam.isEmpty())
+							CustColors.tryAddColor(FarNam, cc);
+					}
+				}
+			}
+			if ((tmp.startsWith("%%RGBCustomColor")) || (tmp.startsWith("%%RGBProcessColor")))
+			{
+				if (tmp.contains("(atend)"))
+					isAtend = true;
+				else
+				{
+					if (tmp.startsWith("%%RGBCustomColor"))
+						tmp = tmp.remove(0,17);
+					else if (tmp.startsWith("%%RGBProcessColor"))
+						tmp = tmp.remove(0,18);
+					ScTextStream ts2(&tmp, QIODevice::ReadOnly);
+					ts2 >> c >> m >> yc;
+					FarNam = ts2.readAll();
+					FarNam = FarNam.trimmed();
+					FarNam = FarNam.remove(0,1);
+					FarNam = FarNam.remove(FarNam.length()-1,1);
+					FarNam = FarNam.simplified();
+					QByteArray farN;
+					for (int a = 0; a < FarNam.length(); a++)
+					{
+						QChar ch = FarNam.at(a);
+						uint chc = ch.unicode();
+						if (chc > 255)
+							farN.append(chc >> 8);
+						farN.append(chc & 0x00FF);
+					}
+					FarNam = QString::fromUtf8(farN.constData());
+					cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc));
+					if (!FarNam.isEmpty())
+						CustColors.tryAddColor(FarNam, cc);
+					while (!ts.atEnd())
+					{
+						quint64 oldPos = ts.device()->pos();
+						tmp = readLinefromDataStream(ts);
+						if (!tmp.startsWith("%%+"))
+						{
+							ts.device()->seek(oldPos);
+							break;
+						}
+						tmp = tmp.remove(0,3);
+						ScTextStream ts2(&tmp, QIODevice::ReadOnly);
+						ts2 >> c >> m >> yc;
+						FarNam = ts2.readAll();
+						FarNam = FarNam.trimmed();
+						FarNam = FarNam.remove(0,1);
+						FarNam = FarNam.remove(FarNam.length()-1,1);
+						FarNam = FarNam.simplified();
+						QByteArray farN;
+						for (int a = 0; a < FarNam.length(); a++)
+						{
+							QChar ch = FarNam.at(a);
+							uint chc = ch.unicode();
+							if (chc > 255)
+								farN.append(chc >> 8);
+							farN.append(chc & 0x00FF);
+						}
+						FarNam = QString::fromUtf8(farN.constData());
+						cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc));
+						if (!FarNam.isEmpty())
+							CustColors.tryAddColor(FarNam, cc);
+					}
+				}
+			}
+			if (tmp.startsWith("%%EndComments"))
+			{
+				while (!ts.atEnd())
+				{
+					bool isX = false;
+					tmp = readLinefromDataStream(ts);
+					if ((tmp.endsWith("Xa") || tmp.endsWith(" k") || tmp.endsWith(" x")) && (tmp.length() > 4))
+					{
+						ScTextStream ts2(&tmp, QIODevice::ReadOnly);
+						ts2 >> c >> m >> yc >> k;
+						if (tmp.endsWith(" x"))
+						{
+							isX = true;
+							int an = tmp.indexOf("(");
+							int en = tmp.lastIndexOf(")");
+							FarNam = tmp.mid(an+1, en-an-1);
+							FarNam = FarNam.simplified();
+							QByteArray farN;
+							for (int a = 0; a < FarNam.length(); a++)
+							{
+								QChar ch = FarNam.at(a);
+								uint chc = ch.unicode();
+								if (chc > 255)
+									farN.append(chc >> 8);
+								farN.append(chc & 0x00FF);
+							}
+							FarNam = QString::fromUtf8(farN.constData());
+						}
+						tmp = readLinefromDataStream(ts);
+						if (tmp.endsWith("Pc"))
+						{
+							if (!isX)
+							{
+								tmp = tmp.trimmed();
+								tmp = tmp.remove(0,1);
+								int en = tmp.indexOf(")");
+								FarNam = tmp.mid(0, en);
+								FarNam = FarNam.simplified();
+								QByteArray farN;
+								for (int a = 0; a < FarNam.length(); a++)
+								{
+									QChar ch = FarNam.at(a);
+									uint chc = ch.unicode();
+									if (chc > 255)
+										farN.append(chc >> 8);
+									farN.append(chc & 0x00FF);
+								}
+								FarNam = QString::fromUtf8(farN.constData());
+							}
+							cc = ScColor(qRound(255 * c), qRound(255 * m), qRound(255 * yc), qRound(255 * k));
+							cc.setSpotColor(true);
+							CustColors.tryAddColor(FarNam, cc);
+						}
+					}
+				}
+				if (!isAtend)
+					break;
+			}
+		}
+		f.close();
+		if (found)
+		{
+			QStringList bb = BBox.split(" ", QString::SkipEmptyParts);
+			if (bb.count() == 4)
+			{
+				x = ScCLocale::toDoubleC(bb[0]);
+				y = ScCLocale::toDoubleC(bb[1]);
+				b = ScCLocale::toDoubleC(bb[2]);
+				h = ScCLocale::toDoubleC(bb[3]);
+			}
+		}
+	}
+	return found;
+}
+
+QString AIPlug::removeAIPrefix(QString comment)
+{
+	QString tmp;
+	if (comment.startsWith("%AI"))
+	{
+		int an = comment.indexOf("_");
+		tmp = comment.remove(0, an+1);
+	}
+	else
+		tmp = comment;
+	return tmp;
+}
+
+QString AIPlug::parseColor(QString data)
+{
+	QString ret = CommonStrings::None;
+	if (data.isEmpty())
+		return ret;
+	double c, m, y, k;
+	ScColor tmp;
+	ScTextStream Code(&data, QIODevice::ReadOnly);
+	Code >> c;
+	Code >> m;
+	Code >> y;
+	Code >> k;
+	int Cc = qRound(c * 255);
+	int Mc = qRound(m * 255);
+	int Yc = qRound(y * 255);
+	int Kc = qRound(k * 255);
+	tmp.setColor(Cc, Mc, Yc, Kc);
+	tmp.setSpotColor(false);
+	tmp.setRegistrationColor(false);
+	QString namPrefix = "FromAI";
+	QString fNam = m_Doc->PageColors.tryAddColor(namPrefix+tmp.name(), tmp);
+	if (fNam == namPrefix+tmp.name())
+		importedColors.append(fNam);
+	ret = fNam;
+	meshColorMode = 0;
+	return ret;
+}
+
+QString AIPlug::parseColorGray(QString data)
+{
+	QString ret = CommonStrings::None;
+	if (data.isEmpty())
+		return ret;
+	double k;
+	ScColor tmp;
+	ColorList::Iterator it;
+	ScTextStream Code(&data, QIODevice::ReadOnly);
+	Code >> k;
+	int Kc = 255 - qRound(k * 255);
+	tmp.setColor(0, 0, 0, Kc);
+	tmp.setSpotColor(false);
+	tmp.setRegistrationColor(false);
+	QString namPrefix = "FromAI";
+	QString fNam = m_Doc->PageColors.tryAddColor(namPrefix+tmp.name(), tmp);
+	if (fNam == namPrefix+tmp.name())
+		importedColors.append(fNam);
+	ret = fNam;
+	meshColorMode = 2;
+	return ret;
+}
+
+QString AIPlug::parseColorRGB(QString data)
+{
+	QString ret = CommonStrings::None;
+	if (data.isEmpty())
+		return ret;
+	double r, g, b;
+	ScColor tmp;
+	ScTextStream Code(&data, QIODevice::ReadOnly);
+	Code >> r;
+	Code >> g;
+	Code >> b;
+	int Rc = qRound(r * 255);
+	int Gc = qRound(g * 255);
+	int Bc = qRound(b * 255);
+	tmp.setColorRGB(Rc, Gc, Bc);
+	tmp.setSpotColor(false);
+	tmp.setRegistrationColor(false);
+	QString namPrefix = "FromAI";
+	QString fNam = m_Doc->PageColors.tryAddColor(namPrefix+tmp.name(), tmp);
+	if (fNam == namPrefix+tmp.name())
+		importedColors.append(fNam);
+	ret = fNam;
+	meshColorMode = 1;
+	return ret;
+}
+
+QString AIPlug::parseCustomColor(QString data, double &shade)
+{
+	QString ret = CommonStrings::None;
+	if (data.isEmpty())
+		return ret;
+	double c, m, y, k, sh;
+	ScColor tmp;
+	ScTextStream Code(&data, QIODevice::ReadOnly);
+	Code >> c;
+	Code >> m;
+	Code >> y;
+	Code >> k;
+	QString tmpS = data;
+	int an = data.indexOf("(");
+	int en = data.lastIndexOf(")");
+	QString FarNam = data.mid(an+1, en-an-1);
+	FarNam.remove("\\");
+	QString FarSha = data.mid(en+1, data.size() - en);
+	ScTextStream Val(&FarSha, QIODevice::ReadOnly);
+	Val >> sh;
+	shade = (1.0 - sh) * 100.0;
+	int Cc = qRound(c * 255);
+	int Mc = qRound(m * 255);
+	int Yc = qRound(y * 255);
+	int Kc = qRound(k * 255);
+	tmp.setColor(Cc, Mc, Yc, Kc);
+	tmp.setSpotColor(true);
+	tmp.setRegistrationColor(false);
+	QString fNam = m_Doc->PageColors.tryAddColor(FarNam, tmp);
+	if (fNam == FarNam)
+		importedColors.append(FarNam);
+	ret = fNam;
+	meshColorMode = 0;
+	return ret;
+}
+
+QString AIPlug::parseCustomColorX(QString data, double &shade, QString type)
+{
+	QString ret = CommonStrings::None;
+	if (data.isEmpty())
+		return ret;
+	double c, m, y, k, sh, r, g, b;
+	ScColor tmp;
+	ScTextStream Code(&data, QIODevice::ReadOnly);
+	if (type == "1")
+	{
+		Code >> r;
+		Code >> g;
+		Code >> b;
+		int Rc = qRound(r * 255);
+		int Gc = qRound(g * 255);
+		int Bc = qRound(b * 255);
+		tmp.setColorRGB(Rc, Gc, Bc);
+		meshColorMode = 1;
+	}
+	else
+	{
+		Code >> c;
+		Code >> m;
+		Code >> y;
+		Code >> k;
+		int Cc = qRound(c * 255);
+		int Mc = qRound(m * 255);
+		int Yc = qRound(y * 255);
+		int Kc = qRound(k * 255);
+		tmp.setColor(Cc, Mc, Yc, Kc);
+		meshColorMode = 0;
+	}
+	QString tmpS = data;
+	int an = data.indexOf("(");
+	int en = data.lastIndexOf(")");
+	QString FarNam = data.mid(an+1, en-an-1);
+	FarNam.remove("\\");
+	QString FarSha = data.mid(en+1, data.size() - en);
+	ScTextStream Val(&FarSha, QIODevice::ReadOnly);
+	Val >> sh;
+	shade = (1.0 - sh) * 100.0;
+	if (type == "0")
+		tmp.setSpotColor(true);
+	tmp.setRegistrationColor(false);
+	QString fNam = m_Doc->PageColors.tryAddColor(FarNam, tmp);
+	if (fNam == FarNam)
+		importedColors.append(FarNam);
+	ret = fNam;
+	return ret;
+}
+
+QStringList AIPlug::getStrings(QString data)
+{
+	QStringList result;
+	result.clear();
+	QChar tmp;
+	QString tmp2 = "";
+	QString tmp3 = "";
+	bool paran = false;
+	bool skip = false;
+	int digitCount = 0;
+	for (int a = 0; a < data.count(); a++)
+	{
+		tmp = data[a];
+		if (skip)
+		{
+			if (paran)
+			{
+				if (tmp.isDigit())
+				{
+					tmp3 += tmp;
+					digitCount++;
+					if (digitCount == 3)
+					{
+						bool ok = false;
+						int code = tmp3.toInt(&ok, 8);
+						if (ok)
+							tmp2 += QChar(code);
+						digitCount = 0;
+						tmp3 = "";
+						skip = false;
+					}
+				}
+				else
+				{
+					if (tmp == 'r')
+						tmp = SpecialChars::PARSEP;
+					tmp2 += tmp;
+					skip = false;
+				}
+			}
+			continue;
+		}
+		if (tmp == '(')
+		{
+			paran = true;
+			continue;
+		}
+		if (tmp == ')')
+		{
+			paran = false;
+			result.append(tmp2);
+			tmp2 = "";
+			continue;
+		}
+		if (tmp == '\\')
+		{
+			skip = true;
+			continue;
+		}
+		if (paran)
+			tmp2 += tmp;
+	}
+	return result;
+}
+
+void AIPlug::getCommands(QString data, QStringList &commands)
+{
+	QString tmp;
+	QString tmp2;
+	QString tmp3;
+	bool paran = false;
+	bool arra = false;
+	bool skip = false;
+	for (int a = 0; a < data.count(); a++)
+	{
+		tmp = data[a];
+		if (skip)
+		{
+			tmp2 += tmp;
+			skip = false;
+			continue;
+		}
+		if (tmp == "(")
+		{
+			paran = true;
+			tmp2 += tmp;
+			continue;
+		}
+		if (tmp == ")")
+		{
+			paran = false;
+			tmp2 += tmp;
+			continue;
+		}
+		if (tmp == "[")
+		{
+			arra = true;
+			tmp2 += tmp;
+			continue;
+		}
+		if (tmp == "]")
+		{
+			arra = false;
+			tmp2 += tmp;
+			continue;
+		}
+//		if (tmp == "\\")
+//		{
+//			skip = true;
+//			continue;
+//		}
+		if (!paran)
+		{
+			if (tmp == " ")
+			{
+				tmp3 += " " + tmp2;
+				if (commandList.contains(tmp2))
+				{
+					commands.append(tmp3);
+					tmp3 = "";
+				}
+				tmp2 = "";
+				continue;
+			}
+		}
+		tmp2 += tmp;
+	}
+	if (!tmp2.isEmpty())
+	{
+		tmp3 += " " + tmp2;
+		commands.append(tmp3);
+	}
+}
+
+void AIPlug::decodeA85(QByteArray &psdata, QString tmp)
+{
+	uchar byte;
+	ushort data;
+	unsigned long sum = 0;
+	int quintet = 0;
+	for (int c = 0; c < tmp.length(); c++)
+	{
+		byte = QChar(tmp.at(c)).cell();
+		if (byte >= '!' && byte <= 'u')
+		{
+			sum = sum * 85 + ((unsigned long)byte - '!');
+			quintet++;
+			if (quintet == 5)
+			{
+				psdata.resize(psdata.size()+4);
+				data = (sum >> 24) & 0xFF;
+				psdata[psdata.size()-4] = data;
+				data = (sum >> 16) & 0xFF;
+				psdata[psdata.size()-3] = data;
+				data = (sum >> 8) & 0xFF;
+				psdata[psdata.size()-2] = data;
+				data = sum & 0xFF;
+				psdata[psdata.size()-1] = data;
+				quintet = 0;
+				sum = 0;
+			}
+		}
+		else if (byte == 'z')
+		{
+			psdata.resize(psdata.size()+4);
+			psdata[psdata.size()-4] = 0;
+			psdata[psdata.size()-3] = 0;
+			psdata[psdata.size()-2] = 0;
+			psdata[psdata.size()-1] = 0;
+		}
+		else if (byte == '~')
+		{
+			if (quintet)
+			{
+				int i;
+				for (i = 0; i < 5 - quintet; i++)
+					sum *= 85;
+				if (quintet > 1)
+					sum += (0xFFFFFF >> ((quintet - 2) * 8));
+				for (i = 0; i < quintet - 1; i++)
+				{
+					data = (sum >> (24 - 8 * i)) & 0xFF;
+					psdata.resize(psdata.size()+1);
+					psdata[psdata.size()-1] = data;
+				}
+				quintet = 0;
+			}
+			break;
+		}
+	}
+}
+
+void AIPlug::processData(QString data)
+{
+	double x, y, x1, y1, x2, y2;
+	int z, tmpInt;
+	PageItem *ite;
+	QString command = "";
+	QString Cdata = "";
+	QStringList da;
+	if (dataMode && fObjectMode)
+	{
+		if (data.contains("~>"))
+		{
+			dataString += data.mid(1);
+			dataMode = false;
+			QByteArray fData;
+			decodeA85(fData, dataString);
+			dataString = "";
+			if (fObjectMode)
+			{
+				FPoint wh = currentSpecialPath.WidthHeight();
+				if ((currentSpecialPath.size() > 3) && (wh.x() != 0.0) && (wh.y() != 0.0))
+				{
+					z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
+					ite = m_Doc->Items->at(z);
+					ite->PoLine = currentSpecialPath.copy();
+					ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+					ite->ClipEdited = true;
+					ite->FrameType = 3;
+					ite->setFillShade(CurrFillShade);
+					ite->setLineShade(CurrStrokeShade);
+					ite->setFillEvenOdd(fillRule);
+					ite->setFillTransparency(1.0 - Opacity);
+					ite->setLineTransparency(1.0 - Opacity);
+#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
+					ite->setFillBlendmode(blendMode);
+					ite->setLineBlendmode(blendMode);
+#endif
+					ite->setLineEnd(CapStyle);
+					ite->setLineJoin(JoinStyle);
+					wh = getMaxClipF(&ite->PoLine);
+					ite->setWidthHeight(wh.x(),wh.y());
+					ite->setTextFlowMode(PageItem::TextFlowDisabled);
+					m_Doc->AdjustItemSize(ite);
+					ite->tempImageFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_ai_XXXXXX.pdf");
+					ite->tempImageFile->open();
+					ite->tempImageFile->write(fData);
+					QString imgName = getLongPathName(ite->tempImageFile->fileName());
+					ite->tempImageFile->close();
+					ite->isInlineImage = true;
+					m_Doc->LoadPict(imgName, z);
+					if (ite->PictureIsAvailable)
+						ite->setImageXYScale(ite->width() / ite->pixm.width(), ite->height() / ite->pixm.height());
+					ite->setImageFlippedV(true);
+					ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
+					ite->setRedrawBounding();
+					if (importerFlags & LoadSavePlugin::lfCreateDoc)
+						ite->setLocked(itemLocked);
+					if (patternMode)
+						PatternElements.append(ite);
+					else
+						Elements.append(ite);
+					if (groupStack.count() != 0)
+						groupStack.top().append(ite);
+				}
+			}
+			fObjectMode = false;
+			currentSpecialPath.resize(0);
+			currentSpecialPath.svgInit();
+		}
+		else
+		{
+			dataString += data.mid(1);
+		}
+		return;
+	}
+	getCommands(data, da);
+	for (int a = 0; a < da.count(); a++)
+	{
+		Cdata = da[a];
+		if (((Cdata.startsWith("%")) || (Cdata.startsWith(" %"))) && (!meshMode))
+			continue;
+		if (Cdata.contains("SymbolInstance"))
+		{
+			symbolMode = true;
+			return;
+		}
+		if (symbolMode)
+		{
+			if (Cdata.contains("SymbolRef"))
+			{
+				int an = Cdata.indexOf("(");
+				int en = Cdata.lastIndexOf(")");
+				if ((an != -1) && (en != -1))
+				{
+					currentSymbolName = Cdata.mid(an+1, en-an-1);
+					currentSymbolName.remove("\\");
+					currentSymbolName = "S_"+currentSymbolName.trimmed().simplified().replace(" ", "_");
+				}
+			}
+			else if (Cdata.contains("TransformMatrix"))
+			{
+				ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+				ts2 >> x >> y >> x1 >> y1 >> x2 >> y2;
+				QTransform symTrans = QTransform(x, y, x1, y1, x2, y2);
+				double rotation = getRotationFromMatrix(symTrans, 0.0);
+				QTransform symT;
+				symT.translate(x2, y2);
+				QPointF pos1 = importedSymbols[currentSymbolName];
+				pos1 = symT.map(pos1);
+				double xp = pos1.x();
+				double yp = pos1.y();
+			//	xp += m_Doc->currentPage()->xOffset();
+			//	yp += m_Doc->currentPage()->yOffset();
+				int z = m_Doc->itemAdd(PageItem::Symbol, PageItem::Unspecified, baseX + xp, baseY + yp, 1, 1, 0, CommonStrings::None, CommonStrings::None, true);
+				PageItem *b = m_Doc->Items->at(z);
+				b->LayerID = m_Doc->activeLayer();
+				ScPattern pat = m_Doc->docPatterns[currentSymbolName];
+				b->setWidth(pat.width * symTrans.m11());
+				b->setHeight(pat.height * symTrans.m22());
+				b->OldB2 = b->width();
+				b->OldH2 = b->height();
+				b->setPattern(currentSymbolName);
+				double xoffset = 0.0, yoffset = 0.0;
+			//	if (rotation != 0.0)
+			//	{
+			//		double temp = -b->height();
+			//		xoffset = sin(-rotation) * temp;
+			//		yoffset = cos(-rotation) * temp;
+			//	}
+				b->setXPos(xp + xoffset);
+				b->setYPos(yp + yoffset);
+				m_Doc->RotMode(3);
+				m_Doc->RotateItem(rotation * 180 / M_PI, b);
+				m_Doc->RotMode(0);
+//				b->setRotation(rotation * 180 / M_PI);
+				b->setTextFlowMode(PageItem::TextFlowDisabled);
+				b->setFillTransparency(1.0 - Opacity);
+				b->setLineTransparency(1.0 - Opacity);
+	#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
+				b->setFillBlendmode(blendMode);
+				b->setLineBlendmode(blendMode);
+	#endif
+				b->updateClip();
+				if (patternMode)
+					PatternElements.append(b);
+				else
+					Elements.append(b);
+				if (groupStack.count() != 0)
+					groupStack.top().append(b);
+				symbolMode = false;
+			}
+		}
+		QStringList da2 = Cdata.split(" ", QString::SkipEmptyParts);
+		if (da2.count() == 0)
+			return;
+		command = da2[da2.count()-1];
+/* Start Path construction commands */
+		if (command == "m")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> x >> y;
+			Coords.svgMoveTo(x - docX, docHeight - (y - docY));
+			currentPoint = FPoint(x - docX, docHeight - (y - docY));
+		}
+		else if ((command == "L") || (command == "l"))
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> x >> y;
+			Coords.svgLineTo(x - docX, docHeight - (y - docY));
+			currentPoint = FPoint(x - docX, docHeight - (y - docY));
+		}
+		else if ((command == "C") || (command == "c"))
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> x >> y >> x1 >> y1 >> x2 >> y2;
+			Coords.svgCurveToCubic(x - docX, docHeight - (y - docY),
+								   x1 - docX, docHeight - (y1 - docY),
+								   x2 - docX, docHeight - (y2 - docY));
+			currentPoint = FPoint(x2 - docX, docHeight - (y2 - docY));
+		}
+		else if ((command == "Y") || (command == "y"))
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> x1 >> y1 >> x2 >> y2;
+			Coords.svgCurveToCubic(x1 - docX, docHeight - (y1 - docY), x2 - docX, docHeight - (y2 - docY), x2 - docX, docHeight - (y2 - docY));
+			currentPoint = FPoint(x2 - docX, docHeight - (y2 - docY));
+		}
+		else if ((command == "V") || (command == "v"))
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> x >> y >> x2 >> y2;
+			Coords.svgCurveToCubic(currentPoint.x(), currentPoint.y(), x - docX, docHeight - (y - docY), x2 - docX, docHeight - (y2 - docY));
+			currentPoint = FPoint(x2 - docX, docHeight - (y2 - docY));
+		}
+/* End Path construction commands */
+/* Start Object creation commands */
+		else if ((command == "b") || (command == "B") || (command == "f") || (command == "F") || (command == "s") || (command == "S"))
+		{
+			FPoint wh = Coords.WidthHeight();
+			if ((Coords.size() > 3) && (wh.x() != 0.0) && (wh.y() != 0.0))
+			{
+				if ((!WasU) || ((WasU) && (FirstU)))
+				{
+					if ((command == "B") || (command == "F") || (command == "S"))
+					{
+						if (command == "F")
+							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CommonStrings::None, true);
+						else if (command == "B")
+							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+						else
+							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColorStroke, true);
+					}
+					else
+					{
+						if (command == "f")
+							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CommonStrings::None, true);
+						else if (command == "b")
+							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+						else
+							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColorStroke, true);
+					}
+					ite = m_Doc->Items->at(z);
+					ite->PoLine = Coords.copy();
+					ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+					ite->ClipEdited = true;
+					ite->FrameType = 3;
+					ite->setFillShade(CurrFillShade);
+					ite->setLineShade(CurrStrokeShade);
+					ite->setFillEvenOdd(fillRule);
+					ite->setFillTransparency(1.0 - Opacity);
+					ite->setLineTransparency(1.0 - Opacity);
+	#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
+					ite->setFillBlendmode(blendMode);
+					ite->setLineBlendmode(blendMode);
+	#endif
+					if (!currentPatternName.isEmpty())
+					{
+						ite->setPattern(currentPatternName);
+						ite->setPatternTransform(currentPatternXScale * 100, currentPatternYScale * 100, currentPatternX, currentPatternY, currentPatternRotation, 0.0, 0.0);
+						ite->GrType = 8;
+						currentPatternName = "";
+					}
+					if (!currentStrokePatternName.isEmpty())
+					{
+						ite->setStrokePattern(currentStrokePatternName);
+						ite->setStrokePatternTransform(currentStrokePatternXScale * 100, currentStrokePatternYScale * 100, currentStrokePatternX, currentStrokePatternY, currentStrokePatternRotation, 0.0, 0.0, 1.0);
+						currentStrokePatternName = "";
+					}
+					ite->setLineEnd(CapStyle);
+					ite->setLineJoin(JoinStyle);
+					if (!WasU)
+					{
+						FPoint wh = getMaxClipF(&ite->PoLine);
+						ite->setWidthHeight(wh.x(),wh.y());
+						ite->setTextFlowMode(PageItem::TextFlowDisabled);
+						m_Doc->AdjustItemSize(ite);
+					}
+					if (patternMode)
+						PatternElements.append(ite);
+					else
+						Elements.append(ite);
+					if (groupStack.count() != 0)
+						groupStack.top().append(ite);
+					if (importerFlags & LoadSavePlugin::lfCreateDoc)
+						ite->setLocked(itemLocked);
+					
+				}
+				else
+				{
+					ite = m_Doc->Items->at(m_Doc->Items->count()-1);
+					ite->PoLine.setMarker();
+					Coords.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+					ite->PoLine.putPoints(ite->PoLine.size(), Coords.size(), Coords);
+				}
+				FirstU = false;
+				itemRendered = true;
+				CurrFillShade = 100.0;
+				CurrStrokeShade = 100.0;
+			}
+			Coords.resize(0);
+			Coords.svgInit();
+		}
+		else if (command == "*u")
+		{
+			FirstU = true;
+			WasU = true;
+		}
+		else if (command == "*U")
+		{
+			WasU = false;
+			ite = m_Doc->Items->at(m_Doc->Items->count()-1);
+			FPoint wh = getMaxClipF(&ite->PoLine);
+			ite->setWidthHeight(wh.x(),wh.y());
+			m_Doc->AdjustItemSize(ite);
+		}
+		else if ((command == "u") || (command == "q"))
+		{
+			QList<PageItem*> gElements;
+			groupStack.push(gElements);
+			clipStack.push(clipCoords);
+		}
+		else if ((command == "U") || (command == "Q"))
+		{
+			if (groupStack.count() != 0)
+			{
+				QList<PageItem*> gElements = groupStack.pop();
+				clipCoords = clipStack.pop();
+				tmpSel->clear();
+				if (gElements.count() > 0)
+				{
+					for (int dre = 0; dre < gElements.count(); ++dre)
+					{
+						tmpSel->addItem(gElements.at(dre), true);
+						if (patternMode)
+							PatternElements.removeAll(gElements.at(dre));
+						else
+							Elements.removeAll(gElements.at(dre));
+					}
+					ite = m_Doc->groupObjectsSelection(tmpSel);
+					if ((clipCoords.size() > 4) && (command == "Q"))
+					{
+						clipCoords.translate(m_Doc->currentPage()->xOffset()-ite->xPos(), m_Doc->currentPage()->yOffset()-ite->yPos());
+						ite->PoLine = clipCoords.copy();
+						ite->PoLine.translate(baseX, baseY);
+					}
+					for (int as = 0; as < tmpSel->count(); ++as)
+					{
+						if (patternMode)
+							PatternElements.append(tmpSel->itemAt(as));
+						else
+							Elements.append(tmpSel->itemAt(as));
+					}
+				}
+				if (groupStack.count() != 0)
+				{
+					for (int as = 0; as < tmpSel->count(); ++as)
+					{
+						groupStack.top().append(tmpSel->itemAt(as));
+					}
+				}
+				tmpSel->clear();
+			}
+			if (command == "Q")
+			{
+				clipCoords.resize(0);
+				clipCoords.svgInit();
+			}
+		}
+		else if (command == "W")
+		{
+			if (clipStack.count() != 0)
+			{
+				if (clipStack.top().size() > 3)
+				{
+					clipStack.top().setMarker();
+					clipStack.top().putPoints(clipStack.top().size(), Coords.size(), Coords);
+				}
+				else
+					clipStack.top() = Coords.copy();
+			}
+		}
+		else if ((command == "N") || (command == "n"))
+		{
+			if (command == "n")
+				Coords.svgClosePath();
+			currentSpecialPath = Coords.copy();
+			Coords.resize(0);
+			Coords.svgInit();
+		}
+/* End Object construction commands */
+/* Start Graphics state commands */
+		else if (command == "A")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> tmpInt;
+			if (tmpInt == 1)
+				itemLocked = true;
+			else
+				itemLocked = false;
+		}
+		else if (command == "w")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> LineW;
+		}
+		else if (command == "j")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> tmpInt;
+			if (tmpInt == 0)
+				JoinStyle = Qt::MiterJoin;
+			else if (tmpInt == 1)
+				JoinStyle = Qt::RoundJoin;
+			else if (tmpInt == 1)
+				JoinStyle = Qt::BevelJoin;
+		}
+		else if (command == "J")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> tmpInt;
+			if (tmpInt == 0)
+				CapStyle = Qt::FlatCap;
+			else if (tmpInt == 1)
+				CapStyle = Qt::RoundCap;
+			else if (tmpInt == 1)
+				CapStyle = Qt::SquareCap;
+		}
+		/* undocumented Command Xy
+			- has up to 5 Parameters
+			- first Parameter might be the Blendmode
+			- second Parameter is the Opacity
+		*/
+		else if (command == "Xy")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> blendMode >> Opacity;
+		}
+		else if (command == "XR")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> tmpInt;
+			if (tmpInt == 1)
+				fillRule = true;
+			else
+				fillRule = false;
+		}
+		else if (command == "Bb")
+		{
+			gradientMode = true;
+			wasBC = false;
+			itemRendered = false;
+			startMatrix = QTransform();
+			endMatrix = QTransform();
+		}
+		else if (command == "Xm")
+		{
+			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+			double m1, m2, m3, m4, m5, m6;
+			gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
+			startMatrix.translate(m5, -m6);
+			endMatrix.scale(m1, m4);
+			wasBC = true;
+		}
+		else if (command == "Bm")
+		{
+			if (m_gradients[currentGradientName].type() == 1)
+			{
+				ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+				double m1, m2, m3, m4, m5, m6;
+				gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
+				startMatrix.translate(m5, -m6);
+//				endMatrix.scale(m1, m4);
+				endMatrix *= QTransform(m1, m2, m3, m4, 0, 0);
+//				endMatrix = QTransform(m1, m2, m3, m4, m5, m6);
+				wasBC = true;
+			}
+		}
+		else if (command == "BB")
+		{
+			if (itemRendered)
+			{
+				gradientMode = false;
+				ite = m_Doc->Items->at(m_Doc->Items->count()-1);
+				ite->fill_gradient = m_gradients[currentGradientName];
+				ite->setGradient(currentGradientName);
+				if (ite->fill_gradient.type() == 0)
+					ite->GrType = 6;
+				else
+					ite->GrType = 7;
+				QTransform m1;
+				m1.translate(currentGradientOrigin.x() - ite->xPos(), currentGradientOrigin.y() - ite->yPos());
+				m1.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+				m1.rotate(-currentGradientAngle);
+				ite->GrStartX = currentGradientOrigin.x() - ite->xPos() + m_Doc->currentPage()->xOffset();
+				ite->GrStartY = currentGradientOrigin.y() - ite->yPos() + m_Doc->currentPage()->yOffset();
+				QPointF target = m1.map(QPointF(currentGradientLenght, 0.0));
+				ite->GrEndX = target.x();
+				ite->GrEndY = target.y();
+				if (wasBC)
+				{
+					QPointF newS = startMatrix.map(QPointF(ite->GrStartX, ite->GrStartY));
+					ite->GrStartX = newS.x();
+					ite->GrStartY = newS.y();
+					QTransform m2;
+					m2.rotate(-currentGradientAngle);
+					m2 *= endMatrix;
+					QPointF target = m2.map(QPointF(currentGradientLenght, 0.0));
+					ite->GrEndX = target.x();
+					ite->GrEndY = target.y();
+				}
+			}
+			wasBC = false;
+			currentGradientMatrix = QTransform();
+			currentGradientOrigin = QPointF(0.0, 0.0);
+			currentGradientAngle = 0.0;
+			currentGradientLenght = 1.0;
+			itemRendered = false;
+		}
+		else if (command == "Bg")
+		{
+			int an = Cdata.indexOf("(");
+			int en = Cdata.lastIndexOf(")");
+			currentGradientName = Cdata.mid(an+1, en-an-1);
+			currentGradientName.remove("\\");
+			QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
+			ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
+			double xOrig, yOrig, m1, m2, m3, m4, m5, m6;
+			gVals >> xOrig >> yOrig >> currentGradientAngle >> currentGradientLenght >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
+			currentGradientOrigin = QPointF(xOrig - docX, docHeight - (yOrig - docY));
+			currentGradientMatrix = QTransform(m1, m2, m3, m4, m5, m6);
+		}
+/* End Graphics state commands */
+/* Start Color commands */
+		else if ((command == "G") || (command == "g"))
+		{
+			if (command == "G")
+				CurrColorStroke = parseColorGray(Cdata);
+			else
+				CurrColorFill = parseColorGray(Cdata);
+			meshColorMode = 2;
+		}
+		else if ((command == "K") || (command == "k"))
+		{
+			if (command == "K")
+				CurrColorStroke = parseColor(Cdata);
+			else
+				CurrColorFill = parseColor(Cdata);
+		}
+		else if ((command == "XA") || (command == "Xa"))
+		{
+			QString Xdata = da2[da2.count()-4] + " " + da2[da2.count()-3] + " " + da2[da2.count()-2];
+			if (command == "XA")
+				CurrColorStroke = parseColorRGB(Xdata);
+			else
+				CurrColorFill = parseColorRGB(Xdata);
+			meshColorMode = 1;
+		}
+		else if ((command == "XX") || (command == "Xx") || (command == "Xk"))
+		{
+			if (command == "XX")
+				CurrColorStroke = parseCustomColorX(Cdata, CurrStrokeShade, da2[da2.count()-2]);
+			else
+				CurrColorFill = parseCustomColorX(Cdata, CurrFillShade, da2[da2.count()-2]);
+		}
+		else if ((command == "X") || (command == "x"))
+		{
+			if (command == "X")
+				CurrColorStroke = parseCustomColor(Cdata, CurrStrokeShade);
+			else
+				CurrColorFill = parseCustomColor(Cdata, CurrFillShade);
+		}
+		else if (command == "p")
+		{
+			int an = Cdata.indexOf("(");
+			int en = Cdata.lastIndexOf(")");
+			currentPatternName = Cdata.mid(an+1, en-an-1);
+			currentPatternName.remove("\\");
+			currentPatternName = currentPatternName.trimmed().simplified().replace(" ", "_");
+			QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
+			ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
+			gVals >> currentPatternX >> currentPatternY >> currentPatternXScale >> currentPatternYScale >> currentPatternRotation;
+		}
+		else if (command == "P")
+		{
+			int an = Cdata.indexOf("(");
+			int en = Cdata.lastIndexOf(")");
+			currentStrokePatternName = Cdata.mid(an+1, en-an-1);
+			currentStrokePatternName.remove("\\");
+			currentStrokePatternName = currentPatternName.trimmed().simplified().replace(" ", "_");
+			QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
+			ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
+			gVals >> currentStrokePatternX >> currentStrokePatternY >> currentStrokePatternXScale >> currentStrokePatternYScale >> currentStrokePatternRotation;
+		}
+		else if (command == "X!")
+		{
+			if (Cdata.contains("/Mesh"))
+			{
+				meshMode = true;
+				meshNodeCounter = 0;
+//				meshColorMode = 0;
+				meshGradientArray.clear();
+			}
+			if (Cdata.contains("/End"))
+			{
+				meshMode = false;
+				if (meshGradientArray.count() != 0)
+				{
+					z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
+					ite = m_Doc->Items->at(z);
+					for (int x = 0; x < meshGradientArray.count(); x++)
+					{
+						for (int y = 0; y < meshGradientArray[x].count(); y++)
+						{
+							meshGradientArray[x][y].moveRel(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+						}
+					}
+					ite->meshGradientArray = meshGradientArray;
+					ite->GrType = 11;
+					ite->meshToShape();
+					for (int grow = 0; grow < ite->meshGradientArray.count(); grow++)
+					{
+						for (int gcol = 0; gcol < ite->meshGradientArray[grow].count(); gcol++)
+						{
+							meshPoint mp = ite->meshGradientArray[grow][gcol];
+							ite->setMeshPointColor(grow, gcol, mp.colorName, mp.shade, mp.transparency);
+						}
+					}
+					ite->setFillShade(CurrFillShade);
+					ite->setLineShade(CurrFillShade);
+					ite->setFillEvenOdd(fillRule);
+					ite->setFillTransparency(1.0 - Opacity);
+					ite->setLineTransparency(1.0 - Opacity);
+	#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
+					ite->setFillBlendmode(blendMode);
+					ite->setLineBlendmode(blendMode);
+	#endif
+					ite->setLineEnd(CapStyle);
+					ite->setLineJoin(JoinStyle);
+					if (importerFlags & LoadSavePlugin::lfCreateDoc)
+						ite->setLocked(itemLocked);
+					if (patternMode)
+						PatternElements.append(ite);
+					else
+						Elements.append(ite);
+					if (groupStack.count() != 0)
+						groupStack.top().append(ite);
+				}
+			}
+		}
+		else if (command == "X#")
+		{
+			int an = Cdata.indexOf("_");
+			QString cmdLine = Cdata.remove(0, an+1);
+			an = cmdLine.lastIndexOf("/");
+			QString tmpS = cmdLine.mid(an+1, Cdata.size());
+			ScTextStream mVals(&tmpS, QIODevice::ReadOnly);
+			QString mKey;
+			mVals >> mKey;
+			if (mKey == "Size")
+			{
+				meshGradientArray.clear();
+				int ans = cmdLine.indexOf("[");
+				int ens = cmdLine.lastIndexOf("]");
+				QString sizeVals = cmdLine.mid(ans+1, ens-ans-1);
+				ScTextStream mVals2(&sizeVals, QIODevice::ReadOnly);
+				mVals2 >> meshXSize >> meshYSize;
+				for (int mgr = 0; mgr < meshYSize+1; mgr++)
+				{
+					QList<meshPoint> ml;
+					for (int mgc = 0; mgc < meshXSize+1; mgc++)
+					{
+						meshPoint mp;
+						ml.append(mp);
+					}
+					meshGradientArray.append(ml);
+				}
+			}
+			if (mKey == "P")
+			{
+				int ans = cmdLine.indexOf("[");
+				int ens = cmdLine.lastIndexOf("]");
+				QString posVals = cmdLine.mid(ans+1, ens-ans-1);
+				ScTextStream mVals3(&posVals, QIODevice::ReadOnly);
+				mVals3 >> currentMeshXPos >> currentMeshYPos;
+			}
+			if (mKey == "CS")
+			{
+				if (Cdata.contains("CMYK"))
+					meshColorMode = 0;
+				else if (Cdata.contains("RGB"))
+					meshColorMode = 1;
+				else if (Cdata.contains("Gray"))
+					meshColorMode = 2;
+			}
+			if (mKey == "E")
+			{
+				int indY = meshYSize - currentMeshYPos - 1;
+				int indX = currentMeshXPos;
+				FPoint p2 = FPoint(meshNode1PointX, meshNode1PointY);
+				FPoint p1 = FPoint(meshNode2PointX, meshNode2PointY);
+				FPoint p4 = FPoint(meshNode3PointX, meshNode3PointY);
+				FPoint p3 = FPoint(meshNode4PointX, meshNode4PointY);
+				meshGradientArray[indY+1][indX+1].gridPoint   = FPoint(meshNode2PointX, meshNode2PointY);
+				meshGradientArray[indY+1][indX+1].controlTop  = FPoint(meshNode2Control2X, meshNode2Control2Y);
+				meshGradientArray[indY+1][indX+1].controlLeft = FPoint(meshNode2Control1X, meshNode2Control1Y);
+				meshGradientArray[indY+1][indX+1].colorName = meshColor2;
+				meshGradientArray[indY+1][indX+1].shade = 100;
+				meshGradientArray[indY+1][indX+1].transparency = 1.0;
+				meshGradientArray[indY+1][indX].gridPoint    = FPoint(meshNode1PointX, meshNode1PointY);
+				meshGradientArray[indY+1][indX].controlRight = FPoint(meshNode1Control2X, meshNode1Control2Y);
+				meshGradientArray[indY+1][indX].controlTop   = FPoint(meshNode1Control1X, meshNode1Control1Y);
+				meshGradientArray[indY+1][indX].colorName = meshColor1;
+				meshGradientArray[indY+1][indX].shade = 100;
+				meshGradientArray[indY+1][indX].transparency = 1.0;
+				meshGradientArray[indY][indX].gridPoint     = FPoint(meshNode4PointX, meshNode4PointY);
+				meshGradientArray[indY][indX].controlBottom = FPoint(meshNode4Control2X, meshNode4Control2Y);
+				meshGradientArray[indY][indX].controlRight  = FPoint(meshNode4Control1X, meshNode4Control1Y);
+				meshGradientArray[indY][indX].colorName = meshColor4;
+				meshGradientArray[indY][indX].shade = 100;
+				meshGradientArray[indY][indX].transparency = 1.0;
+				meshGradientArray[indY][indX+1].gridPoint     = FPoint(meshNode3PointX, meshNode3PointY);
+				meshGradientArray[indY][indX+1].controlLeft   = FPoint(meshNode3Control2X, meshNode3Control2Y);
+				meshGradientArray[indY][indX+1].controlBottom = FPoint(meshNode3Control1X, meshNode3Control1Y);
+				meshGradientArray[indY][indX+1].colorName = meshColor3;
+				meshGradientArray[indY][indX+1].shade = 100;
+				meshGradientArray[indY][indX+1].transparency = 1.0;
+				meshNodeCounter = 0;
+			}
+			if (mKey == "N")
+			{
+				double cVal, mVal, yVal, kVal, coorX1, coorY1, coorX2, coorY2, coorX3, coorY3;
+				int dummy;
+				meshNodeCounter++;
+				int ans = cmdLine.indexOf("[");
+				int ens = cmdLine.lastIndexOf("]");
+				QString nodeVals = cmdLine.mid(ans+1, ens-ans-1);
+				ScTextStream mVals4(&nodeVals, QIODevice::ReadOnly);
+				kVal = 0.0;
+				if (meshColorMode == 0)
+					mVals4 >> cVal >> mVal >> yVal >> kVal >> coorX1 >> coorY1 >> coorX2 >> coorY2 >> dummy >> coorX3 >> coorY3;
+				else if (meshColorMode == 1)
+					mVals4 >> cVal >> mVal >> yVal >> coorX1 >> coorY1 >> coorX2 >> coorY2 >> dummy >> coorX3 >> coorY3;
+				else if (meshColorMode == 2)
+					mVals4 >> cVal >> coorX1 >> coorY1 >> coorX2 >> coorY2 >> dummy >> coorX3 >> coorY3;
+				QString nodeColor;
+				ScColor tmpColor;
+				ColorList::Iterator it;
+				int Cc = qRound(cVal * 255);
+				int Mc = qRound(mVal * 255);
+				int Yc = qRound(yVal * 255);
+				int Kc = qRound(kVal * 255);
+				int hC, hM, hY, hK;
+				bool found = false;
+				if (meshColorMode == 0)
+				{
+					tmpColor.setColor(Cc, Mc, Yc, Kc);
+					for (it = m_Doc->PageColors.begin(); it != m_Doc->PageColors.end(); ++it)
+					{
+						if (it.value().getColorModel() == colorModelCMYK)
+						{
+							it.value().getCMYK(&hC, &hM, &hY, &hK);
+							if ((Cc == hC) && (Mc == hM) && (Yc == hY) && (Kc == hK))
+							{
+								nodeColor = it.key();
+								found = true;
+								break;
+							}
+						}
+					}
+				}
+				else if (meshColorMode == 1)
+				{
+					tmpColor.setColorRGB(Cc, Mc, Yc);
+					for (it = m_Doc->PageColors.begin(); it != m_Doc->PageColors.end(); ++it)
+					{
+						if (it.value().getColorModel() == colorModelRGB)
+						{
+							it.value().getRGB(&hC, &hM, &hY);
+							if ((Cc == hC) && (Mc == hM) && (Yc == hY))
+							{
+								nodeColor = it.key();
+								found = true;
+								break;
+							}
+						}
+					}
+				}
+				else if (meshColorMode == 2)
+				{
+					tmpColor.setColor(0, 0, 0, Cc);
+					for (it = m_Doc->PageColors.begin(); it != m_Doc->PageColors.end(); ++it)
+					{
+						if (it.value().getColorModel() == colorModelCMYK)
+						{
+							it.value().getCMYK(&hC, &hM, &hY, &hK);
+							if ((Cc == hC) && (Mc == hM) && (Yc == hY) && (Kc == hK))
+							{
+								nodeColor = it.key();
+								found = true;
+								break;
+							}
+						}
+					}
+				}
+				if (!found)
+				{
+					tmpColor.setSpotColor(false);
+					tmpColor.setRegistrationColor(false);
+					QString namPrefix = "FromAI";
+					m_Doc->PageColors.insert(namPrefix+tmpColor.name(), tmpColor);
+					nodeColor = namPrefix+tmpColor.name();
+				}
+				if (meshNodeCounter == 1)
+				{
+					meshNode1PointX = coorX1 - docX;
+					meshNode1PointY = docHeight - (coorY1 - docY);
+					meshNode1Control2X = coorX2 - docX;
+					meshNode1Control2Y = docHeight - (coorY2 - docY);
+					meshNode1Control1X = coorX3 - docX;
+					meshNode1Control1Y = docHeight - (coorY3 - docY);
+					meshColor1 = nodeColor;
+				}
+				if (meshNodeCounter == 2)
+				{
+					meshNode2PointX = coorX1 - docX;
+					meshNode2PointY = docHeight - (coorY1 - docY);
+					meshNode2Control2X = coorX2 - docX;
+					meshNode2Control2Y = docHeight - (coorY2 - docY);
+					meshNode2Control1X = coorX3 - docX;
+					meshNode2Control1Y = docHeight - (coorY3 - docY);
+					meshColor2 = nodeColor;
+				}
+				if (meshNodeCounter == 3)
+				{
+					meshNode3PointX = coorX1 - docX;
+					meshNode3PointY = docHeight - (coorY1 - docY);
+					meshNode3Control2X = coorX2 - docX;
+					meshNode3Control2Y = docHeight - (coorY2 - docY);
+					meshNode3Control1X = coorX3 - docX;
+					meshNode3Control1Y = docHeight - (coorY3 - docY);
+					meshColor3 = nodeColor;
+				}
+				if (meshNodeCounter == 4)
+				{
+					meshNode4PointX = coorX1 - docX;
+					meshNode4PointY = docHeight - (coorY1 - docY);
+					meshNode4Control2X = coorX2 - docX;
+					meshNode4Control2Y = docHeight - (coorY2 - docY);
+					meshNode4Control1X = coorX3 - docX;
+					meshNode4Control1Y = docHeight - (coorY3 - docY);
+					meshColor4 = nodeColor;
+				}
+			}
+		}
+/* End Color commands */
+/* Start Layer commands */
+		else if (command == "Lb")
+		{
+			if (importerFlags & LoadSavePlugin::lfCreateDoc)
+			{
+				int visible, preview, enabled, printing, dummy, rc, gc, bc;
+				ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+				ts2 >> visible >> preview >> enabled >> printing >> dummy >> dummy >> dummy >> rc >> gc >> bc;
+				if (!firstLayer)
+					currentLayer = m_Doc->addLayer("Layer", true);
+				m_Doc->setLayerVisible(currentLayer, static_cast<bool>(visible));
+				m_Doc->setLayerOutline(currentLayer, static_cast<bool>(!preview));
+				m_Doc->setLayerLocked(currentLayer, static_cast<bool>(!enabled));
+				m_Doc->setLayerPrintable(currentLayer, static_cast<bool>(printing));
+				m_Doc->setLayerMarker(currentLayer, QColor(rc, gc, bc));
+				QList<PageItem*> gElements;
+				groupStack.push(gElements);
+				clipStack.push(clipCoords);
+				firstLayer = false;
+			}
+			Coords.resize(0);
+			Coords.svgInit();
+		}
+		else if (command == "LB")
+		{
+			if (importerFlags & LoadSavePlugin::lfCreateDoc)
+			{
+				if (groupStack.count() != 0)
+				{
+					QList<PageItem*> gElements = groupStack.pop();
+					clipStack.pop();
+					tmpSel->clear();
+					if (gElements.count() > 0)
+					{
+						for (int dre = 0; dre < gElements.count(); ++dre)
+						{
+							tmpSel->addItem(gElements.at(dre), true);
+							if (patternMode)
+								PatternElements.removeAll(gElements.at(dre));
+							else
+								Elements.removeAll(gElements.at(dre));
+						}
+						m_Doc->groupObjectsSelection(tmpSel);
+						ite = tmpSel->itemAt(0);
+						if (Coords.size() > 3)
+						{
+							Coords.translate(m_Doc->currentPage()->xOffset()-ite->xPos(), m_Doc->currentPage()->yOffset()-ite->yPos());
+							ite->PoLine = Coords.copy();
+							ite->PoLine.translate(baseX, baseY);
+						}
+						for (int as = 0; as < tmpSel->count(); ++as)
+						{
+							if (patternMode)
+								PatternElements.append(tmpSel->itemAt(as));
+							else
+								Elements.append(tmpSel->itemAt(as));
+						}
+						ite->setItemName( tr("Group%1").arg(m_Doc->layerName(currentLayer)));
+					}
+					if (groupStack.count() != 0)
+					{
+						for (int as = 0; as < tmpSel->count(); ++as)
+						{
+							groupStack.top().append(tmpSel->itemAt(as));
+						}
+					}
+					tmpSel->clear();
+				}
+			}
+			Coords.resize(0);
+			Coords.svgInit();
+		}
+		else if (command == "Ln")
+		{
+			if (importerFlags & LoadSavePlugin::lfCreateDoc)
+			{
+				int an = Cdata.indexOf("(");
+				int en = Cdata.lastIndexOf(")");
+				QString LayerNam = Cdata.mid(an+1, en-an-1);
+				LayerNam.remove("\\");
+				m_Doc->changeLayerName(currentLayer, LayerNam);
+			}
+		}
+/* End Layer commands */
+/* Start Text commands */
+		else if (command == "To")
+		{
+			ScTextStream ts2(&Cdata, QIODevice::ReadOnly);
+			ts2 >> textMode;
+			textData.clear();
+			textMatrix = QTransform();
+			maxWidth = 0;
+			tempW = 0;
+			maxHeight = 0;
+			textKern = 0;
+			startCurrentTextRange = 0;
+			endCurrentTextRange = 0;
+			textScaleH = 1000;
+			textScaleV = 1000;
+		}
+		else if (command == "Tp")
+		{
+			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+			double m1, m2, m3, m4, m5, m6;
+			gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6;
+			textMatrix = QTransform(m1, m2, m3, m4, m5, m6);
+		}
+		else if (command == "Tx") // || (command == "TX"))
+		{
+			QStringList res = getStrings(Cdata);
+			if (res.count() > 0)
+			{
+				QString tex = res[0];
+				double tempH = 0;
+				startCurrentTextRange = textData.length();
+				for (int tt = 0; tt < tex.length(); ++tt)
+				{
+					CharStyle nstyle;
+					QString ch = tex.mid(tt,1);
+					nstyle.setFont((*m_Doc->AllFonts)[textFont]);
+					nstyle.setFontSize(textSize);
+					nstyle.setFillColor(CurrColorFill);
+					nstyle.setTracking(textKern);
+					nstyle.setFillShade(100);
+					nstyle.setStrokeColor(CurrColorStroke);
+					nstyle.setStrokeShade(100);
+					nstyle.setScaleH(textScaleH);
+					nstyle.setScaleV(textScaleV);
+					nstyle.setBaselineOffset(0);
+					nstyle.setShadowXOffset(50);
+					nstyle.setShadowYOffset(-50);
+					nstyle.setOutlineWidth(10);
+					nstyle.setUnderlineOffset(-1);
+					nstyle.setUnderlineWidth(-1);
+					nstyle.setStrikethruOffset(-1);
+					nstyle.setStrikethruWidth(-1);
+					nstyle.setFeatures(StyleFlag(ScStyle_Default).featureList());
+					int pot = textData.length();
+					textData.insertChars(pot, ch);
+					textData.applyCharStyle(pot, 1, nstyle);
+					tempW += nstyle.font().realCharWidth(ch[0], nstyle.fontSize() / 10.0)+1;
+					tempH  = qMax(tempH, nstyle.font().height(nstyle.fontSize() / 10.0) + 2.0);
+					maxWidth  = qMax(tempW, maxWidth);
+					maxHeight = qMax(tempH, maxHeight);
+					if ((ch == SpecialChars::PARSEP) || (ch == SpecialChars::LINEBREAK))
+					{
+						maxHeight += nstyle.font().height(nstyle.fontSize() / 10.0);
+						tempW = 0;
+					}
+					endCurrentTextRange = pot;
+				}
+			}
+		}
+		else if (command == "Tk")
+		{
+			int flag;
+			double val;
+			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+			gVals >> flag >> val;
+			if (flag == 1)
+				val = 0;
+			double oldval = textData.charStyle(startCurrentTextRange).tracking();
+			CharStyle nstyle = textData.charStyle(startCurrentTextRange);
+			nstyle.setTracking(oldval + val);
+			textData.applyCharStyle(startCurrentTextRange, 1, nstyle);
+		}
+		else if (command == "Tc")
+		{
+			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+			gVals >> textKern;
+			textKern *= 100.0;
+		}
+		else if (command == "Tz")
+		{
+			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+			gVals >> textScaleH >> textScaleV;
+			textScaleH *= 10.0;
+			textScaleV *= 10.0;
+		}
+		else if (command == "T*")
+		{
+			CharStyle nstyle;
+			QString ch = SpecialChars::LINEBREAK;
+			nstyle.setFont((*m_Doc->AllFonts)[textFont]);
+			nstyle.setFontSize(textSize);
+			nstyle.setFillColor(CurrColorFill);
+			nstyle.setTracking(textKern);
+			nstyle.setFillShade(100);
+			nstyle.setStrokeColor(CurrColorStroke);
+			nstyle.setStrokeShade(100);
+			nstyle.setScaleH(textScaleH);
+			nstyle.setScaleV(textScaleV);
+			nstyle.setBaselineOffset(0);
+			nstyle.setShadowXOffset(50);
+			nstyle.setShadowYOffset(-50);
+			nstyle.setOutlineWidth(10);
+			nstyle.setUnderlineOffset(-1);
+			nstyle.setUnderlineWidth(-1);
+			nstyle.setStrikethruOffset(-1);
+			nstyle.setStrikethruWidth(-1);
+			nstyle.setFeatures(StyleFlag(ScStyle_Default).featureList());
+			int pot = textData.length();
+			textData.insertChars(pot, ch);
+			textData.applyCharStyle(pot, 1, nstyle);
+			maxHeight += nstyle.font().height(nstyle.fontSize() / 10.0) + 2.0;
+			tempW = 0;
+		}
+		else if (command == "Tf")
+		{
+			ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+			gVals >> textFont >> textSize;
+			textFont.remove(0, 2);
+			QString family = textFont;
+			QString ret = "";
+			family.replace( QRegExp( "'" ) , QChar( ' ' ) );
+			textFont = m_Doc->itemToolPrefs().textFont;
+			bool found = false;
+			SCFontsIterator it(PrefsManager::instance()->appPrefs.fontPrefs.AvailFonts);
+			for ( ; it.hasNext(); it.next())
+			{
+				QString fam;
+				QString fn = it.current().scName();
+				int pos = fn.indexOf(" ");
+				fam = fn.left(pos);
+				if (fam == family)
+				{
+					found = true;
+					ret = fn;
+				}
+			}
+			if (found)
+				textFont = family;
+			else
+			{
+				if (importerFlags & LoadSavePlugin::lfCreateThumbnail)
+					textFont = PrefsManager::instance()->appPrefs.itemToolPrefs.textFont;
+				else
+				{
+					if (!PrefsManager::instance()->appPrefs.fontPrefs.GFontSub.contains(family))
+					{
+						qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+						MissingFont *dia = new MissingFont(0, family, m_Doc);
+						dia->exec();
+						QString tmpf = dia->getReplacementFont();
+						delete dia;
+						qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
+						PrefsManager::instance()->appPrefs.fontPrefs.GFontSub[family] = tmpf;
+					}
+					else
+						textFont = PrefsManager::instance()->appPrefs.fontPrefs.GFontSub[family];
+				}
+			}
+			textSize *= 10.0;
+		}
+		else if (command == "TO")
+		{
+			if (textData.length() > 0)
+			{
+				if (!((textData.length() == 1) && (textData.text(0) == SpecialChars::PARSEP)))
+				{
+					QPointF pos = QPointF(textMatrix.dx(), textMatrix.dy());
+					pos += QPointF(m_Doc->currentPage()->xOffset(), -m_Doc->currentPage()->yOffset());
+					pos += QPointF(0.0, textSize / 10.0 + 2.0);
+					z = m_Doc->itemAdd(PageItem::TextFrame, PageItem::Unspecified, pos.x() - docX, docHeight - (pos.y() - docY), 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
+					ite = m_Doc->Items->at(z);
+					ite->setTextToFrameDist(0.0, 0.0, 0.0, 0.0);
+					ite->itemText.append(textData);
+					double xpos = ite->xPos();
+					double ypos = ite->yPos();
+					ite->setWidthHeight(qMax(ite->width(), maxWidth), qMax(ite->height(), maxHeight));
+					double xoffset = 0.0, yoffset = 0.0;
+					double rotation = getRotationFromMatrix(textMatrix, 0.0);
+					if (rotation != 0.0)
+					{
+						double temp = textSize / 10.0 + 2.0;
+						xoffset = sin(rotation) * temp;
+						yoffset = cos(rotation) * temp;
+					}
+					ite->setXPos(xpos + xoffset);
+					ite->setYPos(ypos + yoffset);
+					ite->setRotation(rotation * 180 / M_PI);
+					ite->SetRectFrame();
+					m_Doc->setRedrawBounding(ite);
+					ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
+					ite->setTextFlowMode(PageItem::TextFlowDisabled);
+					ite->setFillShade(CurrFillShade);
+					ite->setLineShade(CurrStrokeShade);
+					ite->setFillEvenOdd(fillRule);
+					ite->setFillTransparency(1.0 - Opacity);
+					ite->setLineTransparency(1.0 - Opacity);
+					ite->setLineEnd(CapStyle);
+					ite->setLineJoin(JoinStyle);
+					if (importerFlags & LoadSavePlugin::lfCreateDoc)
+						ite->setLocked(itemLocked);
+					if (patternMode)
+						PatternElements.append(ite);
+					else
+						Elements.append(ite);
+					if (groupStack.count() != 0)
+						groupStack.top().append(ite);
+				}
+			}
+		}
+/* End Text commands */
+/* Start special Commands */
+		else if (command == "*")
+		{
+			Coords.resize(0);
+			Coords.svgInit();
+		}
+		else if (command == "[")
+		{
+			Coords.resize(0);
+			Coords.svgInit();
+			int an = Cdata.indexOf("(");
+			int en = Cdata.lastIndexOf(")");
+			if ((an != -1) && (en != -1))
+			{
+				patternMode = true;
+				currentPatternDefName = Cdata.mid(an+1, en-an-1);
+				currentPatternDefName.remove("\\");
+				currentPatternDefName = currentPatternDefName.trimmed().simplified().replace(" ", "_");
+				QString tmpS = Cdata.mid(en+1, Cdata.size() - en);
+				ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
+				gVals >> patternX1 >> patternY1 >> patternX2 >> patternY2;
+			}
+		}
+		else if (command == ",")
+		{
+			if (Cdata.contains("/Data"))
+			{
+				dataMode = true;
+				dataString = "";
+			}
+		}
+		else if (command == ":")
+		{
+			fObjectMode = true;
+		}
+/* End special Commands */
+/* Skip everything else */
+//		else
+//			qDebug() << command;
+	}
+}
+
+void AIPlug::processGradientData(QString data)
+{
+	QString command = "";
+	QString Cdata = "";
+	QStringList da;
+	getCommands(data, da);
+	for (int a = 0; a < da.count(); a++)
+	{
+		Cdata = da[a];
+		QStringList da2 = Cdata.split(" ", QString::SkipEmptyParts);
+		command = da2[da2.count()-1];
+		if (command == "Bd")
+		{
+			QString tmpS = Cdata;
+			int an = Cdata.indexOf("(");
+			int en = Cdata.lastIndexOf(")");
+			currentGradientName = Cdata.mid(an+1, en-an-1);
+			currentGradientName.remove("\\");
+			if (da2[da2.count()-3] == "0")
+				currentGradient = VGradient(VGradient::linear);
+			else
+				currentGradient = VGradient(VGradient::radial);
+			currentGradient.clearStops();
+		}
+		else if ((command == "%_Bs") || (command == "%_BS"))
+		{
+			QString stopName = "";
+			double stop = ScCLocale::toDoubleC(da2[da2.count()-2]) / 100.0;
+			double colorShade = 100.0;
+			int colortype = da2[da2.count()-4].toInt();
+			if (colortype == 0)
+			{
+				stopName = parseColorGray(Cdata);
+				const ScColor& gradC = m_Doc->PageColors[stopName];
+				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
+			}
+			else if (colortype == 1)
+			{
+				stopName = parseColor(Cdata);
+				const ScColor& gradC = m_Doc->PageColors[stopName];
+				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
+			}
+			else if (colortype == 2)
+			{
+				stopName = parseColor(Cdata);
+				const ScColor& gradC = m_Doc->PageColors[stopName];
+				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
+			}
+			else if (colortype == 3)
+			{
+				stopName = parseCustomColor(Cdata, colorShade);
+				const ScColor& gradC = m_Doc->PageColors[stopName];
+				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, qRound(colorShade));
+			}
+			else if (colortype == 4)
+			{
+				stopName = parseCustomColorX(Cdata, colorShade, "0");
+				const ScColor& gradC = m_Doc->PageColors[stopName];
+				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, qRound(colorShade));
+			}
+			else if (colortype == 6)
+			{
+				stopName = parseColor(Cdata);
+				const ScColor& gradC = m_Doc->PageColors[stopName];
+				currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), stop, 0.5, 1.0, stopName, 100 );
+			}
+		}
+		else if (command == "BD")
+		{
+			m_gradients.insert(currentGradientName, currentGradient);
+			if (m_Doc->addGradient(currentGradientName, currentGradient))
+				importedGradients.append(currentGradientName);
+			currentGradient = VGradient(VGradient::linear);
+			currentGradient.clearStops();
+			currentGradient.setRepeatMethod( VGradient::none );
+			currentGradientName = "";
+		}
+	}
+}
+
+void AIPlug::processPattern(QDataStream &ts)
+{
+	QString tmp = "";
+	QString tmpData = "";
+	while (!ts.atEnd())
+	{
+		tmp = removeAIPrefix(readLinefromDataStream(ts));
+		if (importerFlags & LoadSavePlugin::lfKeepPatterns)
+		{
+			if (tmp.startsWith("%_"))
+				tmp.remove(0, 2);
+		}
+		if (patternMode)
+		{
+			if (tmp == "EndPattern")
+			{
+				tmpSel->clear();
+				if (PatternElements.count() > 0)
+				{
+					for (int dre = 0; dre < PatternElements.count(); ++dre)
+					{
+						tmpSel->addItem(PatternElements.at(dre), true);
+						if (groupStack.count() != 0)
+							groupStack.top().removeAll(PatternElements.at(dre));
+					}
+					if (PatternElements.count() > 1)
+						m_Doc->itemSelection_GroupObjects(false, false, tmpSel);
+					if ((tmpSel->width() > 1) && (tmpSel->height() > 1))
+					{
+						ScPattern pat = ScPattern();
+						pat.setDoc(m_Doc);
+						PageItem* currItem = tmpSel->itemAt(0);
+						currItem->setItemName(currentPatternDefName);
+						m_Doc->DoDrawing = true;
+						QImage tmpImg = currItem->DrawObj_toImage(qMax(qRound(patternX2 - patternX1), qRound(patternY2 - patternY1)));
+						if (!tmpImg.isNull())
+						{
+							QImage retImg = QImage(qRound(patternX2 - patternX1), qRound(patternY2 - patternY1), QImage::Format_ARGB32_Premultiplied);
+							retImg.fill( qRgba(255, 255, 255, 0) );
+							QPainter p;
+							p.begin(&retImg);
+							if (PatternElements.count() > 1)
+								p.drawImage(qRound(-patternX1), qRound(-patternY1), tmpImg);
+							else
+								p.drawImage(0, 0, tmpImg);
+							p.end();
+							pat.pattern = retImg;
+		//					pat.pattern = currItem->DrawObj_toImage();
+							m_Doc->DoDrawing = false;
+							//			pat.width = currItem->gWidth;
+							//			pat.height = currItem->gHeight;
+							pat.width = patternX2 - patternX1;
+							pat.height = patternY2 - patternY1;
+							pat.xoffset = -patternX1;
+							pat.yoffset = -patternY1;
+							for (int as = 0; as < tmpSel->count(); ++as)
+							{
+								PageItem* Neu = tmpSel->itemAt(as);
+								Neu->moveBy(-patternX1, -patternY1, true);
+								Neu->gXpos -= patternX1;
+								Neu->gYpos -= patternY1;
+								pat.items.append(Neu);
+							}
+							m_Doc->addPattern(currentPatternDefName, pat);
+							importedPatterns.append(currentPatternDefName);
+						}
+					}
+					m_Doc->itemSelection_DeleteItem(tmpSel);
+				}
+				PatternElements.clear();
+				currentPatternDefName = "";
+				break;
+			}
+			else if (tmp.startsWith("Tile"))
+				continue;
+			else if (tmp.contains(") @"))
+			{
+				tmpData += tmp;
+				tmpData.remove(") @");
+				processData(tmpData);
+				tmpData = "";
+			}
+			else if (tmp.contains(") &"))
+			{
+				tmpData += tmp;
+				tmpData.remove(") &");
+				processData(tmpData);
+				tmpData = "";
+			}
+			else if (tmp.startsWith("("))
+			{
+				if (tmp.startsWith("("))
+					tmp.remove(0, 1);
+				tmpData += " "+tmp;
+			}
+			else
+				processData(tmp);
+		}
+		else if (tmp == "EndPattern")
+		{
+			PatternElements.clear();
+			currentPatternDefName = "";
+			break;
+		}
+		else if (tmp.contains("BeginRaster") && (tmp.startsWith("%")))
+		{
+			while (!ts.atEnd())
+			{
+				tmp = readLinefromDataStream(ts);
+				if (tmp.contains("EndRaster"))
+					break;
+				if(progressDialog)
+				{
+					progressDialog->setProgress("GI", ts.device()->pos());
+					qApp->processEvents();
+				}
+			}
+		}
+		else
+		{
+			Coords.resize(0);
+			Coords.svgInit();
+			int an = tmp.indexOf("(");
+			int en = tmp.lastIndexOf(")");
+			if ((an != -1) && (en != -1))
+			{
+				patternMode = true;
+				currentPatternDefName = tmp.mid(an+1, en-an-1);
+				currentPatternDefName.remove("\\");
+				currentPatternDefName = currentPatternDefName.trimmed().simplified().replace(" ", "_");
+				QString tmpS = tmp.mid(en+1, tmp.size() - en);
+				ScTextStream gVals(&tmpS, QIODevice::ReadOnly);
+				gVals >> patternX1 >> patternY1 >> patternX2 >> patternY2;
+			}
+		}
+	//		processData(tmp);
+	}
+	patternMode = false;
+}
+
+void AIPlug::processSymbol(QDataStream &ts, bool sym)
+{
+	QString tmp = "";
+	QString tmpData = "";
+	while (!ts.atEnd())
+	{
+		tmp = removeAIPrefix(readLinefromDataStream(ts));
+		if (!patternMode)
+		{
+			int an = tmp.indexOf("(");
+			int en = tmp.lastIndexOf(")");
+			if ((an != -1) && (en != -1))
+			{
+				patternMode = true;
+				currentPatternDefName = tmp.mid(an+1, en-an-1);
+				currentPatternDefName.remove("\\");
+				if (sym)
+					currentPatternDefName = "S_"+currentPatternDefName.trimmed().simplified().replace(" ", "_");
+				else
+					currentPatternDefName = currentPatternDefName.trimmed().simplified().replace(" ", "_");
+			}
+		}
+		else if ((tmp == "EndSymbol") || (tmp == "EndBrushPattern"))
+		{
+			tmpSel->clear();
+			if (PatternElements.count() > 0)
+			{
+				for (int dre = 0; dre < PatternElements.count(); ++dre)
+				{
+					tmpSel->addItem(PatternElements.at(dre), true);
+					groupStack.top().removeAll(PatternElements.at(dre));
+				}
+				if (PatternElements.count() > 1)
+					m_Doc->itemSelection_GroupObjects(false, false, tmpSel);
+				if ((tmpSel->width() > 1) && (tmpSel->height() > 1))
+				{
+					ScPattern pat = ScPattern();
+					pat.setDoc(m_Doc);
+					PageItem* currItem = tmpSel->itemAt(0);
+					currItem->setItemName(currentPatternDefName);
+					m_Doc->DoDrawing = true;
+					pat.pattern = currItem->DrawObj_toImage(qMax(tmpSel->width(), tmpSel->height()));
+					if (!pat.pattern.isNull())
+					{
+						pat.width = currItem->gWidth;
+						pat.height = currItem->gHeight;
+						m_Doc->DoDrawing = false;
+						for (int as = 0; as < tmpSel->count(); ++as)
+						{
+							PageItem* Neu = tmpSel->itemAt(as);
+							pat.items.append(Neu);
+						}
+						importedPatterns.append(currentPatternDefName);
+						importedSymbols.insert(currentPatternDefName, QPointF(currItem->xPos(), currItem->yPos()));
+						m_Doc->addPattern(currentPatternDefName, pat);
+					}
+				}
+				m_Doc->itemSelection_DeleteItem(tmpSel);
+			}
+			PatternElements.clear();
+			currentPatternDefName = "";
+			break;
+		}
+		else if (tmp.contains("BeginRaster") && (tmp.startsWith("%")))
+		{
+			while (!ts.atEnd())
+			{
+				tmp = readLinefromDataStream(ts);
+				if (tmp.contains("EndRaster"))
+					break;
+				if(progressDialog)
+				{
+					progressDialog->setProgress("GI", ts.device()->pos());
+					qApp->processEvents();
+				}
+			}
+		}
+		else
+		{
+			processData(tmp);
+		}
+	}
+	patternMode = false;
+}
+
+void AIPlug::processRaster(QDataStream &ts)
+{
+	double m1, m2, m3, m4, m5, m6, x1, y1, x2, y2, dummy;
+	int w, h, type, alpha, bin, bits;
+	QString tmp = "";
+	QString cumulated = "";
+	while (!ts.atEnd())
+	{
+		tmp = readLinefromDataStream(ts);
+		if (tmp.startsWith("%"))
+			break;
+		tmp.remove("[");
+		tmp.remove("]");
+		if (!tmp.isEmpty())
+			cumulated += " " + tmp;
+	}
+	QString Cdata = "";
+	QStringList da;
+	getCommands(cumulated, da);
+	Cdata = da[da.count()-1];
+	ScTextStream gVals(&Cdata, QIODevice::ReadOnly);
+	gVals >> m1 >> m2 >> m3 >> m4 >> m5 >> m6 >> x1 >> y1 >> x2 >> y2 >> w >> h >> bits >> type >> alpha >> dummy >> bin;
+//	qDebug() << QString("Matrix: %1 %2 %3 %4 %5 %6").arg(m1).arg(m2).arg(m3).arg(m4).arg(m5).arg(m6);
+//	qDebug() << QString("Bounds: %1 %2 %3 %4").arg(x1).arg(y1).arg(x2).arg(y2);
+//	qDebug() << QString("Size: %1 %2").arg(w).arg(h);
+//	qDebug() << QString("Bits: %1").arg(bits);
+//	qDebug() << QString("Typ: %1").arg(type);
+//	qDebug() << QString("Alpha-Channels: %1").arg(alpha);
+//	qDebug() << QString("Encoding: %1").arg(bin);
+	uint dataSize = w * h * (type + alpha);
+	uint alphaData = w * h * type;
+	bool cmyk = false;
+	if (type == 4)
+		cmyk = true;
+	if (tmp.startsWith("%%BeginData"))
+	{
+		QString dummyS;
+		ScTextStream gVals2(&tmp, QIODevice::ReadOnly);
+		tmp = readLinefromDataStream(ts);
+	}
+	QByteArray psdata;
+	psdata.resize(dataSize);
+	RawImage m_image;
+	if (type == 4)
+	{
+		if (alpha > 0)
+			m_image.create(w, 1, 5);
+		else
+			m_image.create(w, 1, 4);
+	}
+	else
+	{
+		if (alpha > 0)
+			m_image.create(w, 1, 4);
+		else
+			m_image.create(w, 1, 3);
+	}
+	bool first = false;
+	if (bin == 0) // 0 = ASCII encoded data
+	{
+		uint dataPointer = 0;
+		while (!ts.atEnd())
+		{
+			if (first)
+				tmp = readLinefromDataStream(ts);
+			first = true;
+			if (tmp.startsWith("%AI5_EndRaster"))
+				break;
+			for (int a = 1; a < tmp.length(); a += 2)
+			{
+				bool ok;
+				ushort data = tmp.mid(a, 2).toUShort(&ok, 16);
+				psdata[dataPointer++] = data;
+			}
+		}
+	}
+	else
+	{
+		psdata.resize(dataSize);
+		ts.readRawData(psdata.data(), dataSize);
+	}
+	QTransform imgMatrix = QTransform(m1, m2, m3, m4, m5, m6);
+	QPointF pos = QPointF(imgMatrix.dx(), imgMatrix.dy());
+	pos += QPointF(m_Doc->currentPage()->xOffset(), -m_Doc->currentPage()->yOffset());
+	pos += QPointF(baseX, -baseY);
+	int z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, pos.x() - docX, docHeight - (pos.y() - docY), 10, 10, 0, CurrColorFill, CurrColorStroke, true);
+	PageItem* ite = m_Doc->Items->at(z);
+	ite->setWidthHeight(fabs(w * m1), fabs(h * m4));
+	double rotation = getRotationFromMatrix(imgMatrix, 0.0);
+	ite->setRotation(rotation * 180 / M_PI);
+	ite->SetRectFrame();
+	m_Doc->setRedrawBounding(ite);
+	ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
+	ite->setTextFlowMode(PageItem::TextFlowDisabled);
+	ite->setFillShade(CurrFillShade);
+	ite->setLineShade(CurrStrokeShade);
+	ite->setFillEvenOdd(fillRule);
+	ite->setFillTransparency(1.0 - Opacity);
+	ite->setLineTransparency(1.0 - Opacity);
+#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 4))
+	ite->setFillBlendmode(blendMode);
+	ite->setLineBlendmode(blendMode);
+#endif
+	ite->setLineEnd(CapStyle);
+	ite->setLineJoin(JoinStyle);
+	uchar *p;
+	uint yCount = 0;
+	quint16 eTag = EXTRASAMPLE_UNASSALPHA;
+	ite->tempImageFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_ai_XXXXXX.tif");
+	ite->tempImageFile->open();
+	QString imgName = getLongPathName(ite->tempImageFile->fileName());
+	ite->tempImageFile->close();
+	ite->isInlineImage = true;
+	TIFF* tif = TIFFOpen(imgName.toLocal8Bit().data(), "w");
+	if (tif)
+	{
+		TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, w);
+		TIFFSetField(tif, TIFFTAG_IMAGELENGTH, h);
+		TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
+		TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, m_image.channels());
+		if (alpha == 1)
+			TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, 1, &eTag);
+		TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+		if (type == 4)
+			TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
+		else
+			TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
+		TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
+		for (int y = 0; y < h; ++y)
+		{
+			p = m_image.scanLine( 0 );
+			for (int xh = 0; xh < m_image.width(); ++xh )
+			{
+				p[0] = psdata[yCount++];
+				if (type > 1)
+				{
+					p[1] = psdata[yCount++];
+					p[2] = psdata[yCount++];
+					if (type == 4)
+						p[3] = psdata[yCount++];
+				}
+				else
+				{
+					p[1] = p[0];
+					p[2] = p[0];
+				}
+				if (alpha == 1)
+				{
+					if (type == 4)
+						p[4] = psdata[alphaData++];
+					else
+						p[3] = psdata[alphaData++];
+				}
+				p += m_image.channels();
+			}
+			TIFFWriteScanline(tif, m_image.scanLine(0), y);
+		}
+		TIFFClose(tif);
+	}
+	m_Doc->LoadPict(imgName, z);
+	if (ite->PictureIsAvailable)
+		ite->setImageXYScale(ite->width() / ite->pixm.width(), ite->height() / ite->pixm.height());
+	if (importerFlags & LoadSavePlugin::lfCreateDoc)
+		ite->setLocked(itemLocked);
+	if (patternMode)
+		PatternElements.append(ite);
+	else
+		Elements.append(ite);
+	if (groupStack.count() != 0)
+		groupStack.top().append(ite);
+}
+
+void AIPlug::processComment(QDataStream &ts, QString comment)
+{
+	QString tmp = removeAIPrefix(comment);
+	if (tmp.startsWith("Begin_NonPrinting"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("BeginGradient"))
+			{
+				while (!ts.atEnd())
+				{
+					tmp = removeAIPrefix(readLinefromDataStream(ts));
+					if (tmp.startsWith("EndGradient"))
+						break;
+					else
+						processGradientData(tmp);
+				}
+			}
+			if (tmp.startsWith("BeginPattern:"))
+				processPattern(ts);
+			if (tmp == "BeginSymbol")
+				processSymbol(ts, true);
+			if (tmp == "BeginBrushPattern")
+				processSymbol(ts, false);
+			if (tmp.startsWith("End_NonPrinting"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginPattern:"))
+		processPattern(ts);
+	else if (tmp.startsWith("BeginGradient"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndGradient"))
+				break;
+			else
+				processGradientData(tmp);
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginPalette"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndPalette"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp == "BeginSymbol")
+		processSymbol(ts, true);
+	else if (tmp == "BeginBrushPattern")
+		processSymbol(ts, false);
+/*	{
+		while (!ts.atEnd())
+		{
+			processSymbol(ts);
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndSymbol"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	} */
+	else if (tmp.startsWith("BeginDocumentData"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndDocumentData"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginTextDocument"))
+	{
+		QString dataStringT = "";
+		tmp = removeAIPrefix(readLinefromDataStream(ts));
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndTextDocument"))
+			{
+			//	QByteArray fData;
+			//	decodeA85(fData, dataStringT);
+				break;
+			}
+		//	else
+		//		dataStringT += tmp.mid(1);
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("%%BeginProlog"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("%%EndProlog"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("%%BeginData"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("%%EndData"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("%%BeginCrops"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("%%EndCrops"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginRaster"))
+	{
+		processRaster(ts);
+		if(progressDialog)
+		{
+			progressDialog->setProgress("GI", ts.device()->pos());
+			qApp->processEvents();
+		}
+	}
+	else if (tmp.contains("BeginRaster") && (tmp.startsWith("%")))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = readLinefromDataStream(ts);
+			if (tmp.contains("EndRaster"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginSVGFilter"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndSVGFilter"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginArtStyles"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndArtStyles"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginPluginObject"))
+	{
+		while (!ts.atEnd())
+		{
+			tmp = removeAIPrefix(readLinefromDataStream(ts));
+			if (tmp.startsWith("EndPluginObject"))
+				break;
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+	else if (tmp.startsWith("BeginLayer"))
+	{
+		while (!ts.atEnd())
+		{
+			QString rl = readLinefromDataStream(ts);
+			tmp = removeAIPrefix(rl);
+			if (tmp.startsWith("BeginRaster"))
+			{
+				processRaster(ts);
+				continue;
+			}
+			if (tmp.startsWith("EndLayer"))
+				break;
+			else
+				processData(rl);
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+	}
+}
+
+bool AIPlug::convert(QString fn)
+{
+	QString tmp;
+	LineW = 1.0;
+	Opacity = 1.0;
+	blendMode = 0;
+	CurrColorFill = "White";
+	CurrFillShade = 100.0;
+	CurrColorStroke = "Black";
+	CurrStrokeShade = 100.0;
+	JoinStyle = Qt::MiterJoin;
+	CapStyle = Qt::FlatCap;
+	DashPattern.clear();
+	DashOffset = 0.0;
+	fillRule = false;
+	FirstU = false;
+	WasU = false;
+	firstLayer = true;
+	patternMode = false;
+	symbolMode = false;
+	meshMode = false;
+	dataMode = false;
+	fObjectMode = false;
+	dataString = "";
+	itemLocked = false;
+	patternX1 = 0.0;
+	patternY1 = 0.0;
+	patternX2 = 0.0;
+	patternY2 = 0.0;
+	Coords.resize(0);
+	Coords.svgInit();
+	clipCoords.resize(0);
+	clipCoords.svgInit();
+	currentSpecialPath.resize(0);
+	currentSpecialPath.svgInit();
+	currentPoint = FPoint(0.0, 0.0);
+	currentLayer = 0;
+	currentGradient = VGradient(VGradient::linear);
+	currentGradient.clearStops();
+	currentGradient.setRepeatMethod( VGradient::none );
+	currentGradientName = "";
+	currentGradientMatrix = QTransform();
+	currentGradientOrigin = QPointF(0.0, 0.0);
+	currentGradientAngle = 0.0;
+	currentGradientLenght = 1.0;
+	currentPatternName = "";
+	currentPatternX = 0.0;
+	currentPatternY = 0.0;
+	currentPatternXScale = 1.0;
+	currentPatternYScale = 1.0;
+	currentPatternRotation = 0.0;
+	currentStrokePatternName = "";
+	currentStrokePatternX = 0.0;
+	currentStrokePatternY = 0.0;
+	currentStrokePatternXScale = 1.0;
+	currentStrokePatternYScale = 1.0;
+	currentStrokePatternRotation = 0.0;
+	QList<PageItem*> gElements;
+	groupStack.push(gElements);
+	clipStack.push(clipCoords);
+	commandList << "m" << "l" << "L" << "c" << "C" << "v" << "V" << "y" << "Y";		// Path construction
+	commandList << "b" << "B" << "f" << "F" << "s" << "S" << "*u" << "*U";			// Object creation
+	commandList << "u" << "U" << "W" << "q" << "Q";									// Object creation
+	commandList << "A" << "w" << "j" << "J" << "Xy" << "XR";						// Graphic state
+	commandList << "k" << "K" << "Xa" << "XA" << "x" << "X" << "XX" << "Xx";		// Color commands
+	commandList << "Xk" << "g" << "G" << "p" << "P";								// Color commands
+	commandList << "Ln" << "Lb" << "LB";											// Layer commands
+	commandList << "Bd" << "BD" << "%_Bs" << "Bg" << "Bb" << "BB" << "Bm" << "Xm";	// Gradient commands
+	commandList << "To" << "TO" << "Tf" << "Tp" << "Tx" << "TX" << "T*" << "Tk";	// Text commands
+	commandList << "Tc" << "Tz";													// Text commands
+	commandList << "XI" << "XG" << "Xh";											// Image commands
+	commandList << "n" << "N" << "*" << "[";										// Special commands
+	commandList << "X!" << "X#";													// Mesh commands
+	commandList << "M" << "d" << "D" << "E";										// unimplemented
+	commandList << "h" << "H" << "i" << "I" << "Np" << "O";							// unimplemented
+	commandList << "P" << "R";														// unimplemented
+	commandList << "XI" << "XF" << "XG" << "XT" << "Z" << "`" << "~" << "_" << "@";	// unimplemented
+	commandList << "&" << "*w" << "*W" << "Ap" << "Ar";								// unimplemented
+	if(progressDialog)
+	{
+		progressDialog->setOverallProgress(2);
+		progressDialog->setLabel("GI", tr("Generating Items"));
+		qApp->processEvents();
+	}
+	QFile f(fn);
+	if (f.open(QIODevice::ReadOnly))
+	{
+		int fSize = (int) f.size();
+		if (progressDialog)
+		{
+			progressDialog->setTotalSteps("GI", fSize);
+			qApp->processEvents();
+		}
+		QDataStream ts(&f);
+		while (!ts.atEnd())
+		{
+			tmp = readLinefromDataStream(ts);
+			if (tmp.startsWith("%"))
+				processComment(ts, tmp);
+			else
+				processData(tmp);
+			if(progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+		f.close();
+	}
+	if (progressDialog)
+		progressDialog->close();
+	return true;
+}

Modified: trunk/Scribus/scribus/plugins/import/wmf/wmfimport.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/plugins/import/wmf/wmfimport.cpp
==============================================================================
--- trunk/Scribus/scribus/plugins/import/wmf/wmfimport.cpp (original)
+++ trunk/Scribus/scribus/plugins/import/wmf/wmfimport.cpp Mon Jun 20 20:43:58 2011
@@ -1,1445 +1,1445 @@
-/*
-For general Scribus (>=1.3.2) copyright and licensing information please refer
-to the COPYING file provided with the program. Following this notice may exist
-a copyright and/or license notice that predates the release of Scribus 1.3.2
-for which a new license (GPL+exception) is in place.
-*/
-
-/* Code inspired by KOffice libwmf and adapted for Scribus by Jean Ghali */
-
-#include "scconfig.h"
-#include "wmfimport.h"
-
-#include <QCursor>
-#include <QDrag>
-#include <QBuffer>
-#include <QDataStream>
-#include <QFile>
-#include <QMimeData>
-#include <QPainterPath>
-#include <QRegExp>
-
-#include "commonstrings.h"
-#include "scribus.h"
-#include "scribusXml.h"
-#include "fonts/scfontmetrics.h"
-#include "fpointarray.h"
-#include "ui/scmwmenumanager.h"
-#include "prefsmanager.h"
-#include "pageitem.h"
-#include "prefsfile.h"
-#include "scmimedata.h"
-#include "scraction.h"
-#include "scribuscore.h"
-#include "scribusdoc.h"
-#include "selection.h"
-#include "ui/customfdialog.h"
-#include "ui/propertiespalette.h"
-#include "undomanager.h"
-#include "loadsaveplugin.h"
-#include "util.h"
-#include "util_icon.h"
-#include "util_math.h"
-
-
-using namespace std;
-
-#include "wmfstruct.h"
-#include "wmfcmd.h"
-#include "wmfcontext.h"
-#include "wmfhandle.h"
-#include "metafuncs.h"
-
-#define WMFIMPORT_DEBUG 0
-#define MAX_OBJHANDLE   128
-
-#define ANSI_CHARSET			0		// ANSI charset (Windows-1252)
-#define DEFAULT_CHARSET			1
-#define SYMBOL_CHARSET			2
-#define MAC_CHARSET				77
-#define SHIFTJIS_CHARSET		128		// Shift JIS charset    (Windows-932)
-#define HANGEUL_CHARSET			129		// Hangeul charset      (Windows-949)
-#define JOHAB_CHARSET			130		// Johab charset        (Windows-1361)
-#define GB2312_CHARSET			134		// GB2312 charset       (Windows-936)
-#define CHINESEBIG5_CHARSET		136		// Chinese Big5 charset (Windows-950)
-#define GREEK_CHARSET			161		// Greek charset        (Windows-1253)
-#define TURKISH_CHARSET			162		// Turkish charset      (Windows-1254)
-#define VIETNAMESE_CHARSET		163		// Vietnamese charset   (Windows-1258)
-#define HEBREW_CHARSET			177		// Hebrew charset       (Windows-1255)
-#define ARABIC_CHARSET			178		// Arabic charset       (Windows-1256)
-#define BALTIC_CHARSET			186		// Baltic charset       (Windows-1257)
-#define RUSSIAN_CHARSET			204		// Cyrillic charset     (Windows-1251)
-#define THAI_CHARSET			222		// Thai charset         (Windows-874)
-#define EASTEUROPE_CHARSET		238		// Eastern european charset (Windows-1250)
-#define OEM_CHARSET				255
-
-/* Symbol to unicode conversion table copied from http://root.cern.ch/viewvc/trunk/qt/src/TQtSymbolCodec.cxx
-This code is placed under GPL licence (http://root.cern.ch/viewvc/trunk/LICENSE) */
-static const ushort greek_symbol_to_unicode[64] = {
-//
-//  upper case letters:
-//  ----------------
-//   Alpha   Beta     Chi   Delta   Epsilon   Phi    Gamma    Eta
-	0x0391, 0x0392, 0x03A7, 0x0394, 0x0395, 0x03A6, 0x0393, 0x0397,
-//   Iota   Theta(S) Kappa  Lambda    Mu      Nu    Omicron   Pi
-	0x0399, 0x03D1, 0x039A, 0x039B, 0x039C, 0x039D, 0x039F, 0x03A0,
-//  Theta    Rho    Sigma    Tau    Upsilon Stigma   Omega     Xi
-	0x0398, 0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03DB, 0x03A9, 0x039E,
-//   Psi     Zeta   Sigma    Tau    Upsilon  ????   Omega     Xi
-	0x03A8, 0x0396, 0x03EA, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD,
-//
-//  lower case letters:
-//  ----------------
-//   Alpha   Beta    Chi    Delta   Epsilon   Phi    Gamma    Eta
-	0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x03B5, 0x03D5, 0x03B3, 0x03B7,
-//   Iota   Phi (2) Kappa   Lambda    Mu      Nu    Omicron   Pi
-	0x03B9, 0x03C6, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, 0x03C0,
-//  Theta    Rho    Sigma    Tau    Upsilon OmegaPi Omega     Xi
-	0x03B8, 0x03C1, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03B9, 0x03BE,
-//   Psi     Zeta   Sigma    Tau    Upsilon  ????   Omega     Xi
-	0x03C8, 0x03B6, 0x03EA, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
-};
-
-/* Symbol to unicode conversion table copied from http://root.cern.ch/viewvc/trunk/qt/src/TQtSymbolCodec.cxx
-This code is placed under GPL licence (http://root.cern.ch/viewvc/trunk/LICENSE) */
-static const ushort symbol_to_unicode[96] = {
-//
-//  upper case letters:
-//  ----------------
-// UPSILON  NUMBER  LessEq   Div   INFINITY ???????  CLUB   DIAMOND     
-	0x03D2, 0x0374, 0x2264, 0x2215, 0x221E, 0x0395, 0x2663, 0x2666,
-//   HEART  SPADE   <--->   <---             -->             RING
-	0x2665, 0x2660, 0x2194, 0x2190, 0x2191, 0x2192, 0x2193, 0x2218,
-//  Theta    Rho    Great    ????   Propor  diff    bullet   ????
-	0x0398, 0x03A1, 0x2265, 0x03A4, 0x221D, 0x2202, 0x2219, 0x03A8,
-//   NonEq  Ident    ????   ellips   div     minus  ?????   aleph
-	0x2260, 0x2261, 0xFFFD, 0x22EF, 0x2223, 0x2212, 0xFFFD, 0xFFFD,
-//
-//  lower case letters:
-//  ----------------
-//   Alpha   Beta    Chi    Delta   Epsilon   Phi    Gamma    Eta
-	0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x03B5, 0x03D5, 0x03B3, 0x03B7,
-//   Iota   Phi (2) Kappa   Lambda    Mu      Nu    Omicron   Pi
-	0x03B9, 0x03C6, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, 0x03C0,
-//  Theta    Rho    Sigma    Tau    Upsilon OmegaPi Omega     Xi
-	0x03B8, 0x03C1, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03B9, 0x03BE,
-//   Psi     Zeta   arrow    Tau    Upsilon  ????   Omega     Xi
-	0x03C8, 0x03B6, 0x21D4, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD,
-//  lower case letters:
-//  ----------------
-//   Alpha   Beta    Chi    Delta   Sigma     Phi    Gamma    Eta
-	0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x2211, 0x03D5, 0x03B3, 0x03B7,
-//   Iota   Phi (2) Kappa   Lambda    Mu      Nu    Omicron   Pi
-	0x03B9, 0x03C6, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, 0x03C0,
-//  Theta   Integr  Sigma    Tau    Upsilon OmegaPi Omega     Xi
-	0x03B8, 0x222b, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03B9, 0x03BE,
-//   Psi     Zeta   Sigma    Tau    Upsilon  ????   Omega     Xi
-	0x03C8, 0x03B6, 0x03EA, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
-};
-
-WMFImport::WMFImport( ScribusDoc* doc, int flags )
-{	
-	m_tmpSel = new Selection(this, false);
-	m_Doc    = doc;
-	unsupported = false;
-	importFailed = false;
-	importCanceled = true;
-	importedColors.clear();
-	m_docDesc = "";
-	m_docTitle = "";
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-
-	m_Valid        = false;
-	m_ObjHandleTab = NULL;
-	m_Dpi          = 1440;
-}
-
-WMFImport::~WMFImport()
-{
-	qDeleteAll(m_commands);
-	m_commands.clear();
-	if ( m_tmpSel) delete m_tmpSel;
-	if ( m_ObjHandleTab ) 
-	{
-		for (int i = 0; i < MAX_OBJHANDLE; ++i)
-		{
-			if (m_ObjHandleTab[i])
-				delete m_ObjHandleTab[i];
-		}
-		delete[] m_ObjHandleTab;
-	}
-}
-
-QString WMFImport::importColor(const QColor& color)
-{
-	ScColor tmp;
-	tmp.fromQColor(color);
-	tmp.setSpotColor(false);
-	tmp.setRegistrationColor(false);
-	QString pNam = "FromWMF"+color.name();
-	QString fNam = m_Doc->PageColors.tryAddColor(pNam, tmp);
-	if (fNam == pNam)
-		importedColors.append(pNam);
-	return fNam;
-}
-
-QColor WMFImport::colorFromParam( short* params )
-{
-	unsigned int colorRef;
-	int red, green, blue;
-
-	colorRef = toDWord( params ) & 0xffffff;
-	red      = colorRef & 255;
-	green    = ( colorRef>>8 ) & 255;
-	blue     = ( colorRef>>16 ) & 255;
-
-	return QColor( red, green, blue );
-}
-
-QTextCodec* WMFImport::codecFromCharset( int charset )
-{
-	QTextCodec* codec = NULL;
-	if (charset == DEFAULT_CHARSET || charset == OEM_CHARSET)
-		codec = QTextCodec::codecForLocale();
-	else if (charset == ANSI_CHARSET)
-		codec = QTextCodec::codecForName("windows-1252");
-	/*else if (charset == SYMBOL_CHARSET)
-		codec = QTextCodec::codecForLocale();// Not supported yet*/
-	else if (charset == MAC_CHARSET)
-		codec = QTextCodec::codecForName("Apple Roman");
-	else if (charset == SHIFTJIS_CHARSET)
-		codec = QTextCodec::codecForName("Shift-JIS");
-	else if (charset == HANGEUL_CHARSET)
-		codec = QTextCodec::codecForName("CP949");
-	else if (charset == GB2312_CHARSET)
-		codec = QTextCodec::codecForName("CP936");
-	else if (charset == CHINESEBIG5_CHARSET)
-		codec = QTextCodec::codecForName("Big5");
-	else if (charset == GREEK_CHARSET)
-		codec = QTextCodec::codecForName("windows-1253");
-	else if (charset == TURKISH_CHARSET)
-		codec = QTextCodec::codecForName("windows-1254");
-	else if (charset == VIETNAMESE_CHARSET)
-		codec = QTextCodec::codecForName("windows-1258");
-	else if (charset == HEBREW_CHARSET)
-		codec = QTextCodec::codecForName("windows-1255");
-	else if (charset == ARABIC_CHARSET)
-		codec = QTextCodec::codecForName("windows-1256");
-	else if (charset == BALTIC_CHARSET)
-		codec = QTextCodec::codecForName("windows-1257");
-	else if (charset == RUSSIAN_CHARSET)
-		codec = QTextCodec::codecForName("windows-1251");
-	else if (charset == THAI_CHARSET)
-		codec = QTextCodec::codecForName("CP874");
-	else if (charset == EASTEUROPE_CHARSET)
-		codec = QTextCodec::codecForName("windows-1250");
-	return codec;
-}
-
-QString WMFImport::symbolToUnicode ( const QByteArray& chars )
-{
-	/*Code under GPL licence (http://root.cern.ch/viewvc/trunk/LICENSE)
-	taken from http://root.cern.ch/viewvc/trunk/qt/src/TQtSymbolCodec.cxx*/
-	QString r;
-	const unsigned char * c = (const unsigned char *) chars.data();
-	
-	if( chars.size() == 0 ) return r;
-	
-	for (int i = 0; i < chars.size(); ++i) 
-	{
-		if ( 64 < c[i] && c[i] <= 64+32 )
-			r.append( QChar(greek_symbol_to_unicode[c[i]-65]) );
-		else if (64+32+1 <= c[i] && c[i] < 64+32+32+1)
-			r.append( QChar(greek_symbol_to_unicode[c[i]-65-32]+32) );
-		else if (161 <= c[i] )
-			r.append(  QChar(symbol_to_unicode[c[i]-161]) );
-		else
-			r.append( QChar(c[i]) );
-	}
-	return r;
-}
-
-FPointArray WMFImport::pointsFromParam( short num, short* params )
-{
-	FPointArray points;
-	points.resize( num );
-
-	for ( int i = 0; i < num; i++, params += 2 )
-		points.setPoint( i, params[ 0 ], params[ 1 ] );
-
-	return points;
-}
-
-FPointArray WMFImport::pointsToPolyline( const FPointArray& points, bool closePath )
-{
-	bool bFirst = true;
-	double x = 0.0, y = 0.0;
-	FPointArray polyline;
-	polyline.svgInit();
-	for( uint i = 0; i < points.size(); ++i )
-	{
-		FPoint point = points.point(i);
-		if( bFirst )
-		{
-			x = point.x();
-			y = point.y();
-			polyline.svgMoveTo(x, y);
-			bFirst = false;
-		}
-		else
-		{
-			x = point.x();
-			y = point.y();
-			polyline.svgLineTo(x, y);
-		}
-	}
-	if (closePath && (points.size() > 4))
-		polyline.svgClosePath();
-	return polyline;
-}
-
-void WMFImport::pointsToAngle( double xStart, double yStart, double xEnd, double yEnd, double& angleStart, double& angleLength )
-{
-	double aStart  = atan2( yStart,  xStart );
-	double aLength = atan2( yEnd, xEnd ) - aStart;
-
-	angleStart  = (int)(aStart * 180.0 / 3.14166);
-	angleLength = (int)(aLength * 180.0 / 3.14166);
-	if ( angleLength < 0 ) angleLength = 360.0 + angleLength;
-}
-
-QImage WMFImport::readThumbnail(QString fname)
-{
-	if (!loadWMF(fname))
-	{
-		importFailed = true;
-		return QImage();
-	}
-	QString CurDirP = QDir::currentPath();
-	QFileInfo efp(fname);
-	QDir::setCurrent(efp.path());
-	double scale  = (m_Dpi > 0) ? 72.0 / m_Dpi : 0.05;
-	double width  = m_BBox.width() * scale;
-	double height = m_BBox.height() * scale;
-	m_Doc = new ScribusDoc();
-	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
-	m_Doc->setPage(width, height, 0, 0, 0, 0, 0, 0, false, false);
-	m_Doc->addPage(0);
-	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	m_Doc->scMW()->setScriptRunning(true);
-	m_Doc->PageColors.ensureDefaultColors();
-	QList<PageItem*> Elements = parseWmfCommands();
-	m_tmpSel->clear();
-	QImage tmpImage = QImage();
-	if (Elements.count() > 0)
-	{
-		if (Elements.count() > 1)
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->m_Selection->delaySignalsOn();
-		for (int dre=0; dre<Elements.count(); ++dre)
-		{
-			m_tmpSel->addItem(Elements.at(dre), true);
-		}
-		m_tmpSel->setGroupRect();
-		double xs = m_tmpSel->width();
-		double ys = m_tmpSel->height();
-		tmpImage = Elements.at(0)->DrawObj_toImage(500);
-		tmpImage.setText("XSize", QString("%1").arg(xs));
-		tmpImage.setText("YSize", QString("%1").arg(ys));
-		m_Doc->m_Selection->delaySignalsOff();
-		m_Doc->setLoading(false);
-	}
-	m_Doc->scMW()->setScriptRunning(false);
-	delete m_Doc;
-	QDir::setCurrent(CurDirP);
-	return tmpImage;
-}
-
-bool WMFImport::import(QString fname, const TransactionSettings& trSettings, int flags)
-{
-	if (!loadWMF(fname))
-	{
-		importFailed = true;
-		return false;
-	}
-	QString CurDirP = QDir::currentPath();
-	QFileInfo efp(fname);
-	QDir::setCurrent(efp.path());
-	bool success = importWMF(trSettings, flags);
-	QDir::setCurrent(CurDirP);
-	return success;
-}
-
-bool WMFImport::loadWMF( const QString &fileName )
-{
-	QFile file( fileName );
-
-	if ( !file.exists() )
-	{
-		cerr << "File " << QFile::encodeName(fileName).data() << " does not exist" << endl;
-		return false;
-	}
-
-	if ( !file.open( QIODevice::ReadOnly ) )
-	{
-		cerr << "Cannot open file " << QFile::encodeName(fileName).data() << endl;
-		return false;
-	}
-
-	QByteArray ba = file.readAll();
-	file.close();
-
-	QBuffer buffer( &ba );
-	buffer.open( QIODevice::ReadOnly );
-	return loadWMF( buffer );
-}
-
-bool WMFImport::loadWMF( QBuffer &buffer )
-{
-	QDataStream st;
-	WmfEnhMetaHeader eheader;
-	WmfMetaHeader header;
-	WmfPlaceableHeader pheader;
-	WORD16 checksum;
-	int filePos, idx, i;
-	WmfCmd *cmd;
-	WORD32 rdSize;
-	WORD16 rdFunc;
-
-	header.mtSize = 0;
-	header.mtHeaderSize = 0;
-	header.mtNoParameters = 0;
-
-	qDeleteAll(m_commands);
-	m_commands.clear();
-
-	st.setDevice( &buffer );
-	st.setByteOrder( QDataStream::LittleEndian ); // Great, I love Qt !
-
-	//----- Read placeable metafile header
-	st >> pheader.key;
-	m_IsPlaceable = (pheader.key == (WORD32) APMHEADER_KEY);
-	if ( m_IsPlaceable )
-	{
-		st >> pheader.hmf;
-		st >> pheader.bbox.left;
-		st >> pheader.bbox.top;
-		st >> pheader.bbox.right;
-		st >> pheader.bbox.bottom;
-		st >> pheader.inch;
-		st >> pheader.reserved;
-		st >> pheader.checksum;
-		checksum = calcCheckSum( &pheader );
-		if ( pheader.checksum!=checksum ) m_IsPlaceable = false;
-
-		m_Dpi = pheader.inch;
-		m_BBox.setLeft( pheader.bbox.left );
-		m_BBox.setTop( pheader.bbox.top );
-		m_BBox.setRight( pheader.bbox.right );
-		m_BBox.setBottom( pheader.bbox.bottom );
-		m_HeaderBoundingBox = m_BBox;
-		if ( WMFIMPORT_DEBUG )
-		{
-			cerr << endl << "-------------------------------------------------" << endl;
-			cerr << "WMF Placeable Header ( " << static_cast<int>(sizeof( pheader ) ) << "):" << endl;
-			cerr << "  bbox=( " << m_BBox.left() << "; " << m_BBox.top() << "; " << m_BBox.width() << "; " << m_BBox.height() << ")" << endl;
-			cerr << "  inch=" << pheader.inch << endl;
-			cerr << "  checksum=" << pheader.checksum << "( " << (pheader.checksum==checksum?"ok":"wrong") << " )" << endl;
-		}
-	}
-	else buffer.seek( 0 );
-
-	//----- Read as enhanced metafile header
-	filePos = buffer.pos();
-	st >> eheader.iType;
-	st >> eheader.nSize;
-	st >> eheader.rclBounds.left;
-	st >> eheader.rclBounds.top;
-	st >> eheader.rclBounds.right;
-	st >> eheader.rclBounds.bottom;
-	st >> eheader.rclFrame.left;
-	st >> eheader.rclFrame.top;
-	st >> eheader.rclFrame.right;
-	st >> eheader.rclFrame.bottom;
-	st >> eheader.dSignature;
-	m_IsEnhanced = ( eheader.dSignature==ENHMETA_SIGNATURE );
-	if ( m_IsEnhanced ) // is it really enhanced ?
-	{
-		st >> eheader.nVersion;
-		st >> eheader.nBytes;
-		st >> eheader.nRecords;
-		st >> eheader.nHandles;
-		st >> eheader.sReserved;
-		st >> eheader.nDescription;
-		st >> eheader.offDescription;
-		st >> eheader.nPalEntries;
-		st >> eheader.szlDevice.width;
-		st >> eheader.szlDevice.height;
-		st >> eheader.szlMillimeters.width;
-		st >> eheader.szlMillimeters.height;
-
-		if ( WMFIMPORT_DEBUG )
-		{
-			cerr << endl << "-------------------------------------------------" << endl;
-			cerr << "WMF Extended Header:" << endl;
-			cerr << "  iType=" << eheader.iType << endl;
-			cerr << "  nSize=" << eheader.nSize << endl;
-			cerr << "  rclBounds=( " << eheader.rclBounds.left << "; " << eheader.rclBounds.top << "; "
-					  << eheader.rclBounds.right << "; " << eheader.rclBounds.bottom << ")" << endl;
-			cerr << "  rclFrame=( " << eheader.rclFrame.left << "; " << eheader.rclFrame.top << "; "
-					  << eheader.rclFrame.right << "; " << eheader.rclFrame.bottom << ")" << endl;
-			cerr << "  nBytes=" << eheader.nBytes << endl;
-			cerr << "\nNOT YET IMPLEMENTED, SORRY." << endl;
-		}
-	}
-	else // no, not enhanced
-	{
-		//----- Read as standard metafile header
-		buffer.seek( filePos );
-		st >> header.mtType;
-		st >> header.mtHeaderSize;
-		st >> header.mtVersion;
-		st >> header.mtSize;
-		st >> header.mtNoObjects;
-		st >> header.mtMaxRecord;
-		st >> header.mtNoParameters;
-		if ( WMFIMPORT_DEBUG ) {
-			cerr << "WMF Header: " <<  "mtSize=" << header.mtSize << endl;
-		}
-	}
-
-	//----- Test header validity
-	m_Valid = ((header.mtHeaderSize == 9) && (header.mtNoParameters == 0)) || m_IsEnhanced || m_IsPlaceable;
-	if ( m_Valid )
-	{
-		//----- Read Metafile Records
-		rdFunc = -1;
-		while ( !st.atEnd() && (rdFunc != 0) )
-		{
-			st >> rdSize;
-			st >> rdFunc;
-			idx = findFunc( rdFunc );
-			rdSize -= 3;
-
-			cmd = new WmfCmd;
-			m_commands.append(cmd);
-
-			cmd->funcIndex = idx;
-			cmd->numParam = rdSize;
-			cmd->params = new WORD16[ rdSize ];
-
-			for ( i=0; i<rdSize && !st.atEnd(); i++ )
-				st >> cmd->params[ i ];
-
-
-			if ( rdFunc == 0x020B && !m_IsPlaceable) {         // SETWINDOWORG: dimensions
-				m_BBox.setLeft( qMin((int) cmd->params[ 1 ], m_BBox.left()) );
-				m_BBox.setTop ( qMin((int) cmd->params[ 0 ], m_BBox.top()) );
-			}
-			if ( rdFunc == 0x020C && !m_IsPlaceable ) {         // SETWINDOWEXT: dimensions
-				m_BBox.setWidth ( qMax((int) cmd->params[ 1 ], m_BBox.width()) );
-				m_BBox.setHeight( qMax((int) cmd->params[ 0 ], m_BBox.height()));
-			}
-
-			if ( i<rdSize )
-			{
-				cerr << "WMF : file truncated !" << endl;
-				return false;
-			}
-		}
-		//----- Test records validities
-		m_Valid = (rdFunc == 0) && (m_BBox.width() != 0) && (m_BBox.height() != 0);
-		if ( !m_Valid ) {
-			cerr << "WMF : incorrect file format !" << endl;
-		}
-	}
-	else {
-		cerr << "WMF Header : incorrect header !" << endl;
-	}
-
-	buffer.close();
-	return m_Valid;
-}
-
-bool WMFImport::importWMF(const TransactionSettings& trSettings, int flags)
-{
-	bool ret = false;
-	//double scale = (m_Dpi > 288) ? 288.0 / m_Dpi : 1.0;
-	double scale  = (m_Dpi > 0) ? 72.0 / m_Dpi : 0.05;
-	double width  = m_BBox.width() * scale;
-	double height = m_BBox.height() * scale;
-	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
-	{
-		m_Doc->setPage(fabs(width), fabs(height), 0, 0, 0, 0, 0, 0, false, false);
-		m_Doc->addPage(0);
-		m_Doc->view()->addPage(0);
-	}
-	else
-	{
-		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
-		{
-			m_Doc=ScCore->primaryMainWindow()->doFileNew(fabs(width), fabs(height), 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
-			ScCore->primaryMainWindow()->HaveNewDoc();
-			ret = true;
-		}
-	}
-	if ((ret) || (!interactive))
-	{
-		if (width > height)
-			m_Doc->setPageOrientation(1);
-		else
-			m_Doc->setPageOrientation(0);
-		m_Doc->setPageSize("Custom");
-	}
+/*
+For general Scribus (>=1.3.2) copyright and licensing information please refer
+to the COPYING file provided with the program. Following this notice may exist
+a copyright and/or license notice that predates the release of Scribus 1.3.2
+for which a new license (GPL+exception) is in place.
+*/
+
+/* Code inspired by KOffice libwmf and adapted for Scribus by Jean Ghali */
+
+#include "scconfig.h"
+#include "wmfimport.h"
+
+#include <QCursor>
+#include <QDrag>
+#include <QBuffer>
+#include <QDataStream>
+#include <QFile>
+#include <QMimeData>
+#include <QPainterPath>
+#include <QRegExp>
+
+#include "commonstrings.h"
+#include "scribus.h"
+#include "scribusXml.h"
+#include "fonts/scfontmetrics.h"
+#include "fpointarray.h"
+#include "ui/scmwmenumanager.h"
+#include "prefsmanager.h"
+#include "pageitem.h"
+#include "prefsfile.h"
+#include "scmimedata.h"
+#include "scraction.h"
+#include "scribuscore.h"
+#include "scribusdoc.h"
+#include "selection.h"
+#include "ui/customfdialog.h"
+#include "ui/propertiespalette.h"
+#include "undomanager.h"
+#include "loadsaveplugin.h"
+#include "util.h"
+#include "util_icon.h"
+#include "util_math.h"
+
+
+using namespace std;
+
+#include "wmfstruct.h"
+#include "wmfcmd.h"
+#include "wmfcontext.h"
+#include "wmfhandle.h"
+#include "metafuncs.h"
+
+#define WMFIMPORT_DEBUG 0
+#define MAX_OBJHANDLE   128
+
+#define ANSI_CHARSET			0		// ANSI charset (Windows-1252)
+#define DEFAULT_CHARSET			1
+#define SYMBOL_CHARSET			2
+#define MAC_CHARSET				77
+#define SHIFTJIS_CHARSET		128		// Shift JIS charset    (Windows-932)
+#define HANGEUL_CHARSET			129		// Hangeul charset      (Windows-949)
+#define JOHAB_CHARSET			130		// Johab charset        (Windows-1361)
+#define GB2312_CHARSET			134		// GB2312 charset       (Windows-936)
+#define CHINESEBIG5_CHARSET		136		// Chinese Big5 charset (Windows-950)
+#define GREEK_CHARSET			161		// Greek charset        (Windows-1253)
+#define TURKISH_CHARSET			162		// Turkish charset      (Windows-1254)
+#define VIETNAMESE_CHARSET		163		// Vietnamese charset   (Windows-1258)
+#define HEBREW_CHARSET			177		// Hebrew charset       (Windows-1255)
+#define ARABIC_CHARSET			178		// Arabic charset       (Windows-1256)
+#define BALTIC_CHARSET			186		// Baltic charset       (Windows-1257)
+#define RUSSIAN_CHARSET			204		// Cyrillic charset     (Windows-1251)
+#define THAI_CHARSET			222		// Thai charset         (Windows-874)
+#define EASTEUROPE_CHARSET		238		// Eastern european charset (Windows-1250)
+#define OEM_CHARSET				255
+
+/* Symbol to unicode conversion table copied from http://root.cern.ch/viewvc/trunk/qt/src/TQtSymbolCodec.cxx
+This code is placed under GPL licence (http://root.cern.ch/viewvc/trunk/LICENSE) */
+static const ushort greek_symbol_to_unicode[64] = {
+//
+//  upper case letters:
+//  ----------------
+//   Alpha   Beta     Chi   Delta   Epsilon   Phi    Gamma    Eta
+	0x0391, 0x0392, 0x03A7, 0x0394, 0x0395, 0x03A6, 0x0393, 0x0397,
+//   Iota   Theta(S) Kappa  Lambda    Mu      Nu    Omicron   Pi
+	0x0399, 0x03D1, 0x039A, 0x039B, 0x039C, 0x039D, 0x039F, 0x03A0,
+//  Theta    Rho    Sigma    Tau    Upsilon Stigma   Omega     Xi
+	0x0398, 0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03DB, 0x03A9, 0x039E,
+//   Psi     Zeta   Sigma    Tau    Upsilon  ????   Omega     Xi
+	0x03A8, 0x0396, 0x03EA, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD,
+//
+//  lower case letters:
+//  ----------------
+//   Alpha   Beta    Chi    Delta   Epsilon   Phi    Gamma    Eta
+	0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x03B5, 0x03D5, 0x03B3, 0x03B7,
+//   Iota   Phi (2) Kappa   Lambda    Mu      Nu    Omicron   Pi
+	0x03B9, 0x03C6, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, 0x03C0,
+//  Theta    Rho    Sigma    Tau    Upsilon OmegaPi Omega     Xi
+	0x03B8, 0x03C1, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03B9, 0x03BE,
+//   Psi     Zeta   Sigma    Tau    Upsilon  ????   Omega     Xi
+	0x03C8, 0x03B6, 0x03EA, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
+};
+
+/* Symbol to unicode conversion table copied from http://root.cern.ch/viewvc/trunk/qt/src/TQtSymbolCodec.cxx
+This code is placed under GPL licence (http://root.cern.ch/viewvc/trunk/LICENSE) */
+static const ushort symbol_to_unicode[96] = {
+//
+//  upper case letters:
+//  ----------------
+// UPSILON  NUMBER  LessEq   Div   INFINITY ???????  CLUB   DIAMOND     
+	0x03D2, 0x0374, 0x2264, 0x2215, 0x221E, 0x0395, 0x2663, 0x2666,
+//   HEART  SPADE   <--->   <---             -->             RING
+	0x2665, 0x2660, 0x2194, 0x2190, 0x2191, 0x2192, 0x2193, 0x2218,
+//  Theta    Rho    Great    ????   Propor  diff    bullet   ????
+	0x0398, 0x03A1, 0x2265, 0x03A4, 0x221D, 0x2202, 0x2219, 0x03A8,
+//   NonEq  Ident    ????   ellips   div     minus  ?????   aleph
+	0x2260, 0x2261, 0xFFFD, 0x22EF, 0x2223, 0x2212, 0xFFFD, 0xFFFD,
+//
+//  lower case letters:
+//  ----------------
+//   Alpha   Beta    Chi    Delta   Epsilon   Phi    Gamma    Eta
+	0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x03B5, 0x03D5, 0x03B3, 0x03B7,
+//   Iota   Phi (2) Kappa   Lambda    Mu      Nu    Omicron   Pi
+	0x03B9, 0x03C6, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, 0x03C0,
+//  Theta    Rho    Sigma    Tau    Upsilon OmegaPi Omega     Xi
+	0x03B8, 0x03C1, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03B9, 0x03BE,
+//   Psi     Zeta   arrow    Tau    Upsilon  ????   Omega     Xi
+	0x03C8, 0x03B6, 0x21D4, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD,
+//  lower case letters:
+//  ----------------
+//   Alpha   Beta    Chi    Delta   Sigma     Phi    Gamma    Eta
+	0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x2211, 0x03D5, 0x03B3, 0x03B7,
+//   Iota   Phi (2) Kappa   Lambda    Mu      Nu    Omicron   Pi
+	0x03B9, 0x03C6, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, 0x03C0,
+//  Theta   Integr  Sigma    Tau    Upsilon OmegaPi Omega     Xi
+	0x03B8, 0x222b, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03B9, 0x03BE,
+//   Psi     Zeta   Sigma    Tau    Upsilon  ????   Omega     Xi
+	0x03C8, 0x03B6, 0x03EA, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
+};
+
+WMFImport::WMFImport( ScribusDoc* doc, int flags )
+{	
+	m_tmpSel = new Selection(this, false);
+	m_Doc    = doc;
+	unsupported = false;
+	importFailed = false;
+	importCanceled = true;
+	importedColors.clear();
+	m_docDesc = "";
+	m_docTitle = "";
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+
+	m_Valid        = false;
+	m_ObjHandleTab = NULL;
+	m_Dpi          = 1440;
+}
+
+WMFImport::~WMFImport()
+{
+	qDeleteAll(m_commands);
+	m_commands.clear();
+	if ( m_tmpSel) delete m_tmpSel;
+	if ( m_ObjHandleTab ) 
+	{
+		for (int i = 0; i < MAX_OBJHANDLE; ++i)
+		{
+			if (m_ObjHandleTab[i])
+				delete m_ObjHandleTab[i];
+		}
+		delete[] m_ObjHandleTab;
+	}
+}
+
+QString WMFImport::importColor(const QColor& color)
+{
+	ScColor tmp;
+	tmp.fromQColor(color);
+	tmp.setSpotColor(false);
+	tmp.setRegistrationColor(false);
+	QString pNam = "FromWMF"+color.name();
+	QString fNam = m_Doc->PageColors.tryAddColor(pNam, tmp);
+	if (fNam == pNam)
+		importedColors.append(pNam);
+	return fNam;
+}
+
+QColor WMFImport::colorFromParam( short* params )
+{
+	unsigned int colorRef;
+	int red, green, blue;
+
+	colorRef = toDWord( params ) & 0xffffff;
+	red      = colorRef & 255;
+	green    = ( colorRef>>8 ) & 255;
+	blue     = ( colorRef>>16 ) & 255;
+
+	return QColor( red, green, blue );
+}
+
+QTextCodec* WMFImport::codecFromCharset( int charset )
+{
+	QTextCodec* codec = NULL;
+	if (charset == DEFAULT_CHARSET || charset == OEM_CHARSET)
+		codec = QTextCodec::codecForLocale();
+	else if (charset == ANSI_CHARSET)
+		codec = QTextCodec::codecForName("windows-1252");
+	/*else if (charset == SYMBOL_CHARSET)
+		codec = QTextCodec::codecForLocale();// Not supported yet*/
+	else if (charset == MAC_CHARSET)
+		codec = QTextCodec::codecForName("Apple Roman");
+	else if (charset == SHIFTJIS_CHARSET)
+		codec = QTextCodec::codecForName("Shift-JIS");
+	else if (charset == HANGEUL_CHARSET)
+		codec = QTextCodec::codecForName("CP949");
+	else if (charset == GB2312_CHARSET)
+		codec = QTextCodec::codecForName("CP936");
+	else if (charset == CHINESEBIG5_CHARSET)
+		codec = QTextCodec::codecForName("Big5");
+	else if (charset == GREEK_CHARSET)
+		codec = QTextCodec::codecForName("windows-1253");
+	else if (charset == TURKISH_CHARSET)
+		codec = QTextCodec::codecForName("windows-1254");
+	else if (charset == VIETNAMESE_CHARSET)
+		codec = QTextCodec::codecForName("windows-1258");
+	else if (charset == HEBREW_CHARSET)
+		codec = QTextCodec::codecForName("windows-1255");
+	else if (charset == ARABIC_CHARSET)
+		codec = QTextCodec::codecForName("windows-1256");
+	else if (charset == BALTIC_CHARSET)
+		codec = QTextCodec::codecForName("windows-1257");
+	else if (charset == RUSSIAN_CHARSET)
+		codec = QTextCodec::codecForName("windows-1251");
+	else if (charset == THAI_CHARSET)
+		codec = QTextCodec::codecForName("CP874");
+	else if (charset == EASTEUROPE_CHARSET)
+		codec = QTextCodec::codecForName("windows-1250");
+	return codec;
+}
+
+QString WMFImport::symbolToUnicode ( const QByteArray& chars )
+{
+	/*Code under GPL licence (http://root.cern.ch/viewvc/trunk/LICENSE)
+	taken from http://root.cern.ch/viewvc/trunk/qt/src/TQtSymbolCodec.cxx*/
+	QString r;
+	const unsigned char * c = (const unsigned char *) chars.data();
+	
+	if( chars.size() == 0 ) return r;
+	
+	for (int i = 0; i < chars.size(); ++i) 
+	{
+		if ( 64 < c[i] && c[i] <= 64+32 )
+			r.append( QChar(greek_symbol_to_unicode[c[i]-65]) );
+		else if (64+32+1 <= c[i] && c[i] < 64+32+32+1)
+			r.append( QChar(greek_symbol_to_unicode[c[i]-65-32]+32) );
+		else if (161 <= c[i] )
+			r.append(  QChar(symbol_to_unicode[c[i]-161]) );
+		else
+			r.append( QChar(c[i]) );
+	}
+	return r;
+}
+
+FPointArray WMFImport::pointsFromParam( short num, short* params )
+{
+	FPointArray points;
+	points.resize( num );
+
+	for ( int i = 0; i < num; i++, params += 2 )
+		points.setPoint( i, params[ 0 ], params[ 1 ] );
+
+	return points;
+}
+
+FPointArray WMFImport::pointsToPolyline( const FPointArray& points, bool closePath )
+{
+	bool bFirst = true;
+	double x = 0.0, y = 0.0;
+	FPointArray polyline;
+	polyline.svgInit();
+	for( uint i = 0; i < points.size(); ++i )
+	{
+		FPoint point = points.point(i);
+		if( bFirst )
+		{
+			x = point.x();
+			y = point.y();
+			polyline.svgMoveTo(x, y);
+			bFirst = false;
+		}
+		else
+		{
+			x = point.x();
+			y = point.y();
+			polyline.svgLineTo(x, y);
+		}
+	}
+	if (closePath && (points.size() > 4))
+		polyline.svgClosePath();
+	return polyline;
+}
+
+void WMFImport::pointsToAngle( double xStart, double yStart, double xEnd, double yEnd, double& angleStart, double& angleLength )
+{
+	double aStart  = atan2( yStart,  xStart );
+	double aLength = atan2( yEnd, xEnd ) - aStart;
+
+	angleStart  = (int)(aStart * 180.0 / 3.14166);
+	angleLength = (int)(aLength * 180.0 / 3.14166);
+	if ( angleLength < 0 ) angleLength = 360.0 + angleLength;
+}
+
+QImage WMFImport::readThumbnail(QString fname)
+{
+	if (!loadWMF(fname))
+	{
+		importFailed = true;
+		return QImage();
+	}
+	QString CurDirP = QDir::currentPath();
+	QFileInfo efp(fname);
+	QDir::setCurrent(efp.path());
+	double scale  = (m_Dpi > 0) ? 72.0 / m_Dpi : 0.05;
+	double width  = m_BBox.width() * scale;
+	double height = m_BBox.height() * scale;
+	m_Doc = new ScribusDoc();
+	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
+	m_Doc->setPage(width, height, 0, 0, 0, 0, 0, 0, false, false);
+	m_Doc->addPage(0);
+	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	m_Doc->scMW()->setScriptRunning(true);
+	m_Doc->PageColors.ensureDefaultColors();
+	QList<PageItem*> Elements = parseWmfCommands();
+	m_tmpSel->clear();
+	QImage tmpImage = QImage();
+	if (Elements.count() > 0)
+	{
+		if (Elements.count() > 1)
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->m_Selection->delaySignalsOn();
+		for (int dre=0; dre<Elements.count(); ++dre)
+		{
+			m_tmpSel->addItem(Elements.at(dre), true);
+		}
+		m_tmpSel->setGroupRect();
+		double xs = m_tmpSel->width();
+		double ys = m_tmpSel->height();
+		tmpImage = Elements.at(0)->DrawObj_toImage(500);
+		tmpImage.setText("XSize", QString("%1").arg(xs));
+		tmpImage.setText("YSize", QString("%1").arg(ys));
+		m_Doc->m_Selection->delaySignalsOff();
+		m_Doc->setLoading(false);
+	}
+	m_Doc->scMW()->setScriptRunning(false);
+	delete m_Doc;
+	QDir::setCurrent(CurDirP);
+	return tmpImage;
+}
+
+bool WMFImport::import(QString fname, const TransactionSettings& trSettings, int flags)
+{
+	if (!loadWMF(fname))
+	{
+		importFailed = true;
+		return false;
+	}
+	QString CurDirP = QDir::currentPath();
+	QFileInfo efp(fname);
+	QDir::setCurrent(efp.path());
+	bool success = importWMF(trSettings, flags);
+	QDir::setCurrent(CurDirP);
+	return success;
+}
+
+bool WMFImport::loadWMF( const QString &fileName )
+{
+	QFile file( fileName );
+
+	if ( !file.exists() )
+	{
+		cerr << "File " << QFile::encodeName(fileName).data() << " does not exist" << endl;
+		return false;
+	}
+
+	if ( !file.open( QIODevice::ReadOnly ) )
+	{
+		cerr << "Cannot open file " << QFile::encodeName(fileName).data() << endl;
+		return false;
+	}
+
+	QByteArray ba = file.readAll();
+	file.close();
+
+	QBuffer buffer( &ba );
+	buffer.open( QIODevice::ReadOnly );
+	return loadWMF( buffer );
+}
+
+bool WMFImport::loadWMF( QBuffer &buffer )
+{
+	QDataStream st;
+	WmfEnhMetaHeader eheader;
+	WmfMetaHeader header;
+	WmfPlaceableHeader pheader;
+	WORD16 checksum;
+	int filePos, idx, i;
+	WmfCmd *cmd;
+	WORD32 rdSize;
+	WORD16 rdFunc;
+
+	header.mtSize = 0;
+	header.mtHeaderSize = 0;
+	header.mtNoParameters = 0;
+
+	qDeleteAll(m_commands);
+	m_commands.clear();
+
+	st.setDevice( &buffer );
+	st.setByteOrder( QDataStream::LittleEndian ); // Great, I love Qt !
+
+	//----- Read placeable metafile header
+	st >> pheader.key;
+	m_IsPlaceable = (pheader.key == (WORD32) APMHEADER_KEY);
+	if ( m_IsPlaceable )
+	{
+		st >> pheader.hmf;
+		st >> pheader.bbox.left;
+		st >> pheader.bbox.top;
+		st >> pheader.bbox.right;
+		st >> pheader.bbox.bottom;
+		st >> pheader.inch;
+		st >> pheader.reserved;
+		st >> pheader.checksum;
+		checksum = calcCheckSum( &pheader );
+		if ( pheader.checksum!=checksum ) m_IsPlaceable = false;
+
+		m_Dpi = pheader.inch;
+		m_BBox.setLeft( pheader.bbox.left );
+		m_BBox.setTop( pheader.bbox.top );
+		m_BBox.setRight( pheader.bbox.right );
+		m_BBox.setBottom( pheader.bbox.bottom );
+		m_HeaderBoundingBox = m_BBox;
+		if ( WMFIMPORT_DEBUG )
+		{
+			cerr << endl << "-------------------------------------------------" << endl;
+			cerr << "WMF Placeable Header ( " << static_cast<int>(sizeof( pheader ) ) << "):" << endl;
+			cerr << "  bbox=( " << m_BBox.left() << "; " << m_BBox.top() << "; " << m_BBox.width() << "; " << m_BBox.height() << ")" << endl;
+			cerr << "  inch=" << pheader.inch << endl;
+			cerr << "  checksum=" << pheader.checksum << "( " << (pheader.checksum==checksum?"ok":"wrong") << " )" << endl;
+		}
+	}
+	else buffer.seek( 0 );
+
+	//----- Read as enhanced metafile header
+	filePos = buffer.pos();
+	st >> eheader.iType;
+	st >> eheader.nSize;
+	st >> eheader.rclBounds.left;
+	st >> eheader.rclBounds.top;
+	st >> eheader.rclBounds.right;
+	st >> eheader.rclBounds.bottom;
+	st >> eheader.rclFrame.left;
+	st >> eheader.rclFrame.top;
+	st >> eheader.rclFrame.right;
+	st >> eheader.rclFrame.bottom;
+	st >> eheader.dSignature;
+	m_IsEnhanced = ( eheader.dSignature==ENHMETA_SIGNATURE );
+	if ( m_IsEnhanced ) // is it really enhanced ?
+	{
+		st >> eheader.nVersion;
+		st >> eheader.nBytes;
+		st >> eheader.nRecords;
+		st >> eheader.nHandles;
+		st >> eheader.sReserved;
+		st >> eheader.nDescription;
+		st >> eheader.offDescription;
+		st >> eheader.nPalEntries;
+		st >> eheader.szlDevice.width;
+		st >> eheader.szlDevice.height;
+		st >> eheader.szlMillimeters.width;
+		st >> eheader.szlMillimeters.height;
+
+		if ( WMFIMPORT_DEBUG )
+		{
+			cerr << endl << "-------------------------------------------------" << endl;
+			cerr << "WMF Extended Header:" << endl;
+			cerr << "  iType=" << eheader.iType << endl;
+			cerr << "  nSize=" << eheader.nSize << endl;
+			cerr << "  rclBounds=( " << eheader.rclBounds.left << "; " << eheader.rclBounds.top << "; "
+					  << eheader.rclBounds.right << "; " << eheader.rclBounds.bottom << ")" << endl;
+			cerr << "  rclFrame=( " << eheader.rclFrame.left << "; " << eheader.rclFrame.top << "; "
+					  << eheader.rclFrame.right << "; " << eheader.rclFrame.bottom << ")" << endl;
+			cerr << "  nBytes=" << eheader.nBytes << endl;
+			cerr << "\nNOT YET IMPLEMENTED, SORRY." << endl;
+		}
+	}
+	else // no, not enhanced
+	{
+		//----- Read as standard metafile header
+		buffer.seek( filePos );
+		st >> header.mtType;
+		st >> header.mtHeaderSize;
+		st >> header.mtVersion;
+		st >> header.mtSize;
+		st >> header.mtNoObjects;
+		st >> header.mtMaxRecord;
+		st >> header.mtNoParameters;
+		if ( WMFIMPORT_DEBUG ) {
+			cerr << "WMF Header: " <<  "mtSize=" << header.mtSize << endl;
+		}
+	}
+
+	//----- Test header validity
+	m_Valid = ((header.mtHeaderSize == 9) && (header.mtNoParameters == 0)) || m_IsEnhanced || m_IsPlaceable;
+	if ( m_Valid )
+	{
+		//----- Read Metafile Records
+		rdFunc = -1;
+		while ( !st.atEnd() && (rdFunc != 0) )
+		{
+			st >> rdSize;
+			st >> rdFunc;
+			idx = findFunc( rdFunc );
+			rdSize -= 3;
+
+			cmd = new WmfCmd;
+			m_commands.append(cmd);
+
+			cmd->funcIndex = idx;
+			cmd->numParam = rdSize;
+			cmd->params = new WORD16[ rdSize ];
+
+			for ( i=0; i<rdSize && !st.atEnd(); i++ )
+				st >> cmd->params[ i ];
+
+
+			if ( rdFunc == 0x020B && !m_IsPlaceable) {         // SETWINDOWORG: dimensions
+				m_BBox.setLeft( qMin((int) cmd->params[ 1 ], m_BBox.left()) );
+				m_BBox.setTop ( qMin((int) cmd->params[ 0 ], m_BBox.top()) );
+			}
+			if ( rdFunc == 0x020C && !m_IsPlaceable ) {         // SETWINDOWEXT: dimensions
+				m_BBox.setWidth ( qMax((int) cmd->params[ 1 ], m_BBox.width()) );
+				m_BBox.setHeight( qMax((int) cmd->params[ 0 ], m_BBox.height()));
+			}
+
+			if ( i<rdSize )
+			{
+				cerr << "WMF : file truncated !" << endl;
+				return false;
+			}
+		}
+		//----- Test records validities
+		m_Valid = (rdFunc == 0) && (m_BBox.width() != 0) && (m_BBox.height() != 0);
+		if ( !m_Valid ) {
+			cerr << "WMF : incorrect file format !" << endl;
+		}
+	}
+	else {
+		cerr << "WMF Header : incorrect header !" << endl;
+	}
+
+	buffer.close();
+	return m_Valid;
+}
+
+bool WMFImport::importWMF(const TransactionSettings& trSettings, int flags)
+{
+	bool ret = false;
+	//double scale = (m_Dpi > 288) ? 288.0 / m_Dpi : 1.0;
+	double scale  = (m_Dpi > 0) ? 72.0 / m_Dpi : 0.05;
+	double width  = m_BBox.width() * scale;
+	double height = m_BBox.height() * scale;
+	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
+	{
+		m_Doc->setPage(fabs(width), fabs(height), 0, 0, 0, 0, 0, 0, false, false);
+		m_Doc->addPage(0);
+		m_Doc->view()->addPage(0);
+	}
+	else
+	{
+		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
+		{
+			m_Doc=ScCore->primaryMainWindow()->doFileNew(fabs(width), fabs(height), 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
+			ScCore->primaryMainWindow()->HaveNewDoc();
+			ret = true;
+		}
+	}
+	if ((ret) || (!interactive))
+	{
+		if (width > height)
+			m_Doc->setPageOrientation(1);
+		else
+			m_Doc->setPageOrientation(0);
+		m_Doc->setPageSize("Custom");
+	}
 	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->Deselect();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->updatesOn(false);
-	m_Doc->scMW()->setScriptRunning(true);
-	qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
-	//gc->Family = m_Doc->toolSettings.textFont;
-	m_Doc->PageColors.ensureDefaultColors();
-	//m_gc.push( gc );
-	QList<PageItem*> Elements = parseWmfCommands();
-	if (flags & LoadSavePlugin::lfCreateDoc)
-	{
-		m_Doc->documentInfo().setTitle(m_docTitle);
-		m_Doc->documentInfo().setComments(m_docDesc);
-	}
-	m_tmpSel->clear();
-	if (Elements.count() == 0)
-	{
-		importFailed = true;
-		if (importedColors.count() != 0)
-		{
-			for (int cd = 0; cd < importedColors.count(); cd++)
-			{
-				m_Doc->PageColors.remove(importedColors[cd]);
-			}
-		}
-	}
-	if (Elements.count() > 1)
-		m_Doc->groupObjectsList(Elements);
-	m_Doc->DoDrawing = true;
-	m_Doc->scMW()->setScriptRunning(false);
-	if (interactive)
-		m_Doc->setLoading(false);
-	qApp->setOverrideCursor(QCursor(Qt::ArrowCursor));
-	if ((Elements.count() > 0) && (!ret) && (interactive))
-	{
-		if (flags & LoadSavePlugin::lfScripted)
-		{
-			bool loadF = m_Doc->isLoading();
-			m_Doc->setLoading(false);
-			m_Doc->changed();
-			m_Doc->setLoading(loadF);
-			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-			{
-				m_Doc->m_Selection->delaySignalsOn();
-				for (int dre=0; dre<Elements.count(); ++dre)
-				{
-					m_Doc->m_Selection->addItem(Elements.at(dre), true);
-				}
-				m_Doc->m_Selection->delaySignalsOff();
-				m_Doc->m_Selection->setGroupRect();
-				m_Doc->view()->updatesOn(true);
-			}
-			importCanceled = false;
-		}
-		else
-		{
-			m_Doc->DragP = true;
-			m_Doc->DraggedElem = 0;
-			m_Doc->DragElements.clear();
-			m_Doc->m_Selection->delaySignalsOn();
-			for (int dre=0; dre<Elements.count(); ++dre)
-			{
-				m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
-				m_tmpSel->addItem(Elements.at(dre), true);
-			}
-			ScriXmlDoc *ss = new ScriXmlDoc();
-			m_tmpSel->setGroupRect();
-			ScElemMimeData* md = new ScElemMimeData();
-			md->setScribusElem(ss->WriteElem(m_Doc, m_tmpSel));
-			delete ss;
-/*#ifndef QT_MAC*/
-// see #2526
-			m_Doc->itemSelection_DeleteItem(m_tmpSel);
-/*#endif*/
-			m_Doc->view()->updatesOn(true);
-			m_Doc->m_Selection->delaySignalsOff();
-			// We must copy the TransationSettings object as it is owned
-			// by handleObjectImport method afterwards
-			TransactionSettings* transacSettings = new TransactionSettings(trSettings);
-			m_Doc->view()->handleObjectImport(md, transacSettings);
-			m_Doc->DragP = false;
-			m_Doc->DraggedElem = 0;
-			m_Doc->DragElements.clear();
-		}
-	}
-	else
-	{
-		bool loadF = m_Doc->isLoading();
-		m_Doc->setLoading(false);
-		m_Doc->changed();
-		m_Doc->reformPages();
-		if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-			m_Doc->view()->updatesOn(true);
-		m_Doc->setLoading(loadF);
-	}
-	return true;
-}
-
-QList<PageItem*> WMFImport::parseWmfCommands(void)
-{
-	int idx, i;
-	const WmfCmd* cmd;
-	QList<PageItem*> elements;
-
-	m_context.reset();
-
-	if ( !m_Valid )  return elements;
-
-	if ( m_ObjHandleTab ) delete[] m_ObjHandleTab;
-	m_ObjHandleTab = new WmfObjHandle* [ MAX_OBJHANDLE ];
-	for ( i = MAX_OBJHANDLE-1; i >= 0; i-- )
-		m_ObjHandleTab[ i ] = NULL;
-
-	if ( WMFIMPORT_DEBUG )  {
-		cerr << "Bounding box : " << m_BBox.left() << " " << m_BBox.top() << " " << m_BBox.right() << " " << m_BBox.bottom() << endl;
-	}
-
-	double scale  = (m_Dpi > 0) ? 72.0 / m_Dpi : 0.05;
-	m_context.setViewportOrg( 0, 0 );
-	m_context.setViewportExt( m_BBox.width() * scale, m_BBox.height() * scale );
-	m_context.setWindowOrg( m_BBox.left(), m_BBox.bottom() );
-	m_context.setWindowExt( m_BBox.width(), m_BBox.height() );
-
-	for (int index = 0; index < m_commands.count(); ++index)
-	{
-		cmd = m_commands.at(index);
-		idx = cmd->funcIndex;
-		( this->*metaFuncTab[ idx ].method )( elements, cmd->numParam, cmd->params );
-
-		if ( WMFIMPORT_DEBUG )  {
-			QString str = "", param;
-			if ( metaFuncTab[ idx ].name == NULL ) {
-				str += "UNKNOWN ";
-			}
-			if ( metaFuncTab[ idx ].method == &WMFImport::noop ) {
-				str += "UNIMPLEMENTED ";
-			}
-			str += metaFuncTab[ idx ].name;
-			str += " : ";
-
-			for ( i=0 ; i < cmd->numParam ; i++ ) {
-				param.setNum( cmd->params[ i ] );
-				str += param;
-				str += " ";
-			}
-			cerr << str.toAscii().data() << endl;
-		}
-	}
-	return elements;
-}
-
-void WMFImport::finishCmdParsing( PageItem* item )
-{
-	QTransform gcm  = m_context.worldMatrix();
-	double coeff1 = sqrt(gcm.m11() * gcm.m11() + gcm.m12() * gcm.m12());
-	double coeff2 = sqrt(gcm.m21() * gcm.m21() + gcm.m22() * gcm.m22());
-	if( item->asImageFrame() )
-	{
-		item->moveBy(gcm.dx(), gcm.dy());
-		item->setWidthHeight(item->width() * gcm.m11(), item->height() * gcm.m22());
-		item->setLineWidth(qMax(item->lineWidth() * (coeff1 + coeff2) / 2.0, 0.25));
-		if (item->PictureIsAvailable)
-			item->setImageXYScale(item->width() / item->pixm.width(), item->height() / item->pixm.height());
-	}
-	else if( item->asTextFrame() )
-	{
-		item->setLineWidth(qMax(item->lineWidth() * (coeff1 + coeff2) / 2.0, 0.25));
-	}
-	else
-	{
-		item->ClipEdited = true;
-		item->FrameType = 3;
-		item->PoLine.map(gcm);
-		item->setLineWidth(qMax(item->lineWidth() * (coeff1 + coeff2) / 2.0, 0.25));
-		FPoint wh = getMaxClipF(&item->PoLine);
-		item->setWidthHeight(wh.x(), wh.y());
-		m_Doc->AdjustItemSize(item);
-	}
-	item->setRedrawBounding();
-	item->OwnPage   = m_Doc->OnPage(item);
-	item->PLineEnd  = m_context.pen().capStyle();
-	item->PLineJoin = m_context.pen().joinStyle();
-	item->setTextFlowMode(PageItem::TextFlowDisabled);
-	//item->DashOffset = gc->dashOffset;
-	//item->DashValues = gc->dashArray;
-}
-
-void WMFImport::setWindowOrg( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setWindowOrg( params[ 1 ], params[ 0 ] );
-}
-
-void WMFImport::setWindowExt( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setWindowExt( params[ 1 ], params[ 0 ] );
-}
-
-void WMFImport::lineTo( QList<PageItem*>& items, long, short* params )
-{
-	double BaseX = m_Doc->currentPage()->xOffset();
-	double BaseY = m_Doc->currentPage()->yOffset();
-	QPoint currentPos = m_context.position();
-	bool   doStroke = (m_context.pen().style() != Qt::NoPen);
-	if (doStroke)
-	{
-		double x1 = currentPos.x();
-		double y1 = currentPos.y();
-		double x2 = params[1];
-		double y2 = params[0];
-		double  lineWidth = m_context.pen().width();
-		QString lineColor = importColor(m_context.pen().color());
-		int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, CommonStrings::None, lineColor, true);
-		PageItem* ite = m_Doc->Items->at(z);
-		ite->PoLine.resize(4);
-		ite->PoLine.setPoint(0, FPoint(x1, y1));
-		ite->PoLine.setPoint(1, FPoint(x1, y1));
-		ite->PoLine.setPoint(2, FPoint(x2, y2));
-		ite->PoLine.setPoint(3, FPoint(x2, y2));
-		finishCmdParsing(ite);
-		items.append(ite);
-	}
-	m_context.setPosition( QPoint(params[1], params[0]) );
-}
-
-void WMFImport::moveTo( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setPosition( QPoint(params[1], params[0]) );
-}
-
-void WMFImport::ellipse( QList<PageItem*>& items, long, short* params )
-{
-	double BaseX = m_Doc->currentPage()->xOffset();
-	double BaseY = m_Doc->currentPage()->yOffset();
-	double rx = (params[ 1 ] - params[ 3 ]) / 2.0;
-	double ry = (params[ 0 ] - params[ 2 ]) / 2.0;
-	double px = (params[ 1 ] + params[ 3 ]) / 2.0 - rx;
-	double py = (params[ 0 ] + params[ 2 ]) / 2.0 - ry;
-	bool   doFill = m_context.brush().style() != Qt::NoBrush;
-	bool   doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, BaseX, BaseY, rx * 2.0, ry * 2.0, lineWidth, fillColor, strokeColor, true);
-	PageItem* ite = m_Doc->Items->at(z);
-	QTransform mm(1.0, 0.0, 0.0, 1.0, px, py);
-	ite->PoLine.map(mm);
-	finishCmdParsing(ite);
-	items.append(ite);
-}
-
-void WMFImport::polygon( QList<PageItem*>& items, long, short* params )
-{
-	//cerr << "WMFImport::polygon unimplemented" << endl;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doFill = m_context.brush().style() != Qt::NoBrush;
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	FPointArray paramPoints = pointsFromParam( params[0], &params[1] );
-	FPointArray points      = pointsToPolyline( paramPoints, true );
-	if( paramPoints.size() > 0 )
-	{
-		int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
-		PageItem* ite = m_Doc->Items->at(z);
-		ite->PoLine = points;
-		ite->fillRule = !m_context.windingFill();
-		finishCmdParsing(ite);
-		items.append(ite);
-	}
-}
-
-void WMFImport::polyPolygon( QList<PageItem*>& items, long num, short* params )
-{
-	int numPolys   = params[0];
-	int pointIndex = params[0] + 1;
-	for (int i = 0; i < numPolys; ++i)
-	{
-		short  numPoints  = params[i + 1];
-		short* paramArray = new short[1 + 2 * numPoints];
-		paramArray[0] = numPoints;
-		memcpy(&paramArray[1], &params[pointIndex], 2 * numPoints * sizeof(short));
-		polygon(items, num, paramArray);
-		delete[] paramArray;
-		pointIndex += (2 * numPoints);
-	}
-}
-
-void WMFImport::polyline( QList<PageItem*>& items, long, short* params )
-{
-	//cerr << "WMFImport::polyline unimplemented" << endl;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	FPointArray paramPoints = pointsFromParam( params[0], &params[1] );
-	FPointArray points      = pointsToPolyline( paramPoints, false );
-	if( paramPoints.size() > 0 )
-	{
-		int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
-		PageItem* ite = m_Doc->Items->at(z);
-		ite->PoLine = points;
-		finishCmdParsing(ite);
-		items.append(ite);
-	}
-}
-
-void WMFImport::rectangle( QList<PageItem*>& items, long, short* params )
-{
-	//cerr << "WMFImport::rectangle unimplemented" << endl;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doFill = m_context.brush().style() != Qt::NoBrush;
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	double x = ((params[3] - params[1]) > 0) ? params[1] : params[3];
-	double y = ((params[2] - params[0]) > 0) ? params[0] : params[2];
-	double width  = fabs((double) params[3] - params[1]);
-	double height = fabs((double) params[2] - params[0]);
-	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, BaseX, BaseY, width, height, lineWidth, fillColor, strokeColor, true);
-	PageItem* ite = m_Doc->Items->at(z);
-	QTransform mm(1.0, 0.0, 0.0, 1.0, x, y);
-	ite->PoLine.map(mm);
-	finishCmdParsing(ite);
-	items.append(ite);
-}
-
-void WMFImport::roundRect( QList<PageItem*>& items, long, short* params )
-{
-	//cerr << "WMFImport::roundRect unimplemented" << endl;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doFill = m_context.brush().style() != Qt::NoBrush;
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	double x = ((params[5] - params[3]) > 0) ? params[3] : params[5];
-	double y = ((params[4] - params[2]) > 0) ? params[2] : params[4];
-	double width  = fabs((double) params[5] - params[3]);
-	double height = fabs((double) params[4] - params[2]);
-	double rx     = params[1] / 2.0;
-	double ry     = params[0] / 2.0;
-	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, BaseX, BaseY, width, height, lineWidth, fillColor, strokeColor, true);
-	PageItem* ite = m_Doc->Items->at(z);
-	if ((rx != 0.0) || (ry != 0.0))
-	{
-		ite->setCornerRadius(qMax(rx, ry));
-		ite->SetFrameRound();
-		m_Doc->setRedrawBounding(ite);
-	}
-	QTransform mm(1.0, 0.0, 0.0, 1.0, x, y);
-	ite->PoLine.map(mm);
-	finishCmdParsing(ite);
-	items.append(ite);
-}
-
-void WMFImport::arc( QList<PageItem*>& items, long, short* params )
-{
-	FPointArray  pointArray;
-	QPainterPath painterPath;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	double  angleStart, angleLength;
-	double  x = ((params[7] - params[5]) > 0) ? params[5] : params[7];
-	double  y = ((params[6] - params[4]) > 0) ? params[4] : params[6];
-	double  xCenter = (params[5] + params[7]) / 2.0;
-	double  yCenter = (params[4] + params[6]) / 2.0;
-	double  xWidth  =  fabs((double) params[5] - params[7]);
-	double  yHeight =  fabs((double) params[4] - params[6]);
-	pointsToAngle(params[3] - xCenter, yCenter - params[2], params[1] - xCenter, yCenter - params[0], angleStart, angleLength);
-	painterPath.arcMoveTo(x, y, xWidth, yHeight, angleStart);
-	painterPath.arcTo(x, y, xWidth, yHeight, angleStart, angleLength);
-	pointArray.fromQPainterPath(painterPath);
-	if( pointArray.size() > 0 )
-	{
-		int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
-		PageItem* ite = m_Doc->Items->at(z);
-		ite->PoLine = pointArray;
-		finishCmdParsing(ite);
-		items.append(ite);
-	}
-}
-
-void WMFImport::chord( QList<PageItem*>& items, long, short* params )
-{
-	QPointF      firstPoint;
-	FPointArray  pointArray;
-	QPainterPath painterPath;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doFill   = m_context.brush().style() != Qt::NoBrush;
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	double  angleStart, angleLength;
-	double  x = ((params[7] - params[5]) > 0) ? params[5] : params[7];
-	double  y = ((params[6] - params[4]) > 0) ? params[4] : params[6];
-	double  xCenter = (params[5] + params[7]) / 2.0;
-	double  yCenter = (params[4] + params[6]) / 2.0;
-	double  xWidth  =  fabs((double) params[5] - params[7]);
-	double  yHeight =  fabs((double) params[4] - params[6]);
-	pointsToAngle(params[3] - xCenter, yCenter - params[2], params[1] - xCenter, yCenter - params[0], angleStart, angleLength);
-	painterPath.arcMoveTo(x, y, xWidth, yHeight, angleStart);
-	firstPoint = painterPath.currentPosition();
-	painterPath.arcTo (x, y, xWidth, yHeight, angleStart, angleLength);
-	painterPath.lineTo(firstPoint);
-	pointArray.fromQPainterPath(painterPath);
-	if( pointArray.size() > 0 )
-	{
-		int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
-		PageItem* ite = m_Doc->Items->at(z);
-		ite->PoLine = pointArray;
-		finishCmdParsing(ite);
-		items.append(ite);
-	}
-}
-
-void WMFImport::pie( QList<PageItem*>& items, long, short* params )
-{
-	QPointF      firstPoint;
-	FPointArray  pointArray;
-	QPainterPath painterPath;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-	bool    doFill   = m_context.brush().style() != Qt::NoBrush;
-	bool    doStroke = m_context.pen().style() != Qt::NoPen;
-	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
-	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
-	double  lineWidth   = m_context.pen().width();
-	if (doStroke && lineWidth <= 0.0 )
-		lineWidth = 1.0;
-	double  angleStart, angleLength;
-	double  x = ((params[7] - params[5]) > 0) ? params[5] : params[7];
-	double  y = ((params[6] - params[4]) > 0) ? params[4] : params[6];
-	double  xCenter = (params[5] + params[7]) / 2.0;
-	double  yCenter = (params[4] + params[6]) / 2.0;
-	double  xWidth  =  fabs((double) params[5] - params[7]);
-	double  yHeight =  fabs((double) params[4] - params[6]);
-	pointsToAngle(params[3] - xCenter, yCenter - params[2], params[1] - xCenter, yCenter - params[0], angleStart, angleLength);
-	painterPath.arcMoveTo(x,y, xWidth, yHeight, angleStart);
-	firstPoint = painterPath.currentPosition();
-	painterPath.arcTo (x, y, xWidth, yHeight, angleStart, angleLength);
-	painterPath.lineTo(xCenter, yCenter);
-	painterPath.lineTo(firstPoint);
-	pointArray.fromQPainterPath(painterPath);
-	if( pointArray.size() > 0 )
-	{
-		int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
-		PageItem* ite = m_Doc->Items->at(z);
-		ite->PoLine = pointArray;
-		finishCmdParsing(ite);
-		items.append(ite);
-	}
-}
-
-void WMFImport::setPolyFillMode( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setWindingFill( params[0] );
-}
-
-void WMFImport::setBkColor( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setBackgroundColor( colorFromParam( params ) );
-}
-
-void WMFImport::setBkMode( QList<PageItem*>& /*items*/, long, short* params )
-{
-	if ( params[ 0 ]==1 ) 
-		m_context.setBackgroundMode( Qt::TransparentMode );
-	else 
-		m_context.setBackgroundMode( Qt::OpaqueMode );
-}
-
-void WMFImport::saveDC( QList<PageItem*>& /*items*/, long, short* )
-{
-	m_context.save();
-}
-
-void WMFImport::restoreDC( QList<PageItem*>& /*items*/, long, short *params )
-{
-	for ( int i=0; i > params[ 0 ] ; i-- )
-		m_context.restore();
-}
-
-void WMFImport::intersectClipRect( QList<PageItem*>& /*items*/, long, short* /*params*/ )
-{
-	cerr << "WMFImport::intersectClipRect unimplemented" << endl;
-}
-
-void WMFImport::excludeClipRect( QList<PageItem*>& /*items*/, long, short* /*params*/ )
-{
-	cerr << "WMFImport::excludeClipRect unimplemented" << endl;
-}
-
-void WMFImport::setTextColor( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setTextColor( colorFromParam(params) );
-}
-
-void WMFImport::setTextAlign( QList<PageItem*>& /*items*/, long, short* params )
-{
-	m_context.setTextAlign(params[ 0 ]);
-}
-
-void WMFImport::textOut( QList<PageItem*>& items, long num, short* params )
-{
-	short *copyParm = new short[num + 1];
-
-	// re-order parameters
-	int idxOffset = (params[0] / 2) + 1 + (params[0] & 1);
-	copyParm[0] = params[idxOffset];
-	copyParm[1] = params[idxOffset + 1];
-	copyParm[2] = params[0];
-	copyParm[3] = 0;
-	memcpy( &copyParm[4], &params[1], params[0] );
-
-	extTextOut(items, num + 1, copyParm );
-	delete [] copyParm;
-}
-
-void WMFImport::extTextOut( QList<PageItem*>& items, long num, short* params )
-{
-	QString    textString;
-	double  BaseX = m_Doc->currentPage()->xOffset();
-	double  BaseY = m_Doc->currentPage()->yOffset();
-
-	if (params[3] & 0x0010) // ETO_GLYPH_INDEX
-	{
-		cerr << "WMFImport::extTextOut: ETO_GLYPH_INDEX option not supported " << endl;
-		unsupported = true;
-		return;
-	}
-
-	// ETO_CLIPPED flag add 4 parameters
-	char* ptStr = (params[3] & 0x0004) ? ((char*)&params[8]) : ((char*)&params[4]);
-	QByteArray textArray( ptStr, params[2] );
-	
-	QTextCodec* codec = codecFromCharset( m_context.textCharSet() );
-	if (codec)
-		textString = codec->toUnicode(textArray);
-	else if ( m_context.textCharSet() == SYMBOL_CHARSET )
-		textString = symbolToUnicode(textArray);
-	else
-		textString = QString::fromLocal8Bit(textArray.data());
-
-	QFontMetrics fm( m_context.font() );
-	int width  = fm.width(textString) + fm.descent();  // because fm.width(text) isn't rigth with Italic text
-	/*int height = fm.height();
-	int ascent = fm.ascent();*/
-
-	double startX = params[1], startY = params[0];
-	int    textAlign    = m_context.textAlign();
-	double textRotation = m_context.textRotation();
-	if ( textAlign & 0x01 ) {       // (left, top) position = current logical position
-		QPoint pos = m_context.position();
-		startX = pos.x();
-		startY = pos.y();
-	}
-
-	m_context.save();
-	// A bit hacky but should be sufficient to have text not flipped
-	// top down in some wmfs (see cell.wmf sample from libwmf)
-	if ( m_context.worldMatrix().m22() < 0.0)
-	{
-		m_context.translate(startX, startY);
-		m_context.scale (1.0, -1.0);
-		m_context.translate( -startX, -startY);
-	}
-	if ( textRotation != 0.0) {
-		m_context.translate(startX, startY);
-		m_context.rotate ( textRotation );
-		m_context.translate( -startX, -startY);
-	}
-
-	if ( (textAlign & 0x04) && (textAlign & 0x02) ) // TA_CENTER 0x06
-		startX -= (width / 2);
-	else if ( textAlign & 0x02 ) // TA_RIGHT 0x02
-		startX -= width;
-	if ( textAlign == 0 ) // TA_TOP                       
-		startY += fm.ascent();
-
-	bool eto_empty = (params[3] == 0);
-	bool eto_clipped_set = (params[3] & 0x0004);
-	bool eto_pdy_set     = (params[3] & 0x2000);
-
-	int  idxOffset = (params[ 2 ] / 2) + 4 + (params[ 2 ] & 1) + (eto_clipped_set ? 4 : 0);
-	int  minParams = eto_pdy_set ? (idxOffset + 2 * (params[2] - 1)) : (idxOffset + params[2]);
-	bool useCharInterdistances = (num >= minParams) && (eto_empty || eto_pdy_set);
-	if ((params[2] > 1) && useCharInterdistances) 
-	{
-		double xpos  = startX;
-		double ypos  = startY;
-		double lineWidth = 0.0;
-		FPointArray textPath;
-		QString textColor = importColor( m_context.textColor() );
-		for (int index = 0; (index < params[2] && index < textString.length()); ++index) 
-		{
-			QPainterPath painterPath;
-			if (index > 0 && eto_pdy_set)
-			{
-				xpos += params[idxOffset + index * 2 - 1];
-				ypos += params[idxOffset + index * 2];
-			}
-			else if (index > 0)
-				xpos += params[idxOffset + index - 1];
-			painterPath.addText(xpos, ypos, m_context.font(), textString.at(index));
-			textPath.fromQPainterPath(painterPath);
-			if (textPath.size() > 0)
-			{
-				int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, textColor, CommonStrings::None, true);
-				PageItem* ite = m_Doc->Items->at(z);
-				ite->PoLine = textPath;
-				finishCmdParsing(ite);
-				items.append(ite);
-			}
-		}
-	}
-	else 
-	{
-		FPointArray textPath;
-		QString textColor = importColor( m_context.textColor() );
-		QPainterPath painterPath;
-		painterPath.addText( startX, startY, m_context.font(), textString );
-		textPath.fromQPainterPath(painterPath);
-		if (textPath.size() > 0)
-		{
-			double  lineWidth = 0.0;
-			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, textColor, CommonStrings::None, true);
-			PageItem* ite = m_Doc->Items->at(z);
-			ite->PoLine = textPath;
-			finishCmdParsing(ite);
-			items.append(ite);
-		}
-	}
-	m_context.restore();
-}
-
-void WMFImport::selectObject( QList<PageItem*>& /*items*/, long, short* params )
-{
-	int idx = params[ 0 ];
-	if ( idx >= 0 && idx < MAX_OBJHANDLE && m_ObjHandleTab[ idx ] )
-		m_ObjHandleTab[ idx ]->apply( m_context );
-}
-
-void WMFImport::deleteObject( QList<PageItem*>& /*items*/, long, short* params )
-{
-	deleteHandle( params[ 0 ] );
-}
-
-void WMFImport::createEmptyObject( QList<PageItem*>& /*items*/, long, short* )
-{
-	// allocation of an empty object (to keep object counting in sync)
-	WmfObjPenHandle* handle = new WmfObjPenHandle();
-	addHandle( handle );
-	cerr << "WMFImport: unimplemented createObject " << endl;
-}
-
-void WMFImport::createBrushIndirect( QList<PageItem*>& /*items*/, long, short* params )
-{
-	static Qt::BrushStyle hatchedStyleTab[] =
-	{
-		Qt::HorPattern,
-		Qt::FDiagPattern,
-		Qt::BDiagPattern,
-		Qt::CrossPattern,
-		Qt::DiagCrossPattern
-	};
-	static Qt::BrushStyle styleTab[] =
-	{ Qt::SolidPattern,
-	  Qt::NoBrush,
-	  Qt::FDiagPattern,   /* hatched */
-	  Qt::Dense4Pattern,  /* should be custom bitmap pattern */
-	  Qt::HorPattern,     /* should be BS_INDEXED (?) */
-	  Qt::VerPattern,     /* should be device-independent bitmap */
-	  Qt::Dense6Pattern,  /* should be device-independent packed-bitmap */
-	  Qt::Dense2Pattern,  /* should be BS_PATTERN8x8 */
-	  Qt::Dense3Pattern   /* should be device-independent BS_DIBPATTERN8x8 */
-	};
-	Qt::BrushStyle style;
-	short arg;
-	WmfObjBrushHandle* handle = new WmfObjBrushHandle();
-	addHandle( handle );
-
-	arg = params[0];
-	if ( arg == 2 )
-	{
-		arg = params[3];
-		if ( arg >= 0 && arg < 5 ) 
-			style = hatchedStyleTab[ arg ];
-		else
-		{
-			cerr << "WMFImport::createBrushIndirect: invalid hatched brush " << arg << endl;
-			style = Qt::SolidPattern;
-		}
-	}
-	else if ( arg >= 0 && arg < 9 )
-		style = styleTab[arg];
-	else
-	{
-		cerr << "WMFImport::createBrushIndirect: invalid brush " << arg << endl;
-		style = Qt::SolidPattern;
-	}
-	handle->brush.setStyle( style );
-	handle->brush.setColor( colorFromParam( params+1 ) );
-}
-
-void WMFImport::createPenIndirect( QList<PageItem*>& /*items*/, long, short* params )
-{
-	static Qt::PenStyle styleTab[] = { Qt::SolidLine, Qt::DashLine, Qt::DotLine, Qt::DashDotLine, Qt::DashDotDotLine,
-	  Qt::NoPen, Qt::SolidLine };
-	Qt::PenStyle style;
-	WmfObjPenHandle* handle = new WmfObjPenHandle();
-	addHandle( handle );
-
-	if ( params[0] >= 0 && params[0] < 6 ) 
-		style = styleTab[ params[0] ];
-	else
-	{
-		cerr << "WMFImport::createPenIndirect: invalid pen " << params[ 0 ] << endl;
-		style = Qt::SolidLine;
-	}
-
-	handle->pen.setStyle( style );
-	handle->pen.setWidth( params[1] );
-	handle->pen.setColor( colorFromParam( params+3 ) );
-	handle->pen.setCapStyle( Qt::RoundCap );
-}
-
-void WMFImport::createFontIndirect( QList<PageItem*>& /*items*/, long , short* params)
-{
-	WmfObjFontHandle* handle = new WmfObjFontHandle();
-	addHandle( handle );
-
-	QString family( (const char*)&params[ 9 ] );
-
-	handle->rotation = -params[ 2 ]  / 10; // text rotation (in 1/10 degree)
-	handle->font.setFamily( family );
-	handle->font.setStyleStrategy( QFont::PreferOutline );
-	handle->font.setFixedPitch( ((params[ 8 ] & 0x01) == 0) );
-	// TODO: investigation why some test case need -2. (size of font in logical point)
-	int fontSize = (params[0] != 0) ? (qAbs(params[0]) - 2) : 12;
-	handle->font.setPixelSize( fontSize );
-	handle->font.setWeight( (params[ 4 ] >> 3) );
-	handle->font.setItalic( (params[ 5 ] & 0x01) );
-	handle->font.setUnderline( (params[ 5 ] & 0x100) );
-	handle->font.setStrikeOut( (params[ 6 ] & 0x01) );
-	handle->charset = (params[ 6 ] & 0xFF00) >> 8;
-}
-
-void WMFImport::noop( QList<PageItem*>& /*items*/, long, short* )
-{
-}
-
-void WMFImport::end( QList<PageItem*>& /*items*/, long, short* )
-{
-	//cerr << "WMFImport::end unimplemented" << endl;
-}
-
-void WMFImport::addHandle( WmfObjHandle* handle )
-{
-	int idx;
-
-	for ( idx =0; idx < MAX_OBJHANDLE ; idx++ )
-		if ( m_ObjHandleTab[ idx ] == NULL )  break;
-
-	if ( idx < MAX_OBJHANDLE )
-		m_ObjHandleTab[ idx ] = handle;
-	else
-		cerr << "WMFImport error: handle table full !" << endl;
-}
-
-void WMFImport::deleteHandle( int idx )
-{
-	if ( idx >= 0 && idx < MAX_OBJHANDLE && m_ObjHandleTab[ idx ] )
-	{
-		delete m_ObjHandleTab[ idx ];
-		m_ObjHandleTab[ idx ] = NULL;
-	}
-}
-
-unsigned short WMFImport::calcCheckSum( WmfPlaceableHeader* apmfh )
-{
-	WORD16*  lpWord;
-	WORD16   wResult, i;
-
-	// Start with the first word
-	wResult = *( lpWord = ( WORD16* )( apmfh ) );
-	// XOR in each of the other 9 words
-	for( i=1; i<=9; i++ )
-	{
-		wResult ^= lpWord[ i ];
-	}
-	return wResult;
-}
-
-int WMFImport::findFunc( unsigned short aFunc ) const
-{
-	int i = 0;
-
-	for ( i=0; metaFuncTab[ i ].name; i++ )
-		if ( metaFuncTab[ i ].func == aFunc ) return i;
-
-	// here : unknown function
-	return i;
-}
-
-unsigned int WMFImport::toDWord( short* params )
-{
-	unsigned int l;
-#if !defined( WORDS_BIGENDIAN )
-	l = *( unsigned int* )( params );
-#else
-	char *bytes;
-	char swap[ 4 ];
-	bytes = ( char* )params;
-	swap[ 0 ] = bytes[ 2 ];
-	swap[ 1 ] = bytes[ 3 ];
-	swap[ 2 ] = bytes[ 0 ];
-	swap[ 3 ] = bytes[ 1 ];
-	l = *( unsigned int* )( swap );
-#endif
-	return l;
-}
+		m_Doc->view()->Deselect();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+		m_Doc->view()->updatesOn(false);
+	m_Doc->scMW()->setScriptRunning(true);
+	qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
+	//gc->Family = m_Doc->toolSettings.textFont;
+	m_Doc->PageColors.ensureDefaultColors();
+	//m_gc.push( gc );
+	QList<PageItem*> Elements = parseWmfCommands();
+	if (flags & LoadSavePlugin::lfCreateDoc)
+	{
+		m_Doc->documentInfo().setTitle(m_docTitle);
+		m_Doc->documentInfo().setComments(m_docDesc);
+	}
+	m_tmpSel->clear();
+	if (Elements.count() == 0)
+	{
+		importFailed = true;
+		if (importedColors.count() != 0)
+		{
+			for (int cd = 0; cd < importedColors.count(); cd++)
+			{
+				m_Doc->PageColors.remove(importedColors[cd]);
+			}
+		}
+	}
+	if (Elements.count() > 1)
+		m_Doc->groupObjectsList(Elements);
+	m_Doc->DoDrawing = true;
+	m_Doc->scMW()->setScriptRunning(false);
+	if (interactive)
+		m_Doc->setLoading(false);
+	qApp->setOverrideCursor(QCursor(Qt::ArrowCursor));
+	if ((Elements.count() > 0) && (!ret) && (interactive))
+	{
+		if (flags & LoadSavePlugin::lfScripted)
+		{
+			bool loadF = m_Doc->isLoading();
+			m_Doc->setLoading(false);
+			m_Doc->changed();
+			m_Doc->setLoading(loadF);
+			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+			{
+				m_Doc->m_Selection->delaySignalsOn();
+				for (int dre=0; dre<Elements.count(); ++dre)
+				{
+					m_Doc->m_Selection->addItem(Elements.at(dre), true);
+				}
+				m_Doc->m_Selection->delaySignalsOff();
+				m_Doc->m_Selection->setGroupRect();
+				m_Doc->view()->updatesOn(true);
+			}
+			importCanceled = false;
+		}
+		else
+		{
+			m_Doc->DragP = true;
+			m_Doc->DraggedElem = 0;
+			m_Doc->DragElements.clear();
+			m_Doc->m_Selection->delaySignalsOn();
+			for (int dre=0; dre<Elements.count(); ++dre)
+			{
+				m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
+				m_tmpSel->addItem(Elements.at(dre), true);
+			}
+			ScriXmlDoc *ss = new ScriXmlDoc();
+			m_tmpSel->setGroupRect();
+			ScElemMimeData* md = new ScElemMimeData();
+			md->setScribusElem(ss->WriteElem(m_Doc, m_tmpSel));
+			delete ss;
+/*#ifndef QT_MAC*/
+// see #2526
+			m_Doc->itemSelection_DeleteItem(m_tmpSel);
+/*#endif*/
+			m_Doc->view()->updatesOn(true);
+			m_Doc->m_Selection->delaySignalsOff();
+			// We must copy the TransationSettings object as it is owned
+			// by handleObjectImport method afterwards
+			TransactionSettings* transacSettings = new TransactionSettings(trSettings);
+			m_Doc->view()->handleObjectImport(md, transacSettings);
+			m_Doc->DragP = false;
+			m_Doc->DraggedElem = 0;
+			m_Doc->DragElements.clear();
+		}
+	}
+	else
+	{
+		bool loadF = m_Doc->isLoading();
+		m_Doc->setLoading(false);
+		m_Doc->changed();
+		m_Doc->reformPages();
+		if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+			m_Doc->view()->updatesOn(true);
+		m_Doc->setLoading(loadF);
+	}
+	return true;
+}
+
+QList<PageItem*> WMFImport::parseWmfCommands(void)
+{
+	int idx, i;
+	const WmfCmd* cmd;
+	QList<PageItem*> elements;
+
+	m_context.reset();
+
+	if ( !m_Valid )  return elements;
+
+	if ( m_ObjHandleTab ) delete[] m_ObjHandleTab;
+	m_ObjHandleTab = new WmfObjHandle* [ MAX_OBJHANDLE ];
+	for ( i = MAX_OBJHANDLE-1; i >= 0; i-- )
+		m_ObjHandleTab[ i ] = NULL;
+
+	if ( WMFIMPORT_DEBUG )  {
+		cerr << "Bounding box : " << m_BBox.left() << " " << m_BBox.top() << " " << m_BBox.right() << " " << m_BBox.bottom() << endl;
+	}
+
+	double scale  = (m_Dpi > 0) ? 72.0 / m_Dpi : 0.05;
+	m_context.setViewportOrg( 0, 0 );
+	m_context.setViewportExt( m_BBox.width() * scale, m_BBox.height() * scale );
+	m_context.setWindowOrg( m_BBox.left(), m_BBox.bottom() );
+	m_context.setWindowExt( m_BBox.width(), m_BBox.height() );
+
+	for (int index = 0; index < m_commands.count(); ++index)
+	{
+		cmd = m_commands.at(index);
+		idx = cmd->funcIndex;
+		( this->*metaFuncTab[ idx ].method )( elements, cmd->numParam, cmd->params );
+
+		if ( WMFIMPORT_DEBUG )  {
+			QString str = "", param;
+			if ( metaFuncTab[ idx ].name == NULL ) {
+				str += "UNKNOWN ";
+			}
+			if ( metaFuncTab[ idx ].method == &WMFImport::noop ) {
+				str += "UNIMPLEMENTED ";
+			}
+			str += metaFuncTab[ idx ].name;
+			str += " : ";
+
+			for ( i=0 ; i < cmd->numParam ; i++ ) {
+				param.setNum( cmd->params[ i ] );
+				str += param;
+				str += " ";
+			}
+			cerr << str.toAscii().data() << endl;
+		}
+	}
+	return elements;
+}
+
+void WMFImport::finishCmdParsing( PageItem* item )
+{
+	QTransform gcm  = m_context.worldMatrix();
+	double coeff1 = sqrt(gcm.m11() * gcm.m11() + gcm.m12() * gcm.m12());
+	double coeff2 = sqrt(gcm.m21() * gcm.m21() + gcm.m22() * gcm.m22());
+	if( item->asImageFrame() )
+	{
+		item->moveBy(gcm.dx(), gcm.dy());
+		item->setWidthHeight(item->width() * gcm.m11(), item->height() * gcm.m22());
+		item->setLineWidth(qMax(item->lineWidth() * (coeff1 + coeff2) / 2.0, 0.25));
+		if (item->PictureIsAvailable)
+			item->setImageXYScale(item->width() / item->pixm.width(), item->height() / item->pixm.height());
+	}
+	else if( item->asTextFrame() )
+	{
+		item->setLineWidth(qMax(item->lineWidth() * (coeff1 + coeff2) / 2.0, 0.25));
+	}
+	else
+	{
+		item->ClipEdited = true;
+		item->FrameType = 3;
+		item->PoLine.map(gcm);
+		item->setLineWidth(qMax(item->lineWidth() * (coeff1 + coeff2) / 2.0, 0.25));
+		FPoint wh = getMaxClipF(&item->PoLine);
+		item->setWidthHeight(wh.x(), wh.y());
+		m_Doc->AdjustItemSize(item);
+	}
+	item->setRedrawBounding();
+	item->OwnPage   = m_Doc->OnPage(item);
+	item->PLineEnd  = m_context.pen().capStyle();
+	item->PLineJoin = m_context.pen().joinStyle();
+	item->setTextFlowMode(PageItem::TextFlowDisabled);
+	//item->DashOffset = gc->dashOffset;
+	//item->DashValues = gc->dashArray;
+}
+
+void WMFImport::setWindowOrg( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setWindowOrg( params[ 1 ], params[ 0 ] );
+}
+
+void WMFImport::setWindowExt( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setWindowExt( params[ 1 ], params[ 0 ] );
+}
+
+void WMFImport::lineTo( QList<PageItem*>& items, long, short* params )
+{
+	double BaseX = m_Doc->currentPage()->xOffset();
+	double BaseY = m_Doc->currentPage()->yOffset();
+	QPoint currentPos = m_context.position();
+	bool   doStroke = (m_context.pen().style() != Qt::NoPen);
+	if (doStroke)
+	{
+		double x1 = currentPos.x();
+		double y1 = currentPos.y();
+		double x2 = params[1];
+		double y2 = params[0];
+		double  lineWidth = m_context.pen().width();
+		QString lineColor = importColor(m_context.pen().color());
+		int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, CommonStrings::None, lineColor, true);
+		PageItem* ite = m_Doc->Items->at(z);
+		ite->PoLine.resize(4);
+		ite->PoLine.setPoint(0, FPoint(x1, y1));
+		ite->PoLine.setPoint(1, FPoint(x1, y1));
+		ite->PoLine.setPoint(2, FPoint(x2, y2));
+		ite->PoLine.setPoint(3, FPoint(x2, y2));
+		finishCmdParsing(ite);
+		items.append(ite);
+	}
+	m_context.setPosition( QPoint(params[1], params[0]) );
+}
+
+void WMFImport::moveTo( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setPosition( QPoint(params[1], params[0]) );
+}
+
+void WMFImport::ellipse( QList<PageItem*>& items, long, short* params )
+{
+	double BaseX = m_Doc->currentPage()->xOffset();
+	double BaseY = m_Doc->currentPage()->yOffset();
+	double rx = (params[ 1 ] - params[ 3 ]) / 2.0;
+	double ry = (params[ 0 ] - params[ 2 ]) / 2.0;
+	double px = (params[ 1 ] + params[ 3 ]) / 2.0 - rx;
+	double py = (params[ 0 ] + params[ 2 ]) / 2.0 - ry;
+	bool   doFill = m_context.brush().style() != Qt::NoBrush;
+	bool   doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, BaseX, BaseY, rx * 2.0, ry * 2.0, lineWidth, fillColor, strokeColor, true);
+	PageItem* ite = m_Doc->Items->at(z);
+	QTransform mm(1.0, 0.0, 0.0, 1.0, px, py);
+	ite->PoLine.map(mm);
+	finishCmdParsing(ite);
+	items.append(ite);
+}
+
+void WMFImport::polygon( QList<PageItem*>& items, long, short* params )
+{
+	//cerr << "WMFImport::polygon unimplemented" << endl;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doFill = m_context.brush().style() != Qt::NoBrush;
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	FPointArray paramPoints = pointsFromParam( params[0], &params[1] );
+	FPointArray points      = pointsToPolyline( paramPoints, true );
+	if( paramPoints.size() > 0 )
+	{
+		int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
+		PageItem* ite = m_Doc->Items->at(z);
+		ite->PoLine = points;
+		ite->fillRule = !m_context.windingFill();
+		finishCmdParsing(ite);
+		items.append(ite);
+	}
+}
+
+void WMFImport::polyPolygon( QList<PageItem*>& items, long num, short* params )
+{
+	int numPolys   = params[0];
+	int pointIndex = params[0] + 1;
+	for (int i = 0; i < numPolys; ++i)
+	{
+		short  numPoints  = params[i + 1];
+		short* paramArray = new short[1 + 2 * numPoints];
+		paramArray[0] = numPoints;
+		memcpy(&paramArray[1], &params[pointIndex], 2 * numPoints * sizeof(short));
+		polygon(items, num, paramArray);
+		delete[] paramArray;
+		pointIndex += (2 * numPoints);
+	}
+}
+
+void WMFImport::polyline( QList<PageItem*>& items, long, short* params )
+{
+	//cerr << "WMFImport::polyline unimplemented" << endl;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	FPointArray paramPoints = pointsFromParam( params[0], &params[1] );
+	FPointArray points      = pointsToPolyline( paramPoints, false );
+	if( paramPoints.size() > 0 )
+	{
+		int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
+		PageItem* ite = m_Doc->Items->at(z);
+		ite->PoLine = points;
+		finishCmdParsing(ite);
+		items.append(ite);
+	}
+}
+
+void WMFImport::rectangle( QList<PageItem*>& items, long, short* params )
+{
+	//cerr << "WMFImport::rectangle unimplemented" << endl;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doFill = m_context.brush().style() != Qt::NoBrush;
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	double x = ((params[3] - params[1]) > 0) ? params[1] : params[3];
+	double y = ((params[2] - params[0]) > 0) ? params[0] : params[2];
+	double width  = fabs((double) params[3] - params[1]);
+	double height = fabs((double) params[2] - params[0]);
+	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, BaseX, BaseY, width, height, lineWidth, fillColor, strokeColor, true);
+	PageItem* ite = m_Doc->Items->at(z);
+	QTransform mm(1.0, 0.0, 0.0, 1.0, x, y);
+	ite->PoLine.map(mm);
+	finishCmdParsing(ite);
+	items.append(ite);
+}
+
+void WMFImport::roundRect( QList<PageItem*>& items, long, short* params )
+{
+	//cerr << "WMFImport::roundRect unimplemented" << endl;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doFill = m_context.brush().style() != Qt::NoBrush;
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	double x = ((params[5] - params[3]) > 0) ? params[3] : params[5];
+	double y = ((params[4] - params[2]) > 0) ? params[2] : params[4];
+	double width  = fabs((double) params[5] - params[3]);
+	double height = fabs((double) params[4] - params[2]);
+	double rx     = params[1] / 2.0;
+	double ry     = params[0] / 2.0;
+	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, BaseX, BaseY, width, height, lineWidth, fillColor, strokeColor, true);
+	PageItem* ite = m_Doc->Items->at(z);
+	if ((rx != 0.0) || (ry != 0.0))
+	{
+		ite->setCornerRadius(qMax(rx, ry));
+		ite->SetFrameRound();
+		m_Doc->setRedrawBounding(ite);
+	}
+	QTransform mm(1.0, 0.0, 0.0, 1.0, x, y);
+	ite->PoLine.map(mm);
+	finishCmdParsing(ite);
+	items.append(ite);
+}
+
+void WMFImport::arc( QList<PageItem*>& items, long, short* params )
+{
+	FPointArray  pointArray;
+	QPainterPath painterPath;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	double  angleStart, angleLength;
+	double  x = ((params[7] - params[5]) > 0) ? params[5] : params[7];
+	double  y = ((params[6] - params[4]) > 0) ? params[4] : params[6];
+	double  xCenter = (params[5] + params[7]) / 2.0;
+	double  yCenter = (params[4] + params[6]) / 2.0;
+	double  xWidth  =  fabs((double) params[5] - params[7]);
+	double  yHeight =  fabs((double) params[4] - params[6]);
+	pointsToAngle(params[3] - xCenter, yCenter - params[2], params[1] - xCenter, yCenter - params[0], angleStart, angleLength);
+	painterPath.arcMoveTo(x, y, xWidth, yHeight, angleStart);
+	painterPath.arcTo(x, y, xWidth, yHeight, angleStart, angleLength);
+	pointArray.fromQPainterPath(painterPath);
+	if( pointArray.size() > 0 )
+	{
+		int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
+		PageItem* ite = m_Doc->Items->at(z);
+		ite->PoLine = pointArray;
+		finishCmdParsing(ite);
+		items.append(ite);
+	}
+}
+
+void WMFImport::chord( QList<PageItem*>& items, long, short* params )
+{
+	QPointF      firstPoint;
+	FPointArray  pointArray;
+	QPainterPath painterPath;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doFill   = m_context.brush().style() != Qt::NoBrush;
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	double  angleStart, angleLength;
+	double  x = ((params[7] - params[5]) > 0) ? params[5] : params[7];
+	double  y = ((params[6] - params[4]) > 0) ? params[4] : params[6];
+	double  xCenter = (params[5] + params[7]) / 2.0;
+	double  yCenter = (params[4] + params[6]) / 2.0;
+	double  xWidth  =  fabs((double) params[5] - params[7]);
+	double  yHeight =  fabs((double) params[4] - params[6]);
+	pointsToAngle(params[3] - xCenter, yCenter - params[2], params[1] - xCenter, yCenter - params[0], angleStart, angleLength);
+	painterPath.arcMoveTo(x, y, xWidth, yHeight, angleStart);
+	firstPoint = painterPath.currentPosition();
+	painterPath.arcTo (x, y, xWidth, yHeight, angleStart, angleLength);
+	painterPath.lineTo(firstPoint);
+	pointArray.fromQPainterPath(painterPath);
+	if( pointArray.size() > 0 )
+	{
+		int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
+		PageItem* ite = m_Doc->Items->at(z);
+		ite->PoLine = pointArray;
+		finishCmdParsing(ite);
+		items.append(ite);
+	}
+}
+
+void WMFImport::pie( QList<PageItem*>& items, long, short* params )
+{
+	QPointF      firstPoint;
+	FPointArray  pointArray;
+	QPainterPath painterPath;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+	bool    doFill   = m_context.brush().style() != Qt::NoBrush;
+	bool    doStroke = m_context.pen().style() != Qt::NoPen;
+	QString fillColor   = doFill ? importColor( m_context.brush().color() ) : CommonStrings::None;
+	QString strokeColor = doStroke ? importColor( m_context.pen().color() ) : CommonStrings::None;
+	double  lineWidth   = m_context.pen().width();
+	if (doStroke && lineWidth <= 0.0 )
+		lineWidth = 1.0;
+	double  angleStart, angleLength;
+	double  x = ((params[7] - params[5]) > 0) ? params[5] : params[7];
+	double  y = ((params[6] - params[4]) > 0) ? params[4] : params[6];
+	double  xCenter = (params[5] + params[7]) / 2.0;
+	double  yCenter = (params[4] + params[6]) / 2.0;
+	double  xWidth  =  fabs((double) params[5] - params[7]);
+	double  yHeight =  fabs((double) params[4] - params[6]);
+	pointsToAngle(params[3] - xCenter, yCenter - params[2], params[1] - xCenter, yCenter - params[0], angleStart, angleLength);
+	painterPath.arcMoveTo(x,y, xWidth, yHeight, angleStart);
+	firstPoint = painterPath.currentPosition();
+	painterPath.arcTo (x, y, xWidth, yHeight, angleStart, angleLength);
+	painterPath.lineTo(xCenter, yCenter);
+	painterPath.lineTo(firstPoint);
+	pointArray.fromQPainterPath(painterPath);
+	if( pointArray.size() > 0 )
+	{
+		int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, fillColor, strokeColor, true);
+		PageItem* ite = m_Doc->Items->at(z);
+		ite->PoLine = pointArray;
+		finishCmdParsing(ite);
+		items.append(ite);
+	}
+}
+
+void WMFImport::setPolyFillMode( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setWindingFill( params[0] );
+}
+
+void WMFImport::setBkColor( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setBackgroundColor( colorFromParam( params ) );
+}
+
+void WMFImport::setBkMode( QList<PageItem*>& /*items*/, long, short* params )
+{
+	if ( params[ 0 ]==1 ) 
+		m_context.setBackgroundMode( Qt::TransparentMode );
+	else 
+		m_context.setBackgroundMode( Qt::OpaqueMode );
+}
+
+void WMFImport::saveDC( QList<PageItem*>& /*items*/, long, short* )
+{
+	m_context.save();
+}
+
+void WMFImport::restoreDC( QList<PageItem*>& /*items*/, long, short *params )
+{
+	for ( int i=0; i > params[ 0 ] ; i-- )
+		m_context.restore();
+}
+
+void WMFImport::intersectClipRect( QList<PageItem*>& /*items*/, long, short* /*params*/ )
+{
+	cerr << "WMFImport::intersectClipRect unimplemented" << endl;
+}
+
+void WMFImport::excludeClipRect( QList<PageItem*>& /*items*/, long, short* /*params*/ )
+{
+	cerr << "WMFImport::excludeClipRect unimplemented" << endl;
+}
+
+void WMFImport::setTextColor( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setTextColor( colorFromParam(params) );
+}
+
+void WMFImport::setTextAlign( QList<PageItem*>& /*items*/, long, short* params )
+{
+	m_context.setTextAlign(params[ 0 ]);
+}
+
+void WMFImport::textOut( QList<PageItem*>& items, long num, short* params )
+{
+	short *copyParm = new short[num + 1];
+
+	// re-order parameters
+	int idxOffset = (params[0] / 2) + 1 + (params[0] & 1);
+	copyParm[0] = params[idxOffset];
+	copyParm[1] = params[idxOffset + 1];
+	copyParm[2] = params[0];
+	copyParm[3] = 0;
+	memcpy( &copyParm[4], &params[1], params[0] );
+
+	extTextOut(items, num + 1, copyParm );
+	delete [] copyParm;
+}
+
+void WMFImport::extTextOut( QList<PageItem*>& items, long num, short* params )
+{
+	QString    textString;
+	double  BaseX = m_Doc->currentPage()->xOffset();
+	double  BaseY = m_Doc->currentPage()->yOffset();
+
+	if (params[3] & 0x0010) // ETO_GLYPH_INDEX
+	{
+		cerr << "WMFImport::extTextOut: ETO_GLYPH_INDEX option not supported " << endl;
+		unsupported = true;
+		return;
+	}
+
+	// ETO_CLIPPED flag add 4 parameters
+	char* ptStr = (params[3] & 0x0004) ? ((char*)&params[8]) : ((char*)&params[4]);
+	QByteArray textArray( ptStr, params[2] );
+	
+	QTextCodec* codec = codecFromCharset( m_context.textCharSet() );
+	if (codec)
+		textString = codec->toUnicode(textArray);
+	else if ( m_context.textCharSet() == SYMBOL_CHARSET )
+		textString = symbolToUnicode(textArray);
+	else
+		textString = QString::fromLocal8Bit(textArray.data());
+
+	QFontMetrics fm( m_context.font() );
+	int width  = fm.width(textString) + fm.descent();  // because fm.width(text) isn't rigth with Italic text
+	/*int height = fm.height();
+	int ascent = fm.ascent();*/
+
+	double startX = params[1], startY = params[0];
+	int    textAlign    = m_context.textAlign();
+	double textRotation = m_context.textRotation();
+	if ( textAlign & 0x01 ) {       // (left, top) position = current logical position
+		QPoint pos = m_context.position();
+		startX = pos.x();
+		startY = pos.y();
+	}
+
+	m_context.save();
+	// A bit hacky but should be sufficient to have text not flipped
+	// top down in some wmfs (see cell.wmf sample from libwmf)
+	if ( m_context.worldMatrix().m22() < 0.0)
+	{
+		m_context.translate(startX, startY);
+		m_context.scale (1.0, -1.0);
+		m_context.translate( -startX, -startY);
+	}
+	if ( textRotation != 0.0) {
+		m_context.translate(startX, startY);
+		m_context.rotate ( textRotation );
+		m_context.translate( -startX, -startY);
+	}
+
+	if ( (textAlign & 0x04) && (textAlign & 0x02) ) // TA_CENTER 0x06
+		startX -= (width / 2);
+	else if ( textAlign & 0x02 ) // TA_RIGHT 0x02
+		startX -= width;
+	if ( textAlign == 0 ) // TA_TOP                       
+		startY += fm.ascent();
+
+	bool eto_empty = (params[3] == 0);
+	bool eto_clipped_set = (params[3] & 0x0004);
+	bool eto_pdy_set     = (params[3] & 0x2000);
+
+	int  idxOffset = (params[ 2 ] / 2) + 4 + (params[ 2 ] & 1) + (eto_clipped_set ? 4 : 0);
+	int  minParams = eto_pdy_set ? (idxOffset + 2 * (params[2] - 1)) : (idxOffset + params[2]);
+	bool useCharInterdistances = (num >= minParams) && (eto_empty || eto_pdy_set);
+	if ((params[2] > 1) && useCharInterdistances) 
+	{
+		double xpos  = startX;
+		double ypos  = startY;
+		double lineWidth = 0.0;
+		FPointArray textPath;
+		QString textColor = importColor( m_context.textColor() );
+		for (int index = 0; (index < params[2] && index < textString.length()); ++index) 
+		{
+			QPainterPath painterPath;
+			if (index > 0 && eto_pdy_set)
+			{
+				xpos += params[idxOffset + index * 2 - 1];
+				ypos += params[idxOffset + index * 2];
+			}
+			else if (index > 0)
+				xpos += params[idxOffset + index - 1];
+			painterPath.addText(xpos, ypos, m_context.font(), textString.at(index));
+			textPath.fromQPainterPath(painterPath);
+			if (textPath.size() > 0)
+			{
+				int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, textColor, CommonStrings::None, true);
+				PageItem* ite = m_Doc->Items->at(z);
+				ite->PoLine = textPath;
+				finishCmdParsing(ite);
+				items.append(ite);
+			}
+		}
+	}
+	else 
+	{
+		FPointArray textPath;
+		QString textColor = importColor( m_context.textColor() );
+		QPainterPath painterPath;
+		painterPath.addText( startX, startY, m_context.font(), textString );
+		textPath.fromQPainterPath(painterPath);
+		if (textPath.size() > 0)
+		{
+			double  lineWidth = 0.0;
+			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, BaseX, BaseY, 10, 10, lineWidth, textColor, CommonStrings::None, true);
+			PageItem* ite = m_Doc->Items->at(z);
+			ite->PoLine = textPath;
+			finishCmdParsing(ite);
+			items.append(ite);
+		}
+	}
+	m_context.restore();
+}
+
+void WMFImport::selectObject( QList<PageItem*>& /*items*/, long, short* params )
+{
+	int idx = params[ 0 ];
+	if ( idx >= 0 && idx < MAX_OBJHANDLE && m_ObjHandleTab[ idx ] )
+		m_ObjHandleTab[ idx ]->apply( m_context );
+}
+
+void WMFImport::deleteObject( QList<PageItem*>& /*items*/, long, short* params )
+{
+	deleteHandle( params[ 0 ] );
+}
+
+void WMFImport::createEmptyObject( QList<PageItem*>& /*items*/, long, short* )
+{
+	// allocation of an empty object (to keep object counting in sync)
+	WmfObjPenHandle* handle = new WmfObjPenHandle();
+	addHandle( handle );
+	cerr << "WMFImport: unimplemented createObject " << endl;
+}
+
+void WMFImport::createBrushIndirect( QList<PageItem*>& /*items*/, long, short* params )
+{
+	static Qt::BrushStyle hatchedStyleTab[] =
+	{
+		Qt::HorPattern,
+		Qt::FDiagPattern,
+		Qt::BDiagPattern,
+		Qt::CrossPattern,
+		Qt::DiagCrossPattern
+	};
+	static Qt::BrushStyle styleTab[] =
+	{ Qt::SolidPattern,
+	  Qt::NoBrush,
+	  Qt::FDiagPattern,   /* hatched */
+	  Qt::Dense4Pattern,  /* should be custom bitmap pattern */
+	  Qt::HorPattern,     /* should be BS_INDEXED (?) */
+	  Qt::VerPattern,     /* should be device-independent bitmap */
+	  Qt::Dense6Pattern,  /* should be device-independent packed-bitmap */
+	  Qt::Dense2Pattern,  /* should be BS_PATTERN8x8 */
+	  Qt::Dense3Pattern   /* should be device-independent BS_DIBPATTERN8x8 */
+	};
+	Qt::BrushStyle style;
+	short arg;
+	WmfObjBrushHandle* handle = new WmfObjBrushHandle();
+	addHandle( handle );
+
+	arg = params[0];
+	if ( arg == 2 )
+	{
+		arg = params[3];
+		if ( arg >= 0 && arg < 5 ) 
+			style = hatchedStyleTab[ arg ];
+		else
+		{
+			cerr << "WMFImport::createBrushIndirect: invalid hatched brush " << arg << endl;
+			style = Qt::SolidPattern;
+		}
+	}
+	else if ( arg >= 0 && arg < 9 )
+		style = styleTab[arg];
+	else
+	{
+		cerr << "WMFImport::createBrushIndirect: invalid brush " << arg << endl;
+		style = Qt::SolidPattern;
+	}
+	handle->brush.setStyle( style );
+	handle->brush.setColor( colorFromParam( params+1 ) );
+}
+
+void WMFImport::createPenIndirect( QList<PageItem*>& /*items*/, long, short* params )
+{
+	static Qt::PenStyle styleTab[] = { Qt::SolidLine, Qt::DashLine, Qt::DotLine, Qt::DashDotLine, Qt::DashDotDotLine,
+	  Qt::NoPen, Qt::SolidLine };
+	Qt::PenStyle style;
+	WmfObjPenHandle* handle = new WmfObjPenHandle();
+	addHandle( handle );
+
+	if ( params[0] >= 0 && params[0] < 6 ) 
+		style = styleTab[ params[0] ];
+	else
+	{
+		cerr << "WMFImport::createPenIndirect: invalid pen " << params[ 0 ] << endl;
+		style = Qt::SolidLine;
+	}
+
+	handle->pen.setStyle( style );
+	handle->pen.setWidth( params[1] );
+	handle->pen.setColor( colorFromParam( params+3 ) );
+	handle->pen.setCapStyle( Qt::RoundCap );
+}
+
+void WMFImport::createFontIndirect( QList<PageItem*>& /*items*/, long , short* params)
+{
+	WmfObjFontHandle* handle = new WmfObjFontHandle();
+	addHandle( handle );
+
+	QString family( (const char*)&params[ 9 ] );
+
+	handle->rotation = -params[ 2 ]  / 10; // text rotation (in 1/10 degree)
+	handle->font.setFamily( family );
+	handle->font.setStyleStrategy( QFont::PreferOutline );
+	handle->font.setFixedPitch( ((params[ 8 ] & 0x01) == 0) );
+	// TODO: investigation why some test case need -2. (size of font in logical point)
+	int fontSize = (params[0] != 0) ? (qAbs(params[0]) - 2) : 12;
+	handle->font.setPixelSize( fontSize );
+	handle->font.setWeight( (params[ 4 ] >> 3) );
+	handle->font.setItalic( (params[ 5 ] & 0x01) );
+	handle->font.setUnderline( (params[ 5 ] & 0x100) );
+	handle->font.setStrikeOut( (params[ 6 ] & 0x01) );
+	handle->charset = (params[ 6 ] & 0xFF00) >> 8;
+}
+
+void WMFImport::noop( QList<PageItem*>& /*items*/, long, short* )
+{
+}
+
+void WMFImport::end( QList<PageItem*>& /*items*/, long, short* )
+{
+	//cerr << "WMFImport::end unimplemented" << endl;
+}
+
+void WMFImport::addHandle( WmfObjHandle* handle )
+{
+	int idx;
+
+	for ( idx =0; idx < MAX_OBJHANDLE ; idx++ )
+		if ( m_ObjHandleTab[ idx ] == NULL )  break;
+
+	if ( idx < MAX_OBJHANDLE )
+		m_ObjHandleTab[ idx ] = handle;
+	else
+		cerr << "WMFImport error: handle table full !" << endl;
+}
+
+void WMFImport::deleteHandle( int idx )
+{
+	if ( idx >= 0 && idx < MAX_OBJHANDLE && m_ObjHandleTab[ idx ] )
+	{
+		delete m_ObjHandleTab[ idx ];
+		m_ObjHandleTab[ idx ] = NULL;
+	}
+}
+
+unsigned short WMFImport::calcCheckSum( WmfPlaceableHeader* apmfh )
+{
+	WORD16*  lpWord;
+	WORD16   wResult, i;
+
+	// Start with the first word
+	wResult = *( lpWord = ( WORD16* )( apmfh ) );
+	// XOR in each of the other 9 words
+	for( i=1; i<=9; i++ )
+	{
+		wResult ^= lpWord[ i ];
+	}
+	return wResult;
+}
+
+int WMFImport::findFunc( unsigned short aFunc ) const
+{
+	int i = 0;
+
+	for ( i=0; metaFuncTab[ i ].name; i++ )
+		if ( metaFuncTab[ i ].func == aFunc ) return i;
+
+	// here : unknown function
+	return i;
+}
+
+unsigned int WMFImport::toDWord( short* params )
+{
+	unsigned int l;
+#if !defined( WORDS_BIGENDIAN )
+	l = *( unsigned int* )( params );
+#else
+	char *bytes;
+	char swap[ 4 ];
+	bytes = ( char* )params;
+	swap[ 0 ] = bytes[ 2 ];
+	swap[ 1 ] = bytes[ 3 ];
+	swap[ 2 ] = bytes[ 0 ];
+	swap[ 3 ] = bytes[ 1 ];
+	l = *( unsigned int* )( swap );
+#endif
+	return l;
+}

Modified: trunk/Scribus/scribus/plugins/import/wpg/importwpg.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/plugins/import/wpg/importwpg.cpp
==============================================================================
--- trunk/Scribus/scribus/plugins/import/wpg/importwpg.cpp (original)
+++ trunk/Scribus/scribus/plugins/import/wpg/importwpg.cpp Mon Jun 20 20:43:58 2011
@@ -1,723 +1,723 @@
-/*
-For general Scribus (>=1.3.2) copyright and licensing information please refer
-to the COPYING file provided with the program. Following this notice may exist
-a copyright and/or license notice that predates the release of Scribus 1.3.2
-for which a new license (GPL+exception) is in place.
-*/
-
-#include <QByteArray>
-#include <QCursor>
-#include <QDrag>
-#include <QFile>
-#include <QList>
-#include <QMimeData>
-#include <QRegExp>
-#include <QStack>
-#include <QDebug>
-
-#include <cstdlib>
-
-#include "commonstrings.h"
-#include "ui/customfdialog.h"
-#include "importwpg.h"
-#include "loadsaveplugin.h"
-#include "ui/missing.h"
-#include "ui/multiprogressdialog.h"
-#include "pagesize.h"
-#include "prefscontext.h"
-#include "prefsfile.h"
-#include "prefsmanager.h"
-#include "prefstable.h"
-#include "ui/propertiespalette.h"
-#include "rawimage.h"
-#include "scclocale.h"
-#include "sccolorengine.h"
-#include "scconfig.h"
-#include "scmimedata.h"
-#include "scpaths.h"
-#include "scpattern.h"
-#include "scribus.h"
-#include "scribusXml.h"
-#include "scribuscore.h"
-#include "sctextstream.h"
-#include "selection.h"
-#include "undomanager.h"
-#include "util.h"
-#include "util_formats.h"
-#include "util_icon.h"
-#include "util_math.h"
-#include <stdio.h>
-#include "third_party/wpg/WPGStreamImplementation.h"
-
-extern SCRIBUS_API ScribusQApp * ScQApp;
-
-ScrPainter::ScrPainter(): libwpg::WPGPaintInterface()
-{
-}
-
-void ScrPainter::startGraphics(double width, double height)
-{
-	CurrColorFill = "Black";
-	CurrFillShade = 100.0;
-	CurrColorStroke = "Black";
-	CurrStrokeShade = 100.0;
-	CurrStrokeTrans = 0.0;
-	CurrFillTrans = 0.0;
-	Coords.resize(0);
-	Coords.svgInit();
-	LineW = 1.0;
-	lineJoin = Qt::MiterJoin;
-	lineEnd = Qt::FlatCap;
-	fillrule = true;
-	gradientAngle = 0.0;
-	isGradient = false;
-	fillSet = false;
-	strokeSet = false;
-	currentGradient = VGradient(VGradient::linear);
-	currentGradient.clearStops();
-	currentGradient.setRepeatMethod( VGradient::none );
-	dashArray.clear();
-	if (flags & LoadSavePlugin::lfCreateDoc)
-	{
-		m_Doc->setPage(72 * width, 72 * height, 0, 0, 0, 0, 0, 0, false, false);
-		if (width > height)
-			m_Doc->setPageOrientation(1);
-		else
-			m_Doc->setPageOrientation(0);
-		m_Doc->setPageSize("Custom");
-		m_Doc->changePageMargins(0, 0, 0, 0, 72 * height, 72 * width, 72 * height, 72 * width, m_Doc->pageOrientation(), m_Doc->pageSize(), m_Doc->currentPage()->pageNr(), 0);
-	}
-	firstLayer = true;
-}
-
-void ScrPainter::endGraphics()
-{
-}
-
-void ScrPainter::startLayer(unsigned int id)
-{
-	if (flags & LoadSavePlugin::lfCreateDoc)
-	{
-		if (!firstLayer)
-			m_Doc->addLayer(QString("Layer %1").arg(id), true);
-		firstLayer = false;
-	}
-}
-
-void ScrPainter::endLayer(unsigned int id)
-{
-}
-
-void ScrPainter::setPen(const libwpg::WPGPen& pen)
-{
-	LineW = 72 * pen.width;
-	ScColor tmp;
-	ColorList::Iterator it;
-	CurrColorStroke = "Black";
-	CurrStrokeShade = 100.0;
-	int Rc, Gc, Bc;
-	Rc = pen.foreColor.red;
-	Gc = pen.foreColor.green;
-	Bc = pen.foreColor.blue;
-	tmp.setColorRGB(Rc, Gc, Bc);
-	tmp.setSpotColor(false);
-	tmp.setRegistrationColor(false);
-	QString newColorName = "FromWPG"+tmp.name();
-	QString fNam = m_Doc->PageColors.tryAddColor(newColorName, tmp);
-	if (fNam == newColorName)
-		importedColors.append(newColorName);
-	CurrColorStroke = fNam;
-	CurrStrokeTrans = pen.foreColor.alpha / 255.0;
-	if(!pen.solid)
-	{
-		dashArray.clear();
-		for(unsigned i = 0; i < pen.dashArray.count(); i++)
-		{
-			dashArray.append(pen.dashArray.at(i)*LineW);
-		}
-	}
-	switch (pen.joinstyle)
-	{
-		case 1:
-			lineJoin = Qt::BevelJoin;
-			break;
-		case 2:
-			lineJoin = Qt::MiterJoin;
-			break;
-		case 3:
-			lineJoin = Qt::RoundJoin;
-			break;
-		default:
-			lineJoin = Qt::MiterJoin;
-			break;
-	}
-	switch (pen.capstyle)
-	{
-		case 0:
-			lineEnd = Qt::FlatCap;
-			break;
-		case 1:
-			lineEnd = Qt::RoundCap;
-			break;
-		case 2:
-			lineEnd = Qt::SquareCap;
-			break;
-		default:
-			lineEnd = Qt::FlatCap;
-			break;
-	}
-	strokeSet = true;
-}
-
-void ScrPainter::setBrush(const libwpg::WPGBrush& brush)
-{
-	ScColor tmp;
-	ColorList::Iterator it;
-	CurrColorFill = "Black";
-	CurrFillShade = 100.0;
-	int Rc, Gc, Bc;
-	if(brush.style == libwpg::WPGBrush::Solid)
-	{
-		Rc = brush.foreColor.red;
-		Gc = brush.foreColor.green;
-		Bc = brush.foreColor.blue;
-		tmp.setColorRGB(Rc, Gc, Bc);
-		tmp.setSpotColor(false);
-		tmp.setRegistrationColor(false);
-		QString newColorName = "FromWPG"+tmp.name();
-		QString fNam = m_Doc->PageColors.tryAddColor(newColorName, tmp);
-		if (fNam == newColorName)
-			importedColors.append(newColorName);
-		CurrColorFill = fNam;
-		CurrFillTrans = brush.foreColor.alpha / 255.0;
-	}
-	else if (brush.style == libwpg::WPGBrush::Gradient)
-	{
-		gradientAngle = brush.gradient.angle();
-		isGradient = true;
-		currentGradient = VGradient(VGradient::linear);
-		currentGradient.clearStops();
-		for(unsigned c = 0; c < brush.gradient.count(); c++)
-		{
-			QString currStopColor = CommonStrings::None;
-			Rc = brush.gradient.stopColor(c).red;
-			Gc = brush.gradient.stopColor(c).green;
-			Bc = brush.gradient.stopColor(c).blue;
-			tmp.setColorRGB(Rc, Gc, Bc);
-			tmp.setSpotColor(false);
-			tmp.setRegistrationColor(false);
-			QString newColorName = "FromWPG"+tmp.name();
-			QString fNam = m_Doc->PageColors.tryAddColor(newColorName, tmp);
-			if (fNam == newColorName)
-				importedColors.append(newColorName);
-			currStopColor = fNam;
-			const ScColor& gradC = m_Doc->PageColors[currStopColor];
-			double pos = qBound(0.0, fabs(brush.gradient.stopOffset(c)), 1.0);
-			currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), pos, 0.5, 1.0, currStopColor, 100 );
-		}
-	}
-	else if (brush.style == libwpg::WPGBrush::NoBrush)
-		CurrColorFill = CommonStrings::None;
-	fillSet = true;
-}
-
-void ScrPainter::setFillRule(FillRule rule)
-{
-	if(rule == libwpg::WPGPaintInterface::WindingFill)
-		fillrule = false;
-	else
-		fillrule = true;
-//	qDebug() << "Fill Rule " << fillrule;
-}
-
-void ScrPainter::drawRectangle(const libwpg::WPGRect& rect, double rx, double ry)
-{
-	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, baseX, baseY, rect.width() * 72.0, rect.height() * 72.0, LineW, CurrColorFill, CurrColorStroke, true);
-	PageItem *ite = m_Doc->Items->at(z);
-	if ((rx > 0) && (ry > 0))
-	{
-		ite->setCornerRadius(qMax(72*rx, 72*ry));
-		ite->SetFrameRound();
-		m_Doc->setRedrawBounding(ite);
-	}
-	QTransform mm = QTransform();
-	mm.translate(72*rect.x1, 72*rect.y1);
-	ite->PoLine.map(mm);
-	ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-	finishItem(ite);
-//	qDebug() << "draw Rect";
-}
-
-void ScrPainter::drawEllipse(const libwpg::WPGPoint& center, double rx, double ry)
-{
-	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX, baseY, rx * 144.0, ry * 144.0, LineW, CurrColorFill, CurrColorStroke, true);
-	PageItem *ite = m_Doc->Items->at(z);
-	QTransform mm = QTransform();
-	mm.translate(72*(center.x - rx), 72*(center.y - ry));
-	ite->PoLine.map(mm);
-	ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-	finishItem(ite);
-//	qDebug() << "draw Ellipse";
-}
-
-void ScrPainter::drawPolygon(const libwpg::WPGPointArray& vertices, bool closed)
-{
-	if(vertices.count() < 2)
-		return;
-	Coords.resize(0);
-	Coords.svgInit();
-	PageItem *ite;
-	Coords.svgMoveTo(72 * vertices[0].x, 72 * vertices[0].y);
-	for(unsigned i = 1; i < vertices.count(); i++)
-	{
-		Coords.svgLineTo(72 * vertices[i].x, 72 * vertices[i].y);
-	}
-	if (closed)
-		Coords.svgClosePath();
-	if (Coords.size() > 0)
-	{
-		int z;
-		if (closed)
-			z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-		else
-			z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColorStroke, true);
-		ite = m_Doc->Items->at(z);
-		ite->PoLine = Coords.copy();
-		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-		finishItem(ite);
-	}
-//	qDebug() << "draw Polygon";
-}
-
-void ScrPainter::drawPath(const libwpg::WPGPath& path)
-{
-	Coords.resize(0);
-	Coords.svgInit();
-	PageItem *ite;
-	for(unsigned i = 0; i < path.count(); i++)
-	{
-		libwpg::WPGPathElement element = path.element(i);
-		libwpg::WPGPoint point = element.point;
-		switch(element.type)
-		{
-			case libwpg::WPGPathElement::MoveToElement:
-				Coords.svgMoveTo(72 * point.x, 72 * point.y);
-				break;
-			case libwpg::WPGPathElement::LineToElement:
-				Coords.svgLineTo(72 * point.x, 72 * point.y);
-				break;
-			case libwpg::WPGPathElement::CurveToElement:
-				Coords.svgCurveToCubic(72*element.extra1.x, 72*element.extra1.y, 72*element.extra2.x, 72*element.extra2.y, 72 * point.x, 72 * point.y);
-				break;
-			default:
-				break;
-		}
-	}
-	if (Coords.size() > 0)
-	{
-		int z;
-		if (fillSet)
-		{
-			if (!path.filled)
-				CurrColorFill = CommonStrings::None;
-		}
-		if (strokeSet)
-		{
-			if (!path.framed)
-				CurrColorStroke = CommonStrings::None;
-		}
-		if(path.closed)
-		{
-			Coords.svgClosePath();
-			z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-		}
-		else
-			z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-		ite = m_Doc->Items->at(z);
-		ite->PoLine = Coords.copy();
-		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-		finishItem(ite);
-	}
-//	qDebug() << "draw Path" << CurrFillTrans;
-}
-
-void ScrPainter::finishItem(PageItem* ite)
-{
-	ite->ClipEdited = true;
-	ite->FrameType = 3;
-	ite->setFillShade(CurrFillShade);
-	ite->setFillEvenOdd(fillrule);
-	ite->setLineShade(CurrStrokeShade);
-	ite->setLineJoin(lineJoin);
-	ite->setLineEnd(lineEnd);
-	ite->DashValues = dashArray;
-	FPoint wh = getMaxClipF(&ite->PoLine);
-	ite->setWidthHeight(wh.x(),wh.y());
-	ite->setTextFlowMode(PageItem::TextFlowDisabled);
-	m_Doc->AdjustItemSize(ite);
-	ite->OldB2 = ite->width();
-	ite->OldH2 = ite->height();
-	if (isGradient)
-	{
-		ite->fill_gradient = currentGradient;
-		ite->GrType = 6;
-		QTransform m1;
-		m1.rotate(-gradientAngle);
-		ite->GrStartX = 0;
-		ite->GrStartY = 0;
-		QPointF target = m1.map(QPointF(0.0, ite->height()));
-		ite->GrEndX = target.x();
-		ite->GrEndY = target.y();
-	}
-	else
-	{
-		ite->setFillTransparency(CurrFillTrans);
-		ite->setLineTransparency(CurrStrokeTrans);
-	}
-	ite->updateClip();
-	Elements.append(ite);
-	Coords.resize(0);
-	Coords.svgInit();
-}
-
-void ScrPainter::drawBitmap(const libwpg::WPGBitmap& bitmap, double hres, double vres)
-{
-	QImage image = QImage(bitmap.width(), bitmap.height(), QImage::Format_RGB32);
-	for(int x = 0; x < bitmap.width(); x++)
-	{
-		for(int y = 0; y < bitmap.height(); y++)
-		{
-			libwpg::WPGColor color = bitmap.pixel(x, y);
-			image.setPixel(x, y, qRgb(color.red, color.green, color.blue));
-		}
-	}
-	double w = (bitmap.rect.x2 - bitmap.rect.x1) * 72.0;
-	double h = (bitmap.rect.y2 - bitmap.rect.y1) * 72.0;
-	int z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, bitmap.rect.x1 * 72 + baseX, bitmap.rect.y1 * 72 + baseY, w, h, 1, m_Doc->itemToolPrefs().imageFillColor, CommonStrings::None, true);
-	PageItem *ite = m_Doc->Items->at(z);
-	ite->tempImageFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_wpg_XXXXXX.png");
-	ite->tempImageFile->open();
-	QString fileName = getLongPathName(ite->tempImageFile->fileName());
-	ite->tempImageFile->close();
-	ite->isInlineImage = true;
-	image.setDotsPerMeterX ((int) (hres / 0.0254));
-	image.setDotsPerMeterY ((int) (vres / 0.0254));
-	image.save(fileName, "PNG");
-	m_Doc->LoadPict(fileName, z);
-	ite->setImageScalingMode(false, false);
-	ite->moveBy(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-	finishItem(ite);
-//	qDebug() << "drawBitmap";
-}
-
-void ScrPainter::drawImageObject(const libwpg::WPGBinaryData& /*binaryData*/)
-{
-//	qDebug() << "drawBinaryData";
-}
-
-
-WpgPlug::WpgPlug(ScribusDoc* doc, int flags)
-{
-	tmpSel=new Selection(this, false);
-	m_Doc=doc;
-	importerFlags = flags;
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-}
-
-QImage WpgPlug::readThumbnail(QString fName)
-{
-	QFileInfo fi = QFileInfo(fName);
-	double b, h;
-	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	docWidth = b;
-	docHeight = h;
-	progressDialog = NULL;
-	m_Doc = new ScribusDoc();
-	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
-	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
-	m_Doc->addPage(0);
-	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
-	baseX = m_Doc->currentPage()->xOffset();
-	baseY = m_Doc->currentPage()->yOffset();
-	Elements.clear();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	m_Doc->scMW()->setScriptRunning(true);
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	if (convert(fName))
-	{
-		tmpSel->clear();
-		QDir::setCurrent(CurDirP);
-		if (Elements.count() > 1)
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->m_Selection->delaySignalsOn();
-		QImage tmpImage;
-		if (Elements.count() > 0)
-		{
-			for (int dre=0; dre<Elements.count(); ++dre)
-			{
-				tmpSel->addItem(Elements.at(dre), true);
-			}
-			tmpSel->setGroupRect();
-			double xs = tmpSel->width();
-			double ys = tmpSel->height();
-			tmpImage = Elements.at(0)->DrawObj_toImage(500);
-			tmpImage.setText("XSize", QString("%1").arg(xs));
-			tmpImage.setText("YSize", QString("%1").arg(ys));
-		}
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->setLoading(false);
-		m_Doc->m_Selection->delaySignalsOff();
-		delete m_Doc;
-		return tmpImage;
-	}
-	else
-	{
-		QDir::setCurrent(CurDirP);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		delete m_Doc;
-	}
-	return QImage();
-}
-
-bool WpgPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
-{
-	QString fName = fNameIn;
-	bool success = false;
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-	importerFlags = flags;
-	cancel = false;
-	double x, y, b, h;
-	bool ret = false;
-	QFileInfo fi = QFileInfo(fName);
-	if ( !ScCore->usingGUI() )
-	{
-		interactive = false;
-		showProgress = false;
-	}
-	if ( showProgress )
-	{
-		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
-		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
-		QStringList barNames, barTexts;
-		barNames << "GI";
-		barTexts << tr("Analyzing File:");
-		QList<bool> barsNumeric;
-		barsNumeric << false;
-		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
-		progressDialog->setOverallTotalSteps(3);
-		progressDialog->setOverallProgress(0);
-		progressDialog->setProgress("GI", 0);
-		progressDialog->show();
-		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
-		qApp->processEvents();
-	}
-	else
-		progressDialog = NULL;
-/* Set default Page to size defined in Preferences */
-	x = 0.0;
-	y = 0.0;
-	b = 0.0;
-	h = 0.0;
-	if (progressDialog)
-	{
-		progressDialog->setOverallProgress(1);
-		qApp->processEvents();
-	}
-	if (b == 0.0)
-		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	if (h == 0.0)
-		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	docWidth = b;
-	docHeight = h;
-	baseX = 0;
-	baseY = 0;
-	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
-	{
-		m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
-		m_Doc->addPage(0);
-		m_Doc->view()->addPage(0, true);
-		baseX = 0;
-		baseY = 0;
-	}
-	else
-	{
-		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
-		{
-			m_Doc=ScCore->primaryMainWindow()->doFileNew(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
-			ScCore->primaryMainWindow()->HaveNewDoc();
-			ret = true;
-			baseX = 0;
-			baseY = 0;
-			baseX = m_Doc->currentPage()->xOffset();
-			baseY = m_Doc->currentPage()->yOffset();
-		}
-	}
-	if ((!ret) && (interactive))
-	{
-		baseX = m_Doc->currentPage()->xOffset();
-		baseY = m_Doc->currentPage()->yOffset();
-	}
-	if ((ret) || (!interactive))
-	{
-		if (docWidth > docHeight)
-			m_Doc->setPageOrientation(1);
-		else
-			m_Doc->setPageOrientation(0);
-		m_Doc->setPageSize("Custom");
-	}
+/*
+For general Scribus (>=1.3.2) copyright and licensing information please refer
+to the COPYING file provided with the program. Following this notice may exist
+a copyright and/or license notice that predates the release of Scribus 1.3.2
+for which a new license (GPL+exception) is in place.
+*/
+
+#include <QByteArray>
+#include <QCursor>
+#include <QDrag>
+#include <QFile>
+#include <QList>
+#include <QMimeData>
+#include <QRegExp>
+#include <QStack>
+#include <QDebug>
+
+#include <cstdlib>
+
+#include "commonstrings.h"
+#include "ui/customfdialog.h"
+#include "importwpg.h"
+#include "loadsaveplugin.h"
+#include "ui/missing.h"
+#include "ui/multiprogressdialog.h"
+#include "pagesize.h"
+#include "prefscontext.h"
+#include "prefsfile.h"
+#include "prefsmanager.h"
+#include "prefstable.h"
+#include "ui/propertiespalette.h"
+#include "rawimage.h"
+#include "scclocale.h"
+#include "sccolorengine.h"
+#include "scconfig.h"
+#include "scmimedata.h"
+#include "scpaths.h"
+#include "scpattern.h"
+#include "scribus.h"
+#include "scribusXml.h"
+#include "scribuscore.h"
+#include "sctextstream.h"
+#include "selection.h"
+#include "undomanager.h"
+#include "util.h"
+#include "util_formats.h"
+#include "util_icon.h"
+#include "util_math.h"
+#include <stdio.h>
+#include "third_party/wpg/WPGStreamImplementation.h"
+
+extern SCRIBUS_API ScribusQApp * ScQApp;
+
+ScrPainter::ScrPainter(): libwpg::WPGPaintInterface()
+{
+}
+
+void ScrPainter::startGraphics(double width, double height)
+{
+	CurrColorFill = "Black";
+	CurrFillShade = 100.0;
+	CurrColorStroke = "Black";
+	CurrStrokeShade = 100.0;
+	CurrStrokeTrans = 0.0;
+	CurrFillTrans = 0.0;
+	Coords.resize(0);
+	Coords.svgInit();
+	LineW = 1.0;
+	lineJoin = Qt::MiterJoin;
+	lineEnd = Qt::FlatCap;
+	fillrule = true;
+	gradientAngle = 0.0;
+	isGradient = false;
+	fillSet = false;
+	strokeSet = false;
+	currentGradient = VGradient(VGradient::linear);
+	currentGradient.clearStops();
+	currentGradient.setRepeatMethod( VGradient::none );
+	dashArray.clear();
+	if (flags & LoadSavePlugin::lfCreateDoc)
+	{
+		m_Doc->setPage(72 * width, 72 * height, 0, 0, 0, 0, 0, 0, false, false);
+		if (width > height)
+			m_Doc->setPageOrientation(1);
+		else
+			m_Doc->setPageOrientation(0);
+		m_Doc->setPageSize("Custom");
+		m_Doc->changePageMargins(0, 0, 0, 0, 72 * height, 72 * width, 72 * height, 72 * width, m_Doc->pageOrientation(), m_Doc->pageSize(), m_Doc->currentPage()->pageNr(), 0);
+	}
+	firstLayer = true;
+}
+
+void ScrPainter::endGraphics()
+{
+}
+
+void ScrPainter::startLayer(unsigned int id)
+{
+	if (flags & LoadSavePlugin::lfCreateDoc)
+	{
+		if (!firstLayer)
+			m_Doc->addLayer(QString("Layer %1").arg(id), true);
+		firstLayer = false;
+	}
+}
+
+void ScrPainter::endLayer(unsigned int id)
+{
+}
+
+void ScrPainter::setPen(const libwpg::WPGPen& pen)
+{
+	LineW = 72 * pen.width;
+	ScColor tmp;
+	ColorList::Iterator it;
+	CurrColorStroke = "Black";
+	CurrStrokeShade = 100.0;
+	int Rc, Gc, Bc;
+	Rc = pen.foreColor.red;
+	Gc = pen.foreColor.green;
+	Bc = pen.foreColor.blue;
+	tmp.setColorRGB(Rc, Gc, Bc);
+	tmp.setSpotColor(false);
+	tmp.setRegistrationColor(false);
+	QString newColorName = "FromWPG"+tmp.name();
+	QString fNam = m_Doc->PageColors.tryAddColor(newColorName, tmp);
+	if (fNam == newColorName)
+		importedColors.append(newColorName);
+	CurrColorStroke = fNam;
+	CurrStrokeTrans = pen.foreColor.alpha / 255.0;
+	if(!pen.solid)
+	{
+		dashArray.clear();
+		for(unsigned i = 0; i < pen.dashArray.count(); i++)
+		{
+			dashArray.append(pen.dashArray.at(i)*LineW);
+		}
+	}
+	switch (pen.joinstyle)
+	{
+		case 1:
+			lineJoin = Qt::BevelJoin;
+			break;
+		case 2:
+			lineJoin = Qt::MiterJoin;
+			break;
+		case 3:
+			lineJoin = Qt::RoundJoin;
+			break;
+		default:
+			lineJoin = Qt::MiterJoin;
+			break;
+	}
+	switch (pen.capstyle)
+	{
+		case 0:
+			lineEnd = Qt::FlatCap;
+			break;
+		case 1:
+			lineEnd = Qt::RoundCap;
+			break;
+		case 2:
+			lineEnd = Qt::SquareCap;
+			break;
+		default:
+			lineEnd = Qt::FlatCap;
+			break;
+	}
+	strokeSet = true;
+}
+
+void ScrPainter::setBrush(const libwpg::WPGBrush& brush)
+{
+	ScColor tmp;
+	ColorList::Iterator it;
+	CurrColorFill = "Black";
+	CurrFillShade = 100.0;
+	int Rc, Gc, Bc;
+	if(brush.style == libwpg::WPGBrush::Solid)
+	{
+		Rc = brush.foreColor.red;
+		Gc = brush.foreColor.green;
+		Bc = brush.foreColor.blue;
+		tmp.setColorRGB(Rc, Gc, Bc);
+		tmp.setSpotColor(false);
+		tmp.setRegistrationColor(false);
+		QString newColorName = "FromWPG"+tmp.name();
+		QString fNam = m_Doc->PageColors.tryAddColor(newColorName, tmp);
+		if (fNam == newColorName)
+			importedColors.append(newColorName);
+		CurrColorFill = fNam;
+		CurrFillTrans = brush.foreColor.alpha / 255.0;
+	}
+	else if (brush.style == libwpg::WPGBrush::Gradient)
+	{
+		gradientAngle = brush.gradient.angle();
+		isGradient = true;
+		currentGradient = VGradient(VGradient::linear);
+		currentGradient.clearStops();
+		for(unsigned c = 0; c < brush.gradient.count(); c++)
+		{
+			QString currStopColor = CommonStrings::None;
+			Rc = brush.gradient.stopColor(c).red;
+			Gc = brush.gradient.stopColor(c).green;
+			Bc = brush.gradient.stopColor(c).blue;
+			tmp.setColorRGB(Rc, Gc, Bc);
+			tmp.setSpotColor(false);
+			tmp.setRegistrationColor(false);
+			QString newColorName = "FromWPG"+tmp.name();
+			QString fNam = m_Doc->PageColors.tryAddColor(newColorName, tmp);
+			if (fNam == newColorName)
+				importedColors.append(newColorName);
+			currStopColor = fNam;
+			const ScColor& gradC = m_Doc->PageColors[currStopColor];
+			double pos = qBound(0.0, fabs(brush.gradient.stopOffset(c)), 1.0);
+			currentGradient.addStop( ScColorEngine::getRGBColor(gradC, m_Doc), pos, 0.5, 1.0, currStopColor, 100 );
+		}
+	}
+	else if (brush.style == libwpg::WPGBrush::NoBrush)
+		CurrColorFill = CommonStrings::None;
+	fillSet = true;
+}
+
+void ScrPainter::setFillRule(FillRule rule)
+{
+	if(rule == libwpg::WPGPaintInterface::WindingFill)
+		fillrule = false;
+	else
+		fillrule = true;
+//	qDebug() << "Fill Rule " << fillrule;
+}
+
+void ScrPainter::drawRectangle(const libwpg::WPGRect& rect, double rx, double ry)
+{
+	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, baseX, baseY, rect.width() * 72.0, rect.height() * 72.0, LineW, CurrColorFill, CurrColorStroke, true);
+	PageItem *ite = m_Doc->Items->at(z);
+	if ((rx > 0) && (ry > 0))
+	{
+		ite->setCornerRadius(qMax(72*rx, 72*ry));
+		ite->SetFrameRound();
+		m_Doc->setRedrawBounding(ite);
+	}
+	QTransform mm = QTransform();
+	mm.translate(72*rect.x1, 72*rect.y1);
+	ite->PoLine.map(mm);
+	ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+	finishItem(ite);
+//	qDebug() << "draw Rect";
+}
+
+void ScrPainter::drawEllipse(const libwpg::WPGPoint& center, double rx, double ry)
+{
+	int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX, baseY, rx * 144.0, ry * 144.0, LineW, CurrColorFill, CurrColorStroke, true);
+	PageItem *ite = m_Doc->Items->at(z);
+	QTransform mm = QTransform();
+	mm.translate(72*(center.x - rx), 72*(center.y - ry));
+	ite->PoLine.map(mm);
+	ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+	finishItem(ite);
+//	qDebug() << "draw Ellipse";
+}
+
+void ScrPainter::drawPolygon(const libwpg::WPGPointArray& vertices, bool closed)
+{
+	if(vertices.count() < 2)
+		return;
+	Coords.resize(0);
+	Coords.svgInit();
+	PageItem *ite;
+	Coords.svgMoveTo(72 * vertices[0].x, 72 * vertices[0].y);
+	for(unsigned i = 1; i < vertices.count(); i++)
+	{
+		Coords.svgLineTo(72 * vertices[i].x, 72 * vertices[i].y);
+	}
+	if (closed)
+		Coords.svgClosePath();
+	if (Coords.size() > 0)
+	{
+		int z;
+		if (closed)
+			z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+		else
+			z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColorStroke, true);
+		ite = m_Doc->Items->at(z);
+		ite->PoLine = Coords.copy();
+		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+		finishItem(ite);
+	}
+//	qDebug() << "draw Polygon";
+}
+
+void ScrPainter::drawPath(const libwpg::WPGPath& path)
+{
+	Coords.resize(0);
+	Coords.svgInit();
+	PageItem *ite;
+	for(unsigned i = 0; i < path.count(); i++)
+	{
+		libwpg::WPGPathElement element = path.element(i);
+		libwpg::WPGPoint point = element.point;
+		switch(element.type)
+		{
+			case libwpg::WPGPathElement::MoveToElement:
+				Coords.svgMoveTo(72 * point.x, 72 * point.y);
+				break;
+			case libwpg::WPGPathElement::LineToElement:
+				Coords.svgLineTo(72 * point.x, 72 * point.y);
+				break;
+			case libwpg::WPGPathElement::CurveToElement:
+				Coords.svgCurveToCubic(72*element.extra1.x, 72*element.extra1.y, 72*element.extra2.x, 72*element.extra2.y, 72 * point.x, 72 * point.y);
+				break;
+			default:
+				break;
+		}
+	}
+	if (Coords.size() > 0)
+	{
+		int z;
+		if (fillSet)
+		{
+			if (!path.filled)
+				CurrColorFill = CommonStrings::None;
+		}
+		if (strokeSet)
+		{
+			if (!path.framed)
+				CurrColorStroke = CommonStrings::None;
+		}
+		if(path.closed)
+		{
+			Coords.svgClosePath();
+			z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+		}
+		else
+			z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+		ite = m_Doc->Items->at(z);
+		ite->PoLine = Coords.copy();
+		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+		finishItem(ite);
+	}
+//	qDebug() << "draw Path" << CurrFillTrans;
+}
+
+void ScrPainter::finishItem(PageItem* ite)
+{
+	ite->ClipEdited = true;
+	ite->FrameType = 3;
+	ite->setFillShade(CurrFillShade);
+	ite->setFillEvenOdd(fillrule);
+	ite->setLineShade(CurrStrokeShade);
+	ite->setLineJoin(lineJoin);
+	ite->setLineEnd(lineEnd);
+	ite->DashValues = dashArray;
+	FPoint wh = getMaxClipF(&ite->PoLine);
+	ite->setWidthHeight(wh.x(),wh.y());
+	ite->setTextFlowMode(PageItem::TextFlowDisabled);
+	m_Doc->AdjustItemSize(ite);
+	ite->OldB2 = ite->width();
+	ite->OldH2 = ite->height();
+	if (isGradient)
+	{
+		ite->fill_gradient = currentGradient;
+		ite->GrType = 6;
+		QTransform m1;
+		m1.rotate(-gradientAngle);
+		ite->GrStartX = 0;
+		ite->GrStartY = 0;
+		QPointF target = m1.map(QPointF(0.0, ite->height()));
+		ite->GrEndX = target.x();
+		ite->GrEndY = target.y();
+	}
+	else
+	{
+		ite->setFillTransparency(CurrFillTrans);
+		ite->setLineTransparency(CurrStrokeTrans);
+	}
+	ite->updateClip();
+	Elements.append(ite);
+	Coords.resize(0);
+	Coords.svgInit();
+}
+
+void ScrPainter::drawBitmap(const libwpg::WPGBitmap& bitmap, double hres, double vres)
+{
+	QImage image = QImage(bitmap.width(), bitmap.height(), QImage::Format_RGB32);
+	for(int x = 0; x < bitmap.width(); x++)
+	{
+		for(int y = 0; y < bitmap.height(); y++)
+		{
+			libwpg::WPGColor color = bitmap.pixel(x, y);
+			image.setPixel(x, y, qRgb(color.red, color.green, color.blue));
+		}
+	}
+	double w = (bitmap.rect.x2 - bitmap.rect.x1) * 72.0;
+	double h = (bitmap.rect.y2 - bitmap.rect.y1) * 72.0;
+	int z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, bitmap.rect.x1 * 72 + baseX, bitmap.rect.y1 * 72 + baseY, w, h, 1, m_Doc->itemToolPrefs().imageFillColor, CommonStrings::None, true);
+	PageItem *ite = m_Doc->Items->at(z);
+	ite->tempImageFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_wpg_XXXXXX.png");
+	ite->tempImageFile->open();
+	QString fileName = getLongPathName(ite->tempImageFile->fileName());
+	ite->tempImageFile->close();
+	ite->isInlineImage = true;
+	image.setDotsPerMeterX ((int) (hres / 0.0254));
+	image.setDotsPerMeterY ((int) (vres / 0.0254));
+	image.save(fileName, "PNG");
+	m_Doc->LoadPict(fileName, z);
+	ite->setImageScalingMode(false, false);
+	ite->moveBy(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+	finishItem(ite);
+//	qDebug() << "drawBitmap";
+}
+
+void ScrPainter::drawImageObject(const libwpg::WPGBinaryData& /*binaryData*/)
+{
+//	qDebug() << "drawBinaryData";
+}
+
+
+WpgPlug::WpgPlug(ScribusDoc* doc, int flags)
+{
+	tmpSel=new Selection(this, false);
+	m_Doc=doc;
+	importerFlags = flags;
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+}
+
+QImage WpgPlug::readThumbnail(QString fName)
+{
+	QFileInfo fi = QFileInfo(fName);
+	double b, h;
+	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	docWidth = b;
+	docHeight = h;
+	progressDialog = NULL;
+	m_Doc = new ScribusDoc();
+	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
+	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
+	m_Doc->addPage(0);
+	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
+	baseX = m_Doc->currentPage()->xOffset();
+	baseY = m_Doc->currentPage()->yOffset();
+	Elements.clear();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	m_Doc->scMW()->setScriptRunning(true);
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	if (convert(fName))
+	{
+		tmpSel->clear();
+		QDir::setCurrent(CurDirP);
+		if (Elements.count() > 1)
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->m_Selection->delaySignalsOn();
+		QImage tmpImage;
+		if (Elements.count() > 0)
+		{
+			for (int dre=0; dre<Elements.count(); ++dre)
+			{
+				tmpSel->addItem(Elements.at(dre), true);
+			}
+			tmpSel->setGroupRect();
+			double xs = tmpSel->width();
+			double ys = tmpSel->height();
+			tmpImage = Elements.at(0)->DrawObj_toImage(500);
+			tmpImage.setText("XSize", QString("%1").arg(xs));
+			tmpImage.setText("YSize", QString("%1").arg(ys));
+		}
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->setLoading(false);
+		m_Doc->m_Selection->delaySignalsOff();
+		delete m_Doc;
+		return tmpImage;
+	}
+	else
+	{
+		QDir::setCurrent(CurDirP);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		delete m_Doc;
+	}
+	return QImage();
+}
+
+bool WpgPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
+{
+	QString fName = fNameIn;
+	bool success = false;
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+	importerFlags = flags;
+	cancel = false;
+	double x, y, b, h;
+	bool ret = false;
+	QFileInfo fi = QFileInfo(fName);
+	if ( !ScCore->usingGUI() )
+	{
+		interactive = false;
+		showProgress = false;
+	}
+	if ( showProgress )
+	{
+		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
+		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
+		QStringList barNames, barTexts;
+		barNames << "GI";
+		barTexts << tr("Analyzing File:");
+		QList<bool> barsNumeric;
+		barsNumeric << false;
+		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
+		progressDialog->setOverallTotalSteps(3);
+		progressDialog->setOverallProgress(0);
+		progressDialog->setProgress("GI", 0);
+		progressDialog->show();
+		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
+		qApp->processEvents();
+	}
+	else
+		progressDialog = NULL;
+/* Set default Page to size defined in Preferences */
+	x = 0.0;
+	y = 0.0;
+	b = 0.0;
+	h = 0.0;
+	if (progressDialog)
+	{
+		progressDialog->setOverallProgress(1);
+		qApp->processEvents();
+	}
+	if (b == 0.0)
+		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	if (h == 0.0)
+		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	docWidth = b;
+	docHeight = h;
+	baseX = 0;
+	baseY = 0;
+	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
+	{
+		m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
+		m_Doc->addPage(0);
+		m_Doc->view()->addPage(0, true);
+		baseX = 0;
+		baseY = 0;
+	}
+	else
+	{
+		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
+		{
+			m_Doc=ScCore->primaryMainWindow()->doFileNew(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
+			ScCore->primaryMainWindow()->HaveNewDoc();
+			ret = true;
+			baseX = 0;
+			baseY = 0;
+			baseX = m_Doc->currentPage()->xOffset();
+			baseY = m_Doc->currentPage()->yOffset();
+		}
+	}
+	if ((!ret) && (interactive))
+	{
+		baseX = m_Doc->currentPage()->xOffset();
+		baseY = m_Doc->currentPage()->yOffset();
+	}
+	if ((ret) || (!interactive))
+	{
+		if (docWidth > docHeight)
+			m_Doc->setPageOrientation(1);
+		else
+			m_Doc->setPageOrientation(0);
+		m_Doc->setPageSize("Custom");
+	}
 	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->Deselect();
-	Elements.clear();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->updatesOn(false);
-	m_Doc->scMW()->setScriptRunning(true);
-	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	if (convert(fName))
-	{
-		tmpSel->clear();
-		QDir::setCurrent(CurDirP);
-		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->setLoading(false);
-		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-		if ((Elements.count() > 0) && (!ret) && (interactive))
-		{
-			if (flags & LoadSavePlugin::lfScripted)
-			{
-				bool loadF = m_Doc->isLoading();
-				m_Doc->setLoading(false);
-				m_Doc->changed();
-				m_Doc->setLoading(loadF);
-				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-				{
-					m_Doc->m_Selection->delaySignalsOn();
-					for (int dre=0; dre<Elements.count(); ++dre)
-					{
-						m_Doc->m_Selection->addItem(Elements.at(dre), true);
-					}
-					m_Doc->m_Selection->delaySignalsOff();
-					m_Doc->m_Selection->setGroupRect();
-					m_Doc->view()->updatesOn(true);
-				}
-			}
-			else
-			{
-				m_Doc->DragP = true;
-				m_Doc->DraggedElem = 0;
-				m_Doc->DragElements.clear();
-				m_Doc->m_Selection->delaySignalsOn();
-				for (int dre=0; dre<Elements.count(); ++dre)
-				{
-					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
-					tmpSel->addItem(Elements.at(dre), true);
-				}
-				tmpSel->setGroupRect();
-				ScriXmlDoc *ss = new ScriXmlDoc();
-				ScElemMimeData* md = new ScElemMimeData();
-				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
-				delete ss;
-				m_Doc->itemSelection_DeleteItem(tmpSel);
-				m_Doc->view()->updatesOn(true);
-				m_Doc->m_Selection->delaySignalsOff();
-				// We must copy the TransationSettings object as it is owned
-				// by handleObjectImport method afterwards
-				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
-				m_Doc->view()->handleObjectImport(md, transacSettings);
-				m_Doc->DragP = false;
-				m_Doc->DraggedElem = 0;
-				m_Doc->DragElements.clear();
-			}
-		}
-		else
-		{
-			m_Doc->changed();
-			m_Doc->reformPages();
-			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-				m_Doc->view()->updatesOn(true);
-		}
-		success = true;
-	}
-	else
-	{
-		QDir::setCurrent(CurDirP);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->view()->updatesOn(true);
-		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-	}
-	if (interactive)
-		m_Doc->setLoading(false);
-	//CB If we have a gui we must refresh it if we have used the progressbar
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-	{
-		if ((showProgress) && (!interactive))
-			m_Doc->view()->DrawNew();
-	}
-	return success;
-}
-
-WpgPlug::~WpgPlug()
-{
-	if (progressDialog)
-		delete progressDialog;
-	delete tmpSel;
-}
-
-bool WpgPlug::convert(QString fn)
-{
-	QString tmp;
-	importedColors.clear();
-
-	QFile file(fn);
-	if ( !file.exists() )
-	{
-		qDebug() << "File " << QFile::encodeName(fn).data() << " does not exist" << endl;
-		return false;
-	}
-	if ( !file.open( QIODevice::ReadOnly ) )
-	{
-		qDebug() << "Cannot open file " << QFile::encodeName(fn).data() << endl;
-		return false;
-	}
-	QByteArray ba = file.readAll();
-	file.close();
-
-	libwpg::WPGMemoryStream input(ba.constData(), ba.size());
-	if (!libwpg::WPGraphics::isSupported(&input))
-	{
-		fprintf(stderr, "ERROR: Unsupported file format (unsupported version) or file is encrypted!\n");
-		return false;
-	}
-	ScrPainter painter;
-	painter.m_Doc = m_Doc;
-	painter.baseX = baseX;
-	painter.baseY = baseY;
-	painter.flags = importerFlags;
-	libwpg::WPGraphics::parse(&input, &painter);
-	Elements = painter.Elements;
-	importedColors = painter.importedColors;
-	if (Elements.count() == 0)
-	{
-		if (importedColors.count() != 0)
-		{
-			for (int cd = 0; cd < importedColors.count(); cd++)
-			{
-				m_Doc->PageColors.remove(importedColors[cd]);
-			}
-		}
-	}
-	if (progressDialog)
-		progressDialog->close();
-	return true;
-}
+		m_Doc->view()->Deselect();
+	Elements.clear();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+		m_Doc->view()->updatesOn(false);
+	m_Doc->scMW()->setScriptRunning(true);
+	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	if (convert(fName))
+	{
+		tmpSel->clear();
+		QDir::setCurrent(CurDirP);
+		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->setLoading(false);
+		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+		if ((Elements.count() > 0) && (!ret) && (interactive))
+		{
+			if (flags & LoadSavePlugin::lfScripted)
+			{
+				bool loadF = m_Doc->isLoading();
+				m_Doc->setLoading(false);
+				m_Doc->changed();
+				m_Doc->setLoading(loadF);
+				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+				{
+					m_Doc->m_Selection->delaySignalsOn();
+					for (int dre=0; dre<Elements.count(); ++dre)
+					{
+						m_Doc->m_Selection->addItem(Elements.at(dre), true);
+					}
+					m_Doc->m_Selection->delaySignalsOff();
+					m_Doc->m_Selection->setGroupRect();
+					m_Doc->view()->updatesOn(true);
+				}
+			}
+			else
+			{
+				m_Doc->DragP = true;
+				m_Doc->DraggedElem = 0;
+				m_Doc->DragElements.clear();
+				m_Doc->m_Selection->delaySignalsOn();
+				for (int dre=0; dre<Elements.count(); ++dre)
+				{
+					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
+					tmpSel->addItem(Elements.at(dre), true);
+				}
+				tmpSel->setGroupRect();
+				ScriXmlDoc *ss = new ScriXmlDoc();
+				ScElemMimeData* md = new ScElemMimeData();
+				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
+				delete ss;
+				m_Doc->itemSelection_DeleteItem(tmpSel);
+				m_Doc->view()->updatesOn(true);
+				m_Doc->m_Selection->delaySignalsOff();
+				// We must copy the TransationSettings object as it is owned
+				// by handleObjectImport method afterwards
+				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
+				m_Doc->view()->handleObjectImport(md, transacSettings);
+				m_Doc->DragP = false;
+				m_Doc->DraggedElem = 0;
+				m_Doc->DragElements.clear();
+			}
+		}
+		else
+		{
+			m_Doc->changed();
+			m_Doc->reformPages();
+			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+				m_Doc->view()->updatesOn(true);
+		}
+		success = true;
+	}
+	else
+	{
+		QDir::setCurrent(CurDirP);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->view()->updatesOn(true);
+		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+	}
+	if (interactive)
+		m_Doc->setLoading(false);
+	//CB If we have a gui we must refresh it if we have used the progressbar
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+	{
+		if ((showProgress) && (!interactive))
+			m_Doc->view()->DrawNew();
+	}
+	return success;
+}
+
+WpgPlug::~WpgPlug()
+{
+	if (progressDialog)
+		delete progressDialog;
+	delete tmpSel;
+}
+
+bool WpgPlug::convert(QString fn)
+{
+	QString tmp;
+	importedColors.clear();
+
+	QFile file(fn);
+	if ( !file.exists() )
+	{
+		qDebug() << "File " << QFile::encodeName(fn).data() << " does not exist" << endl;
+		return false;
+	}
+	if ( !file.open( QIODevice::ReadOnly ) )
+	{
+		qDebug() << "Cannot open file " << QFile::encodeName(fn).data() << endl;
+		return false;
+	}
+	QByteArray ba = file.readAll();
+	file.close();
+
+	libwpg::WPGMemoryStream input(ba.constData(), ba.size());
+	if (!libwpg::WPGraphics::isSupported(&input))
+	{
+		fprintf(stderr, "ERROR: Unsupported file format (unsupported version) or file is encrypted!\n");
+		return false;
+	}
+	ScrPainter painter;
+	painter.m_Doc = m_Doc;
+	painter.baseX = baseX;
+	painter.baseY = baseY;
+	painter.flags = importerFlags;
+	libwpg::WPGraphics::parse(&input, &painter);
+	Elements = painter.Elements;
+	importedColors = painter.importedColors;
+	if (Elements.count() == 0)
+	{
+		if (importedColors.count() != 0)
+		{
+			for (int cd = 0; cd < importedColors.count(); cd++)
+			{
+				m_Doc->PageColors.remove(importedColors[cd]);
+			}
+		}
+	}
+	if (progressDialog)
+		progressDialog->close();
+	return true;
+}

Modified: trunk/Scribus/scribus/plugins/import/xfig/importxfig.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/plugins/import/xfig/importxfig.cpp
==============================================================================
--- trunk/Scribus/scribus/plugins/import/xfig/importxfig.cpp (original)
+++ trunk/Scribus/scribus/plugins/import/xfig/importxfig.cpp Mon Jun 20 20:43:58 2011
@@ -1,1671 +1,1671 @@
-/*
-For general Scribus (>=1.3.2) copyright and licensing information please refer
-to the COPYING file provided with the program. Following this notice may exist
-a copyright and/or license notice that predates the release of Scribus 1.3.2
-for which a new license (GPL+exception) is in place.
-*/
-
-#include <QByteArray>
-#include <QCursor>
-#include <QDrag>
-#include <QFile>
-#include <QList>
-#include <QMimeData>
-#include <QRegExp>
-#include <QStack>
-#include <QDebug>
-
-#include <cstdlib>
-
-#include "commonstrings.h"
-#include "importxfig.h"
-#include "loadsaveplugin.h"
-#include "pagesize.h"
-#include "pageitem.h"
-#include "prefscontext.h"
-#include "prefsfile.h"
-#include "prefsmanager.h"
-#include "prefstable.h"
-#include "rawimage.h"
-#include "scclocale.h"
-#include "sccolorengine.h"
-#include "scconfig.h"
-#include "scmimedata.h"
-#include "scpaths.h"
-#include "scpattern.h"
-#include "scribus.h"
-#include "scribusXml.h"
-#include "scribuscore.h"
-#include "sctextstream.h"
-#include "selection.h"
-#include "ui/customfdialog.h"
-#include "ui/missing.h"
-#include "ui/multiprogressdialog.h"
-#include "ui/propertiespalette.h"
-#include "undomanager.h"
-#include "util.h"
-#include "util_formats.h"
-#include "util_icon.h"
-#include "util_math.h"
-
-extern SCRIBUS_API ScribusQApp * ScQApp;
-
-XfigPlug::XfigPlug(ScribusDoc* doc, int flags)
-{
-	tmpSel=new Selection(this, false);
-	m_Doc=doc;
-	importerFlags = flags;
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-}
-
-QImage XfigPlug::readThumbnail(QString fName)
-{
-	QFileInfo fi = QFileInfo(fName);
-	baseFile = QDir::cleanPath(QDir::toNativeSeparators(fi.absolutePath()+"/"));
-	double b, h, x, y;
-	parseHeader(fName, x, y, b, h);
-	docX = x;
-	docY = y;
-	if (b == 0.0)
-		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	if (h == 0.0)
-		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	docWidth = b - x;
-	docHeight = h - y;
-	progressDialog = NULL;
-	m_Doc = new ScribusDoc();
-	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
-	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
-	m_Doc->addPage(0);
-	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
-	baseX = m_Doc->currentPage()->xOffset();
-	baseY = m_Doc->currentPage()->yOffset();
-	Elements.clear();
-	CustColors.clear();
-	importedColors.insert(0, "Black");
-	importedColors.insert(1, "Blue");
-	importedColors.insert(2, "Green");
-	importedColors.insert(3, "Cyan");
-	importedColors.insert(4, "Red");
-	importedColors.insert(5, "Magenta");
-	importedColors.insert(6, "Yellow");
-	importedColors.insert(7, "White");
-	importedColors.insert(8, "Blue4");
-	importedColors.insert(9, "Blue3");
-	importedColors.insert(10, "Blue2");
-	importedColors.insert(11, "LtBlue");
-	importedColors.insert(12, "Green4");
-	importedColors.insert(13, "Green3");
-	importedColors.insert(14, "Green2");
-	importedColors.insert(15, "Cyan4");
-	importedColors.insert(16, "Cyan3");
-	importedColors.insert(17, "Cyan2");
-	importedColors.insert(18, "Red4");
-	importedColors.insert(19, "Red3");
-	importedColors.insert(20, "Red2");
-	importedColors.insert(21, "Magenta4");
-	importedColors.insert(22, "Magenta3");
-	importedColors.insert(23, "Magenta2");
-	importedColors.insert(24, "Brown4");
-	importedColors.insert(25, "Brown3");
-	importedColors.insert(26, "Brown2");
-	importedColors.insert(27, "Pink4");
-	importedColors.insert(28, "Pink3");
-	importedColors.insert(29, "Pink2");
-	importedColors.insert(30, "Pink");
-	importedColors.insert(31, "Gold");
-	CustColors.insert("Blue", ScColor(0, 0, 255));
-	CustColors.insert("Blue4", ScColor(0, 0, 144));
-	CustColors.insert("Blue3", ScColor(0, 0, 176));
-	CustColors.insert("Blue2", ScColor(0, 0, 208));
-	CustColors.insert("LtBlue", ScColor(135, 206, 255));
-	CustColors.insert("Cyan", ScColor(255, 0, 0, 0));
-	CustColors.insert("Cyan4", ScColor(0, 144, 144));
-	CustColors.insert("Cyan3", ScColor(0, 176, 176));
-	CustColors.insert("Cyan2", ScColor(0, 208, 208));
-	CustColors.insert("Green", ScColor(255, 0, 255, 0));
-	CustColors.insert("Green4", ScColor(0, 144, 0));
-	CustColors.insert("Green3", ScColor(0, 176, 0));
-	CustColors.insert("Green2", ScColor(0, 208, 0));
-	CustColors.insert("Red", ScColor(0, 255, 255, 0));
-	CustColors.insert("Red4", ScColor(144, 0, 0));
-	CustColors.insert("Red3", ScColor(176, 0, 0));
-	CustColors.insert("Red2", ScColor(208, 0, 0));
-	CustColors.insert("Yellow", ScColor(0, 0, 255, 0));
-	CustColors.insert("Magenta", ScColor(0, 255, 0, 0));
-	CustColors.insert("Magenta4", ScColor(144, 0, 144));
-	CustColors.insert("Magenta3", ScColor(176, 0, 176));
-	CustColors.insert("Magenta2", ScColor(208, 0, 208));
-	CustColors.insert("Brown4", ScColor(128, 48, 0));
-	CustColors.insert("Brown3", ScColor(160, 64, 0));
-	CustColors.insert("Brown2", ScColor(192, 96, 0));
-	CustColors.insert("Pink4", ScColor(255, 128, 128));
-	CustColors.insert("Pink3", ScColor(255, 160, 160));
-	CustColors.insert("Pink2", ScColor(255, 192, 192));
-	CustColors.insert("Pink", ScColor(255, 224, 224));
-	CustColors.insert("Gold", ScColor(255, 215, 0));
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	m_Doc->scMW()->setScriptRunning(true);
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	if (convert(fName))
-	{
-		tmpSel->clear();
-		QDir::setCurrent(CurDirP);
-		if (Elements.count() > 1)
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->m_Selection->delaySignalsOn();
-		QImage tmpImage;
-		if (Elements.count() > 0)
-		{
-			for (int dre=0; dre<Elements.count(); ++dre)
-			{
-				tmpSel->addItem(Elements.at(dre), true);
-			}
-			tmpSel->setGroupRect();
-			double xs = tmpSel->width();
-			double ys = tmpSel->height();
-			tmpImage = Elements.at(0)->DrawObj_toImage(500);
-			tmpImage.setText("XSize", QString("%1").arg(xs));
-			tmpImage.setText("YSize", QString("%1").arg(ys));
-		}
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->setLoading(false);
-		m_Doc->m_Selection->delaySignalsOff();
-		delete m_Doc;
-		return tmpImage;
-	}
-	else
-	{
-		QDir::setCurrent(CurDirP);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		delete m_Doc;
-	}
-	return QImage();
-}
-
-bool XfigPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
-{
-	QString fName = fNameIn;
-	bool success = false;
-	interactive = (flags & LoadSavePlugin::lfInteractive);
-	importerFlags = flags;
-	cancel = false;
-	double x, y, b, h;
-	bool ret = false;
-	CustColors.clear();
-	importedColors.insert(0, "Black");
-	importedColors.insert(1, "Blue");
-	importedColors.insert(2, "Green");
-	importedColors.insert(3, "Cyan");
-	importedColors.insert(4, "Red");
-	importedColors.insert(5, "Magenta");
-	importedColors.insert(6, "Yellow");
-	importedColors.insert(7, "White");
-	importedColors.insert(8, "Blue4");
-	importedColors.insert(9, "Blue3");
-	importedColors.insert(10, "Blue2");
-	importedColors.insert(11, "LtBlue");
-	importedColors.insert(12, "Green4");
-	importedColors.insert(13, "Green3");
-	importedColors.insert(14, "Green2");
-	importedColors.insert(15, "Cyan4");
-	importedColors.insert(16, "Cyan3");
-	importedColors.insert(17, "Cyan2");
-	importedColors.insert(18, "Red4");
-	importedColors.insert(19, "Red3");
-	importedColors.insert(20, "Red2");
-	importedColors.insert(21, "Magenta4");
-	importedColors.insert(22, "Magenta3");
-	importedColors.insert(23, "Magenta2");
-	importedColors.insert(24, "Brown4");
-	importedColors.insert(25, "Brown3");
-	importedColors.insert(26, "Brown2");
-	importedColors.insert(27, "Pink4");
-	importedColors.insert(28, "Pink3");
-	importedColors.insert(29, "Pink2");
-	importedColors.insert(30, "Pink");
-	importedColors.insert(31, "Gold");
-	CustColors.insert("Blue", ScColor(0, 0, 255));
-	CustColors.insert("Blue4", ScColor(0, 0, 144));
-	CustColors.insert("Blue3", ScColor(0, 0, 176));
-	CustColors.insert("Blue2", ScColor(0, 0, 208));
-	CustColors.insert("LtBlue", ScColor(135, 206, 255));
-	CustColors.insert("Cyan", ScColor(255, 0, 0, 0));
-	CustColors.insert("Cyan4", ScColor(0, 144, 144));
-	CustColors.insert("Cyan3", ScColor(0, 176, 176));
-	CustColors.insert("Cyan2", ScColor(0, 208, 208));
-	CustColors.insert("Green", ScColor(255, 0, 255, 0));
-	CustColors.insert("Green4", ScColor(0, 144, 0));
-	CustColors.insert("Green3", ScColor(0, 176, 0));
-	CustColors.insert("Green2", ScColor(0, 208, 0));
-	CustColors.insert("Red", ScColor(0, 255, 255, 0));
-	CustColors.insert("Red4", ScColor(144, 0, 0));
-	CustColors.insert("Red3", ScColor(176, 0, 0));
-	CustColors.insert("Red2", ScColor(208, 0, 0));
-	CustColors.insert("Yellow", ScColor(0, 0, 255, 0));
-	CustColors.insert("Magenta", ScColor(0, 255, 0, 0));
-	CustColors.insert("Magenta4", ScColor(144, 0, 144));
-	CustColors.insert("Magenta3", ScColor(176, 0, 176));
-	CustColors.insert("Magenta2", ScColor(208, 0, 208));
-	CustColors.insert("Brown4", ScColor(128, 48, 0));
-	CustColors.insert("Brown3", ScColor(160, 64, 0));
-	CustColors.insert("Brown2", ScColor(192, 96, 0));
-	CustColors.insert("Pink4", ScColor(255, 128, 128));
-	CustColors.insert("Pink3", ScColor(255, 160, 160));
-	CustColors.insert("Pink2", ScColor(255, 192, 192));
-	CustColors.insert("Pink", ScColor(255, 224, 224));
-	CustColors.insert("Gold", ScColor(255, 215, 0));
-	QFileInfo fi = QFileInfo(fName);
-	if ( !ScCore->usingGUI() )
-	{
-		interactive = false;
-		showProgress = false;
-	}
-	baseFile = QDir::cleanPath(QDir::toNativeSeparators(fi.absolutePath()+"/"));
-	if ( showProgress )
-	{
-		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
-		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
-		QStringList barNames, barTexts;
-		barNames << "GI";
-		barTexts << tr("Analyzing File:");
-		QList<bool> barsNumeric;
-		barsNumeric << false;
-		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
-		progressDialog->setOverallTotalSteps(3);
-		progressDialog->setOverallProgress(0);
-		progressDialog->setProgress("GI", 0);
-		progressDialog->show();
-		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
-		qApp->processEvents();
-	}
-	else
-		progressDialog = NULL;
-/* Set default Page to size defined in Preferences */
-	x = 0.0;
-	y = 0.0;
-	b = 0.0;
-	h = 0.0;
-	if (progressDialog)
-	{
-		progressDialog->setOverallProgress(1);
-		qApp->processEvents();
-	}
-	parseHeader(fName, x, y, b, h);
-	docX = x;
-	docY = y;
-	if (b == 0.0)
-		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
-	if (h == 0.0)
-		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
-	docWidth = b - x;
-	docHeight = h - y;
-	baseX = 0;
-	baseY = 0;
-	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
-	{
-		m_Doc->setPage(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false);
-		m_Doc->addPage(0);
-		m_Doc->view()->addPage(0, true);
-		baseX = 0;
-		baseY = 0;
-	}
-	else
-	{
-		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
-		{
-			m_Doc=ScCore->primaryMainWindow()->doFileNew(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
-			ScCore->primaryMainWindow()->HaveNewDoc();
-			ret = true;
-			baseX = 0;
-			baseY = 0;
-		}
-	}
-	if (flags & LoadSavePlugin::lfCreateDoc)
-	{
-		m_Doc->documentInfo().setAuthor(docCreator);
-		m_Doc->documentInfo().setPublisher(docOrganisation);
-		m_Doc->documentInfo().setTitle(docTitle);
-		m_Doc->documentInfo().setDate(docDate+" "+docTime);
-	}
-	if ((!ret) && (interactive))
-	{
-		baseX = m_Doc->currentPage()->xOffset();
-		baseY = m_Doc->currentPage()->yOffset();
-	}
-	if ((ret) || (!interactive))
-	{
-		if (b-x > h-y)
-			m_Doc->setPageOrientation(1);
-		else
-			m_Doc->setPageOrientation(0);
-		m_Doc->setPageSize("Custom");
-	}
+/*
+For general Scribus (>=1.3.2) copyright and licensing information please refer
+to the COPYING file provided with the program. Following this notice may exist
+a copyright and/or license notice that predates the release of Scribus 1.3.2
+for which a new license (GPL+exception) is in place.
+*/
+
+#include <QByteArray>
+#include <QCursor>
+#include <QDrag>
+#include <QFile>
+#include <QList>
+#include <QMimeData>
+#include <QRegExp>
+#include <QStack>
+#include <QDebug>
+
+#include <cstdlib>
+
+#include "commonstrings.h"
+#include "importxfig.h"
+#include "loadsaveplugin.h"
+#include "pagesize.h"
+#include "pageitem.h"
+#include "prefscontext.h"
+#include "prefsfile.h"
+#include "prefsmanager.h"
+#include "prefstable.h"
+#include "rawimage.h"
+#include "scclocale.h"
+#include "sccolorengine.h"
+#include "scconfig.h"
+#include "scmimedata.h"
+#include "scpaths.h"
+#include "scpattern.h"
+#include "scribus.h"
+#include "scribusXml.h"
+#include "scribuscore.h"
+#include "sctextstream.h"
+#include "selection.h"
+#include "ui/customfdialog.h"
+#include "ui/missing.h"
+#include "ui/multiprogressdialog.h"
+#include "ui/propertiespalette.h"
+#include "undomanager.h"
+#include "util.h"
+#include "util_formats.h"
+#include "util_icon.h"
+#include "util_math.h"
+
+extern SCRIBUS_API ScribusQApp * ScQApp;
+
+XfigPlug::XfigPlug(ScribusDoc* doc, int flags)
+{
+	tmpSel=new Selection(this, false);
+	m_Doc=doc;
+	importerFlags = flags;
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+}
+
+QImage XfigPlug::readThumbnail(QString fName)
+{
+	QFileInfo fi = QFileInfo(fName);
+	baseFile = QDir::cleanPath(QDir::toNativeSeparators(fi.absolutePath()+"/"));
+	double b, h, x, y;
+	parseHeader(fName, x, y, b, h);
+	docX = x;
+	docY = y;
+	if (b == 0.0)
+		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	if (h == 0.0)
+		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	docWidth = b - x;
+	docHeight = h - y;
+	progressDialog = NULL;
+	m_Doc = new ScribusDoc();
+	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
+	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
+	m_Doc->addPage(0);
+	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
+	baseX = m_Doc->currentPage()->xOffset();
+	baseY = m_Doc->currentPage()->yOffset();
+	Elements.clear();
+	CustColors.clear();
+	importedColors.insert(0, "Black");
+	importedColors.insert(1, "Blue");
+	importedColors.insert(2, "Green");
+	importedColors.insert(3, "Cyan");
+	importedColors.insert(4, "Red");
+	importedColors.insert(5, "Magenta");
+	importedColors.insert(6, "Yellow");
+	importedColors.insert(7, "White");
+	importedColors.insert(8, "Blue4");
+	importedColors.insert(9, "Blue3");
+	importedColors.insert(10, "Blue2");
+	importedColors.insert(11, "LtBlue");
+	importedColors.insert(12, "Green4");
+	importedColors.insert(13, "Green3");
+	importedColors.insert(14, "Green2");
+	importedColors.insert(15, "Cyan4");
+	importedColors.insert(16, "Cyan3");
+	importedColors.insert(17, "Cyan2");
+	importedColors.insert(18, "Red4");
+	importedColors.insert(19, "Red3");
+	importedColors.insert(20, "Red2");
+	importedColors.insert(21, "Magenta4");
+	importedColors.insert(22, "Magenta3");
+	importedColors.insert(23, "Magenta2");
+	importedColors.insert(24, "Brown4");
+	importedColors.insert(25, "Brown3");
+	importedColors.insert(26, "Brown2");
+	importedColors.insert(27, "Pink4");
+	importedColors.insert(28, "Pink3");
+	importedColors.insert(29, "Pink2");
+	importedColors.insert(30, "Pink");
+	importedColors.insert(31, "Gold");
+	CustColors.insert("Blue", ScColor(0, 0, 255));
+	CustColors.insert("Blue4", ScColor(0, 0, 144));
+	CustColors.insert("Blue3", ScColor(0, 0, 176));
+	CustColors.insert("Blue2", ScColor(0, 0, 208));
+	CustColors.insert("LtBlue", ScColor(135, 206, 255));
+	CustColors.insert("Cyan", ScColor(255, 0, 0, 0));
+	CustColors.insert("Cyan4", ScColor(0, 144, 144));
+	CustColors.insert("Cyan3", ScColor(0, 176, 176));
+	CustColors.insert("Cyan2", ScColor(0, 208, 208));
+	CustColors.insert("Green", ScColor(255, 0, 255, 0));
+	CustColors.insert("Green4", ScColor(0, 144, 0));
+	CustColors.insert("Green3", ScColor(0, 176, 0));
+	CustColors.insert("Green2", ScColor(0, 208, 0));
+	CustColors.insert("Red", ScColor(0, 255, 255, 0));
+	CustColors.insert("Red4", ScColor(144, 0, 0));
+	CustColors.insert("Red3", ScColor(176, 0, 0));
+	CustColors.insert("Red2", ScColor(208, 0, 0));
+	CustColors.insert("Yellow", ScColor(0, 0, 255, 0));
+	CustColors.insert("Magenta", ScColor(0, 255, 0, 0));
+	CustColors.insert("Magenta4", ScColor(144, 0, 144));
+	CustColors.insert("Magenta3", ScColor(176, 0, 176));
+	CustColors.insert("Magenta2", ScColor(208, 0, 208));
+	CustColors.insert("Brown4", ScColor(128, 48, 0));
+	CustColors.insert("Brown3", ScColor(160, 64, 0));
+	CustColors.insert("Brown2", ScColor(192, 96, 0));
+	CustColors.insert("Pink4", ScColor(255, 128, 128));
+	CustColors.insert("Pink3", ScColor(255, 160, 160));
+	CustColors.insert("Pink2", ScColor(255, 192, 192));
+	CustColors.insert("Pink", ScColor(255, 224, 224));
+	CustColors.insert("Gold", ScColor(255, 215, 0));
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	m_Doc->scMW()->setScriptRunning(true);
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	if (convert(fName))
+	{
+		tmpSel->clear();
+		QDir::setCurrent(CurDirP);
+		if (Elements.count() > 1)
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->m_Selection->delaySignalsOn();
+		QImage tmpImage;
+		if (Elements.count() > 0)
+		{
+			for (int dre=0; dre<Elements.count(); ++dre)
+			{
+				tmpSel->addItem(Elements.at(dre), true);
+			}
+			tmpSel->setGroupRect();
+			double xs = tmpSel->width();
+			double ys = tmpSel->height();
+			tmpImage = Elements.at(0)->DrawObj_toImage(500);
+			tmpImage.setText("XSize", QString("%1").arg(xs));
+			tmpImage.setText("YSize", QString("%1").arg(ys));
+		}
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->setLoading(false);
+		m_Doc->m_Selection->delaySignalsOff();
+		delete m_Doc;
+		return tmpImage;
+	}
+	else
+	{
+		QDir::setCurrent(CurDirP);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		delete m_Doc;
+	}
+	return QImage();
+}
+
+bool XfigPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
+{
+	QString fName = fNameIn;
+	bool success = false;
+	interactive = (flags & LoadSavePlugin::lfInteractive);
+	importerFlags = flags;
+	cancel = false;
+	double x, y, b, h;
+	bool ret = false;
+	CustColors.clear();
+	importedColors.insert(0, "Black");
+	importedColors.insert(1, "Blue");
+	importedColors.insert(2, "Green");
+	importedColors.insert(3, "Cyan");
+	importedColors.insert(4, "Red");
+	importedColors.insert(5, "Magenta");
+	importedColors.insert(6, "Yellow");
+	importedColors.insert(7, "White");
+	importedColors.insert(8, "Blue4");
+	importedColors.insert(9, "Blue3");
+	importedColors.insert(10, "Blue2");
+	importedColors.insert(11, "LtBlue");
+	importedColors.insert(12, "Green4");
+	importedColors.insert(13, "Green3");
+	importedColors.insert(14, "Green2");
+	importedColors.insert(15, "Cyan4");
+	importedColors.insert(16, "Cyan3");
+	importedColors.insert(17, "Cyan2");
+	importedColors.insert(18, "Red4");
+	importedColors.insert(19, "Red3");
+	importedColors.insert(20, "Red2");
+	importedColors.insert(21, "Magenta4");
+	importedColors.insert(22, "Magenta3");
+	importedColors.insert(23, "Magenta2");
+	importedColors.insert(24, "Brown4");
+	importedColors.insert(25, "Brown3");
+	importedColors.insert(26, "Brown2");
+	importedColors.insert(27, "Pink4");
+	importedColors.insert(28, "Pink3");
+	importedColors.insert(29, "Pink2");
+	importedColors.insert(30, "Pink");
+	importedColors.insert(31, "Gold");
+	CustColors.insert("Blue", ScColor(0, 0, 255));
+	CustColors.insert("Blue4", ScColor(0, 0, 144));
+	CustColors.insert("Blue3", ScColor(0, 0, 176));
+	CustColors.insert("Blue2", ScColor(0, 0, 208));
+	CustColors.insert("LtBlue", ScColor(135, 206, 255));
+	CustColors.insert("Cyan", ScColor(255, 0, 0, 0));
+	CustColors.insert("Cyan4", ScColor(0, 144, 144));
+	CustColors.insert("Cyan3", ScColor(0, 176, 176));
+	CustColors.insert("Cyan2", ScColor(0, 208, 208));
+	CustColors.insert("Green", ScColor(255, 0, 255, 0));
+	CustColors.insert("Green4", ScColor(0, 144, 0));
+	CustColors.insert("Green3", ScColor(0, 176, 0));
+	CustColors.insert("Green2", ScColor(0, 208, 0));
+	CustColors.insert("Red", ScColor(0, 255, 255, 0));
+	CustColors.insert("Red4", ScColor(144, 0, 0));
+	CustColors.insert("Red3", ScColor(176, 0, 0));
+	CustColors.insert("Red2", ScColor(208, 0, 0));
+	CustColors.insert("Yellow", ScColor(0, 0, 255, 0));
+	CustColors.insert("Magenta", ScColor(0, 255, 0, 0));
+	CustColors.insert("Magenta4", ScColor(144, 0, 144));
+	CustColors.insert("Magenta3", ScColor(176, 0, 176));
+	CustColors.insert("Magenta2", ScColor(208, 0, 208));
+	CustColors.insert("Brown4", ScColor(128, 48, 0));
+	CustColors.insert("Brown3", ScColor(160, 64, 0));
+	CustColors.insert("Brown2", ScColor(192, 96, 0));
+	CustColors.insert("Pink4", ScColor(255, 128, 128));
+	CustColors.insert("Pink3", ScColor(255, 160, 160));
+	CustColors.insert("Pink2", ScColor(255, 192, 192));
+	CustColors.insert("Pink", ScColor(255, 224, 224));
+	CustColors.insert("Gold", ScColor(255, 215, 0));
+	QFileInfo fi = QFileInfo(fName);
+	if ( !ScCore->usingGUI() )
+	{
+		interactive = false;
+		showProgress = false;
+	}
+	baseFile = QDir::cleanPath(QDir::toNativeSeparators(fi.absolutePath()+"/"));
+	if ( showProgress )
+	{
+		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
+		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
+		QStringList barNames, barTexts;
+		barNames << "GI";
+		barTexts << tr("Analyzing File:");
+		QList<bool> barsNumeric;
+		barsNumeric << false;
+		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
+		progressDialog->setOverallTotalSteps(3);
+		progressDialog->setOverallProgress(0);
+		progressDialog->setProgress("GI", 0);
+		progressDialog->show();
+		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
+		qApp->processEvents();
+	}
+	else
+		progressDialog = NULL;
+/* Set default Page to size defined in Preferences */
+	x = 0.0;
+	y = 0.0;
+	b = 0.0;
+	h = 0.0;
+	if (progressDialog)
+	{
+		progressDialog->setOverallProgress(1);
+		qApp->processEvents();
+	}
+	parseHeader(fName, x, y, b, h);
+	docX = x;
+	docY = y;
+	if (b == 0.0)
+		b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
+	if (h == 0.0)
+		h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
+	docWidth = b - x;
+	docHeight = h - y;
+	baseX = 0;
+	baseY = 0;
+	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
+	{
+		m_Doc->setPage(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false);
+		m_Doc->addPage(0);
+		m_Doc->view()->addPage(0, true);
+		baseX = 0;
+		baseY = 0;
+	}
+	else
+	{
+		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
+		{
+			m_Doc=ScCore->primaryMainWindow()->doFileNew(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
+			ScCore->primaryMainWindow()->HaveNewDoc();
+			ret = true;
+			baseX = 0;
+			baseY = 0;
+		}
+	}
+	if (flags & LoadSavePlugin::lfCreateDoc)
+	{
+		m_Doc->documentInfo().setAuthor(docCreator);
+		m_Doc->documentInfo().setPublisher(docOrganisation);
+		m_Doc->documentInfo().setTitle(docTitle);
+		m_Doc->documentInfo().setDate(docDate+" "+docTime);
+	}
+	if ((!ret) && (interactive))
+	{
+		baseX = m_Doc->currentPage()->xOffset();
+		baseY = m_Doc->currentPage()->yOffset();
+	}
+	if ((ret) || (!interactive))
+	{
+		if (b-x > h-y)
+			m_Doc->setPageOrientation(1);
+		else
+			m_Doc->setPageOrientation(0);
+		m_Doc->setPageSize("Custom");
+	}
 	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->Deselect();
-	Elements.clear();
-	m_Doc->setLoading(true);
-	m_Doc->DoDrawing = false;
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-		m_Doc->view()->updatesOn(false);
-	m_Doc->scMW()->setScriptRunning(true);
-	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
-	QString CurDirP = QDir::currentPath();
-	QDir::setCurrent(fi.path());
-	if (convert(fName))
-	{
-		tmpSel->clear();
-		QDir::setCurrent(CurDirP);
-		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
-			m_Doc->groupObjectsList(Elements);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->setLoading(false);
-		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-		if ((Elements.count() > 0) && (!ret) && (interactive))
-		{
-			if (flags & LoadSavePlugin::lfScripted)
-			{
-				bool loadF = m_Doc->isLoading();
-				m_Doc->setLoading(false);
-				m_Doc->changed();
-				m_Doc->setLoading(loadF);
-				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-				{
-					m_Doc->m_Selection->delaySignalsOn();
-					for (int dre=0; dre<Elements.count(); ++dre)
-					{
-						m_Doc->m_Selection->addItem(Elements.at(dre), true);
-					}
-					m_Doc->m_Selection->delaySignalsOff();
-					m_Doc->m_Selection->setGroupRect();
-					m_Doc->view()->updatesOn(true);
-				}
-			}
-			else
-			{
-				m_Doc->DragP = true;
-				m_Doc->DraggedElem = 0;
-				m_Doc->DragElements.clear();
-				m_Doc->m_Selection->delaySignalsOn();
-				for (int dre=0; dre<Elements.count(); ++dre)
-				{
-					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
-					tmpSel->addItem(Elements.at(dre), true);
-				}
-				tmpSel->setGroupRect();
-				ScriXmlDoc *ss = new ScriXmlDoc();
-				ScElemMimeData* md = new ScElemMimeData();
-				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
-				delete ss;
-/*#ifndef Q_WS_MAC*/
-// see #2196
-				m_Doc->itemSelection_DeleteItem(tmpSel);
-/*#else
-				qDebug("xfigimport: leaving items on page");
-#endif*/
-				m_Doc->view()->updatesOn(true);
-				m_Doc->m_Selection->delaySignalsOff();
-				// We must copy the TransationSettings object as it is owned
-				// by handleObjectImport method afterwards
-				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
-				m_Doc->view()->handleObjectImport(md, transacSettings);
-				m_Doc->DragP = false;
-				m_Doc->DraggedElem = 0;
-				m_Doc->DragElements.clear();
-			}
-		}
-		else
-		{
-			m_Doc->changed();
-			m_Doc->reformPages();
-			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-				m_Doc->view()->updatesOn(true);
-		}
-		success = true;
-	}
-	else
-	{
-		QDir::setCurrent(CurDirP);
-		m_Doc->DoDrawing = true;
-		m_Doc->scMW()->setScriptRunning(false);
-		m_Doc->view()->updatesOn(true);
-		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
-	}
-	if (interactive)
-		m_Doc->setLoading(false);
-	//CB If we have a gui we must refresh it if we have used the progressbar
-	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
-	{
-		if ((showProgress) && (!interactive))
-			m_Doc->view()->DrawNew();
-	}
-	return success;
-}
-
-XfigPlug::~XfigPlug()
-{
-	if (progressDialog)
-		delete progressDialog;
-	delete tmpSel;
-}
-
-bool XfigPlug::parseHeader(QString fName, double &x, double &y, double &b, double &h)
-{
-	QString tmp, BBox, tmp2, FarNam;
-	ScColor cc;
-	bool found = false;
-	QFile f(fName);
-	if (f.open(QIODevice::ReadOnly))
-	{
-		QDataStream ts(&f);
-		QString version = readLinefromDataStream(ts);
-		if (!version.startsWith("#FIG 3"))
-		{
-			f.close();
-			return false;
-		}
-		QString orientation = readLinefromDataStream(ts);
-		QString justification = readLinefromDataStream(ts);
-		QString units = readLinefromDataStream(ts);
-		QString papersize = readLinefromDataStream(ts);
-		PageSize ps(papersize);
-		if (orientation.startsWith("Landscape"))
-		{
-			h = ps.width();
-			b = ps.height();
-		}
-		else
-		{
-			b = ps.width();
-			h = ps.height();
-		}
-		f.close();
-		found = true;
-	}
-	return found;
-}
-
-void XfigPlug::parseColor(QString data)
-{
-	if (data.isEmpty())
-		return;
-	int colorNum, dummy;
-	QString colorValues;
-	ScColor tmp;
-	ScTextStream Code(&data, QIODevice::ReadOnly);
-	Code >> dummy >> colorNum >> colorValues;
-	tmp.setNamedColor(colorValues);
-	tmp.setSpotColor(false);
-	tmp.setRegistrationColor(false);
-	QString namPrefix = "FromXfig%1-"+colorValues;
-	CustColors.insert(namPrefix.arg(colorNum), tmp);
-	importedColors.insert(colorNum, namPrefix.arg(colorNum));
-}
-
-void XfigPlug::useColor(int colorNum, int area_fill, bool forFill)
-{
-	QString color = CommonStrings::None;
-	int shade = 100;
-	if (forFill)
-	{
-		if (area_fill == -1)
-			color = CommonStrings::None;
-		else
-		{
-			if ((colorNum == -1) || (colorNum == 0))
-			{
-				if (area_fill == 0)
-				{
-					color = "White";
-					shade = 100;
-				}
-				else if (area_fill == 20)
-				{
-					color = "Black";
-					shade = 100;
-				}
-				else if ((area_fill > 0) && (area_fill < 20))
-				{
-					color = "Black";
-					shade = qRound(100.0 / 19.0 * area_fill);
-				}
-			}
-			else if (colorNum == 7)
-			{
-				if (area_fill == 0)
-				{
-					color = "Black";
-					shade = 100;
-				}
-				else if (area_fill == 20)
-				{
-					color = "White";
-					shade = 100;
-				}
-				else if ((area_fill > 0) && (area_fill < 20))
-				{
-					color = "Black";
-					shade = qRound(100.0 / 19.0 * (20 - area_fill));
-				}
-			}
-			else
-			{
-				if (importedColors.contains(colorNum))
-				{
-					color = importedColors[colorNum];
-					if (!m_Doc->PageColors.contains(color))
-						m_Doc->PageColors.insert(color, CustColors[color]);
-					int sat = area_fill - 20;
-					if ((sat > 0) && (sat < 20))
-						shade = qRound(100.0 / 19.0 * sat);
-				}
-				else
-					color = CommonStrings::None;
-			}
-		}
-		CurrColorFill = color;
-		CurrFillShade = shade;
-	}
-	else
-	{
-		if (area_fill == -1)
-			CurrColorStroke = CommonStrings::None;
-		else
-		{
-			if ((colorNum == -1) || (colorNum == 0))
-				CurrColorStroke = "Black";
-			else
-			{
-				if (importedColors.contains(colorNum))
-				{
-					CurrColorStroke = importedColors[colorNum];
-					if (!m_Doc->PageColors.contains(CurrColorStroke))
-						m_Doc->PageColors.insert(CurrColorStroke, CustColors[CurrColorStroke]);
-				}
-				else
-					CurrColorStroke = CommonStrings::None;
-			}
-		}
-	}
-}
-
-QVector<double> XfigPlug::getDashValues(double linewidth, int code)
-{
-	QVector<double> tmp;
-	if (code == 1)
-	{
-		tmp << qMax(4.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-	}
-	else if (code == 2)
-	{
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-	}
-	else if (code == 3)
-	{
-		tmp << qMax(4.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-	}
-	else if (code == 4)
-	{
-		tmp << qMax(4.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-	}
-	else if (code == 5)
-	{
-		tmp << qMax(4.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-		tmp << qMax(1.0 * linewidth, 0.1);
-		tmp << qMax(2.0 * linewidth, 0.1);
-	}
-	return tmp;
-}
-
-void XfigPlug::processArrows(int forward_arrow, QString fArrowData, int backward_arrow, QString bArrowData, int depth, PageItem *ite)
-{
-	int		arrow_typeAF;			// (enumeration type)
-	int		arrow_styleAF;			// (enumeration type)
-	float	arrow_thicknessAF;		// (1/80 inch)
-	float	arrow_widthAF;			// (Fig units)
-	float	arrow_heightAF;			// (Fig units)
-	int		arrow_typeAB;			// (enumeration type)
-	int		arrow_styleAB;			// (enumeration type)
-	float	arrow_thicknessAB;		// (1/80 inch)
-	float	arrow_widthAB;			// (Fig units)
-	float	arrow_heightAB;			// (Fig units)
-	FPointArray arrow;
-	int z = -1;
-	PageItem::ItemType iteType;
-	if (forward_arrow == 1)
-	{
-		arrow.resize(0);
-		ScTextStream CodeAF(&fArrowData, QIODevice::ReadOnly);
-		CodeAF >> arrow_typeAF >> arrow_styleAF >> arrow_thicknessAF >> arrow_widthAF >> arrow_heightAF;
-		arrow_widthAF = fig2Pts(arrow_widthAF);
-		arrow_heightAF = fig2Pts(arrow_heightAF);
-		arrow_thicknessAF = arrow_thicknessAF / 80.0 * 72.0;
-		FPoint End = ite->PoLine.point(ite->PoLine.size()-2);
-		for (uint xx = ite->PoLine.size()-1; xx > 0; xx -= 2)
-		{
-			FPoint Vector = ite->PoLine.point(xx);
-			if ((End.x() != Vector.x()) || (End.y() != Vector.y()))
-			{
-				double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI);
-				QTransform arrowTrans;
-				if (arrow_typeAF == 0)
-					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5");
-				else if (arrow_typeAF == 1)
-					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 z");
-				else if (arrow_typeAF == 2)
-					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 L -0.7 0 z");
-				else if (arrow_typeAF == 3)
-					arrow.parseSVG("M -0.7, -0.5 L 0, 0 L -0.7, 0.5 L -1 0 z");
-				arrowTrans.translate(End.x(), End.y());
-				arrowTrans.rotate(r);
-				arrowTrans.scale(arrow_heightAF, arrow_widthAF);
-				arrow.map(arrowTrans);
-				break;
-			}
-		}
-		QString fillC = "White";
-		if (arrow_styleAF == 1)
-			fillC = CurrColorStroke;
-		if (arrow_typeAF == 0)
-		{
-			fillC = CommonStrings::None;
-			iteType = PageItem::PolyLine;
-		}
-		else
-			iteType = PageItem::Polygon;
-		z = m_Doc->itemAdd(iteType, PageItem::Unspecified, ite->xPos(), ite->yPos(), 10, 10, arrow_thicknessAF, fillC, CurrColorStroke, true);
-		if (z >= 0)
-		{
-			PageItem *item = m_Doc->Items->at(z);
-			item->PoLine = arrow.copy();
-			item->ClipEdited = true;
-			item->FrameType = 3;
-			item->setFillShade(CurrFillShade);
-			item->setLineShade(CurrStrokeShade);
-			FPoint wh = getMaxClipF(&item->PoLine);
-			item->setWidthHeight(wh.x(),wh.y());
-			item->setTextFlowMode(PageItem::TextFlowDisabled);
-			m_Doc->AdjustItemSize(item);
-			item->setWidthHeight(qMax(item->width(), 1.0), qMax(item->height(), 1.0));
-			depthMap.insert(999 - depth, currentItemNr);
-			currentItemNr++;
-		}
-	}
-	if (backward_arrow == 1)
-	{
-		arrow.resize(0);
-		ScTextStream CodeAB(&bArrowData, QIODevice::ReadOnly);
-		CodeAB >> arrow_typeAB >> arrow_styleAB >> arrow_thicknessAB >> arrow_widthAB >> arrow_heightAB;
-		arrow_widthAB = fig2Pts(arrow_widthAB);
-		arrow_heightAB = fig2Pts(arrow_heightAB);
-		arrow_thicknessAB = arrow_thicknessAB / 80.0 * 72.0;
-		FPointArray arrow;
-		FPoint Start = ite->PoLine.point(0);
-		for (uint xx = 1; xx < ite->PoLine.size(); xx += 2)
-		{
-			FPoint Vector = ite->PoLine.point(xx);
-			if ((Start.x() != Vector.x()) || (Start.y() != Vector.y()))
-			{
-				double r = atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI);
-				QTransform arrowTrans;
-				if (arrow_typeAB == 0)
-					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5");
-				else if (arrow_typeAB == 1)
-					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 z");
-				else if (arrow_typeAB == 2)
-					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 L -0.7 0 z");
-				else if (arrow_typeAB == 3)
-					arrow.parseSVG("M -0.7, -0.5 L 0, 0 L -0.7, 0.5 L -1 0 z");
-				arrowTrans.translate(Start.x(), Start.y());
-				arrowTrans.rotate(r);
-				arrowTrans.scale(arrow_heightAB, arrow_widthAB);
-				arrow.map(arrowTrans);
-				break;
-			}
-		}
-		QString fillC = "White";
-		if (arrow_styleAB == 1)
-			fillC = CurrColorStroke;
-		if (arrow_typeAB == 0)
-		{
-			fillC = CommonStrings::None;
-			iteType = PageItem::PolyLine;
-		}
-		else
-			iteType = PageItem::Polygon;
-		z = m_Doc->itemAdd(iteType, PageItem::Unspecified, ite->xPos(), ite->yPos(), 10, 10, arrow_thicknessAB, fillC, CurrColorStroke, true);
-		if (z >= 0)
-		{
-			PageItem *item = m_Doc->Items->at(z);
-			item->PoLine = arrow.copy();
-			item->ClipEdited = true;
-			item->FrameType = 3;
-			item->setFillShade(CurrFillShade);
-			item->setLineShade(CurrStrokeShade);
-			FPoint wh = getMaxClipF(&item->PoLine);
-			item->setWidthHeight(wh.x(),wh.y());
-			item->setTextFlowMode(PageItem::TextFlowDisabled);
-			m_Doc->AdjustItemSize(item);
-			item->setWidthHeight(qMax(item->width(), 1.0), qMax(item->height(), 1.0));
-			depthMap.insert(999 - depth, currentItemNr);
-			currentItemNr++;
-		}
-	}
-}
-
-void XfigPlug::processPolyline(QDataStream &ts, QString data)
-{
-	QString tmp = data;
-	QString fArrowData = "";
-	QString bArrowData = "";
-	int		command;
-	int		subtype;				// (1: polyline, 2: box, 3: polygon, 4: arc-box, 5: imported-picture bounding-box)
-	int		line_style;				// (enumeration type)
-	int		thickness;				// (1/80 inch)
-	int		pen_color;				// (enumeration type, pen color)
-	int		fill_color;				// (enumeration type, fill color)
-	int		depth;					// (enumeration type)
-	int		pen_style;				// (pen style, not used)
-	int		area_fill;				// (enumeration type, -1 = no fill)
-	double	style_val;				// (1/80 inch)
-	int		join_style; 			// (enumeration type)
-	int		cap_style;				// (enumeration type, only used for POLYLINE)
-	int		radius;					// (1/80 inch, radius of arc-boxes)
-	int		forward_arrow;			// (0: off, 1: on)
-	int		backward_arrow;			// (0: off, 1: on)
-	int		npoints;				// (number of points in line)
-	int pointsRead = 0;
-	int imgFlipped;
-	QString imgFile;
-	double x, y;
-	Coords.resize(0);
-	Coords.svgInit();
-	bool first = true;
-	ScTextStream Code(&tmp, QIODevice::ReadOnly);
-	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
-	Code >> area_fill >> style_val >> join_style >> cap_style >> radius >> forward_arrow >> backward_arrow >> npoints;
-	if (forward_arrow == 1)
-		fArrowData = readLinefromDataStream(ts);
-	if (backward_arrow == 1)
-		bArrowData = readLinefromDataStream(ts);
-	if (subtype == 5)
-	{
-		tmp = readLinefromDataStream(ts);
-		ScTextStream imf(&tmp, QIODevice::ReadOnly);
-		imf >> imgFlipped >> imgFile;
-	}
-	while (!ts.atEnd())
-	{
-		tmp = readLinefromDataStream(ts);
-		ScTextStream pts(&tmp, QIODevice::ReadOnly);
-		while (!pts.atEnd())
-		{
-			pts >> x >> y;
-			x = fig2Pts(x) - docX;
-			y = fig2Pts(y) - docY;
-			if (first)
-			{
-				Coords.svgMoveTo(x, y);
-				first = false;
-			}
-			else
-				Coords.svgLineTo(x, y);
-			pointsRead++;
-		}
-		if (pointsRead == npoints)
-		{
-			if (npoints == 1)
-				Coords.svgLineTo(x, y);
-			break;
-		}
-	}
-	useColor(pen_color, 0, false);
-	useColor(fill_color, area_fill, true);
-	LineW = thickness / 80.0 * 72.0;
-	int z = -1;
-	PageItem *ite;
-	if (subtype == 1)
-		z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-	else if ((subtype == 2) || (subtype == 3) || (subtype == 4))
-	{
-		z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-		Coords.svgClosePath();
-	}
-	else if (subtype == 5)
-	{
-		z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-		Coords.svgClosePath();
-	}
-	else
-		z = -1;
-	if (z >= 0)
-	{
-		ite = m_Doc->Items->at(z);
-		ite->PoLine = Coords.copy();
-		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-		ite->ClipEdited = true;
-		ite->FrameType = 3;
-		ite->setFillShade(CurrFillShade);
-		ite->setLineShade(CurrStrokeShade);
-		if (line_style > 0)
-			ite->setDashes(getDashValues(LineW, line_style));
-		if (subtype == 1)
-		{
-			if (join_style == 0)
-				ite->setLineJoin(Qt::MiterJoin);
-			else if (join_style == 1)
-				ite->setLineJoin(Qt::RoundJoin);
-			else if (join_style == 2)
-				ite->setLineJoin(Qt::BevelJoin);
-			if (cap_style == 0)
-				ite->setLineEnd(Qt::FlatCap);
-			else if (cap_style == 1)
-				ite->setLineEnd(Qt::RoundCap);
-			else if (cap_style == 2)
-				ite->setLineEnd(Qt::SquareCap);
-		}
-		FPoint wh = getMaxClipF(&ite->PoLine);
-		ite->setWidthHeight(wh.x(),wh.y());
-		ite->setTextFlowMode(PageItem::TextFlowDisabled);
-		m_Doc->AdjustItemSize(ite);
-		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
-		if (subtype == 4)
-		{
-			ite->setCornerRadius(radius / 80.0 * 72.0);
-			ite->FrameType = 2;
-			ite->ClipEdited = false;
-			ite->updateClip();
-		}
-		if (subtype == 5)
-		{
-			ite->Pfile = baseFile + "/" + imgFile;
-			m_Doc->loadPict(ite->Pfile, ite, false);
-			ite->setImageXYScale(72.0 / 80.0, 72.0 / 80.0);
-			ite->setImageXYOffset(0, 0);
-		}
-		depthMap.insert(999 - depth, currentItemNr);
-		currentItemNr++;
-		if ((ite->itemType() == PageItem::PolyLine) && ((forward_arrow == 1) || (backward_arrow == 1)))
-			processArrows(forward_arrow, fArrowData, backward_arrow, bArrowData, depth, ite);
-	}
-}
-
-void XfigPlug::processSpline(QDataStream &ts, QString data)
-{
-	QString tmp = data;
-	QString fArrowData = "";
-	QString bArrowData = "";
-	int		command;
-	int		subtype;				// 0: open approximated spline
-									// 1: closed approximated spline
-									// 2: open   interpolated spline
-									// 3: closed interpolated spline
-									// 4: open   x-spline 
-									// 5: closed x-spline
-	int		line_style;				// (enumeration type)
-	int		thickness;				// (1/80 inch)
-	int		pen_color;				// (enumeration type, pen color)
-	int		fill_color;				// (enumeration type, fill color)
-	int		depth;					// (enumeration type)
-	int		pen_style;				// (pen style, not used)
-	int		area_fill;				// (enumeration type, -1 = no fill)
-	double	style_val;				// (1/80 inch)
-	int		cap_style;				// (enumeration type, only used for POLYLINE)
-	int		forward_arrow;			// (0: off, 1: on)
-	int		backward_arrow;			// (0: off, 1: on)
-	int		npoints;				// (number of points in line)
-	int pointsRead = 0;
-	double x, y;
-	Coords.resize(0);
-	Coords.svgInit();
-	bool first = true;
-	ScTextStream Code(&tmp, QIODevice::ReadOnly);
-	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
-	Code >> area_fill >> style_val >> cap_style >> forward_arrow >> backward_arrow >> npoints;
-	if (forward_arrow == 1)
-		fArrowData = readLinefromDataStream(ts);
-	if (backward_arrow == 1)
-		bArrowData = readLinefromDataStream(ts);
-	while (!ts.atEnd())
-	{
-		tmp = readLinefromDataStream(ts);
-		ScTextStream pts(&tmp, QIODevice::ReadOnly);
-		while (!pts.atEnd())
-		{
-			pts >> x >> y;
-			x = fig2Pts(x) - docX;
-			y = fig2Pts(y) - docY;
-			if (first)
-			{
-				Coords.svgMoveTo(x, y);
-				first = false;
-			}
-			else
-				Coords.svgLineTo(x, y);
-			pointsRead++;
-		}
-		if (pointsRead == npoints)
-		{
-			if (npoints == 1)
-				Coords.svgLineTo(x, y);
-			break;
-		}
-	}
-	pointsRead = 0;
-	while (!ts.atEnd())
-	{
-		tmp = readLinefromDataStream(ts);
-		ScTextStream pts(&tmp, QIODevice::ReadOnly);
-		while (!pts.atEnd())
-		{
-			pts >> x;
-			pointsRead++;
-		}
-		if (pointsRead == npoints)
-			break;
-	}
-	useColor(pen_color, 0, false);
-	useColor(fill_color, area_fill, true);
-	LineW = thickness / 80.0 * 72.0;
-	int z = -1;
-	PageItem *ite;
-	if ((subtype == 0) || (subtype == 2) || (subtype == 4))
-		z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-	else if ((subtype == 1) || (subtype == 3) || (subtype == 5))
-	{
-		z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-		Coords.svgClosePath();
-	}
-	if (z >= 0)
-	{
-		ite = m_Doc->Items->at(z);
-		ite->PoLine = Coords.copy();
-		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-		ite->ClipEdited = true;
-		ite->FrameType = 3;
-		ite->setFillShade(CurrFillShade);
-		ite->setLineShade(CurrStrokeShade);
-		if (line_style > 0)
-			ite->setDashes(getDashValues(LineW, line_style));
-		if ((subtype == 0) || (subtype == 2) || (subtype == 4))
-		{
-			if (cap_style == 0)
-				ite->setLineEnd(Qt::FlatCap);
-			else if (cap_style == 1)
-				ite->setLineEnd(Qt::RoundCap);
-			else if (cap_style == 2)
-				ite->setLineEnd(Qt::SquareCap);
-		}
-		FPoint wh = getMaxClipF(&ite->PoLine);
-		ite->setWidthHeight(wh.x(),wh.y());
-		ite->setTextFlowMode(PageItem::TextFlowDisabled);
-		m_Doc->AdjustItemSize(ite);
-		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
-		depthMap.insert(999 - depth, currentItemNr);
-		currentItemNr++;
-		if ((ite->itemType() == PageItem::PolyLine) && ((forward_arrow == 1) || (backward_arrow == 1)))
-			processArrows(forward_arrow, fArrowData, backward_arrow, bArrowData, depth, ite);
-	}
-}
-
-void XfigPlug::processArc(QDataStream &ts, QString data)
-{
-	QString tmp = data;
-	QString fArrowData = "";
-	QString bArrowData = "";
-	int		command;
-	int		subtype;				// (1: open ended arc, 2: pie-wedge (closed))
-	int		line_style;				// (enumeration type)
-	int		thickness;				// (1/80 inch)
-	int		pen_color;				// (enumeration type, pen color)
-	int		fill_color;				// (enumeration type, fill color)
-	int		depth;					// (enumeration type)
-	int		pen_style;				// (pen style, not used)
-	int		area_fill;				// (enumeration type, -1 = no fill)
-	double	style_val;				// (1/80 inch)
-	int		cap_style;				// (enumeration type, only used for POLYLINE)
-	int		direction;				// (always 1)
-	int		forward_arrow;			// (0: off, 1: on)
-	int		backward_arrow;			// (0: off, 1: on)
-	double	center_x, center_y;		// (center of the arc)
-	int		x1, y1;					// (Fig units, the 1st point the user entered)
-	int		x2, y2;					// (Fig units, the 2nd point)
-	int		x3, y3;					// (Fig units, the last point)
-	ScTextStream Code(&tmp, QIODevice::ReadOnly);
-	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
-	Code >> area_fill >> style_val >> cap_style >> direction >> forward_arrow >> backward_arrow;
-	Code >> center_x >> center_y >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
-	if (forward_arrow == 1)
-		fArrowData = readLinefromDataStream(ts);
-	if (backward_arrow == 1)
-		bArrowData = readLinefromDataStream(ts);
-	useColor(pen_color, 0, false);
-	useColor(fill_color, area_fill, true);
-	LineW = thickness / 80.0 * 72.0;
-	int z = -1;
-	PageItem *ite;
-	if (subtype == 1)
-		z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-	else if (subtype == 2)
-		z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
-	else
-		z = -1;
-	center_x = fig2Pts(center_x) - docX;
-	center_y = fig2Pts(center_y) - docY;
-	double x1R = fig2Pts(x1) - docX;
-	double y1R = fig2Pts(y1) - docY;
-	double x3R = fig2Pts(x3) - docX;
-	double y3R = fig2Pts(y3) - docY;
-	double r1 = distance(x1R - center_x, y1R - center_y);
-	double x0 = center_x - r1;
-	double y0 = center_y - r1;
-	QRectF bBox = QRectF(x0, y0, r1 * 2.0, r1 * 2.0);
-	double angle1 = -xy2Deg(x1R - center_x, y1R - center_y);
-	double angle2 = -xy2Deg(x3R - center_x, y3R - center_y);
-	double sweep;
-	if (direction == 0)
-	{
-		sweep = angle1 - angle2;
-		if (sweep < 0.0)
-			sweep = 360.0 + sweep;
-	}
-	else
-	{
-		sweep = angle2 - angle1;
-		if (sweep < 0.0)
-			sweep = 360.0 + sweep;
-		double an = angle1;
-		angle1 = angle2;
-		angle2 = an;
-	}
-	QPainterPath aPath;
-	if (subtype == 1)
-	{
-		aPath.arcMoveTo(bBox, angle2);
-		aPath.arcTo(bBox, angle2, sweep);
-	}
-	else
-	{
-		aPath.moveTo(center_x, center_y);
-		aPath.arcTo(bBox, angle2, sweep);
-		aPath.lineTo(center_x, center_y);
-	}
-	FPointArray points;
-	points.fromQPainterPath(aPath);
-
-	if (z >= 0)
-	{
-		ite = m_Doc->Items->at(z);
-		ite->PoLine = points.copy();
-		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
-		ite->ClipEdited = true;
-		ite->FrameType = 3;
-		ite->setFillShade(CurrFillShade);
-		ite->setLineShade(CurrStrokeShade);
-		if (line_style > 0)
-			ite->setDashes(getDashValues(LineW, line_style));
-		if (subtype == 1)
-		{
-			if (cap_style == 0)
-				ite->setLineEnd(Qt::FlatCap);
-			else if (cap_style == 1)
-				ite->setLineEnd(Qt::RoundCap);
-			else if (cap_style == 2)
-				ite->setLineEnd(Qt::SquareCap);
-		}
-		FPoint wh = getMaxClipF(&ite->PoLine);
-		ite->setWidthHeight(wh.x(),wh.y());
-		ite->setTextFlowMode(PageItem::TextFlowDisabled);
-		m_Doc->AdjustItemSize(ite);
-		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
-		depthMap.insert(999 - depth, currentItemNr);
-		currentItemNr++;
-		if ((ite->itemType() == PageItem::PolyLine) && ((forward_arrow == 1) || (backward_arrow == 1)))
-		{
-			if (direction == 1)
-				processArrows(forward_arrow, fArrowData, backward_arrow, bArrowData, depth, ite);
-			else
-				processArrows(backward_arrow, bArrowData, forward_arrow, fArrowData, depth, ite);
-		}
-	}
-}
-
-void XfigPlug::processEllipse(QString data)
-{
-	QString tmp = data;
-	int		command;			// (always 1)
-	int		subtype;			// (1: ellipse defined by radii
-								//  2: ellipse defined by diameters
-								//  3: circle defined by radius
-								//  4: circle defined by diameter)
-	int		line_style;			// (enumeration type)
-	int		thickness;			// (1/80 inch)
-	int		pen_color;			// (enumeration type, pen color)
-	int		fill_color;			// (enumeration type, fill color)
-	int		depth;				// (enumeration type)
-	int		pen_style;			// (pen style, not used)
-	int		area_fill;			// (enumeration type, -1 = no fill)
-	double	style_val;			// (1/80 inch)
-	int		direction;			// (always 1)
-	double	angle;				// (radians, the angle of the x-axis)
-	int		center_x, center_y;	// (Fig units)
-	int		radius_x, radius_y;	// (Fig units)
-	int		start_x, start_y;	// (Fig units; the 1st point entered)
-	int		end_x, end_y;		// (Fig units; the last point entered)
-	double x, y, w, h;
-	ScTextStream Code(&tmp, QIODevice::ReadOnly);
-	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
-	Code >> area_fill >> style_val >> direction >> angle >> center_x >> center_y >> radius_x >> radius_y;
-	Code >> start_x >> start_y >> end_x >> end_y;
-	useColor(pen_color, 0, false);
-	useColor(fill_color, area_fill, true);
-	LineW = thickness / 80.0 * 72.0;
-	w = fig2Pts(radius_x);
-	h = fig2Pts(radius_y);
-	x = fig2Pts(center_x) - w;
-	y = fig2Pts(center_y) - h;
-	w *= 2.0;
-	h *= 2.0;
-	x -= docX;
-	x += m_Doc->currentPage()->xOffset();
-	y -= docY;
-	y += m_Doc->currentPage()->yOffset();
-	int z = -1;
-	PageItem *ite;
-	z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX + x, baseY + y, w, h, LineW, CurrColorFill, CurrColorStroke, true);
-	if (z >= 0)
-	{
-		ite = m_Doc->Items->at(z);
-		ite->setFillShade(CurrFillShade);
-		ite->setLineShade(CurrStrokeShade);
-		if (line_style > 0)
-			ite->setDashes(getDashValues(LineW, line_style));
-		ite->setTextFlowMode(PageItem::TextFlowDisabled);
-		int rot = m_Doc->RotMode();
-		m_Doc->RotMode ( 2);
-		m_Doc->RotateItem(-angle * 180.0 / M_PI, ite);
-		m_Doc->RotMode( rot);
-		depthMap.insert(999 - depth, currentItemNr);
-		currentItemNr++;
-	}
-}
-
-QString XfigPlug::cleanText(QString text)
-{
-	QString ret = "";
-	QString tmp = "";
-	bool sep = false;
-	int sepcount = 0;
-	for (int a = 1; a < text.count(); ++a)
-	{
-		QString ch = text.mid(a,1);
-		if (sep)
-		{
-			if (ch == "\\")
-			{
-				ret += ch;
-				sep = false;
-			}
-			else
-			{
-				tmp += ch;
-				sepcount++;
-				if (sepcount == 3)
-				{
-					sep = false;
-					bool ok = false;
-					if (tmp != "001")
-					{
-						int code = tmp.toInt(&ok, 8);
-						if (ok)
-							ret += QChar(code);
-					}
-					tmp = "";
-				}
-			}
-		}
-		else
-		{
-			if (ch == "\\")
-			{
-				sep = true;
-				sepcount = 0;
-			}
-			else
-				ret += ch;
-		}
-	}
-	return ret;
-}
-
-void XfigPlug::processText(QString data)
-{
-	QString tmp = data;
-	int		command;			// (always 4)
-	int		subtype;			// (0: Left justified
-								//  1: Center justified
-								//  2: Right justified)
-	int		color;				// (enumeration type)
-	int		depth;				// (enumeration type)
-	int		pen_style;			// (enumeration , not used)
-	int		font;				// (enumeration type)
-	float	font_size;			// (font size in points)
-	float	angle;				// (radians, the angle of the text)
-	int		font_flags;			// (bit vector)
-	float	height;				// (Fig units)
-	float	length;				// (Fig units)
-	int		xT, yT;				// (Fig units, coordinate of the origin
-								//  of the string.  If sub_type = 0, it is
-								//  the lower left corner of the string.
-								//  If sub_type = 1, it is the lower
-								//  center.  Otherwise it is the lower
-								//  right corner of the string.)
-	QString text;
-	double x, y, w, h;
-	ScTextStream Code(&tmp, QIODevice::ReadOnly);
-	Code >> command >> subtype >> color >> depth >> pen_style >> font >> font_size >> angle;
-	Code >> font_flags >> height >> length >> xT >> yT;
-	text = Code.readAll();
-	text = cleanText(text);
-	FPointArray textPath;
-	QPainterPath painterPath;
-	QString TFont(m_Doc->itemToolPrefs().textFont);
-	QFont::Weight weight = QFont::Normal;
-	bool isItalic = false;
-	if (font_flags & 4)
-	{
-		switch (font)
-		{
-			case 0:
-				TFont = "Times Roman";
-				weight = QFont::Normal;
-				break;
-			case 1:
-				TFont = "Times Italic";
-				weight = QFont::Normal;
-				isItalic = true;
-				break;
-			case 2:
-				TFont = "Times Bold";
-				weight = QFont::Bold;
-				break;
-			case 3:
-				TFont = "Times Bold Italic";
-				weight = QFont::Bold;
-				isItalic = true;
-				break;
-			case 4:
-				TFont = "AvantGarde Book";
-				weight = QFont::Normal;
-				break;
-			case 5:
-				TFont = "AvantGarde Book Oblique";
-				weight = QFont::Normal;
-				break;
-			case 6:
-				TFont = "AvantGarde Demi";
-				weight = QFont::DemiBold;
-				break;
-			case 7:
-				TFont = "AvantGarde Demi Oblique";
-				weight = QFont::DemiBold;
-				break;
-			case 8:
-				TFont = "Bookman Light";
-				weight = QFont::Light;
-				break;
-			case 9:
-				TFont = "Bookman Light Italic";
-				weight = QFont::Light;
-				isItalic = true;
-				break;
-			case 10:
-				TFont = "Bookman Demi";
-				weight = QFont::DemiBold;
-				break;
-			case 11:
-				TFont = "Bookman Demi Italic";
-				weight = QFont::DemiBold;
-				isItalic = true;
-				break;
-			case 12:
-				TFont = "Courier";
-				weight = QFont::Normal;
-				break;
-			case 13:
-				TFont = "Courier Oblique";
-				weight = QFont::Normal;
-				break;
-			case 14:
-				TFont = "Courier Bold";
-				weight = QFont::Bold;
-				break;
-			case 15:
-				TFont = "Courier Bold Oblique";
-				weight = QFont::Bold;
-				break;
-			case 16:
-				TFont = "Helvetica";
-				weight = QFont::Normal;
-				break;
-			case 17:
-				TFont = "Helvetica Oblique";
-				weight = QFont::Normal;
-				break;
-			case 18:
-				TFont = "Helvetica Bold";
-				weight = QFont::Bold;
-				break;
-			case 19:
-				TFont = "Helvetica Bold Oblique";
-				weight = QFont::Bold;
-				break;
-			case 20:
-				TFont = "Helvetica Narrow";
-				weight = QFont::Normal;
-				break;
-			case 21:
-				TFont = "Helvetica Narrow Oblique";
-				weight = QFont::Normal;
-				break;
-			case 22:
-				TFont = "Helvetica Narrow Bold";
-				weight = QFont::Bold;
-				break;
-			case 23:
-				TFont = "Helvetica Narrow Bold Oblique";
-				weight = QFont::Bold;
-				break;
-			case 24:
-				TFont = "New Century Schoolbook Roman";
-				weight = QFont::Normal;
-				break;
-			case 25:
-				TFont = "New Century Schoolbook Italic";
-				weight = QFont::Normal;
-				isItalic = true;
-				break;
-			case 26:
-				TFont = "New Century Schoolbook Bold";
-				weight = QFont::Bold;
-				break;
-			case 27:
-				TFont = "New Century Schoolbook Bold Italic";
-				weight = QFont::Bold;
-				isItalic = true;
-				break;
-			case 28:
-				TFont = "Palatino Roman";
-				weight = QFont::Normal;
-				break;
-			case 29:
-				TFont = "Palatino Italic";
-				weight = QFont::Normal;
-				isItalic = true;
-				break;
-			case 30:
-				TFont = "Palatino Bold";
-				weight = QFont::Bold;
-				break;
-			case 31:
-				TFont = "Palatino Bold Italic";
-				weight = QFont::Bold;
-				isItalic = true;
-				break;
-			case 32:
-				TFont = "Symbol";
-				weight = QFont::Normal;
-				break;
-			case 33:
-				TFont = "Zapf Chancery Medium Italic";
-				weight = QFont::Normal;
-				isItalic = true;
-				break;
-			case 34:
-				TFont = "Zapf Dingbats";
-				weight = QFont::Normal;
-				break;
-			default:
-				TFont = m_Doc->itemToolPrefs().textFont;
-				weight = QFont::Normal;
-				break;
-		}
-	}
-	else
-	{
-		switch (font)
-		{
-    		case 1: // Roman
-				TFont = "Times";
-				weight = QFont::Normal;
-				break;
-			case 2: // Bold
-				TFont = "Times";
-				weight = QFont::Bold;
-				break;
-			case 3: // Italic
-				TFont = "Times";
-				weight = QFont::Normal;
-				isItalic = true;
-				break;
-			case 4: // Sans Serif
-				TFont = "Helvetica";
-				weight = QFont::Normal;
-				break;
-			case 5: // Typewriter
-				TFont = "Courier";
-				weight = QFont::Normal;
-				break;
-			default:
-				TFont = m_Doc->itemToolPrefs().textFont;
-				weight = QFont::Normal;
-				break;
-		}
-	}
-	w = fig2Pts(length);
-	h = fig2Pts(height);
-	x = fig2Pts(xT);
-	y = fig2Pts(yT);
-	x -= docX;
-	x += m_Doc->currentPage()->xOffset();
-	y -= docY;
-	y += m_Doc->currentPage()->yOffset();
-	QFont tf = QFont(TFont, 10, weight, isItalic);
-	tf.setPointSizeF(font_size / 80.0 * 72.0);
-	painterPath.addText( 0, 0, tf, text );
-	QRectF br = painterPath.boundingRect();
-	if ((angle == 0) && (br.width() > w))
-	{
-		QTransform m;
-		m.scale(w / br.width(), w / br.width());
-		painterPath = m.map(painterPath);
-	}
-	textPath.fromQPainterPath(painterPath);
-	useColor(color, 0, false);
-	int z = -1;
-	PageItem *ite;
-	z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX + x, baseY + y, w, h, 0, CurrColorStroke, CommonStrings::None, true);
-	if (z >= 0)
-	{
-		ite = m_Doc->Items->at(z);
-		ite->setRotation(-angle * 180.0 / M_PI);
-		ite->PoLine = textPath.copy();
-		ite->ClipEdited = true;
-		ite->FrameType = 3;
-		FPoint wh = getMaxClipF(&ite->PoLine);
-		ite->setWidthHeight(wh.x(),wh.y());
-		ite->setTextFlowMode(PageItem::TextFlowDisabled);
-		m_Doc->AdjustItemSize(ite);
-		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
-		if (subtype == 1)
-			m_Doc->MoveRotated(ite, FPoint(-br.width() / 2.0, 0.0));
-		else if (subtype == 2)
-			m_Doc->MoveRotated(ite, FPoint(-br.width(), 0.0));
-		depthMap.insert(999 - depth, currentItemNr);
-		currentItemNr++;
-	}
-}
-
-void XfigPlug::processData(QDataStream &ts, QString data)
-{
-	QString tmp = data;
-	int command, subtype;
-	ScTextStream Code(&tmp, QIODevice::ReadOnly);
-	Code >> command >> subtype;
-	switch (command)
-	{
-		case 0:
-			parseColor(data);
-			break;
-		case 1:
-			processEllipse(data);
-			break;
-		case 2:
-			processPolyline(ts, data);
-			break;
-		case 3:
-			processSpline(ts, data);
-			break;
-		case 4:
-			processText(data);
-			break;
-		case 5:
-			processArc(ts, data);
-			break;
-		case 6:
-//			qDebug() << "Xfig-Import:: Unsupported Compound object";
-			break;
-		case -6:
-//			qDebug() << "Xfig-Import:: Unsupported End of Compound object";
-			break;
-	}
-}
-
-void XfigPlug::resortItems()
-{
-	int ac = m_Doc->Items->count();
-	QList<PageItem*> itemList;
-	for (int as = oldDocItemCount; as < ac; ++as)
-	{
-		itemList.append(m_Doc->Items->takeAt(oldDocItemCount));
-	}
-	QList<int> keylist = depthMap.uniqueKeys();
-	int keysCount = keylist.count();
-	int currentLayer = 0;
-	for (int it = 0; it < keysCount; ++it)
-	{
-		if ((importerFlags & LoadSavePlugin::lfCreateDoc) && (it > 0))
-			currentLayer = m_Doc->addLayer(QString("Layer %1").arg(it), true);
-		QList<int> elems = depthMap.values(keylist.at(it));
-		qSort(elems);
-		int itemsCount = elems.count();
-		for (int i = 0; i < itemsCount; ++i)
-		{
-			PageItem* ite = itemList.at(elems.at(i));
-			Elements.append(ite);
-			m_Doc->Items->append(ite);
-			ite->ItemNr = m_Doc->Items->count()-1;
-			if ((importerFlags & LoadSavePlugin::lfCreateDoc) && (it > 0))
-				ite->LayerID = currentLayer;
-		}
-	}
-}
-
-
-double XfigPlug::fig2Pts(double in)
-{
-	return in / 1200.0 * 72.0;
-}
-
-bool XfigPlug::convert(QString fn)
-{
-	QString tmp;
-	CurrColorFill = "White";
-	CurrFillShade = 100.0;
-	CurrColorStroke = "Black";
-	CurrStrokeShade = 100.0;
-	patternMode = false;
-	patternX1 = 0.0;
-	patternY1 = 0.0;
-	patternX2 = 0.0;
-	patternY2 = 0.0;
-	Coords.resize(0);
-	Coords.svgInit();
-	clipCoords.resize(0);
-	clipCoords.svgInit();
-	currentPatternName = "";
-	currentPatternX = 0.0;
-	currentPatternY = 0.0;
-	currentPatternXScale = 1.0;
-	currentPatternYScale = 1.0;
-	currentPatternRotation = 0.0;
-	QList<PageItem*> gElements;
-	groupStack.push(gElements);
-	currentItemNr = 0;
-	if(progressDialog)
-	{
-		progressDialog->setOverallProgress(2);
-		progressDialog->setLabel("GI", tr("Generating Items"));
-		qApp->processEvents();
-	}
-	QFile f(fn);
-	if (f.open(QIODevice::ReadOnly))
-	{
-		oldDocItemCount = m_Doc->Items->count();
-		int fSize = (int) f.size();
-		if (progressDialog)
-		{
-			progressDialog->setTotalSteps("GI", fSize);
-			qApp->processEvents();
-		}
-		QDataStream ts(&f);
-		QString version = readLinefromDataStream(ts);
-		QString orientation = readLinefromDataStream(ts);
-		QString justification = readLinefromDataStream(ts);
-		QString units = readLinefromDataStream(ts);
-		QString papersize = readLinefromDataStream(ts);
-		QString magnification = readLinefromDataStream(ts);
-		QString multiple = readLinefromDataStream(ts);
-		QString transparent = readLinefromDataStream(ts);
-		tmp = readLinefromDataStream(ts);
-		if (tmp.startsWith("#"))
-			tmp = readLinefromDataStream(ts);
-		QString resolution = tmp;
-		while (!ts.atEnd())
-		{
-			tmp = readLinefromDataStream(ts);
-			if (tmp.startsWith("#"))
-				continue;
-			processData(ts, tmp);
-			if (progressDialog)
-			{
-				progressDialog->setProgress("GI", ts.device()->pos());
-				qApp->processEvents();
-			}
-		}
-		resortItems();
-	}
-	if (progressDialog)
-		progressDialog->close();
-	return true;
-}
+		m_Doc->view()->Deselect();
+	Elements.clear();
+	m_Doc->setLoading(true);
+	m_Doc->DoDrawing = false;
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+		m_Doc->view()->updatesOn(false);
+	m_Doc->scMW()->setScriptRunning(true);
+	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
+	QString CurDirP = QDir::currentPath();
+	QDir::setCurrent(fi.path());
+	if (convert(fName))
+	{
+		tmpSel->clear();
+		QDir::setCurrent(CurDirP);
+		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
+			m_Doc->groupObjectsList(Elements);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->setLoading(false);
+		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+		if ((Elements.count() > 0) && (!ret) && (interactive))
+		{
+			if (flags & LoadSavePlugin::lfScripted)
+			{
+				bool loadF = m_Doc->isLoading();
+				m_Doc->setLoading(false);
+				m_Doc->changed();
+				m_Doc->setLoading(loadF);
+				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+				{
+					m_Doc->m_Selection->delaySignalsOn();
+					for (int dre=0; dre<Elements.count(); ++dre)
+					{
+						m_Doc->m_Selection->addItem(Elements.at(dre), true);
+					}
+					m_Doc->m_Selection->delaySignalsOff();
+					m_Doc->m_Selection->setGroupRect();
+					m_Doc->view()->updatesOn(true);
+				}
+			}
+			else
+			{
+				m_Doc->DragP = true;
+				m_Doc->DraggedElem = 0;
+				m_Doc->DragElements.clear();
+				m_Doc->m_Selection->delaySignalsOn();
+				for (int dre=0; dre<Elements.count(); ++dre)
+				{
+					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
+					tmpSel->addItem(Elements.at(dre), true);
+				}
+				tmpSel->setGroupRect();
+				ScriXmlDoc *ss = new ScriXmlDoc();
+				ScElemMimeData* md = new ScElemMimeData();
+				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
+				delete ss;
+/*#ifndef Q_WS_MAC*/
+// see #2196
+				m_Doc->itemSelection_DeleteItem(tmpSel);
+/*#else
+				qDebug("xfigimport: leaving items on page");
+#endif*/
+				m_Doc->view()->updatesOn(true);
+				m_Doc->m_Selection->delaySignalsOff();
+				// We must copy the TransationSettings object as it is owned
+				// by handleObjectImport method afterwards
+				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
+				m_Doc->view()->handleObjectImport(md, transacSettings);
+				m_Doc->DragP = false;
+				m_Doc->DraggedElem = 0;
+				m_Doc->DragElements.clear();
+			}
+		}
+		else
+		{
+			m_Doc->changed();
+			m_Doc->reformPages();
+			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+				m_Doc->view()->updatesOn(true);
+		}
+		success = true;
+	}
+	else
+	{
+		QDir::setCurrent(CurDirP);
+		m_Doc->DoDrawing = true;
+		m_Doc->scMW()->setScriptRunning(false);
+		m_Doc->view()->updatesOn(true);
+		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
+	}
+	if (interactive)
+		m_Doc->setLoading(false);
+	//CB If we have a gui we must refresh it if we have used the progressbar
+	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
+	{
+		if ((showProgress) && (!interactive))
+			m_Doc->view()->DrawNew();
+	}
+	return success;
+}
+
+XfigPlug::~XfigPlug()
+{
+	if (progressDialog)
+		delete progressDialog;
+	delete tmpSel;
+}
+
+bool XfigPlug::parseHeader(QString fName, double &x, double &y, double &b, double &h)
+{
+	QString tmp, BBox, tmp2, FarNam;
+	ScColor cc;
+	bool found = false;
+	QFile f(fName);
+	if (f.open(QIODevice::ReadOnly))
+	{
+		QDataStream ts(&f);
+		QString version = readLinefromDataStream(ts);
+		if (!version.startsWith("#FIG 3"))
+		{
+			f.close();
+			return false;
+		}
+		QString orientation = readLinefromDataStream(ts);
+		QString justification = readLinefromDataStream(ts);
+		QString units = readLinefromDataStream(ts);
+		QString papersize = readLinefromDataStream(ts);
+		PageSize ps(papersize);
+		if (orientation.startsWith("Landscape"))
+		{
+			h = ps.width();
+			b = ps.height();
+		}
+		else
+		{
+			b = ps.width();
+			h = ps.height();
+		}
+		f.close();
+		found = true;
+	}
+	return found;
+}
+
+void XfigPlug::parseColor(QString data)
+{
+	if (data.isEmpty())
+		return;
+	int colorNum, dummy;
+	QString colorValues;
+	ScColor tmp;
+	ScTextStream Code(&data, QIODevice::ReadOnly);
+	Code >> dummy >> colorNum >> colorValues;
+	tmp.setNamedColor(colorValues);
+	tmp.setSpotColor(false);
+	tmp.setRegistrationColor(false);
+	QString namPrefix = "FromXfig%1-"+colorValues;
+	CustColors.insert(namPrefix.arg(colorNum), tmp);
+	importedColors.insert(colorNum, namPrefix.arg(colorNum));
+}
+
+void XfigPlug::useColor(int colorNum, int area_fill, bool forFill)
+{
+	QString color = CommonStrings::None;
+	int shade = 100;
+	if (forFill)
+	{
+		if (area_fill == -1)
+			color = CommonStrings::None;
+		else
+		{
+			if ((colorNum == -1) || (colorNum == 0))
+			{
+				if (area_fill == 0)
+				{
+					color = "White";
+					shade = 100;
+				}
+				else if (area_fill == 20)
+				{
+					color = "Black";
+					shade = 100;
+				}
+				else if ((area_fill > 0) && (area_fill < 20))
+				{
+					color = "Black";
+					shade = qRound(100.0 / 19.0 * area_fill);
+				}
+			}
+			else if (colorNum == 7)
+			{
+				if (area_fill == 0)
+				{
+					color = "Black";
+					shade = 100;
+				}
+				else if (area_fill == 20)
+				{
+					color = "White";
+					shade = 100;
+				}
+				else if ((area_fill > 0) && (area_fill < 20))
+				{
+					color = "Black";
+					shade = qRound(100.0 / 19.0 * (20 - area_fill));
+				}
+			}
+			else
+			{
+				if (importedColors.contains(colorNum))
+				{
+					color = importedColors[colorNum];
+					if (!m_Doc->PageColors.contains(color))
+						m_Doc->PageColors.insert(color, CustColors[color]);
+					int sat = area_fill - 20;
+					if ((sat > 0) && (sat < 20))
+						shade = qRound(100.0 / 19.0 * sat);
+				}
+				else
+					color = CommonStrings::None;
+			}
+		}
+		CurrColorFill = color;
+		CurrFillShade = shade;
+	}
+	else
+	{
+		if (area_fill == -1)
+			CurrColorStroke = CommonStrings::None;
+		else
+		{
+			if ((colorNum == -1) || (colorNum == 0))
+				CurrColorStroke = "Black";
+			else
+			{
+				if (importedColors.contains(colorNum))
+				{
+					CurrColorStroke = importedColors[colorNum];
+					if (!m_Doc->PageColors.contains(CurrColorStroke))
+						m_Doc->PageColors.insert(CurrColorStroke, CustColors[CurrColorStroke]);
+				}
+				else
+					CurrColorStroke = CommonStrings::None;
+			}
+		}
+	}
+}
+
+QVector<double> XfigPlug::getDashValues(double linewidth, int code)
+{
+	QVector<double> tmp;
+	if (code == 1)
+	{
+		tmp << qMax(4.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+	}
+	else if (code == 2)
+	{
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+	}
+	else if (code == 3)
+	{
+		tmp << qMax(4.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+	}
+	else if (code == 4)
+	{
+		tmp << qMax(4.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+	}
+	else if (code == 5)
+	{
+		tmp << qMax(4.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+		tmp << qMax(1.0 * linewidth, 0.1);
+		tmp << qMax(2.0 * linewidth, 0.1);
+	}
+	return tmp;
+}
+
+void XfigPlug::processArrows(int forward_arrow, QString fArrowData, int backward_arrow, QString bArrowData, int depth, PageItem *ite)
+{
+	int		arrow_typeAF;			// (enumeration type)
+	int		arrow_styleAF;			// (enumeration type)
+	float	arrow_thicknessAF;		// (1/80 inch)
+	float	arrow_widthAF;			// (Fig units)
+	float	arrow_heightAF;			// (Fig units)
+	int		arrow_typeAB;			// (enumeration type)
+	int		arrow_styleAB;			// (enumeration type)
+	float	arrow_thicknessAB;		// (1/80 inch)
+	float	arrow_widthAB;			// (Fig units)
+	float	arrow_heightAB;			// (Fig units)
+	FPointArray arrow;
+	int z = -1;
+	PageItem::ItemType iteType;
+	if (forward_arrow == 1)
+	{
+		arrow.resize(0);
+		ScTextStream CodeAF(&fArrowData, QIODevice::ReadOnly);
+		CodeAF >> arrow_typeAF >> arrow_styleAF >> arrow_thicknessAF >> arrow_widthAF >> arrow_heightAF;
+		arrow_widthAF = fig2Pts(arrow_widthAF);
+		arrow_heightAF = fig2Pts(arrow_heightAF);
+		arrow_thicknessAF = arrow_thicknessAF / 80.0 * 72.0;
+		FPoint End = ite->PoLine.point(ite->PoLine.size()-2);
+		for (uint xx = ite->PoLine.size()-1; xx > 0; xx -= 2)
+		{
+			FPoint Vector = ite->PoLine.point(xx);
+			if ((End.x() != Vector.x()) || (End.y() != Vector.y()))
+			{
+				double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI);
+				QTransform arrowTrans;
+				if (arrow_typeAF == 0)
+					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5");
+				else if (arrow_typeAF == 1)
+					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 z");
+				else if (arrow_typeAF == 2)
+					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 L -0.7 0 z");
+				else if (arrow_typeAF == 3)
+					arrow.parseSVG("M -0.7, -0.5 L 0, 0 L -0.7, 0.5 L -1 0 z");
+				arrowTrans.translate(End.x(), End.y());
+				arrowTrans.rotate(r);
+				arrowTrans.scale(arrow_heightAF, arrow_widthAF);
+				arrow.map(arrowTrans);
+				break;
+			}
+		}
+		QString fillC = "White";
+		if (arrow_styleAF == 1)
+			fillC = CurrColorStroke;
+		if (arrow_typeAF == 0)
+		{
+			fillC = CommonStrings::None;
+			iteType = PageItem::PolyLine;
+		}
+		else
+			iteType = PageItem::Polygon;
+		z = m_Doc->itemAdd(iteType, PageItem::Unspecified, ite->xPos(), ite->yPos(), 10, 10, arrow_thicknessAF, fillC, CurrColorStroke, true);
+		if (z >= 0)
+		{
+			PageItem *item = m_Doc->Items->at(z);
+			item->PoLine = arrow.copy();
+			item->ClipEdited = true;
+			item->FrameType = 3;
+			item->setFillShade(CurrFillShade);
+			item->setLineShade(CurrStrokeShade);
+			FPoint wh = getMaxClipF(&item->PoLine);
+			item->setWidthHeight(wh.x(),wh.y());
+			item->setTextFlowMode(PageItem::TextFlowDisabled);
+			m_Doc->AdjustItemSize(item);
+			item->setWidthHeight(qMax(item->width(), 1.0), qMax(item->height(), 1.0));
+			depthMap.insert(999 - depth, currentItemNr);
+			currentItemNr++;
+		}
+	}
+	if (backward_arrow == 1)
+	{
+		arrow.resize(0);
+		ScTextStream CodeAB(&bArrowData, QIODevice::ReadOnly);
+		CodeAB >> arrow_typeAB >> arrow_styleAB >> arrow_thicknessAB >> arrow_widthAB >> arrow_heightAB;
+		arrow_widthAB = fig2Pts(arrow_widthAB);
+		arrow_heightAB = fig2Pts(arrow_heightAB);
+		arrow_thicknessAB = arrow_thicknessAB / 80.0 * 72.0;
+		FPointArray arrow;
+		FPoint Start = ite->PoLine.point(0);
+		for (uint xx = 1; xx < ite->PoLine.size(); xx += 2)
+		{
+			FPoint Vector = ite->PoLine.point(xx);
+			if ((Start.x() != Vector.x()) || (Start.y() != Vector.y()))
+			{
+				double r = atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI);
+				QTransform arrowTrans;
+				if (arrow_typeAB == 0)
+					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5");
+				else if (arrow_typeAB == 1)
+					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 z");
+				else if (arrow_typeAB == 2)
+					arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 L -0.7 0 z");
+				else if (arrow_typeAB == 3)
+					arrow.parseSVG("M -0.7, -0.5 L 0, 0 L -0.7, 0.5 L -1 0 z");
+				arrowTrans.translate(Start.x(), Start.y());
+				arrowTrans.rotate(r);
+				arrowTrans.scale(arrow_heightAB, arrow_widthAB);
+				arrow.map(arrowTrans);
+				break;
+			}
+		}
+		QString fillC = "White";
+		if (arrow_styleAB == 1)
+			fillC = CurrColorStroke;
+		if (arrow_typeAB == 0)
+		{
+			fillC = CommonStrings::None;
+			iteType = PageItem::PolyLine;
+		}
+		else
+			iteType = PageItem::Polygon;
+		z = m_Doc->itemAdd(iteType, PageItem::Unspecified, ite->xPos(), ite->yPos(), 10, 10, arrow_thicknessAB, fillC, CurrColorStroke, true);
+		if (z >= 0)
+		{
+			PageItem *item = m_Doc->Items->at(z);
+			item->PoLine = arrow.copy();
+			item->ClipEdited = true;
+			item->FrameType = 3;
+			item->setFillShade(CurrFillShade);
+			item->setLineShade(CurrStrokeShade);
+			FPoint wh = getMaxClipF(&item->PoLine);
+			item->setWidthHeight(wh.x(),wh.y());
+			item->setTextFlowMode(PageItem::TextFlowDisabled);
+			m_Doc->AdjustItemSize(item);
+			item->setWidthHeight(qMax(item->width(), 1.0), qMax(item->height(), 1.0));
+			depthMap.insert(999 - depth, currentItemNr);
+			currentItemNr++;
+		}
+	}
+}
+
+void XfigPlug::processPolyline(QDataStream &ts, QString data)
+{
+	QString tmp = data;
+	QString fArrowData = "";
+	QString bArrowData = "";
+	int		command;
+	int		subtype;				// (1: polyline, 2: box, 3: polygon, 4: arc-box, 5: imported-picture bounding-box)
+	int		line_style;				// (enumeration type)
+	int		thickness;				// (1/80 inch)
+	int		pen_color;				// (enumeration type, pen color)
+	int		fill_color;				// (enumeration type, fill color)
+	int		depth;					// (enumeration type)
+	int		pen_style;				// (pen style, not used)
+	int		area_fill;				// (enumeration type, -1 = no fill)
+	double	style_val;				// (1/80 inch)
+	int		join_style; 			// (enumeration type)
+	int		cap_style;				// (enumeration type, only used for POLYLINE)
+	int		radius;					// (1/80 inch, radius of arc-boxes)
+	int		forward_arrow;			// (0: off, 1: on)
+	int		backward_arrow;			// (0: off, 1: on)
+	int		npoints;				// (number of points in line)
+	int pointsRead = 0;
+	int imgFlipped;
+	QString imgFile;
+	double x, y;
+	Coords.resize(0);
+	Coords.svgInit();
+	bool first = true;
+	ScTextStream Code(&tmp, QIODevice::ReadOnly);
+	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
+	Code >> area_fill >> style_val >> join_style >> cap_style >> radius >> forward_arrow >> backward_arrow >> npoints;
+	if (forward_arrow == 1)
+		fArrowData = readLinefromDataStream(ts);
+	if (backward_arrow == 1)
+		bArrowData = readLinefromDataStream(ts);
+	if (subtype == 5)
+	{
+		tmp = readLinefromDataStream(ts);
+		ScTextStream imf(&tmp, QIODevice::ReadOnly);
+		imf >> imgFlipped >> imgFile;
+	}
+	while (!ts.atEnd())
+	{
+		tmp = readLinefromDataStream(ts);
+		ScTextStream pts(&tmp, QIODevice::ReadOnly);
+		while (!pts.atEnd())
+		{
+			pts >> x >> y;
+			x = fig2Pts(x) - docX;
+			y = fig2Pts(y) - docY;
+			if (first)
+			{
+				Coords.svgMoveTo(x, y);
+				first = false;
+			}
+			else
+				Coords.svgLineTo(x, y);
+			pointsRead++;
+		}
+		if (pointsRead == npoints)
+		{
+			if (npoints == 1)
+				Coords.svgLineTo(x, y);
+			break;
+		}
+	}
+	useColor(pen_color, 0, false);
+	useColor(fill_color, area_fill, true);
+	LineW = thickness / 80.0 * 72.0;
+	int z = -1;
+	PageItem *ite;
+	if (subtype == 1)
+		z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+	else if ((subtype == 2) || (subtype == 3) || (subtype == 4))
+	{
+		z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+		Coords.svgClosePath();
+	}
+	else if (subtype == 5)
+	{
+		z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+		Coords.svgClosePath();
+	}
+	else
+		z = -1;
+	if (z >= 0)
+	{
+		ite = m_Doc->Items->at(z);
+		ite->PoLine = Coords.copy();
+		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+		ite->ClipEdited = true;
+		ite->FrameType = 3;
+		ite->setFillShade(CurrFillShade);
+		ite->setLineShade(CurrStrokeShade);
+		if (line_style > 0)
+			ite->setDashes(getDashValues(LineW, line_style));
+		if (subtype == 1)
+		{
+			if (join_style == 0)
+				ite->setLineJoin(Qt::MiterJoin);
+			else if (join_style == 1)
+				ite->setLineJoin(Qt::RoundJoin);
+			else if (join_style == 2)
+				ite->setLineJoin(Qt::BevelJoin);
+			if (cap_style == 0)
+				ite->setLineEnd(Qt::FlatCap);
+			else if (cap_style == 1)
+				ite->setLineEnd(Qt::RoundCap);
+			else if (cap_style == 2)
+				ite->setLineEnd(Qt::SquareCap);
+		}
+		FPoint wh = getMaxClipF(&ite->PoLine);
+		ite->setWidthHeight(wh.x(),wh.y());
+		ite->setTextFlowMode(PageItem::TextFlowDisabled);
+		m_Doc->AdjustItemSize(ite);
+		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
+		if (subtype == 4)
+		{
+			ite->setCornerRadius(radius / 80.0 * 72.0);
+			ite->FrameType = 2;
+			ite->ClipEdited = false;
+			ite->updateClip();
+		}
+		if (subtype == 5)
+		{
+			ite->Pfile = baseFile + "/" + imgFile;
+			m_Doc->loadPict(ite->Pfile, ite, false);
+			ite->setImageXYScale(72.0 / 80.0, 72.0 / 80.0);
+			ite->setImageXYOffset(0, 0);
+		}
+		depthMap.insert(999 - depth, currentItemNr);
+		currentItemNr++;
+		if ((ite->itemType() == PageItem::PolyLine) && ((forward_arrow == 1) || (backward_arrow == 1)))
+			processArrows(forward_arrow, fArrowData, backward_arrow, bArrowData, depth, ite);
+	}
+}
+
+void XfigPlug::processSpline(QDataStream &ts, QString data)
+{
+	QString tmp = data;
+	QString fArrowData = "";
+	QString bArrowData = "";
+	int		command;
+	int		subtype;				// 0: open approximated spline
+									// 1: closed approximated spline
+									// 2: open   interpolated spline
+									// 3: closed interpolated spline
+									// 4: open   x-spline 
+									// 5: closed x-spline
+	int		line_style;				// (enumeration type)
+	int		thickness;				// (1/80 inch)
+	int		pen_color;				// (enumeration type, pen color)
+	int		fill_color;				// (enumeration type, fill color)
+	int		depth;					// (enumeration type)
+	int		pen_style;				// (pen style, not used)
+	int		area_fill;				// (enumeration type, -1 = no fill)
+	double	style_val;				// (1/80 inch)
+	int		cap_style;				// (enumeration type, only used for POLYLINE)
+	int		forward_arrow;			// (0: off, 1: on)
+	int		backward_arrow;			// (0: off, 1: on)
+	int		npoints;				// (number of points in line)
+	int pointsRead = 0;
+	double x, y;
+	Coords.resize(0);
+	Coords.svgInit();
+	bool first = true;
+	ScTextStream Code(&tmp, QIODevice::ReadOnly);
+	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
+	Code >> area_fill >> style_val >> cap_style >> forward_arrow >> backward_arrow >> npoints;
+	if (forward_arrow == 1)
+		fArrowData = readLinefromDataStream(ts);
+	if (backward_arrow == 1)
+		bArrowData = readLinefromDataStream(ts);
+	while (!ts.atEnd())
+	{
+		tmp = readLinefromDataStream(ts);
+		ScTextStream pts(&tmp, QIODevice::ReadOnly);
+		while (!pts.atEnd())
+		{
+			pts >> x >> y;
+			x = fig2Pts(x) - docX;
+			y = fig2Pts(y) - docY;
+			if (first)
+			{
+				Coords.svgMoveTo(x, y);
+				first = false;
+			}
+			else
+				Coords.svgLineTo(x, y);
+			pointsRead++;
+		}
+		if (pointsRead == npoints)
+		{
+			if (npoints == 1)
+				Coords.svgLineTo(x, y);
+			break;
+		}
+	}
+	pointsRead = 0;
+	while (!ts.atEnd())
+	{
+		tmp = readLinefromDataStream(ts);
+		ScTextStream pts(&tmp, QIODevice::ReadOnly);
+		while (!pts.atEnd())
+		{
+			pts >> x;
+			pointsRead++;
+		}
+		if (pointsRead == npoints)
+			break;
+	}
+	useColor(pen_color, 0, false);
+	useColor(fill_color, area_fill, true);
+	LineW = thickness / 80.0 * 72.0;
+	int z = -1;
+	PageItem *ite;
+	if ((subtype == 0) || (subtype == 2) || (subtype == 4))
+		z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+	else if ((subtype == 1) || (subtype == 3) || (subtype == 5))
+	{
+		z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+		Coords.svgClosePath();
+	}
+	if (z >= 0)
+	{
+		ite = m_Doc->Items->at(z);
+		ite->PoLine = Coords.copy();
+		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+		ite->ClipEdited = true;
+		ite->FrameType = 3;
+		ite->setFillShade(CurrFillShade);
+		ite->setLineShade(CurrStrokeShade);
+		if (line_style > 0)
+			ite->setDashes(getDashValues(LineW, line_style));
+		if ((subtype == 0) || (subtype == 2) || (subtype == 4))
+		{
+			if (cap_style == 0)
+				ite->setLineEnd(Qt::FlatCap);
+			else if (cap_style == 1)
+				ite->setLineEnd(Qt::RoundCap);
+			else if (cap_style == 2)
+				ite->setLineEnd(Qt::SquareCap);
+		}
+		FPoint wh = getMaxClipF(&ite->PoLine);
+		ite->setWidthHeight(wh.x(),wh.y());
+		ite->setTextFlowMode(PageItem::TextFlowDisabled);
+		m_Doc->AdjustItemSize(ite);
+		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
+		depthMap.insert(999 - depth, currentItemNr);
+		currentItemNr++;
+		if ((ite->itemType() == PageItem::PolyLine) && ((forward_arrow == 1) || (backward_arrow == 1)))
+			processArrows(forward_arrow, fArrowData, backward_arrow, bArrowData, depth, ite);
+	}
+}
+
+void XfigPlug::processArc(QDataStream &ts, QString data)
+{
+	QString tmp = data;
+	QString fArrowData = "";
+	QString bArrowData = "";
+	int		command;
+	int		subtype;				// (1: open ended arc, 2: pie-wedge (closed))
+	int		line_style;				// (enumeration type)
+	int		thickness;				// (1/80 inch)
+	int		pen_color;				// (enumeration type, pen color)
+	int		fill_color;				// (enumeration type, fill color)
+	int		depth;					// (enumeration type)
+	int		pen_style;				// (pen style, not used)
+	int		area_fill;				// (enumeration type, -1 = no fill)
+	double	style_val;				// (1/80 inch)
+	int		cap_style;				// (enumeration type, only used for POLYLINE)
+	int		direction;				// (always 1)
+	int		forward_arrow;			// (0: off, 1: on)
+	int		backward_arrow;			// (0: off, 1: on)
+	double	center_x, center_y;		// (center of the arc)
+	int		x1, y1;					// (Fig units, the 1st point the user entered)
+	int		x2, y2;					// (Fig units, the 2nd point)
+	int		x3, y3;					// (Fig units, the last point)
+	ScTextStream Code(&tmp, QIODevice::ReadOnly);
+	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
+	Code >> area_fill >> style_val >> cap_style >> direction >> forward_arrow >> backward_arrow;
+	Code >> center_x >> center_y >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
+	if (forward_arrow == 1)
+		fArrowData = readLinefromDataStream(ts);
+	if (backward_arrow == 1)
+		bArrowData = readLinefromDataStream(ts);
+	useColor(pen_color, 0, false);
+	useColor(fill_color, area_fill, true);
+	LineW = thickness / 80.0 * 72.0;
+	int z = -1;
+	PageItem *ite;
+	if (subtype == 1)
+		z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+	else if (subtype == 2)
+		z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColorFill, CurrColorStroke, true);
+	else
+		z = -1;
+	center_x = fig2Pts(center_x) - docX;
+	center_y = fig2Pts(center_y) - docY;
+	double x1R = fig2Pts(x1) - docX;
+	double y1R = fig2Pts(y1) - docY;
+	double x3R = fig2Pts(x3) - docX;
+	double y3R = fig2Pts(y3) - docY;
+	double r1 = distance(x1R - center_x, y1R - center_y);
+	double x0 = center_x - r1;
+	double y0 = center_y - r1;
+	QRectF bBox = QRectF(x0, y0, r1 * 2.0, r1 * 2.0);
+	double angle1 = -xy2Deg(x1R - center_x, y1R - center_y);
+	double angle2 = -xy2Deg(x3R - center_x, y3R - center_y);
+	double sweep;
+	if (direction == 0)
+	{
+		sweep = angle1 - angle2;
+		if (sweep < 0.0)
+			sweep = 360.0 + sweep;
+	}
+	else
+	{
+		sweep = angle2 - angle1;
+		if (sweep < 0.0)
+			sweep = 360.0 + sweep;
+		double an = angle1;
+		angle1 = angle2;
+		angle2 = an;
+	}
+	QPainterPath aPath;
+	if (subtype == 1)
+	{
+		aPath.arcMoveTo(bBox, angle2);
+		aPath.arcTo(bBox, angle2, sweep);
+	}
+	else
+	{
+		aPath.moveTo(center_x, center_y);
+		aPath.arcTo(bBox, angle2, sweep);
+		aPath.lineTo(center_x, center_y);
+	}
+	FPointArray points;
+	points.fromQPainterPath(aPath);
+
+	if (z >= 0)
+	{
+		ite = m_Doc->Items->at(z);
+		ite->PoLine = points.copy();
+		ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
+		ite->ClipEdited = true;
+		ite->FrameType = 3;
+		ite->setFillShade(CurrFillShade);
+		ite->setLineShade(CurrStrokeShade);
+		if (line_style > 0)
+			ite->setDashes(getDashValues(LineW, line_style));
+		if (subtype == 1)
+		{
+			if (cap_style == 0)
+				ite->setLineEnd(Qt::FlatCap);
+			else if (cap_style == 1)
+				ite->setLineEnd(Qt::RoundCap);
+			else if (cap_style == 2)
+				ite->setLineEnd(Qt::SquareCap);
+		}
+		FPoint wh = getMaxClipF(&ite->PoLine);
+		ite->setWidthHeight(wh.x(),wh.y());
+		ite->setTextFlowMode(PageItem::TextFlowDisabled);
+		m_Doc->AdjustItemSize(ite);
+		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
+		depthMap.insert(999 - depth, currentItemNr);
+		currentItemNr++;
+		if ((ite->itemType() == PageItem::PolyLine) && ((forward_arrow == 1) || (backward_arrow == 1)))
+		{
+			if (direction == 1)
+				processArrows(forward_arrow, fArrowData, backward_arrow, bArrowData, depth, ite);
+			else
+				processArrows(backward_arrow, bArrowData, forward_arrow, fArrowData, depth, ite);
+		}
+	}
+}
+
+void XfigPlug::processEllipse(QString data)
+{
+	QString tmp = data;
+	int		command;			// (always 1)
+	int		subtype;			// (1: ellipse defined by radii
+								//  2: ellipse defined by diameters
+								//  3: circle defined by radius
+								//  4: circle defined by diameter)
+	int		line_style;			// (enumeration type)
+	int		thickness;			// (1/80 inch)
+	int		pen_color;			// (enumeration type, pen color)
+	int		fill_color;			// (enumeration type, fill color)
+	int		depth;				// (enumeration type)
+	int		pen_style;			// (pen style, not used)
+	int		area_fill;			// (enumeration type, -1 = no fill)
+	double	style_val;			// (1/80 inch)
+	int		direction;			// (always 1)
+	double	angle;				// (radians, the angle of the x-axis)
+	int		center_x, center_y;	// (Fig units)
+	int		radius_x, radius_y;	// (Fig units)
+	int		start_x, start_y;	// (Fig units; the 1st point entered)
+	int		end_x, end_y;		// (Fig units; the last point entered)
+	double x, y, w, h;
+	ScTextStream Code(&tmp, QIODevice::ReadOnly);
+	Code >> command >> subtype >> line_style >> thickness >> pen_color >> fill_color >> depth >> pen_style;
+	Code >> area_fill >> style_val >> direction >> angle >> center_x >> center_y >> radius_x >> radius_y;
+	Code >> start_x >> start_y >> end_x >> end_y;
+	useColor(pen_color, 0, false);
+	useColor(fill_color, area_fill, true);
+	LineW = thickness / 80.0 * 72.0;
+	w = fig2Pts(radius_x);
+	h = fig2Pts(radius_y);
+	x = fig2Pts(center_x) - w;
+	y = fig2Pts(center_y) - h;
+	w *= 2.0;
+	h *= 2.0;
+	x -= docX;
+	x += m_Doc->currentPage()->xOffset();
+	y -= docY;
+	y += m_Doc->currentPage()->yOffset();
+	int z = -1;
+	PageItem *ite;
+	z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX + x, baseY + y, w, h, LineW, CurrColorFill, CurrColorStroke, true);
+	if (z >= 0)
+	{
+		ite = m_Doc->Items->at(z);
+		ite->setFillShade(CurrFillShade);
+		ite->setLineShade(CurrStrokeShade);
+		if (line_style > 0)
+			ite->setDashes(getDashValues(LineW, line_style));
+		ite->setTextFlowMode(PageItem::TextFlowDisabled);
+		int rot = m_Doc->RotMode();
+		m_Doc->RotMode ( 2);
+		m_Doc->RotateItem(-angle * 180.0 / M_PI, ite);
+		m_Doc->RotMode( rot);
+		depthMap.insert(999 - depth, currentItemNr);
+		currentItemNr++;
+	}
+}
+
+QString XfigPlug::cleanText(QString text)
+{
+	QString ret = "";
+	QString tmp = "";
+	bool sep = false;
+	int sepcount = 0;
+	for (int a = 1; a < text.count(); ++a)
+	{
+		QString ch = text.mid(a,1);
+		if (sep)
+		{
+			if (ch == "\\")
+			{
+				ret += ch;
+				sep = false;
+			}
+			else
+			{
+				tmp += ch;
+				sepcount++;
+				if (sepcount == 3)
+				{
+					sep = false;
+					bool ok = false;
+					if (tmp != "001")
+					{
+						int code = tmp.toInt(&ok, 8);
+						if (ok)
+							ret += QChar(code);
+					}
+					tmp = "";
+				}
+			}
+		}
+		else
+		{
+			if (ch == "\\")
+			{
+				sep = true;
+				sepcount = 0;
+			}
+			else
+				ret += ch;
+		}
+	}
+	return ret;
+}
+
+void XfigPlug::processText(QString data)
+{
+	QString tmp = data;
+	int		command;			// (always 4)
+	int		subtype;			// (0: Left justified
+								//  1: Center justified
+								//  2: Right justified)
+	int		color;				// (enumeration type)
+	int		depth;				// (enumeration type)
+	int		pen_style;			// (enumeration , not used)
+	int		font;				// (enumeration type)
+	float	font_size;			// (font size in points)
+	float	angle;				// (radians, the angle of the text)
+	int		font_flags;			// (bit vector)
+	float	height;				// (Fig units)
+	float	length;				// (Fig units)
+	int		xT, yT;				// (Fig units, coordinate of the origin
+								//  of the string.  If sub_type = 0, it is
+								//  the lower left corner of the string.
+								//  If sub_type = 1, it is the lower
+								//  center.  Otherwise it is the lower
+								//  right corner of the string.)
+	QString text;
+	double x, y, w, h;
+	ScTextStream Code(&tmp, QIODevice::ReadOnly);
+	Code >> command >> subtype >> color >> depth >> pen_style >> font >> font_size >> angle;
+	Code >> font_flags >> height >> length >> xT >> yT;
+	text = Code.readAll();
+	text = cleanText(text);
+	FPointArray textPath;
+	QPainterPath painterPath;
+	QString TFont(m_Doc->itemToolPrefs().textFont);
+	QFont::Weight weight = QFont::Normal;
+	bool isItalic = false;
+	if (font_flags & 4)
+	{
+		switch (font)
+		{
+			case 0:
+				TFont = "Times Roman";
+				weight = QFont::Normal;
+				break;
+			case 1:
+				TFont = "Times Italic";
+				weight = QFont::Normal;
+				isItalic = true;
+				break;
+			case 2:
+				TFont = "Times Bold";
+				weight = QFont::Bold;
+				break;
+			case 3:
+				TFont = "Times Bold Italic";
+				weight = QFont::Bold;
+				isItalic = true;
+				break;
+			case 4:
+				TFont = "AvantGarde Book";
+				weight = QFont::Normal;
+				break;
+			case 5:
+				TFont = "AvantGarde Book Oblique";
+				weight = QFont::Normal;
+				break;
+			case 6:
+				TFont = "AvantGarde Demi";
+				weight = QFont::DemiBold;
+				break;
+			case 7:
+				TFont = "AvantGarde Demi Oblique";
+				weight = QFont::DemiBold;
+				break;
+			case 8:
+				TFont = "Bookman Light";
+				weight = QFont::Light;
+				break;
+			case 9:
+				TFont = "Bookman Light Italic";
+				weight = QFont::Light;
+				isItalic = true;
+				break;
+			case 10:
+				TFont = "Bookman Demi";
+				weight = QFont::DemiBold;
+				break;
+			case 11:
+				TFont = "Bookman Demi Italic";
+				weight = QFont::DemiBold;
+				isItalic = true;
+				break;
+			case 12:
+				TFont = "Courier";
+				weight = QFont::Normal;
+				break;
+			case 13:
+				TFont = "Courier Oblique";
+				weight = QFont::Normal;
+				break;
+			case 14:
+				TFont = "Courier Bold";
+				weight = QFont::Bold;
+				break;
+			case 15:
+				TFont = "Courier Bold Oblique";
+				weight = QFont::Bold;
+				break;
+			case 16:
+				TFont = "Helvetica";
+				weight = QFont::Normal;
+				break;
+			case 17:
+				TFont = "Helvetica Oblique";
+				weight = QFont::Normal;
+				break;
+			case 18:
+				TFont = "Helvetica Bold";
+				weight = QFont::Bold;
+				break;
+			case 19:
+				TFont = "Helvetica Bold Oblique";
+				weight = QFont::Bold;
+				break;
+			case 20:
+				TFont = "Helvetica Narrow";
+				weight = QFont::Normal;
+				break;
+			case 21:
+				TFont = "Helvetica Narrow Oblique";
+				weight = QFont::Normal;
+				break;
+			case 22:
+				TFont = "Helvetica Narrow Bold";
+				weight = QFont::Bold;
+				break;
+			case 23:
+				TFont = "Helvetica Narrow Bold Oblique";
+				weight = QFont::Bold;
+				break;
+			case 24:
+				TFont = "New Century Schoolbook Roman";
+				weight = QFont::Normal;
+				break;
+			case 25:
+				TFont = "New Century Schoolbook Italic";
+				weight = QFont::Normal;
+				isItalic = true;
+				break;
+			case 26:
+				TFont = "New Century Schoolbook Bold";
+				weight = QFont::Bold;
+				break;
+			case 27:
+				TFont = "New Century Schoolbook Bold Italic";
+				weight = QFont::Bold;
+				isItalic = true;
+				break;
+			case 28:
+				TFont = "Palatino Roman";
+				weight = QFont::Normal;
+				break;
+			case 29:
+				TFont = "Palatino Italic";
+				weight = QFont::Normal;
+				isItalic = true;
+				break;
+			case 30:
+				TFont = "Palatino Bold";
+				weight = QFont::Bold;
+				break;
+			case 31:
+				TFont = "Palatino Bold Italic";
+				weight = QFont::Bold;
+				isItalic = true;
+				break;
+			case 32:
+				TFont = "Symbol";
+				weight = QFont::Normal;
+				break;
+			case 33:
+				TFont = "Zapf Chancery Medium Italic";
+				weight = QFont::Normal;
+				isItalic = true;
+				break;
+			case 34:
+				TFont = "Zapf Dingbats";
+				weight = QFont::Normal;
+				break;
+			default:
+				TFont = m_Doc->itemToolPrefs().textFont;
+				weight = QFont::Normal;
+				break;
+		}
+	}
+	else
+	{
+		switch (font)
+		{
+    		case 1: // Roman
+				TFont = "Times";
+				weight = QFont::Normal;
+				break;
+			case 2: // Bold
+				TFont = "Times";
+				weight = QFont::Bold;
+				break;
+			case 3: // Italic
+				TFont = "Times";
+				weight = QFont::Normal;
+				isItalic = true;
+				break;
+			case 4: // Sans Serif
+				TFont = "Helvetica";
+				weight = QFont::Normal;
+				break;
+			case 5: // Typewriter
+				TFont = "Courier";
+				weight = QFont::Normal;
+				break;
+			default:
+				TFont = m_Doc->itemToolPrefs().textFont;
+				weight = QFont::Normal;
+				break;
+		}
+	}
+	w = fig2Pts(length);
+	h = fig2Pts(height);
+	x = fig2Pts(xT);
+	y = fig2Pts(yT);
+	x -= docX;
+	x += m_Doc->currentPage()->xOffset();
+	y -= docY;
+	y += m_Doc->currentPage()->yOffset();
+	QFont tf = QFont(TFont, 10, weight, isItalic);
+	tf.setPointSizeF(font_size / 80.0 * 72.0);
+	painterPath.addText( 0, 0, tf, text );
+	QRectF br = painterPath.boundingRect();
+	if ((angle == 0) && (br.width() > w))
+	{
+		QTransform m;
+		m.scale(w / br.width(), w / br.width());
+		painterPath = m.map(painterPath);
+	}
+	textPath.fromQPainterPath(painterPath);
+	useColor(color, 0, false);
+	int z = -1;
+	PageItem *ite;
+	z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX + x, baseY + y, w, h, 0, CurrColorStroke, CommonStrings::None, true);
+	if (z >= 0)
+	{
+		ite = m_Doc->Items->at(z);
+		ite->setRotation(-angle * 180.0 / M_PI);
+		ite->PoLine = textPath.copy();
+		ite->ClipEdited = true;
+		ite->FrameType = 3;
+		FPoint wh = getMaxClipF(&ite->PoLine);
+		ite->setWidthHeight(wh.x(),wh.y());
+		ite->setTextFlowMode(PageItem::TextFlowDisabled);
+		m_Doc->AdjustItemSize(ite);
+		ite->setWidthHeight(qMax(ite->width(), 1.0), qMax(ite->height(), 1.0));
+		if (subtype == 1)
+			m_Doc->MoveRotated(ite, FPoint(-br.width() / 2.0, 0.0));
+		else if (subtype == 2)
+			m_Doc->MoveRotated(ite, FPoint(-br.width(), 0.0));
+		depthMap.insert(999 - depth, currentItemNr);
+		currentItemNr++;
+	}
+}
+
+void XfigPlug::processData(QDataStream &ts, QString data)
+{
+	QString tmp = data;
+	int command, subtype;
+	ScTextStream Code(&tmp, QIODevice::ReadOnly);
+	Code >> command >> subtype;
+	switch (command)
+	{
+		case 0:
+			parseColor(data);
+			break;
+		case 1:
+			processEllipse(data);
+			break;
+		case 2:
+			processPolyline(ts, data);
+			break;
+		case 3:
+			processSpline(ts, data);
+			break;
+		case 4:
+			processText(data);
+			break;
+		case 5:
+			processArc(ts, data);
+			break;
+		case 6:
+//			qDebug() << "Xfig-Import:: Unsupported Compound object";
+			break;
+		case -6:
+//			qDebug() << "Xfig-Import:: Unsupported End of Compound object";
+			break;
+	}
+}
+
+void XfigPlug::resortItems()
+{
+	int ac = m_Doc->Items->count();
+	QList<PageItem*> itemList;
+	for (int as = oldDocItemCount; as < ac; ++as)
+	{
+		itemList.append(m_Doc->Items->takeAt(oldDocItemCount));
+	}
+	QList<int> keylist = depthMap.uniqueKeys();
+	int keysCount = keylist.count();
+	int currentLayer = 0;
+	for (int it = 0; it < keysCount; ++it)
+	{
+		if ((importerFlags & LoadSavePlugin::lfCreateDoc) && (it > 0))
+			currentLayer = m_Doc->addLayer(QString("Layer %1").arg(it), true);
+		QList<int> elems = depthMap.values(keylist.at(it));
+		qSort(elems);
+		int itemsCount = elems.count();
+		for (int i = 0; i < itemsCount; ++i)
+		{
+			PageItem* ite = itemList.at(elems.at(i));
+			Elements.append(ite);
+			m_Doc->Items->append(ite);
+			ite->ItemNr = m_Doc->Items->count()-1;
+			if ((importerFlags & LoadSavePlugin::lfCreateDoc) && (it > 0))
+				ite->LayerID = currentLayer;
+		}
+	}
+}
+
+
+double XfigPlug::fig2Pts(double in)
+{
+	return in / 1200.0 * 72.0;
+}
+
+bool XfigPlug::convert(QString fn)
+{
+	QString tmp;
+	CurrColorFill = "White";
+	CurrFillShade = 100.0;
+	CurrColorStroke = "Black";
+	CurrStrokeShade = 100.0;
+	patternMode = false;
+	patternX1 = 0.0;
+	patternY1 = 0.0;
+	patternX2 = 0.0;
+	patternY2 = 0.0;
+	Coords.resize(0);
+	Coords.svgInit();
+	clipCoords.resize(0);
+	clipCoords.svgInit();
+	currentPatternName = "";
+	currentPatternX = 0.0;
+	currentPatternY = 0.0;
+	currentPatternXScale = 1.0;
+	currentPatternYScale = 1.0;
+	currentPatternRotation = 0.0;
+	QList<PageItem*> gElements;
+	groupStack.push(gElements);
+	currentItemNr = 0;
+	if(progressDialog)
+	{
+		progressDialog->setOverallProgress(2);
+		progressDialog->setLabel("GI", tr("Generating Items"));
+		qApp->processEvents();
+	}
+	QFile f(fn);
+	if (f.open(QIODevice::ReadOnly))
+	{
+		oldDocItemCount = m_Doc->Items->count();
+		int fSize = (int) f.size();
+		if (progressDialog)
+		{
+			progressDialog->setTotalSteps("GI", fSize);
+			qApp->processEvents();
+		}
+		QDataStream ts(&f);
+		QString version = readLinefromDataStream(ts);
+		QString orientation = readLinefromDataStream(ts);
+		QString justification = readLinefromDataStream(ts);
+		QString units = readLinefromDataStream(ts);
+		QString papersize = readLinefromDataStream(ts);
+		QString magnification = readLinefromDataStream(ts);
+		QString multiple = readLinefromDataStream(ts);
+		QString transparent = readLinefromDataStream(ts);
+		tmp = readLinefromDataStream(ts);
+		if (tmp.startsWith("#"))
+			tmp = readLinefromDataStream(ts);
+		QString resolution = tmp;
+		while (!ts.atEnd())
+		{
+			tmp = readLinefromDataStream(ts);
+			if (tmp.startsWith("#"))
+				continue;
+			processData(ts, tmp);
+			if (progressDialog)
+			{
+				progressDialog->setProgress("GI", ts.device()->pos());
+				qApp->processEvents();
+			}
+		}
+		resortItems();
+	}
+	if (progressDialog)
+		progressDialog->close();
+	return true;
+}

Modified: trunk/Scribus/scribus/scribusdoc.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/scribusdoc.cpp
==============================================================================
--- trunk/Scribus/scribus/scribusdoc.cpp (original)
+++ trunk/Scribus/scribus/scribusdoc.cpp Mon Jun 20 20:43:58 2011
@@ -1022,9 +1022,9 @@
 QList<int> ScribusDoc::getSortedStyleList()
 {
 	QList<int> retList;
-	for (int ff = 0; ff < paragraphStyles().count(); ++ff)
-	{
-		if (paragraphStyles()[ff].parent().isEmpty())
+	for (int ff = 0; ff < docParagraphStyles.count(); ++ff)
+	{
+		if (docParagraphStyles[ff].parent().isEmpty())
 		{
 			if (!retList.contains(ff))
 				retList.append(ff);
@@ -1032,17 +1032,17 @@
 		else
 		{
 			QList<int> retList2;
-			QString par = paragraphStyles()[ff].parent();
+			QString par = docParagraphStyles[ff].parent();
 			retList2.prepend(ff);
 			while (!par.isEmpty())
 			{
-				for (int pp = 0; pp < paragraphStyles().count(); ++pp)
+				for (int pp = 0; pp < docParagraphStyles.count(); ++pp)
 				{
-					if (paragraphStyles()[pp].name() == par)
+					if (docParagraphStyles[pp].name() == par)
 					{
 						if (!retList2.contains(pp))
 							retList2.prepend(pp);
-						par = paragraphStyles()[pp].parent();
+						par = docParagraphStyles[pp].parent();
 					}
 				}
 			}

Modified: trunk/Scribus/scribus/scribusdoc.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=16682&path=/trunk/Scribus/scribus/scribusdoc.h
==============================================================================
--- trunk/Scribus/scribus/scribusdoc.h (original)
+++ trunk/Scribus/scribus/scribusdoc.h Mon Jun 20 20:43:58 2011
@@ -520,6 +520,7 @@
 	void getNamedResources(ResourceCollection& lists) const;
 	void replaceNamedResources(ResourceCollection& newNames);
 	bool styleExists(QString styleName);
+	
 	QList<int> getSortedStyleList();
 	QList<int> getSortedCharStyleList();
 	




More information about the scribus-commit mailing list