diff --git a/plugins/cffadaptor/src/UBCFFAdaptor.cpp b/plugins/cffadaptor/src/UBCFFAdaptor.cpp
index 7de215dc..431c46e8 100644
--- a/plugins/cffadaptor/src/UBCFFAdaptor.cpp
+++ b/plugins/cffadaptor/src/UBCFFAdaptor.cpp
@@ -3,24 +3,24 @@
*
* This file is part of Open-Sankoré.
*
- * Open-Sankoré is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation, version 2,
+ * Open-Sankoré is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * You should have received a copy of the GNU Library General Public
- * License along with Open-Sankoré; if not, see
- * .
+ * You should have received a copy of the GNU General Public License
+ * along with Open-Sankoré. If not, see .
*/
+
#include "UBCFFAdaptor.h"
#include
diff --git a/plugins/cffadaptor/src/UBCFFAdaptor.h b/plugins/cffadaptor/src/UBCFFAdaptor.h
index da14d40d..93eb6166 100644
--- a/plugins/cffadaptor/src/UBCFFAdaptor.h
+++ b/plugins/cffadaptor/src/UBCFFAdaptor.h
@@ -3,21 +3,20 @@
*
* This file is part of Open-Sankoré.
*
- * Open-Sankoré is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation, version 2,
+ * Open-Sankoré is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * You should have received a copy of the GNU Library General Public
- * License along with Open-Sankoré; if not, see
- * .
+ * You should have received a copy of the GNU General Public License
+ * along with Open-Sankoré. If not, see .
*/
diff --git a/plugins/cffadaptor/src/UBCFFAdaptor_global.h b/plugins/cffadaptor/src/UBCFFAdaptor_global.h
index cb21a4a6..182a649a 100644
--- a/plugins/cffadaptor/src/UBCFFAdaptor_global.h
+++ b/plugins/cffadaptor/src/UBCFFAdaptor_global.h
@@ -3,21 +3,20 @@
*
* This file is part of Open-Sankoré.
*
- * Open-Sankoré is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation, version 2,
+ * Open-Sankoré is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * You should have received a copy of the GNU Library General Public
- * License along with Open-Sankoré; if not, see
- * .
+ * You should have received a copy of the GNU General Public License
+ * along with Open-Sankoré. If not, see .
*/
diff --git a/plugins/cffadaptor/src/UBCFFConstants.h b/plugins/cffadaptor/src/UBCFFConstants.h
index 8968fdae..7d03d55f 100644
--- a/plugins/cffadaptor/src/UBCFFConstants.h
+++ b/plugins/cffadaptor/src/UBCFFConstants.h
@@ -3,21 +3,20 @@
*
* This file is part of Open-Sankoré.
*
- * Open-Sankoré is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation, version 2,
+ * Open-Sankoré is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * You should have received a copy of the GNU Library General Public
- * License along with Open-Sankoré; if not, see
- * .
+ * You should have received a copy of the GNU General Public License
+ * along with Open-Sankoré. If not, see .
*/
diff --git a/plugins/cffadaptor/src/UBGlobals.h b/plugins/cffadaptor/src/UBGlobals.h
index 46c39405..309004c2 100644
--- a/plugins/cffadaptor/src/UBGlobals.h
+++ b/plugins/cffadaptor/src/UBGlobals.h
@@ -3,21 +3,20 @@
*
* This file is part of Open-Sankoré.
*
- * Open-Sankoré is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation, version 2,
+ * Open-Sankoré is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * You should have received a copy of the GNU Library General Public
- * License along with Open-Sankoré; if not, see
- * .
+ * You should have received a copy of the GNU General Public License
+ * along with Open-Sankoré. If not, see .
*/
diff --git a/src/adaptors/UBCFFSubsetAdaptor.cpp b/src/adaptors/UBCFFSubsetAdaptor.cpp
index 565b7ea4..6f26472d 100644
--- a/src/adaptors/UBCFFSubsetAdaptor.cpp
+++ b/src/adaptors/UBCFFSubsetAdaptor.cpp
@@ -19,1531 +19,1531 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include
-#include
-#include
-#include
-#include
-
-#include "core/UBPersistenceManager.h"
-
-#include "document/UBDocumentProxy.h"
-
-#include "domain/UBItem.h"
-#include "domain/UBGraphicsPolygonItem.h"
-#include "domain/UBGraphicsStroke.h"
-#include "domain/UBGraphicsTextItem.h"
-#include "domain/UBGraphicsSvgItem.h"
-#include "domain/UBGraphicsPixmapItem.h"
-#include "domain/UBGraphicsMediaItem.h"
-#include "domain/UBGraphicsWidgetItem.h"
-#include "domain/UBGraphicsTextItem.h"
-#include "domain/UBGraphicsTextItemDelegate.h"
-#include "domain/UBGraphicsWidgetItem.h"
-#include "domain/UBGraphicsGroupContainerItem.h"
-
-#include "frameworks/UBFileSystemUtils.h"
-
-#include "UBCFFSubsetAdaptor.h"
-#include "UBMetadataDcSubsetAdaptor.h"
-#include "UBThumbnailAdaptor.h"
-#include "UBSvgSubsetAdaptor.h"
-
-#include "core/UBApplication.h"
-#include "QFile"
-
-#include "core/memcheck.h"
-//#include "qtlogger.h"
-
-//tag names definition. Use them everiwhere!
-static QString tElement = "element";
-static QString tGroup = "group";
-static QString tEllipse = "ellipse";
-static QString tIwb = "iwb";
-static QString tMeta = "meta";
-static QString tPage = "page";
-static QString tPageset = "pageset";
-static QString tG = "g";
-static QString tSwitch = "switch";
-static QString tPolygon = "polygon";
-static QString tPolyline = "polyline";
-static QString tRect = "rect";
-static QString tSvg = "svg";
-static QString tText = "text";
-static QString tTextarea = "textarea";
-static QString tTspan = "tspan";
-static QString tBreak = "tbreak";
-static QString tImage = "image";
-static QString tFlash = "flash";
-static QString tAudio = "a";
-static QString tVideo = "video";
-
-//attribute names definition
-static QString aFill = "fill";
-static QString aFillopacity = "fill-opacity";
-static QString aX = "x";
-static QString aY = "y";
-static QString aWidth = "width";
-static QString aHeight = "height";
-static QString aStroke = "stroke";
-static QString aStrokewidth = "stroke-width";
-static QString aCx = "cx";
-static QString aCy = "cy";
-static QString aRx = "rx";
-static QString aRy = "ry";
-static QString aTransform = "transform";
-static QString aViewbox = "viewbox";
-static QString aFontSize = "font-size";
-static QString aFontfamily = "font-family";
-static QString aFontstretch = "font-stretch";
-static QString aFontstyle = "font-style";
-static QString aFontweight = "font-weight";
-static QString aTextalign = "text-align";
-static QString aPoints = "points";
-static QString svgNS = "http://www.w3.org/2000/svg";
-static QString iwbNS = "http://www.imsglobal.org/xsd/iwb_v1p0";
-static QString aId = "id";
-static QString aRef = "ref";
-static QString aHref = "href";
-static QString aBackground = "background";
-static QString aLocked = "locked";
-static QString aEditable = "editable";
-
-//attributes part names
-static QString apRotate = "rotate";
-static QString apTranslate = "translate";
-
-
-UBCFFSubsetAdaptor::UBCFFSubsetAdaptor()
-{}
-
-bool UBCFFSubsetAdaptor::ConvertCFFFileToUbz(QString &cffSourceFile, UBDocumentProxy* pDocument)
-{
- //TODO
- // fill document proxy metadata
- // create persistance manager to save data using proxy
- // create UBCFFSubsetReader and make it parse cffSourceFolder
- QFile file(cffSourceFile);
-
- if (!file.open(QIODevice::ReadOnly))
- {
- qWarning() << "Cannot open file " << cffSourceFile << " for reading ...";
- return false;
- }
-
- UBCFFSubsetReader cffReader(pDocument, &file);
- bool result = cffReader.parse();
- file.close();
-
- return result;
-}
-UBCFFSubsetAdaptor::UBCFFSubsetReader::UBCFFSubsetReader(UBDocumentProxy *proxy, QFile *content)
- : mProxy(proxy)
- , mGSectionContainer(NULL)
-{
- int errorLine, errorColumn;
- QString errorStr;
- if(!mDOMdoc.setContent(content, true, &errorStr, &errorLine, &errorColumn)){
- qWarning() << "Error:Parseerroratline" << errorLine << ","
- << "column" << errorColumn << ":" << errorStr;
- } else {
- qDebug() << "well parsed to DOM";
- pwdContent = QFileInfo(content->fileName()).dir().absolutePath();
- }
- qDebug() << "tmp path is" << pwdContent;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parse()
-{
- UBMetadataDcSubsetAdaptor::persist(mProxy);
-
- mIndent = "";
- if (!getTempFileName() || !createTempFlashPath())
- return false;
-
- if (mDOMdoc.isNull())
- return false;
-
- bool result = parseDoc();
- if (result)
- result = mProxy->pageCount() != 0;
-
- if (QFile::exists(mTempFilePath))
- QFile::remove(mTempFilePath);
-
-// if (mTmpFlashDir.exists())
-// UBFileSystemUtils::deleteDir(mTmpFlashDir.path());
-
- return result;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseGSection(const QDomElement &element)
-{
- mGSectionContainer = new UBGraphicsGroupContainerItem();
-
- QDomElement currentSvgElement = element.firstChildElement();
- while (!currentSvgElement.isNull()) {
- parseSvgElement(currentSvgElement);
- currentSvgElement = currentSvgElement.nextSiblingElement();
- }
-
- if (mGSectionContainer->childItems().count())
- {
- mCurrentScene->addGroup(mGSectionContainer);
- }
- else
- {
- delete mGSectionContainer;
- }
- mGSectionContainer = NULL;
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgSwitchSection(const QDomElement &element)
-{
-
- QDomElement currentSvgElement = element.firstChildElement();
- while (!currentSvgElement.isNull()) {
- if (parseSvgElement(currentSvgElement))
- return true;
- }
-
- return false;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgRect(const QDomElement &element)
-{
- qreal x1 = element.attribute(aX).toDouble();
- qreal y1 = element.attribute(aY).toDouble();
- //rect dimensions
- qreal width = element.attribute(aWidth).toDouble();
- qreal height = element.attribute(aHeight).toDouble();
-
- QString textFillColor = element.attribute(aFill);
- QString textStrokeColor = element.attribute(aStroke);
- QString textStrokeWidth = element.attribute(aStrokewidth);
-
- QColor fillColor = !textFillColor.isNull() ? colorFromString(textFillColor) : QColor();
- QColor strokeColor = !textStrokeColor.isNull() ? colorFromString(textStrokeColor) : QColor();
- int strokeWidth = textStrokeWidth.toInt();
-
- x1 -= strokeWidth/2;
- y1 -= strokeWidth/2;
- width += strokeWidth;
- height += strokeWidth;
-
- //init svg generator with temp file
- QSvgGenerator *generator = createSvgGenerator(width, height);
-
- //init painter to paint to svg
- QPainter painter;
-
- painter.begin(generator);
-
- //fill rect
- if (fillColor.isValid()) {
- painter.setBrush(QBrush(fillColor));
- painter.fillRect(0, 0, width, height, fillColor);
- }
- QPen pen;
- if (strokeColor.isValid()) {
- pen.setColor(strokeColor);
- }
- if (strokeWidth)
- pen.setWidth(strokeWidth);
- painter.setPen(pen);
- painter.drawRect(0, 0, width, height);
-
- painter.end();
-
- UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- svgItem->setUuid(QUuid(uuid));
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- svgItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, svgItem);
- }
-
- repositionSvgItem(svgItem, width, height, x1, y1, transform);
- hashSceneItem(element, svgItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(svgItem);
- }
-
- delete generator;
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgEllipse(const QDomElement &element)
-{
- //ellipse horisontal and vertical radius
- qreal rx = element.attribute(aRx).toDouble();
- qreal ry = element.attribute(aRy).toDouble();
- QSvgGenerator *generator = createSvgGenerator(rx * 2, ry * 2);
-
- //fill and stroke color
- QColor fillColor = colorFromString(element.attribute(aFill));
- QColor strokeColor = colorFromString(element.attribute(aStroke));
- int strokeWidth = element.attribute(aStrokewidth).toInt();
-
- //ellipse center coordinates
- qreal cx = element.attribute(aCx).toDouble();
- qreal cy = element.attribute(aCy).toDouble();
-
- //init painter to paint to svg
- QPainter painter;
- painter.begin(generator);
-
- QPen pen(strokeColor);
- pen.setWidth(strokeWidth);
- painter.setPen(pen);
- painter.setBrush(QBrush(fillColor));
-
- painter.drawEllipse(0, 0, rx * 2, ry * 2);
-
- painter.end();
-
- UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- svgItem->setUuid(QUuid(uuid));
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- svgItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, svgItem);
- }
-
-
- repositionSvgItem(svgItem, rx * 2, ry * 2, cx - 2*rx, cy+ry, transform);
- hashSceneItem(element, svgItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(svgItem);
- }
-
- delete generator;
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPolygon(const QDomElement &element)
-{
- QString svgPoints = element.attribute(aPoints);
- QPolygonF polygon;
-
- if (!svgPoints.isNull()) {
- QStringList ts = svgPoints.split(QLatin1Char(' '), QString::SkipEmptyParts);
-
- foreach(const QString sPoint, ts) {
- QStringList sCoord = sPoint.split(QLatin1Char(','), QString::SkipEmptyParts);
- if (sCoord.size() == 2) {
- QPointF point;
- point.setX(sCoord.at(0).toFloat());
- point.setY(sCoord.at(1).toFloat());
- polygon << point;
- }
- else if (sCoord.size() == 4){
- //This is the case on system were the "," is used to seperate decimal
- QPointF point;
- QString x = sCoord.at(0) + "." + sCoord.at(1);
- QString y = sCoord.at(2) + "." + sCoord.at(3);
- point.setX(x.toFloat());
- point.setY(y.toFloat());
- polygon << point;
- }
- else {
- qWarning() << "cannot make sense of a 'point' value" << sCoord;
- }
- }
- }
-
- //bounding rect lef top corner coordinates
- qreal x1 = polygon.boundingRect().topLeft().x();
- qreal y1 = polygon.boundingRect().topLeft().y();
- //bounding rect dimensions
- qreal width = polygon.boundingRect().width();
- qreal height = polygon.boundingRect().height();
-
- QString strokeColorText = element.attribute(aStroke);
- QString fillColorText = element.attribute(aFill);
- QString strokeWidthText = element.attribute(aStrokewidth);
-
- QColor strokeColor = !strokeColorText.isEmpty() ? colorFromString(strokeColorText) : QColor();
- QColor fillColor = !fillColorText.isEmpty() ? colorFromString(fillColorText) : QColor();
- int strokeWidth = strokeWidthText.toDouble();
-
- QPen pen;
- pen.setColor(strokeColor);
- pen.setWidth(strokeWidth);
-
- QBrush brush;
- brush.setColor(fillColor);
- brush.setStyle(Qt::SolidPattern);
-
-
- QUuid itemUuid(element.attribute(aId).right(QUuid().toString().length()));
- QUuid itemGroupUuid(element.attribute(aId).left(QUuid().toString().length()-1));
- if (!itemUuid.isNull() && (itemGroupUuid!=itemUuid)) // reimported from UBZ
- {
- UBGraphicsPolygonItem *graphicsPolygon = mCurrentScene->polygonToPolygonItem(polygon);
-
- graphicsPolygon->setBrush(brush);
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- graphicsPolygon->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, graphicsPolygon);
- }
- mCurrentScene->addItem(graphicsPolygon);
-
- graphicsPolygon->setUuid(itemUuid);
- mRefToUuidMap.insert(element.attribute(aId), itemUuid);
-
- }
- else // single CFF
- {
- QSvgGenerator *generator = createSvgGenerator(width + pen.width(), height + pen.width());
- QPainter painter;
-
- painter.begin(generator); //drawing to svg tmp file
-
- painter.translate(pen.widthF() / 2 - x1, pen.widthF() / 2 - y1);
- painter.setBrush(brush);
- painter.setPen(pen);
- painter.drawPolygon(polygon);
-
- painter.end();
-
- //add resulting svg file to scene
- UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- QUuid uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- svgItem->setUuid(uuid);
-
- svgItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, svgItem);
- }
- repositionSvgItem(svgItem, width +strokeWidth, height + strokeWidth, x1 - strokeWidth/2 + transform.m31(), y1 + strokeWidth/2 + transform.m32(), transform);
- hashSceneItem(element, svgItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(svgItem);
- }
-
- delete generator;
- }
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPolyline(const QDomElement &element)
-{
- QString svgPoints = element.attribute(aPoints);
- QPolygonF polygon;
-
- if (!svgPoints.isNull()) {
- QStringList ts = svgPoints.split(QLatin1Char(' '),
- QString::SkipEmptyParts);
-
- foreach(const QString sPoint, ts) {
- QStringList sCoord = sPoint.split(QLatin1Char(','), QString::SkipEmptyParts);
- if (sCoord.size() == 2) {
- QPointF point;
- point.setX(sCoord.at(0).toFloat());
- point.setY(sCoord.at(1).toFloat());
- polygon << point;
- }
- else if (sCoord.size() == 4){
- //This is the case on system were the "," is used to seperate decimal
- QPointF point;
- QString x = sCoord.at(0) + "." + sCoord.at(1);
- QString y = sCoord.at(2) + "." + sCoord.at(3);
- point.setX(x.toFloat());
- point.setY(y.toFloat());
- polygon << point;
- }
- else {
- qWarning() << "cannot make sense of a 'point' value" << sCoord;
- }
- }
- }
-
- //bounding rect lef top corner coordinates
- qreal x1 = polygon.boundingRect().topLeft().x();
- qreal y1 = polygon.boundingRect().topLeft().y();
-
- //bounding rect dimensions
- qreal width = polygon.boundingRect().width();
- qreal height = polygon.boundingRect().height();
-
- QString strokeColorText = element.attribute(aStroke);
- QString strokeWidthText = element.attribute(aStrokewidth);
-
- QColor strokeColor = !strokeColorText.isEmpty() ? colorFromString(strokeColorText) : QColor();
- int strokeWidth = strokeWidthText.toDouble();
-
- width += strokeWidth;
- height += strokeWidth;
-
- QPen pen;
- pen.setColor(strokeColor);
- pen.setWidth(strokeWidth);
-
- QBrush brush;
- brush.setColor(strokeColor);
- brush.setStyle(Qt::SolidPattern);
-
- QUuid itemUuid(element.attribute(aId).right(QUuid().toString().length()));
- QUuid itemGroupUuid(element.attribute(aId).left(QUuid().toString().length()-1));
- if (!itemUuid.isNull() && (itemGroupUuid!=itemUuid)) // reimported from UBZ
- {
- UBGraphicsPolygonItem *graphicsPolygon = new UBGraphicsPolygonItem(polygon);
-
- UBGraphicsStroke *stroke = new UBGraphicsStroke();
- graphicsPolygon->setStroke(stroke);
-
- graphicsPolygon->setBrush(brush);
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- graphicsPolygon->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, graphicsPolygon);
- }
- mCurrentScene->addItem(graphicsPolygon);
-
- graphicsPolygon->setUuid(itemUuid);
- mRefToUuidMap.insert(element.attribute(aId), itemUuid);
-
- }
- else // simple CFF
- {
- QSvgGenerator *generator = createSvgGenerator(width + pen.width(), height + pen.width());
- QPainter painter;
-
- painter.begin(generator); //drawing to svg tmp file
-
- painter.translate(pen.widthF() / 2 - x1, pen.widthF() / 2 - y1);
- painter.setBrush(brush);
- painter.setPen(pen);
- painter.drawPolygon(polygon);
-
- painter.end();
-
- //add resulting svg file to scene
- UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- svgItem->setUuid(QUuid(uuid));
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- svgItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, svgItem);
- }
- repositionSvgItem(svgItem, width +strokeWidth, height + strokeWidth, x1 - strokeWidth/2 + transform.m31(), y1 + strokeWidth/2 + transform.m32(), transform);
- hashSceneItem(element, svgItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(svgItem);
- }
-
- delete generator;
- }
-
-
- return true;
-}
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseTextAttributes(const QDomElement &element,
- qreal &fontSize, QColor &fontColor, QString &fontFamily,
- QString &fontStretch, bool &italic, int &fontWeight,
- int &textAlign, QTransform &fontTransform)
-{
- //consider inch has 72 liens
- //since svg font size is given in pixels, divide it by pixels per line
- QString fontSz = element.attribute(aFontSize);
- if (!fontSz.isNull()) fontSize = fontSz.toDouble() * 72 / QApplication::desktop()->physicalDpiY();
-
- QString fontColorText = element.attribute(aFill);
- if (!fontColorText.isNull()) fontColor = colorFromString(fontColorText);
-
- QString fontFamilyText = element.attribute(aFontfamily);
- if (!fontFamilyText.isNull()) fontFamily = fontFamilyText;
-
- QString fontStretchText = element.attribute(aFontstretch);
- if (!fontStretchText.isNull()) fontStretch = fontStretchText;
-
- if (!element.attribute(aFontstyle).isNull())
- italic = (element.attribute(aFontstyle) == "italic");
-
- QString weight = element.attribute(aFontweight);
- if (!weight.isNull()) {
- if (weight == "normal") fontWeight = QFont::Normal;
- else if (weight == "light") fontWeight = QFont::Light;
- else if (weight == "demibold") fontWeight = QFont::DemiBold;
- else if (weight == "bold") fontWeight = QFont::Bold;
- else if (weight == "black") fontWeight = QFont::Black;
- }
- QString align = element.attribute(aTextalign);
- if (!align.isNull()) {
- if (align == "middle" || align == "center") textAlign = Qt::AlignHCenter;
- else if (align == "start") textAlign = Qt::AlignLeft;
- else if (align == "end") textAlign = Qt::AlignRight;
- }
-
- if (!element.attribute(aTransform).isNull())
- fontTransform = transformFromString(element.attribute(aTransform));
-}
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::readTextBlockAttr(const QDomElement &element, QTextBlockFormat &format)
-{
- QString fontStretchText = element.attribute(aFontstretch);
- if (!fontStretchText.isNull()) format.setAlignment(Qt::AlignJustify);
-
- QString align = element.attribute(aTextalign);
- if (!align.isNull()) {
- if (align == "middle" || align == "center") format.setAlignment(Qt::AlignHCenter);
- else if (align == "start") format.setAlignment(Qt::AlignLeft);
- else if (align == "end") format.setAlignment(Qt::AlignRight);
- else if (align == "justify") format.setAlignment(Qt::AlignJustify);
- }
-}
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::readTextCharAttr(const QDomElement &element, QTextCharFormat &format)
-{
- QString fontSz = element.attribute(aFontSize);
- if (!fontSz.isNull()) {
- qreal fontSize = fontSz.remove("pt").toDouble();
- format.setFontPointSize(fontSize);
- }
- QString fontColorText = element.attribute(aFill);
- if (!fontColorText.isNull()) {
- QColor fontColor = colorFromString(fontColorText);
- if (fontColor.isValid()) format.setForeground(fontColor);
- }
- QString fontFamilyText = element.attribute(aFontfamily);
- if (!fontFamilyText.isNull()) {
- format.setFontFamily(fontFamilyText);
- }
- if (!element.attribute(aFontstyle).isNull()) {
- bool italic = (element.attribute(aFontstyle) == "italic");
- format.setFontItalic(italic);
- }
- QString weight = element.attribute(aFontweight);
- if (!weight.isNull()) {
- if (weight == "normal") format.setFontWeight(QFont::Normal);
- else if (weight == "light") format.setFontWeight(QFont::Light);
- else if (weight == "demibold") format.setFontWeight(QFont::DemiBold);
- else if (weight == "bold") format.setFontWeight(QFont::Bold);
- else if (weight == "black") format.setFontWeight(QFont::Black);
- }
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgText(const QDomElement &element)
-{
- qreal x = element.attribute(aX).toDouble();
- qreal y = element.attribute(aY).toDouble();
- qreal width = element.attribute(aWidth).toDouble();
- qreal height = element.attribute(aHeight).toDouble();
-
-
- qreal fontSize = 12;
- QColor fontColor(qApp->palette().foreground().color());
- QString fontFamily = "Arial";
- QString fontStretch = "normal";
- bool italic = false;
- int fontWeight = QFont::Normal;
- int textAlign = Qt::AlignLeft;
- QTransform fontTransform;
- parseTextAttributes(element, fontSize, fontColor, fontFamily, fontStretch, italic, fontWeight, textAlign, fontTransform);
-
- QFont startFont(fontFamily, fontSize, fontWeight, italic);
- height = QFontMetrics(startFont).height();
- width = QFontMetrics(startFont).width(element.text()) + 5;
-
- QSvgGenerator *generator = createSvgGenerator(width, height);
- QPainter painter;
- painter.begin(generator);
- painter.setFont(startFont);
-
- qreal curY = 0.0;
- qreal curX = 0.0;
- qreal linespacing = QFontMetricsF(painter.font()).leading();
-
-// remember if text area has transform
-// QString transformString;
- QTransform transform = fontTransform;
-
- QRectF lastDrawnTextBoundingRect;
- //parse text area tags
-
- //recursive call any tspan in text svg element
- parseTSpan(element, painter
- , curX, curY, width, height, linespacing, lastDrawnTextBoundingRect
- , fontSize, fontColor, fontFamily, fontStretch, italic, fontWeight, textAlign, fontTransform);
-
- painter.end();
-
- //add resulting svg file to scene
- UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- svgItem->setUuid(QUuid(uuid));
-
- svgItem->resetTransform();
- repositionSvgItem(svgItem, width, height, x + transform.m31(), y + transform.m32(), transform);
- hashSceneItem(element, svgItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(svgItem);
- }
-
- delete generator;
- return true;
-}
-
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseTSpan(const QDomElement &parent, QPainter &painter
- , qreal &curX, qreal &curY, qreal &width, qreal &height, qreal &linespacing, QRectF &lastDrawnTextBoundingRect
- , qreal &fontSize, QColor &fontColor, QString &fontFamily, QString &fontStretch, bool &italic
- , int &fontWeight, int &textAlign, QTransform &fontTransform)
-{
- QDomNode curNode = parent.firstChild();
- while (!curNode.isNull()) {
- if (curNode.toElement().tagName() == tTspan) {
- QDomElement curTSpan = curNode.toElement();
- parseTextAttributes(curTSpan, fontSize, fontColor, fontFamily, fontStretch, italic
- , fontWeight, textAlign, fontTransform);
- painter.setFont(QFont(fontFamily, fontSize, fontWeight, italic));
- painter.setPen(fontColor);
- linespacing = QFontMetricsF(painter.font()).leading();
- parseTSpan(curTSpan, painter
- , curX, curY, width, height, linespacing, lastDrawnTextBoundingRect
- , fontSize, fontColor, fontFamily, fontStretch, italic, fontWeight, textAlign, fontTransform);
- } else if (curNode.nodeType() == QDomNode::CharacterDataNode
- || curNode.nodeType() == QDomNode::CDATASectionNode
- || curNode.nodeType() == QDomNode::TextNode) {
-
- QDomCharacterData textData = curNode.toCharacterData();
- QString text = textData.data().trimmed();
-// width = painter.fontMetrics().width(text);
- //get bounding rect to obtain desired text height
- lastDrawnTextBoundingRect = painter.boundingRect(QRectF(curX, curY, width, height - curY), textAlign|Qt::TextWordWrap, text);
- painter.drawText(curX, curY, width, lastDrawnTextBoundingRect.height(), textAlign|Qt::TextWordWrap, text);
- curX += lastDrawnTextBoundingRect.x() + lastDrawnTextBoundingRect.width();
- } else if (curNode.nodeType() == QDomNode::ElementNode
- && curNode.toElement().tagName() == tBreak) {
-
- curY += lastDrawnTextBoundingRect.height() + linespacing;
- curX = 0.0;
- lastDrawnTextBoundingRect = QRectF(0,0,0,0);
- }
- curNode = curNode.nextSibling();
- }
-}
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseTSpan(const QDomElement &element, QTextCursor &cursor
- , QTextBlockFormat &blockFormat, QTextCharFormat &charFormat)
-{
- QDomNode curNode = element.firstChild();
- while (!curNode.isNull()) {
- if (curNode.toElement().tagName() == tTspan) {
- QDomElement curTspan = curNode.toElement();
- readTextBlockAttr(curTspan, blockFormat);
- readTextCharAttr(curTspan, charFormat);
- cursor.setBlockFormat(blockFormat);
- cursor.setCharFormat(charFormat);
- parseTSpan(curTspan, cursor, blockFormat, charFormat);
-
- } else if (curNode.nodeType() == QDomNode::CharacterDataNode
- || curNode.nodeType() == QDomNode::CDATASectionNode
- || curNode.nodeType() == QDomNode::TextNode) {
-
- QDomCharacterData textData = curNode.toCharacterData();
- QString text = textData.data().trimmed();
- cursor.insertText(text, charFormat);
-
- } else if (curNode.nodeType() == QDomNode::ElementNode
- && curNode.toElement().tagName() == tBreak) {
- cursor.insertBlock();
- }
- curNode = curNode.nextSibling();
- }
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgTextarea(const QDomElement &element)
-{
- qreal x = element.attribute(aX).toDouble();
- qreal y = element.attribute(aY).toDouble();
- qreal width = element.attribute(aWidth).toDouble();
- qreal height = element.attribute(aHeight).toDouble();
-
- QTextBlockFormat blockFormat;
- blockFormat.setAlignment(Qt::AlignLeft);
-
- QTextCharFormat textFormat;
- // default values
- textFormat.setFontPointSize(12);
- textFormat.setForeground(qApp->palette().foreground().color());
- textFormat.setFontFamily("Arial");
- textFormat.setFontItalic(false);
- textFormat.setFontWeight(QFont::Normal);
-
- // readed values
- readTextBlockAttr(element, blockFormat);
- readTextCharAttr(element, textFormat);
-
- QTextDocument doc;
- doc.setPlainText("");
- QTextCursor tCursor(&doc);
- tCursor.setBlockFormat(blockFormat);
- tCursor.setCharFormat(textFormat);
-
- parseTSpan(element, tCursor, blockFormat, textFormat);
-
- UBGraphicsTextItem *svgItem = mCurrentScene->addTextHtml(doc.toHtml());
- svgItem->resize(width, height);
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- svgItem->setUuid(QUuid(uuid));
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- svgItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, svgItem);
- }
-
- //by default all the textAreas are not editable
- UBGraphicsTextItemDelegate *curDelegate = dynamic_cast(svgItem->Delegate());
- if (curDelegate) {
- curDelegate->setEditable(false);
- }
-
- repositionSvgItem(svgItem, width, height, x + transform.m31(), y + transform.m32(), transform);
- hashSceneItem(element, svgItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(svgItem);
- }
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgImage(const QDomElement &element)
-{
- qreal x = element.attribute(aX).toDouble();
- qreal y = element.attribute(aY).toDouble();
- qreal width = element.attribute(aWidth).toDouble();
- qreal height = element.attribute(aHeight).toDouble();
-
- QString itemRefPath = element.attribute(aHref);
-
- QPixmap pix;
- if (!itemRefPath.isNull()) {
- QString imagePath = pwdContent + "/" + itemRefPath;
- if (!QFile::exists(imagePath)) {
- qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
- return false;
- } else {
-// qDebug() << "size of file" << itemRefPath << QFileInfo(itemRefPath).size();
- }
- pix.load(imagePath);
- if (pix.isNull()) {
- qDebug() << "can't create pixmap for file" << pwdContent + "/" + itemRefPath << "maybe format does not supported";
- }
- }
-
- UBGraphicsPixmapItem *pixItem = mCurrentScene->addPixmap(pix, NULL);
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- pixItem->setUuid(QUuid(uuid));
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- pixItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, pixItem);
- }
- repositionSvgItem(pixItem, width, height, x + transform.m31(), y + transform.m32(), transform);
- hashSceneItem(element, pixItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(pixItem);
- }
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgFlash(const QDomElement &element)
-{
- QString itemRefPath = element.attribute(aHref);
-
- qreal x = element.attribute(aX).toDouble();
- qreal y = element.attribute(aY).toDouble();
- qreal width = element.attribute(aWidth).toDouble();
- qreal height = element.attribute(aHeight).toDouble();
-
- QUrl urlPath;
- QString flashPath;
- if (!itemRefPath.isNull()) {
- flashPath = pwdContent + "/" + itemRefPath;
- if (!QFile::exists(flashPath)) {
- qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
- return false;
- }
- urlPath = QUrl::fromLocalFile(flashPath);
- }
- QDir tmpFlashDir(mTmpFlashDir);
- if (!tmpFlashDir.exists()) {
- qDebug() << "Can't create temporary directory to put flash";
- return false;
- }
-
- QString flashUrl = UBGraphicsW3CWidgetItem::createNPAPIWrapperInDir(flashPath, tmpFlashDir, "application/x-shockwave-flash"
- ,QSize(mCurrentSceneRect.width(), mCurrentSceneRect.height()));
- UBGraphicsWidgetItem *flashItem = mCurrentScene->addW3CWidget(QUrl::fromLocalFile(flashUrl));
- flashItem->setSourceUrl(urlPath);
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
- flashItem->setUuid(QUuid(uuid));
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- flashItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, flashItem);
- }
- repositionSvgItem(flashItem, width, height, x + transform.m31(), y + transform.m32(), transform);
- hashSceneItem(element, flashItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(flashItem);
- }
-
- return true;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgAudio(const QDomElement &element)
-{
- QDomElement parentOfAudio = element.firstChild().toElement();
-
- qreal x = parentOfAudio.attribute(aX).toDouble();
- qreal y = parentOfAudio.attribute(aY).toDouble();
-
- QString itemRefPath = element.attribute(aHref);
-
- QUrl concreteUrl;
- if (!itemRefPath.isNull()) {
- QString audioPath = pwdContent + "/" + itemRefPath;
- if (!QFile::exists(audioPath)) {
- qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
- return false;
- }
- concreteUrl = QUrl::fromLocalFile(audioPath);
- }
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
-
- QString destFile;
- bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(
- mCurrentScene->document(),
- concreteUrl.toLocalFile(),
- UBPersistenceManager::audioDirectory,
- QUuid(uuid),
- destFile);
- if (!b)
- {
- return false;
- }
- concreteUrl = QUrl::fromLocalFile(destFile);
-
- UBGraphicsMediaItem *audioItem = mCurrentScene->addAudio(concreteUrl, false);
-
- QTransform transform;
- QString textTransform = parentOfAudio.attribute(aTransform);
-
- audioItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, audioItem);
- }
- repositionSvgItem(audioItem, audioItem->boundingRect().width(), audioItem->boundingRect().height(), x + transform.m31(), y + transform.m32(), transform);
- hashSceneItem(element, audioItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(audioItem);
- }
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgVideo(const QDomElement &element)
-{
- QString itemRefPath = element.attribute(aHref);
- if (itemRefPath.startsWith(tFlash + "/") && itemRefPath.endsWith(".swf")) {
- if (parseSvgFlash(element)) return true;
- else return false;
- }
- qreal x = element.attribute(aX).toDouble();
- qreal y = element.attribute(aY).toDouble();
-
- QUrl concreteUrl;
- if (!itemRefPath.isNull()) {
- QString videoPath = pwdContent + "/" + itemRefPath;
- if (!QFile::exists(videoPath)) {
- qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
- return false;
- }
- concreteUrl = QUrl::fromLocalFile(videoPath);
- }
-
- QString uuid = QUuid::createUuid().toString();
- mRefToUuidMap.insert(element.attribute(aId), uuid);
-
- QString destFile;
- bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(
- mCurrentScene->document(),
- concreteUrl.toLocalFile(),
- UBPersistenceManager::videoDirectory,
- QUuid(uuid),
- destFile);
- if (!b)
- {
- return false;
- }
- concreteUrl = QUrl::fromLocalFile(destFile);
-
- UBGraphicsMediaItem *videoItem = mCurrentScene->addVideo(concreteUrl, false);
-
- QTransform transform;
- QString textTransform = element.attribute(aTransform);
-
- videoItem->resetTransform();
- if (!textTransform.isNull()) {
- transform = transformFromString(textTransform, videoItem);
- }
- repositionSvgItem(videoItem, videoItem->boundingRect().width(), videoItem->boundingRect().height(), x + transform.m31(), y + transform.m32(), transform);
- hashSceneItem(element, videoItem);
-
- if (mGSectionContainer)
- {
- addItemToGSection(videoItem);
- }
-
- return true;
-}
-
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgSectionAttr(const QDomElement &svgSection)
-{
- getViewBoxDimenstions(svgSection.attribute(aViewbox));
- mSize = QSize(svgSection.attribute(aWidth).toInt(),
- svgSection.attribute(aHeight).toInt());
-}
-
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::addItemToGSection(QGraphicsItem *item)
-{
- mGSectionContainer->addToGroup(item);
-}
-
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::hashSceneItem(const QDomElement &element, UBGraphicsItem *item)
-{
-// adding element pointer to hash to refer if needed
- QString key = element.attribute(aId);
- if (!key.isNull()) {
- persistedItems.insert(key, item);
- }
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgElement(const QDomElement &parent)
-{
- QString tagName = parent.tagName();
- if (parent.namespaceURI() != svgNS) {
- qWarning() << "Incorrect namespace, error at content file, line number" << parent.lineNumber();
- //return false;
- }
-
- if (tagName == tG && !parseGSection(parent)) return false;
- else if (tagName == tSwitch && !parseSvgSwitchSection(parent)) return false;
- else if (tagName == tRect && !parseSvgRect(parent)) return false;
- else if (tagName == tEllipse && !parseSvgEllipse(parent)) return false;
- else if (tagName == tPolygon && !parseSvgPolygon(parent)) return false;
- else if (tagName == tPolyline && !parseSvgPolyline(parent)) return false;
- else if (tagName == tText && !parseSvgText(parent)) return false;
- else if (tagName == tTextarea && !parseSvgTextarea(parent)) return false;
- else if (tagName == tImage && !parseSvgImage(parent)) return false;
- else if (tagName == tFlash && !parseSvgFlash(parent)) return false;
- else if (tagName == tAudio && !parseSvgAudio(parent)) return false;
- else if (tagName == tVideo && !parseSvgVideo(parent)) return false;
-
- return true;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPage(const QDomElement &parent)
-{
- createNewScene();
- QDomElement currentSvgElement = parent.firstChildElement();
- while (!currentSvgElement.isNull()) {
- if (!parseSvgElement(currentSvgElement))
- return false;
-
- currentSvgElement = currentSvgElement.nextSiblingElement();
- }
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPageset(const QDomElement &parent)
-{
- QDomElement currentPage = parent.firstChildElement(tPage);
- while (!currentPage.isNull()) {
- if (!parseSvgPage(currentPage))
- return false;
- currentPage = currentPage.nextSiblingElement(tPage);
- }
- return true;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseIwbMeta(const QDomElement &element)
-{
- if (element.namespaceURI() != iwbNS) {
- qWarning() << "incorrect meta namespace, incorrect document";
- //return false;
- }
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvg(const QDomElement &svgSection)
-{
- if (svgSection.namespaceURI() != svgNS) {
- qWarning() << "incorrect svg namespace, incorrect document";
- // return false;
- }
-
- parseSvgSectionAttr(svgSection);
- QDomElement currentSvg = svgSection.firstChildElement();
-
- if (currentSvg.tagName() != tPageset) {
- parseSvgPage(svgSection);
- } else if (currentSvg.tagName() == tPageset){
- parseSvgPageset(currentSvg);
- }
-
- return true;
-}
-
-UBGraphicsGroupContainerItem *UBCFFSubsetAdaptor::UBCFFSubsetReader::parseIwbGroup(QDomElement &parent)
-{
- //TODO. Create groups from elements parsed by parseIwbElement() function
- if (parent.namespaceURI() != iwbNS) {
- qWarning() << "incorrect iwb group namespace, incorrect document";
- // return false;
- }
-
- UBGraphicsGroupContainerItem *group = new UBGraphicsGroupContainerItem();
- QMultiMap strokesGroupsContainer;
- QList groupContainer;
- QString currentStrokeIdentifier;
-
- QDomElement currentStrokeElement = parent.firstChildElement();
- while (!currentStrokeElement.isNull())
- {
- if (tGroup == currentStrokeElement.tagName())
- group->addToGroup(parseIwbGroup(currentStrokeElement));
- else
- {
-
- QString ref = currentStrokeElement.attribute(aRef);
- QString uuid = mRefToUuidMap[ref];
- if (!uuid.isEmpty())
- {
- if (ref.size() > QUuid().toString().length()) // create stroke group
- {
- currentStrokeIdentifier = ref.left(QUuid().toString().length()-1);
- UBGraphicsPolygonItem *strokeByUuid = qgraphicsitem_cast(mCurrentScene->itemForUuid(QUuid(ref.right(QUuid().toString().length()))));
-
- if (strokeByUuid)
- strokesGroupsContainer.insert(currentStrokeIdentifier, strokeByUuid);
- }
- else // single elements in group
- groupContainer.append(mCurrentScene->itemForUuid(QUuid(uuid)));
- }
- }
- currentStrokeElement = currentStrokeElement.nextSiblingElement();
- }
-
-
-
- foreach (QString key, strokesGroupsContainer.keys().toSet())
- {
- UBGraphicsStrokesGroup* pStrokesGroup = new UBGraphicsStrokesGroup();
- UBGraphicsStroke *currentStroke = new UBGraphicsStroke();
- foreach(UBGraphicsPolygonItem* poly, strokesGroupsContainer.values(key))
- {
- if (poly)
- {
- mCurrentScene->removeItem(poly);
- mCurrentScene->removeItemFromDeletion(poly);
- poly->setStrokesGroup(pStrokesGroup);
- poly->setStroke(currentStroke);
- pStrokesGroup->addToGroup(poly);
- }
- }
- if (currentStroke->polygons().empty())
- delete currentStroke;
-
- if (pStrokesGroup->childItems().count())
- mCurrentScene->addItem(pStrokesGroup);
- else
- delete pStrokesGroup;
-
- if (pStrokesGroup)
- {
- QGraphicsItem *strokeGroup = qgraphicsitem_cast(pStrokesGroup);
- groupContainer.append(strokeGroup);
- }
- }
-
- foreach(QGraphicsItem* item, groupContainer)
- group->addToGroup(item);
-
- if (group->childItems().count())
- {
- mCurrentScene->addItem(group);
-
- if (1 == group->childItems().count())
- {
- group->destroy(false);
- }
- }
-
- return group;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::strToBool(QString str)
-{
- return str == "true";
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseIwbElement(QDomElement &element)
-{
- if (element.namespaceURI() != iwbNS) {
- qWarning() << "incorrect iwb element namespace, incorrect document";
- // return false;
- }
-
- bool locked = false;
- bool isEditableItem = false;
- bool isEditable = false; //Text items to convert to UBGraphicsTextItem only
-
- QString IDRef = element.attribute(aRef);
- if (!IDRef.isNull()) {
- element.hasAttribute(aBackground) ? strToBool(element.attribute(aBackground)) : false;
- locked = element.hasAttribute(aBackground) ? strToBool(element.attribute(aBackground)) : false;
- isEditableItem = element.hasAttribute(aEditable);
- if (isEditableItem)
- isEditable = strToBool(element.attribute(aEditable));
-
- UBGraphicsItem *referedItem(0);
- QHash::iterator iReferedItem;
- iReferedItem = persistedItems.find(IDRef);
- if (iReferedItem != persistedItems.end()) {
- referedItem = *iReferedItem;
- referedItem->Delegate()->lock(locked);
- }
- if (isEditableItem) {
- UBGraphicsTextItemDelegate *textDelegate = dynamic_cast(referedItem->Delegate());
- if (textDelegate) {
- textDelegate->setEditable(isEditable);
- }
- }
- }
-
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseDoc()
-{
- QDomElement currentTopElement = mDOMdoc.documentElement().firstChildElement();
- while (!currentTopElement.isNull()) {
- QString tagName = currentTopElement.tagName();
- if (tagName == tMeta && !parseIwbMeta(currentTopElement)) return false;
- else if (tagName == tSvg && !parseSvg(currentTopElement)) return false;
- else if (tagName == tGroup && !parseIwbGroup(currentTopElement)) return false;
- else if (tagName == tElement && !parseIwbElement(currentTopElement)) return false;
-
- currentTopElement = currentTopElement.nextSiblingElement();
- }
- if (!persistScenes()) return false;
-
- return true;
-}
-
-void UBCFFSubsetAdaptor::UBCFFSubsetReader::repositionSvgItem(QGraphicsItem *item, qreal width, qreal height,
- qreal x, qreal y,
- QTransform &transform)
-{
- //First using viebox coordinates, then translate them to scene coordinates
-
- QRectF itemBounds = item->boundingRect();
-
- qreal xScale = width / itemBounds.width();
- qreal yScale = height / itemBounds.height();
-
- qreal fullScaleX = mVBTransFactor * xScale;
- qreal fullScaleY = mVBTransFactor * yScale;
-
- QPointF oldVector((x - transform.dx()), (y - transform.dy()));
- QTransform rTransform;
- QPointF newVector = rTransform.map(oldVector);
-
- QTransform tr = item->sceneTransform();
- item->setTransform(rTransform.scale(fullScaleX, fullScaleY), true);
- tr = item->sceneTransform();
- QPoint pos;
- if (UBGraphicsTextItem::Type == item->type())
- pos = QPoint((int)((x + mShiftVector.x() + (newVector - oldVector).x())), (int)((y +mShiftVector.y() + (newVector - oldVector).y()) * mVBTransFactor));
- else
- pos = QPoint((int)((x + mShiftVector.x() + (newVector - oldVector).x()) * mVBTransFactor), (int)((y +mShiftVector.y() + (newVector - oldVector).y()) * mVBTransFactor));
-
-
- item->setPos(pos);
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::createNewScene()
-{
- mCurrentScene = UBPersistenceManager::persistenceManager()->createDocumentSceneAt(mProxy, mProxy->pageCount(), false);
- mCurrentScene->setSceneRect(mViewBox);
- if ((mCurrentScene->sceneRect().topLeft().x() >= 0) || (mCurrentScene->sceneRect().topLeft().y() >= 0)) {
- mShiftVector = -mViewBox.center();
- }
- mCurrentSceneRect = mViewBox;
- mVBTransFactor = qMin(mCurrentScene->normalizedSceneRect().width() / mViewPort.width(),
- mCurrentScene->normalizedSceneRect().height() / mViewPort.height());
- return true;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::persistCurrentScene()
-{
- if (mCurrentScene != 0 && mCurrentScene->isModified())
- {
- UBThumbnailAdaptor::persistScene(mProxy, mCurrentScene, mProxy->pageCount() - 1);
- UBSvgSubsetAdaptor::persistScene(mProxy, mCurrentScene, mProxy->pageCount() - 1);
-
- mCurrentScene->setModified(false);
- mCurrentScene = 0;
- }
- return true;
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::persistScenes()
-{
- if (!mProxy->pageCount()) {
- qDebug() << "No pages created";
- return false;
- }
- for (int i = 0; i < mProxy->pageCount(); i++) {
- mCurrentScene = UBPersistenceManager::persistenceManager()->getDocumentScene(mProxy, i);
- if (!mCurrentScene) {
- qDebug() << "can't allocate scene, loading failed";
- return false;
- }
-
- UBSvgSubsetAdaptor::persistScene(mProxy, mCurrentScene, i);
- UBGraphicsScene *tmpScene = UBSvgSubsetAdaptor::loadScene(mProxy, i);
- tmpScene->setModified(true);
- UBThumbnailAdaptor::persistScene(mProxy, tmpScene, i);
- mCurrentScene->setModified(false);
- }
-
- return true;
-}
-
-QColor UBCFFSubsetAdaptor::UBCFFSubsetReader::colorFromString(const QString& clrString)
-{
- //init regexp with pattern
- //pattern corresponds to strings like 'rgb(1,2,3) or rgb(10%,20%,30%)'
- QRegExp regexp("rgb\\(([0-9]+%{0,1}),([0-9]+%{0,1}),([0-9]+%{0,1})\\)");
- if (regexp.exactMatch(clrString))
- {
- if (regexp.capturedTexts().count() == 4 && regexp.capturedTexts().at(0).length() == clrString.length())
- {
- int r = regexp.capturedTexts().at(1).toInt();
- if (regexp.capturedTexts().at(1).indexOf("%") != -1)
- r = r * 255 / 100;
- int g = regexp.capturedTexts().at(2).toInt();
- if (regexp.capturedTexts().at(2).indexOf("%") != -1)
- g = g * 255 / 100;
- int b = regexp.capturedTexts().at(3).toInt();
- if (regexp.capturedTexts().at(3).indexOf("%") != -1)
- b = b * 255 / 100;
- return QColor(r, g, b);
- }
- else
- return QColor();
- }
- else
- return QColor(clrString);
-}
-
-QTransform UBCFFSubsetAdaptor::UBCFFSubsetReader::transformFromString(const QString trString, QGraphicsItem *item)
-{
- qreal dxr = 0.0;
- qreal dyr = 0.0;
- qreal dx = 0.0;
- qreal dy = 0.0;
- qreal angle = 0.0;
- QTransform tr;
-
- foreach(QString trStr, trString.split(" ", QString::SkipEmptyParts))
- {
- //check pattern for strings like 'rotate(10)'
- QRegExp regexp("rotate\\( *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *\\)");
- if (regexp.exactMatch(trStr)) {
- angle = regexp.capturedTexts().at(1).toDouble();
- if (item)
- {
- item->setTransformOriginPoint(QPointF(0, 0));
- item->rotate(angle);
- }
- continue;
- };
-
- //check pattern for strings like 'rotate(10,20,20)' or 'rotate(10.1,10.2,34.2)'
- regexp.setPattern("rotate\\( *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *, *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *, *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *\\)");
- if (regexp.exactMatch(trStr)) {
- angle = regexp.capturedTexts().at(1).toDouble();
- dxr = regexp.capturedTexts().at(2).toDouble();
- dyr = regexp.capturedTexts().at(3).toDouble();
- if (item)
- {
- item->setTransformOriginPoint(QPointF(dxr, dyr)-item->pos());
- item->rotate(angle);
- }
- continue;
- }
-
- //check pattern for strings like 'translate(11.0, 12.34)'
- regexp.setPattern("translate\\( *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *,*([-+]{0,1}[0-9]*\\.{0,1}[0-9]*)*\\)");
- if (regexp.exactMatch(trStr)) {
- dx = regexp.capturedTexts().at(1).toDouble();
- dy = regexp.capturedTexts().at(2).toDouble();
- tr.translate(dx,dy);
- continue;
- }
- }
- return tr;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::getViewBoxDimenstions(const QString& viewBox)
-{
- QStringList capturedTexts = viewBox.split(" ", QString::SkipEmptyParts);
- if (capturedTexts.count())
- {
- if (4 == capturedTexts.count())
- {
- mViewBox = QRectF(capturedTexts.at(0).toDouble(), capturedTexts.at(1).toDouble(), capturedTexts.at(2).toDouble(), capturedTexts.at(3).toDouble());
- mViewPort = mViewBox;
- mViewPort.translate(- mViewPort.center());
- mViewBoxCenter.setX(mViewBox.width() / 2);
- mViewBoxCenter.setY(mViewBox.height() / 2);
-
- return true;
- }
- }
-
- mViewBox = QRectF(0, 0, 1000, 1000);
- mViewBoxCenter = QPointF(500, 500);
- return false;
-}
-
-QSvgGenerator* UBCFFSubsetAdaptor::UBCFFSubsetReader::createSvgGenerator(qreal width, qreal height)
-{
- QSvgGenerator* generator = new QSvgGenerator();
-// qWarning() << QString("Making generator with file %1, size (%2, %3) and viewbox (%4 %5 %6 %7)").arg(mTempFilePath)
-// .arg(width).arg(height).arg(0.0).arg(0.0).arg(width).arg(width);
- generator->setResolution(QApplication::desktop()->physicalDpiY());
- generator->setFileName(mTempFilePath);
- generator->setSize(QSize(width, height));
- generator->setViewBox(QRectF(0, 0, width, height));
-
- return generator;
-}
-
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::getTempFileName()
-{
- int tmpNumber = 0;
- QDir rootDir;
- while (true)
- {
- mTempFilePath = QString("%1/sanksvg%2.%3")
- .arg(rootDir.tempPath())
- .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
- .arg(tmpNumber);
- if (!QFile::exists(mTempFilePath))
- return true;
- tmpNumber++;
- if (tmpNumber == 100000)
- {
- qWarning() << "Import failed. Failed to create temporary file for svg objects";
- return false;
- }
- }
-}
-bool UBCFFSubsetAdaptor::UBCFFSubsetReader::createTempFlashPath()
-{
- int tmpNumber = 0;
- QDir systemTmp = QDir::temp();
-
- while (true) {
- QString dirName = QString("SankTmpFlash%1.%2")
- .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
- .arg(tmpNumber++);
- if (!systemTmp.exists(dirName)) {
- if (systemTmp.mkdir(dirName)) {
- mTmpFlashDir = QDir(systemTmp.absolutePath() + "/" + dirName);
- return true;
- } else {
- qDebug() << "Can't create temporary dir maybe due to permissions";
- return false;
- }
- } else if (tmpNumber == 1000) {
- qWarning() << "Import failed. Failed to create temporary file for svg objects";
- return false;
- }
- }
-
- return true;
-}
-UBCFFSubsetAdaptor::UBCFFSubsetReader::~UBCFFSubsetReader()
-{
-// QList pages;
-// for (int i = 0; i < mProxy->pageCount(); i++) {
-// pages << i;
-// }
-// UBPersistenceManager::persistenceManager()->deleteDocumentScenes(mProxy, pages);
-}
+
+
+#include
+#include
+#include
+#include
+#include
+
+#include "core/UBPersistenceManager.h"
+
+#include "document/UBDocumentProxy.h"
+
+#include "domain/UBItem.h"
+#include "domain/UBGraphicsPolygonItem.h"
+#include "domain/UBGraphicsStroke.h"
+#include "domain/UBGraphicsTextItem.h"
+#include "domain/UBGraphicsSvgItem.h"
+#include "domain/UBGraphicsPixmapItem.h"
+#include "domain/UBGraphicsMediaItem.h"
+#include "domain/UBGraphicsWidgetItem.h"
+#include "domain/UBGraphicsTextItem.h"
+#include "domain/UBGraphicsTextItemDelegate.h"
+#include "domain/UBGraphicsWidgetItem.h"
+#include "domain/UBGraphicsGroupContainerItem.h"
+
+#include "frameworks/UBFileSystemUtils.h"
+
+#include "UBCFFSubsetAdaptor.h"
+#include "UBMetadataDcSubsetAdaptor.h"
+#include "UBThumbnailAdaptor.h"
+#include "UBSvgSubsetAdaptor.h"
+
+#include "core/UBApplication.h"
+#include "QFile"
+
+#include "core/memcheck.h"
+//#include "qtlogger.h"
+
+//tag names definition. Use them everiwhere!
+static QString tElement = "element";
+static QString tGroup = "group";
+static QString tEllipse = "ellipse";
+static QString tIwb = "iwb";
+static QString tMeta = "meta";
+static QString tPage = "page";
+static QString tPageset = "pageset";
+static QString tG = "g";
+static QString tSwitch = "switch";
+static QString tPolygon = "polygon";
+static QString tPolyline = "polyline";
+static QString tRect = "rect";
+static QString tSvg = "svg";
+static QString tText = "text";
+static QString tTextarea = "textarea";
+static QString tTspan = "tspan";
+static QString tBreak = "tbreak";
+static QString tImage = "image";
+static QString tFlash = "flash";
+static QString tAudio = "a";
+static QString tVideo = "video";
+
+//attribute names definition
+static QString aFill = "fill";
+static QString aFillopacity = "fill-opacity";
+static QString aX = "x";
+static QString aY = "y";
+static QString aWidth = "width";
+static QString aHeight = "height";
+static QString aStroke = "stroke";
+static QString aStrokewidth = "stroke-width";
+static QString aCx = "cx";
+static QString aCy = "cy";
+static QString aRx = "rx";
+static QString aRy = "ry";
+static QString aTransform = "transform";
+static QString aViewbox = "viewbox";
+static QString aFontSize = "font-size";
+static QString aFontfamily = "font-family";
+static QString aFontstretch = "font-stretch";
+static QString aFontstyle = "font-style";
+static QString aFontweight = "font-weight";
+static QString aTextalign = "text-align";
+static QString aPoints = "points";
+static QString svgNS = "http://www.w3.org/2000/svg";
+static QString iwbNS = "http://www.imsglobal.org/xsd/iwb_v1p0";
+static QString aId = "id";
+static QString aRef = "ref";
+static QString aHref = "href";
+static QString aBackground = "background";
+static QString aLocked = "locked";
+static QString aEditable = "editable";
+
+//attributes part names
+static QString apRotate = "rotate";
+static QString apTranslate = "translate";
+
+
+UBCFFSubsetAdaptor::UBCFFSubsetAdaptor()
+{}
+
+bool UBCFFSubsetAdaptor::ConvertCFFFileToUbz(QString &cffSourceFile, UBDocumentProxy* pDocument)
+{
+ //TODO
+ // fill document proxy metadata
+ // create persistance manager to save data using proxy
+ // create UBCFFSubsetReader and make it parse cffSourceFolder
+ QFile file(cffSourceFile);
+
+ if (!file.open(QIODevice::ReadOnly))
+ {
+ qWarning() << "Cannot open file " << cffSourceFile << " for reading ...";
+ return false;
+ }
+
+ UBCFFSubsetReader cffReader(pDocument, &file);
+ bool result = cffReader.parse();
+ file.close();
+
+ return result;
+}
+UBCFFSubsetAdaptor::UBCFFSubsetReader::UBCFFSubsetReader(UBDocumentProxy *proxy, QFile *content)
+ : mProxy(proxy)
+ , mGSectionContainer(NULL)
+{
+ int errorLine, errorColumn;
+ QString errorStr;
+ if(!mDOMdoc.setContent(content, true, &errorStr, &errorLine, &errorColumn)){
+ qWarning() << "Error:Parseerroratline" << errorLine << ","
+ << "column" << errorColumn << ":" << errorStr;
+ } else {
+ qDebug() << "well parsed to DOM";
+ pwdContent = QFileInfo(content->fileName()).dir().absolutePath();
+ }
+ qDebug() << "tmp path is" << pwdContent;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parse()
+{
+ UBMetadataDcSubsetAdaptor::persist(mProxy);
+
+ mIndent = "";
+ if (!getTempFileName() || !createTempFlashPath())
+ return false;
+
+ if (mDOMdoc.isNull())
+ return false;
+
+ bool result = parseDoc();
+ if (result)
+ result = mProxy->pageCount() != 0;
+
+ if (QFile::exists(mTempFilePath))
+ QFile::remove(mTempFilePath);
+
+// if (mTmpFlashDir.exists())
+// UBFileSystemUtils::deleteDir(mTmpFlashDir.path());
+
+ return result;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseGSection(const QDomElement &element)
+{
+ mGSectionContainer = new UBGraphicsGroupContainerItem();
+
+ QDomElement currentSvgElement = element.firstChildElement();
+ while (!currentSvgElement.isNull()) {
+ parseSvgElement(currentSvgElement);
+ currentSvgElement = currentSvgElement.nextSiblingElement();
+ }
+
+ if (mGSectionContainer->childItems().count())
+ {
+ mCurrentScene->addGroup(mGSectionContainer);
+ }
+ else
+ {
+ delete mGSectionContainer;
+ }
+ mGSectionContainer = NULL;
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgSwitchSection(const QDomElement &element)
+{
+
+ QDomElement currentSvgElement = element.firstChildElement();
+ while (!currentSvgElement.isNull()) {
+ if (parseSvgElement(currentSvgElement))
+ return true;
+ }
+
+ return false;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgRect(const QDomElement &element)
+{
+ qreal x1 = element.attribute(aX).toDouble();
+ qreal y1 = element.attribute(aY).toDouble();
+ //rect dimensions
+ qreal width = element.attribute(aWidth).toDouble();
+ qreal height = element.attribute(aHeight).toDouble();
+
+ QString textFillColor = element.attribute(aFill);
+ QString textStrokeColor = element.attribute(aStroke);
+ QString textStrokeWidth = element.attribute(aStrokewidth);
+
+ QColor fillColor = !textFillColor.isNull() ? colorFromString(textFillColor) : QColor();
+ QColor strokeColor = !textStrokeColor.isNull() ? colorFromString(textStrokeColor) : QColor();
+ int strokeWidth = textStrokeWidth.toInt();
+
+ x1 -= strokeWidth/2;
+ y1 -= strokeWidth/2;
+ width += strokeWidth;
+ height += strokeWidth;
+
+ //init svg generator with temp file
+ QSvgGenerator *generator = createSvgGenerator(width, height);
+
+ //init painter to paint to svg
+ QPainter painter;
+
+ painter.begin(generator);
+
+ //fill rect
+ if (fillColor.isValid()) {
+ painter.setBrush(QBrush(fillColor));
+ painter.fillRect(0, 0, width, height, fillColor);
+ }
+ QPen pen;
+ if (strokeColor.isValid()) {
+ pen.setColor(strokeColor);
+ }
+ if (strokeWidth)
+ pen.setWidth(strokeWidth);
+ painter.setPen(pen);
+ painter.drawRect(0, 0, width, height);
+
+ painter.end();
+
+ UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ svgItem->setUuid(QUuid(uuid));
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ svgItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, svgItem);
+ }
+
+ repositionSvgItem(svgItem, width, height, x1, y1, transform);
+ hashSceneItem(element, svgItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(svgItem);
+ }
+
+ delete generator;
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgEllipse(const QDomElement &element)
+{
+ //ellipse horisontal and vertical radius
+ qreal rx = element.attribute(aRx).toDouble();
+ qreal ry = element.attribute(aRy).toDouble();
+ QSvgGenerator *generator = createSvgGenerator(rx * 2, ry * 2);
+
+ //fill and stroke color
+ QColor fillColor = colorFromString(element.attribute(aFill));
+ QColor strokeColor = colorFromString(element.attribute(aStroke));
+ int strokeWidth = element.attribute(aStrokewidth).toInt();
+
+ //ellipse center coordinates
+ qreal cx = element.attribute(aCx).toDouble();
+ qreal cy = element.attribute(aCy).toDouble();
+
+ //init painter to paint to svg
+ QPainter painter;
+ painter.begin(generator);
+
+ QPen pen(strokeColor);
+ pen.setWidth(strokeWidth);
+ painter.setPen(pen);
+ painter.setBrush(QBrush(fillColor));
+
+ painter.drawEllipse(0, 0, rx * 2, ry * 2);
+
+ painter.end();
+
+ UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ svgItem->setUuid(QUuid(uuid));
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ svgItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, svgItem);
+ }
+
+
+ repositionSvgItem(svgItem, rx * 2, ry * 2, cx - 2*rx, cy+ry, transform);
+ hashSceneItem(element, svgItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(svgItem);
+ }
+
+ delete generator;
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPolygon(const QDomElement &element)
+{
+ QString svgPoints = element.attribute(aPoints);
+ QPolygonF polygon;
+
+ if (!svgPoints.isNull()) {
+ QStringList ts = svgPoints.split(QLatin1Char(' '), QString::SkipEmptyParts);
+
+ foreach(const QString sPoint, ts) {
+ QStringList sCoord = sPoint.split(QLatin1Char(','), QString::SkipEmptyParts);
+ if (sCoord.size() == 2) {
+ QPointF point;
+ point.setX(sCoord.at(0).toFloat());
+ point.setY(sCoord.at(1).toFloat());
+ polygon << point;
+ }
+ else if (sCoord.size() == 4){
+ //This is the case on system were the "," is used to seperate decimal
+ QPointF point;
+ QString x = sCoord.at(0) + "." + sCoord.at(1);
+ QString y = sCoord.at(2) + "." + sCoord.at(3);
+ point.setX(x.toFloat());
+ point.setY(y.toFloat());
+ polygon << point;
+ }
+ else {
+ qWarning() << "cannot make sense of a 'point' value" << sCoord;
+ }
+ }
+ }
+
+ //bounding rect lef top corner coordinates
+ qreal x1 = polygon.boundingRect().topLeft().x();
+ qreal y1 = polygon.boundingRect().topLeft().y();
+ //bounding rect dimensions
+ qreal width = polygon.boundingRect().width();
+ qreal height = polygon.boundingRect().height();
+
+ QString strokeColorText = element.attribute(aStroke);
+ QString fillColorText = element.attribute(aFill);
+ QString strokeWidthText = element.attribute(aStrokewidth);
+
+ QColor strokeColor = !strokeColorText.isEmpty() ? colorFromString(strokeColorText) : QColor();
+ QColor fillColor = !fillColorText.isEmpty() ? colorFromString(fillColorText) : QColor();
+ int strokeWidth = strokeWidthText.toDouble();
+
+ QPen pen;
+ pen.setColor(strokeColor);
+ pen.setWidth(strokeWidth);
+
+ QBrush brush;
+ brush.setColor(fillColor);
+ brush.setStyle(Qt::SolidPattern);
+
+
+ QUuid itemUuid(element.attribute(aId).right(QUuid().toString().length()));
+ QUuid itemGroupUuid(element.attribute(aId).left(QUuid().toString().length()-1));
+ if (!itemUuid.isNull() && (itemGroupUuid!=itemUuid)) // reimported from UBZ
+ {
+ UBGraphicsPolygonItem *graphicsPolygon = mCurrentScene->polygonToPolygonItem(polygon);
+
+ graphicsPolygon->setBrush(brush);
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ graphicsPolygon->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, graphicsPolygon);
+ }
+ mCurrentScene->addItem(graphicsPolygon);
+
+ graphicsPolygon->setUuid(itemUuid);
+ mRefToUuidMap.insert(element.attribute(aId), itemUuid);
+
+ }
+ else // single CFF
+ {
+ QSvgGenerator *generator = createSvgGenerator(width + pen.width(), height + pen.width());
+ QPainter painter;
+
+ painter.begin(generator); //drawing to svg tmp file
+
+ painter.translate(pen.widthF() / 2 - x1, pen.widthF() / 2 - y1);
+ painter.setBrush(brush);
+ painter.setPen(pen);
+ painter.drawPolygon(polygon);
+
+ painter.end();
+
+ //add resulting svg file to scene
+ UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ QUuid uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ svgItem->setUuid(uuid);
+
+ svgItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, svgItem);
+ }
+ repositionSvgItem(svgItem, width +strokeWidth, height + strokeWidth, x1 - strokeWidth/2 + transform.m31(), y1 + strokeWidth/2 + transform.m32(), transform);
+ hashSceneItem(element, svgItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(svgItem);
+ }
+
+ delete generator;
+ }
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPolyline(const QDomElement &element)
+{
+ QString svgPoints = element.attribute(aPoints);
+ QPolygonF polygon;
+
+ if (!svgPoints.isNull()) {
+ QStringList ts = svgPoints.split(QLatin1Char(' '),
+ QString::SkipEmptyParts);
+
+ foreach(const QString sPoint, ts) {
+ QStringList sCoord = sPoint.split(QLatin1Char(','), QString::SkipEmptyParts);
+ if (sCoord.size() == 2) {
+ QPointF point;
+ point.setX(sCoord.at(0).toFloat());
+ point.setY(sCoord.at(1).toFloat());
+ polygon << point;
+ }
+ else if (sCoord.size() == 4){
+ //This is the case on system were the "," is used to seperate decimal
+ QPointF point;
+ QString x = sCoord.at(0) + "." + sCoord.at(1);
+ QString y = sCoord.at(2) + "." + sCoord.at(3);
+ point.setX(x.toFloat());
+ point.setY(y.toFloat());
+ polygon << point;
+ }
+ else {
+ qWarning() << "cannot make sense of a 'point' value" << sCoord;
+ }
+ }
+ }
+
+ //bounding rect lef top corner coordinates
+ qreal x1 = polygon.boundingRect().topLeft().x();
+ qreal y1 = polygon.boundingRect().topLeft().y();
+
+ //bounding rect dimensions
+ qreal width = polygon.boundingRect().width();
+ qreal height = polygon.boundingRect().height();
+
+ QString strokeColorText = element.attribute(aStroke);
+ QString strokeWidthText = element.attribute(aStrokewidth);
+
+ QColor strokeColor = !strokeColorText.isEmpty() ? colorFromString(strokeColorText) : QColor();
+ int strokeWidth = strokeWidthText.toDouble();
+
+ width += strokeWidth;
+ height += strokeWidth;
+
+ QPen pen;
+ pen.setColor(strokeColor);
+ pen.setWidth(strokeWidth);
+
+ QBrush brush;
+ brush.setColor(strokeColor);
+ brush.setStyle(Qt::SolidPattern);
+
+ QUuid itemUuid(element.attribute(aId).right(QUuid().toString().length()));
+ QUuid itemGroupUuid(element.attribute(aId).left(QUuid().toString().length()-1));
+ if (!itemUuid.isNull() && (itemGroupUuid!=itemUuid)) // reimported from UBZ
+ {
+ UBGraphicsPolygonItem *graphicsPolygon = new UBGraphicsPolygonItem(polygon);
+
+ UBGraphicsStroke *stroke = new UBGraphicsStroke();
+ graphicsPolygon->setStroke(stroke);
+
+ graphicsPolygon->setBrush(brush);
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ graphicsPolygon->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, graphicsPolygon);
+ }
+ mCurrentScene->addItem(graphicsPolygon);
+
+ graphicsPolygon->setUuid(itemUuid);
+ mRefToUuidMap.insert(element.attribute(aId), itemUuid);
+
+ }
+ else // simple CFF
+ {
+ QSvgGenerator *generator = createSvgGenerator(width + pen.width(), height + pen.width());
+ QPainter painter;
+
+ painter.begin(generator); //drawing to svg tmp file
+
+ painter.translate(pen.widthF() / 2 - x1, pen.widthF() / 2 - y1);
+ painter.setBrush(brush);
+ painter.setPen(pen);
+ painter.drawPolygon(polygon);
+
+ painter.end();
+
+ //add resulting svg file to scene
+ UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ svgItem->setUuid(QUuid(uuid));
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ svgItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, svgItem);
+ }
+ repositionSvgItem(svgItem, width +strokeWidth, height + strokeWidth, x1 - strokeWidth/2 + transform.m31(), y1 + strokeWidth/2 + transform.m32(), transform);
+ hashSceneItem(element, svgItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(svgItem);
+ }
+
+ delete generator;
+ }
+
+
+ return true;
+}
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseTextAttributes(const QDomElement &element,
+ qreal &fontSize, QColor &fontColor, QString &fontFamily,
+ QString &fontStretch, bool &italic, int &fontWeight,
+ int &textAlign, QTransform &fontTransform)
+{
+ //consider inch has 72 liens
+ //since svg font size is given in pixels, divide it by pixels per line
+ QString fontSz = element.attribute(aFontSize);
+ if (!fontSz.isNull()) fontSize = fontSz.toDouble() * 72 / QApplication::desktop()->physicalDpiY();
+
+ QString fontColorText = element.attribute(aFill);
+ if (!fontColorText.isNull()) fontColor = colorFromString(fontColorText);
+
+ QString fontFamilyText = element.attribute(aFontfamily);
+ if (!fontFamilyText.isNull()) fontFamily = fontFamilyText;
+
+ QString fontStretchText = element.attribute(aFontstretch);
+ if (!fontStretchText.isNull()) fontStretch = fontStretchText;
+
+ if (!element.attribute(aFontstyle).isNull())
+ italic = (element.attribute(aFontstyle) == "italic");
+
+ QString weight = element.attribute(aFontweight);
+ if (!weight.isNull()) {
+ if (weight == "normal") fontWeight = QFont::Normal;
+ else if (weight == "light") fontWeight = QFont::Light;
+ else if (weight == "demibold") fontWeight = QFont::DemiBold;
+ else if (weight == "bold") fontWeight = QFont::Bold;
+ else if (weight == "black") fontWeight = QFont::Black;
+ }
+ QString align = element.attribute(aTextalign);
+ if (!align.isNull()) {
+ if (align == "middle" || align == "center") textAlign = Qt::AlignHCenter;
+ else if (align == "start") textAlign = Qt::AlignLeft;
+ else if (align == "end") textAlign = Qt::AlignRight;
+ }
+
+ if (!element.attribute(aTransform).isNull())
+ fontTransform = transformFromString(element.attribute(aTransform));
+}
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::readTextBlockAttr(const QDomElement &element, QTextBlockFormat &format)
+{
+ QString fontStretchText = element.attribute(aFontstretch);
+ if (!fontStretchText.isNull()) format.setAlignment(Qt::AlignJustify);
+
+ QString align = element.attribute(aTextalign);
+ if (!align.isNull()) {
+ if (align == "middle" || align == "center") format.setAlignment(Qt::AlignHCenter);
+ else if (align == "start") format.setAlignment(Qt::AlignLeft);
+ else if (align == "end") format.setAlignment(Qt::AlignRight);
+ else if (align == "justify") format.setAlignment(Qt::AlignJustify);
+ }
+}
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::readTextCharAttr(const QDomElement &element, QTextCharFormat &format)
+{
+ QString fontSz = element.attribute(aFontSize);
+ if (!fontSz.isNull()) {
+ qreal fontSize = fontSz.remove("pt").toDouble();
+ format.setFontPointSize(fontSize);
+ }
+ QString fontColorText = element.attribute(aFill);
+ if (!fontColorText.isNull()) {
+ QColor fontColor = colorFromString(fontColorText);
+ if (fontColor.isValid()) format.setForeground(fontColor);
+ }
+ QString fontFamilyText = element.attribute(aFontfamily);
+ if (!fontFamilyText.isNull()) {
+ format.setFontFamily(fontFamilyText);
+ }
+ if (!element.attribute(aFontstyle).isNull()) {
+ bool italic = (element.attribute(aFontstyle) == "italic");
+ format.setFontItalic(italic);
+ }
+ QString weight = element.attribute(aFontweight);
+ if (!weight.isNull()) {
+ if (weight == "normal") format.setFontWeight(QFont::Normal);
+ else if (weight == "light") format.setFontWeight(QFont::Light);
+ else if (weight == "demibold") format.setFontWeight(QFont::DemiBold);
+ else if (weight == "bold") format.setFontWeight(QFont::Bold);
+ else if (weight == "black") format.setFontWeight(QFont::Black);
+ }
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgText(const QDomElement &element)
+{
+ qreal x = element.attribute(aX).toDouble();
+ qreal y = element.attribute(aY).toDouble();
+ qreal width = element.attribute(aWidth).toDouble();
+ qreal height = element.attribute(aHeight).toDouble();
+
+
+ qreal fontSize = 12;
+ QColor fontColor(qApp->palette().foreground().color());
+ QString fontFamily = "Arial";
+ QString fontStretch = "normal";
+ bool italic = false;
+ int fontWeight = QFont::Normal;
+ int textAlign = Qt::AlignLeft;
+ QTransform fontTransform;
+ parseTextAttributes(element, fontSize, fontColor, fontFamily, fontStretch, italic, fontWeight, textAlign, fontTransform);
+
+ QFont startFont(fontFamily, fontSize, fontWeight, italic);
+ height = QFontMetrics(startFont).height();
+ width = QFontMetrics(startFont).width(element.text()) + 5;
+
+ QSvgGenerator *generator = createSvgGenerator(width, height);
+ QPainter painter;
+ painter.begin(generator);
+ painter.setFont(startFont);
+
+ qreal curY = 0.0;
+ qreal curX = 0.0;
+ qreal linespacing = QFontMetricsF(painter.font()).leading();
+
+// remember if text area has transform
+// QString transformString;
+ QTransform transform = fontTransform;
+
+ QRectF lastDrawnTextBoundingRect;
+ //parse text area tags
+
+ //recursive call any tspan in text svg element
+ parseTSpan(element, painter
+ , curX, curY, width, height, linespacing, lastDrawnTextBoundingRect
+ , fontSize, fontColor, fontFamily, fontStretch, italic, fontWeight, textAlign, fontTransform);
+
+ painter.end();
+
+ //add resulting svg file to scene
+ UBGraphicsSvgItem *svgItem = mCurrentScene->addSvg(QUrl::fromLocalFile(generator->fileName()));
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ svgItem->setUuid(QUuid(uuid));
+
+ svgItem->resetTransform();
+ repositionSvgItem(svgItem, width, height, x + transform.m31(), y + transform.m32(), transform);
+ hashSceneItem(element, svgItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(svgItem);
+ }
+
+ delete generator;
+ return true;
+}
+
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseTSpan(const QDomElement &parent, QPainter &painter
+ , qreal &curX, qreal &curY, qreal &width, qreal &height, qreal &linespacing, QRectF &lastDrawnTextBoundingRect
+ , qreal &fontSize, QColor &fontColor, QString &fontFamily, QString &fontStretch, bool &italic
+ , int &fontWeight, int &textAlign, QTransform &fontTransform)
+{
+ QDomNode curNode = parent.firstChild();
+ while (!curNode.isNull()) {
+ if (curNode.toElement().tagName() == tTspan) {
+ QDomElement curTSpan = curNode.toElement();
+ parseTextAttributes(curTSpan, fontSize, fontColor, fontFamily, fontStretch, italic
+ , fontWeight, textAlign, fontTransform);
+ painter.setFont(QFont(fontFamily, fontSize, fontWeight, italic));
+ painter.setPen(fontColor);
+ linespacing = QFontMetricsF(painter.font()).leading();
+ parseTSpan(curTSpan, painter
+ , curX, curY, width, height, linespacing, lastDrawnTextBoundingRect
+ , fontSize, fontColor, fontFamily, fontStretch, italic, fontWeight, textAlign, fontTransform);
+ } else if (curNode.nodeType() == QDomNode::CharacterDataNode
+ || curNode.nodeType() == QDomNode::CDATASectionNode
+ || curNode.nodeType() == QDomNode::TextNode) {
+
+ QDomCharacterData textData = curNode.toCharacterData();
+ QString text = textData.data().trimmed();
+// width = painter.fontMetrics().width(text);
+ //get bounding rect to obtain desired text height
+ lastDrawnTextBoundingRect = painter.boundingRect(QRectF(curX, curY, width, height - curY), textAlign|Qt::TextWordWrap, text);
+ painter.drawText(curX, curY, width, lastDrawnTextBoundingRect.height(), textAlign|Qt::TextWordWrap, text);
+ curX += lastDrawnTextBoundingRect.x() + lastDrawnTextBoundingRect.width();
+ } else if (curNode.nodeType() == QDomNode::ElementNode
+ && curNode.toElement().tagName() == tBreak) {
+
+ curY += lastDrawnTextBoundingRect.height() + linespacing;
+ curX = 0.0;
+ lastDrawnTextBoundingRect = QRectF(0,0,0,0);
+ }
+ curNode = curNode.nextSibling();
+ }
+}
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseTSpan(const QDomElement &element, QTextCursor &cursor
+ , QTextBlockFormat &blockFormat, QTextCharFormat &charFormat)
+{
+ QDomNode curNode = element.firstChild();
+ while (!curNode.isNull()) {
+ if (curNode.toElement().tagName() == tTspan) {
+ QDomElement curTspan = curNode.toElement();
+ readTextBlockAttr(curTspan, blockFormat);
+ readTextCharAttr(curTspan, charFormat);
+ cursor.setBlockFormat(blockFormat);
+ cursor.setCharFormat(charFormat);
+ parseTSpan(curTspan, cursor, blockFormat, charFormat);
+
+ } else if (curNode.nodeType() == QDomNode::CharacterDataNode
+ || curNode.nodeType() == QDomNode::CDATASectionNode
+ || curNode.nodeType() == QDomNode::TextNode) {
+
+ QDomCharacterData textData = curNode.toCharacterData();
+ QString text = textData.data().trimmed();
+ cursor.insertText(text, charFormat);
+
+ } else if (curNode.nodeType() == QDomNode::ElementNode
+ && curNode.toElement().tagName() == tBreak) {
+ cursor.insertBlock();
+ }
+ curNode = curNode.nextSibling();
+ }
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgTextarea(const QDomElement &element)
+{
+ qreal x = element.attribute(aX).toDouble();
+ qreal y = element.attribute(aY).toDouble();
+ qreal width = element.attribute(aWidth).toDouble();
+ qreal height = element.attribute(aHeight).toDouble();
+
+ QTextBlockFormat blockFormat;
+ blockFormat.setAlignment(Qt::AlignLeft);
+
+ QTextCharFormat textFormat;
+ // default values
+ textFormat.setFontPointSize(12);
+ textFormat.setForeground(qApp->palette().foreground().color());
+ textFormat.setFontFamily("Arial");
+ textFormat.setFontItalic(false);
+ textFormat.setFontWeight(QFont::Normal);
+
+ // readed values
+ readTextBlockAttr(element, blockFormat);
+ readTextCharAttr(element, textFormat);
+
+ QTextDocument doc;
+ doc.setPlainText("");
+ QTextCursor tCursor(&doc);
+ tCursor.setBlockFormat(blockFormat);
+ tCursor.setCharFormat(textFormat);
+
+ parseTSpan(element, tCursor, blockFormat, textFormat);
+
+ UBGraphicsTextItem *svgItem = mCurrentScene->addTextHtml(doc.toHtml());
+ svgItem->resize(width, height);
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ svgItem->setUuid(QUuid(uuid));
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ svgItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, svgItem);
+ }
+
+ //by default all the textAreas are not editable
+ UBGraphicsTextItemDelegate *curDelegate = dynamic_cast(svgItem->Delegate());
+ if (curDelegate) {
+ curDelegate->setEditable(false);
+ }
+
+ repositionSvgItem(svgItem, width, height, x + transform.m31(), y + transform.m32(), transform);
+ hashSceneItem(element, svgItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(svgItem);
+ }
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgImage(const QDomElement &element)
+{
+ qreal x = element.attribute(aX).toDouble();
+ qreal y = element.attribute(aY).toDouble();
+ qreal width = element.attribute(aWidth).toDouble();
+ qreal height = element.attribute(aHeight).toDouble();
+
+ QString itemRefPath = element.attribute(aHref);
+
+ QPixmap pix;
+ if (!itemRefPath.isNull()) {
+ QString imagePath = pwdContent + "/" + itemRefPath;
+ if (!QFile::exists(imagePath)) {
+ qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
+ return false;
+ } else {
+// qDebug() << "size of file" << itemRefPath << QFileInfo(itemRefPath).size();
+ }
+ pix.load(imagePath);
+ if (pix.isNull()) {
+ qDebug() << "can't create pixmap for file" << pwdContent + "/" + itemRefPath << "maybe format does not supported";
+ }
+ }
+
+ UBGraphicsPixmapItem *pixItem = mCurrentScene->addPixmap(pix, NULL);
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ pixItem->setUuid(QUuid(uuid));
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ pixItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, pixItem);
+ }
+ repositionSvgItem(pixItem, width, height, x + transform.m31(), y + transform.m32(), transform);
+ hashSceneItem(element, pixItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(pixItem);
+ }
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgFlash(const QDomElement &element)
+{
+ QString itemRefPath = element.attribute(aHref);
+
+ qreal x = element.attribute(aX).toDouble();
+ qreal y = element.attribute(aY).toDouble();
+ qreal width = element.attribute(aWidth).toDouble();
+ qreal height = element.attribute(aHeight).toDouble();
+
+ QUrl urlPath;
+ QString flashPath;
+ if (!itemRefPath.isNull()) {
+ flashPath = pwdContent + "/" + itemRefPath;
+ if (!QFile::exists(flashPath)) {
+ qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
+ return false;
+ }
+ urlPath = QUrl::fromLocalFile(flashPath);
+ }
+ QDir tmpFlashDir(mTmpFlashDir);
+ if (!tmpFlashDir.exists()) {
+ qDebug() << "Can't create temporary directory to put flash";
+ return false;
+ }
+
+ QString flashUrl = UBGraphicsW3CWidgetItem::createNPAPIWrapperInDir(flashPath, tmpFlashDir, "application/x-shockwave-flash"
+ ,QSize(mCurrentSceneRect.width(), mCurrentSceneRect.height()));
+ UBGraphicsWidgetItem *flashItem = mCurrentScene->addW3CWidget(QUrl::fromLocalFile(flashUrl));
+ flashItem->setSourceUrl(urlPath);
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+ flashItem->setUuid(QUuid(uuid));
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ flashItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, flashItem);
+ }
+ repositionSvgItem(flashItem, width, height, x + transform.m31(), y + transform.m32(), transform);
+ hashSceneItem(element, flashItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(flashItem);
+ }
+
+ return true;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgAudio(const QDomElement &element)
+{
+ QDomElement parentOfAudio = element.firstChild().toElement();
+
+ qreal x = parentOfAudio.attribute(aX).toDouble();
+ qreal y = parentOfAudio.attribute(aY).toDouble();
+
+ QString itemRefPath = element.attribute(aHref);
+
+ QUrl concreteUrl;
+ if (!itemRefPath.isNull()) {
+ QString audioPath = pwdContent + "/" + itemRefPath;
+ if (!QFile::exists(audioPath)) {
+ qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
+ return false;
+ }
+ concreteUrl = QUrl::fromLocalFile(audioPath);
+ }
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+
+ QString destFile;
+ bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(
+ mCurrentScene->document(),
+ concreteUrl.toLocalFile(),
+ UBPersistenceManager::audioDirectory,
+ QUuid(uuid),
+ destFile);
+ if (!b)
+ {
+ return false;
+ }
+ concreteUrl = QUrl::fromLocalFile(destFile);
+
+ UBGraphicsMediaItem *audioItem = mCurrentScene->addAudio(concreteUrl, false);
+
+ QTransform transform;
+ QString textTransform = parentOfAudio.attribute(aTransform);
+
+ audioItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, audioItem);
+ }
+ repositionSvgItem(audioItem, audioItem->boundingRect().width(), audioItem->boundingRect().height(), x + transform.m31(), y + transform.m32(), transform);
+ hashSceneItem(element, audioItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(audioItem);
+ }
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgVideo(const QDomElement &element)
+{
+ QString itemRefPath = element.attribute(aHref);
+ if (itemRefPath.startsWith(tFlash + "/") && itemRefPath.endsWith(".swf")) {
+ if (parseSvgFlash(element)) return true;
+ else return false;
+ }
+ qreal x = element.attribute(aX).toDouble();
+ qreal y = element.attribute(aY).toDouble();
+
+ QUrl concreteUrl;
+ if (!itemRefPath.isNull()) {
+ QString videoPath = pwdContent + "/" + itemRefPath;
+ if (!QFile::exists(videoPath)) {
+ qDebug() << "can't load file" << pwdContent + "/" + itemRefPath << "maybe file corrupted";
+ return false;
+ }
+ concreteUrl = QUrl::fromLocalFile(videoPath);
+ }
+
+ QString uuid = QUuid::createUuid().toString();
+ mRefToUuidMap.insert(element.attribute(aId), uuid);
+
+ QString destFile;
+ bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(
+ mCurrentScene->document(),
+ concreteUrl.toLocalFile(),
+ UBPersistenceManager::videoDirectory,
+ QUuid(uuid),
+ destFile);
+ if (!b)
+ {
+ return false;
+ }
+ concreteUrl = QUrl::fromLocalFile(destFile);
+
+ UBGraphicsMediaItem *videoItem = mCurrentScene->addVideo(concreteUrl, false);
+
+ QTransform transform;
+ QString textTransform = element.attribute(aTransform);
+
+ videoItem->resetTransform();
+ if (!textTransform.isNull()) {
+ transform = transformFromString(textTransform, videoItem);
+ }
+ repositionSvgItem(videoItem, videoItem->boundingRect().width(), videoItem->boundingRect().height(), x + transform.m31(), y + transform.m32(), transform);
+ hashSceneItem(element, videoItem);
+
+ if (mGSectionContainer)
+ {
+ addItemToGSection(videoItem);
+ }
+
+ return true;
+}
+
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgSectionAttr(const QDomElement &svgSection)
+{
+ getViewBoxDimenstions(svgSection.attribute(aViewbox));
+ mSize = QSize(svgSection.attribute(aWidth).toInt(),
+ svgSection.attribute(aHeight).toInt());
+}
+
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::addItemToGSection(QGraphicsItem *item)
+{
+ mGSectionContainer->addToGroup(item);
+}
+
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::hashSceneItem(const QDomElement &element, UBGraphicsItem *item)
+{
+// adding element pointer to hash to refer if needed
+ QString key = element.attribute(aId);
+ if (!key.isNull()) {
+ persistedItems.insert(key, item);
+ }
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgElement(const QDomElement &parent)
+{
+ QString tagName = parent.tagName();
+ if (parent.namespaceURI() != svgNS) {
+ qWarning() << "Incorrect namespace, error at content file, line number" << parent.lineNumber();
+ //return false;
+ }
+
+ if (tagName == tG && !parseGSection(parent)) return false;
+ else if (tagName == tSwitch && !parseSvgSwitchSection(parent)) return false;
+ else if (tagName == tRect && !parseSvgRect(parent)) return false;
+ else if (tagName == tEllipse && !parseSvgEllipse(parent)) return false;
+ else if (tagName == tPolygon && !parseSvgPolygon(parent)) return false;
+ else if (tagName == tPolyline && !parseSvgPolyline(parent)) return false;
+ else if (tagName == tText && !parseSvgText(parent)) return false;
+ else if (tagName == tTextarea && !parseSvgTextarea(parent)) return false;
+ else if (tagName == tImage && !parseSvgImage(parent)) return false;
+ else if (tagName == tFlash && !parseSvgFlash(parent)) return false;
+ else if (tagName == tAudio && !parseSvgAudio(parent)) return false;
+ else if (tagName == tVideo && !parseSvgVideo(parent)) return false;
+
+ return true;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPage(const QDomElement &parent)
+{
+ createNewScene();
+ QDomElement currentSvgElement = parent.firstChildElement();
+ while (!currentSvgElement.isNull()) {
+ if (!parseSvgElement(currentSvgElement))
+ return false;
+
+ currentSvgElement = currentSvgElement.nextSiblingElement();
+ }
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvgPageset(const QDomElement &parent)
+{
+ QDomElement currentPage = parent.firstChildElement(tPage);
+ while (!currentPage.isNull()) {
+ if (!parseSvgPage(currentPage))
+ return false;
+ currentPage = currentPage.nextSiblingElement(tPage);
+ }
+ return true;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseIwbMeta(const QDomElement &element)
+{
+ if (element.namespaceURI() != iwbNS) {
+ qWarning() << "incorrect meta namespace, incorrect document";
+ //return false;
+ }
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseSvg(const QDomElement &svgSection)
+{
+ if (svgSection.namespaceURI() != svgNS) {
+ qWarning() << "incorrect svg namespace, incorrect document";
+ // return false;
+ }
+
+ parseSvgSectionAttr(svgSection);
+ QDomElement currentSvg = svgSection.firstChildElement();
+
+ if (currentSvg.tagName() != tPageset) {
+ parseSvgPage(svgSection);
+ } else if (currentSvg.tagName() == tPageset){
+ parseSvgPageset(currentSvg);
+ }
+
+ return true;
+}
+
+UBGraphicsGroupContainerItem *UBCFFSubsetAdaptor::UBCFFSubsetReader::parseIwbGroup(QDomElement &parent)
+{
+ //TODO. Create groups from elements parsed by parseIwbElement() function
+ if (parent.namespaceURI() != iwbNS) {
+ qWarning() << "incorrect iwb group namespace, incorrect document";
+ // return false;
+ }
+
+ UBGraphicsGroupContainerItem *group = new UBGraphicsGroupContainerItem();
+ QMultiMap strokesGroupsContainer;
+ QList groupContainer;
+ QString currentStrokeIdentifier;
+
+ QDomElement currentStrokeElement = parent.firstChildElement();
+ while (!currentStrokeElement.isNull())
+ {
+ if (tGroup == currentStrokeElement.tagName())
+ group->addToGroup(parseIwbGroup(currentStrokeElement));
+ else
+ {
+
+ QString ref = currentStrokeElement.attribute(aRef);
+ QString uuid = mRefToUuidMap[ref];
+ if (!uuid.isEmpty())
+ {
+ if (ref.size() > QUuid().toString().length()) // create stroke group
+ {
+ currentStrokeIdentifier = ref.left(QUuid().toString().length()-1);
+ UBGraphicsPolygonItem *strokeByUuid = qgraphicsitem_cast(mCurrentScene->itemForUuid(QUuid(ref.right(QUuid().toString().length()))));
+
+ if (strokeByUuid)
+ strokesGroupsContainer.insert(currentStrokeIdentifier, strokeByUuid);
+ }
+ else // single elements in group
+ groupContainer.append(mCurrentScene->itemForUuid(QUuid(uuid)));
+ }
+ }
+ currentStrokeElement = currentStrokeElement.nextSiblingElement();
+ }
+
+
+
+ foreach (QString key, strokesGroupsContainer.keys().toSet())
+ {
+ UBGraphicsStrokesGroup* pStrokesGroup = new UBGraphicsStrokesGroup();
+ UBGraphicsStroke *currentStroke = new UBGraphicsStroke();
+ foreach(UBGraphicsPolygonItem* poly, strokesGroupsContainer.values(key))
+ {
+ if (poly)
+ {
+ mCurrentScene->removeItem(poly);
+ mCurrentScene->removeItemFromDeletion(poly);
+ poly->setStrokesGroup(pStrokesGroup);
+ poly->setStroke(currentStroke);
+ pStrokesGroup->addToGroup(poly);
+ }
+ }
+ if (currentStroke->polygons().empty())
+ delete currentStroke;
+
+ if (pStrokesGroup->childItems().count())
+ mCurrentScene->addItem(pStrokesGroup);
+ else
+ delete pStrokesGroup;
+
+ if (pStrokesGroup)
+ {
+ QGraphicsItem *strokeGroup = qgraphicsitem_cast(pStrokesGroup);
+ groupContainer.append(strokeGroup);
+ }
+ }
+
+ foreach(QGraphicsItem* item, groupContainer)
+ group->addToGroup(item);
+
+ if (group->childItems().count())
+ {
+ mCurrentScene->addItem(group);
+
+ if (1 == group->childItems().count())
+ {
+ group->destroy(false);
+ }
+ }
+
+ return group;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::strToBool(QString str)
+{
+ return str == "true";
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseIwbElement(QDomElement &element)
+{
+ if (element.namespaceURI() != iwbNS) {
+ qWarning() << "incorrect iwb element namespace, incorrect document";
+ // return false;
+ }
+
+ bool locked = false;
+ bool isEditableItem = false;
+ bool isEditable = false; //Text items to convert to UBGraphicsTextItem only
+
+ QString IDRef = element.attribute(aRef);
+ if (!IDRef.isNull()) {
+ element.hasAttribute(aBackground) ? strToBool(element.attribute(aBackground)) : false;
+ locked = element.hasAttribute(aBackground) ? strToBool(element.attribute(aBackground)) : false;
+ isEditableItem = element.hasAttribute(aEditable);
+ if (isEditableItem)
+ isEditable = strToBool(element.attribute(aEditable));
+
+ UBGraphicsItem *referedItem(0);
+ QHash::iterator iReferedItem;
+ iReferedItem = persistedItems.find(IDRef);
+ if (iReferedItem != persistedItems.end()) {
+ referedItem = *iReferedItem;
+ referedItem->Delegate()->lock(locked);
+ }
+ if (isEditableItem) {
+ UBGraphicsTextItemDelegate *textDelegate = dynamic_cast(referedItem->Delegate());
+ if (textDelegate) {
+ textDelegate->setEditable(isEditable);
+ }
+ }
+ }
+
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::parseDoc()
+{
+ QDomElement currentTopElement = mDOMdoc.documentElement().firstChildElement();
+ while (!currentTopElement.isNull()) {
+ QString tagName = currentTopElement.tagName();
+ if (tagName == tMeta && !parseIwbMeta(currentTopElement)) return false;
+ else if (tagName == tSvg && !parseSvg(currentTopElement)) return false;
+ else if (tagName == tGroup && !parseIwbGroup(currentTopElement)) return false;
+ else if (tagName == tElement && !parseIwbElement(currentTopElement)) return false;
+
+ currentTopElement = currentTopElement.nextSiblingElement();
+ }
+ if (!persistScenes()) return false;
+
+ return true;
+}
+
+void UBCFFSubsetAdaptor::UBCFFSubsetReader::repositionSvgItem(QGraphicsItem *item, qreal width, qreal height,
+ qreal x, qreal y,
+ QTransform &transform)
+{
+ //First using viebox coordinates, then translate them to scene coordinates
+
+ QRectF itemBounds = item->boundingRect();
+
+ qreal xScale = width / itemBounds.width();
+ qreal yScale = height / itemBounds.height();
+
+ qreal fullScaleX = mVBTransFactor * xScale;
+ qreal fullScaleY = mVBTransFactor * yScale;
+
+ QPointF oldVector((x - transform.dx()), (y - transform.dy()));
+ QTransform rTransform;
+ QPointF newVector = rTransform.map(oldVector);
+
+ QTransform tr = item->sceneTransform();
+ item->setTransform(rTransform.scale(fullScaleX, fullScaleY), true);
+ tr = item->sceneTransform();
+ QPoint pos;
+ if (UBGraphicsTextItem::Type == item->type())
+ pos = QPoint((int)((x + mShiftVector.x() + (newVector - oldVector).x())), (int)((y +mShiftVector.y() + (newVector - oldVector).y()) * mVBTransFactor));
+ else
+ pos = QPoint((int)((x + mShiftVector.x() + (newVector - oldVector).x()) * mVBTransFactor), (int)((y +mShiftVector.y() + (newVector - oldVector).y()) * mVBTransFactor));
+
+
+ item->setPos(pos);
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::createNewScene()
+{
+ mCurrentScene = UBPersistenceManager::persistenceManager()->createDocumentSceneAt(mProxy, mProxy->pageCount(), false);
+ mCurrentScene->setSceneRect(mViewBox);
+ if ((mCurrentScene->sceneRect().topLeft().x() >= 0) || (mCurrentScene->sceneRect().topLeft().y() >= 0)) {
+ mShiftVector = -mViewBox.center();
+ }
+ mCurrentSceneRect = mViewBox;
+ mVBTransFactor = qMin(mCurrentScene->normalizedSceneRect().width() / mViewPort.width(),
+ mCurrentScene->normalizedSceneRect().height() / mViewPort.height());
+ return true;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::persistCurrentScene()
+{
+ if (mCurrentScene != 0 && mCurrentScene->isModified())
+ {
+ UBThumbnailAdaptor::persistScene(mProxy, mCurrentScene, mProxy->pageCount() - 1);
+ UBSvgSubsetAdaptor::persistScene(mProxy, mCurrentScene, mProxy->pageCount() - 1);
+
+ mCurrentScene->setModified(false);
+ mCurrentScene = 0;
+ }
+ return true;
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::persistScenes()
+{
+ if (!mProxy->pageCount()) {
+ qDebug() << "No pages created";
+ return false;
+ }
+ for (int i = 0; i < mProxy->pageCount(); i++) {
+ mCurrentScene = UBPersistenceManager::persistenceManager()->getDocumentScene(mProxy, i);
+ if (!mCurrentScene) {
+ qDebug() << "can't allocate scene, loading failed";
+ return false;
+ }
+
+ UBSvgSubsetAdaptor::persistScene(mProxy, mCurrentScene, i);
+ UBGraphicsScene *tmpScene = UBSvgSubsetAdaptor::loadScene(mProxy, i);
+ tmpScene->setModified(true);
+ UBThumbnailAdaptor::persistScene(mProxy, tmpScene, i);
+ mCurrentScene->setModified(false);
+ }
+
+ return true;
+}
+
+QColor UBCFFSubsetAdaptor::UBCFFSubsetReader::colorFromString(const QString& clrString)
+{
+ //init regexp with pattern
+ //pattern corresponds to strings like 'rgb(1,2,3) or rgb(10%,20%,30%)'
+ QRegExp regexp("rgb\\(([0-9]+%{0,1}),([0-9]+%{0,1}),([0-9]+%{0,1})\\)");
+ if (regexp.exactMatch(clrString))
+ {
+ if (regexp.capturedTexts().count() == 4 && regexp.capturedTexts().at(0).length() == clrString.length())
+ {
+ int r = regexp.capturedTexts().at(1).toInt();
+ if (regexp.capturedTexts().at(1).indexOf("%") != -1)
+ r = r * 255 / 100;
+ int g = regexp.capturedTexts().at(2).toInt();
+ if (regexp.capturedTexts().at(2).indexOf("%") != -1)
+ g = g * 255 / 100;
+ int b = regexp.capturedTexts().at(3).toInt();
+ if (regexp.capturedTexts().at(3).indexOf("%") != -1)
+ b = b * 255 / 100;
+ return QColor(r, g, b);
+ }
+ else
+ return QColor();
+ }
+ else
+ return QColor(clrString);
+}
+
+QTransform UBCFFSubsetAdaptor::UBCFFSubsetReader::transformFromString(const QString trString, QGraphicsItem *item)
+{
+ qreal dxr = 0.0;
+ qreal dyr = 0.0;
+ qreal dx = 0.0;
+ qreal dy = 0.0;
+ qreal angle = 0.0;
+ QTransform tr;
+
+ foreach(QString trStr, trString.split(" ", QString::SkipEmptyParts))
+ {
+ //check pattern for strings like 'rotate(10)'
+ QRegExp regexp("rotate\\( *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *\\)");
+ if (regexp.exactMatch(trStr)) {
+ angle = regexp.capturedTexts().at(1).toDouble();
+ if (item)
+ {
+ item->setTransformOriginPoint(QPointF(0, 0));
+ item->rotate(angle);
+ }
+ continue;
+ };
+
+ //check pattern for strings like 'rotate(10,20,20)' or 'rotate(10.1,10.2,34.2)'
+ regexp.setPattern("rotate\\( *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *, *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *, *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *\\)");
+ if (regexp.exactMatch(trStr)) {
+ angle = regexp.capturedTexts().at(1).toDouble();
+ dxr = regexp.capturedTexts().at(2).toDouble();
+ dyr = regexp.capturedTexts().at(3).toDouble();
+ if (item)
+ {
+ item->setTransformOriginPoint(QPointF(dxr, dyr)-item->pos());
+ item->rotate(angle);
+ }
+ continue;
+ }
+
+ //check pattern for strings like 'translate(11.0, 12.34)'
+ regexp.setPattern("translate\\( *([-+]{0,1}[0-9]*\\.{0,1}[0-9]*) *,*([-+]{0,1}[0-9]*\\.{0,1}[0-9]*)*\\)");
+ if (regexp.exactMatch(trStr)) {
+ dx = regexp.capturedTexts().at(1).toDouble();
+ dy = regexp.capturedTexts().at(2).toDouble();
+ tr.translate(dx,dy);
+ continue;
+ }
+ }
+ return tr;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::getViewBoxDimenstions(const QString& viewBox)
+{
+ QStringList capturedTexts = viewBox.split(" ", QString::SkipEmptyParts);
+ if (capturedTexts.count())
+ {
+ if (4 == capturedTexts.count())
+ {
+ mViewBox = QRectF(capturedTexts.at(0).toDouble(), capturedTexts.at(1).toDouble(), capturedTexts.at(2).toDouble(), capturedTexts.at(3).toDouble());
+ mViewPort = mViewBox;
+ mViewPort.translate(- mViewPort.center());
+ mViewBoxCenter.setX(mViewBox.width() / 2);
+ mViewBoxCenter.setY(mViewBox.height() / 2);
+
+ return true;
+ }
+ }
+
+ mViewBox = QRectF(0, 0, 1000, 1000);
+ mViewBoxCenter = QPointF(500, 500);
+ return false;
+}
+
+QSvgGenerator* UBCFFSubsetAdaptor::UBCFFSubsetReader::createSvgGenerator(qreal width, qreal height)
+{
+ QSvgGenerator* generator = new QSvgGenerator();
+// qWarning() << QString("Making generator with file %1, size (%2, %3) and viewbox (%4 %5 %6 %7)").arg(mTempFilePath)
+// .arg(width).arg(height).arg(0.0).arg(0.0).arg(width).arg(width);
+ generator->setResolution(QApplication::desktop()->physicalDpiY());
+ generator->setFileName(mTempFilePath);
+ generator->setSize(QSize(width, height));
+ generator->setViewBox(QRectF(0, 0, width, height));
+
+ return generator;
+}
+
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::getTempFileName()
+{
+ int tmpNumber = 0;
+ QDir rootDir;
+ while (true)
+ {
+ mTempFilePath = QString("%1/sanksvg%2.%3")
+ .arg(rootDir.tempPath())
+ .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
+ .arg(tmpNumber);
+ if (!QFile::exists(mTempFilePath))
+ return true;
+ tmpNumber++;
+ if (tmpNumber == 100000)
+ {
+ qWarning() << "Import failed. Failed to create temporary file for svg objects";
+ return false;
+ }
+ }
+}
+bool UBCFFSubsetAdaptor::UBCFFSubsetReader::createTempFlashPath()
+{
+ int tmpNumber = 0;
+ QDir systemTmp = QDir::temp();
+
+ while (true) {
+ QString dirName = QString("SankTmpFlash%1.%2")
+ .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
+ .arg(tmpNumber++);
+ if (!systemTmp.exists(dirName)) {
+ if (systemTmp.mkdir(dirName)) {
+ mTmpFlashDir = QDir(systemTmp.absolutePath() + "/" + dirName);
+ return true;
+ } else {
+ qDebug() << "Can't create temporary dir maybe due to permissions";
+ return false;
+ }
+ } else if (tmpNumber == 1000) {
+ qWarning() << "Import failed. Failed to create temporary file for svg objects";
+ return false;
+ }
+ }
+
+ return true;
+}
+UBCFFSubsetAdaptor::UBCFFSubsetReader::~UBCFFSubsetReader()
+{
+// QList pages;
+// for (int i = 0; i < mProxy->pageCount(); i++) {
+// pages << i;
+// }
+// UBPersistenceManager::persistenceManager()->deleteDocumentScenes(mProxy, pages);
+}
diff --git a/src/adaptors/UBCFFSubsetAdaptor.h b/src/adaptors/UBCFFSubsetAdaptor.h
index 56e7afdd..5e6e7df3 100644
--- a/src/adaptors/UBCFFSubsetAdaptor.h
+++ b/src/adaptors/UBCFFSubsetAdaptor.h
@@ -19,135 +19,135 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBCFFSUBSETADAPTOR_H
-#define UBCFFSUBSETADAPTOR_H
-
-#include
-#include
-#include
-#include
-#include
-
-class UBDocumentProxy;
-class UBGraphicsScene;
-class QSvgGenerator;
-class UBGraphicsSvgItem;
-class UBGraphicsPixmapItem;
-class UBGraphicsItemDelegate;
-class QTransform;
-class QPainter;
-class UBGraphicsItem;
-class QGraphicsItem;
-class QTextBlockFormat;
-class QTextCharFormat;
-class QTextCursor;
-class UBGraphicsStrokesGroup;
-
-
-class UBCFFSubsetAdaptor
-{
-public:
- UBCFFSubsetAdaptor();
- static bool ConvertCFFFileToUbz(QString &cffSourceFile, UBDocumentProxy* pDocument);
-
-private:
- class UBCFFSubsetReader
- {
- public:
- UBCFFSubsetReader(UBDocumentProxy *proxy, QFile *content);
- ~UBCFFSubsetReader();
-
- UBDocumentProxy *mProxy;
- QString pwdContent;
-
- bool parse();
-
- private:
- QString mTempFilePath;
- UBGraphicsScene *mCurrentScene;
- QRectF mCurrentSceneRect;
- QString mIndent;
- QRectF mViewBox;
- QRectF mViewPort;
- qreal mVBTransFactor;
- QPointF mViewBoxCenter;
- QSize mSize;
- QPointF mShiftVector;
- bool mSvgGSectionIsOpened;
- UBGraphicsGroupContainerItem *mGSectionContainer;
-
- private:
- QDomDocument mDOMdoc;
- QDomNode mCurrentDOMElement;
- QHash persistedItems;
- QMap mRefToUuidMap;
- QDir mTmpFlashDir;
-
- void addItemToGSection(QGraphicsItem *item);
- bool hashElements();
- void addExtentionsToHash(QDomElement *parent, QDomElement *topGroup);
-
- void hashSvg(QDomNode *parent, QString prefix = "");
- void hashSiblingIwbElements(QDomElement *parent, QDomElement *topGroup = 0);
-
- inline void parseSvgSectionAttr(const QDomElement &);
- bool parseSvgPage(const QDomElement &parent);
- bool parseSvgPageset(const QDomElement &parent);
- bool parseSvgElement(const QDomElement &parent);
- bool parseIwbMeta(const QDomElement &element);
- bool parseSvg(const QDomElement &svgSection);
-
- inline bool parseGSection(const QDomElement &element);
- inline bool parseSvgSwitchSection(const QDomElement &element);
- inline bool parseSvgRect(const QDomElement &element);
- inline bool parseSvgEllipse(const QDomElement &element);
- inline bool parseSvgPolygon(const QDomElement &element);
- inline bool parseSvgPolyline(const QDomElement &element);
- inline bool parseSvgText(const QDomElement &element);
- inline bool parseSvgTextarea(const QDomElement &element);
- inline bool parseSvgImage(const QDomElement &element);
- inline bool parseSvgFlash(const QDomElement &element);
- inline bool parseSvgAudio(const QDomElement &element);
- inline bool parseSvgVideo(const QDomElement &element);
- inline UBGraphicsGroupContainerItem *parseIwbGroup(QDomElement &parent);
- inline bool parseIwbElement(QDomElement &element);
- inline void parseTSpan(const QDomElement &parent, QPainter &painter
- , qreal &curX, qreal &curY, qreal &width, qreal &height, qreal &linespacing, QRectF &lastDrawnTextBoundingRect
- , qreal &fontSize, QColor &fontColor, QString &fontFamily, QString &fontStretch, bool &italic
- , int &fontWeight, int &textAlign, QTransform &fontTransform);
- inline void parseTSpan(const QDomElement &element, QTextCursor &cursor
- , QTextBlockFormat &blockFormat, QTextCharFormat &charFormat);
- inline void hashSceneItem(const QDomElement &element, UBGraphicsItem *item);
-
- // to kill
- inline void parseTextAttributes(const QDomElement &element, qreal &fontSize, QColor &fontColor,
- QString &fontFamily, QString &fontStretch, bool &italic,
- int &fontWeight, int &textAlign, QTransform &fontTransform);
- inline void parseTextAttributes(const QDomElement &element, QFont &font, QColor);
- inline void readTextBlockAttr(const QDomElement &element, QTextBlockFormat &format);
- inline void readTextCharAttr(const QDomElement &element, QTextCharFormat &format);
-
- //elements parsing methods
- bool parseDoc();
-
- bool createNewScene();
- bool persistCurrentScene();
- bool persistScenes();
-
-// helper methods
- void repositionSvgItem(QGraphicsItem *item, qreal width, qreal height,
- qreal x, qreal y,
- QTransform &transform);
- QColor colorFromString(const QString& clrString);
- QTransform transformFromString(const QString trString, QGraphicsItem *item = 0);
- bool getViewBoxDimenstions(const QString& viewBox);
- QSvgGenerator* createSvgGenerator(qreal width, qreal height);
- bool getTempFileName();
- inline bool strToBool(QString);
- bool createTempFlashPath();
- };
-};
-
-#endif // UBCFFSUBSETADAPTOR_H
+
+
+#ifndef UBCFFSUBSETADAPTOR_H
+#define UBCFFSUBSETADAPTOR_H
+
+#include
+#include
+#include
+#include
+#include
+
+class UBDocumentProxy;
+class UBGraphicsScene;
+class QSvgGenerator;
+class UBGraphicsSvgItem;
+class UBGraphicsPixmapItem;
+class UBGraphicsItemDelegate;
+class QTransform;
+class QPainter;
+class UBGraphicsItem;
+class QGraphicsItem;
+class QTextBlockFormat;
+class QTextCharFormat;
+class QTextCursor;
+class UBGraphicsStrokesGroup;
+
+
+class UBCFFSubsetAdaptor
+{
+public:
+ UBCFFSubsetAdaptor();
+ static bool ConvertCFFFileToUbz(QString &cffSourceFile, UBDocumentProxy* pDocument);
+
+private:
+ class UBCFFSubsetReader
+ {
+ public:
+ UBCFFSubsetReader(UBDocumentProxy *proxy, QFile *content);
+ ~UBCFFSubsetReader();
+
+ UBDocumentProxy *mProxy;
+ QString pwdContent;
+
+ bool parse();
+
+ private:
+ QString mTempFilePath;
+ UBGraphicsScene *mCurrentScene;
+ QRectF mCurrentSceneRect;
+ QString mIndent;
+ QRectF mViewBox;
+ QRectF mViewPort;
+ qreal mVBTransFactor;
+ QPointF mViewBoxCenter;
+ QSize mSize;
+ QPointF mShiftVector;
+ bool mSvgGSectionIsOpened;
+ UBGraphicsGroupContainerItem *mGSectionContainer;
+
+ private:
+ QDomDocument mDOMdoc;
+ QDomNode mCurrentDOMElement;
+ QHash persistedItems;
+ QMap mRefToUuidMap;
+ QDir mTmpFlashDir;
+
+ void addItemToGSection(QGraphicsItem *item);
+ bool hashElements();
+ void addExtentionsToHash(QDomElement *parent, QDomElement *topGroup);
+
+ void hashSvg(QDomNode *parent, QString prefix = "");
+ void hashSiblingIwbElements(QDomElement *parent, QDomElement *topGroup = 0);
+
+ inline void parseSvgSectionAttr(const QDomElement &);
+ bool parseSvgPage(const QDomElement &parent);
+ bool parseSvgPageset(const QDomElement &parent);
+ bool parseSvgElement(const QDomElement &parent);
+ bool parseIwbMeta(const QDomElement &element);
+ bool parseSvg(const QDomElement &svgSection);
+
+ inline bool parseGSection(const QDomElement &element);
+ inline bool parseSvgSwitchSection(const QDomElement &element);
+ inline bool parseSvgRect(const QDomElement &element);
+ inline bool parseSvgEllipse(const QDomElement &element);
+ inline bool parseSvgPolygon(const QDomElement &element);
+ inline bool parseSvgPolyline(const QDomElement &element);
+ inline bool parseSvgText(const QDomElement &element);
+ inline bool parseSvgTextarea(const QDomElement &element);
+ inline bool parseSvgImage(const QDomElement &element);
+ inline bool parseSvgFlash(const QDomElement &element);
+ inline bool parseSvgAudio(const QDomElement &element);
+ inline bool parseSvgVideo(const QDomElement &element);
+ inline UBGraphicsGroupContainerItem *parseIwbGroup(QDomElement &parent);
+ inline bool parseIwbElement(QDomElement &element);
+ inline void parseTSpan(const QDomElement &parent, QPainter &painter
+ , qreal &curX, qreal &curY, qreal &width, qreal &height, qreal &linespacing, QRectF &lastDrawnTextBoundingRect
+ , qreal &fontSize, QColor &fontColor, QString &fontFamily, QString &fontStretch, bool &italic
+ , int &fontWeight, int &textAlign, QTransform &fontTransform);
+ inline void parseTSpan(const QDomElement &element, QTextCursor &cursor
+ , QTextBlockFormat &blockFormat, QTextCharFormat &charFormat);
+ inline void hashSceneItem(const QDomElement &element, UBGraphicsItem *item);
+
+ // to kill
+ inline void parseTextAttributes(const QDomElement &element, qreal &fontSize, QColor &fontColor,
+ QString &fontFamily, QString &fontStretch, bool &italic,
+ int &fontWeight, int &textAlign, QTransform &fontTransform);
+ inline void parseTextAttributes(const QDomElement &element, QFont &font, QColor);
+ inline void readTextBlockAttr(const QDomElement &element, QTextBlockFormat &format);
+ inline void readTextCharAttr(const QDomElement &element, QTextCharFormat &format);
+
+ //elements parsing methods
+ bool parseDoc();
+
+ bool createNewScene();
+ bool persistCurrentScene();
+ bool persistScenes();
+
+// helper methods
+ void repositionSvgItem(QGraphicsItem *item, qreal width, qreal height,
+ qreal x, qreal y,
+ QTransform &transform);
+ QColor colorFromString(const QString& clrString);
+ QTransform transformFromString(const QString trString, QGraphicsItem *item = 0);
+ bool getViewBoxDimenstions(const QString& viewBox);
+ QSvgGenerator* createSvgGenerator(qreal width, qreal height);
+ bool getTempFileName();
+ inline bool strToBool(QString);
+ bool createTempFlashPath();
+ };
+};
+
+#endif // UBCFFSUBSETADAPTOR_H
diff --git a/src/adaptors/UBImportCFF.cpp b/src/adaptors/UBImportCFF.cpp
index 8adf42a6..f8b2cca6 100644
--- a/src/adaptors/UBImportCFF.cpp
+++ b/src/adaptors/UBImportCFF.cpp
@@ -19,270 +19,270 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include
-#include
-
-#include "core/UBApplication.h"
-#include "core/UBPersistenceManager.h"
-#include "core/UBDocumentManager.h"
-#include "core/UBPersistenceManager.h"
-#include "document/UBDocumentProxy.h"
-#include "domain/UBGraphicsPDFItem.h"
-#include "frameworks/UBFileSystemUtils.h"
-#include "pdf/PDFRenderer.h"
-
-#include "UBCFFSubsetAdaptor.h"
-#include "UBImportCFF.h"
-
-#include "globals/UBGlobals.h"
-
-THIRD_PARTY_WARNINGS_DISABLE
-#include "quazip.h"
-#include "quazipfile.h"
-#include "quazipfileinfo.h"
-THIRD_PARTY_WARNINGS_ENABLE
-
-#include "core/memcheck.h"
-
-UBImportCFF::UBImportCFF(QObject *parent)
- : UBDocumentBasedImportAdaptor(parent)
-{
- // NOOP
-}
-
-
-UBImportCFF::~UBImportCFF()
-{
- // NOOP
-}
-
-
-QStringList UBImportCFF::supportedExtentions()
-{
- return QStringList("iwb");
-}
-
-
-QString UBImportCFF::importFileFilter()
-{
- QString filter = tr("Common File Format (");
- QStringList formats = supportedExtentions();
- bool isFirst = true;
-
- foreach(QString format, formats)
- {
- if(isFirst)
- isFirst = false;
- else
- filter.append(" ");
-
- filter.append("*."+format);
- }
-
- filter.append(")");
-
- return filter;
-}
-
-bool UBImportCFF::addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile)
-{
- QFileInfo fi(pFile);
- UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);
-
- // first unzip the file to the correct place
- //TODO create temporary path for iwb file content
- QString path = QDir::tempPath();
-
- QString documentRootFolder = expandFileToDir(pFile, path);
- QString contentFile;
- if (documentRootFolder.isEmpty()) //if file has failed to unzip it is probably just xml file
- contentFile = pFile.fileName();
- else //get path to content xml (according to iwbcff specification)
- contentFile = documentRootFolder.append("/content.xml");
-
- if(!contentFile.length()){
- UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
- return false;
- }
- else{
- //TODO convert expanded CFF file content to the destination document
- //create destination document proxy
- //fill metadata and save
- UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
- QDir dir;
- dir.mkdir(destDocument->persistencePath());
-
- //try to import cff to document
- if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
- {
- UBPersistenceManager::persistenceManager()->addDirectoryContentToDocument(destDocument->persistencePath(), pDocument);
- UBFileSystemUtils::deleteDir(destDocument->persistencePath());
- delete destDocument;
- UBApplication::showMessage(tr("Import successful."));
- return true;
- }
- else
- {
- UBFileSystemUtils::deleteDir(destDocument->persistencePath());
- delete destDocument;
- UBApplication::showMessage(tr("Import failed."));
- return false;
- }
- }
-}
-
-QString UBImportCFF::expandFileToDir(const QFile& pZipFile, const QString& pDir)
-{
- QuaZip zip(pZipFile.fileName());
-
- if(!zip.open(QuaZip::mdUnzip)) {
- qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError();
- return "";
- }
-
- zip.setFileNameCodec("UTF-8");
- QuaZipFileInfo info;
- QuaZipFile file(&zip);
-
- //create unique cff document root fodler
- //use current date/time and temp number for folder name
- QString documentRootFolder;
- int tmpNumber = 0;
- QDir rootDir;
- while (true) {
- QString tempPath = QString("%1/sank%2.%3")
- .arg(pDir)
- .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
- .arg(tmpNumber);
- if (!rootDir.exists(tempPath)) {
- documentRootFolder = tempPath;
- break;
- }
- tmpNumber++;
- if (tmpNumber == 100000) {
- qWarning() << "Import failed. Failed to create temporary directory for iwb file";
- return "";
- }
- }
- if (!rootDir.mkdir(documentRootFolder)) {
- qWarning() << "Import failed. Couse: failed to create temp folder for cff package";
- }
-
- QFile out;
- char c;
- for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
- if(!zip.getCurrentFileInfo(&info)) {
- //TOD UB 4.3 O display error to user or use crash reporter
- qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
- return "";
- }
-// if(!file.open(QIODevice::ReadOnly)) {
-// qWarning() << "Import failed. Cause: file.open(): " << zip.getZipError();
-// return "";
-// }
- file.open(QIODevice::ReadOnly);
- if(file.getZipError()!= UNZ_OK) {
- qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError();
- return "";
- }
-
- QString newFileName = documentRootFolder + "/" + file.getActualFileName();
-
- QFileInfo newFileInfo(newFileName);
- rootDir.mkpath(newFileInfo.absolutePath());
-
- out.setFileName(newFileName);
- out.open(QIODevice::WriteOnly);
-
- while(file.getChar(&c))
- out.putChar(c);
-
- out.close();
-
- if(file.getZipError()!=UNZ_OK) {
- qWarning() << "Import failed. Cause: " << zip.getZipError();
- return "";
- }
- if(!file.atEnd()) {
- qWarning() << "Import failed. Cause: read all but not EOF";
- return "";
- }
-
- file.close();
-
- if(file.getZipError()!=UNZ_OK) {
- qWarning() << "Import failed. Cause: file.close(): " << file.getZipError();
- return "";
- }
- }
-
- zip.close();
-
- if(zip.getZipError()!=UNZ_OK) {
- qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError();
- return "";
- }
-
- return documentRootFolder;
-}
-
-
-UBDocumentProxy* UBImportCFF::importFile(const QFile& pFile, const QString& pGroup)
-{
- Q_UNUSED(pGroup); // group is defined in the imported file
-
- QFileInfo fi(pFile);
- UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);
-
- // first unzip the file to the correct place
- //TODO create temporary path for iwb file content
- QString path = QDir::tempPath();
-
- QString documentRootFolder = expandFileToDir(pFile, path);
- QString contentFile;
- if (documentRootFolder.isEmpty())
- //if file has failed to umzip it is probably just xml file
- contentFile = pFile.fileName();
- else
- //get path to content xml
- contentFile = QString("%1/content.xml").arg(documentRootFolder);
-
- if(!contentFile.length()){
- UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
- return 0;
- }
- else{
- //create destination document proxy
- //fill metadata and save
- UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
- QDir dir;
- dir.mkdir(destDocument->persistencePath());
- if (pGroup.length() > 0)
- destDocument->setMetaData(UBSettings::documentGroupName, pGroup);
- if (fi.baseName() > 0)
- destDocument->setMetaData(UBSettings::documentName, fi.baseName());
-
- destDocument->setMetaData(UBSettings::documentVersion, UBSettings::currentFileVersion);
- destDocument->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- UBDocumentProxy* newDocument = NULL;
- //try to import cff to document
- if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
- {
- newDocument = UBPersistenceManager::persistenceManager()->createDocumentFromDir(destDocument->persistencePath());
- UBApplication::showMessage(tr("Import successful."));
- }
- else
- {
- UBFileSystemUtils::deleteDir(destDocument->persistencePath());
- UBApplication::showMessage(tr("Import failed."));
- }
- delete destDocument;
-
- if (documentRootFolder.length() != 0)
- UBFileSystemUtils::deleteDir(documentRootFolder);
- return newDocument;
- }
-}
+
+
+#include
+#include
+
+#include "core/UBApplication.h"
+#include "core/UBPersistenceManager.h"
+#include "core/UBDocumentManager.h"
+#include "core/UBPersistenceManager.h"
+#include "document/UBDocumentProxy.h"
+#include "domain/UBGraphicsPDFItem.h"
+#include "frameworks/UBFileSystemUtils.h"
+#include "pdf/PDFRenderer.h"
+
+#include "UBCFFSubsetAdaptor.h"
+#include "UBImportCFF.h"
+
+#include "globals/UBGlobals.h"
+
+THIRD_PARTY_WARNINGS_DISABLE
+#include "quazip.h"
+#include "quazipfile.h"
+#include "quazipfileinfo.h"
+THIRD_PARTY_WARNINGS_ENABLE
+
+#include "core/memcheck.h"
+
+UBImportCFF::UBImportCFF(QObject *parent)
+ : UBDocumentBasedImportAdaptor(parent)
+{
+ // NOOP
+}
+
+
+UBImportCFF::~UBImportCFF()
+{
+ // NOOP
+}
+
+
+QStringList UBImportCFF::supportedExtentions()
+{
+ return QStringList("iwb");
+}
+
+
+QString UBImportCFF::importFileFilter()
+{
+ QString filter = tr("Common File Format (");
+ QStringList formats = supportedExtentions();
+ bool isFirst = true;
+
+ foreach(QString format, formats)
+ {
+ if(isFirst)
+ isFirst = false;
+ else
+ filter.append(" ");
+
+ filter.append("*."+format);
+ }
+
+ filter.append(")");
+
+ return filter;
+}
+
+bool UBImportCFF::addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile)
+{
+ QFileInfo fi(pFile);
+ UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);
+
+ // first unzip the file to the correct place
+ //TODO create temporary path for iwb file content
+ QString path = QDir::tempPath();
+
+ QString documentRootFolder = expandFileToDir(pFile, path);
+ QString contentFile;
+ if (documentRootFolder.isEmpty()) //if file has failed to unzip it is probably just xml file
+ contentFile = pFile.fileName();
+ else //get path to content xml (according to iwbcff specification)
+ contentFile = documentRootFolder.append("/content.xml");
+
+ if(!contentFile.length()){
+ UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
+ return false;
+ }
+ else{
+ //TODO convert expanded CFF file content to the destination document
+ //create destination document proxy
+ //fill metadata and save
+ UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
+ QDir dir;
+ dir.mkdir(destDocument->persistencePath());
+
+ //try to import cff to document
+ if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
+ {
+ UBPersistenceManager::persistenceManager()->addDirectoryContentToDocument(destDocument->persistencePath(), pDocument);
+ UBFileSystemUtils::deleteDir(destDocument->persistencePath());
+ delete destDocument;
+ UBApplication::showMessage(tr("Import successful."));
+ return true;
+ }
+ else
+ {
+ UBFileSystemUtils::deleteDir(destDocument->persistencePath());
+ delete destDocument;
+ UBApplication::showMessage(tr("Import failed."));
+ return false;
+ }
+ }
+}
+
+QString UBImportCFF::expandFileToDir(const QFile& pZipFile, const QString& pDir)
+{
+ QuaZip zip(pZipFile.fileName());
+
+ if(!zip.open(QuaZip::mdUnzip)) {
+ qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError();
+ return "";
+ }
+
+ zip.setFileNameCodec("UTF-8");
+ QuaZipFileInfo info;
+ QuaZipFile file(&zip);
+
+ //create unique cff document root fodler
+ //use current date/time and temp number for folder name
+ QString documentRootFolder;
+ int tmpNumber = 0;
+ QDir rootDir;
+ while (true) {
+ QString tempPath = QString("%1/sank%2.%3")
+ .arg(pDir)
+ .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
+ .arg(tmpNumber);
+ if (!rootDir.exists(tempPath)) {
+ documentRootFolder = tempPath;
+ break;
+ }
+ tmpNumber++;
+ if (tmpNumber == 100000) {
+ qWarning() << "Import failed. Failed to create temporary directory for iwb file";
+ return "";
+ }
+ }
+ if (!rootDir.mkdir(documentRootFolder)) {
+ qWarning() << "Import failed. Couse: failed to create temp folder for cff package";
+ }
+
+ QFile out;
+ char c;
+ for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
+ if(!zip.getCurrentFileInfo(&info)) {
+ //TOD UB 4.3 O display error to user or use crash reporter
+ qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
+ return "";
+ }
+// if(!file.open(QIODevice::ReadOnly)) {
+// qWarning() << "Import failed. Cause: file.open(): " << zip.getZipError();
+// return "";
+// }
+ file.open(QIODevice::ReadOnly);
+ if(file.getZipError()!= UNZ_OK) {
+ qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError();
+ return "";
+ }
+
+ QString newFileName = documentRootFolder + "/" + file.getActualFileName();
+
+ QFileInfo newFileInfo(newFileName);
+ rootDir.mkpath(newFileInfo.absolutePath());
+
+ out.setFileName(newFileName);
+ out.open(QIODevice::WriteOnly);
+
+ while(file.getChar(&c))
+ out.putChar(c);
+
+ out.close();
+
+ if(file.getZipError()!=UNZ_OK) {
+ qWarning() << "Import failed. Cause: " << zip.getZipError();
+ return "";
+ }
+ if(!file.atEnd()) {
+ qWarning() << "Import failed. Cause: read all but not EOF";
+ return "";
+ }
+
+ file.close();
+
+ if(file.getZipError()!=UNZ_OK) {
+ qWarning() << "Import failed. Cause: file.close(): " << file.getZipError();
+ return "";
+ }
+ }
+
+ zip.close();
+
+ if(zip.getZipError()!=UNZ_OK) {
+ qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError();
+ return "";
+ }
+
+ return documentRootFolder;
+}
+
+
+UBDocumentProxy* UBImportCFF::importFile(const QFile& pFile, const QString& pGroup)
+{
+ Q_UNUSED(pGroup); // group is defined in the imported file
+
+ QFileInfo fi(pFile);
+ UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);
+
+ // first unzip the file to the correct place
+ //TODO create temporary path for iwb file content
+ QString path = QDir::tempPath();
+
+ QString documentRootFolder = expandFileToDir(pFile, path);
+ QString contentFile;
+ if (documentRootFolder.isEmpty())
+ //if file has failed to umzip it is probably just xml file
+ contentFile = pFile.fileName();
+ else
+ //get path to content xml
+ contentFile = QString("%1/content.xml").arg(documentRootFolder);
+
+ if(!contentFile.length()){
+ UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
+ return 0;
+ }
+ else{
+ //create destination document proxy
+ //fill metadata and save
+ UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
+ QDir dir;
+ dir.mkdir(destDocument->persistencePath());
+ if (pGroup.length() > 0)
+ destDocument->setMetaData(UBSettings::documentGroupName, pGroup);
+ if (fi.baseName() > 0)
+ destDocument->setMetaData(UBSettings::documentName, fi.baseName());
+
+ destDocument->setMetaData(UBSettings::documentVersion, UBSettings::currentFileVersion);
+ destDocument->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ UBDocumentProxy* newDocument = NULL;
+ //try to import cff to document
+ if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
+ {
+ newDocument = UBPersistenceManager::persistenceManager()->createDocumentFromDir(destDocument->persistencePath());
+ UBApplication::showMessage(tr("Import successful."));
+ }
+ else
+ {
+ UBFileSystemUtils::deleteDir(destDocument->persistencePath());
+ UBApplication::showMessage(tr("Import failed."));
+ }
+ delete destDocument;
+
+ if (documentRootFolder.length() != 0)
+ UBFileSystemUtils::deleteDir(documentRootFolder);
+ return newDocument;
+ }
+}
diff --git a/src/adaptors/UBImportCFF.h b/src/adaptors/UBImportCFF.h
index ab36b514..7748f5f3 100644
--- a/src/adaptors/UBImportCFF.h
+++ b/src/adaptors/UBImportCFF.h
@@ -19,32 +19,32 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBIMPORTCFF_H
-#define UBIMPORTCFF_H
-
-#include
-#include "UBImportAdaptor.h"
-
-class UBDocumentProxy;
-
-class UBImportCFF : public UBDocumentBasedImportAdaptor
-{
- Q_OBJECT;
-
- public:
- UBImportCFF(QObject *parent = 0);
- virtual ~UBImportCFF();
-
- virtual QStringList supportedExtentions();
- virtual QString importFileFilter();
-
- virtual bool addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile);
- virtual UBDocumentProxy* importFile(const QFile& pFile, const QString& pGroup);
-
- private:
- QString expandFileToDir(const QFile& pZipFile, const QString& pDir);
-};
-
-#endif // UBIMPORTCFF_H
+
+
+#ifndef UBIMPORTCFF_H
+#define UBIMPORTCFF_H
+
+#include
+#include "UBImportAdaptor.h"
+
+class UBDocumentProxy;
+
+class UBImportCFF : public UBDocumentBasedImportAdaptor
+{
+ Q_OBJECT;
+
+ public:
+ UBImportCFF(QObject *parent = 0);
+ virtual ~UBImportCFF();
+
+ virtual QStringList supportedExtentions();
+ virtual QString importFileFilter();
+
+ virtual bool addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile);
+ virtual UBDocumentProxy* importFile(const QFile& pFile, const QString& pGroup);
+
+ private:
+ QString expandFileToDir(const QFile& pZipFile, const QString& pDir);
+};
+
+#endif // UBIMPORTCFF_H
diff --git a/src/adaptors/UBSvgSubsetAdaptor.h b/src/adaptors/UBSvgSubsetAdaptor.h
index 013a23ce..0d7d2c38 100644
--- a/src/adaptors/UBSvgSubsetAdaptor.h
+++ b/src/adaptors/UBSvgSubsetAdaptor.h
@@ -19,249 +19,249 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBSVGSUBSETADAPTOR_H_
-#define UBSVGSUBSETADAPTOR_H_
-
-#include
-#include
-
-#include "frameworks/UBGeometryUtils.h"
-
-class UBGraphicsSvgItem;
-class UBGraphicsPolygonItem;
-class UBGraphicsPixmapItem;
-class UBGraphicsPDFItem;
-class UBGraphicsWidgetItem;
-class UBGraphicsMediaItem;
-class UBGraphicsAppleWidgetItem;
-class UBGraphicsW3CWidgetItem;
-class UBGraphicsTextItem;
-class UBGraphicsCurtainItem;
-class UBGraphicsRuler;
-class UBGraphicsCompass;
-class UBGraphicsProtractor;
-class UBGraphicsScene;
-class UBDocumentProxy;
-class UBGraphicsStroke;
-class UBPersistenceManager;
-class UBGraphicsTriangle;
-class UBGraphicsCache;
-class IDataStorage;
-class UBGraphicsGroupContainerItem;
-class UBGraphicsStrokesGroup;
-
-class UBSvgSubsetAdaptor
-{
- private:
-
- UBSvgSubsetAdaptor() {;}
- virtual ~UBSvgSubsetAdaptor() {;}
-
- public:
-
- static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const int pageIndex);
- static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex);
- static void upgradeScene(UBDocumentProxy* proxy, const int pageIndex);
-
- static QUuid sceneUuid(UBDocumentProxy* proxy, const int pageIndex);
- static void setSceneUuid(UBDocumentProxy* proxy, const int pageIndex, QUuid pUuid);
-
- static bool addElementToBeStored(QString domName,IDataStorage* dataStorageClass);
-
- static void convertPDFObjectsToImages(UBDocumentProxy* proxy);
- static void convertSvgImagesToImages(UBDocumentProxy* proxy);
-
- static QMap getAdditionalElementToStore() { return additionalElementToStore;}
-
- static const QString nsSvg;
- static const QString nsXLink;
- static const QString nsXHtml;
- static const QString nsUb;
- static const QString xmlTrue;
- static const QString xmlFalse;
-
- static const QString sFontSizePrefix;
- static const QString sPixelUnit;
- static const QString sFontWeightPrefix;
- static const QString sFontStylePrefix;
-
- static QString readTeacherGuideNode(int sceneIndex);
- private:
-
- static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const QByteArray& pArray);
-
- static QDomDocument loadSceneDocument(UBDocumentProxy* proxy, const int pPageIndex);
-
- static QString uniboardDocumentNamespaceUriFromVersion(int fileVersion);
-
- static const QString sFormerUniboardDocumentNamespaceUri;
-
- static QString toSvgTransform(const QMatrix& matrix);
- static QMatrix fromSvgTransform(const QString& transform);
-
- static QMap additionalElementToStore;
-
-
-
-
- class UBSvgSubsetReader
- {
- public:
-
- UBSvgSubsetReader(UBDocumentProxy* proxy, const QByteArray& pXmlData);
-
- virtual ~UBSvgSubsetReader(){}
-
- UBGraphicsScene* loadScene();
-
- private:
-
- UBGraphicsPolygonItem* polygonItemFromLineSvg(const QColor& pDefaultBrushColor);
-
- UBGraphicsPolygonItem* polygonItemFromPolygonSvg(const QColor& pDefaultBrushColor);
-
- QList polygonItemsFromPolylineSvg(const QColor& pDefaultColor);
-
- UBGraphicsPixmapItem* pixmapItemFromSvg();
-
- UBGraphicsSvgItem* svgItemFromSvg();
-
- UBGraphicsPDFItem* pdfItemFromPDF();
-
- UBGraphicsMediaItem* videoItemFromSvg();
-
- UBGraphicsMediaItem* audioItemFromSvg();
-
- UBGraphicsAppleWidgetItem* graphicsAppleWidgetFromSvg();
-
- UBGraphicsW3CWidgetItem* graphicsW3CWidgetFromSvg();
-
- UBGraphicsTextItem* textItemFromSvg();
-
- UBGraphicsCurtainItem* curtainItemFromSvg();
-
- UBGraphicsRuler* rulerFromSvg();
-
- UBGraphicsCompass* compassFromSvg();
-
- UBGraphicsProtractor* protractorFromSvg();
-
- UBGraphicsTriangle* triangleFromSvg();
-
- UBGraphicsCache* cacheFromSvg();
-
- void readGroupRoot();
- QGraphicsItem *readElementFromGroup();
- UBGraphicsGroupContainerItem* readGroup();
-
- void graphicsItemFromSvg(QGraphicsItem* gItem);
-
- qreal getZValueFromSvg();
- QUuid getUuidFromSvg();
-
- QXmlStreamReader mXmlReader;
- int mFileVersion;
- UBDocumentProxy *mProxy;
- QString mDocumentPath;
-
- QColor mGroupDarkBackgroundColor;
- QColor mGroupLightBackgroundColor;
- qreal mGroupZIndex;
- bool mGroupHasInfo;
-
- QString mNamespaceUri;
- UBGraphicsScene *mScene;
-
- QMap mStrokesList;
- };
-
- class UBSvgSubsetWriter
- {
- public:
-
- UBSvgSubsetWriter(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex);
-
- bool persistScene(int pageIndex);
-
- virtual ~UBSvgSubsetWriter(){}
-
- private:
-
- void persistGroupToDom(QGraphicsItem *groupItem, QDomElement *curParent, QDomDocument *curDomDocument);
- void persistStrokeToDom(QGraphicsItem *strokeItem, QDomElement *curParent, QDomDocument *curDomDocument);
- void polygonItemToSvgPolygon(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo);
- void polygonItemToSvgLine(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo);
- void strokeToSvgPolyline(UBGraphicsStroke* stroke, bool groupHoldsInfo);
- void strokeToSvgPolygon(UBGraphicsStroke* stroke, bool groupHoldsInfo);
-
- inline QString pointsToSvgPointsAttribute(QVector points)
- {
- UBGeometryUtils::crashPointList(points);
-
- int pointsCount = points.size();
- QString svgPoints;
-
- int length = 0;
- QString sBuf;
-
- for(int j = 0; j < pointsCount; j++)
- {
- sBuf = "%1,%2 ";
- const QPointF & point = points.at(j);
-
- QString temp1 = "%1", temp2 = "%2";
-
- temp1 = temp1.arg(point.x());
- temp2 = temp2.arg(point.y());
-
- QLocale loc(QLocale::C);
- sBuf = sBuf.arg(loc.toFloat(temp1)).arg(loc.toFloat(temp2));
-
- svgPoints.insert(length, sBuf);
- length += sBuf.length();
- }
- return svgPoints;
- }
-
- inline qreal trickAlpha(qreal alpha)
- {
- qreal trickAlpha = alpha;
- if(trickAlpha >= 0.2 && trickAlpha < 0.6){
- trickAlpha /= 5;
- }else if (trickAlpha < 0.8)
- trickAlpha /= 3;
-
- return trickAlpha;
- }
-
- void pixmapItemToLinkedImage(UBGraphicsPixmapItem *pixmapItem);
- void svgItemToLinkedSvg(UBGraphicsSvgItem *svgItem);
- void pdfItemToLinkedPDF(UBGraphicsPDFItem *pdfItem);
- void videoItemToLinkedVideo(UBGraphicsMediaItem *videoItem);
- void audioItemToLinkedAudio(UBGraphicsMediaItem *audioItem);
- void graphicsItemToSvg(QGraphicsItem *item);
- void graphicsAppleWidgetToSvg(UBGraphicsAppleWidgetItem *item);
- void graphicsW3CWidgetToSvg(UBGraphicsW3CWidgetItem *item);
- void graphicsWidgetToSvg(UBGraphicsWidgetItem *item);
- void textItemToSvg(UBGraphicsTextItem *item);
- void curtainItemToSvg(UBGraphicsCurtainItem *item);
- void rulerToSvg(UBGraphicsRuler *item);
- void compassToSvg(UBGraphicsCompass *item);
- void protractorToSvg(UBGraphicsProtractor *item);
- void cacheToSvg(UBGraphicsCache* item);
- void triangleToSvg(UBGraphicsTriangle *item);
- void writeSvgElement();
-
- private:
-
- UBGraphicsScene* mScene;
- QXmlStreamWriter mXmlWriter;
- QString mDocumentPath;
- int mPageIndex;
-
- };
-};
-
-#endif /* UBSVGSUBSETADAPTOR_H_ */
+
+
+#ifndef UBSVGSUBSETADAPTOR_H_
+#define UBSVGSUBSETADAPTOR_H_
+
+#include
+#include
+
+#include "frameworks/UBGeometryUtils.h"
+
+class UBGraphicsSvgItem;
+class UBGraphicsPolygonItem;
+class UBGraphicsPixmapItem;
+class UBGraphicsPDFItem;
+class UBGraphicsWidgetItem;
+class UBGraphicsMediaItem;
+class UBGraphicsAppleWidgetItem;
+class UBGraphicsW3CWidgetItem;
+class UBGraphicsTextItem;
+class UBGraphicsCurtainItem;
+class UBGraphicsRuler;
+class UBGraphicsCompass;
+class UBGraphicsProtractor;
+class UBGraphicsScene;
+class UBDocumentProxy;
+class UBGraphicsStroke;
+class UBPersistenceManager;
+class UBGraphicsTriangle;
+class UBGraphicsCache;
+class IDataStorage;
+class UBGraphicsGroupContainerItem;
+class UBGraphicsStrokesGroup;
+
+class UBSvgSubsetAdaptor
+{
+ private:
+
+ UBSvgSubsetAdaptor() {;}
+ virtual ~UBSvgSubsetAdaptor() {;}
+
+ public:
+
+ static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const int pageIndex);
+ static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex);
+ static void upgradeScene(UBDocumentProxy* proxy, const int pageIndex);
+
+ static QUuid sceneUuid(UBDocumentProxy* proxy, const int pageIndex);
+ static void setSceneUuid(UBDocumentProxy* proxy, const int pageIndex, QUuid pUuid);
+
+ static bool addElementToBeStored(QString domName,IDataStorage* dataStorageClass);
+
+ static void convertPDFObjectsToImages(UBDocumentProxy* proxy);
+ static void convertSvgImagesToImages(UBDocumentProxy* proxy);
+
+ static QMap getAdditionalElementToStore() { return additionalElementToStore;}
+
+ static const QString nsSvg;
+ static const QString nsXLink;
+ static const QString nsXHtml;
+ static const QString nsUb;
+ static const QString xmlTrue;
+ static const QString xmlFalse;
+
+ static const QString sFontSizePrefix;
+ static const QString sPixelUnit;
+ static const QString sFontWeightPrefix;
+ static const QString sFontStylePrefix;
+
+ static QString readTeacherGuideNode(int sceneIndex);
+ private:
+
+ static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const QByteArray& pArray);
+
+ static QDomDocument loadSceneDocument(UBDocumentProxy* proxy, const int pPageIndex);
+
+ static QString uniboardDocumentNamespaceUriFromVersion(int fileVersion);
+
+ static const QString sFormerUniboardDocumentNamespaceUri;
+
+ static QString toSvgTransform(const QMatrix& matrix);
+ static QMatrix fromSvgTransform(const QString& transform);
+
+ static QMap additionalElementToStore;
+
+
+
+
+ class UBSvgSubsetReader
+ {
+ public:
+
+ UBSvgSubsetReader(UBDocumentProxy* proxy, const QByteArray& pXmlData);
+
+ virtual ~UBSvgSubsetReader(){}
+
+ UBGraphicsScene* loadScene();
+
+ private:
+
+ UBGraphicsPolygonItem* polygonItemFromLineSvg(const QColor& pDefaultBrushColor);
+
+ UBGraphicsPolygonItem* polygonItemFromPolygonSvg(const QColor& pDefaultBrushColor);
+
+ QList polygonItemsFromPolylineSvg(const QColor& pDefaultColor);
+
+ UBGraphicsPixmapItem* pixmapItemFromSvg();
+
+ UBGraphicsSvgItem* svgItemFromSvg();
+
+ UBGraphicsPDFItem* pdfItemFromPDF();
+
+ UBGraphicsMediaItem* videoItemFromSvg();
+
+ UBGraphicsMediaItem* audioItemFromSvg();
+
+ UBGraphicsAppleWidgetItem* graphicsAppleWidgetFromSvg();
+
+ UBGraphicsW3CWidgetItem* graphicsW3CWidgetFromSvg();
+
+ UBGraphicsTextItem* textItemFromSvg();
+
+ UBGraphicsCurtainItem* curtainItemFromSvg();
+
+ UBGraphicsRuler* rulerFromSvg();
+
+ UBGraphicsCompass* compassFromSvg();
+
+ UBGraphicsProtractor* protractorFromSvg();
+
+ UBGraphicsTriangle* triangleFromSvg();
+
+ UBGraphicsCache* cacheFromSvg();
+
+ void readGroupRoot();
+ QGraphicsItem *readElementFromGroup();
+ UBGraphicsGroupContainerItem* readGroup();
+
+ void graphicsItemFromSvg(QGraphicsItem* gItem);
+
+ qreal getZValueFromSvg();
+ QUuid getUuidFromSvg();
+
+ QXmlStreamReader mXmlReader;
+ int mFileVersion;
+ UBDocumentProxy *mProxy;
+ QString mDocumentPath;
+
+ QColor mGroupDarkBackgroundColor;
+ QColor mGroupLightBackgroundColor;
+ qreal mGroupZIndex;
+ bool mGroupHasInfo;
+
+ QString mNamespaceUri;
+ UBGraphicsScene *mScene;
+
+ QMap mStrokesList;
+ };
+
+ class UBSvgSubsetWriter
+ {
+ public:
+
+ UBSvgSubsetWriter(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex);
+
+ bool persistScene(int pageIndex);
+
+ virtual ~UBSvgSubsetWriter(){}
+
+ private:
+
+ void persistGroupToDom(QGraphicsItem *groupItem, QDomElement *curParent, QDomDocument *curDomDocument);
+ void persistStrokeToDom(QGraphicsItem *strokeItem, QDomElement *curParent, QDomDocument *curDomDocument);
+ void polygonItemToSvgPolygon(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo);
+ void polygonItemToSvgLine(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo);
+ void strokeToSvgPolyline(UBGraphicsStroke* stroke, bool groupHoldsInfo);
+ void strokeToSvgPolygon(UBGraphicsStroke* stroke, bool groupHoldsInfo);
+
+ inline QString pointsToSvgPointsAttribute(QVector points)
+ {
+ UBGeometryUtils::crashPointList(points);
+
+ int pointsCount = points.size();
+ QString svgPoints;
+
+ int length = 0;
+ QString sBuf;
+
+ for(int j = 0; j < pointsCount; j++)
+ {
+ sBuf = "%1,%2 ";
+ const QPointF & point = points.at(j);
+
+ QString temp1 = "%1", temp2 = "%2";
+
+ temp1 = temp1.arg(point.x());
+ temp2 = temp2.arg(point.y());
+
+ QLocale loc(QLocale::C);
+ sBuf = sBuf.arg(loc.toFloat(temp1)).arg(loc.toFloat(temp2));
+
+ svgPoints.insert(length, sBuf);
+ length += sBuf.length();
+ }
+ return svgPoints;
+ }
+
+ inline qreal trickAlpha(qreal alpha)
+ {
+ qreal trickAlpha = alpha;
+ if(trickAlpha >= 0.2 && trickAlpha < 0.6){
+ trickAlpha /= 5;
+ }else if (trickAlpha < 0.8)
+ trickAlpha /= 3;
+
+ return trickAlpha;
+ }
+
+ void pixmapItemToLinkedImage(UBGraphicsPixmapItem *pixmapItem);
+ void svgItemToLinkedSvg(UBGraphicsSvgItem *svgItem);
+ void pdfItemToLinkedPDF(UBGraphicsPDFItem *pdfItem);
+ void videoItemToLinkedVideo(UBGraphicsMediaItem *videoItem);
+ void audioItemToLinkedAudio(UBGraphicsMediaItem *audioItem);
+ void graphicsItemToSvg(QGraphicsItem *item);
+ void graphicsAppleWidgetToSvg(UBGraphicsAppleWidgetItem *item);
+ void graphicsW3CWidgetToSvg(UBGraphicsW3CWidgetItem *item);
+ void graphicsWidgetToSvg(UBGraphicsWidgetItem *item);
+ void textItemToSvg(UBGraphicsTextItem *item);
+ void curtainItemToSvg(UBGraphicsCurtainItem *item);
+ void rulerToSvg(UBGraphicsRuler *item);
+ void compassToSvg(UBGraphicsCompass *item);
+ void protractorToSvg(UBGraphicsProtractor *item);
+ void cacheToSvg(UBGraphicsCache* item);
+ void triangleToSvg(UBGraphicsTriangle *item);
+ void writeSvgElement();
+
+ private:
+
+ UBGraphicsScene* mScene;
+ QXmlStreamWriter mXmlWriter;
+ QString mDocumentPath;
+ int mPageIndex;
+
+ };
+};
+
+#endif /* UBSVGSUBSETADAPTOR_H_ */
diff --git a/src/adaptors/UBThumbnailAdaptor.cpp b/src/adaptors/UBThumbnailAdaptor.cpp
index 68441c58..bd1a6acc 100644
--- a/src/adaptors/UBThumbnailAdaptor.cpp
+++ b/src/adaptors/UBThumbnailAdaptor.cpp
@@ -19,169 +19,169 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include "UBThumbnailAdaptor.h"
-
-#include
-
-#include "frameworks/UBFileSystemUtils.h"
-
-#include "core/UBPersistenceManager.h"
-#include "core/UBApplication.h"
-#include "core/UBSettings.h"
-
-
-#include "gui/UBDockTeacherGuideWidget.h"
-#include "gui/UBTeacherGuideWidget.h"
-
-#include "board/UBBoardController.h"
-#include "board/UBBoardPaletteManager.h"
-
-#include "document/UBDocumentProxy.h"
-
-#include "domain/UBGraphicsScene.h"
-
-#include "UBSvgSubsetAdaptor.h"
-
-#include "core/memcheck.h"
-
-void UBThumbnailAdaptor::generateMissingThumbnails(UBDocumentProxy* proxy)
-{
- int existingPageCount = proxy->pageCount();
-
- for (int iPageNo = 0; iPageNo < existingPageCount; ++iPageNo)
- {
- QString thumbFileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", iPageNo);
-
- QFile thumbFile(thumbFileName);
-
- if (!thumbFile.exists())
- {
- bool displayMessage = (existingPageCount > 5);
-
- int thumbCount = 0;
-
- UBGraphicsScene* scene = UBSvgSubsetAdaptor::loadScene(proxy, iPageNo);
-
- if (scene)
- {
- thumbCount++;
-
- if (displayMessage && thumbCount == 1)
- UBApplication::showMessage(tr("Generating preview thumbnails ..."));
-
- persistScene(proxy, scene, iPageNo);
- }
-
- if (displayMessage && thumbCount > 0)
- UBApplication::showMessage(tr("%1 thumbnails generated ...").arg(thumbCount));
-
- }
- }
-}
-
-const QPixmap* UBThumbnailAdaptor::get(UBDocumentProxy* proxy, int pageIndex)
-{
- QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
-
- QFile file(fileName);
- if (!file.exists())
- {
- generateMissingThumbnails(proxy);
- }
-
- QPixmap* pix = new QPixmap();
- if (file.exists())
- {
- //Warning. Works only with modified Qt
-#ifdef Q_WS_X11
- pix->load(fileName, 0, Qt::AutoColor);
-#else
- pix->load(fileName, 0, Qt::AutoColor, false);
-#endif
- }
- return pix;
-}
-
-void UBThumbnailAdaptor::updateDocumentToHandleZeroPage(UBDocumentProxy* proxy)
-{
- if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()){
- QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", 0);
- QFile file(fileName);
- if(!file.exists()){
- UBPersistenceManager::persistenceManager()->persistDocumentScene(proxy,new UBGraphicsScene(proxy),0);
- }
- }
-}
-
-void UBThumbnailAdaptor::load(UBDocumentProxy* proxy, QList& list)
-{
- updateDocumentToHandleZeroPage(proxy);
- generateMissingThumbnails(proxy);
-
- foreach(const QPixmap* pm, list)
- delete pm;
- list.clear();
- for(int i=0; ipageCount(); i++)
- list.append(get(proxy, i));
-}
-
-void UBThumbnailAdaptor::persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified)
-{
- QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
-
- QFile thumbFile(fileName);
-
- if (pScene->isModified() || overrideModified || !thumbFile.exists() || UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified())
- {
- qreal nominalWidth = pScene->nominalSize().width();
- qreal nominalHeight = pScene->nominalSize().height();
- qreal ratio = nominalWidth / nominalHeight;
- QRectF sceneRect = pScene->normalizedSceneRect(ratio);
-
- qreal width = UBSettings::maxThumbnailWidth;
- qreal height = width / ratio;
-
- QImage thumb(width, height, QImage::Format_ARGB32);
-
- QRectF imageRect(0, 0, width, height);
-
- QPainter painter(&thumb);
- painter.setRenderHint(QPainter::Antialiasing, true);
- painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
-
- if (pScene->isDarkBackground())
- {
- painter.fillRect(imageRect, Qt::black);
- }
- else
- {
- painter.fillRect(imageRect, Qt::white);
- }
-
- pScene->setRenderingContext(UBGraphicsScene::NonScreen);
- pScene->setRenderingQuality(UBItem::RenderingQualityHigh);
-
- pScene->render(&painter, imageRect, sceneRect, Qt::KeepAspectRatio);
-
- if(UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()){
- QPixmap toque(":images/toque.svg");
- painter.setOpacity(0.6);
- painter.drawPixmap(QPoint(width - toque.width(),0),toque);
- }
-
- pScene->setRenderingContext(UBGraphicsScene::Screen);
- pScene->setRenderingQuality(UBItem::RenderingQualityNormal);
-
- thumb.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(fileName, "JPG");
- }
-}
-
-
-QUrl UBThumbnailAdaptor::thumbnailUrl(UBDocumentProxy* proxy, int pageIndex)
-{
- QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
-
- return QUrl::fromLocalFile(fileName);
-}
+
+
+#include "UBThumbnailAdaptor.h"
+
+#include
+
+#include "frameworks/UBFileSystemUtils.h"
+
+#include "core/UBPersistenceManager.h"
+#include "core/UBApplication.h"
+#include "core/UBSettings.h"
+
+
+#include "gui/UBDockTeacherGuideWidget.h"
+#include "gui/UBTeacherGuideWidget.h"
+
+#include "board/UBBoardController.h"
+#include "board/UBBoardPaletteManager.h"
+
+#include "document/UBDocumentProxy.h"
+
+#include "domain/UBGraphicsScene.h"
+
+#include "UBSvgSubsetAdaptor.h"
+
+#include "core/memcheck.h"
+
+void UBThumbnailAdaptor::generateMissingThumbnails(UBDocumentProxy* proxy)
+{
+ int existingPageCount = proxy->pageCount();
+
+ for (int iPageNo = 0; iPageNo < existingPageCount; ++iPageNo)
+ {
+ QString thumbFileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", iPageNo);
+
+ QFile thumbFile(thumbFileName);
+
+ if (!thumbFile.exists())
+ {
+ bool displayMessage = (existingPageCount > 5);
+
+ int thumbCount = 0;
+
+ UBGraphicsScene* scene = UBSvgSubsetAdaptor::loadScene(proxy, iPageNo);
+
+ if (scene)
+ {
+ thumbCount++;
+
+ if (displayMessage && thumbCount == 1)
+ UBApplication::showMessage(tr("Generating preview thumbnails ..."));
+
+ persistScene(proxy, scene, iPageNo);
+ }
+
+ if (displayMessage && thumbCount > 0)
+ UBApplication::showMessage(tr("%1 thumbnails generated ...").arg(thumbCount));
+
+ }
+ }
+}
+
+const QPixmap* UBThumbnailAdaptor::get(UBDocumentProxy* proxy, int pageIndex)
+{
+ QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
+
+ QFile file(fileName);
+ if (!file.exists())
+ {
+ generateMissingThumbnails(proxy);
+ }
+
+ QPixmap* pix = new QPixmap();
+ if (file.exists())
+ {
+ //Warning. Works only with modified Qt
+#ifdef Q_WS_X11
+ pix->load(fileName, 0, Qt::AutoColor);
+#else
+ pix->load(fileName, 0, Qt::AutoColor, false);
+#endif
+ }
+ return pix;
+}
+
+void UBThumbnailAdaptor::updateDocumentToHandleZeroPage(UBDocumentProxy* proxy)
+{
+ if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()){
+ QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", 0);
+ QFile file(fileName);
+ if(!file.exists()){
+ UBPersistenceManager::persistenceManager()->persistDocumentScene(proxy,new UBGraphicsScene(proxy),0);
+ }
+ }
+}
+
+void UBThumbnailAdaptor::load(UBDocumentProxy* proxy, QList& list)
+{
+ updateDocumentToHandleZeroPage(proxy);
+ generateMissingThumbnails(proxy);
+
+ foreach(const QPixmap* pm, list)
+ delete pm;
+ list.clear();
+ for(int i=0; ipageCount(); i++)
+ list.append(get(proxy, i));
+}
+
+void UBThumbnailAdaptor::persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified)
+{
+ QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
+
+ QFile thumbFile(fileName);
+
+ if (pScene->isModified() || overrideModified || !thumbFile.exists() || UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified())
+ {
+ qreal nominalWidth = pScene->nominalSize().width();
+ qreal nominalHeight = pScene->nominalSize().height();
+ qreal ratio = nominalWidth / nominalHeight;
+ QRectF sceneRect = pScene->normalizedSceneRect(ratio);
+
+ qreal width = UBSettings::maxThumbnailWidth;
+ qreal height = width / ratio;
+
+ QImage thumb(width, height, QImage::Format_ARGB32);
+
+ QRectF imageRect(0, 0, width, height);
+
+ QPainter painter(&thumb);
+ painter.setRenderHint(QPainter::Antialiasing, true);
+ painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
+
+ if (pScene->isDarkBackground())
+ {
+ painter.fillRect(imageRect, Qt::black);
+ }
+ else
+ {
+ painter.fillRect(imageRect, Qt::white);
+ }
+
+ pScene->setRenderingContext(UBGraphicsScene::NonScreen);
+ pScene->setRenderingQuality(UBItem::RenderingQualityHigh);
+
+ pScene->render(&painter, imageRect, sceneRect, Qt::KeepAspectRatio);
+
+ if(UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()){
+ QPixmap toque(":images/toque.svg");
+ painter.setOpacity(0.6);
+ painter.drawPixmap(QPoint(width - toque.width(),0),toque);
+ }
+
+ pScene->setRenderingContext(UBGraphicsScene::Screen);
+ pScene->setRenderingQuality(UBItem::RenderingQualityNormal);
+
+ thumb.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(fileName, "JPG");
+ }
+}
+
+
+QUrl UBThumbnailAdaptor::thumbnailUrl(UBDocumentProxy* proxy, int pageIndex)
+{
+ QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
+
+ return QUrl::fromLocalFile(fileName);
+}
diff --git a/src/adaptors/UBThumbnailAdaptor.h b/src/adaptors/UBThumbnailAdaptor.h
index bbdecb9f..52305dc1 100644
--- a/src/adaptors/UBThumbnailAdaptor.h
+++ b/src/adaptors/UBThumbnailAdaptor.h
@@ -19,34 +19,34 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBTHUMBNAILADAPTOR_H
-#define UBTHUMBNAILADAPTOR_H
-
-#include
-
-class UBDocument;
-class UBDocumentProxy;
-class UBGraphicsScene;
-
-class UBThumbnailAdaptor //static class
-{
- Q_DECLARE_TR_FUNCTIONS(UBThumbnailAdaptor)
-
-public:
- static QUrl thumbnailUrl(UBDocumentProxy* proxy, int pageIndex);
-
- static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified = false);
-
- static const QPixmap* get(UBDocumentProxy* proxy, int index);
- static void load(UBDocumentProxy* proxy, QList& list);
-
-private:
- static void generateMissingThumbnails(UBDocumentProxy* proxy);
- static void updateDocumentToHandleZeroPage(UBDocumentProxy* proxy);
-
- UBThumbnailAdaptor() {}
-};
-
-#endif // UBTHUMBNAILADAPTOR_H
+
+
+#ifndef UBTHUMBNAILADAPTOR_H
+#define UBTHUMBNAILADAPTOR_H
+
+#include
+
+class UBDocument;
+class UBDocumentProxy;
+class UBGraphicsScene;
+
+class UBThumbnailAdaptor //static class
+{
+ Q_DECLARE_TR_FUNCTIONS(UBThumbnailAdaptor)
+
+public:
+ static QUrl thumbnailUrl(UBDocumentProxy* proxy, int pageIndex);
+
+ static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified = false);
+
+ static const QPixmap* get(UBDocumentProxy* proxy, int index);
+ static void load(UBDocumentProxy* proxy, QList& list);
+
+private:
+ static void generateMissingThumbnails(UBDocumentProxy* proxy);
+ static void updateDocumentToHandleZeroPage(UBDocumentProxy* proxy);
+
+ UBThumbnailAdaptor() {}
+};
+
+#endif // UBTHUMBNAILADAPTOR_H
diff --git a/src/adaptors/publishing/UBDocumentPublisher.cpp b/src/adaptors/publishing/UBDocumentPublisher.cpp
index 96b8d6bf..33e9b58e 100644
--- a/src/adaptors/publishing/UBDocumentPublisher.cpp
+++ b/src/adaptors/publishing/UBDocumentPublisher.cpp
@@ -19,813 +19,813 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include
-
-#include "UBDocumentPublisher.h"
-
-#include "frameworks/UBPlatformUtils.h"
-#include "frameworks/UBFileSystemUtils.h"
-#include "frameworks/UBStringUtils.h"
-
-#include "network/UBNetworkAccessManager.h"
-#include "network/UBServerXMLHttpRequest.h"
-
-#include "core/UBDocumentManager.h"
-#include "core/UBApplication.h"
-#include "core/UBPersistenceManager.h"
-#include "core/UBApplicationController.h"
-
-#include "board/UBBoardController.h"
-
-#include "gui/UBMainWindow.h"
-
-#include "document/UBDocumentProxy.h"
-#include "document/UBDocumentContainer.h"
-
-#include "domain/UBGraphicsWidgetItem.h"
-
-#include "globals/UBGlobals.h"
-
-THIRD_PARTY_WARNINGS_DISABLE
-#include "quazip.h"
-#include "quazipfile.h"
-THIRD_PARTY_WARNINGS_ENABLE
-
-#include "adaptors/UBExportFullPDF.h"
-#include "adaptors/UBExportDocument.h"
-#include "adaptors/UBSvgSubsetAdaptor.h"
-
-#include "UBSvgSubsetRasterizer.h"
-
-#include "../../core/UBApplication.h"
-
-#include "core/memcheck.h"
-
-
-UBDocumentPublisher::UBDocumentPublisher(UBDocumentProxy* pDocument, QObject *parent)
- : QObject(parent)
- , mSourceDocument(pDocument)
- , mUsername("")
- , mPassword("")
- , bLoginCookieSet(false)
-{
- init();
-}
-
-
-UBDocumentPublisher::~UBDocumentPublisher()
-{
-}
-
-
-void UBDocumentPublisher::publish()
-{
- //check that the username and password are stored on preferences
- UBSettings* settings = UBSettings::settings();
-
- if(settings->communityUsername().isEmpty() || settings->communityPassword().isEmpty()){
- UBApplication::showMessage(tr("Credentials has to not been filled out yet."));
- qDebug() << "trying to connect to community without the required credentials";
- return;
- }
-
- mUsername = settings->communityUsername();
- mPassword = settings->communityPassword();
-
- UBPublicationDlg dlg;
- if(QDialog::Accepted == dlg.exec())
- {
- mDocInfos.title = dlg.title();
- mDocInfos.description = dlg.description();
-
- buildUbwFile();
-
- UBApplication::showMessage(tr("Uploading Sankore File on Web."));
-
- sendUbw(mUsername, mPassword);
- }
-}
-
-void UBDocumentPublisher::buildUbwFile()
-{
- QDir d;
- d.mkpath(UBFileSystemUtils::defaultTempDirPath());
-
- QString tmpDir = UBFileSystemUtils::createTempDir();
-
- if (UBFileSystemUtils::copyDir(mSourceDocument->persistencePath(), tmpDir))
- {
- QString documentName = mSourceDocument->name();
-
- mPublishingPath = tmpDir;
- mPublishingSize = mSourceDocument->pageCount();
-
- rasterizeScenes();
-
- upgradeDocumentForPublishing();
-
- UBExportFullPDF pdfExporter;
- pdfExporter.setVerbode(false);
- pdfExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".pdf");
-
- UBExportDocument ubzExporter;
- ubzExporter.setVerbode(false);
- ubzExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".ubz");
-
- // remove all useless files
-
- for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++) {
- QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.svg",pageIndex);
-
- QFile::remove(filename);
- }
-
- UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::imageDirectory);
- UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::objectDirectory);
- UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::videoDirectory);
- UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::audioDirectory);
-
- mTmpZipFile = UBFileSystemUtils::defaultTempDirPath() + "/" + UBStringUtils::toCanonicalUuid(QUuid::createUuid()) + ".ubw~";
-
- QuaZip zip(mTmpZipFile);
- zip.setFileNameCodec("UTF-8");
- if (!zip.open(QuaZip::mdCreate))
- {
- qWarning() << "Export failed. Cause: zip.open(): " << zip.getZipError() << "," << mTmpZipFile;
- QApplication::restoreOverrideCursor();
- return;
- }
-
- QuaZipFile outFile(&zip);
-
- if (!UBFileSystemUtils::compressDirInZip(mPublishingPath, "", &outFile, true))
- {
- qWarning("Export failed. compressDirInZip failed ...");
- zip.close();
- UBApplication::showMessage(tr("Export failed."));
- QApplication::restoreOverrideCursor();
- return;
- }
-
- if (zip.getZipError() != 0)
- {
- qWarning("Export failed. Cause: zip.close(): %d", zip.getZipError());
- zip.close();
- UBApplication::showMessage(tr("Export failed."));
- QApplication::restoreOverrideCursor();
- return;
- }
-
- zip.close();
-
- }
- else
- {
- UBApplication::showMessage(tr("Export canceled ..."));
- QApplication::restoreOverrideCursor();
- }
-}
-
-void UBDocumentPublisher::rasterizeScenes()
-{
-
- for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++)
- {
- UBApplication::showMessage(tr("Converting page %1/%2 ...").arg(UBDocumentContainer::pageFromSceneIndex(pageIndex)).arg(mPublishingSize), true);
-
- UBDocumentProxy publishingDocument(mPublishingPath);
- UBSvgSubsetRasterizer rasterizer(&publishingDocument, pageIndex);
-
- QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.jpg",pageIndex);
-
- rasterizer.rasterizeToFile(filename);
-
- }
-}
-
-
-void UBDocumentPublisher::updateGoogleMapApiKey()
-{
- QDir widgestDir(mPublishingPath + "/" + UBPersistenceManager::widgetDirectory);
-
- QString uniboardWebGoogleMapApiKey = UBSettings::settings()->uniboardWebGoogleMapApiKey->get().toString();
-
- foreach(QFileInfo dirInfo, widgestDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
- {
- QString config = UBFileSystemUtils::readTextFile(dirInfo.absoluteFilePath() + "/config.xml").toLower();
-
- if (config.contains("google") && config.contains("map"))
- {
- QDir widgetDir(dirInfo.absoluteFilePath());
-
- foreach(QFileInfo fileInfo, widgetDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot))
- {
- QFile file(fileInfo.absoluteFilePath());
-
- if (file.open(QIODevice::ReadWrite))
- {
- QTextStream stream(&file);
- QString content = stream.readAll();
-
- if (content.contains("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og"))
- {
- content.replace("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og",
- uniboardWebGoogleMapApiKey);
-
- file.resize(0);
- file.write(content.toUtf8());
- }
- file.close();
- }
- }
- }
- }
-}
-
-
-void UBDocumentPublisher::upgradeDocumentForPublishing()
-{
- for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++)
- {
- UBDocumentProxy publishingDocument(mPublishingPath);
- UBGraphicsScene *scene = UBSvgSubsetAdaptor::loadScene(&publishingDocument, pageIndex);
-
- QList widgets;
-
- foreach(QGraphicsItem* item, scene->items()){
- UBGraphicsW3CWidgetItem *widgetItem = dynamic_cast(item);
-
- if(widgetItem){
- generateWidgetPropertyScript(widgetItem, UBDocumentContainer::pageFromSceneIndex(pageIndex));
- widgets << widgetItem;
- }
- }
-
- QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.json",pageIndex);
-
- QFile jsonFile(filename);
- if (jsonFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
- {
- jsonFile.write("{\n");
- jsonFile.write(QString(" \"scene\": {\n").toUtf8());
- jsonFile.write(QString(" \"x\": %1,\n").arg(scene->normalizedSceneRect().x()).toUtf8());
- jsonFile.write(QString(" \"y\": %1,\n").arg(scene->normalizedSceneRect().y()).toUtf8());
- jsonFile.write(QString(" \"width\": %1,\n").arg(scene->normalizedSceneRect().width()).toUtf8());
- jsonFile.write(QString(" \"height\": %1\n").arg(scene->normalizedSceneRect().height()).toUtf8());
- jsonFile.write(QString(" },\n").toUtf8());
-
- jsonFile.write(QString(" \"widgets\": [\n").toUtf8());
-
- bool first = true;
-
- foreach(UBGraphicsW3CWidgetItem* widget, widgets)
- {
- if (!first)
- jsonFile.write(QString(" ,\n").toUtf8());
-
- jsonFile.write(QString(" {\n").toUtf8());
- jsonFile.write(QString(" \"uuid\": \"%1\",\n").arg(UBStringUtils::toCanonicalUuid(widget->uuid())).toUtf8());
- jsonFile.write(QString(" \"id\": \"%1\",\n").arg(widget->metadatas().id).toUtf8());
-
- jsonFile.write(QString(" \"name\": \"%1\",\n").arg(widget->metadatas().name).toUtf8());
- jsonFile.write(QString(" \"description\": \"%1\",\n").arg(widget->metadatas().description).toUtf8());
- jsonFile.write(QString(" \"author\": \"%1\",\n").arg(widget->metadatas().author).toUtf8());
- jsonFile.write(QString(" \"authorEmail\": \"%1\",\n").arg(widget->metadatas().authorEmail).toUtf8());
- jsonFile.write(QString(" \"authorHref\": \"%1\",\n").arg(widget->metadatas().authorHref).toUtf8());
- jsonFile.write(QString(" \"version\": \"%1\",\n").arg(widget->metadatas().authorHref).toUtf8());
-
- jsonFile.write(QString(" \"x\": %1,\n").arg(widget->sceneBoundingRect().x()).toUtf8());
- jsonFile.write(QString(" \"y\": %1,\n").arg(widget->sceneBoundingRect().y()).toUtf8());
- jsonFile.write(QString(" \"width\": %1,\n").arg(widget->sceneBoundingRect().width()).toUtf8());
- jsonFile.write(QString(" \"height\": %1,\n").arg(widget->sceneBoundingRect().height()).toUtf8());
-
- jsonFile.write(QString(" \"nominalWidth\": %1,\n").arg(widget->boundingRect().width()).toUtf8());
- jsonFile.write(QString(" \"nominalHeight\": %1,\n").arg(widget->boundingRect().height()).toUtf8());
-
- QString url = UBPersistenceManager::widgetDirectory + "/" + widget->uuid().toString() + ".wgt";
- jsonFile.write(QString(" \"src\": \"%1\",\n").arg(url).toUtf8());
- QString startFile = widget->mainHtmlFileName();
- jsonFile.write(QString(" \"startFile\": \"%1\",\n").arg(startFile).toUtf8());
-
- QMap preferences = widget->UBGraphicsWidgetItem::preferences();
-
- jsonFile.write(QString(" \"preferences\": {\n").toUtf8());
-
- foreach(QString key, preferences.keys())
- {
- QString sep = ",";
- if (key == preferences.keys().last())
- sep = "";
-
- jsonFile.write(QString(" \"%1\": \"%2\"%3\n")
- .arg(key)
- .arg(preferences.value(key))
- .arg(sep)
- .toUtf8());
- }
- jsonFile.write(QString(" },\n").toUtf8());
-
- jsonFile.write(QString(" \"datastore\": {\n").toUtf8());
-
- QMap datastoreEntries = widget->datastoreEntries();
-
- foreach(QString entry, datastoreEntries.keys())
- {
- QString sep = ",";
- if (entry == datastoreEntries.keys().last())
- sep = "";
-
- jsonFile.write(QString(" \"%1\": \"%2\"%3\n")
- .arg(entry)
- .arg(datastoreEntries.value(entry))
- .arg(sep)
- .toUtf8());
- }
- jsonFile.write(QString(" }\n").toUtf8());
-
- jsonFile.write(QString(" }\n").toUtf8());
-
- first = false;
- }
-
- jsonFile.write(" ]\n");
- jsonFile.write("}\n");
- }
- else
- {
- qWarning() << "Cannot open file" << filename << "for saving page state";
- }
-
- delete scene;
- }
-
- updateGoogleMapApiKey();
-}
-
-
-void UBDocumentPublisher::generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber)
-{
-
- QMap preferences = widgetItem->UBGraphicsWidgetItem::preferences();
- QMap datastoreEntries = widgetItem->datastoreEntries();
-
- QString startFileName = widgetItem->mainHtmlFileName();
-
- if (!startFileName.startsWith("http://"))
- {
- QString startFilePath = mPublishingPath + "/" + UBPersistenceManager::widgetDirectory + "/" + widgetItem->uuid().toString() + ".wgt/" + startFileName;
-
- QFile startFile(startFilePath);
-
- if (startFile.exists())
- {
- if (startFile.open(QIODevice::ReadWrite))
- {
- QTextStream stream(&startFile);
- QStringList lines;
-
- bool addedJs = false;
-
- QString line;
- do
- {
- line = stream.readLine();
- if (!line.isNull())
- {
- lines << line;
-
- if (!addedJs && line.contains("") ) // TODO UB 4.6, this is naive ... the HEAD tag may be on several lines
- {
- lines << "";
- lines << " ";
- lines << "";
-
- addedJs = true;
- }
- }
- }
- while (!line.isNull());
-
- startFile.resize(0);
- startFile.write(lines.join("\n").toUtf8()); // TODO UB 4.x detect real html encoding
-
- startFile.close();
- }
- }
- }
- else{
- qWarning() << "Remote Widget start file, cannot inject widget preferences and datastore entries";
- }
-}
-
-void UBDocumentPublisher::init()
-{
- mCrlf=0x0d;
- mCrlf+=0x0a;
- mDocInfos.title = "";
- mDocInfos.description = "";
-
- mpCookieJar = new QNetworkCookieJar();
- mpNetworkMgr = new QNetworkAccessManager(this);
-
- connect(mpNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
-}
-
-void UBDocumentPublisher::onFinished(QNetworkReply *reply)
-{
- QVariant cookieHeader = reply->rawHeader("Set-Cookie");
- // First we concatenate all the Set-Cookie values (the packet can contains many of them)
- QStringList qslCookie = cookieHeader.toString().split("\n");
- QString qsCookieValue = qslCookie.at(0);
- for (int i = 1; i < qslCookie.size(); i++) {
- qsCookieValue += "; " +qslCookie.at(i);
- }
-
- // Now we isolate every cookie value
- QStringList qslCookieVals = qsCookieValue.split("; ");
-
- bool bTransferOk = false;
-
- for(int j = 0; j < qslCookieVals.size(); j++)
- {
- qDebug() << j;
- if(qslCookieVals.at(j).startsWith("assetStatus"))
- {
- QStringList qslAsset = qslCookieVals.at(j).split("=");
- if(qslAsset.at(1) == "UPLOADED")
- {
- bTransferOk = true;
- break;
- }
- }
- }
-
- if(bTransferOk)
- {
- UBApplication::showMessage(tr("Document uploaded correctly on the web."));
- }
- else
- {
- UBApplication::showMessage(tr("Failed to upload document on the web."));
- }
-
- reply->deleteLater();
-}
-
-void UBDocumentPublisher::sendUbw(QString username, QString password)
-{
- if (QFile::exists(mTmpZipFile))
- {
- QFile f(mTmpZipFile);
- if (f.open(QIODevice::ReadOnly))
- {
- QFileInfo fi(f);
- QByteArray ba = f.readAll();
- QString boundary,data, multipartHeader;
- QByteArray datatoSend;
-
- boundary = "---WebKitFormBoundaryDKBTgA53MiyWrzLY";
- multipartHeader = "multipart/form-data; boundary="+boundary;
-
- data="--"+boundary+mCrlf;
- data+="Content-Disposition: form-data; name=\"title\"" + mCrlf + mCrlf + mDocInfos.title + mCrlf;
- data+="--"+boundary+mCrlf;
- data+="Content-Disposition: form-data; name=\"description\"" + mCrlf + mCrlf + mDocInfos.description.remove("\n") + mCrlf;
- data+="--"+boundary+mCrlf;
- data+="Content-Disposition: form-data; name=\"file\"; filename=\""+ fi.fileName() +"\""+mCrlf;
- data+="Content-Type: application/octet-stream"+mCrlf+mCrlf;
- datatoSend=data.toAscii(); // convert data string to byte array for request
- datatoSend += ba;
- datatoSend += mCrlf;
- datatoSend += QString("--%0--%1").arg(boundary).arg(mCrlf);
-
- QNetworkRequest request(QUrl(QString(DOCPUBLICATION_URL).toAscii().constData()));
-
- request.setHeader(QNetworkRequest::ContentTypeHeader, multipartHeader);
- request.setHeader(QNetworkRequest::ContentLengthHeader,datatoSend.size());
- QString b64Auth = getBase64Of(QString("%0:%1").arg(username).arg(password));
- request.setRawHeader("Authorization", QString("Basic %0").arg(b64Auth).toAscii().constData());
- request.setRawHeader("Host", "planete.sankore.org");
- request.setRawHeader("Accept", "*/*");
- request.setRawHeader("Accept-Language", "en-US,*");
-
- mpCookieJar->setCookiesFromUrl(mCookies, QUrl(DOCPUBLICATION_URL));
- mpNetworkMgr->setCookieJar(mpCookieJar);
-
- // Send the file
- mpNetworkMgr->post(request,datatoSend);
- }
- }
-}
-
-QString UBDocumentPublisher::getBase64Of(QString stringToEncode)
-{
- return stringToEncode.toAscii().toBase64();
-}
-
-// ---------------------------------------------------------
-UBProxyLoginDlg::UBProxyLoginDlg(QWidget *parent, const char *name):QDialog(parent)
- , mpLayout(NULL)
- , mpUserLayout(NULL)
- , mpPasswordLayout(NULL)
- , mpButtons(NULL)
- , mpUserLabel(NULL)
- , mpPasswordLabel(NULL)
- , mpUsername(NULL)
- , mpPassword(NULL)
-{
- setObjectName(name);
- setFixedSize(400, 150);
- setWindowTitle(tr("Proxy Login"));
-
- mpLayout = new QVBoxLayout();
- setLayout(mpLayout);
- mpUserLayout = new QHBoxLayout();
- mpLayout->addLayout(mpUserLayout);
- mpPasswordLayout = new QHBoxLayout();
- mpLayout->addLayout(mpPasswordLayout);
-
- mpUserLabel = new QLabel(tr("Username:"), this);
- mpUsername = new QLineEdit(this);
- mpUserLayout->addWidget(mpUserLabel, 0);
- mpUserLayout->addWidget(mpUsername, 1);
-
- mpPasswordLabel = new QLabel(tr("Password:"), this);
- mpPassword = new QLineEdit(this);
- mpPasswordLayout->addWidget(mpPasswordLabel, 0);
- mpPasswordLayout->addWidget(mpPassword, 1);
-
- mpButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
- mpLayout->addWidget(mpButtons);
-
- connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept()));
- connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject()));
-
-}
-
-UBProxyLoginDlg::~UBProxyLoginDlg()
-{
- if(NULL != mpLayout)
- {
- delete mpLayout;
- mpLayout = NULL;
- }
- if(NULL != mpButtons)
- {
- delete mpButtons;
- mpButtons = NULL;
- }
- if(NULL != mpUserLabel)
- {
- delete mpUserLabel;
- mpUserLabel = NULL;
- }
- if(NULL != mpPasswordLabel)
- {
- delete mpPasswordLabel;
- mpPasswordLabel = NULL;
- }
- if(NULL != mpUsername)
- {
- delete mpUsername;
- mpUsername = NULL;
- }
- if(NULL != mpPassword)
- {
- delete mpPassword;
- mpPassword = NULL;
- }
-}
-
-// ---------------------------------------------------------
-UBPublicationDlg::UBPublicationDlg(QWidget *parent, const char *name):QDialog(parent)
- , mpLayout(NULL)
- , mpTitleLayout(NULL)
- , mpTitleLabel(NULL)
- , mpTitle(NULL)
- , mpDescLabel(NULL)
- , mpDescription(NULL)
- , mpButtons(NULL)
-{
- setObjectName(name);
- setWindowTitle(tr("Publish document on the web"));
-
- resize(500, 300);
-
- mpLayout = new QVBoxLayout();
- setLayout(mpLayout);
-
- mpTitleLabel = new QLabel(tr("Title:"), this);
- mpTitle = new QLineEdit(this);
- mpTitleLayout = new QHBoxLayout();
- mpTitleLayout->addWidget(mpTitleLabel, 0);
- mpTitleLayout->addWidget(mpTitle, 1);
- mpLayout->addLayout(mpTitleLayout, 0);
-
- mpDescLabel = new QLabel(tr("Description:"), this);
- mpLayout->addWidget(mpDescLabel, 0);
-
- mpDescription = new QTextEdit(this);
- mpLayout->addWidget(mpDescription, 1);
-
- mpButtons = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this);
- mpButtons->button(QDialogButtonBox::Ok)->setText(tr("Publish"));
- mpLayout->addWidget(mpButtons);
-
- mpButtons->button(QDialogButtonBox::Ok)->setEnabled(false);
-
- connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept()));
- connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject()));
- connect(mpTitle, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged()));
- connect(mpDescription, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
-}
-
-UBPublicationDlg::~UBPublicationDlg()
-{
- if(NULL != mpTitleLabel)
- {
- delete mpTitleLabel;
- mpTitleLabel = NULL;
- }
- if(NULL != mpTitle)
- {
- delete mpTitle;
- mpTitle = NULL;
- }
- if(NULL != mpDescLabel)
- {
- delete mpDescLabel;
- mpDescLabel = NULL;
- }
- if(NULL != mpDescription)
- {
- delete mpDescription;
- mpDescription = NULL;
- }
- if(NULL != mpButtons)
- {
- delete mpButtons;
- mpButtons = NULL;
- }
- if(NULL != mpTitleLayout)
- {
- delete mpTitleLayout;
- mpTitleLayout = NULL;
- }
- if(NULL != mpLayout)
- {
- delete mpLayout;
- mpLayout = NULL;
- }
-}
-
-void UBPublicationDlg::onTextChanged()
-{
- bool bPublishButtonState = false;
- if(mpTitle->text() != "" && mpDescription->document()->toPlainText() != "")
- {
- bPublishButtonState = true;
- }
- else
- {
- bPublishButtonState = false;
- }
-
- mpButtons->button(QDialogButtonBox::Ok)->setEnabled(bPublishButtonState);
-}
+
+
+#include
+
+#include "UBDocumentPublisher.h"
+
+#include "frameworks/UBPlatformUtils.h"
+#include "frameworks/UBFileSystemUtils.h"
+#include "frameworks/UBStringUtils.h"
+
+#include "network/UBNetworkAccessManager.h"
+#include "network/UBServerXMLHttpRequest.h"
+
+#include "core/UBDocumentManager.h"
+#include "core/UBApplication.h"
+#include "core/UBPersistenceManager.h"
+#include "core/UBApplicationController.h"
+
+#include "board/UBBoardController.h"
+
+#include "gui/UBMainWindow.h"
+
+#include "document/UBDocumentProxy.h"
+#include "document/UBDocumentContainer.h"
+
+#include "domain/UBGraphicsWidgetItem.h"
+
+#include "globals/UBGlobals.h"
+
+THIRD_PARTY_WARNINGS_DISABLE
+#include "quazip.h"
+#include "quazipfile.h"
+THIRD_PARTY_WARNINGS_ENABLE
+
+#include "adaptors/UBExportFullPDF.h"
+#include "adaptors/UBExportDocument.h"
+#include "adaptors/UBSvgSubsetAdaptor.h"
+
+#include "UBSvgSubsetRasterizer.h"
+
+#include "../../core/UBApplication.h"
+
+#include "core/memcheck.h"
+
+
+UBDocumentPublisher::UBDocumentPublisher(UBDocumentProxy* pDocument, QObject *parent)
+ : QObject(parent)
+ , mSourceDocument(pDocument)
+ , mUsername("")
+ , mPassword("")
+ , bLoginCookieSet(false)
+{
+ init();
+}
+
+
+UBDocumentPublisher::~UBDocumentPublisher()
+{
+}
+
+
+void UBDocumentPublisher::publish()
+{
+ //check that the username and password are stored on preferences
+ UBSettings* settings = UBSettings::settings();
+
+ if(settings->communityUsername().isEmpty() || settings->communityPassword().isEmpty()){
+ UBApplication::showMessage(tr("Credentials has to not been filled out yet."));
+ qDebug() << "trying to connect to community without the required credentials";
+ return;
+ }
+
+ mUsername = settings->communityUsername();
+ mPassword = settings->communityPassword();
+
+ UBPublicationDlg dlg;
+ if(QDialog::Accepted == dlg.exec())
+ {
+ mDocInfos.title = dlg.title();
+ mDocInfos.description = dlg.description();
+
+ buildUbwFile();
+
+ UBApplication::showMessage(tr("Uploading Sankore File on Web."));
+
+ sendUbw(mUsername, mPassword);
+ }
+}
+
+void UBDocumentPublisher::buildUbwFile()
+{
+ QDir d;
+ d.mkpath(UBFileSystemUtils::defaultTempDirPath());
+
+ QString tmpDir = UBFileSystemUtils::createTempDir();
+
+ if (UBFileSystemUtils::copyDir(mSourceDocument->persistencePath(), tmpDir))
+ {
+ QString documentName = mSourceDocument->name();
+
+ mPublishingPath = tmpDir;
+ mPublishingSize = mSourceDocument->pageCount();
+
+ rasterizeScenes();
+
+ upgradeDocumentForPublishing();
+
+ UBExportFullPDF pdfExporter;
+ pdfExporter.setVerbode(false);
+ pdfExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".pdf");
+
+ UBExportDocument ubzExporter;
+ ubzExporter.setVerbode(false);
+ ubzExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".ubz");
+
+ // remove all useless files
+
+ for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++) {
+ QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.svg",pageIndex);
+
+ QFile::remove(filename);
+ }
+
+ UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::imageDirectory);
+ UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::objectDirectory);
+ UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::videoDirectory);
+ UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::audioDirectory);
+
+ mTmpZipFile = UBFileSystemUtils::defaultTempDirPath() + "/" + UBStringUtils::toCanonicalUuid(QUuid::createUuid()) + ".ubw~";
+
+ QuaZip zip(mTmpZipFile);
+ zip.setFileNameCodec("UTF-8");
+ if (!zip.open(QuaZip::mdCreate))
+ {
+ qWarning() << "Export failed. Cause: zip.open(): " << zip.getZipError() << "," << mTmpZipFile;
+ QApplication::restoreOverrideCursor();
+ return;
+ }
+
+ QuaZipFile outFile(&zip);
+
+ if (!UBFileSystemUtils::compressDirInZip(mPublishingPath, "", &outFile, true))
+ {
+ qWarning("Export failed. compressDirInZip failed ...");
+ zip.close();
+ UBApplication::showMessage(tr("Export failed."));
+ QApplication::restoreOverrideCursor();
+ return;
+ }
+
+ if (zip.getZipError() != 0)
+ {
+ qWarning("Export failed. Cause: zip.close(): %d", zip.getZipError());
+ zip.close();
+ UBApplication::showMessage(tr("Export failed."));
+ QApplication::restoreOverrideCursor();
+ return;
+ }
+
+ zip.close();
+
+ }
+ else
+ {
+ UBApplication::showMessage(tr("Export canceled ..."));
+ QApplication::restoreOverrideCursor();
+ }
+}
+
+void UBDocumentPublisher::rasterizeScenes()
+{
+
+ for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++)
+ {
+ UBApplication::showMessage(tr("Converting page %1/%2 ...").arg(UBDocumentContainer::pageFromSceneIndex(pageIndex)).arg(mPublishingSize), true);
+
+ UBDocumentProxy publishingDocument(mPublishingPath);
+ UBSvgSubsetRasterizer rasterizer(&publishingDocument, pageIndex);
+
+ QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.jpg",pageIndex);
+
+ rasterizer.rasterizeToFile(filename);
+
+ }
+}
+
+
+void UBDocumentPublisher::updateGoogleMapApiKey()
+{
+ QDir widgestDir(mPublishingPath + "/" + UBPersistenceManager::widgetDirectory);
+
+ QString uniboardWebGoogleMapApiKey = UBSettings::settings()->uniboardWebGoogleMapApiKey->get().toString();
+
+ foreach(QFileInfo dirInfo, widgestDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
+ {
+ QString config = UBFileSystemUtils::readTextFile(dirInfo.absoluteFilePath() + "/config.xml").toLower();
+
+ if (config.contains("google") && config.contains("map"))
+ {
+ QDir widgetDir(dirInfo.absoluteFilePath());
+
+ foreach(QFileInfo fileInfo, widgetDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot))
+ {
+ QFile file(fileInfo.absoluteFilePath());
+
+ if (file.open(QIODevice::ReadWrite))
+ {
+ QTextStream stream(&file);
+ QString content = stream.readAll();
+
+ if (content.contains("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og"))
+ {
+ content.replace("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og",
+ uniboardWebGoogleMapApiKey);
+
+ file.resize(0);
+ file.write(content.toUtf8());
+ }
+ file.close();
+ }
+ }
+ }
+ }
+}
+
+
+void UBDocumentPublisher::upgradeDocumentForPublishing()
+{
+ for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++)
+ {
+ UBDocumentProxy publishingDocument(mPublishingPath);
+ UBGraphicsScene *scene = UBSvgSubsetAdaptor::loadScene(&publishingDocument, pageIndex);
+
+ QList widgets;
+
+ foreach(QGraphicsItem* item, scene->items()){
+ UBGraphicsW3CWidgetItem *widgetItem = dynamic_cast(item);
+
+ if(widgetItem){
+ generateWidgetPropertyScript(widgetItem, UBDocumentContainer::pageFromSceneIndex(pageIndex));
+ widgets << widgetItem;
+ }
+ }
+
+ QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.json",pageIndex);
+
+ QFile jsonFile(filename);
+ if (jsonFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
+ {
+ jsonFile.write("{\n");
+ jsonFile.write(QString(" \"scene\": {\n").toUtf8());
+ jsonFile.write(QString(" \"x\": %1,\n").arg(scene->normalizedSceneRect().x()).toUtf8());
+ jsonFile.write(QString(" \"y\": %1,\n").arg(scene->normalizedSceneRect().y()).toUtf8());
+ jsonFile.write(QString(" \"width\": %1,\n").arg(scene->normalizedSceneRect().width()).toUtf8());
+ jsonFile.write(QString(" \"height\": %1\n").arg(scene->normalizedSceneRect().height()).toUtf8());
+ jsonFile.write(QString(" },\n").toUtf8());
+
+ jsonFile.write(QString(" \"widgets\": [\n").toUtf8());
+
+ bool first = true;
+
+ foreach(UBGraphicsW3CWidgetItem* widget, widgets)
+ {
+ if (!first)
+ jsonFile.write(QString(" ,\n").toUtf8());
+
+ jsonFile.write(QString(" {\n").toUtf8());
+ jsonFile.write(QString(" \"uuid\": \"%1\",\n").arg(UBStringUtils::toCanonicalUuid(widget->uuid())).toUtf8());
+ jsonFile.write(QString(" \"id\": \"%1\",\n").arg(widget->metadatas().id).toUtf8());
+
+ jsonFile.write(QString(" \"name\": \"%1\",\n").arg(widget->metadatas().name).toUtf8());
+ jsonFile.write(QString(" \"description\": \"%1\",\n").arg(widget->metadatas().description).toUtf8());
+ jsonFile.write(QString(" \"author\": \"%1\",\n").arg(widget->metadatas().author).toUtf8());
+ jsonFile.write(QString(" \"authorEmail\": \"%1\",\n").arg(widget->metadatas().authorEmail).toUtf8());
+ jsonFile.write(QString(" \"authorHref\": \"%1\",\n").arg(widget->metadatas().authorHref).toUtf8());
+ jsonFile.write(QString(" \"version\": \"%1\",\n").arg(widget->metadatas().authorHref).toUtf8());
+
+ jsonFile.write(QString(" \"x\": %1,\n").arg(widget->sceneBoundingRect().x()).toUtf8());
+ jsonFile.write(QString(" \"y\": %1,\n").arg(widget->sceneBoundingRect().y()).toUtf8());
+ jsonFile.write(QString(" \"width\": %1,\n").arg(widget->sceneBoundingRect().width()).toUtf8());
+ jsonFile.write(QString(" \"height\": %1,\n").arg(widget->sceneBoundingRect().height()).toUtf8());
+
+ jsonFile.write(QString(" \"nominalWidth\": %1,\n").arg(widget->boundingRect().width()).toUtf8());
+ jsonFile.write(QString(" \"nominalHeight\": %1,\n").arg(widget->boundingRect().height()).toUtf8());
+
+ QString url = UBPersistenceManager::widgetDirectory + "/" + widget->uuid().toString() + ".wgt";
+ jsonFile.write(QString(" \"src\": \"%1\",\n").arg(url).toUtf8());
+ QString startFile = widget->mainHtmlFileName();
+ jsonFile.write(QString(" \"startFile\": \"%1\",\n").arg(startFile).toUtf8());
+
+ QMap preferences = widget->UBGraphicsWidgetItem::preferences();
+
+ jsonFile.write(QString(" \"preferences\": {\n").toUtf8());
+
+ foreach(QString key, preferences.keys())
+ {
+ QString sep = ",";
+ if (key == preferences.keys().last())
+ sep = "";
+
+ jsonFile.write(QString(" \"%1\": \"%2\"%3\n")
+ .arg(key)
+ .arg(preferences.value(key))
+ .arg(sep)
+ .toUtf8());
+ }
+ jsonFile.write(QString(" },\n").toUtf8());
+
+ jsonFile.write(QString(" \"datastore\": {\n").toUtf8());
+
+ QMap datastoreEntries = widget->datastoreEntries();
+
+ foreach(QString entry, datastoreEntries.keys())
+ {
+ QString sep = ",";
+ if (entry == datastoreEntries.keys().last())
+ sep = "";
+
+ jsonFile.write(QString(" \"%1\": \"%2\"%3\n")
+ .arg(entry)
+ .arg(datastoreEntries.value(entry))
+ .arg(sep)
+ .toUtf8());
+ }
+ jsonFile.write(QString(" }\n").toUtf8());
+
+ jsonFile.write(QString(" }\n").toUtf8());
+
+ first = false;
+ }
+
+ jsonFile.write(" ]\n");
+ jsonFile.write("}\n");
+ }
+ else
+ {
+ qWarning() << "Cannot open file" << filename << "for saving page state";
+ }
+
+ delete scene;
+ }
+
+ updateGoogleMapApiKey();
+}
+
+
+void UBDocumentPublisher::generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber)
+{
+
+ QMap preferences = widgetItem->UBGraphicsWidgetItem::preferences();
+ QMap datastoreEntries = widgetItem->datastoreEntries();
+
+ QString startFileName = widgetItem->mainHtmlFileName();
+
+ if (!startFileName.startsWith("http://"))
+ {
+ QString startFilePath = mPublishingPath + "/" + UBPersistenceManager::widgetDirectory + "/" + widgetItem->uuid().toString() + ".wgt/" + startFileName;
+
+ QFile startFile(startFilePath);
+
+ if (startFile.exists())
+ {
+ if (startFile.open(QIODevice::ReadWrite))
+ {
+ QTextStream stream(&startFile);
+ QStringList lines;
+
+ bool addedJs = false;
+
+ QString line;
+ do
+ {
+ line = stream.readLine();
+ if (!line.isNull())
+ {
+ lines << line;
+
+ if (!addedJs && line.contains("") ) // TODO UB 4.6, this is naive ... the HEAD tag may be on several lines
+ {
+ lines << "";
+ lines << " ";
+ lines << "";
+
+ addedJs = true;
+ }
+ }
+ }
+ while (!line.isNull());
+
+ startFile.resize(0);
+ startFile.write(lines.join("\n").toUtf8()); // TODO UB 4.x detect real html encoding
+
+ startFile.close();
+ }
+ }
+ }
+ else{
+ qWarning() << "Remote Widget start file, cannot inject widget preferences and datastore entries";
+ }
+}
+
+void UBDocumentPublisher::init()
+{
+ mCrlf=0x0d;
+ mCrlf+=0x0a;
+ mDocInfos.title = "";
+ mDocInfos.description = "";
+
+ mpCookieJar = new QNetworkCookieJar();
+ mpNetworkMgr = new QNetworkAccessManager(this);
+
+ connect(mpNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
+}
+
+void UBDocumentPublisher::onFinished(QNetworkReply *reply)
+{
+ QVariant cookieHeader = reply->rawHeader("Set-Cookie");
+ // First we concatenate all the Set-Cookie values (the packet can contains many of them)
+ QStringList qslCookie = cookieHeader.toString().split("\n");
+ QString qsCookieValue = qslCookie.at(0);
+ for (int i = 1; i < qslCookie.size(); i++) {
+ qsCookieValue += "; " +qslCookie.at(i);
+ }
+
+ // Now we isolate every cookie value
+ QStringList qslCookieVals = qsCookieValue.split("; ");
+
+ bool bTransferOk = false;
+
+ for(int j = 0; j < qslCookieVals.size(); j++)
+ {
+ qDebug() << j;
+ if(qslCookieVals.at(j).startsWith("assetStatus"))
+ {
+ QStringList qslAsset = qslCookieVals.at(j).split("=");
+ if(qslAsset.at(1) == "UPLOADED")
+ {
+ bTransferOk = true;
+ break;
+ }
+ }
+ }
+
+ if(bTransferOk)
+ {
+ UBApplication::showMessage(tr("Document uploaded correctly on the web."));
+ }
+ else
+ {
+ UBApplication::showMessage(tr("Failed to upload document on the web."));
+ }
+
+ reply->deleteLater();
+}
+
+void UBDocumentPublisher::sendUbw(QString username, QString password)
+{
+ if (QFile::exists(mTmpZipFile))
+ {
+ QFile f(mTmpZipFile);
+ if (f.open(QIODevice::ReadOnly))
+ {
+ QFileInfo fi(f);
+ QByteArray ba = f.readAll();
+ QString boundary,data, multipartHeader;
+ QByteArray datatoSend;
+
+ boundary = "---WebKitFormBoundaryDKBTgA53MiyWrzLY";
+ multipartHeader = "multipart/form-data; boundary="+boundary;
+
+ data="--"+boundary+mCrlf;
+ data+="Content-Disposition: form-data; name=\"title\"" + mCrlf + mCrlf + mDocInfos.title + mCrlf;
+ data+="--"+boundary+mCrlf;
+ data+="Content-Disposition: form-data; name=\"description\"" + mCrlf + mCrlf + mDocInfos.description.remove("\n") + mCrlf;
+ data+="--"+boundary+mCrlf;
+ data+="Content-Disposition: form-data; name=\"file\"; filename=\""+ fi.fileName() +"\""+mCrlf;
+ data+="Content-Type: application/octet-stream"+mCrlf+mCrlf;
+ datatoSend=data.toAscii(); // convert data string to byte array for request
+ datatoSend += ba;
+ datatoSend += mCrlf;
+ datatoSend += QString("--%0--%1").arg(boundary).arg(mCrlf);
+
+ QNetworkRequest request(QUrl(QString(DOCPUBLICATION_URL).toAscii().constData()));
+
+ request.setHeader(QNetworkRequest::ContentTypeHeader, multipartHeader);
+ request.setHeader(QNetworkRequest::ContentLengthHeader,datatoSend.size());
+ QString b64Auth = getBase64Of(QString("%0:%1").arg(username).arg(password));
+ request.setRawHeader("Authorization", QString("Basic %0").arg(b64Auth).toAscii().constData());
+ request.setRawHeader("Host", "planete.sankore.org");
+ request.setRawHeader("Accept", "*/*");
+ request.setRawHeader("Accept-Language", "en-US,*");
+
+ mpCookieJar->setCookiesFromUrl(mCookies, QUrl(DOCPUBLICATION_URL));
+ mpNetworkMgr->setCookieJar(mpCookieJar);
+
+ // Send the file
+ mpNetworkMgr->post(request,datatoSend);
+ }
+ }
+}
+
+QString UBDocumentPublisher::getBase64Of(QString stringToEncode)
+{
+ return stringToEncode.toAscii().toBase64();
+}
+
+// ---------------------------------------------------------
+UBProxyLoginDlg::UBProxyLoginDlg(QWidget *parent, const char *name):QDialog(parent)
+ , mpLayout(NULL)
+ , mpUserLayout(NULL)
+ , mpPasswordLayout(NULL)
+ , mpButtons(NULL)
+ , mpUserLabel(NULL)
+ , mpPasswordLabel(NULL)
+ , mpUsername(NULL)
+ , mpPassword(NULL)
+{
+ setObjectName(name);
+ setFixedSize(400, 150);
+ setWindowTitle(tr("Proxy Login"));
+
+ mpLayout = new QVBoxLayout();
+ setLayout(mpLayout);
+ mpUserLayout = new QHBoxLayout();
+ mpLayout->addLayout(mpUserLayout);
+ mpPasswordLayout = new QHBoxLayout();
+ mpLayout->addLayout(mpPasswordLayout);
+
+ mpUserLabel = new QLabel(tr("Username:"), this);
+ mpUsername = new QLineEdit(this);
+ mpUserLayout->addWidget(mpUserLabel, 0);
+ mpUserLayout->addWidget(mpUsername, 1);
+
+ mpPasswordLabel = new QLabel(tr("Password:"), this);
+ mpPassword = new QLineEdit(this);
+ mpPasswordLayout->addWidget(mpPasswordLabel, 0);
+ mpPasswordLayout->addWidget(mpPassword, 1);
+
+ mpButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
+ mpLayout->addWidget(mpButtons);
+
+ connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept()));
+ connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject()));
+
+}
+
+UBProxyLoginDlg::~UBProxyLoginDlg()
+{
+ if(NULL != mpLayout)
+ {
+ delete mpLayout;
+ mpLayout = NULL;
+ }
+ if(NULL != mpButtons)
+ {
+ delete mpButtons;
+ mpButtons = NULL;
+ }
+ if(NULL != mpUserLabel)
+ {
+ delete mpUserLabel;
+ mpUserLabel = NULL;
+ }
+ if(NULL != mpPasswordLabel)
+ {
+ delete mpPasswordLabel;
+ mpPasswordLabel = NULL;
+ }
+ if(NULL != mpUsername)
+ {
+ delete mpUsername;
+ mpUsername = NULL;
+ }
+ if(NULL != mpPassword)
+ {
+ delete mpPassword;
+ mpPassword = NULL;
+ }
+}
+
+// ---------------------------------------------------------
+UBPublicationDlg::UBPublicationDlg(QWidget *parent, const char *name):QDialog(parent)
+ , mpLayout(NULL)
+ , mpTitleLayout(NULL)
+ , mpTitleLabel(NULL)
+ , mpTitle(NULL)
+ , mpDescLabel(NULL)
+ , mpDescription(NULL)
+ , mpButtons(NULL)
+{
+ setObjectName(name);
+ setWindowTitle(tr("Publish document on the web"));
+
+ resize(500, 300);
+
+ mpLayout = new QVBoxLayout();
+ setLayout(mpLayout);
+
+ mpTitleLabel = new QLabel(tr("Title:"), this);
+ mpTitle = new QLineEdit(this);
+ mpTitleLayout = new QHBoxLayout();
+ mpTitleLayout->addWidget(mpTitleLabel, 0);
+ mpTitleLayout->addWidget(mpTitle, 1);
+ mpLayout->addLayout(mpTitleLayout, 0);
+
+ mpDescLabel = new QLabel(tr("Description:"), this);
+ mpLayout->addWidget(mpDescLabel, 0);
+
+ mpDescription = new QTextEdit(this);
+ mpLayout->addWidget(mpDescription, 1);
+
+ mpButtons = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this);
+ mpButtons->button(QDialogButtonBox::Ok)->setText(tr("Publish"));
+ mpLayout->addWidget(mpButtons);
+
+ mpButtons->button(QDialogButtonBox::Ok)->setEnabled(false);
+
+ connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept()));
+ connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject()));
+ connect(mpTitle, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged()));
+ connect(mpDescription, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
+}
+
+UBPublicationDlg::~UBPublicationDlg()
+{
+ if(NULL != mpTitleLabel)
+ {
+ delete mpTitleLabel;
+ mpTitleLabel = NULL;
+ }
+ if(NULL != mpTitle)
+ {
+ delete mpTitle;
+ mpTitle = NULL;
+ }
+ if(NULL != mpDescLabel)
+ {
+ delete mpDescLabel;
+ mpDescLabel = NULL;
+ }
+ if(NULL != mpDescription)
+ {
+ delete mpDescription;
+ mpDescription = NULL;
+ }
+ if(NULL != mpButtons)
+ {
+ delete mpButtons;
+ mpButtons = NULL;
+ }
+ if(NULL != mpTitleLayout)
+ {
+ delete mpTitleLayout;
+ mpTitleLayout = NULL;
+ }
+ if(NULL != mpLayout)
+ {
+ delete mpLayout;
+ mpLayout = NULL;
+ }
+}
+
+void UBPublicationDlg::onTextChanged()
+{
+ bool bPublishButtonState = false;
+ if(mpTitle->text() != "" && mpDescription->document()->toPlainText() != "")
+ {
+ bPublishButtonState = true;
+ }
+ else
+ {
+ bPublishButtonState = false;
+ }
+
+ mpButtons->button(QDialogButtonBox::Ok)->setEnabled(bPublishButtonState);
+}
diff --git a/src/adaptors/publishing/UBDocumentPublisher.h b/src/adaptors/publishing/UBDocumentPublisher.h
index 7f8b2bb5..6b4b5f27 100644
--- a/src/adaptors/publishing/UBDocumentPublisher.h
+++ b/src/adaptors/publishing/UBDocumentPublisher.h
@@ -19,124 +19,124 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBDOCUMENTPUBLISHER_H
-#define UBDOCUMENTPUBLISHER_H
-
-#include
-#include
-
-#include "ui_webPublishing.h"
-
-#define DOCPUBLICATION_URL "http://planete.sankore.org/xwiki/bin/view/CreateResources/UniboardUpload?xpage=plain&outputSyntax=plain"
-
-typedef struct
-{
- QString title;
- QString description;
-} sDocumentInfos;
-
-class UBDocumentProxy;
-class UBServerXMLHttpRequest;
-class UBGraphicsW3CWidgetItem;
-class QWebView;
-
-class UBProxyLoginDlg : public QDialog
-{
- Q_OBJECT
-public:
- UBProxyLoginDlg(QWidget* parent=0, const char* name="ProxyLoginDlg");
- ~UBProxyLoginDlg();
-
- QString username(){return mpUsername->text();}
- QString password(){return mpPassword->text();}
-
-private:
- QVBoxLayout* mpLayout;
- QHBoxLayout* mpUserLayout;
- QHBoxLayout* mpPasswordLayout;
- QDialogButtonBox* mpButtons;
- QLabel* mpUserLabel;
- QLabel* mpPasswordLabel;
- QLineEdit* mpUsername;
- QLineEdit* mpPassword;
-};
-
-class UBPublicationDlg : public QDialog
-{
- Q_OBJECT
-public:
- UBPublicationDlg(QWidget* parent=0, const char* name="UBPublicationDlg");
- ~UBPublicationDlg();
-
- QString title(){return mpTitle->text();}
- QString description(){return mpDescription->document()->toPlainText();}
-
-private slots:
- void onTextChanged();
-
-private:
- QVBoxLayout* mpLayout;
- QHBoxLayout* mpTitleLayout;
- QLabel* mpTitleLabel;
- QLineEdit* mpTitle;
- QLabel* mpDescLabel;
- QTextEdit* mpDescription;
- QDialogButtonBox* mpButtons;
-};
-
-
-class UBDocumentPublisher : public QObject
-{
- Q_OBJECT;
-
-public:
- explicit UBDocumentPublisher(UBDocumentProxy* sourceDocument, QObject *parent = 0);
- virtual ~UBDocumentPublisher();
-
- void publish();
-
-signals:
-
- void loginDone();
-
-protected:
-
- virtual void updateGoogleMapApiKey();
- virtual void rasterizeScenes();
- virtual void upgradeDocumentForPublishing();
- virtual void generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber);
-
-private slots:
-
- void onFinished(QNetworkReply* reply);
-
-private:
-
- UBDocumentProxy *mSourceDocument;
-
- //UBDocumentProxy *mPublishingDocument;
- QString mPublishingPath;
- int mPublishingSize;
-
-
- void init();
- void sendUbw(QString username, QString password);
- QString getBase64Of(QString stringToEncode);
-
- QHBoxLayout* mpLayout;
- QNetworkAccessManager* mpNetworkMgr;
- QNetworkCookieJar* mpCookieJar;
- QString mUsername;
- QString mPassword;
- QString mCrlf;
- bool bLoginCookieSet;
-
- void buildUbwFile();
- QString mTmpZipFile;
- QList mCookies;
- sDocumentInfos mDocInfos;
-
-};
-#endif // UBDOCUMENTPUBLISHER_H
+
+
+#ifndef UBDOCUMENTPUBLISHER_H
+#define UBDOCUMENTPUBLISHER_H
+
+#include
+#include
+
+#include "ui_webPublishing.h"
+
+#define DOCPUBLICATION_URL "http://planete.sankore.org/xwiki/bin/view/CreateResources/UniboardUpload?xpage=plain&outputSyntax=plain"
+
+typedef struct
+{
+ QString title;
+ QString description;
+} sDocumentInfos;
+
+class UBDocumentProxy;
+class UBServerXMLHttpRequest;
+class UBGraphicsW3CWidgetItem;
+class QWebView;
+
+class UBProxyLoginDlg : public QDialog
+{
+ Q_OBJECT
+public:
+ UBProxyLoginDlg(QWidget* parent=0, const char* name="ProxyLoginDlg");
+ ~UBProxyLoginDlg();
+
+ QString username(){return mpUsername->text();}
+ QString password(){return mpPassword->text();}
+
+private:
+ QVBoxLayout* mpLayout;
+ QHBoxLayout* mpUserLayout;
+ QHBoxLayout* mpPasswordLayout;
+ QDialogButtonBox* mpButtons;
+ QLabel* mpUserLabel;
+ QLabel* mpPasswordLabel;
+ QLineEdit* mpUsername;
+ QLineEdit* mpPassword;
+};
+
+class UBPublicationDlg : public QDialog
+{
+ Q_OBJECT
+public:
+ UBPublicationDlg(QWidget* parent=0, const char* name="UBPublicationDlg");
+ ~UBPublicationDlg();
+
+ QString title(){return mpTitle->text();}
+ QString description(){return mpDescription->document()->toPlainText();}
+
+private slots:
+ void onTextChanged();
+
+private:
+ QVBoxLayout* mpLayout;
+ QHBoxLayout* mpTitleLayout;
+ QLabel* mpTitleLabel;
+ QLineEdit* mpTitle;
+ QLabel* mpDescLabel;
+ QTextEdit* mpDescription;
+ QDialogButtonBox* mpButtons;
+};
+
+
+class UBDocumentPublisher : public QObject
+{
+ Q_OBJECT;
+
+public:
+ explicit UBDocumentPublisher(UBDocumentProxy* sourceDocument, QObject *parent = 0);
+ virtual ~UBDocumentPublisher();
+
+ void publish();
+
+signals:
+
+ void loginDone();
+
+protected:
+
+ virtual void updateGoogleMapApiKey();
+ virtual void rasterizeScenes();
+ virtual void upgradeDocumentForPublishing();
+ virtual void generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber);
+
+private slots:
+
+ void onFinished(QNetworkReply* reply);
+
+private:
+
+ UBDocumentProxy *mSourceDocument;
+
+ //UBDocumentProxy *mPublishingDocument;
+ QString mPublishingPath;
+ int mPublishingSize;
+
+
+ void init();
+ void sendUbw(QString username, QString password);
+ QString getBase64Of(QString stringToEncode);
+
+ QHBoxLayout* mpLayout;
+ QNetworkAccessManager* mpNetworkMgr;
+ QNetworkCookieJar* mpCookieJar;
+ QString mUsername;
+ QString mPassword;
+ QString mCrlf;
+ bool bLoginCookieSet;
+
+ void buildUbwFile();
+ QString mTmpZipFile;
+ QList mCookies;
+ sDocumentInfos mDocInfos;
+
+};
+#endif // UBDOCUMENTPUBLISHER_H
diff --git a/src/board/UBBoardController.cpp b/src/board/UBBoardController.cpp
index 73f70795..7d5a42e3 100644
--- a/src/board/UBBoardController.cpp
+++ b/src/board/UBBoardController.cpp
@@ -19,2499 +19,2499 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include "UBBoardController.h"
-
-#include
-#include
-
-#include "frameworks/UBFileSystemUtils.h"
-#include "frameworks/UBPlatformUtils.h"
-
-#include "core/UBApplication.h"
-#include "core/UBSettings.h"
-#include "core/UBSetting.h"
-#include "core/UBPersistenceManager.h"
-#include "core/UBApplicationController.h"
-#include "core/UBDocumentManager.h"
-#include "core/UBMimeData.h"
-#include "core/UBDownloadManager.h"
-
-#include "network/UBHttpGet.h"
-
-#include "gui/UBMessageWindow.h"
-#include "gui/UBResources.h"
-#include "gui/UBToolbarButtonGroup.h"
-#include "gui/UBMainWindow.h"
-#include "gui/UBToolWidget.h"
-#include "gui/UBKeyboardPalette.h"
-#include "gui/UBMagnifer.h"
-#include "gui/UBDockPaletteWidget.h"
-#include "gui/UBDockTeacherGuideWidget.h"
-#include "gui/UBTeacherGuideWidget.h"
-
-#include "domain/UBGraphicsPixmapItem.h"
-#include "domain/UBGraphicsItemUndoCommand.h"
-#include "domain/UBGraphicsProxyWidget.h"
-#include "domain/UBGraphicsSvgItem.h"
-#include "domain/UBGraphicsWidgetItem.h"
-#include "domain/UBGraphicsMediaItem.h"
-#include "domain/UBGraphicsPDFItem.h"
-#include "domain/UBGraphicsTextItem.h"
-#include "domain/UBPageSizeUndoCommand.h"
-#include "domain/UBGraphicsGroupContainerItem.h"
-#include "domain/UBItem.h"
-#include "board/UBFeaturesController.h"
-#include "domain/UBGraphicsStrokesGroup.h"
-
-#include "gui/UBFeaturesWidget.h"
-
-#include "tools/UBToolsManager.h"
-
-#include "document/UBDocumentProxy.h"
-#include "document/UBDocumentController.h"
-
-#include "board/UBDrawingController.h"
-#include "board/UBBoardView.h"
-
-#include "podcast/UBPodcastController.h"
-
-#include "adaptors/UBMetadataDcSubsetAdaptor.h"
-#include "adaptors/UBSvgSubsetAdaptor.h"
-
-#include "UBBoardPaletteManager.h"
-
-#include "core/UBSettings.h"
-
-#include "core/memcheck.h"
-
-UBBoardController::UBBoardController(UBMainWindow* mainWindow)
- : UBDocumentContainer(mainWindow->centralWidget())
- , mMainWindow(mainWindow)
- , mActiveScene(0)
- , mActiveSceneIndex(-1)
- , mPaletteManager(0)
- , mSoftwareUpdateDialog(0)
- , mMessageWindow(0)
- , mControlView(0)
- , mDisplayView(0)
- , mControlContainer(0)
- , mControlLayout(0)
- , mZoomFactor(1.0)
- , mIsClosing(false)
- , mSystemScaleFactor(1.0)
- , mCleanupDone(false)
- , mCacheWidgetIsEnabled(false)
- , mDeletingSceneIndex(-1)
- , mMovingSceneIndex(-1)
- , mActionGroupText(tr("Group"))
- , mActionUngroupText(tr("Ungroup"))
-{
- mZoomFactor = UBSettings::settings()->boardZoomFactor->get().toDouble();
-
- int penColorIndex = UBSettings::settings()->penColorIndex();
- int markerColorIndex = UBSettings::settings()->markerColorIndex();
-
- mPenColorOnDarkBackground = UBSettings::settings()->penColors(true).at(penColorIndex);
- mPenColorOnLightBackground = UBSettings::settings()->penColors(false).at(penColorIndex);
- mMarkerColorOnDarkBackground = UBSettings::settings()->markerColors(true).at(markerColorIndex);
- mMarkerColorOnLightBackground = UBSettings::settings()->markerColors(false).at(markerColorIndex);
-
- QDesktopWidget* desktop = UBApplication::desktop();
- int dpiCommon = (desktop->physicalDpiX() + desktop->physicalDpiY()) / 2;
- int sPixelsPerMillimeter = qRound(dpiCommon / UBGeometryUtils::inchSize);
- UBSettings::settings()->crossSize = 10*sPixelsPerMillimeter;
-}
-
-
-void UBBoardController::init()
-{
- setupViews();
- setupToolbar();
-
- connect(UBApplication::undoStack, SIGNAL(canUndoChanged(bool))
- , this, SLOT(undoRedoStateChange(bool)));
-
- connect(UBApplication::undoStack, SIGNAL(canRedoChanged (bool))
- , this, SLOT(undoRedoStateChange(bool)));
-
- connect(UBDrawingController::drawingController(), SIGNAL(stylusToolChanged(int))
- , this, SLOT(setToolCursor(int)));
-
- connect(UBDrawingController::drawingController(), SIGNAL(stylusToolChanged(int))
- , this, SLOT(stylusToolChanged(int)));
-
- connect(UBApplication::app(), SIGNAL(lastWindowClosed())
- , this, SLOT(lastWindowClosed()));
-
- connect(UBDownloadManager::downloadManager(), SIGNAL(downloadModalFinished()), this, SLOT(onDownloadModalFinished()));
- connect(UBDownloadManager::downloadManager(), SIGNAL(addDownloadedFileToBoard(bool,QUrl,QUrl,QString,QByteArray,QPointF,QSize,bool)), this, SLOT(downloadFinished(bool,QUrl,QUrl,QString,QByteArray,QPointF,QSize,bool)));
-
- UBDocumentProxy* doc = UBPersistenceManager::persistenceManager()->createDocument();
-
- setActiveDocumentScene(doc);
-
- connect(UBApplication::mainWindow->actionGroupItems, SIGNAL(triggered()), this, SLOT(groupButtonClicked()));
-
- undoRedoStateChange(true);
-}
-
-
-UBBoardController::~UBBoardController()
-{
- delete mDisplayView;
-}
-
-
-int UBBoardController::currentPage()
-{
- if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool())
- return mActiveSceneIndex;
- return mActiveSceneIndex + 1;
-}
-
-void UBBoardController::setupViews()
-{
- mControlContainer = new QWidget(mMainWindow->centralWidget());
-
- mControlLayout = new QHBoxLayout(mControlContainer);
- mControlLayout->setContentsMargins(0, 0, 0, 0);
-
- mControlView = new UBBoardView(this, mControlContainer, true, false);
- mControlView->setInteractive(true);
- mControlView->setMouseTracking(true);
-
- mControlView->grabGesture(Qt::SwipeGesture);
-
- mControlView->setTransformationAnchor(QGraphicsView::NoAnchor);
-
- mControlLayout->addWidget(mControlView);
- mControlContainer->setObjectName("ubBoardControlContainer");
- mMainWindow->addBoardWidget(mControlContainer);
-
- connect(mControlView, SIGNAL(resized(QResizeEvent*)), this, SLOT(boardViewResized(QResizeEvent*)));
-
- // TODO UB 4.x Optimization do we have to create the display view even if their is
- // only 1 screen
- //
- mDisplayView = new UBBoardView(this, UBItemLayerType::FixedBackground, UBItemLayerType::Tool, 0);
- mDisplayView->setInteractive(false);
- mDisplayView->setTransformationAnchor(QGraphicsView::NoAnchor);
-
- mMessageWindow = new UBMessageWindow(mControlView);
- mMessageWindow->hide();
-
- mPaletteManager = new UBBoardPaletteManager(mControlContainer, this);
- connect(this, SIGNAL(activeSceneChanged()), mPaletteManager, SLOT(activeSceneChanged()));
-
-}
-
-
-void UBBoardController::setupLayout()
-{
- if(mPaletteManager)
- mPaletteManager->setupLayout();
-}
-
-
-void UBBoardController::setBoxing(QRect displayRect)
-{
- if (displayRect.isNull())
- {
- mControlLayout->setContentsMargins(0, 0, 0, 0);
- return;
- }
-
- qreal controlWidth = (qreal)mMainWindow->centralWidget()->width();
- qreal controlHeight = (qreal)mMainWindow->centralWidget()->height();
- qreal displayWidth = (qreal)displayRect.width();
- qreal displayHeight = (qreal)displayRect.height();
-
- qreal displayRatio = displayWidth / displayHeight;
- qreal controlRatio = controlWidth / controlHeight;
-
- if (displayRatio < controlRatio)
- {
- // Pillarboxing
- int boxWidth = (controlWidth - (displayWidth * (controlHeight / displayHeight))) / 2;
- mControlLayout->setContentsMargins(boxWidth, 0, boxWidth, 0);
- }
- else if (displayRatio > controlRatio)
- {
- // Letterboxing
- int boxHeight = (controlHeight - (displayHeight * (controlWidth / displayWidth))) / 2;
- mControlLayout->setContentsMargins(0, boxHeight, 0, boxHeight);
- }
- else
- {
- // No boxing
- mControlLayout->setContentsMargins(0, 0, 0, 0);
- }
-}
-
-
-QSize UBBoardController::displayViewport()
-{
- return mDisplayView->geometry().size();
-}
-
-
-QSize UBBoardController::controlViewport()
-{
- return mControlView->geometry().size();
-}
-
-
-QRectF UBBoardController::controlGeometry()
-{
- return mControlView->geometry();
-}
-
-
-void UBBoardController::setupToolbar()
-{
- UBSettings *settings = UBSettings::settings();
-
- // Setup color choice widget
- QList colorActions;
- colorActions.append(mMainWindow->actionColor0);
- colorActions.append(mMainWindow->actionColor1);
- colorActions.append(mMainWindow->actionColor2);
- colorActions.append(mMainWindow->actionColor3);
-
- UBToolbarButtonGroup *colorChoice =
- new UBToolbarButtonGroup(mMainWindow->boardToolBar, colorActions);
-
- mMainWindow->boardToolBar->insertWidget(mMainWindow->actionBackgrounds, colorChoice);
-
- connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), colorChoice, SLOT(displayText(QVariant)));
- connect(colorChoice, SIGNAL(activated(int)), this, SLOT(setColorIndex(int)));
- connect(UBDrawingController::drawingController(), SIGNAL(colorIndexChanged(int)), colorChoice, SLOT(setCurrentIndex(int)));
- connect(UBDrawingController::drawingController(), SIGNAL(colorPaletteChanged()), colorChoice, SLOT(colorPaletteChanged()));
- connect(UBDrawingController::drawingController(), SIGNAL(colorPaletteChanged()), this, SLOT(colorPaletteChanged()));
-
- colorChoice->displayText(QVariant(settings->appToolBarDisplayText->get().toBool()));
- colorChoice->colorPaletteChanged();
-
- // Setup line width choice widget
- QList lineWidthActions;
- lineWidthActions.append(mMainWindow->actionLineSmall);
- lineWidthActions.append(mMainWindow->actionLineMedium);
- lineWidthActions.append(mMainWindow->actionLineLarge);
-
- UBToolbarButtonGroup *lineWidthChoice =
- new UBToolbarButtonGroup(mMainWindow->boardToolBar, lineWidthActions);
-
- connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), lineWidthChoice, SLOT(displayText(QVariant)));
-
- connect(lineWidthChoice, SIGNAL(activated(int))
- , UBDrawingController::drawingController(), SLOT(setLineWidthIndex(int)));
-
- connect(UBDrawingController::drawingController(), SIGNAL(lineWidthIndexChanged(int))
- , lineWidthChoice, SLOT(setCurrentIndex(int)));
-
- lineWidthChoice->displayText(QVariant(settings->appToolBarDisplayText->get().toBool()));
-
- mMainWindow->boardToolBar->insertWidget(mMainWindow->actionBackgrounds, lineWidthChoice);
-
- //-----------------------------------------------------------//
- // Setup eraser width choice widget
-
- QList eraserWidthActions;
- eraserWidthActions.append(mMainWindow->actionEraserSmall);
- eraserWidthActions.append(mMainWindow->actionEraserMedium);
- eraserWidthActions.append(mMainWindow->actionEraserLarge);
-
- UBToolbarButtonGroup *eraserWidthChoice =
- new UBToolbarButtonGroup(mMainWindow->boardToolBar, eraserWidthActions);
-
- mMainWindow->boardToolBar->insertWidget(mMainWindow->actionBackgrounds, eraserWidthChoice);
-
- connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), eraserWidthChoice, SLOT(displayText(QVariant)));
- connect(eraserWidthChoice, SIGNAL(activated(int)), UBDrawingController::drawingController(), SLOT(setEraserWidthIndex(int)));
-
- eraserWidthChoice->displayText(QVariant(settings->appToolBarDisplayText->get().toBool()));
- eraserWidthChoice->setCurrentIndex(settings->eraserWidthIndex());
-
- mMainWindow->boardToolBar->insertSeparator(mMainWindow->actionBackgrounds);
-
- //-----------------------------------------------------------//
-
- UBApplication::app()->insertSpaceToToolbarBeforeAction(mMainWindow->boardToolBar, mMainWindow->actionBoard);
- UBApplication::app()->insertSpaceToToolbarBeforeAction(mMainWindow->tutorialToolBar, mMainWindow->actionBoard);
-
- UBApplication::app()->decorateActionMenu(mMainWindow->actionMenu);
-
- mMainWindow->actionBoard->setVisible(false);
-
- mMainWindow->webToolBar->hide();
- mMainWindow->documentToolBar->hide();
- mMainWindow->tutorialToolBar->hide();
-
- connectToolbar();
- initToolbarTexts();
-}
-
-
-void UBBoardController::setToolCursor(int tool)
-{
- if (mActiveScene)
- {
- mActiveScene->setToolCursor(tool);
- }
-
- mControlView->setToolCursor(tool);
-}
-
-
-void UBBoardController::connectToolbar()
-{
- connect(mMainWindow->actionAdd, SIGNAL(triggered()), this, SLOT(addItem()));
- connect(mMainWindow->actionNewPage, SIGNAL(triggered()), this, SLOT(addScene()));
- connect(mMainWindow->actionDuplicatePage, SIGNAL(triggered()), this, SLOT(duplicateScene()));
-
- connect(mMainWindow->actionClearPage, SIGNAL(triggered()), this, SLOT(clearScene()));
- connect(mMainWindow->actionEraseItems, SIGNAL(triggered()), this, SLOT(clearSceneItems()));
- connect(mMainWindow->actionEraseAnnotations, SIGNAL(triggered()), this, SLOT(clearSceneAnnotation()));
- connect(mMainWindow->actionEraseBackground,SIGNAL(triggered()),this,SLOT(clearSceneBackground()));
-
- connect(mMainWindow->actionUndo, SIGNAL(triggered()), UBApplication::undoStack, SLOT(undo()));
- connect(mMainWindow->actionRedo, SIGNAL(triggered()), UBApplication::undoStack, SLOT(redo()));
- connect(mMainWindow->actionRedo, SIGNAL(triggered()), this, SLOT(startScript()));
- connect(mMainWindow->actionBack, SIGNAL( triggered()), this, SLOT(previousScene()));
- connect(mMainWindow->actionForward, SIGNAL(triggered()), this, SLOT(nextScene()));
- connect(mMainWindow->actionSleep, SIGNAL(triggered()), this, SLOT(stopScript()));
- connect(mMainWindow->actionSleep, SIGNAL(triggered()), this, SLOT(blackout()));
- connect(mMainWindow->actionVirtualKeyboard, SIGNAL(triggered(bool)), this, SLOT(showKeyboard(bool)));
- connect(mMainWindow->actionImportPage, SIGNAL(triggered()), this, SLOT(importPage()));
-}
-
-void UBBoardController::startScript()
-{
- freezeW3CWidgets(false);
-}
-
-void UBBoardController::stopScript()
-{
- freezeW3CWidgets(true);
-}
-
-void UBBoardController::initToolbarTexts()
-{
- QList allToolbarActions;
-
- allToolbarActions << mMainWindow->boardToolBar->actions();
- allToolbarActions << mMainWindow->webToolBar->actions();
- allToolbarActions << mMainWindow->documentToolBar->actions();
-
- foreach(QAction* action, allToolbarActions)
- {
- QString nominalText = action->text();
- QString shortText = truncate(nominalText, 48);
- QPair texts(nominalText, shortText);
-
- mActionTexts.insert(action, texts);
- }
-}
-
-
-void UBBoardController::setToolbarTexts()
-{
- bool highResolution = mMainWindow->width() > 1024;
- QSize iconSize;
-
- if (highResolution)
- iconSize = QSize(48, 32);
- else
- iconSize = QSize(32, 32);
-
- mMainWindow->boardToolBar->setIconSize(iconSize);
- mMainWindow->webToolBar->setIconSize(iconSize);
- mMainWindow->documentToolBar->setIconSize(iconSize);
-
- foreach(QAction* action, mActionTexts.keys())
- {
- QPair texts = mActionTexts.value(action);
-
- if (highResolution)
- action->setText(texts.first);
- else
- {
- action->setText(texts.second);
- }
-
- action->setToolTip(texts.first);
- }
-}
-
-
-QString UBBoardController::truncate(QString text, int maxWidth)
-{
- QFontMetricsF fontMetrics(mMainWindow->font());
- return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
-}
-
-
-void UBBoardController::stylusToolDoubleClicked(int tool)
-{
- if (tool == UBStylusTool::ZoomIn || tool == UBStylusTool::ZoomOut)
- {
- zoomRestore();
- }
- else if (tool == UBStylusTool::Hand)
- {
- centerRestore();
- }
-}
-
-
-
-void UBBoardController::addScene()
-{
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
-
- UBDocumentContainer::addPage(mActiveSceneIndex + 1);
-
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- setActiveDocumentScene(mActiveSceneIndex + 1);
- QApplication::restoreOverrideCursor();
-}
-
-void UBBoardController::addScene(UBGraphicsScene* scene, bool replaceActiveIfEmpty)
-{
- if (scene)
- {
- UBGraphicsScene* clone = scene->sceneDeepCopy();
-
- if (scene->document() && (scene->document() != selectedDocument()))
- {
- foreach(QUrl relativeFile, scene->relativeDependencies())
- {
- QString source = scene->document()->persistencePath() + "/" + relativeFile.toString();
- QString target = selectedDocument()->persistencePath() + "/" + relativeFile.toString();
-
- QFileInfo fi(target);
- QDir d = fi.dir();
-
- d.mkpath(d.absolutePath());
- QFile::copy(source, target);
- }
- }
-
- if (replaceActiveIfEmpty && mActiveScene->isEmpty())
- {
- setActiveDocumentScene(mActiveSceneIndex);
- }
- else
- {
- persistCurrentScene();
- UBPersistenceManager::persistenceManager()->insertDocumentSceneAt(selectedDocument(), clone, mActiveSceneIndex + 1);
- setActiveDocumentScene(mActiveSceneIndex + 1);
- }
-
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
- }
-}
-
-
-void UBBoardController::addScene(UBDocumentProxy* proxy, int sceneIndex, bool replaceActiveIfEmpty)
-{
- UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(proxy, sceneIndex);
-
- if (scene)
- {
- addScene(scene, replaceActiveIfEmpty);
- }
-}
-
-void UBBoardController::duplicateScene(int nIndex)
-{
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
-
- QList scIndexes;
- scIndexes << nIndex;
- duplicatePages(scIndexes);
- insertThumbPage(nIndex);
- emit documentThumbnailsUpdated(this);
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- setActiveDocumentScene(nIndex + 1);
- QApplication::restoreOverrideCursor();
-
- emit pageChanged();
-}
-
-void UBBoardController::duplicateScene()
-{
- if (UBApplication::applicationController->displayMode() != UBApplicationController::Board)
- return;
- duplicateScene(mActiveSceneIndex);
-}
-
-UBGraphicsItem *UBBoardController::duplicateItem(UBItem *item, bool bAsync)
-{
- if (!item)
- return NULL;
-
- UBGraphicsItem *retItem = NULL;
-
- mLastCreatedItem = NULL;
-
- QUrl sourceUrl;
- QByteArray pData;
-
- //common parameters for any item
- QPointF itemPos;
- QSizeF itemSize;
-
- QGraphicsItem *commonItem = dynamic_cast(item);
- if (commonItem)
- {
- qreal shifting = UBSettings::settings()->objectFrameWidth;
- itemPos = commonItem->pos() + QPointF(shifting,shifting);
- itemSize = commonItem->boundingRect().size();
- commonItem->setSelected(false);
- }
-
- UBMimeType::Enum itemMimeType;
-
- QString srcFile = item->sourceUrl().toLocalFile();
- if (srcFile.isEmpty())
- srcFile = item->sourceUrl().toString();
-
- QString contentTypeHeader;
- if (!srcFile.isEmpty())
- contentTypeHeader = UBFileSystemUtils::mimeTypeFromFileName(srcFile);
-
- if(NULL != qgraphicsitem_cast(commonItem))
- itemMimeType = UBMimeType::Group;
- else
- itemMimeType = UBFileSystemUtils::mimeTypeFromString(contentTypeHeader);
-
- switch(static_cast(itemMimeType))
- {
- case UBMimeType::AppleWidget:
- case UBMimeType::W3CWidget:
- {
- UBGraphicsWidgetItem *witem = dynamic_cast(item);
- if (witem)
- {
- sourceUrl = witem->getOwnFolder();
- }
- }break;
-
- case UBMimeType::Video:
- case UBMimeType::Audio:
- {
- UBGraphicsMediaItem *mitem = dynamic_cast(item);
- if (mitem)
- {
- sourceUrl = mitem->mediaFileUrl();
- if (bAsync)
- {
- downloadURL(sourceUrl, srcFile, itemPos, QSize(itemSize.width(), itemSize.height()), false, false);
- return NULL; // async operation
- }
- }
- }break;
-
- case UBMimeType::VectorImage:
- {
- UBGraphicsSvgItem *viitem = dynamic_cast(item);
- if (viitem)
- {
- pData = viitem->fileData();
- sourceUrl = item->sourceUrl();
- }
- }break;
-
- case UBMimeType::RasterImage:
- {
- UBGraphicsPixmapItem *pixitem = dynamic_cast(item);
- if (pixitem)
- {
- QBuffer buffer(&pData);
- buffer.open(QIODevice::WriteOnly);
- QString format = UBFileSystemUtils::extension(item->sourceUrl().toLocalFile());
- pixitem->pixmap().save(&buffer, format.toLatin1());
- }
- }break;
-
- case UBMimeType::Group:
- {
- UBGraphicsGroupContainerItem* groupItem = dynamic_cast(item);
- UBGraphicsGroupContainerItem* duplicatedGroup = NULL;
-
- QList duplicatedItems;
- QList children = groupItem->childItems();
-
- mActiveScene->setURStackEnable(false);
- foreach(QGraphicsItem* pIt, children){
- UBItem* pItem = dynamic_cast(pIt);
- if(pItem){ // we diong sync duplication of all childs.
- QGraphicsItem * itemToGroup = dynamic_cast(duplicateItem(pItem, false));
- if (itemToGroup)
- duplicatedItems.append(itemToGroup);
- }
- }
- duplicatedGroup = mActiveScene->createGroup(duplicatedItems);
- duplicatedGroup->setTransform(groupItem->transform());
- groupItem->setSelected(false);
-
- retItem = dynamic_cast(duplicatedGroup);
-
- QGraphicsItem * itemToAdd = dynamic_cast(retItem);
- if (itemToAdd)
- {
- mActiveScene->addItem(itemToAdd);
- itemToAdd->setSelected(true);
- }
- mActiveScene->setURStackEnable(true);
- }break;
-
- case UBMimeType::UNKNOWN:
- {
- QGraphicsItem *gitem = dynamic_cast(item->deepCopy());
- if (gitem)
- {
- mActiveScene->addItem(gitem);
- gitem->setPos(itemPos);
- mLastCreatedItem = gitem;
- gitem->setSelected(true);
- }
- retItem = dynamic_cast(gitem);
- }break;
- }
-
- if (retItem)
- {
- QGraphicsItem *graphicsRetItem = dynamic_cast(retItem);
- if (mActiveScene->isURStackIsEnabled()) { //should be deleted after scene own undo stack implemented
- UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(mActiveScene, 0, graphicsRetItem);
- UBApplication::undoStack->push(uc);
- }
- return retItem;
- }
-
- UBItem *createdItem = downloadFinished(true, sourceUrl, srcFile, contentTypeHeader, pData, itemPos, QSize(itemSize.width(), itemSize.height()), false);
- if (createdItem)
- {
- createdItem->setSourceUrl(item->sourceUrl());
- item->copyItemParameters(createdItem);
-
- QGraphicsItem *createdGitem = dynamic_cast(createdItem);
- if (createdGitem)
- createdGitem->setPos(itemPos);
- mLastCreatedItem = dynamic_cast(createdItem);
- mLastCreatedItem->setSelected(true);
-
- retItem = dynamic_cast(createdItem);
- }
-
- return retItem;
-}
-
-void UBBoardController::deleteScene(int nIndex)
-{
- if (selectedDocument()->pageCount()>=2)
- {
- mDeletingSceneIndex = nIndex;
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
- showMessage(tr("Delete page %1 from document").arg(nIndex), true);
-
- QList scIndexes;
- scIndexes << nIndex;
- deletePages(scIndexes);
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- if (nIndex >= pageCount())
- nIndex = pageCount()-1;
- setActiveDocumentScene(nIndex);
- showMessage(tr("Page %1 deleted").arg(nIndex));
- QApplication::restoreOverrideCursor();
- mDeletingSceneIndex = -1;
- }
-}
-
-
-void UBBoardController::clearScene()
-{
- if (mActiveScene)
- {
- freezeW3CWidgets(true);
- mActiveScene->clearContent(UBGraphicsScene::clearItemsAndAnnotations);
- updateActionStates();
- }
-}
-
-
-void UBBoardController::clearSceneItems()
-{
- if (mActiveScene)
- {
- freezeW3CWidgets(true);
- mActiveScene->clearContent(UBGraphicsScene::clearItems);
- updateActionStates();
- }
-}
-
-
-void UBBoardController::clearSceneAnnotation()
-{
- if (mActiveScene)
- {
- mActiveScene->clearContent(UBGraphicsScene::clearAnnotations);
- updateActionStates();
- }
-}
-
-void UBBoardController::clearSceneBackground()
-{
- if (mActiveScene)
- {
- mActiveScene->clearContent(UBGraphicsScene::clearBackground);
- updateActionStates();
- }
-}
-
-void UBBoardController::showDocumentsDialog()
-{
- if (selectedDocument())
- persistCurrentScene();
-
- UBApplication::mainWindow->actionLibrary->setChecked(false);
-
-}
-
-void UBBoardController::libraryDialogClosed(int ret)
-{
- Q_UNUSED(ret);
-
- mMainWindow->actionLibrary->setChecked(false);
-}
-
-
-void UBBoardController::blackout()
-{
- UBApplication::applicationController->blackout();
-}
-
-
-void UBBoardController::showKeyboard(bool show)
-{
- if(show)
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- mPaletteManager->showVirtualKeyboard(show);
-}
-
-
-void UBBoardController::zoomIn(QPointF scenePoint)
-{
- if (mControlView->transform().m11() > UB_MAX_ZOOM)
- {
- qApp->beep();
- return;
- }
- zoom(mZoomFactor, scenePoint);
-}
-
-
-void UBBoardController::zoomOut(QPointF scenePoint)
-{
- if ((mControlView->horizontalScrollBar()->maximum() == 0) && (mControlView->verticalScrollBar()->maximum() == 0))
- {
- // Do not zoom out if we reached the maximum
- qApp->beep();
- return;
- }
-
- qreal newZoomFactor = 1 / mZoomFactor;
-
- zoom(newZoomFactor, scenePoint);
-}
-
-
-void UBBoardController::zoomRestore()
-{
- QTransform tr;
-
- tr.scale(mSystemScaleFactor, mSystemScaleFactor);
- mControlView->setTransform(tr);
-
- centerRestore();
-
- foreach(QGraphicsItem *gi, mActiveScene->selectedItems ())
- {
- //force item to redraw the frame (for the anti scale calculation)
- gi->setSelected(false);
- gi->setSelected(true);
- }
-
- emit zoomChanged(1.0);
-}
-
-
-void UBBoardController::centerRestore()
-{
- centerOn(QPointF(0,0));
-}
-
-
-void UBBoardController::centerOn(QPointF scenePoint)
-{
- mControlView->centerOn(scenePoint);
- UBApplication::applicationController->adjustDisplayView();
-}
-
-
-void UBBoardController::zoom(const qreal ratio, QPointF scenePoint)
-{
-
- QPointF viewCenter = mControlView->mapToScene(QRect(0, 0, mControlView->width(), mControlView->height()).center());
- QPointF offset = scenePoint - viewCenter;
- QPointF scalledOffset = offset / ratio;
-
- qreal currentZoom = ratio * mControlView->viewportTransform().m11() / mSystemScaleFactor;
-
- qreal usedRatio = ratio;
- if (currentZoom > UB_MAX_ZOOM)
- {
- currentZoom = UB_MAX_ZOOM;
- usedRatio = currentZoom * mSystemScaleFactor / mControlView->viewportTransform().m11();
- }
-
- mControlView->scale(usedRatio, usedRatio);
-
- QPointF newCenter = scenePoint - scalledOffset;
-
- mControlView->centerOn(newCenter);
-
- emit zoomChanged(currentZoom);
- UBApplication::applicationController->adjustDisplayView();
-
- emit controlViewportChanged();
- mActiveScene->setBackgroundZoomFactor(mControlView->transform().m11());
-}
-
-
-void UBBoardController::handScroll(qreal dx, qreal dy)
-{
- mControlView->translate(dx, dy);
-
- UBApplication::applicationController->adjustDisplayView();
-
- emit controlViewportChanged();
-}
-
-
-void UBBoardController::previousScene()
-{
- if (mActiveSceneIndex > 0)
- {
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
- setActiveDocumentScene(mActiveSceneIndex - 1);
- QApplication::restoreOverrideCursor();
- }
-
- updateActionStates();
- emit pageChanged();
-}
-
-
-void UBBoardController::nextScene()
-{
- if (mActiveSceneIndex < selectedDocument()->pageCount() - 1)
- {
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
- setActiveDocumentScene(mActiveSceneIndex + 1);
- QApplication::restoreOverrideCursor();
- }
-
- updateActionStates();
- emit pageChanged();
-}
-
-
-void UBBoardController::firstScene()
-{
- if (mActiveSceneIndex > 0)
- {
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
- setActiveDocumentScene(0);
- QApplication::restoreOverrideCursor();
- }
-
- updateActionStates();
- emit pageChanged();
-}
-
-
-void UBBoardController::lastScene()
-{
- if (mActiveSceneIndex < selectedDocument()->pageCount() - 1)
- {
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- persistCurrentScene();
- setActiveDocumentScene(selectedDocument()->pageCount() - 1);
- QApplication::restoreOverrideCursor();
- }
-
- updateActionStates();
- emit pageChanged();
-}
-
-void UBBoardController::groupButtonClicked()
-{
- QAction *groupAction = UBApplication::mainWindow->actionGroupItems;
- QList selItems = activeScene()->selectedItems();
- if (!selItems.count()) {
- qDebug() << "Got grouping request when there is no any selected item on the scene";
- return;
- }
-
- if (groupAction->text() == mActionGroupText) { //The only way to get information from item, considering using smth else
- UBGraphicsGroupContainerItem *groupItem = activeScene()->createGroup(selItems);
- groupItem->setSelected(true);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
-
- }
- else if (groupAction->text() == mActionUngroupText) {
- //Considering one selected item and it's a group
- if (selItems.count() > 1)
- {
- qDebug() << "can't make sense of ungrouping more then one item. Grouping action should be performed for that purpose";
- return;
- }
- UBGraphicsGroupContainerItem *currentGroup = dynamic_cast(selItems.first());
- if (currentGroup) {
- currentGroup->destroy();
- }
- }
-}
-
-void UBBoardController::downloadURL(const QUrl& url, QString contentSourceUrl, const QPointF& pPos, const QSize& pSize, bool isBackground, bool internalData)
-{
- qDebug() << "something has been dropped on the board! Url is: " << url.toString();
- QString sUrl = url.toString();
-
- QGraphicsItem *oldBackgroundObject = NULL;
- if (isBackground)
- oldBackgroundObject = mActiveScene->backgroundObject();
-
- if(sUrl.startsWith("uniboardTool://"))
- {
- downloadFinished(true, url, QUrl(), "application/vnd.mnemis-uniboard-tool", QByteArray(), pPos, pSize, isBackground);
- }
- else if (sUrl.startsWith("file://") || sUrl.startsWith("/"))
- {
- QUrl formedUrl = sUrl.startsWith("file://") ? url : QUrl::fromLocalFile(sUrl);
- QString fileName = formedUrl.toLocalFile();
- QString contentType = UBFileSystemUtils::mimeTypeFromFileName(fileName);
-
- bool shouldLoadFileData =
- contentType.startsWith("image")
- || contentType.startsWith("application/widget")
- || contentType.startsWith("application/vnd.apple-widget");
-
- if (shouldLoadFileData)
- {
- QFile file(fileName);
- file.open(QIODevice::ReadOnly);
- downloadFinished(true, formedUrl, QUrl(), contentType, file.readAll(), pPos, pSize, isBackground, internalData);
- file.close();
- }
- else
- {
- // media items should be copyed in separate thread
-
- sDownloadFileDesc desc;
- desc.modal = false;
- desc.srcUrl = sUrl;
- desc.originalSrcUrl = contentSourceUrl;
- desc.currentSize = 0;
- desc.name = QFileInfo(url.toString()).fileName();
- desc.totalSize = 0; // The total size will be retrieved during the download
- desc.pos = pPos;
- desc.size = pSize;
- desc.isBackground = isBackground;
-
- UBDownloadManager::downloadManager()->addFileToDownload(desc);
- }
- }
- else
- {
- QString urlString = url.toString();
- int parametersStringPosition = urlString.indexOf("?");
- if(parametersStringPosition != -1)
- urlString = urlString.left(parametersStringPosition);
-
- // When we fall there, it means that we are dropping something from the web to the board
- sDownloadFileDesc desc;
- desc.modal = true;
- desc.srcUrl = urlString;
- desc.currentSize = 0;
- desc.name = QFileInfo(urlString).fileName();
- desc.totalSize = 0; // The total size will be retrieved during the download
- desc.pos = pPos;
- desc.size = pSize;
- desc.isBackground = isBackground;
-
- UBDownloadManager::downloadManager()->addFileToDownload(desc);
- }
-
- if (isBackground && oldBackgroundObject != mActiveScene->backgroundObject())
- {
- if (mActiveScene->isURStackIsEnabled()) { //should be deleted after scene own undo stack implemented
- UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(mActiveScene, oldBackgroundObject, mActiveScene->backgroundObject());
- UBApplication::undoStack->push(uc);
- }
- }
-
-
-}
-
-
-UBItem *UBBoardController::downloadFinished(bool pSuccess, QUrl sourceUrl, QUrl contentUrl, QString pContentTypeHeader,
- QByteArray pData, QPointF pPos, QSize pSize,
- bool isBackground, bool internalData)
-{
- QString mimeType = pContentTypeHeader;
-
- // In some cases "image/jpeg;charset=" is retourned by the drag-n-drop. That is
- // why we will check if an ; exists and take the first part (the standard allows this kind of mimetype)
- if(mimeType.isEmpty())
- mimeType = UBFileSystemUtils::mimeTypeFromFileName(sourceUrl.toString());
-
- int position=mimeType.indexOf(";");
- if(position != -1)
- mimeType=mimeType.left(position);
-
- UBMimeType::Enum itemMimeType = UBFileSystemUtils::mimeTypeFromString(mimeType);
-
- if (!pSuccess)
- {
- showMessage(tr("Downloading content %1 failed").arg(sourceUrl.toString()));
- return NULL;
- }
-
-
- mActiveScene->deselectAllItems();
-
- if (!sourceUrl.toString().startsWith("file://") && !sourceUrl.toString().startsWith("uniboardTool://"))
- showMessage(tr("Download finished"));
-
- if (UBMimeType::RasterImage == itemMimeType)
- {
-
- qDebug() << "accepting mime type" << mimeType << "as raster image";
-
-
- QPixmap pix;
- if(pData.length() == 0){
- pix.load(sourceUrl.toLocalFile());
- }
- else{
- QImage img;
- img.loadFromData(pData);
- pix = QPixmap::fromImage(img);
- }
-
- UBGraphicsPixmapItem* pixItem = mActiveScene->addPixmap(pix, NULL, pPos, 1.);
- pixItem->setSourceUrl(sourceUrl);
-
- if (isBackground)
- {
- mActiveScene->setAsBackgroundObject(pixItem, true);
- }
- else
- {
- mActiveScene->scaleToFitDocumentSize(pixItem, true, UBSettings::objectInControlViewMargin);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- pixItem->setSelected(true);
- }
-
- return pixItem;
- }
- else if (UBMimeType::VectorImage == itemMimeType)
- {
- qDebug() << "accepting mime type" << mimeType << "as vecto image";
-
- UBGraphicsSvgItem* svgItem = mActiveScene->addSvg(sourceUrl, pPos, pData);
- svgItem->setSourceUrl(sourceUrl);
-
- if (isBackground)
- {
- mActiveScene->setAsBackgroundObject(svgItem);
- }
- else
- {
- mActiveScene->scaleToFitDocumentSize(svgItem, true, UBSettings::objectInControlViewMargin);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- svgItem->setSelected(true);
- }
-
- return svgItem;
- }
- else if (UBMimeType::AppleWidget == itemMimeType) //mime type invented by us :-(
- {
- qDebug() << "accepting mime type" << mimeType << "as Apple widget";
-
- QUrl widgetUrl = sourceUrl;
-
- if (pData.length() > 0)
- {
- widgetUrl = expandWidgetToTempDir(pData, "wdgt");
- }
-
- UBGraphicsWidgetItem* appleWidgetItem = mActiveScene->addAppleWidget(widgetUrl, pPos);
-
- appleWidgetItem->setSourceUrl(sourceUrl);
-
- if (isBackground)
- {
- mActiveScene->setAsBackgroundObject(appleWidgetItem);
- }
- else
- {
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
-
- return appleWidgetItem;
- }
- else if (UBMimeType::W3CWidget == itemMimeType)
- {
- qDebug() << "accepting mime type" << mimeType << "as W3C widget";
- QUrl widgetUrl = sourceUrl;
-
- if (pData.length() > 0)
- {
- widgetUrl = expandWidgetToTempDir(pData);
- }
-
- UBGraphicsWidgetItem *w3cWidgetItem = addW3cWidget(widgetUrl, pPos);
-
- if (isBackground)
- {
- mActiveScene->setAsBackgroundObject(w3cWidgetItem);
- }
- else
- {
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
-
- return w3cWidgetItem;
- }
- else if (UBMimeType::Video == itemMimeType)
- {
- qDebug() << "accepting mime type" << mimeType << "as video";
-
- UBGraphicsMediaItem *mediaVideoItem = 0;
- QUuid uuid = QUuid::createUuid();
- if (pData.length() > 0)
- {
- QString destFile;
- bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
- sourceUrl.toString(),
- UBPersistenceManager::videoDirectory,
- uuid,
- destFile,
- &pData);
- if (!b)
- {
- showMessage(tr("Add file operation failed: file copying error"));
- return NULL;
- }
-
- QUrl url = QUrl::fromLocalFile(destFile);
-
- mediaVideoItem = mActiveScene->addMedia(url, false, pPos);
- }
- else
- {
- qDebug() << sourceUrl.toString();
- mediaVideoItem = addVideo(sourceUrl, false, pPos, true);
- }
-
- if(mediaVideoItem){
- if (contentUrl.isEmpty())
- mediaVideoItem->setSourceUrl(sourceUrl);
- else
- mediaVideoItem->setSourceUrl(contentUrl);
- mediaVideoItem->setUuid(uuid);
- connect(this, SIGNAL(activeSceneChanged()), mediaVideoItem, SLOT(activeSceneChanged()));
- }
-
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
-
- return mediaVideoItem;
- }
- else if (UBMimeType::Audio == itemMimeType)
- {
- qDebug() << "accepting mime type" << mimeType << "as audio";
-
- UBGraphicsMediaItem *audioMediaItem = 0;
-
- QUuid uuid = QUuid::createUuid();
- if (pData.length() > 0)
- {
- QString destFile;
- bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
- sourceUrl.toString(),
- UBPersistenceManager::audioDirectory,
- uuid,
- destFile,
- &pData);
- if (!b)
- {
- showMessage(tr("Add file operation failed: file copying error"));
- return NULL;
- }
-
- QUrl url = QUrl::fromLocalFile(destFile);
-
- audioMediaItem = mActiveScene->addMedia(url, false, pPos);
- }
- else
- {
- audioMediaItem = addAudio(sourceUrl, false, pPos, true);
- }
-
- if(audioMediaItem){
- if (contentUrl.isEmpty())
- audioMediaItem->setSourceUrl(sourceUrl);
- else
- audioMediaItem->setSourceUrl(contentUrl);
- audioMediaItem->setUuid(uuid);
- connect(this, SIGNAL(activeSceneChanged()), audioMediaItem, SLOT(activeSceneChanged()));
- }
-
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
-
- return audioMediaItem;
- }
-
- else if (UBMimeType::Flash == itemMimeType)
- {
-
- qDebug() << "accepting mime type" << mimeType << "as flash";
-
- QString sUrl = sourceUrl.toString();
-
- if (sUrl.startsWith("file://") || sUrl.startsWith("/"))
- {
- sUrl = sourceUrl.toLocalFile();
- }
-
- QTemporaryFile* eduMediaFile = 0;
-
- if (sUrl.toLower().contains("edumedia-sciences.com"))
- {
- eduMediaFile = new QTemporaryFile("XXXXXX.swf");
- if (eduMediaFile->open())
- {
- eduMediaFile->write(pData);
- QFileInfo fi(*eduMediaFile);
- sUrl = fi.absoluteFilePath();
- }
- }
-
- QSize size;
-
- if (pSize.height() > 0 && pSize.width() > 0)
- size = pSize;
- else
- size = mActiveScene->nominalSize() * .8;
-
- Q_UNUSED(internalData)
-
- QString widgetUrl = UBGraphicsW3CWidgetItem::createNPAPIWrapper(sUrl, mimeType, size);
- emit npapiWidgetCreated(widgetUrl);
-
- if (widgetUrl.length() > 0)
- {
- UBGraphicsWidgetItem *widgetItem = mActiveScene->addW3CWidget(QUrl::fromLocalFile(widgetUrl), pPos);
- widgetItem->setUuid(QUuid::createUuid());
- widgetItem->setSourceUrl(QUrl::fromLocalFile(widgetUrl));
-
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
-
- return widgetItem;
- }
-
- if (eduMediaFile)
- delete eduMediaFile;
-
- }
- else if (UBMimeType::PDF == itemMimeType)
- {
- qDebug() << "accepting mime type" << mimeType << "as PDF";
- qDebug() << "pdf data length: " << pData.size();
- qDebug() << "sourceurl : " + sourceUrl.toString();
- int result = 0;
- if(!sourceUrl.isEmpty()){
- QStringList fileNames;
- fileNames << sourceUrl.toLocalFile();
- result = UBDocumentManager::documentManager()->addFilesToDocument(selectedDocument(), fileNames);
- }
- else if(pData.size()){
- QTemporaryFile pdfFile("XXXXXX.pdf");
- if (pdfFile.open())
- {
- pdfFile.write(pData);
- QStringList fileNames;
- fileNames << pdfFile.fileName();
- result = UBDocumentManager::documentManager()->addFilesToDocument(selectedDocument(), fileNames);
- pdfFile.close();
- }
- }
-
- if (result){
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
- }
- }
- else if (UBMimeType::UniboardTool == itemMimeType)
- {
- qDebug() << "accepting mime type" << mimeType << "as Uniboard Tool";
-
- if (sourceUrl.toString() == UBToolsManager::manager()->compass.id)
- {
- mActiveScene->addCompass(pPos);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else if (sourceUrl.toString() == UBToolsManager::manager()->ruler.id)
- {
- mActiveScene->addRuler(pPos);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else if (sourceUrl.toString() == UBToolsManager::manager()->protractor.id)
- {
- mActiveScene->addProtractor(pPos);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else if (sourceUrl.toString() == UBToolsManager::manager()->triangle.id)
- {
- mActiveScene->addTriangle(pPos);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else if (sourceUrl.toString() == UBToolsManager::manager()->cache.id)
- {
- mActiveScene->addCache();
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else if (sourceUrl.toString() == UBToolsManager::manager()->magnifier.id)
- {
- UBMagnifierParams params;
- params.x = controlContainer()->geometry().width() / 2;
- params.y = controlContainer()->geometry().height() / 2;
- params.zoom = 2;
- params.sizePercentFromScene = 20;
- mActiveScene->addMagnifier(params);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else if (sourceUrl.toString() == UBToolsManager::manager()->mask.id)
- {
- mActiveScene->addMask(pPos);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
- else
- {
- showMessage(tr("Unknown tool type %1").arg(sourceUrl.toString()));
- }
- }
- else if (sourceUrl.toString().contains("edumedia-sciences.com"))
- {
- qDebug() << "accepting url " << sourceUrl.toString() << "as eduMedia content";
-
- QTemporaryFile eduMediaZipFile("XXXXXX.edumedia");
- if (eduMediaZipFile.open())
- {
- eduMediaZipFile.write(pData);
- eduMediaZipFile.close();
-
- QString tempDir = UBFileSystemUtils::createTempDir("uniboard-edumedia");
-
- UBFileSystemUtils::expandZipToDir(eduMediaZipFile, tempDir);
-
- QDir appDir(tempDir);
-
- foreach(QString subDirName, appDir.entryList(QDir::AllDirs))
- {
- QDir subDir(tempDir + "/" + subDirName + "/contents");
-
- foreach(QString fileName, subDir.entryList(QDir::Files))
- {
- if (fileName.toLower().endsWith(".swf"))
- {
- QString swfFile = tempDir + "/" + subDirName + "/contents/" + fileName;
-
- QSize size;
-
- if (pSize.height() > 0 && pSize.width() > 0)
- size = pSize;
- else
- size = mActiveScene->nominalSize() * .8;
-
- QString widgetUrl = UBGraphicsW3CWidgetItem::createNPAPIWrapper(swfFile, "application/x-shockwave-flash", size);
-
- if (widgetUrl.length() > 0)
- {
- UBGraphicsWidgetItem *widgetItem = mActiveScene->addW3CWidget(QUrl::fromLocalFile(widgetUrl), pPos);
-
- widgetItem->setSourceUrl(sourceUrl);
-
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
-
- return widgetItem;
- }
- }
- }
- }
- }
- }
- else
- {
- showMessage(tr("Unknown content type %1").arg(pContentTypeHeader));
- qWarning() << "ignoring mime type" << pContentTypeHeader ;
- }
-
- return NULL;
-}
-
-void UBBoardController::setActiveDocumentScene(int pSceneIndex)
-{
- setActiveDocumentScene(selectedDocument(), pSceneIndex);
-}
-
-void UBBoardController::setActiveDocumentScene(UBDocumentProxy* pDocumentProxy, const int pSceneIndex, bool forceReload)
-{
- saveViewState();
-
- bool documentChange = selectedDocument() != pDocumentProxy;
-
- int index = pSceneIndex;
- int sceneCount = pDocumentProxy->pageCount();
- if (index >= sceneCount && sceneCount > 0)
- index = sceneCount - 1;
-
- UBGraphicsScene* targetScene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pDocumentProxy, index);
-
- bool sceneChange = targetScene != mActiveScene;
-
- if (targetScene)
- {
- freezeW3CWidgets(true);
-
- persistCurrentScene();
-
- ClearUndoStack();
-
- mActiveScene = targetScene;
- mActiveSceneIndex = index;
- setDocument(pDocumentProxy, forceReload);
-
- updateSystemScaleFactor();
-
- mControlView->setScene(mActiveScene);
- mDisplayView->setScene(mActiveScene);
- mActiveScene->setBackgroundZoomFactor(mControlView->transform().m11());
- pDocumentProxy->setDefaultDocumentSize(mActiveScene->nominalSize());
- updatePageSizeState();
-
- adjustDisplayViews();
-
- UBSettings::settings()->setDarkBackground(mActiveScene->isDarkBackground());
- UBSettings::settings()->setCrossedBackground(mActiveScene->isCrossedBackground());
-
- freezeW3CWidgets(false);
- }
-
- selectionChanged();
-
- updateBackgroundActionsState(mActiveScene->isDarkBackground(), mActiveScene->isCrossedBackground());
- updateBackgroundState();
-
- if(documentChange)
- {
- UBGraphicsTextItem::lastUsedTextColor = QColor();
- }
-
-
- if (sceneChange)
- {
- emit activeSceneChanged();
- emit pageChanged();
- }
-}
-
-
-void UBBoardController::moveSceneToIndex(int source, int target)
-{
- if (selectedDocument())
- {
-
- persistCurrentScene();
-
- UBDocumentContainer::movePageToIndex(source, target);
-
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
- UBMetadataDcSubsetAdaptor::persist(selectedDocument());
- mMovingSceneIndex = source;
- setActiveDocumentScene(target);
- mMovingSceneIndex = -1;
-
- }
-}
-
-void UBBoardController::ClearUndoStack()
-{
-// The code has been removed because it leads to a strange error and because the final goal has never been
-// reached on tests and sound a little bit strange.
-// Strange error: item->scene() crashes the application because item doesn't implement scene() method. I'm
-// not able to give all the steps to reproduce this error sistematically but is quite frequent (~ twice per utilisation hours)
-// strange goal: if item is on the undocommand, the item->scene() is null and the item is not on the deleted scene item list then
-// then it's deleted.
-
- // QSet uniqueItems;
-// // go through all stack command
-// for(int i = 0; i < UBApplication::undoStack->count(); i++)
-// {
-
-// UBAbstractUndoCommand *abstractCmd = (UBAbstractUndoCommand*)UBApplication::undoStack->command(i);
-// if(abstractCmd->getType() != UBAbstractUndoCommand::undotype_GRAPHICITEM)
-// continue;
-
-// UBGraphicsItemUndoCommand *cmd = (UBGraphicsItemUndoCommand*)UBApplication::undoStack->command(i);
-
-// // go through all added and removed objects, for create list of unique objects
-// // grouped items will be deleted by groups, so we don't need do delete that items.
-// QSetIterator itAdded(cmd->GetAddedList());
-// while (itAdded.hasNext())
-// {
-// QGraphicsItem* item = itAdded.next();
-// if( !uniqueItems.contains(item) && !(item->parentItem() && UBGraphicsGroupContainerItem::Type == item->parentItem()->type()))
-// uniqueItems.insert(item);
-// }
-
-// QSetIterator itRemoved(cmd->GetRemovedList());
-// while (itRemoved.hasNext())
-// {
-// QGraphicsItem* item = itRemoved.next();
-// if( !uniqueItems.contains(item) && !(item->parentItem() && UBGraphicsGroupContainerItem::Type == item->parentItem()->type()))
-// uniqueItems.insert(item);
-// }
-// }
-
-// // go through all unique items, and check, ot on scene, or not.
-// // if not on scene, than item can be deleted
-
-// QSetIterator itUniq(uniqueItems);
-// while (itUniq.hasNext())
-// {
-// QGraphicsItem* item = itUniq.next();
-// UBGraphicsScene *scene = NULL;
-// if (item->scene()) {
-// scene = dynamic_cast(item->scene());
-// }
-// if(!scene)
-// {
-// if (!mActiveScene->deleteItem(item))
-// delete item;
-// }
-// }
-
- // clear stack, and command list
- UBApplication::undoStack->clear();
-
-}
-
-void UBBoardController::adjustDisplayViews()
-{
- if (UBApplication::applicationController)
- {
- UBApplication::applicationController->adjustDisplayView();
- UBApplication::applicationController->adjustPreviousViews(mActiveSceneIndex, selectedDocument());
- }
-}
-
-
-void UBBoardController::changeBackground(bool isDark, bool isCrossed)
-{
- bool currentIsDark = mActiveScene->isDarkBackground();
- bool currentIsCrossed = mActiveScene->isCrossedBackground();
-
- if ((isDark != currentIsDark) || (currentIsCrossed != isCrossed))
- {
- UBSettings::settings()->setDarkBackground(isDark);
- UBSettings::settings()->setCrossedBackground(isCrossed);
-
- mActiveScene->setBackground(isDark, isCrossed);
-
- updateBackgroundState();
-
- emit backgroundChanged();
- }
-}
-
-void UBBoardController::boardViewResized(QResizeEvent* event)
-{
- Q_UNUSED(event);
-
- int innerMargin = UBSettings::boardMargin;
- int userHeight = mControlContainer->height() - (2 * innerMargin);
-
- mMessageWindow->move(innerMargin, innerMargin + userHeight - mMessageWindow->height());
- mMessageWindow->adjustSizeAndPosition();
-
- UBApplication::applicationController->initViewState(
- mControlView->horizontalScrollBar()->value(),
- mControlView->verticalScrollBar()->value());
-
- updateSystemScaleFactor();
-
- mControlView->centerOn(0,0);
-
- if (mDisplayView)
- mDisplayView->centerOn(0,0);
-
- mPaletteManager->containerResized();
-
- UBApplication::boardController->controlView()->scene()->moveMagnifier();
-
-}
-
-
-void UBBoardController::documentWillBeDeleted(UBDocumentProxy* pProxy)
-{
- if (selectedDocument() == pProxy)
- {
- if (!mIsClosing)
- setActiveDocumentScene(UBPersistenceManager::persistenceManager()->createDocument());
- }
-}
-
-
-void UBBoardController::showMessage(const QString& message, bool showSpinningWheel)
-{
- mMessageWindow->showMessage(message, showSpinningWheel);
-}
-
-
-void UBBoardController::hideMessage()
-{
- mMessageWindow->hideMessage();
-}
-
-
-void UBBoardController::setDisabled(bool disable)
-{
- mMainWindow->boardToolBar->setDisabled(disable);
- mControlView->setDisabled(disable);
-}
-
-
-void UBBoardController::selectionChanged()
-{
- updateActionStates();
- emit pageSelectionChanged(activeSceneIndex());
-}
-
-
-void UBBoardController::undoRedoStateChange(bool canUndo)
-{
- Q_UNUSED(canUndo);
-
- mMainWindow->actionUndo->setEnabled(UBApplication::undoStack->canUndo());
- mMainWindow->actionRedo->setEnabled(UBApplication::undoStack->canRedo());
-
- updateActionStates();
-}
-
-
-void UBBoardController::updateActionStates()
-{
- mMainWindow->actionBack->setEnabled(selectedDocument() && (mActiveSceneIndex > 0));
- mMainWindow->actionForward->setEnabled(selectedDocument() && (mActiveSceneIndex < selectedDocument()->pageCount() - 1));
- mMainWindow->actionErase->setEnabled(mActiveScene && !mActiveScene->isEmpty());
-}
-
-
-UBGraphicsScene* UBBoardController::activeScene() const
-{
- return mActiveScene;
-}
-
-
-int UBBoardController::activeSceneIndex() const
-{
- return mActiveSceneIndex;
-}
-
-
-void UBBoardController::documentSceneChanged(UBDocumentProxy* pDocumentProxy, int pIndex)
-{
- Q_UNUSED(pIndex);
-
- if(selectedDocument() == pDocumentProxy)
- {
- setActiveDocumentScene(mActiveSceneIndex);
- }
-}
-
-void UBBoardController::closing()
-{
- mIsClosing = true;
- ClearUndoStack();
- lastWindowClosed();
-}
-
-void UBBoardController::lastWindowClosed()
-{
- if (!mCleanupDone)
- {
- bool teacherGuideModified = false;
- if(UBApplication::boardController->paletteManager()->teacherGuideDockWidget())
- teacherGuideModified = UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified();
- if (selectedDocument()->pageCount() == 1 && (!mActiveScene || mActiveScene->isEmpty()) && !teacherGuideModified)
- {
- UBPersistenceManager::persistenceManager()->deleteDocument(selectedDocument());
- }
- else
- {
- persistCurrentScene();
- }
-
- UBPersistenceManager::persistenceManager()->purgeEmptyDocuments();
-
- mCleanupDone = true;
- }
-}
-
-
-
-void UBBoardController::setColorIndex(int pColorIndex)
-{
- UBDrawingController::drawingController()->setColorIndex(pColorIndex);
-
- if (UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Marker &&
- UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Line &&
- UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Text &&
- UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Selector)
- {
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Pen);
- }
-
- if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Pen ||
- UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Line ||
- UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Text ||
- UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Selector)
- {
- mPenColorOnDarkBackground = UBSettings::settings()->penColors(true).at(pColorIndex);
- mPenColorOnLightBackground = UBSettings::settings()->penColors(false).at(pColorIndex);
-
- if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Selector)
- {
- // If we are in mode board, then do that
- if(UBApplication::applicationController->displayMode() == UBApplicationController::Board)
- {
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Pen);
- mMainWindow->actionPen->setChecked(true);
- }
- }
-
- emit penColorChanged();
- }
- else if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Marker)
- {
- mMarkerColorOnDarkBackground = UBSettings::settings()->markerColors(true).at(pColorIndex);
- mMarkerColorOnLightBackground = UBSettings::settings()->markerColors(false).at(pColorIndex);
- }
-}
-
-void UBBoardController::colorPaletteChanged()
-{
- mPenColorOnDarkBackground = UBSettings::settings()->penColor(true);
- mPenColorOnLightBackground = UBSettings::settings()->penColor(false);
- mMarkerColorOnDarkBackground = UBSettings::settings()->markerColor(true);
- mMarkerColorOnLightBackground = UBSettings::settings()->markerColor(false);
-}
-
-
-qreal UBBoardController::currentZoom()
-{
- if (mControlView)
- return mControlView->viewportTransform().m11() / mSystemScaleFactor;
- else
- return 1.0;
-}
-
-void UBBoardController::removeTool(UBToolWidget* toolWidget)
-{
- toolWidget->hide();
-
- delete toolWidget;
-}
-
-void UBBoardController::hide()
-{
- UBApplication::mainWindow->actionLibrary->setChecked(false);
-}
-
-void UBBoardController::show()
-{
- UBApplication::mainWindow->actionLibrary->setChecked(false);
-}
-
-void UBBoardController::persistCurrentScene()
-{
- if(UBPersistenceManager::persistenceManager()
- && selectedDocument() && mActiveScene && mActiveSceneIndex != mDeletingSceneIndex
- && (mActiveSceneIndex >= 0) && mActiveSceneIndex != mMovingSceneIndex
- && (mActiveScene->isModified() || (UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified())))
- {
- UBPersistenceManager::persistenceManager()->persistDocumentScene(selectedDocument(), mActiveScene, mActiveSceneIndex);
- updatePage(mActiveSceneIndex);
- }
-}
-
-void UBBoardController::updateSystemScaleFactor()
-{
- qreal newScaleFactor = 1.0;
-
- if (mActiveScene)
- {
- QSize pageNominalSize = mActiveScene->nominalSize();
- //we're going to keep scale factor untouched if the size is custom
- QMap sizesMap = UBSettings::settings()->documentSizes;
- // if(pageNominalSize == sizesMap.value(DocumentSizeRatio::Ratio16_9) || pageNominalSize == sizesMap.value(DocumentSizeRatio::Ratio4_3))
- {
- QSize controlSize = controlViewport();
-
- qreal hFactor = ((qreal)controlSize.width()) / ((qreal)pageNominalSize.width());
- qreal vFactor = ((qreal)controlSize.height()) / ((qreal)pageNominalSize.height());
-
- newScaleFactor = qMin(hFactor, vFactor);
- }
- }
-
- if (mSystemScaleFactor != newScaleFactor)
- {
- mSystemScaleFactor = newScaleFactor;
- emit systemScaleFactorChanged(newScaleFactor);
- }
-
- UBGraphicsScene::SceneViewState viewState = mActiveScene->viewState();
-
- QTransform scalingTransform;
-
- qreal scaleFactor = viewState.zoomFactor * mSystemScaleFactor;
- scalingTransform.scale(scaleFactor, scaleFactor);
-
- mControlView->setTransform(scalingTransform);
- mControlView->horizontalScrollBar()->setValue(viewState.horizontalPosition);
- mControlView->verticalScrollBar()->setValue(viewState.verticalPostition);
- mActiveScene->setBackgroundZoomFactor(mControlView->transform().m11());}
-
-
-void UBBoardController::setWidePageSize(bool checked)
-{
- Q_UNUSED(checked);
- QSize newSize = UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio16_9);
-
- if (mActiveScene->nominalSize() != newSize)
- {
- UBPageSizeUndoCommand* uc = new UBPageSizeUndoCommand(mActiveScene, mActiveScene->nominalSize(), newSize);
- UBApplication::undoStack->push(uc);
-
- setPageSize(newSize);
- }
-}
-
-
-void UBBoardController::setRegularPageSize(bool checked)
-{
- Q_UNUSED(checked);
- QSize newSize = UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio4_3);
-
- if (mActiveScene->nominalSize() != newSize)
- {
- UBPageSizeUndoCommand* uc = new UBPageSizeUndoCommand(mActiveScene, mActiveScene->nominalSize(), newSize);
- UBApplication::undoStack->push(uc);
-
- setPageSize(newSize);
- }
-}
-
-
-void UBBoardController::setPageSize(QSize newSize)
-{
- if (mActiveScene->nominalSize() != newSize)
- {
- mActiveScene->setNominalSize(newSize);
-
- saveViewState();
-
- updateSystemScaleFactor();
- updatePageSizeState();
- adjustDisplayViews();
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- UBSettings::settings()->pageSize->set(newSize);
- }
-}
-
-void UBBoardController::notifyCache(bool visible)
-{
- if(visible)
- {
- emit cacheEnabled();
- }
- else
- {
- emit cacheDisabled();
- }
- mCacheWidgetIsEnabled = visible;
-}
-
-void UBBoardController::updatePageSizeState()
-{
- if (mActiveScene->nominalSize() == UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio16_9))
- {
- mMainWindow->actionWidePageSize->setChecked(true);
- }
- else if(mActiveScene->nominalSize() == UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio4_3))
- {
- mMainWindow->actionRegularPageSize->setChecked(true);
- }
- else
- {
- mMainWindow->actionCustomPageSize->setChecked(true);
- }
-}
-
-
-void UBBoardController::saveViewState()
-{
- if (mActiveScene)
- {
- mActiveScene->setViewState(UBGraphicsScene::SceneViewState(currentZoom(),
- mControlView->horizontalScrollBar()->value(),
- mControlView->verticalScrollBar()->value()));
- }
-}
-
-
-void UBBoardController::updateBackgroundState()
-{
- //adjust background style
- QString newBackgroundStyle;
-
- if (mActiveScene && mActiveScene->isDarkBackground())
- {
- newBackgroundStyle ="QWidget {background-color: #0E0E0E}";
- }
- else
- {
- newBackgroundStyle ="QWidget {background-color: #F1F1F1}";
- }
-}
-
-void UBBoardController::stylusToolChanged(int tool)
-{
- if (UBPlatformUtils::hasVirtualKeyboard() && mPaletteManager->mKeyboardPalette)
- {
- UBStylusTool::Enum eTool = (UBStylusTool::Enum)tool;
- if(eTool != UBStylusTool::Selector && eTool != UBStylusTool::Text)
- {
- if(mPaletteManager->mKeyboardPalette->m_isVisible)
- UBApplication::mainWindow->actionVirtualKeyboard->activate(QAction::Trigger);
- }
- }
-
- updateBackgroundState();
-}
-
-
-QUrl UBBoardController::expandWidgetToTempDir(const QByteArray& pZipedData, const QString& ext)
-{
- QUrl widgetUrl;
- QTemporaryFile tmp;
-
- if (tmp.open())
- {
- tmp.write(pZipedData);
- tmp.flush();
- tmp.close();
-
- QString tmpDir = UBFileSystemUtils::createTempDir() + "." + ext;
-
- if (UBFileSystemUtils::expandZipToDir(tmp, tmpDir))
- {
- widgetUrl = QUrl::fromLocalFile(tmpDir);
- }
- }
-
- return widgetUrl;
-}
-
-
-void UBBoardController::grabScene(const QRectF& pSceneRect)
-{
- if (mActiveScene)
- {
- QImage image(pSceneRect.width(), pSceneRect.height(), QImage::Format_ARGB32);
- image.fill(Qt::transparent);
-
- QRectF targetRect(0, 0, pSceneRect.width(), pSceneRect.height());
- QPainter painter(&image);
- painter.setRenderHint(QPainter::SmoothPixmapTransform);
- painter.setRenderHint(QPainter::Antialiasing);
-
- mActiveScene->setRenderingContext(UBGraphicsScene::NonScreen);
- mActiveScene->setRenderingQuality(UBItem::RenderingQualityHigh);
-
- mActiveScene->render(&painter, targetRect, pSceneRect);
-
- mActiveScene->setRenderingContext(UBGraphicsScene::Screen);
- mActiveScene->setRenderingQuality(UBItem::RenderingQualityNormal);
-
- mPaletteManager->addItem(QPixmap::fromImage(image));
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
- }
-}
-
-UBGraphicsMediaItem* UBBoardController::addVideo(const QUrl& pSourceUrl, bool startPlay, const QPointF& pos, bool bUseSource)
-{
- QUuid uuid = QUuid::createUuid();
- QUrl concreteUrl = pSourceUrl;
-
- // media file is not in document folder yet
- if (!bUseSource)
- {
- QString destFile;
- bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
- pSourceUrl.toLocalFile(),
- UBPersistenceManager::videoDirectory,
- uuid,
- destFile);
- if (!b)
- {
- showMessage(tr("Add file operation failed: file copying error"));
- return NULL;
- }
- concreteUrl = QUrl::fromLocalFile(destFile);
- }// else we just use source Url.
-
-
- UBGraphicsMediaItem* vi = mActiveScene->addMedia(concreteUrl, startPlay, pos);
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- if (vi) {
- vi->setUuid(uuid);
- vi->setSourceUrl(pSourceUrl);
- }
-
- return vi;
-
-}
-
-UBGraphicsMediaItem* UBBoardController::addAudio(const QUrl& pSourceUrl, bool startPlay, const QPointF& pos, bool bUseSource)
-{
- QUuid uuid = QUuid::createUuid();
- QUrl concreteUrl = pSourceUrl;
-
- // media file is not in document folder yet
- if (!bUseSource)
- {
- QString destFile;
- bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
- pSourceUrl.toLocalFile(),
- UBPersistenceManager::audioDirectory,
- uuid,
- destFile);
- if (!b)
- {
- showMessage(tr("Add file operation failed: file copying error"));
- return NULL;
- }
- concreteUrl = QUrl::fromLocalFile(destFile);
- }// else we just use source Url.
-
- UBGraphicsMediaItem* ai = mActiveScene->addMedia(concreteUrl, startPlay, pos);
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-
- if (ai){
- ai->setUuid(uuid);
- ai->setSourceUrl(pSourceUrl);
- }
-
- return ai;
-
-}
-
-UBGraphicsWidgetItem *UBBoardController::addW3cWidget(const QUrl &pUrl, const QPointF &pos)
-{
- UBGraphicsWidgetItem* w3cWidgetItem = 0;
-
- QUuid uuid = QUuid::createUuid();
-
- QString destPath;
- if (!UBPersistenceManager::persistenceManager()->addGraphicsWidgteToDocument(selectedDocument(), pUrl.toLocalFile(), uuid, destPath))
- return NULL;
- QUrl newUrl = QUrl::fromLocalFile(destPath);
-
- w3cWidgetItem = mActiveScene->addW3CWidget(newUrl, pos);
-
- if (w3cWidgetItem) {
- w3cWidgetItem->setUuid(uuid);
- w3cWidgetItem->setOwnFolder(newUrl);
- w3cWidgetItem->setSourceUrl(pUrl);
-
- QString struuid = UBStringUtils::toCanonicalUuid(uuid);
- QString snapshotPath = selectedDocument()->persistencePath() + "/" + UBPersistenceManager::widgetDirectory + "/" + struuid + ".png";
- w3cWidgetItem->setSnapshotPath(QUrl::fromLocalFile(snapshotPath));
- UBGraphicsWidgetItem *tmpItem = dynamic_cast(w3cWidgetItem);
- if (tmpItem && tmpItem->scene())
- tmpItem->takeSnapshot().save(snapshotPath, "PNG");
-
- }
-
- return w3cWidgetItem;
-}
-
-void UBBoardController::cut()
-{
- //---------------------------------------------------------//
-
- QList selectedItems;
- foreach(QGraphicsItem* gi, mActiveScene->selectedItems())
- selectedItems << gi;
-
- //---------------------------------------------------------//
-
- QList selected;
- foreach(QGraphicsItem* gi, selectedItems)
- {
- gi->setSelected(false);
-
- UBItem* ubItem = dynamic_cast(gi);
- UBGraphicsItem *ubGi = dynamic_cast(gi);
-
- if (ubItem && ubGi && !mActiveScene->tools().contains(gi))
- {
- selected << ubItem->deepCopy();
- ubGi->remove();
- }
- }
-
- //---------------------------------------------------------//
-
- if (selected.size() > 0)
- {
- QClipboard *clipboard = QApplication::clipboard();
-
- UBMimeDataGraphicsItem* mimeGi = new UBMimeDataGraphicsItem(selected);
-
- mimeGi->setData(UBApplication::mimeTypeUniboardPageItem, QByteArray());
- clipboard->setMimeData(mimeGi);
-
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
- }
-
- //---------------------------------------------------------//
-}
-
-
-void UBBoardController::copy()
-{
- QList selected;
-
- foreach(QGraphicsItem* gi, mActiveScene->selectedItems())
- {
- UBItem* ubItem = dynamic_cast(gi);
-
- if (ubItem && !mActiveScene->tools().contains(gi))
- {
- UBItem *itemCopy = ubItem->deepCopy();
- if (itemCopy)
- selected << itemCopy;
- }
- }
-
- if (selected.size() > 0)
- {
- QClipboard *clipboard = QApplication::clipboard();
-
- UBMimeDataGraphicsItem* mimeGi = new UBMimeDataGraphicsItem(selected);
-
- mimeGi->setData(UBApplication::mimeTypeUniboardPageItem, QByteArray());
- clipboard->setMimeData(mimeGi);
-
- }
-}
-
-
-void UBBoardController::paste()
-{
- QClipboard *clipboard = QApplication::clipboard();
- QPointF pos(0, 0);
- processMimeData(clipboard->mimeData(), pos);
-
- selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
-}
-
-
-void UBBoardController::processMimeData(const QMimeData* pMimeData, const QPointF& pPos)
-{
- if (pMimeData->hasFormat(UBApplication::mimeTypeUniboardPage))
- {
- const UBMimeData* mimeData = qobject_cast (pMimeData);
-
- if (mimeData)
- {
- int previousActiveSceneIndex = activeSceneIndex();
- int previousPageCount = selectedDocument()->pageCount();
-
- foreach (UBMimeDataItem sourceItem, mimeData->items())
- addScene(sourceItem.documentProxy(), sourceItem.sceneIndex(), true);
-
- if (selectedDocument()->pageCount() < previousPageCount + mimeData->items().count())
- setActiveDocumentScene(previousActiveSceneIndex);
- else
- setActiveDocumentScene(previousActiveSceneIndex + 1);
-
- return;
- }
- }
-
- if (pMimeData->hasFormat(UBApplication::mimeTypeUniboardPageItem))
- {
- const UBMimeDataGraphicsItem* mimeData = qobject_cast (pMimeData);
-
- if (mimeData)
- {
- foreach(UBItem* item, mimeData->items())
- {
- QGraphicsItem* pItem = dynamic_cast(item);
- if(NULL != pItem){
- duplicateItem(item);
- }
- }
-
- return;
- }
- }
-
- if(pMimeData->hasHtml())
- {
- QString qsHtml = pMimeData->html();
- QString url = UBApplication::urlFromHtml(qsHtml);
-
- if("" != url)
- {
- downloadURL(url, QString(), pPos);
- return;
- }
- }
-
- if (pMimeData->hasUrls())
- {
- QList urls = pMimeData->urls();
-
- int index = 0;
-
- const UBFeaturesMimeData *internalMimeData = qobject_cast(pMimeData);
- bool internalData = false;
- if (internalMimeData) {
- internalData = true;
- }
-
- foreach(const QUrl url, urls){
- QPointF pos(pPos + QPointF(index * 15, index * 15));
-
- downloadURL(url, QString(), pos, QSize(), false, internalData);
- index++;
- }
-
- return;
- }
-
- if (pMimeData->hasImage())
- {
- QImage img = qvariant_cast (pMimeData->imageData());
- QPixmap pix = QPixmap::fromImage(img);
-
- // validate that the image is really an image, webkit does not fill properly the image mime data
- if (pix.width() != 0 && pix.height() != 0)
- {
- mActiveScene->addPixmap(pix, NULL, pPos, 1.);
- return;
- }
- }
-
- if (pMimeData->hasText())
- {
- if("" != pMimeData->text()){
- // Sometimes, it is possible to have an URL as text. we check here if it is the case
- QString qsTmp = pMimeData->text().remove(QRegExp("[\\0]"));
- if(qsTmp.startsWith("http")){
- downloadURL(QUrl(qsTmp), QString(), pPos);
- }
- else{
- mActiveScene->addTextHtml(pMimeData->html(), pPos);
- }
- }
- else{
-#ifdef Q_WS_MACX
- // With Safari, in 95% of the drops, the mime datas are hidden in Apple Web Archive pasteboard type.
- // This is due to the way Safari is working so we have to dig into the pasteboard in order to retrieve
- // the data.
- QString qsUrl = UBPlatformUtils::urlFromClipboard();
- if("" != qsUrl){
- // We finally got the url of the dropped ressource! Let's import it!
- downloadURL(qsUrl, qsUrl, pPos);
- return;
- }
-#endif
- }
- }
-}
-
-
-void UBBoardController::togglePodcast(bool checked)
-{
- if (UBPodcastController::instance())
- UBPodcastController::instance()->toggleRecordingPalette(checked);
-}
-
-void UBBoardController::moveGraphicsWidgetToControlView(UBGraphicsWidgetItem* graphicsWidget)
-{
- mActiveScene->setURStackEnable(false);
- UBGraphicsItem *toolW3C = duplicateItem(dynamic_cast(graphicsWidget));
- UBGraphicsWidgetItem *copyedGraphicsWidget = NULL;
-
- if (UBGraphicsWidgetItem::Type == toolW3C->type())
- copyedGraphicsWidget = static_cast(toolW3C);
-
- UBToolWidget *toolWidget = new UBToolWidget(copyedGraphicsWidget, mControlView);
-
- graphicsWidget->remove(false);
- mActiveScene->addItemToDeletion(graphicsWidget);
-
- mActiveScene->setURStackEnable(true);
-
- QPoint controlViewPos = mControlView->mapFromScene(graphicsWidget->sceneBoundingRect().center());
- toolWidget->centerOn(mControlView->mapTo(mControlContainer, controlViewPos));
- toolWidget->show();
-}
-
-
-void UBBoardController::moveToolWidgetToScene(UBToolWidget* toolWidget)
-{
- UBGraphicsWidgetItem *widgetToScene = toolWidget->toolWidget();
-
- widgetToScene->resetTransform();
-
- QPoint mainWindowCenter = toolWidget->mapTo(mMainWindow, QPoint(toolWidget->width(), toolWidget->height()) / 2);
- QPoint controlViewCenter = mControlView->mapFrom(mMainWindow, mainWindowCenter);
- QPointF scenePos = mControlView->mapToScene(controlViewCenter);
-
- mActiveScene->addGraphicsWidget(widgetToScene, scenePos);
-
- toolWidget->remove();
-}
-
-
-void UBBoardController::updateBackgroundActionsState(bool isDark, bool isCrossed)
-{
- if (isDark && !isCrossed)
- mMainWindow->actionPlainDarkBackground->setChecked(true);
- else if (isDark && isCrossed)
- mMainWindow->actionCrossedDarkBackground->setChecked(true);
- else if (!isDark && isCrossed)
- mMainWindow->actionCrossedLightBackground->setChecked(true);
- else
- mMainWindow->actionPlainLightBackground->setChecked(true);
-}
-
-
-void UBBoardController::addItem()
-{
- QString defaultPath = UBSettings::settings()->lastImportToLibraryPath->get().toString();
-
- QString extensions;
- foreach(QString ext, UBSettings::imageFileExtensions)
- {
- extensions += " *.";
- extensions += ext;
- }
-
- QString filename = QFileDialog::getOpenFileName(mControlContainer, tr("Add Item"),
- defaultPath,
- tr("All Supported (%1)").arg(extensions), NULL, QFileDialog::DontUseNativeDialog);
-
- if (filename.length() > 0)
- {
- mPaletteManager->addItem(QUrl::fromLocalFile(filename));
- QFileInfo source(filename);
- UBSettings::settings()->lastImportToLibraryPath->set(QVariant(source.absolutePath()));
- }
-}
-
-void UBBoardController::importPage()
-{
- int pageCount = selectedDocument()->pageCount();
- if (UBApplication::documentController->addFileToDocument(selectedDocument()))
- {
- setActiveDocumentScene(selectedDocument(), pageCount, true);
- }
-}
-
-void UBBoardController::notifyPageChanged()
-{
- emit pageChanged();
-}
-
-void UBBoardController::onDownloadModalFinished()
-{
-
-}
-
-void UBBoardController::displayMetaData(QMap metadatas)
-{
- emit displayMetadata(metadatas);
-}
-
-void UBBoardController::freezeW3CWidgets(bool freeze)
-{
- if (mActiveSceneIndex >= 0)
- {
- QList list = UBApplication::boardController->activeScene()->getFastAccessItems();
- foreach(QGraphicsItem *item, list)
- {
- freezeW3CWidget(item, freeze);
- }
- }
-}
-
-void UBBoardController::freezeW3CWidget(QGraphicsItem *item, bool freeze)
-{
- if(item->type() == UBGraphicsW3CWidgetItem::Type)
- {
- UBGraphicsW3CWidgetItem* item_casted = dynamic_cast(item);
- if (0 == item_casted)
- return;
-
- if (freeze) {
- item_casted->load(QUrl(UBGraphicsW3CWidgetItem::freezedWidgetFilePath()));
- } else
- item_casted->loadMainHtml();
- }
-}
+
+
+#include "UBBoardController.h"
+
+#include
+#include
+
+#include "frameworks/UBFileSystemUtils.h"
+#include "frameworks/UBPlatformUtils.h"
+
+#include "core/UBApplication.h"
+#include "core/UBSettings.h"
+#include "core/UBSetting.h"
+#include "core/UBPersistenceManager.h"
+#include "core/UBApplicationController.h"
+#include "core/UBDocumentManager.h"
+#include "core/UBMimeData.h"
+#include "core/UBDownloadManager.h"
+
+#include "network/UBHttpGet.h"
+
+#include "gui/UBMessageWindow.h"
+#include "gui/UBResources.h"
+#include "gui/UBToolbarButtonGroup.h"
+#include "gui/UBMainWindow.h"
+#include "gui/UBToolWidget.h"
+#include "gui/UBKeyboardPalette.h"
+#include "gui/UBMagnifer.h"
+#include "gui/UBDockPaletteWidget.h"
+#include "gui/UBDockTeacherGuideWidget.h"
+#include "gui/UBTeacherGuideWidget.h"
+
+#include "domain/UBGraphicsPixmapItem.h"
+#include "domain/UBGraphicsItemUndoCommand.h"
+#include "domain/UBGraphicsProxyWidget.h"
+#include "domain/UBGraphicsSvgItem.h"
+#include "domain/UBGraphicsWidgetItem.h"
+#include "domain/UBGraphicsMediaItem.h"
+#include "domain/UBGraphicsPDFItem.h"
+#include "domain/UBGraphicsTextItem.h"
+#include "domain/UBPageSizeUndoCommand.h"
+#include "domain/UBGraphicsGroupContainerItem.h"
+#include "domain/UBItem.h"
+#include "board/UBFeaturesController.h"
+#include "domain/UBGraphicsStrokesGroup.h"
+
+#include "gui/UBFeaturesWidget.h"
+
+#include "tools/UBToolsManager.h"
+
+#include "document/UBDocumentProxy.h"
+#include "document/UBDocumentController.h"
+
+#include "board/UBDrawingController.h"
+#include "board/UBBoardView.h"
+
+#include "podcast/UBPodcastController.h"
+
+#include "adaptors/UBMetadataDcSubsetAdaptor.h"
+#include "adaptors/UBSvgSubsetAdaptor.h"
+
+#include "UBBoardPaletteManager.h"
+
+#include "core/UBSettings.h"
+
+#include "core/memcheck.h"
+
+UBBoardController::UBBoardController(UBMainWindow* mainWindow)
+ : UBDocumentContainer(mainWindow->centralWidget())
+ , mMainWindow(mainWindow)
+ , mActiveScene(0)
+ , mActiveSceneIndex(-1)
+ , mPaletteManager(0)
+ , mSoftwareUpdateDialog(0)
+ , mMessageWindow(0)
+ , mControlView(0)
+ , mDisplayView(0)
+ , mControlContainer(0)
+ , mControlLayout(0)
+ , mZoomFactor(1.0)
+ , mIsClosing(false)
+ , mSystemScaleFactor(1.0)
+ , mCleanupDone(false)
+ , mCacheWidgetIsEnabled(false)
+ , mDeletingSceneIndex(-1)
+ , mMovingSceneIndex(-1)
+ , mActionGroupText(tr("Group"))
+ , mActionUngroupText(tr("Ungroup"))
+{
+ mZoomFactor = UBSettings::settings()->boardZoomFactor->get().toDouble();
+
+ int penColorIndex = UBSettings::settings()->penColorIndex();
+ int markerColorIndex = UBSettings::settings()->markerColorIndex();
+
+ mPenColorOnDarkBackground = UBSettings::settings()->penColors(true).at(penColorIndex);
+ mPenColorOnLightBackground = UBSettings::settings()->penColors(false).at(penColorIndex);
+ mMarkerColorOnDarkBackground = UBSettings::settings()->markerColors(true).at(markerColorIndex);
+ mMarkerColorOnLightBackground = UBSettings::settings()->markerColors(false).at(markerColorIndex);
+
+ QDesktopWidget* desktop = UBApplication::desktop();
+ int dpiCommon = (desktop->physicalDpiX() + desktop->physicalDpiY()) / 2;
+ int sPixelsPerMillimeter = qRound(dpiCommon / UBGeometryUtils::inchSize);
+ UBSettings::settings()->crossSize = 10*sPixelsPerMillimeter;
+}
+
+
+void UBBoardController::init()
+{
+ setupViews();
+ setupToolbar();
+
+ connect(UBApplication::undoStack, SIGNAL(canUndoChanged(bool))
+ , this, SLOT(undoRedoStateChange(bool)));
+
+ connect(UBApplication::undoStack, SIGNAL(canRedoChanged (bool))
+ , this, SLOT(undoRedoStateChange(bool)));
+
+ connect(UBDrawingController::drawingController(), SIGNAL(stylusToolChanged(int))
+ , this, SLOT(setToolCursor(int)));
+
+ connect(UBDrawingController::drawingController(), SIGNAL(stylusToolChanged(int))
+ , this, SLOT(stylusToolChanged(int)));
+
+ connect(UBApplication::app(), SIGNAL(lastWindowClosed())
+ , this, SLOT(lastWindowClosed()));
+
+ connect(UBDownloadManager::downloadManager(), SIGNAL(downloadModalFinished()), this, SLOT(onDownloadModalFinished()));
+ connect(UBDownloadManager::downloadManager(), SIGNAL(addDownloadedFileToBoard(bool,QUrl,QUrl,QString,QByteArray,QPointF,QSize,bool)), this, SLOT(downloadFinished(bool,QUrl,QUrl,QString,QByteArray,QPointF,QSize,bool)));
+
+ UBDocumentProxy* doc = UBPersistenceManager::persistenceManager()->createDocument();
+
+ setActiveDocumentScene(doc);
+
+ connect(UBApplication::mainWindow->actionGroupItems, SIGNAL(triggered()), this, SLOT(groupButtonClicked()));
+
+ undoRedoStateChange(true);
+}
+
+
+UBBoardController::~UBBoardController()
+{
+ delete mDisplayView;
+}
+
+
+int UBBoardController::currentPage()
+{
+ if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool())
+ return mActiveSceneIndex;
+ return mActiveSceneIndex + 1;
+}
+
+void UBBoardController::setupViews()
+{
+ mControlContainer = new QWidget(mMainWindow->centralWidget());
+
+ mControlLayout = new QHBoxLayout(mControlContainer);
+ mControlLayout->setContentsMargins(0, 0, 0, 0);
+
+ mControlView = new UBBoardView(this, mControlContainer, true, false);
+ mControlView->setInteractive(true);
+ mControlView->setMouseTracking(true);
+
+ mControlView->grabGesture(Qt::SwipeGesture);
+
+ mControlView->setTransformationAnchor(QGraphicsView::NoAnchor);
+
+ mControlLayout->addWidget(mControlView);
+ mControlContainer->setObjectName("ubBoardControlContainer");
+ mMainWindow->addBoardWidget(mControlContainer);
+
+ connect(mControlView, SIGNAL(resized(QResizeEvent*)), this, SLOT(boardViewResized(QResizeEvent*)));
+
+ // TODO UB 4.x Optimization do we have to create the display view even if their is
+ // only 1 screen
+ //
+ mDisplayView = new UBBoardView(this, UBItemLayerType::FixedBackground, UBItemLayerType::Tool, 0);
+ mDisplayView->setInteractive(false);
+ mDisplayView->setTransformationAnchor(QGraphicsView::NoAnchor);
+
+ mMessageWindow = new UBMessageWindow(mControlView);
+ mMessageWindow->hide();
+
+ mPaletteManager = new UBBoardPaletteManager(mControlContainer, this);
+ connect(this, SIGNAL(activeSceneChanged()), mPaletteManager, SLOT(activeSceneChanged()));
+
+}
+
+
+void UBBoardController::setupLayout()
+{
+ if(mPaletteManager)
+ mPaletteManager->setupLayout();
+}
+
+
+void UBBoardController::setBoxing(QRect displayRect)
+{
+ if (displayRect.isNull())
+ {
+ mControlLayout->setContentsMargins(0, 0, 0, 0);
+ return;
+ }
+
+ qreal controlWidth = (qreal)mMainWindow->centralWidget()->width();
+ qreal controlHeight = (qreal)mMainWindow->centralWidget()->height();
+ qreal displayWidth = (qreal)displayRect.width();
+ qreal displayHeight = (qreal)displayRect.height();
+
+ qreal displayRatio = displayWidth / displayHeight;
+ qreal controlRatio = controlWidth / controlHeight;
+
+ if (displayRatio < controlRatio)
+ {
+ // Pillarboxing
+ int boxWidth = (controlWidth - (displayWidth * (controlHeight / displayHeight))) / 2;
+ mControlLayout->setContentsMargins(boxWidth, 0, boxWidth, 0);
+ }
+ else if (displayRatio > controlRatio)
+ {
+ // Letterboxing
+ int boxHeight = (controlHeight - (displayHeight * (controlWidth / displayWidth))) / 2;
+ mControlLayout->setContentsMargins(0, boxHeight, 0, boxHeight);
+ }
+ else
+ {
+ // No boxing
+ mControlLayout->setContentsMargins(0, 0, 0, 0);
+ }
+}
+
+
+QSize UBBoardController::displayViewport()
+{
+ return mDisplayView->geometry().size();
+}
+
+
+QSize UBBoardController::controlViewport()
+{
+ return mControlView->geometry().size();
+}
+
+
+QRectF UBBoardController::controlGeometry()
+{
+ return mControlView->geometry();
+}
+
+
+void UBBoardController::setupToolbar()
+{
+ UBSettings *settings = UBSettings::settings();
+
+ // Setup color choice widget
+ QList colorActions;
+ colorActions.append(mMainWindow->actionColor0);
+ colorActions.append(mMainWindow->actionColor1);
+ colorActions.append(mMainWindow->actionColor2);
+ colorActions.append(mMainWindow->actionColor3);
+
+ UBToolbarButtonGroup *colorChoice =
+ new UBToolbarButtonGroup(mMainWindow->boardToolBar, colorActions);
+
+ mMainWindow->boardToolBar->insertWidget(mMainWindow->actionBackgrounds, colorChoice);
+
+ connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), colorChoice, SLOT(displayText(QVariant)));
+ connect(colorChoice, SIGNAL(activated(int)), this, SLOT(setColorIndex(int)));
+ connect(UBDrawingController::drawingController(), SIGNAL(colorIndexChanged(int)), colorChoice, SLOT(setCurrentIndex(int)));
+ connect(UBDrawingController::drawingController(), SIGNAL(colorPaletteChanged()), colorChoice, SLOT(colorPaletteChanged()));
+ connect(UBDrawingController::drawingController(), SIGNAL(colorPaletteChanged()), this, SLOT(colorPaletteChanged()));
+
+ colorChoice->displayText(QVariant(settings->appToolBarDisplayText->get().toBool()));
+ colorChoice->colorPaletteChanged();
+
+ // Setup line width choice widget
+ QList lineWidthActions;
+ lineWidthActions.append(mMainWindow->actionLineSmall);
+ lineWidthActions.append(mMainWindow->actionLineMedium);
+ lineWidthActions.append(mMainWindow->actionLineLarge);
+
+ UBToolbarButtonGroup *lineWidthChoice =
+ new UBToolbarButtonGroup(mMainWindow->boardToolBar, lineWidthActions);
+
+ connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), lineWidthChoice, SLOT(displayText(QVariant)));
+
+ connect(lineWidthChoice, SIGNAL(activated(int))
+ , UBDrawingController::drawingController(), SLOT(setLineWidthIndex(int)));
+
+ connect(UBDrawingController::drawingController(), SIGNAL(lineWidthIndexChanged(int))
+ , lineWidthChoice, SLOT(setCurrentIndex(int)));
+
+ lineWidthChoice->displayText(QVariant(settings->appToolBarDisplayText->get().toBool()));
+
+ mMainWindow->boardToolBar->insertWidget(mMainWindow->actionBackgrounds, lineWidthChoice);
+
+ //-----------------------------------------------------------//
+ // Setup eraser width choice widget
+
+ QList eraserWidthActions;
+ eraserWidthActions.append(mMainWindow->actionEraserSmall);
+ eraserWidthActions.append(mMainWindow->actionEraserMedium);
+ eraserWidthActions.append(mMainWindow->actionEraserLarge);
+
+ UBToolbarButtonGroup *eraserWidthChoice =
+ new UBToolbarButtonGroup(mMainWindow->boardToolBar, eraserWidthActions);
+
+ mMainWindow->boardToolBar->insertWidget(mMainWindow->actionBackgrounds, eraserWidthChoice);
+
+ connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), eraserWidthChoice, SLOT(displayText(QVariant)));
+ connect(eraserWidthChoice, SIGNAL(activated(int)), UBDrawingController::drawingController(), SLOT(setEraserWidthIndex(int)));
+
+ eraserWidthChoice->displayText(QVariant(settings->appToolBarDisplayText->get().toBool()));
+ eraserWidthChoice->setCurrentIndex(settings->eraserWidthIndex());
+
+ mMainWindow->boardToolBar->insertSeparator(mMainWindow->actionBackgrounds);
+
+ //-----------------------------------------------------------//
+
+ UBApplication::app()->insertSpaceToToolbarBeforeAction(mMainWindow->boardToolBar, mMainWindow->actionBoard);
+ UBApplication::app()->insertSpaceToToolbarBeforeAction(mMainWindow->tutorialToolBar, mMainWindow->actionBoard);
+
+ UBApplication::app()->decorateActionMenu(mMainWindow->actionMenu);
+
+ mMainWindow->actionBoard->setVisible(false);
+
+ mMainWindow->webToolBar->hide();
+ mMainWindow->documentToolBar->hide();
+ mMainWindow->tutorialToolBar->hide();
+
+ connectToolbar();
+ initToolbarTexts();
+}
+
+
+void UBBoardController::setToolCursor(int tool)
+{
+ if (mActiveScene)
+ {
+ mActiveScene->setToolCursor(tool);
+ }
+
+ mControlView->setToolCursor(tool);
+}
+
+
+void UBBoardController::connectToolbar()
+{
+ connect(mMainWindow->actionAdd, SIGNAL(triggered()), this, SLOT(addItem()));
+ connect(mMainWindow->actionNewPage, SIGNAL(triggered()), this, SLOT(addScene()));
+ connect(mMainWindow->actionDuplicatePage, SIGNAL(triggered()), this, SLOT(duplicateScene()));
+
+ connect(mMainWindow->actionClearPage, SIGNAL(triggered()), this, SLOT(clearScene()));
+ connect(mMainWindow->actionEraseItems, SIGNAL(triggered()), this, SLOT(clearSceneItems()));
+ connect(mMainWindow->actionEraseAnnotations, SIGNAL(triggered()), this, SLOT(clearSceneAnnotation()));
+ connect(mMainWindow->actionEraseBackground,SIGNAL(triggered()),this,SLOT(clearSceneBackground()));
+
+ connect(mMainWindow->actionUndo, SIGNAL(triggered()), UBApplication::undoStack, SLOT(undo()));
+ connect(mMainWindow->actionRedo, SIGNAL(triggered()), UBApplication::undoStack, SLOT(redo()));
+ connect(mMainWindow->actionRedo, SIGNAL(triggered()), this, SLOT(startScript()));
+ connect(mMainWindow->actionBack, SIGNAL( triggered()), this, SLOT(previousScene()));
+ connect(mMainWindow->actionForward, SIGNAL(triggered()), this, SLOT(nextScene()));
+ connect(mMainWindow->actionSleep, SIGNAL(triggered()), this, SLOT(stopScript()));
+ connect(mMainWindow->actionSleep, SIGNAL(triggered()), this, SLOT(blackout()));
+ connect(mMainWindow->actionVirtualKeyboard, SIGNAL(triggered(bool)), this, SLOT(showKeyboard(bool)));
+ connect(mMainWindow->actionImportPage, SIGNAL(triggered()), this, SLOT(importPage()));
+}
+
+void UBBoardController::startScript()
+{
+ freezeW3CWidgets(false);
+}
+
+void UBBoardController::stopScript()
+{
+ freezeW3CWidgets(true);
+}
+
+void UBBoardController::initToolbarTexts()
+{
+ QList allToolbarActions;
+
+ allToolbarActions << mMainWindow->boardToolBar->actions();
+ allToolbarActions << mMainWindow->webToolBar->actions();
+ allToolbarActions << mMainWindow->documentToolBar->actions();
+
+ foreach(QAction* action, allToolbarActions)
+ {
+ QString nominalText = action->text();
+ QString shortText = truncate(nominalText, 48);
+ QPair texts(nominalText, shortText);
+
+ mActionTexts.insert(action, texts);
+ }
+}
+
+
+void UBBoardController::setToolbarTexts()
+{
+ bool highResolution = mMainWindow->width() > 1024;
+ QSize iconSize;
+
+ if (highResolution)
+ iconSize = QSize(48, 32);
+ else
+ iconSize = QSize(32, 32);
+
+ mMainWindow->boardToolBar->setIconSize(iconSize);
+ mMainWindow->webToolBar->setIconSize(iconSize);
+ mMainWindow->documentToolBar->setIconSize(iconSize);
+
+ foreach(QAction* action, mActionTexts.keys())
+ {
+ QPair texts = mActionTexts.value(action);
+
+ if (highResolution)
+ action->setText(texts.first);
+ else
+ {
+ action->setText(texts.second);
+ }
+
+ action->setToolTip(texts.first);
+ }
+}
+
+
+QString UBBoardController::truncate(QString text, int maxWidth)
+{
+ QFontMetricsF fontMetrics(mMainWindow->font());
+ return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
+}
+
+
+void UBBoardController::stylusToolDoubleClicked(int tool)
+{
+ if (tool == UBStylusTool::ZoomIn || tool == UBStylusTool::ZoomOut)
+ {
+ zoomRestore();
+ }
+ else if (tool == UBStylusTool::Hand)
+ {
+ centerRestore();
+ }
+}
+
+
+
+void UBBoardController::addScene()
+{
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+
+ UBDocumentContainer::addPage(mActiveSceneIndex + 1);
+
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ setActiveDocumentScene(mActiveSceneIndex + 1);
+ QApplication::restoreOverrideCursor();
+}
+
+void UBBoardController::addScene(UBGraphicsScene* scene, bool replaceActiveIfEmpty)
+{
+ if (scene)
+ {
+ UBGraphicsScene* clone = scene->sceneDeepCopy();
+
+ if (scene->document() && (scene->document() != selectedDocument()))
+ {
+ foreach(QUrl relativeFile, scene->relativeDependencies())
+ {
+ QString source = scene->document()->persistencePath() + "/" + relativeFile.toString();
+ QString target = selectedDocument()->persistencePath() + "/" + relativeFile.toString();
+
+ QFileInfo fi(target);
+ QDir d = fi.dir();
+
+ d.mkpath(d.absolutePath());
+ QFile::copy(source, target);
+ }
+ }
+
+ if (replaceActiveIfEmpty && mActiveScene->isEmpty())
+ {
+ setActiveDocumentScene(mActiveSceneIndex);
+ }
+ else
+ {
+ persistCurrentScene();
+ UBPersistenceManager::persistenceManager()->insertDocumentSceneAt(selectedDocument(), clone, mActiveSceneIndex + 1);
+ setActiveDocumentScene(mActiveSceneIndex + 1);
+ }
+
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+ }
+}
+
+
+void UBBoardController::addScene(UBDocumentProxy* proxy, int sceneIndex, bool replaceActiveIfEmpty)
+{
+ UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(proxy, sceneIndex);
+
+ if (scene)
+ {
+ addScene(scene, replaceActiveIfEmpty);
+ }
+}
+
+void UBBoardController::duplicateScene(int nIndex)
+{
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+
+ QList scIndexes;
+ scIndexes << nIndex;
+ duplicatePages(scIndexes);
+ insertThumbPage(nIndex);
+ emit documentThumbnailsUpdated(this);
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ setActiveDocumentScene(nIndex + 1);
+ QApplication::restoreOverrideCursor();
+
+ emit pageChanged();
+}
+
+void UBBoardController::duplicateScene()
+{
+ if (UBApplication::applicationController->displayMode() != UBApplicationController::Board)
+ return;
+ duplicateScene(mActiveSceneIndex);
+}
+
+UBGraphicsItem *UBBoardController::duplicateItem(UBItem *item, bool bAsync)
+{
+ if (!item)
+ return NULL;
+
+ UBGraphicsItem *retItem = NULL;
+
+ mLastCreatedItem = NULL;
+
+ QUrl sourceUrl;
+ QByteArray pData;
+
+ //common parameters for any item
+ QPointF itemPos;
+ QSizeF itemSize;
+
+ QGraphicsItem *commonItem = dynamic_cast(item);
+ if (commonItem)
+ {
+ qreal shifting = UBSettings::settings()->objectFrameWidth;
+ itemPos = commonItem->pos() + QPointF(shifting,shifting);
+ itemSize = commonItem->boundingRect().size();
+ commonItem->setSelected(false);
+ }
+
+ UBMimeType::Enum itemMimeType;
+
+ QString srcFile = item->sourceUrl().toLocalFile();
+ if (srcFile.isEmpty())
+ srcFile = item->sourceUrl().toString();
+
+ QString contentTypeHeader;
+ if (!srcFile.isEmpty())
+ contentTypeHeader = UBFileSystemUtils::mimeTypeFromFileName(srcFile);
+
+ if(NULL != qgraphicsitem_cast(commonItem))
+ itemMimeType = UBMimeType::Group;
+ else
+ itemMimeType = UBFileSystemUtils::mimeTypeFromString(contentTypeHeader);
+
+ switch(static_cast(itemMimeType))
+ {
+ case UBMimeType::AppleWidget:
+ case UBMimeType::W3CWidget:
+ {
+ UBGraphicsWidgetItem *witem = dynamic_cast(item);
+ if (witem)
+ {
+ sourceUrl = witem->getOwnFolder();
+ }
+ }break;
+
+ case UBMimeType::Video:
+ case UBMimeType::Audio:
+ {
+ UBGraphicsMediaItem *mitem = dynamic_cast(item);
+ if (mitem)
+ {
+ sourceUrl = mitem->mediaFileUrl();
+ if (bAsync)
+ {
+ downloadURL(sourceUrl, srcFile, itemPos, QSize(itemSize.width(), itemSize.height()), false, false);
+ return NULL; // async operation
+ }
+ }
+ }break;
+
+ case UBMimeType::VectorImage:
+ {
+ UBGraphicsSvgItem *viitem = dynamic_cast(item);
+ if (viitem)
+ {
+ pData = viitem->fileData();
+ sourceUrl = item->sourceUrl();
+ }
+ }break;
+
+ case UBMimeType::RasterImage:
+ {
+ UBGraphicsPixmapItem *pixitem = dynamic_cast(item);
+ if (pixitem)
+ {
+ QBuffer buffer(&pData);
+ buffer.open(QIODevice::WriteOnly);
+ QString format = UBFileSystemUtils::extension(item->sourceUrl().toLocalFile());
+ pixitem->pixmap().save(&buffer, format.toLatin1());
+ }
+ }break;
+
+ case UBMimeType::Group:
+ {
+ UBGraphicsGroupContainerItem* groupItem = dynamic_cast(item);
+ UBGraphicsGroupContainerItem* duplicatedGroup = NULL;
+
+ QList duplicatedItems;
+ QList children = groupItem->childItems();
+
+ mActiveScene->setURStackEnable(false);
+ foreach(QGraphicsItem* pIt, children){
+ UBItem* pItem = dynamic_cast(pIt);
+ if(pItem){ // we diong sync duplication of all childs.
+ QGraphicsItem * itemToGroup = dynamic_cast(duplicateItem(pItem, false));
+ if (itemToGroup)
+ duplicatedItems.append(itemToGroup);
+ }
+ }
+ duplicatedGroup = mActiveScene->createGroup(duplicatedItems);
+ duplicatedGroup->setTransform(groupItem->transform());
+ groupItem->setSelected(false);
+
+ retItem = dynamic_cast(duplicatedGroup);
+
+ QGraphicsItem * itemToAdd = dynamic_cast(retItem);
+ if (itemToAdd)
+ {
+ mActiveScene->addItem(itemToAdd);
+ itemToAdd->setSelected(true);
+ }
+ mActiveScene->setURStackEnable(true);
+ }break;
+
+ case UBMimeType::UNKNOWN:
+ {
+ QGraphicsItem *gitem = dynamic_cast(item->deepCopy());
+ if (gitem)
+ {
+ mActiveScene->addItem(gitem);
+ gitem->setPos(itemPos);
+ mLastCreatedItem = gitem;
+ gitem->setSelected(true);
+ }
+ retItem = dynamic_cast(gitem);
+ }break;
+ }
+
+ if (retItem)
+ {
+ QGraphicsItem *graphicsRetItem = dynamic_cast(retItem);
+ if (mActiveScene->isURStackIsEnabled()) { //should be deleted after scene own undo stack implemented
+ UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(mActiveScene, 0, graphicsRetItem);
+ UBApplication::undoStack->push(uc);
+ }
+ return retItem;
+ }
+
+ UBItem *createdItem = downloadFinished(true, sourceUrl, srcFile, contentTypeHeader, pData, itemPos, QSize(itemSize.width(), itemSize.height()), false);
+ if (createdItem)
+ {
+ createdItem->setSourceUrl(item->sourceUrl());
+ item->copyItemParameters(createdItem);
+
+ QGraphicsItem *createdGitem = dynamic_cast(createdItem);
+ if (createdGitem)
+ createdGitem->setPos(itemPos);
+ mLastCreatedItem = dynamic_cast(createdItem);
+ mLastCreatedItem->setSelected(true);
+
+ retItem = dynamic_cast(createdItem);
+ }
+
+ return retItem;
+}
+
+void UBBoardController::deleteScene(int nIndex)
+{
+ if (selectedDocument()->pageCount()>=2)
+ {
+ mDeletingSceneIndex = nIndex;
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+ showMessage(tr("Delete page %1 from document").arg(nIndex), true);
+
+ QList scIndexes;
+ scIndexes << nIndex;
+ deletePages(scIndexes);
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ if (nIndex >= pageCount())
+ nIndex = pageCount()-1;
+ setActiveDocumentScene(nIndex);
+ showMessage(tr("Page %1 deleted").arg(nIndex));
+ QApplication::restoreOverrideCursor();
+ mDeletingSceneIndex = -1;
+ }
+}
+
+
+void UBBoardController::clearScene()
+{
+ if (mActiveScene)
+ {
+ freezeW3CWidgets(true);
+ mActiveScene->clearContent(UBGraphicsScene::clearItemsAndAnnotations);
+ updateActionStates();
+ }
+}
+
+
+void UBBoardController::clearSceneItems()
+{
+ if (mActiveScene)
+ {
+ freezeW3CWidgets(true);
+ mActiveScene->clearContent(UBGraphicsScene::clearItems);
+ updateActionStates();
+ }
+}
+
+
+void UBBoardController::clearSceneAnnotation()
+{
+ if (mActiveScene)
+ {
+ mActiveScene->clearContent(UBGraphicsScene::clearAnnotations);
+ updateActionStates();
+ }
+}
+
+void UBBoardController::clearSceneBackground()
+{
+ if (mActiveScene)
+ {
+ mActiveScene->clearContent(UBGraphicsScene::clearBackground);
+ updateActionStates();
+ }
+}
+
+void UBBoardController::showDocumentsDialog()
+{
+ if (selectedDocument())
+ persistCurrentScene();
+
+ UBApplication::mainWindow->actionLibrary->setChecked(false);
+
+}
+
+void UBBoardController::libraryDialogClosed(int ret)
+{
+ Q_UNUSED(ret);
+
+ mMainWindow->actionLibrary->setChecked(false);
+}
+
+
+void UBBoardController::blackout()
+{
+ UBApplication::applicationController->blackout();
+}
+
+
+void UBBoardController::showKeyboard(bool show)
+{
+ if(show)
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ mPaletteManager->showVirtualKeyboard(show);
+}
+
+
+void UBBoardController::zoomIn(QPointF scenePoint)
+{
+ if (mControlView->transform().m11() > UB_MAX_ZOOM)
+ {
+ qApp->beep();
+ return;
+ }
+ zoom(mZoomFactor, scenePoint);
+}
+
+
+void UBBoardController::zoomOut(QPointF scenePoint)
+{
+ if ((mControlView->horizontalScrollBar()->maximum() == 0) && (mControlView->verticalScrollBar()->maximum() == 0))
+ {
+ // Do not zoom out if we reached the maximum
+ qApp->beep();
+ return;
+ }
+
+ qreal newZoomFactor = 1 / mZoomFactor;
+
+ zoom(newZoomFactor, scenePoint);
+}
+
+
+void UBBoardController::zoomRestore()
+{
+ QTransform tr;
+
+ tr.scale(mSystemScaleFactor, mSystemScaleFactor);
+ mControlView->setTransform(tr);
+
+ centerRestore();
+
+ foreach(QGraphicsItem *gi, mActiveScene->selectedItems ())
+ {
+ //force item to redraw the frame (for the anti scale calculation)
+ gi->setSelected(false);
+ gi->setSelected(true);
+ }
+
+ emit zoomChanged(1.0);
+}
+
+
+void UBBoardController::centerRestore()
+{
+ centerOn(QPointF(0,0));
+}
+
+
+void UBBoardController::centerOn(QPointF scenePoint)
+{
+ mControlView->centerOn(scenePoint);
+ UBApplication::applicationController->adjustDisplayView();
+}
+
+
+void UBBoardController::zoom(const qreal ratio, QPointF scenePoint)
+{
+
+ QPointF viewCenter = mControlView->mapToScene(QRect(0, 0, mControlView->width(), mControlView->height()).center());
+ QPointF offset = scenePoint - viewCenter;
+ QPointF scalledOffset = offset / ratio;
+
+ qreal currentZoom = ratio * mControlView->viewportTransform().m11() / mSystemScaleFactor;
+
+ qreal usedRatio = ratio;
+ if (currentZoom > UB_MAX_ZOOM)
+ {
+ currentZoom = UB_MAX_ZOOM;
+ usedRatio = currentZoom * mSystemScaleFactor / mControlView->viewportTransform().m11();
+ }
+
+ mControlView->scale(usedRatio, usedRatio);
+
+ QPointF newCenter = scenePoint - scalledOffset;
+
+ mControlView->centerOn(newCenter);
+
+ emit zoomChanged(currentZoom);
+ UBApplication::applicationController->adjustDisplayView();
+
+ emit controlViewportChanged();
+ mActiveScene->setBackgroundZoomFactor(mControlView->transform().m11());
+}
+
+
+void UBBoardController::handScroll(qreal dx, qreal dy)
+{
+ mControlView->translate(dx, dy);
+
+ UBApplication::applicationController->adjustDisplayView();
+
+ emit controlViewportChanged();
+}
+
+
+void UBBoardController::previousScene()
+{
+ if (mActiveSceneIndex > 0)
+ {
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+ setActiveDocumentScene(mActiveSceneIndex - 1);
+ QApplication::restoreOverrideCursor();
+ }
+
+ updateActionStates();
+ emit pageChanged();
+}
+
+
+void UBBoardController::nextScene()
+{
+ if (mActiveSceneIndex < selectedDocument()->pageCount() - 1)
+ {
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+ setActiveDocumentScene(mActiveSceneIndex + 1);
+ QApplication::restoreOverrideCursor();
+ }
+
+ updateActionStates();
+ emit pageChanged();
+}
+
+
+void UBBoardController::firstScene()
+{
+ if (mActiveSceneIndex > 0)
+ {
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+ setActiveDocumentScene(0);
+ QApplication::restoreOverrideCursor();
+ }
+
+ updateActionStates();
+ emit pageChanged();
+}
+
+
+void UBBoardController::lastScene()
+{
+ if (mActiveSceneIndex < selectedDocument()->pageCount() - 1)
+ {
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ persistCurrentScene();
+ setActiveDocumentScene(selectedDocument()->pageCount() - 1);
+ QApplication::restoreOverrideCursor();
+ }
+
+ updateActionStates();
+ emit pageChanged();
+}
+
+void UBBoardController::groupButtonClicked()
+{
+ QAction *groupAction = UBApplication::mainWindow->actionGroupItems;
+ QList selItems = activeScene()->selectedItems();
+ if (!selItems.count()) {
+ qDebug() << "Got grouping request when there is no any selected item on the scene";
+ return;
+ }
+
+ if (groupAction->text() == mActionGroupText) { //The only way to get information from item, considering using smth else
+ UBGraphicsGroupContainerItem *groupItem = activeScene()->createGroup(selItems);
+ groupItem->setSelected(true);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+
+ }
+ else if (groupAction->text() == mActionUngroupText) {
+ //Considering one selected item and it's a group
+ if (selItems.count() > 1)
+ {
+ qDebug() << "can't make sense of ungrouping more then one item. Grouping action should be performed for that purpose";
+ return;
+ }
+ UBGraphicsGroupContainerItem *currentGroup = dynamic_cast(selItems.first());
+ if (currentGroup) {
+ currentGroup->destroy();
+ }
+ }
+}
+
+void UBBoardController::downloadURL(const QUrl& url, QString contentSourceUrl, const QPointF& pPos, const QSize& pSize, bool isBackground, bool internalData)
+{
+ qDebug() << "something has been dropped on the board! Url is: " << url.toString();
+ QString sUrl = url.toString();
+
+ QGraphicsItem *oldBackgroundObject = NULL;
+ if (isBackground)
+ oldBackgroundObject = mActiveScene->backgroundObject();
+
+ if(sUrl.startsWith("uniboardTool://"))
+ {
+ downloadFinished(true, url, QUrl(), "application/vnd.mnemis-uniboard-tool", QByteArray(), pPos, pSize, isBackground);
+ }
+ else if (sUrl.startsWith("file://") || sUrl.startsWith("/"))
+ {
+ QUrl formedUrl = sUrl.startsWith("file://") ? url : QUrl::fromLocalFile(sUrl);
+ QString fileName = formedUrl.toLocalFile();
+ QString contentType = UBFileSystemUtils::mimeTypeFromFileName(fileName);
+
+ bool shouldLoadFileData =
+ contentType.startsWith("image")
+ || contentType.startsWith("application/widget")
+ || contentType.startsWith("application/vnd.apple-widget");
+
+ if (shouldLoadFileData)
+ {
+ QFile file(fileName);
+ file.open(QIODevice::ReadOnly);
+ downloadFinished(true, formedUrl, QUrl(), contentType, file.readAll(), pPos, pSize, isBackground, internalData);
+ file.close();
+ }
+ else
+ {
+ // media items should be copyed in separate thread
+
+ sDownloadFileDesc desc;
+ desc.modal = false;
+ desc.srcUrl = sUrl;
+ desc.originalSrcUrl = contentSourceUrl;
+ desc.currentSize = 0;
+ desc.name = QFileInfo(url.toString()).fileName();
+ desc.totalSize = 0; // The total size will be retrieved during the download
+ desc.pos = pPos;
+ desc.size = pSize;
+ desc.isBackground = isBackground;
+
+ UBDownloadManager::downloadManager()->addFileToDownload(desc);
+ }
+ }
+ else
+ {
+ QString urlString = url.toString();
+ int parametersStringPosition = urlString.indexOf("?");
+ if(parametersStringPosition != -1)
+ urlString = urlString.left(parametersStringPosition);
+
+ // When we fall there, it means that we are dropping something from the web to the board
+ sDownloadFileDesc desc;
+ desc.modal = true;
+ desc.srcUrl = urlString;
+ desc.currentSize = 0;
+ desc.name = QFileInfo(urlString).fileName();
+ desc.totalSize = 0; // The total size will be retrieved during the download
+ desc.pos = pPos;
+ desc.size = pSize;
+ desc.isBackground = isBackground;
+
+ UBDownloadManager::downloadManager()->addFileToDownload(desc);
+ }
+
+ if (isBackground && oldBackgroundObject != mActiveScene->backgroundObject())
+ {
+ if (mActiveScene->isURStackIsEnabled()) { //should be deleted after scene own undo stack implemented
+ UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(mActiveScene, oldBackgroundObject, mActiveScene->backgroundObject());
+ UBApplication::undoStack->push(uc);
+ }
+ }
+
+
+}
+
+
+UBItem *UBBoardController::downloadFinished(bool pSuccess, QUrl sourceUrl, QUrl contentUrl, QString pContentTypeHeader,
+ QByteArray pData, QPointF pPos, QSize pSize,
+ bool isBackground, bool internalData)
+{
+ QString mimeType = pContentTypeHeader;
+
+ // In some cases "image/jpeg;charset=" is retourned by the drag-n-drop. That is
+ // why we will check if an ; exists and take the first part (the standard allows this kind of mimetype)
+ if(mimeType.isEmpty())
+ mimeType = UBFileSystemUtils::mimeTypeFromFileName(sourceUrl.toString());
+
+ int position=mimeType.indexOf(";");
+ if(position != -1)
+ mimeType=mimeType.left(position);
+
+ UBMimeType::Enum itemMimeType = UBFileSystemUtils::mimeTypeFromString(mimeType);
+
+ if (!pSuccess)
+ {
+ showMessage(tr("Downloading content %1 failed").arg(sourceUrl.toString()));
+ return NULL;
+ }
+
+
+ mActiveScene->deselectAllItems();
+
+ if (!sourceUrl.toString().startsWith("file://") && !sourceUrl.toString().startsWith("uniboardTool://"))
+ showMessage(tr("Download finished"));
+
+ if (UBMimeType::RasterImage == itemMimeType)
+ {
+
+ qDebug() << "accepting mime type" << mimeType << "as raster image";
+
+
+ QPixmap pix;
+ if(pData.length() == 0){
+ pix.load(sourceUrl.toLocalFile());
+ }
+ else{
+ QImage img;
+ img.loadFromData(pData);
+ pix = QPixmap::fromImage(img);
+ }
+
+ UBGraphicsPixmapItem* pixItem = mActiveScene->addPixmap(pix, NULL, pPos, 1.);
+ pixItem->setSourceUrl(sourceUrl);
+
+ if (isBackground)
+ {
+ mActiveScene->setAsBackgroundObject(pixItem, true);
+ }
+ else
+ {
+ mActiveScene->scaleToFitDocumentSize(pixItem, true, UBSettings::objectInControlViewMargin);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ pixItem->setSelected(true);
+ }
+
+ return pixItem;
+ }
+ else if (UBMimeType::VectorImage == itemMimeType)
+ {
+ qDebug() << "accepting mime type" << mimeType << "as vecto image";
+
+ UBGraphicsSvgItem* svgItem = mActiveScene->addSvg(sourceUrl, pPos, pData);
+ svgItem->setSourceUrl(sourceUrl);
+
+ if (isBackground)
+ {
+ mActiveScene->setAsBackgroundObject(svgItem);
+ }
+ else
+ {
+ mActiveScene->scaleToFitDocumentSize(svgItem, true, UBSettings::objectInControlViewMargin);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ svgItem->setSelected(true);
+ }
+
+ return svgItem;
+ }
+ else if (UBMimeType::AppleWidget == itemMimeType) //mime type invented by us :-(
+ {
+ qDebug() << "accepting mime type" << mimeType << "as Apple widget";
+
+ QUrl widgetUrl = sourceUrl;
+
+ if (pData.length() > 0)
+ {
+ widgetUrl = expandWidgetToTempDir(pData, "wdgt");
+ }
+
+ UBGraphicsWidgetItem* appleWidgetItem = mActiveScene->addAppleWidget(widgetUrl, pPos);
+
+ appleWidgetItem->setSourceUrl(sourceUrl);
+
+ if (isBackground)
+ {
+ mActiveScene->setAsBackgroundObject(appleWidgetItem);
+ }
+ else
+ {
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+
+ return appleWidgetItem;
+ }
+ else if (UBMimeType::W3CWidget == itemMimeType)
+ {
+ qDebug() << "accepting mime type" << mimeType << "as W3C widget";
+ QUrl widgetUrl = sourceUrl;
+
+ if (pData.length() > 0)
+ {
+ widgetUrl = expandWidgetToTempDir(pData);
+ }
+
+ UBGraphicsWidgetItem *w3cWidgetItem = addW3cWidget(widgetUrl, pPos);
+
+ if (isBackground)
+ {
+ mActiveScene->setAsBackgroundObject(w3cWidgetItem);
+ }
+ else
+ {
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+
+ return w3cWidgetItem;
+ }
+ else if (UBMimeType::Video == itemMimeType)
+ {
+ qDebug() << "accepting mime type" << mimeType << "as video";
+
+ UBGraphicsMediaItem *mediaVideoItem = 0;
+ QUuid uuid = QUuid::createUuid();
+ if (pData.length() > 0)
+ {
+ QString destFile;
+ bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
+ sourceUrl.toString(),
+ UBPersistenceManager::videoDirectory,
+ uuid,
+ destFile,
+ &pData);
+ if (!b)
+ {
+ showMessage(tr("Add file operation failed: file copying error"));
+ return NULL;
+ }
+
+ QUrl url = QUrl::fromLocalFile(destFile);
+
+ mediaVideoItem = mActiveScene->addMedia(url, false, pPos);
+ }
+ else
+ {
+ qDebug() << sourceUrl.toString();
+ mediaVideoItem = addVideo(sourceUrl, false, pPos, true);
+ }
+
+ if(mediaVideoItem){
+ if (contentUrl.isEmpty())
+ mediaVideoItem->setSourceUrl(sourceUrl);
+ else
+ mediaVideoItem->setSourceUrl(contentUrl);
+ mediaVideoItem->setUuid(uuid);
+ connect(this, SIGNAL(activeSceneChanged()), mediaVideoItem, SLOT(activeSceneChanged()));
+ }
+
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+
+ return mediaVideoItem;
+ }
+ else if (UBMimeType::Audio == itemMimeType)
+ {
+ qDebug() << "accepting mime type" << mimeType << "as audio";
+
+ UBGraphicsMediaItem *audioMediaItem = 0;
+
+ QUuid uuid = QUuid::createUuid();
+ if (pData.length() > 0)
+ {
+ QString destFile;
+ bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
+ sourceUrl.toString(),
+ UBPersistenceManager::audioDirectory,
+ uuid,
+ destFile,
+ &pData);
+ if (!b)
+ {
+ showMessage(tr("Add file operation failed: file copying error"));
+ return NULL;
+ }
+
+ QUrl url = QUrl::fromLocalFile(destFile);
+
+ audioMediaItem = mActiveScene->addMedia(url, false, pPos);
+ }
+ else
+ {
+ audioMediaItem = addAudio(sourceUrl, false, pPos, true);
+ }
+
+ if(audioMediaItem){
+ if (contentUrl.isEmpty())
+ audioMediaItem->setSourceUrl(sourceUrl);
+ else
+ audioMediaItem->setSourceUrl(contentUrl);
+ audioMediaItem->setUuid(uuid);
+ connect(this, SIGNAL(activeSceneChanged()), audioMediaItem, SLOT(activeSceneChanged()));
+ }
+
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+
+ return audioMediaItem;
+ }
+
+ else if (UBMimeType::Flash == itemMimeType)
+ {
+
+ qDebug() << "accepting mime type" << mimeType << "as flash";
+
+ QString sUrl = sourceUrl.toString();
+
+ if (sUrl.startsWith("file://") || sUrl.startsWith("/"))
+ {
+ sUrl = sourceUrl.toLocalFile();
+ }
+
+ QTemporaryFile* eduMediaFile = 0;
+
+ if (sUrl.toLower().contains("edumedia-sciences.com"))
+ {
+ eduMediaFile = new QTemporaryFile("XXXXXX.swf");
+ if (eduMediaFile->open())
+ {
+ eduMediaFile->write(pData);
+ QFileInfo fi(*eduMediaFile);
+ sUrl = fi.absoluteFilePath();
+ }
+ }
+
+ QSize size;
+
+ if (pSize.height() > 0 && pSize.width() > 0)
+ size = pSize;
+ else
+ size = mActiveScene->nominalSize() * .8;
+
+ Q_UNUSED(internalData)
+
+ QString widgetUrl = UBGraphicsW3CWidgetItem::createNPAPIWrapper(sUrl, mimeType, size);
+ emit npapiWidgetCreated(widgetUrl);
+
+ if (widgetUrl.length() > 0)
+ {
+ UBGraphicsWidgetItem *widgetItem = mActiveScene->addW3CWidget(QUrl::fromLocalFile(widgetUrl), pPos);
+ widgetItem->setUuid(QUuid::createUuid());
+ widgetItem->setSourceUrl(QUrl::fromLocalFile(widgetUrl));
+
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+
+ return widgetItem;
+ }
+
+ if (eduMediaFile)
+ delete eduMediaFile;
+
+ }
+ else if (UBMimeType::PDF == itemMimeType)
+ {
+ qDebug() << "accepting mime type" << mimeType << "as PDF";
+ qDebug() << "pdf data length: " << pData.size();
+ qDebug() << "sourceurl : " + sourceUrl.toString();
+ int result = 0;
+ if(!sourceUrl.isEmpty()){
+ QStringList fileNames;
+ fileNames << sourceUrl.toLocalFile();
+ result = UBDocumentManager::documentManager()->addFilesToDocument(selectedDocument(), fileNames);
+ }
+ else if(pData.size()){
+ QTemporaryFile pdfFile("XXXXXX.pdf");
+ if (pdfFile.open())
+ {
+ pdfFile.write(pData);
+ QStringList fileNames;
+ fileNames << pdfFile.fileName();
+ result = UBDocumentManager::documentManager()->addFilesToDocument(selectedDocument(), fileNames);
+ pdfFile.close();
+ }
+ }
+
+ if (result){
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+ }
+ }
+ else if (UBMimeType::UniboardTool == itemMimeType)
+ {
+ qDebug() << "accepting mime type" << mimeType << "as Uniboard Tool";
+
+ if (sourceUrl.toString() == UBToolsManager::manager()->compass.id)
+ {
+ mActiveScene->addCompass(pPos);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else if (sourceUrl.toString() == UBToolsManager::manager()->ruler.id)
+ {
+ mActiveScene->addRuler(pPos);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else if (sourceUrl.toString() == UBToolsManager::manager()->protractor.id)
+ {
+ mActiveScene->addProtractor(pPos);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else if (sourceUrl.toString() == UBToolsManager::manager()->triangle.id)
+ {
+ mActiveScene->addTriangle(pPos);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else if (sourceUrl.toString() == UBToolsManager::manager()->cache.id)
+ {
+ mActiveScene->addCache();
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else if (sourceUrl.toString() == UBToolsManager::manager()->magnifier.id)
+ {
+ UBMagnifierParams params;
+ params.x = controlContainer()->geometry().width() / 2;
+ params.y = controlContainer()->geometry().height() / 2;
+ params.zoom = 2;
+ params.sizePercentFromScene = 20;
+ mActiveScene->addMagnifier(params);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else if (sourceUrl.toString() == UBToolsManager::manager()->mask.id)
+ {
+ mActiveScene->addMask(pPos);
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+ else
+ {
+ showMessage(tr("Unknown tool type %1").arg(sourceUrl.toString()));
+ }
+ }
+ else if (sourceUrl.toString().contains("edumedia-sciences.com"))
+ {
+ qDebug() << "accepting url " << sourceUrl.toString() << "as eduMedia content";
+
+ QTemporaryFile eduMediaZipFile("XXXXXX.edumedia");
+ if (eduMediaZipFile.open())
+ {
+ eduMediaZipFile.write(pData);
+ eduMediaZipFile.close();
+
+ QString tempDir = UBFileSystemUtils::createTempDir("uniboard-edumedia");
+
+ UBFileSystemUtils::expandZipToDir(eduMediaZipFile, tempDir);
+
+ QDir appDir(tempDir);
+
+ foreach(QString subDirName, appDir.entryList(QDir::AllDirs))
+ {
+ QDir subDir(tempDir + "/" + subDirName + "/contents");
+
+ foreach(QString fileName, subDir.entryList(QDir::Files))
+ {
+ if (fileName.toLower().endsWith(".swf"))
+ {
+ QString swfFile = tempDir + "/" + subDirName + "/contents/" + fileName;
+
+ QSize size;
+
+ if (pSize.height() > 0 && pSize.width() > 0)
+ size = pSize;
+ else
+ size = mActiveScene->nominalSize() * .8;
+
+ QString widgetUrl = UBGraphicsW3CWidgetItem::createNPAPIWrapper(swfFile, "application/x-shockwave-flash", size);
+
+ if (widgetUrl.length() > 0)
+ {
+ UBGraphicsWidgetItem *widgetItem = mActiveScene->addW3CWidget(QUrl::fromLocalFile(widgetUrl), pPos);
+
+ widgetItem->setSourceUrl(sourceUrl);
+
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+
+ return widgetItem;
+ }
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ showMessage(tr("Unknown content type %1").arg(pContentTypeHeader));
+ qWarning() << "ignoring mime type" << pContentTypeHeader ;
+ }
+
+ return NULL;
+}
+
+void UBBoardController::setActiveDocumentScene(int pSceneIndex)
+{
+ setActiveDocumentScene(selectedDocument(), pSceneIndex);
+}
+
+void UBBoardController::setActiveDocumentScene(UBDocumentProxy* pDocumentProxy, const int pSceneIndex, bool forceReload)
+{
+ saveViewState();
+
+ bool documentChange = selectedDocument() != pDocumentProxy;
+
+ int index = pSceneIndex;
+ int sceneCount = pDocumentProxy->pageCount();
+ if (index >= sceneCount && sceneCount > 0)
+ index = sceneCount - 1;
+
+ UBGraphicsScene* targetScene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pDocumentProxy, index);
+
+ bool sceneChange = targetScene != mActiveScene;
+
+ if (targetScene)
+ {
+ freezeW3CWidgets(true);
+
+ persistCurrentScene();
+
+ ClearUndoStack();
+
+ mActiveScene = targetScene;
+ mActiveSceneIndex = index;
+ setDocument(pDocumentProxy, forceReload);
+
+ updateSystemScaleFactor();
+
+ mControlView->setScene(mActiveScene);
+ mDisplayView->setScene(mActiveScene);
+ mActiveScene->setBackgroundZoomFactor(mControlView->transform().m11());
+ pDocumentProxy->setDefaultDocumentSize(mActiveScene->nominalSize());
+ updatePageSizeState();
+
+ adjustDisplayViews();
+
+ UBSettings::settings()->setDarkBackground(mActiveScene->isDarkBackground());
+ UBSettings::settings()->setCrossedBackground(mActiveScene->isCrossedBackground());
+
+ freezeW3CWidgets(false);
+ }
+
+ selectionChanged();
+
+ updateBackgroundActionsState(mActiveScene->isDarkBackground(), mActiveScene->isCrossedBackground());
+ updateBackgroundState();
+
+ if(documentChange)
+ {
+ UBGraphicsTextItem::lastUsedTextColor = QColor();
+ }
+
+
+ if (sceneChange)
+ {
+ emit activeSceneChanged();
+ emit pageChanged();
+ }
+}
+
+
+void UBBoardController::moveSceneToIndex(int source, int target)
+{
+ if (selectedDocument())
+ {
+
+ persistCurrentScene();
+
+ UBDocumentContainer::movePageToIndex(source, target);
+
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+ UBMetadataDcSubsetAdaptor::persist(selectedDocument());
+ mMovingSceneIndex = source;
+ setActiveDocumentScene(target);
+ mMovingSceneIndex = -1;
+
+ }
+}
+
+void UBBoardController::ClearUndoStack()
+{
+// The code has been removed because it leads to a strange error and because the final goal has never been
+// reached on tests and sound a little bit strange.
+// Strange error: item->scene() crashes the application because item doesn't implement scene() method. I'm
+// not able to give all the steps to reproduce this error sistematically but is quite frequent (~ twice per utilisation hours)
+// strange goal: if item is on the undocommand, the item->scene() is null and the item is not on the deleted scene item list then
+// then it's deleted.
+
+ // QSet uniqueItems;
+// // go through all stack command
+// for(int i = 0; i < UBApplication::undoStack->count(); i++)
+// {
+
+// UBAbstractUndoCommand *abstractCmd = (UBAbstractUndoCommand*)UBApplication::undoStack->command(i);
+// if(abstractCmd->getType() != UBAbstractUndoCommand::undotype_GRAPHICITEM)
+// continue;
+
+// UBGraphicsItemUndoCommand *cmd = (UBGraphicsItemUndoCommand*)UBApplication::undoStack->command(i);
+
+// // go through all added and removed objects, for create list of unique objects
+// // grouped items will be deleted by groups, so we don't need do delete that items.
+// QSetIterator itAdded(cmd->GetAddedList());
+// while (itAdded.hasNext())
+// {
+// QGraphicsItem* item = itAdded.next();
+// if( !uniqueItems.contains(item) && !(item->parentItem() && UBGraphicsGroupContainerItem::Type == item->parentItem()->type()))
+// uniqueItems.insert(item);
+// }
+
+// QSetIterator itRemoved(cmd->GetRemovedList());
+// while (itRemoved.hasNext())
+// {
+// QGraphicsItem* item = itRemoved.next();
+// if( !uniqueItems.contains(item) && !(item->parentItem() && UBGraphicsGroupContainerItem::Type == item->parentItem()->type()))
+// uniqueItems.insert(item);
+// }
+// }
+
+// // go through all unique items, and check, ot on scene, or not.
+// // if not on scene, than item can be deleted
+
+// QSetIterator itUniq(uniqueItems);
+// while (itUniq.hasNext())
+// {
+// QGraphicsItem* item = itUniq.next();
+// UBGraphicsScene *scene = NULL;
+// if (item->scene()) {
+// scene = dynamic_cast(item->scene());
+// }
+// if(!scene)
+// {
+// if (!mActiveScene->deleteItem(item))
+// delete item;
+// }
+// }
+
+ // clear stack, and command list
+ UBApplication::undoStack->clear();
+
+}
+
+void UBBoardController::adjustDisplayViews()
+{
+ if (UBApplication::applicationController)
+ {
+ UBApplication::applicationController->adjustDisplayView();
+ UBApplication::applicationController->adjustPreviousViews(mActiveSceneIndex, selectedDocument());
+ }
+}
+
+
+void UBBoardController::changeBackground(bool isDark, bool isCrossed)
+{
+ bool currentIsDark = mActiveScene->isDarkBackground();
+ bool currentIsCrossed = mActiveScene->isCrossedBackground();
+
+ if ((isDark != currentIsDark) || (currentIsCrossed != isCrossed))
+ {
+ UBSettings::settings()->setDarkBackground(isDark);
+ UBSettings::settings()->setCrossedBackground(isCrossed);
+
+ mActiveScene->setBackground(isDark, isCrossed);
+
+ updateBackgroundState();
+
+ emit backgroundChanged();
+ }
+}
+
+void UBBoardController::boardViewResized(QResizeEvent* event)
+{
+ Q_UNUSED(event);
+
+ int innerMargin = UBSettings::boardMargin;
+ int userHeight = mControlContainer->height() - (2 * innerMargin);
+
+ mMessageWindow->move(innerMargin, innerMargin + userHeight - mMessageWindow->height());
+ mMessageWindow->adjustSizeAndPosition();
+
+ UBApplication::applicationController->initViewState(
+ mControlView->horizontalScrollBar()->value(),
+ mControlView->verticalScrollBar()->value());
+
+ updateSystemScaleFactor();
+
+ mControlView->centerOn(0,0);
+
+ if (mDisplayView)
+ mDisplayView->centerOn(0,0);
+
+ mPaletteManager->containerResized();
+
+ UBApplication::boardController->controlView()->scene()->moveMagnifier();
+
+}
+
+
+void UBBoardController::documentWillBeDeleted(UBDocumentProxy* pProxy)
+{
+ if (selectedDocument() == pProxy)
+ {
+ if (!mIsClosing)
+ setActiveDocumentScene(UBPersistenceManager::persistenceManager()->createDocument());
+ }
+}
+
+
+void UBBoardController::showMessage(const QString& message, bool showSpinningWheel)
+{
+ mMessageWindow->showMessage(message, showSpinningWheel);
+}
+
+
+void UBBoardController::hideMessage()
+{
+ mMessageWindow->hideMessage();
+}
+
+
+void UBBoardController::setDisabled(bool disable)
+{
+ mMainWindow->boardToolBar->setDisabled(disable);
+ mControlView->setDisabled(disable);
+}
+
+
+void UBBoardController::selectionChanged()
+{
+ updateActionStates();
+ emit pageSelectionChanged(activeSceneIndex());
+}
+
+
+void UBBoardController::undoRedoStateChange(bool canUndo)
+{
+ Q_UNUSED(canUndo);
+
+ mMainWindow->actionUndo->setEnabled(UBApplication::undoStack->canUndo());
+ mMainWindow->actionRedo->setEnabled(UBApplication::undoStack->canRedo());
+
+ updateActionStates();
+}
+
+
+void UBBoardController::updateActionStates()
+{
+ mMainWindow->actionBack->setEnabled(selectedDocument() && (mActiveSceneIndex > 0));
+ mMainWindow->actionForward->setEnabled(selectedDocument() && (mActiveSceneIndex < selectedDocument()->pageCount() - 1));
+ mMainWindow->actionErase->setEnabled(mActiveScene && !mActiveScene->isEmpty());
+}
+
+
+UBGraphicsScene* UBBoardController::activeScene() const
+{
+ return mActiveScene;
+}
+
+
+int UBBoardController::activeSceneIndex() const
+{
+ return mActiveSceneIndex;
+}
+
+
+void UBBoardController::documentSceneChanged(UBDocumentProxy* pDocumentProxy, int pIndex)
+{
+ Q_UNUSED(pIndex);
+
+ if(selectedDocument() == pDocumentProxy)
+ {
+ setActiveDocumentScene(mActiveSceneIndex);
+ }
+}
+
+void UBBoardController::closing()
+{
+ mIsClosing = true;
+ ClearUndoStack();
+ lastWindowClosed();
+}
+
+void UBBoardController::lastWindowClosed()
+{
+ if (!mCleanupDone)
+ {
+ bool teacherGuideModified = false;
+ if(UBApplication::boardController->paletteManager()->teacherGuideDockWidget())
+ teacherGuideModified = UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified();
+ if (selectedDocument()->pageCount() == 1 && (!mActiveScene || mActiveScene->isEmpty()) && !teacherGuideModified)
+ {
+ UBPersistenceManager::persistenceManager()->deleteDocument(selectedDocument());
+ }
+ else
+ {
+ persistCurrentScene();
+ }
+
+ UBPersistenceManager::persistenceManager()->purgeEmptyDocuments();
+
+ mCleanupDone = true;
+ }
+}
+
+
+
+void UBBoardController::setColorIndex(int pColorIndex)
+{
+ UBDrawingController::drawingController()->setColorIndex(pColorIndex);
+
+ if (UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Marker &&
+ UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Line &&
+ UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Text &&
+ UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Selector)
+ {
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Pen);
+ }
+
+ if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Pen ||
+ UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Line ||
+ UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Text ||
+ UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Selector)
+ {
+ mPenColorOnDarkBackground = UBSettings::settings()->penColors(true).at(pColorIndex);
+ mPenColorOnLightBackground = UBSettings::settings()->penColors(false).at(pColorIndex);
+
+ if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Selector)
+ {
+ // If we are in mode board, then do that
+ if(UBApplication::applicationController->displayMode() == UBApplicationController::Board)
+ {
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Pen);
+ mMainWindow->actionPen->setChecked(true);
+ }
+ }
+
+ emit penColorChanged();
+ }
+ else if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Marker)
+ {
+ mMarkerColorOnDarkBackground = UBSettings::settings()->markerColors(true).at(pColorIndex);
+ mMarkerColorOnLightBackground = UBSettings::settings()->markerColors(false).at(pColorIndex);
+ }
+}
+
+void UBBoardController::colorPaletteChanged()
+{
+ mPenColorOnDarkBackground = UBSettings::settings()->penColor(true);
+ mPenColorOnLightBackground = UBSettings::settings()->penColor(false);
+ mMarkerColorOnDarkBackground = UBSettings::settings()->markerColor(true);
+ mMarkerColorOnLightBackground = UBSettings::settings()->markerColor(false);
+}
+
+
+qreal UBBoardController::currentZoom()
+{
+ if (mControlView)
+ return mControlView->viewportTransform().m11() / mSystemScaleFactor;
+ else
+ return 1.0;
+}
+
+void UBBoardController::removeTool(UBToolWidget* toolWidget)
+{
+ toolWidget->hide();
+
+ delete toolWidget;
+}
+
+void UBBoardController::hide()
+{
+ UBApplication::mainWindow->actionLibrary->setChecked(false);
+}
+
+void UBBoardController::show()
+{
+ UBApplication::mainWindow->actionLibrary->setChecked(false);
+}
+
+void UBBoardController::persistCurrentScene()
+{
+ if(UBPersistenceManager::persistenceManager()
+ && selectedDocument() && mActiveScene && mActiveSceneIndex != mDeletingSceneIndex
+ && (mActiveSceneIndex >= 0) && mActiveSceneIndex != mMovingSceneIndex
+ && (mActiveScene->isModified() || (UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified())))
+ {
+ UBPersistenceManager::persistenceManager()->persistDocumentScene(selectedDocument(), mActiveScene, mActiveSceneIndex);
+ updatePage(mActiveSceneIndex);
+ }
+}
+
+void UBBoardController::updateSystemScaleFactor()
+{
+ qreal newScaleFactor = 1.0;
+
+ if (mActiveScene)
+ {
+ QSize pageNominalSize = mActiveScene->nominalSize();
+ //we're going to keep scale factor untouched if the size is custom
+ QMap sizesMap = UBSettings::settings()->documentSizes;
+ // if(pageNominalSize == sizesMap.value(DocumentSizeRatio::Ratio16_9) || pageNominalSize == sizesMap.value(DocumentSizeRatio::Ratio4_3))
+ {
+ QSize controlSize = controlViewport();
+
+ qreal hFactor = ((qreal)controlSize.width()) / ((qreal)pageNominalSize.width());
+ qreal vFactor = ((qreal)controlSize.height()) / ((qreal)pageNominalSize.height());
+
+ newScaleFactor = qMin(hFactor, vFactor);
+ }
+ }
+
+ if (mSystemScaleFactor != newScaleFactor)
+ {
+ mSystemScaleFactor = newScaleFactor;
+ emit systemScaleFactorChanged(newScaleFactor);
+ }
+
+ UBGraphicsScene::SceneViewState viewState = mActiveScene->viewState();
+
+ QTransform scalingTransform;
+
+ qreal scaleFactor = viewState.zoomFactor * mSystemScaleFactor;
+ scalingTransform.scale(scaleFactor, scaleFactor);
+
+ mControlView->setTransform(scalingTransform);
+ mControlView->horizontalScrollBar()->setValue(viewState.horizontalPosition);
+ mControlView->verticalScrollBar()->setValue(viewState.verticalPostition);
+ mActiveScene->setBackgroundZoomFactor(mControlView->transform().m11());}
+
+
+void UBBoardController::setWidePageSize(bool checked)
+{
+ Q_UNUSED(checked);
+ QSize newSize = UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio16_9);
+
+ if (mActiveScene->nominalSize() != newSize)
+ {
+ UBPageSizeUndoCommand* uc = new UBPageSizeUndoCommand(mActiveScene, mActiveScene->nominalSize(), newSize);
+ UBApplication::undoStack->push(uc);
+
+ setPageSize(newSize);
+ }
+}
+
+
+void UBBoardController::setRegularPageSize(bool checked)
+{
+ Q_UNUSED(checked);
+ QSize newSize = UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio4_3);
+
+ if (mActiveScene->nominalSize() != newSize)
+ {
+ UBPageSizeUndoCommand* uc = new UBPageSizeUndoCommand(mActiveScene, mActiveScene->nominalSize(), newSize);
+ UBApplication::undoStack->push(uc);
+
+ setPageSize(newSize);
+ }
+}
+
+
+void UBBoardController::setPageSize(QSize newSize)
+{
+ if (mActiveScene->nominalSize() != newSize)
+ {
+ mActiveScene->setNominalSize(newSize);
+
+ saveViewState();
+
+ updateSystemScaleFactor();
+ updatePageSizeState();
+ adjustDisplayViews();
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ UBSettings::settings()->pageSize->set(newSize);
+ }
+}
+
+void UBBoardController::notifyCache(bool visible)
+{
+ if(visible)
+ {
+ emit cacheEnabled();
+ }
+ else
+ {
+ emit cacheDisabled();
+ }
+ mCacheWidgetIsEnabled = visible;
+}
+
+void UBBoardController::updatePageSizeState()
+{
+ if (mActiveScene->nominalSize() == UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio16_9))
+ {
+ mMainWindow->actionWidePageSize->setChecked(true);
+ }
+ else if(mActiveScene->nominalSize() == UBSettings::settings()->documentSizes.value(DocumentSizeRatio::Ratio4_3))
+ {
+ mMainWindow->actionRegularPageSize->setChecked(true);
+ }
+ else
+ {
+ mMainWindow->actionCustomPageSize->setChecked(true);
+ }
+}
+
+
+void UBBoardController::saveViewState()
+{
+ if (mActiveScene)
+ {
+ mActiveScene->setViewState(UBGraphicsScene::SceneViewState(currentZoom(),
+ mControlView->horizontalScrollBar()->value(),
+ mControlView->verticalScrollBar()->value()));
+ }
+}
+
+
+void UBBoardController::updateBackgroundState()
+{
+ //adjust background style
+ QString newBackgroundStyle;
+
+ if (mActiveScene && mActiveScene->isDarkBackground())
+ {
+ newBackgroundStyle ="QWidget {background-color: #0E0E0E}";
+ }
+ else
+ {
+ newBackgroundStyle ="QWidget {background-color: #F1F1F1}";
+ }
+}
+
+void UBBoardController::stylusToolChanged(int tool)
+{
+ if (UBPlatformUtils::hasVirtualKeyboard() && mPaletteManager->mKeyboardPalette)
+ {
+ UBStylusTool::Enum eTool = (UBStylusTool::Enum)tool;
+ if(eTool != UBStylusTool::Selector && eTool != UBStylusTool::Text)
+ {
+ if(mPaletteManager->mKeyboardPalette->m_isVisible)
+ UBApplication::mainWindow->actionVirtualKeyboard->activate(QAction::Trigger);
+ }
+ }
+
+ updateBackgroundState();
+}
+
+
+QUrl UBBoardController::expandWidgetToTempDir(const QByteArray& pZipedData, const QString& ext)
+{
+ QUrl widgetUrl;
+ QTemporaryFile tmp;
+
+ if (tmp.open())
+ {
+ tmp.write(pZipedData);
+ tmp.flush();
+ tmp.close();
+
+ QString tmpDir = UBFileSystemUtils::createTempDir() + "." + ext;
+
+ if (UBFileSystemUtils::expandZipToDir(tmp, tmpDir))
+ {
+ widgetUrl = QUrl::fromLocalFile(tmpDir);
+ }
+ }
+
+ return widgetUrl;
+}
+
+
+void UBBoardController::grabScene(const QRectF& pSceneRect)
+{
+ if (mActiveScene)
+ {
+ QImage image(pSceneRect.width(), pSceneRect.height(), QImage::Format_ARGB32);
+ image.fill(Qt::transparent);
+
+ QRectF targetRect(0, 0, pSceneRect.width(), pSceneRect.height());
+ QPainter painter(&image);
+ painter.setRenderHint(QPainter::SmoothPixmapTransform);
+ painter.setRenderHint(QPainter::Antialiasing);
+
+ mActiveScene->setRenderingContext(UBGraphicsScene::NonScreen);
+ mActiveScene->setRenderingQuality(UBItem::RenderingQualityHigh);
+
+ mActiveScene->render(&painter, targetRect, pSceneRect);
+
+ mActiveScene->setRenderingContext(UBGraphicsScene::Screen);
+ mActiveScene->setRenderingQuality(UBItem::RenderingQualityNormal);
+
+ mPaletteManager->addItem(QPixmap::fromImage(image));
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+ }
+}
+
+UBGraphicsMediaItem* UBBoardController::addVideo(const QUrl& pSourceUrl, bool startPlay, const QPointF& pos, bool bUseSource)
+{
+ QUuid uuid = QUuid::createUuid();
+ QUrl concreteUrl = pSourceUrl;
+
+ // media file is not in document folder yet
+ if (!bUseSource)
+ {
+ QString destFile;
+ bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
+ pSourceUrl.toLocalFile(),
+ UBPersistenceManager::videoDirectory,
+ uuid,
+ destFile);
+ if (!b)
+ {
+ showMessage(tr("Add file operation failed: file copying error"));
+ return NULL;
+ }
+ concreteUrl = QUrl::fromLocalFile(destFile);
+ }// else we just use source Url.
+
+
+ UBGraphicsMediaItem* vi = mActiveScene->addMedia(concreteUrl, startPlay, pos);
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ if (vi) {
+ vi->setUuid(uuid);
+ vi->setSourceUrl(pSourceUrl);
+ }
+
+ return vi;
+
+}
+
+UBGraphicsMediaItem* UBBoardController::addAudio(const QUrl& pSourceUrl, bool startPlay, const QPointF& pos, bool bUseSource)
+{
+ QUuid uuid = QUuid::createUuid();
+ QUrl concreteUrl = pSourceUrl;
+
+ // media file is not in document folder yet
+ if (!bUseSource)
+ {
+ QString destFile;
+ bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(selectedDocument(),
+ pSourceUrl.toLocalFile(),
+ UBPersistenceManager::audioDirectory,
+ uuid,
+ destFile);
+ if (!b)
+ {
+ showMessage(tr("Add file operation failed: file copying error"));
+ return NULL;
+ }
+ concreteUrl = QUrl::fromLocalFile(destFile);
+ }// else we just use source Url.
+
+ UBGraphicsMediaItem* ai = mActiveScene->addMedia(concreteUrl, startPlay, pos);
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+
+ if (ai){
+ ai->setUuid(uuid);
+ ai->setSourceUrl(pSourceUrl);
+ }
+
+ return ai;
+
+}
+
+UBGraphicsWidgetItem *UBBoardController::addW3cWidget(const QUrl &pUrl, const QPointF &pos)
+{
+ UBGraphicsWidgetItem* w3cWidgetItem = 0;
+
+ QUuid uuid = QUuid::createUuid();
+
+ QString destPath;
+ if (!UBPersistenceManager::persistenceManager()->addGraphicsWidgteToDocument(selectedDocument(), pUrl.toLocalFile(), uuid, destPath))
+ return NULL;
+ QUrl newUrl = QUrl::fromLocalFile(destPath);
+
+ w3cWidgetItem = mActiveScene->addW3CWidget(newUrl, pos);
+
+ if (w3cWidgetItem) {
+ w3cWidgetItem->setUuid(uuid);
+ w3cWidgetItem->setOwnFolder(newUrl);
+ w3cWidgetItem->setSourceUrl(pUrl);
+
+ QString struuid = UBStringUtils::toCanonicalUuid(uuid);
+ QString snapshotPath = selectedDocument()->persistencePath() + "/" + UBPersistenceManager::widgetDirectory + "/" + struuid + ".png";
+ w3cWidgetItem->setSnapshotPath(QUrl::fromLocalFile(snapshotPath));
+ UBGraphicsWidgetItem *tmpItem = dynamic_cast(w3cWidgetItem);
+ if (tmpItem && tmpItem->scene())
+ tmpItem->takeSnapshot().save(snapshotPath, "PNG");
+
+ }
+
+ return w3cWidgetItem;
+}
+
+void UBBoardController::cut()
+{
+ //---------------------------------------------------------//
+
+ QList selectedItems;
+ foreach(QGraphicsItem* gi, mActiveScene->selectedItems())
+ selectedItems << gi;
+
+ //---------------------------------------------------------//
+
+ QList selected;
+ foreach(QGraphicsItem* gi, selectedItems)
+ {
+ gi->setSelected(false);
+
+ UBItem* ubItem = dynamic_cast(gi);
+ UBGraphicsItem *ubGi = dynamic_cast(gi);
+
+ if (ubItem && ubGi && !mActiveScene->tools().contains(gi))
+ {
+ selected << ubItem->deepCopy();
+ ubGi->remove();
+ }
+ }
+
+ //---------------------------------------------------------//
+
+ if (selected.size() > 0)
+ {
+ QClipboard *clipboard = QApplication::clipboard();
+
+ UBMimeDataGraphicsItem* mimeGi = new UBMimeDataGraphicsItem(selected);
+
+ mimeGi->setData(UBApplication::mimeTypeUniboardPageItem, QByteArray());
+ clipboard->setMimeData(mimeGi);
+
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+ }
+
+ //---------------------------------------------------------//
+}
+
+
+void UBBoardController::copy()
+{
+ QList selected;
+
+ foreach(QGraphicsItem* gi, mActiveScene->selectedItems())
+ {
+ UBItem* ubItem = dynamic_cast(gi);
+
+ if (ubItem && !mActiveScene->tools().contains(gi))
+ {
+ UBItem *itemCopy = ubItem->deepCopy();
+ if (itemCopy)
+ selected << itemCopy;
+ }
+ }
+
+ if (selected.size() > 0)
+ {
+ QClipboard *clipboard = QApplication::clipboard();
+
+ UBMimeDataGraphicsItem* mimeGi = new UBMimeDataGraphicsItem(selected);
+
+ mimeGi->setData(UBApplication::mimeTypeUniboardPageItem, QByteArray());
+ clipboard->setMimeData(mimeGi);
+
+ }
+}
+
+
+void UBBoardController::paste()
+{
+ QClipboard *clipboard = QApplication::clipboard();
+ QPointF pos(0, 0);
+ processMimeData(clipboard->mimeData(), pos);
+
+ selectedDocument()->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
+}
+
+
+void UBBoardController::processMimeData(const QMimeData* pMimeData, const QPointF& pPos)
+{
+ if (pMimeData->hasFormat(UBApplication::mimeTypeUniboardPage))
+ {
+ const UBMimeData* mimeData = qobject_cast (pMimeData);
+
+ if (mimeData)
+ {
+ int previousActiveSceneIndex = activeSceneIndex();
+ int previousPageCount = selectedDocument()->pageCount();
+
+ foreach (UBMimeDataItem sourceItem, mimeData->items())
+ addScene(sourceItem.documentProxy(), sourceItem.sceneIndex(), true);
+
+ if (selectedDocument()->pageCount() < previousPageCount + mimeData->items().count())
+ setActiveDocumentScene(previousActiveSceneIndex);
+ else
+ setActiveDocumentScene(previousActiveSceneIndex + 1);
+
+ return;
+ }
+ }
+
+ if (pMimeData->hasFormat(UBApplication::mimeTypeUniboardPageItem))
+ {
+ const UBMimeDataGraphicsItem* mimeData = qobject_cast (pMimeData);
+
+ if (mimeData)
+ {
+ foreach(UBItem* item, mimeData->items())
+ {
+ QGraphicsItem* pItem = dynamic_cast(item);
+ if(NULL != pItem){
+ duplicateItem(item);
+ }
+ }
+
+ return;
+ }
+ }
+
+ if(pMimeData->hasHtml())
+ {
+ QString qsHtml = pMimeData->html();
+ QString url = UBApplication::urlFromHtml(qsHtml);
+
+ if("" != url)
+ {
+ downloadURL(url, QString(), pPos);
+ return;
+ }
+ }
+
+ if (pMimeData->hasUrls())
+ {
+ QList urls = pMimeData->urls();
+
+ int index = 0;
+
+ const UBFeaturesMimeData *internalMimeData = qobject_cast(pMimeData);
+ bool internalData = false;
+ if (internalMimeData) {
+ internalData = true;
+ }
+
+ foreach(const QUrl url, urls){
+ QPointF pos(pPos + QPointF(index * 15, index * 15));
+
+ downloadURL(url, QString(), pos, QSize(), false, internalData);
+ index++;
+ }
+
+ return;
+ }
+
+ if (pMimeData->hasImage())
+ {
+ QImage img = qvariant_cast (pMimeData->imageData());
+ QPixmap pix = QPixmap::fromImage(img);
+
+ // validate that the image is really an image, webkit does not fill properly the image mime data
+ if (pix.width() != 0 && pix.height() != 0)
+ {
+ mActiveScene->addPixmap(pix, NULL, pPos, 1.);
+ return;
+ }
+ }
+
+ if (pMimeData->hasText())
+ {
+ if("" != pMimeData->text()){
+ // Sometimes, it is possible to have an URL as text. we check here if it is the case
+ QString qsTmp = pMimeData->text().remove(QRegExp("[\\0]"));
+ if(qsTmp.startsWith("http")){
+ downloadURL(QUrl(qsTmp), QString(), pPos);
+ }
+ else{
+ mActiveScene->addTextHtml(pMimeData->html(), pPos);
+ }
+ }
+ else{
+#ifdef Q_WS_MACX
+ // With Safari, in 95% of the drops, the mime datas are hidden in Apple Web Archive pasteboard type.
+ // This is due to the way Safari is working so we have to dig into the pasteboard in order to retrieve
+ // the data.
+ QString qsUrl = UBPlatformUtils::urlFromClipboard();
+ if("" != qsUrl){
+ // We finally got the url of the dropped ressource! Let's import it!
+ downloadURL(qsUrl, qsUrl, pPos);
+ return;
+ }
+#endif
+ }
+ }
+}
+
+
+void UBBoardController::togglePodcast(bool checked)
+{
+ if (UBPodcastController::instance())
+ UBPodcastController::instance()->toggleRecordingPalette(checked);
+}
+
+void UBBoardController::moveGraphicsWidgetToControlView(UBGraphicsWidgetItem* graphicsWidget)
+{
+ mActiveScene->setURStackEnable(false);
+ UBGraphicsItem *toolW3C = duplicateItem(dynamic_cast(graphicsWidget));
+ UBGraphicsWidgetItem *copyedGraphicsWidget = NULL;
+
+ if (UBGraphicsWidgetItem::Type == toolW3C->type())
+ copyedGraphicsWidget = static_cast(toolW3C);
+
+ UBToolWidget *toolWidget = new UBToolWidget(copyedGraphicsWidget, mControlView);
+
+ graphicsWidget->remove(false);
+ mActiveScene->addItemToDeletion(graphicsWidget);
+
+ mActiveScene->setURStackEnable(true);
+
+ QPoint controlViewPos = mControlView->mapFromScene(graphicsWidget->sceneBoundingRect().center());
+ toolWidget->centerOn(mControlView->mapTo(mControlContainer, controlViewPos));
+ toolWidget->show();
+}
+
+
+void UBBoardController::moveToolWidgetToScene(UBToolWidget* toolWidget)
+{
+ UBGraphicsWidgetItem *widgetToScene = toolWidget->toolWidget();
+
+ widgetToScene->resetTransform();
+
+ QPoint mainWindowCenter = toolWidget->mapTo(mMainWindow, QPoint(toolWidget->width(), toolWidget->height()) / 2);
+ QPoint controlViewCenter = mControlView->mapFrom(mMainWindow, mainWindowCenter);
+ QPointF scenePos = mControlView->mapToScene(controlViewCenter);
+
+ mActiveScene->addGraphicsWidget(widgetToScene, scenePos);
+
+ toolWidget->remove();
+}
+
+
+void UBBoardController::updateBackgroundActionsState(bool isDark, bool isCrossed)
+{
+ if (isDark && !isCrossed)
+ mMainWindow->actionPlainDarkBackground->setChecked(true);
+ else if (isDark && isCrossed)
+ mMainWindow->actionCrossedDarkBackground->setChecked(true);
+ else if (!isDark && isCrossed)
+ mMainWindow->actionCrossedLightBackground->setChecked(true);
+ else
+ mMainWindow->actionPlainLightBackground->setChecked(true);
+}
+
+
+void UBBoardController::addItem()
+{
+ QString defaultPath = UBSettings::settings()->lastImportToLibraryPath->get().toString();
+
+ QString extensions;
+ foreach(QString ext, UBSettings::imageFileExtensions)
+ {
+ extensions += " *.";
+ extensions += ext;
+ }
+
+ QString filename = QFileDialog::getOpenFileName(mControlContainer, tr("Add Item"),
+ defaultPath,
+ tr("All Supported (%1)").arg(extensions), NULL, QFileDialog::DontUseNativeDialog);
+
+ if (filename.length() > 0)
+ {
+ mPaletteManager->addItem(QUrl::fromLocalFile(filename));
+ QFileInfo source(filename);
+ UBSettings::settings()->lastImportToLibraryPath->set(QVariant(source.absolutePath()));
+ }
+}
+
+void UBBoardController::importPage()
+{
+ int pageCount = selectedDocument()->pageCount();
+ if (UBApplication::documentController->addFileToDocument(selectedDocument()))
+ {
+ setActiveDocumentScene(selectedDocument(), pageCount, true);
+ }
+}
+
+void UBBoardController::notifyPageChanged()
+{
+ emit pageChanged();
+}
+
+void UBBoardController::onDownloadModalFinished()
+{
+
+}
+
+void UBBoardController::displayMetaData(QMap metadatas)
+{
+ emit displayMetadata(metadatas);
+}
+
+void UBBoardController::freezeW3CWidgets(bool freeze)
+{
+ if (mActiveSceneIndex >= 0)
+ {
+ QList list = UBApplication::boardController->activeScene()->getFastAccessItems();
+ foreach(QGraphicsItem *item, list)
+ {
+ freezeW3CWidget(item, freeze);
+ }
+ }
+}
+
+void UBBoardController::freezeW3CWidget(QGraphicsItem *item, bool freeze)
+{
+ if(item->type() == UBGraphicsW3CWidgetItem::Type)
+ {
+ UBGraphicsW3CWidgetItem* item_casted = dynamic_cast(item);
+ if (0 == item_casted)
+ return;
+
+ if (freeze) {
+ item_casted->load(QUrl(UBGraphicsW3CWidgetItem::freezedWidgetFilePath()));
+ } else
+ item_casted->loadMainHtml();
+ }
+}
diff --git a/src/board/UBBoardController.h b/src/board/UBBoardController.h
index 5497b9be..10be4e81 100644
--- a/src/board/UBBoardController.h
+++ b/src/board/UBBoardController.h
@@ -19,295 +19,295 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBBOARDCONTROLLER_H_
-#define UBBOARDCONTROLLER_H_
-
-#include
-
-#include
-#include "document/UBDocumentContainer.h"
-
-class UBMainWindow;
-class UBApplication;
-class UBBoardView;
-
-class UBDocumentController;
-class UBMessageWindow;
-class UBGraphicsScene;
-class UBDocumentProxy;
-class UBBlackoutWidget;
-class UBToolWidget;
-class UBVersion;
-class UBSoftwareUpdate;
-class UBSoftwareUpdateDialog;
-class UBGraphicsMediaItem;
-class UBGraphicsVideoItem;
-class UBGraphicsAudioItem;
-class UBGraphicsWidgetItem;
-class UBBoardPaletteManager;
-class UBItem;
-class UBGraphicsItem;
-
-
-class UBBoardController : public UBDocumentContainer
-{
- Q_OBJECT
-
- public:
- UBBoardController(UBMainWindow *mainWindow);
- virtual ~UBBoardController();
-
- void init();
- void setupLayout();
-
- UBGraphicsScene* activeScene() const;
- int activeSceneIndex() const;
- QSize displayViewport();
- QSize controlViewport();
- QRectF controlGeometry();
- void closing();
-
- int currentPage();
-
- QWidget* controlContainer()
- {
- return mControlContainer;
- }
-
- UBBoardView* controlView()
- {
- return mControlView;
- }
-
- UBBoardView* displayView()
- {
- return mDisplayView;
- }
-
- UBGraphicsScene* activeScene()
- {
- return mActiveScene;
- }
-
- void setPenColorOnDarkBackground(const QColor& pColor)
- {
- if (mPenColorOnDarkBackground == pColor)
- return;
-
- mPenColorOnDarkBackground = pColor;
- emit penColorChanged();
- }
-
- void setPenColorOnLightBackground(const QColor& pColor)
- {
- if (mPenColorOnLightBackground == pColor)
- return;
-
- mPenColorOnLightBackground = pColor;
- emit penColorChanged();
- }
-
- void setMarkerColorOnDarkBackground(const QColor& pColor)
- {
- mMarkerColorOnDarkBackground = pColor;
- }
-
- void setMarkerColorOnLightBackground(const QColor& pColor)
- {
- mMarkerColorOnLightBackground = pColor;
- }
-
- QColor penColorOnDarkBackground()
- {
- return mPenColorOnDarkBackground;
- }
-
- QColor penColorOnLightBackground()
- {
- return mPenColorOnLightBackground;
- }
-
- QColor markerColorOnDarkBackground()
- {
- return mMarkerColorOnDarkBackground;
- }
-
- QColor markerColorOnLightBackground()
- {
- return mMarkerColorOnLightBackground;
- }
-
- qreal systemScaleFactor()
- {
- return mSystemScaleFactor;
- }
- qreal currentZoom();
- void persistCurrentScene();
- void showNewVersionAvailable(bool automatic, const UBVersion &installedVersion, const UBSoftwareUpdate &softwareUpdate);
- void setBoxing(QRect displayRect);
- void setToolbarTexts();
- static QUrl expandWidgetToTempDir(const QByteArray& pZipedData, const QString& pExtension = QString("wgt"));
-// static QRect freeRectInGlobalPos() const {return ;}
- void setPageSize(QSize newSize);
- UBBoardPaletteManager *paletteManager()
- {
- return mPaletteManager;
- }
-
- void notifyCache(bool visible);
- void notifyPageChanged();
- void displayMetaData(QMap metadatas);
-
- void ClearUndoStack();
-
- void setActiveDocumentScene(UBDocumentProxy* pDocumentProxy, int pSceneIndex = 0, bool forceReload = false);
- void setActiveDocumentScene(int pSceneIndex);
-
- void moveSceneToIndex(int source, int target);
- void duplicateScene(int index);
- UBGraphicsItem *duplicateItem(UBItem *item, bool bAsync = true);
- void deleteScene(int index);
-
- bool cacheIsVisible() {return mCacheWidgetIsEnabled;}
-
- QString actionGroupText(){ return mActionGroupText;}
- QString actionUngroupText(){ return mActionUngroupText;}
-
- public slots:
- void showDocumentsDialog();
- void showKeyboard(bool show);
- void togglePodcast(bool checked);
- void blackout();
- void addScene();
- void addScene(UBDocumentProxy* proxy, int sceneIndex, bool replaceActiveIfEmpty = false);
- void addScene(UBGraphicsScene* scene, bool replaceActiveIfEmpty = false);
- void duplicateScene();
- void importPage();
- void clearScene();
- void clearSceneItems();
- void clearSceneAnnotation();
- void clearSceneBackground();
- void zoomIn(QPointF scenePoint = QPointF(0,0));
- void zoomOut(QPointF scenePoint = QPointF(0,0));
- void zoomRestore();
- void centerRestore();
- void centerOn(QPointF scenePoint = QPointF(0,0));
- void zoom(const qreal ratio, QPointF scenePoint);
- void handScroll(qreal dx, qreal dy);
- void previousScene();
- void nextScene();
- void firstScene();
- void lastScene();
- void groupButtonClicked();
- void downloadURL(const QUrl& url, QString contentSourceUrl = QString(), const QPointF& pPos = QPointF(0.0, 0.0), const QSize& pSize = QSize(), bool isBackground = false, bool internalData = false);
- UBItem *downloadFinished(bool pSuccess, QUrl sourceUrl, QUrl contentUrl, QString pHeader,
- QByteArray pData, QPointF pPos, QSize pSize,
- bool isBackground = false, bool internalData = false);
- void changeBackground(bool isDark, bool isCrossed);
- void setToolCursor(int tool);
- void showMessage(const QString& message, bool showSpinningWheel = false);
- void hideMessage();
- void setDisabled(bool disable);
- void setColorIndex(int pColorIndex);
- void removeTool(UBToolWidget* toolWidget);
- void hide();
- void show();
- void setWidePageSize(bool checked);
- void setRegularPageSize(bool checked);
- void stylusToolChanged(int tool);
- void grabScene(const QRectF& pSceneRect);
- UBGraphicsMediaItem* addVideo(const QUrl& pUrl, bool startPlay, const QPointF& pos, bool bUseSource = false);
- UBGraphicsMediaItem* addAudio(const QUrl& pUrl, bool startPlay, const QPointF& pos, bool bUseSource = false);
- UBGraphicsWidgetItem *addW3cWidget(const QUrl& pUrl, const QPointF& pos);
-
- void cut();
- void copy();
- void paste();
- void processMimeData(const QMimeData* pMimeData, const QPointF& pPos);
- void moveGraphicsWidgetToControlView(UBGraphicsWidgetItem* graphicWidget);
- void moveToolWidgetToScene(UBToolWidget* toolWidget);
- void addItem();
-
- void freezeW3CWidgets(bool freeze);
- void freezeW3CWidget(QGraphicsItem* item, bool freeze);
- void startScript();
- void stopScript();
-
- signals:
- void newPageAdded();
- void activeSceneChanged();
- void zoomChanged(qreal pZoomFactor);
- void systemScaleFactorChanged(qreal pSystemScaleFactor);
- void penColorChanged();
- void controlViewportChanged();
- void backgroundChanged();
- void cacheEnabled();
- void cacheDisabled();
- void pageChanged();
- void documentReorganized(int index);
- void displayMetadata(QMap metadata);
- void pageSelectionChanged(int index);
- void npapiWidgetCreated(const QString &Url);
-
- protected:
- void setupViews();
- void setupToolbar();
- void connectToolbar();
- void initToolbarTexts();
- void updateActionStates();
- void updateSystemScaleFactor();
- QString truncate(QString text, int maxWidth);
-
- protected slots:
- void selectionChanged();
- void undoRedoStateChange(bool canUndo);
- void documentSceneChanged(UBDocumentProxy* proxy, int pIndex);
-
- private:
- void updatePageSizeState();
- void saveViewState();
- void adjustDisplayViews();
-
- UBMainWindow *mMainWindow;
- UBGraphicsScene* mActiveScene;
- int mActiveSceneIndex;
- UBBoardPaletteManager *mPaletteManager;
- UBSoftwareUpdateDialog *mSoftwareUpdateDialog;
- UBMessageWindow *mMessageWindow;
- UBBoardView *mControlView;
- UBBoardView *mDisplayView;
- QWidget *mControlContainer;
- QHBoxLayout *mControlLayout;
- qreal mZoomFactor;
- bool mIsClosing;
- QColor mPenColorOnDarkBackground;
- QColor mPenColorOnLightBackground;
- QColor mMarkerColorOnDarkBackground;
- QColor mMarkerColorOnLightBackground;
- qreal mSystemScaleFactor;
- bool mCleanupDone;
- QMap > mActionTexts;
- bool mCacheWidgetIsEnabled;
- QGraphicsItem* mLastCreatedItem;
- int mDeletingSceneIndex;
- int mMovingSceneIndex;
- QString mActionGroupText;
- QString mActionUngroupText;
-
- private slots:
- void stylusToolDoubleClicked(int tool);
- void boardViewResized(QResizeEvent* event);
- void documentWillBeDeleted(UBDocumentProxy* pProxy);
- void updateBackgroundActionsState(bool isDark, bool isCrossed);
- void updateBackgroundState();
- void colorPaletteChanged();
- void libraryDialogClosed(int ret);
- void lastWindowClosed();
- void onDownloadModalFinished();
-
-};
-
-
-#endif /* UBBOARDCONTROLLER_H_ */
+
+
+#ifndef UBBOARDCONTROLLER_H_
+#define UBBOARDCONTROLLER_H_
+
+#include
+
+#include
+#include "document/UBDocumentContainer.h"
+
+class UBMainWindow;
+class UBApplication;
+class UBBoardView;
+
+class UBDocumentController;
+class UBMessageWindow;
+class UBGraphicsScene;
+class UBDocumentProxy;
+class UBBlackoutWidget;
+class UBToolWidget;
+class UBVersion;
+class UBSoftwareUpdate;
+class UBSoftwareUpdateDialog;
+class UBGraphicsMediaItem;
+class UBGraphicsVideoItem;
+class UBGraphicsAudioItem;
+class UBGraphicsWidgetItem;
+class UBBoardPaletteManager;
+class UBItem;
+class UBGraphicsItem;
+
+
+class UBBoardController : public UBDocumentContainer
+{
+ Q_OBJECT
+
+ public:
+ UBBoardController(UBMainWindow *mainWindow);
+ virtual ~UBBoardController();
+
+ void init();
+ void setupLayout();
+
+ UBGraphicsScene* activeScene() const;
+ int activeSceneIndex() const;
+ QSize displayViewport();
+ QSize controlViewport();
+ QRectF controlGeometry();
+ void closing();
+
+ int currentPage();
+
+ QWidget* controlContainer()
+ {
+ return mControlContainer;
+ }
+
+ UBBoardView* controlView()
+ {
+ return mControlView;
+ }
+
+ UBBoardView* displayView()
+ {
+ return mDisplayView;
+ }
+
+ UBGraphicsScene* activeScene()
+ {
+ return mActiveScene;
+ }
+
+ void setPenColorOnDarkBackground(const QColor& pColor)
+ {
+ if (mPenColorOnDarkBackground == pColor)
+ return;
+
+ mPenColorOnDarkBackground = pColor;
+ emit penColorChanged();
+ }
+
+ void setPenColorOnLightBackground(const QColor& pColor)
+ {
+ if (mPenColorOnLightBackground == pColor)
+ return;
+
+ mPenColorOnLightBackground = pColor;
+ emit penColorChanged();
+ }
+
+ void setMarkerColorOnDarkBackground(const QColor& pColor)
+ {
+ mMarkerColorOnDarkBackground = pColor;
+ }
+
+ void setMarkerColorOnLightBackground(const QColor& pColor)
+ {
+ mMarkerColorOnLightBackground = pColor;
+ }
+
+ QColor penColorOnDarkBackground()
+ {
+ return mPenColorOnDarkBackground;
+ }
+
+ QColor penColorOnLightBackground()
+ {
+ return mPenColorOnLightBackground;
+ }
+
+ QColor markerColorOnDarkBackground()
+ {
+ return mMarkerColorOnDarkBackground;
+ }
+
+ QColor markerColorOnLightBackground()
+ {
+ return mMarkerColorOnLightBackground;
+ }
+
+ qreal systemScaleFactor()
+ {
+ return mSystemScaleFactor;
+ }
+ qreal currentZoom();
+ void persistCurrentScene();
+ void showNewVersionAvailable(bool automatic, const UBVersion &installedVersion, const UBSoftwareUpdate &softwareUpdate);
+ void setBoxing(QRect displayRect);
+ void setToolbarTexts();
+ static QUrl expandWidgetToTempDir(const QByteArray& pZipedData, const QString& pExtension = QString("wgt"));
+// static QRect freeRectInGlobalPos() const {return ;}
+ void setPageSize(QSize newSize);
+ UBBoardPaletteManager *paletteManager()
+ {
+ return mPaletteManager;
+ }
+
+ void notifyCache(bool visible);
+ void notifyPageChanged();
+ void displayMetaData(QMap metadatas);
+
+ void ClearUndoStack();
+
+ void setActiveDocumentScene(UBDocumentProxy* pDocumentProxy, int pSceneIndex = 0, bool forceReload = false);
+ void setActiveDocumentScene(int pSceneIndex);
+
+ void moveSceneToIndex(int source, int target);
+ void duplicateScene(int index);
+ UBGraphicsItem *duplicateItem(UBItem *item, bool bAsync = true);
+ void deleteScene(int index);
+
+ bool cacheIsVisible() {return mCacheWidgetIsEnabled;}
+
+ QString actionGroupText(){ return mActionGroupText;}
+ QString actionUngroupText(){ return mActionUngroupText;}
+
+ public slots:
+ void showDocumentsDialog();
+ void showKeyboard(bool show);
+ void togglePodcast(bool checked);
+ void blackout();
+ void addScene();
+ void addScene(UBDocumentProxy* proxy, int sceneIndex, bool replaceActiveIfEmpty = false);
+ void addScene(UBGraphicsScene* scene, bool replaceActiveIfEmpty = false);
+ void duplicateScene();
+ void importPage();
+ void clearScene();
+ void clearSceneItems();
+ void clearSceneAnnotation();
+ void clearSceneBackground();
+ void zoomIn(QPointF scenePoint = QPointF(0,0));
+ void zoomOut(QPointF scenePoint = QPointF(0,0));
+ void zoomRestore();
+ void centerRestore();
+ void centerOn(QPointF scenePoint = QPointF(0,0));
+ void zoom(const qreal ratio, QPointF scenePoint);
+ void handScroll(qreal dx, qreal dy);
+ void previousScene();
+ void nextScene();
+ void firstScene();
+ void lastScene();
+ void groupButtonClicked();
+ void downloadURL(const QUrl& url, QString contentSourceUrl = QString(), const QPointF& pPos = QPointF(0.0, 0.0), const QSize& pSize = QSize(), bool isBackground = false, bool internalData = false);
+ UBItem *downloadFinished(bool pSuccess, QUrl sourceUrl, QUrl contentUrl, QString pHeader,
+ QByteArray pData, QPointF pPos, QSize pSize,
+ bool isBackground = false, bool internalData = false);
+ void changeBackground(bool isDark, bool isCrossed);
+ void setToolCursor(int tool);
+ void showMessage(const QString& message, bool showSpinningWheel = false);
+ void hideMessage();
+ void setDisabled(bool disable);
+ void setColorIndex(int pColorIndex);
+ void removeTool(UBToolWidget* toolWidget);
+ void hide();
+ void show();
+ void setWidePageSize(bool checked);
+ void setRegularPageSize(bool checked);
+ void stylusToolChanged(int tool);
+ void grabScene(const QRectF& pSceneRect);
+ UBGraphicsMediaItem* addVideo(const QUrl& pUrl, bool startPlay, const QPointF& pos, bool bUseSource = false);
+ UBGraphicsMediaItem* addAudio(const QUrl& pUrl, bool startPlay, const QPointF& pos, bool bUseSource = false);
+ UBGraphicsWidgetItem *addW3cWidget(const QUrl& pUrl, const QPointF& pos);
+
+ void cut();
+ void copy();
+ void paste();
+ void processMimeData(const QMimeData* pMimeData, const QPointF& pPos);
+ void moveGraphicsWidgetToControlView(UBGraphicsWidgetItem* graphicWidget);
+ void moveToolWidgetToScene(UBToolWidget* toolWidget);
+ void addItem();
+
+ void freezeW3CWidgets(bool freeze);
+ void freezeW3CWidget(QGraphicsItem* item, bool freeze);
+ void startScript();
+ void stopScript();
+
+ signals:
+ void newPageAdded();
+ void activeSceneChanged();
+ void zoomChanged(qreal pZoomFactor);
+ void systemScaleFactorChanged(qreal pSystemScaleFactor);
+ void penColorChanged();
+ void controlViewportChanged();
+ void backgroundChanged();
+ void cacheEnabled();
+ void cacheDisabled();
+ void pageChanged();
+ void documentReorganized(int index);
+ void displayMetadata(QMap metadata);
+ void pageSelectionChanged(int index);
+ void npapiWidgetCreated(const QString &Url);
+
+ protected:
+ void setupViews();
+ void setupToolbar();
+ void connectToolbar();
+ void initToolbarTexts();
+ void updateActionStates();
+ void updateSystemScaleFactor();
+ QString truncate(QString text, int maxWidth);
+
+ protected slots:
+ void selectionChanged();
+ void undoRedoStateChange(bool canUndo);
+ void documentSceneChanged(UBDocumentProxy* proxy, int pIndex);
+
+ private:
+ void updatePageSizeState();
+ void saveViewState();
+ void adjustDisplayViews();
+
+ UBMainWindow *mMainWindow;
+ UBGraphicsScene* mActiveScene;
+ int mActiveSceneIndex;
+ UBBoardPaletteManager *mPaletteManager;
+ UBSoftwareUpdateDialog *mSoftwareUpdateDialog;
+ UBMessageWindow *mMessageWindow;
+ UBBoardView *mControlView;
+ UBBoardView *mDisplayView;
+ QWidget *mControlContainer;
+ QHBoxLayout *mControlLayout;
+ qreal mZoomFactor;
+ bool mIsClosing;
+ QColor mPenColorOnDarkBackground;
+ QColor mPenColorOnLightBackground;
+ QColor mMarkerColorOnDarkBackground;
+ QColor mMarkerColorOnLightBackground;
+ qreal mSystemScaleFactor;
+ bool mCleanupDone;
+ QMap > mActionTexts;
+ bool mCacheWidgetIsEnabled;
+ QGraphicsItem* mLastCreatedItem;
+ int mDeletingSceneIndex;
+ int mMovingSceneIndex;
+ QString mActionGroupText;
+ QString mActionUngroupText;
+
+ private slots:
+ void stylusToolDoubleClicked(int tool);
+ void boardViewResized(QResizeEvent* event);
+ void documentWillBeDeleted(UBDocumentProxy* pProxy);
+ void updateBackgroundActionsState(bool isDark, bool isCrossed);
+ void updateBackgroundState();
+ void colorPaletteChanged();
+ void libraryDialogClosed(int ret);
+ void lastWindowClosed();
+ void onDownloadModalFinished();
+
+};
+
+
+#endif /* UBBOARDCONTROLLER_H_ */
diff --git a/src/board/UBBoardPaletteManager.cpp b/src/board/UBBoardPaletteManager.cpp
index 582118bb..086da59b 100644
--- a/src/board/UBBoardPaletteManager.cpp
+++ b/src/board/UBBoardPaletteManager.cpp
@@ -19,984 +19,984 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include "UBBoardPaletteManager.h"
-
-#include "frameworks/UBPlatformUtils.h"
-#include "frameworks/UBFileSystemUtils.h"
-
-#include "core/UBApplication.h"
-#include "core/UBApplicationController.h"
-#include "core/UBSettings.h"
-#include "core/UBSetting.h"
-#include "core/UBDisplayManager.h"
-
-#include "gui/UBMainWindow.h"
-#include "gui/UBStylusPalette.h"
-#include "gui/UBKeyboardPalette.h"
-#include "gui/UBToolWidget.h"
-#include "gui/UBZoomPalette.h"
-#include "gui/UBWebToolsPalette.h"
-#include "gui/UBActionPalette.h"
-#include "gui/UBFavoriteToolPalette.h"
-#include "gui/UBDockTeacherGuideWidget.h"
-
-
-#include "web/UBWebPage.h"
-#include "web/UBWebController.h"
-#include "web/browser/WBBrowserWindow.h"
-#include "web/browser/WBTabWidget.h"
-#include "web/browser/WBWebView.h"
-
-#include "desktop/UBDesktopAnnotationController.h"
-
-
-#include "network/UBNetworkAccessManager.h"
-#include "network/UBServerXMLHttpRequest.h"
-
-#include "domain/UBGraphicsScene.h"
-#include "domain/UBGraphicsPixmapItem.h"
-
-#include "document/UBDocumentProxy.h"
-#include "podcast/UBPodcastController.h"
-#include "board/UBDrawingController.h"
-
-#include "tools/UBToolsManager.h"
-
-#include "UBBoardController.h"
-
-#include "document/UBDocumentController.h"
-
-#include "core/memcheck.h"
-
-UBBoardPaletteManager::UBBoardPaletteManager(QWidget* container, UBBoardController* pBoardController)
- : QObject(container)
- , mKeyboardPalette(0)
- , mWebToolsCurrentPalette(0)
- , mContainer(container)
- , mBoardControler(pBoardController)
- , mStylusPalette(0)
- , mZoomPalette(0)
- , mLeftPalette(NULL)
- , mRightPalette(NULL)
- , mBackgroundsPalette(0)
- , mToolsPalette(0)
- , mAddItemPalette(0)
- , mErasePalette(NULL)
- , mPagePalette(NULL)
- , mPendingPageButtonPressed(false)
- , mPendingZoomButtonPressed(false)
- , mPendingPanButtonPressed(false)
- , mPendingEraseButtonPressed(false)
- , mpPageNavigWidget(NULL)
- , mpCachePropWidget(NULL)
- , mpDownloadWidget(NULL)
- , mpTeacherGuideWidget(NULL)
- , mDownloadInProgress(false)
-{
- setupPalettes();
- connectPalettes();
-}
-
-
-UBBoardPaletteManager::~UBBoardPaletteManager()
-{
-
-// mAddedItemPalette is delete automatically because of is parent
-// that changes depending on the mode
-
-// mMainWindow->centralWidget is the parent of mStylusPalette
-// do not delete this here.
-}
-
-void UBBoardPaletteManager::initPalettesPosAtStartup()
-{
- mStylusPalette->initPosition();
-}
-
-void UBBoardPaletteManager::setupLayout()
-{
-
-}
-
-/**
- * \brief Set up the dock palette widgets
- */
-void UBBoardPaletteManager::setupDockPaletteWidgets()
-{
-
- //------------------------------------------------//
- // Create the widgets for the dock palettes
-
- mpPageNavigWidget = new UBPageNavigationWidget();
-
- mpCachePropWidget = new UBCachePropertiesWidget();
-
- mpDownloadWidget = new UBDockDownloadWidget();
-
- // Add the dock palettes
- mLeftPalette = new UBLeftPalette(mContainer);
-
- // LEFT palette widgets
- mpPageNavigWidget = new UBPageNavigationWidget();
- mLeftPalette->registerWidget(mpPageNavigWidget);
- mLeftPalette->addTab(mpPageNavigWidget);
-
- if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool() || UBSettings::settings()->teacherGuideLessonPagesActivated->get().toBool()){
- mpTeacherGuideWidget = new UBDockTeacherGuideWidget();
- mLeftPalette->registerWidget(mpTeacherGuideWidget);
- mLeftPalette->addTab(mpTeacherGuideWidget);
- }
-
- mLeftPalette->connectSignals();
- mLeftPalette->showTabWidget(0);
-
- mRightPalette = new UBRightPalette(mContainer);
- // RIGHT palette widgets
- mpFeaturesWidget = new UBFeaturesWidget();
- mRightPalette->registerWidget(mpFeaturesWidget);
- mRightPalette->addTab(mpFeaturesWidget);
-
- // The cache widget will be visible only if a cache is put on the page
- mRightPalette->registerWidget(mpCachePropWidget);
-
- // The download widget will be part of the right palette but
- // will become visible only when the first download starts
- mRightPalette->registerWidget(mpDownloadWidget);
- mRightPalette->connectSignals();
- changeMode(eUBDockPaletteWidget_BOARD, true);
-
- // Hide the tabs that must be hidden
- mRightPalette->removeTab(mpDownloadWidget);
- mRightPalette->removeTab(mpCachePropWidget);
-
-}
-
-void UBBoardPaletteManager::slot_changeMainMode(UBApplicationController::MainMode mainMode)
-{
-// Board = 0, Internet, Document, Tutorial, ParaschoolEditor, WebDocument
-
- switch( mainMode )
- {
- case UBApplicationController::Board:
- {
- // call changeMode only when switch NOT from desktop mode
- if(!UBApplication::applicationController->isShowingDesktop())
- changeMode(eUBDockPaletteWidget_BOARD);
- }
- break;
-
- case UBApplicationController::Tutorial:
- {
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- mKeyboardPalette->hide();
- }
- break;
-
- case UBApplicationController::Internet:
- changeMode(eUBDockPaletteWidget_WEB);
- break;
-
- case UBApplicationController::Document:
- changeMode(eUBDockPaletteWidget_DOCUMENT);
- break;
-
- default:
- {
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- mKeyboardPalette->hide();
- }
- break;
- }
-}
-
-void UBBoardPaletteManager::slot_changeDesktopMode(bool isDesktop)
-{
- UBApplicationController::MainMode currMode = UBApplication::applicationController->displayMode();
- if(!isDesktop)
- {
- switch( currMode )
- {
- case UBApplicationController::Board:
- changeMode(eUBDockPaletteWidget_BOARD);
- break;
-
- default:
- break;
- }
- }
- else
- changeMode(eUBDockPaletteWidget_DESKTOP);
-}
-
-void UBBoardPaletteManager::setupPalettes()
-{
-
- if (UBPlatformUtils::hasVirtualKeyboard())
- {
- mKeyboardPalette = new UBKeyboardPalette(0);
-#ifndef Q_WS_WIN
- connect(mKeyboardPalette, SIGNAL(closed()), mKeyboardPalette, SLOT(onDeactivated()));
-#endif
- }
-
-
- setupDockPaletteWidgets();
-
-
- // Add the other palettes
- mStylusPalette = new UBStylusPalette(mContainer, UBSettings::settings()->appToolBarOrientationVertical->get().toBool() ? Qt::Vertical : Qt::Horizontal);
- connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int)));
- mStylusPalette->show(); // always show stylus palette at startup
-
- mZoomPalette = new UBZoomPalette(mContainer);
-
- mStylusPalette->stackUnder(mZoomPalette);
-
- QList backgroundsActions;
-
- backgroundsActions << UBApplication::mainWindow->actionPlainLightBackground;
- backgroundsActions << UBApplication::mainWindow->actionCrossedLightBackground;
- backgroundsActions << UBApplication::mainWindow->actionPlainDarkBackground;
- backgroundsActions << UBApplication::mainWindow->actionCrossedDarkBackground;
-
- mBackgroundsPalette = new UBActionPalette(backgroundsActions, Qt::Horizontal , mContainer);
- mBackgroundsPalette->setButtonIconSize(QSize(128, 128));
- mBackgroundsPalette->groupActions();
- mBackgroundsPalette->setClosable(true);
- mBackgroundsPalette->setAutoClose(true);
- mBackgroundsPalette->adjustSizeAndPosition();
- mBackgroundsPalette->hide();
-
- QList addItemActions;
-
- addItemActions << UBApplication::mainWindow->actionAddItemToCurrentPage;
- addItemActions << UBApplication::mainWindow->actionAddItemToNewPage;
- addItemActions << UBApplication::mainWindow->actionAddItemToLibrary;
-
- mAddItemPalette = new UBActionPalette(addItemActions, Qt::Horizontal, mContainer);
- mAddItemPalette->setButtonIconSize(QSize(128, 128));
- mAddItemPalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
- mAddItemPalette->groupActions();
- mAddItemPalette->setClosable(true);
- mAddItemPalette->adjustSizeAndPosition();
- mAddItemPalette->hide();
-
- QList eraseActions;
-
- eraseActions << UBApplication::mainWindow->actionEraseAnnotations;
- eraseActions << UBApplication::mainWindow->actionEraseItems;
- eraseActions << UBApplication::mainWindow->actionClearPage;
- eraseActions << UBApplication::mainWindow->actionEraseBackground;
-
- mErasePalette = new UBActionPalette(eraseActions, Qt::Horizontal , mContainer);
- mErasePalette->setButtonIconSize(QSize(128, 128));
- mErasePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
- mErasePalette->groupActions();
- mErasePalette->setClosable(true);
- mErasePalette->adjustSizeAndPosition();
- mErasePalette->hide();
-
- QList pageActions;
-
- pageActions << UBApplication::mainWindow->actionNewPage;
- pageActions << UBApplication::mainWindow->actionDuplicatePage;
- pageActions << UBApplication::mainWindow->actionImportPage;
-
- mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer);
- mPagePalette->setButtonIconSize(QSize(128, 128));
- mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
- mPagePalette->groupActions();
- mPagePalette->setClosable(true);
- mPagePalette->adjustSizeAndPosition();
- mPagePalette->hide();
-
- connect(UBSettings::settings()->appToolBarOrientationVertical, SIGNAL(changed(QVariant)), this, SLOT(changeStylusPaletteOrientation(QVariant)));
-}
-
-void UBBoardPaletteManager::pagePaletteButtonPressed()
-{
- mPageButtonPressedTime = QTime::currentTime();
-
- mPendingPageButtonPressed = true;
- QTimer::singleShot(1000, this, SLOT(pagePaletteButtonReleased()));
-}
-
-
-void UBBoardPaletteManager::pagePaletteButtonReleased()
-{
- if (mPendingPageButtonPressed)
- {
- if( mPageButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
- {
- // The palette is reinstanciated because the duplication depends on the current scene
- delete(mPagePalette);
- mPagePalette = 0;
- QListpageActions;
- pageActions << UBApplication::mainWindow->actionNewPage;
- UBBoardController* boardController = UBApplication::boardController;
- if(UBApplication::documentController->pageCanBeDuplicated(UBDocumentContainer::pageFromSceneIndex(boardController->activeSceneIndex()))){
- pageActions << UBApplication::mainWindow->actionDuplicatePage;
- }
- pageActions << UBApplication::mainWindow->actionImportPage;
-
- mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer);
- mPagePalette->setButtonIconSize(QSize(128, 128));
- mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
- mPagePalette->groupActions();
- mPagePalette->setClosable(true);
-
- // As we recreate the pagePalette every time, we must reconnect the slots
- connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
- connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed()));
-
- togglePagePalette(true);
- }
- else
- {
- UBApplication::mainWindow->actionNewPage->trigger();
- }
-
- mPendingPageButtonPressed = false;
- }
-}
-
-void UBBoardPaletteManager::erasePaletteButtonPressed()
-{
- mEraseButtonPressedTime = QTime::currentTime();
-
- mPendingEraseButtonPressed = true;
- QTimer::singleShot(1000, this, SLOT(erasePaletteButtonReleased()));
-}
-
-
-void UBBoardPaletteManager::erasePaletteButtonReleased()
-{
- if (mPendingEraseButtonPressed)
- {
- if( mEraseButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
- {
- toggleErasePalette(true);
- }
- else
- {
- UBApplication::mainWindow->actionClearPage->trigger();
- }
-
- mPendingEraseButtonPressed = false;
- }
-}
-
-
-
-void UBBoardPaletteManager::linkClicked(const QUrl& url)
-{
- UBApplication::applicationController->showInternet();
- UBApplication::webController->loadUrl(url);
-}
-
-
-void UBBoardPaletteManager::purchaseLinkActivated(const QString& link)
-{
- UBApplication::applicationController->showInternet();
- UBApplication::webController->loadUrl(QUrl(link));
-}
-
-void UBBoardPaletteManager::connectPalettes()
-{
- connect(UBApplication::mainWindow->actionStylus, SIGNAL(toggled(bool)), this, SLOT(toggleStylusPalette(bool)));
-
- foreach(QWidget *widget, UBApplication::mainWindow->actionZoomIn->associatedWidgets())
- {
- QAbstractButton *button = qobject_cast(widget);
- if (button)
- {
- connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed()));
- connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased()));
- }
- }
-
- foreach(QWidget *widget, UBApplication::mainWindow->actionZoomOut->associatedWidgets())
- {
- QAbstractButton *button = qobject_cast(widget);
- if (button)
- {
- connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed()));
- connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased()));
- }
- }
-
- foreach(QWidget *widget, UBApplication::mainWindow->actionHand->associatedWidgets())
- {
- QAbstractButton *button = qobject_cast(widget);
- if (button)
- {
- connect(button, SIGNAL(pressed()), this, SLOT(panButtonPressed()));
- connect(button, SIGNAL(released()), this, SLOT(panButtonReleased()));
- }
- }
-
- connect(UBApplication::mainWindow->actionBackgrounds, SIGNAL(toggled(bool)), this, SLOT(toggleBackgroundPalette(bool)));
- connect(mBackgroundsPalette, SIGNAL(closed()), this, SLOT(backgroundPaletteClosed()));
-
- connect(UBApplication::mainWindow->actionPlainLightBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
- connect(UBApplication::mainWindow->actionCrossedLightBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
- connect(UBApplication::mainWindow->actionPlainDarkBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
- connect(UBApplication::mainWindow->actionCrossedDarkBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
- connect(UBApplication::mainWindow->actionPodcast, SIGNAL(triggered(bool)), this, SLOT(tooglePodcastPalette(bool)));
-
- connect(UBApplication::mainWindow->actionAddItemToCurrentPage, SIGNAL(triggered()), this, SLOT(addItemToCurrentPage()));
- connect(UBApplication::mainWindow->actionAddItemToNewPage, SIGNAL(triggered()), this, SLOT(addItemToNewPage()));
- connect(UBApplication::mainWindow->actionAddItemToLibrary, SIGNAL(triggered()), this, SLOT(addItemToLibrary()));
-
- connect(UBApplication::mainWindow->actionEraseItems, SIGNAL(triggered()), mErasePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionEraseAnnotations, SIGNAL(triggered()), mErasePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionClearPage, SIGNAL(triggered()), mErasePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionEraseBackground,SIGNAL(triggered()),mErasePalette,SLOT(close()));
- connect(mErasePalette, SIGNAL(closed()), this, SLOT(erasePaletteClosed()));
-
- foreach(QWidget *widget, UBApplication::mainWindow->actionErase->associatedWidgets())
- {
- QAbstractButton *button = qobject_cast(widget);
- if (button)
- {
- connect(button, SIGNAL(pressed()), this, SLOT(erasePaletteButtonPressed()));
- connect(button, SIGNAL(released()), this, SLOT(erasePaletteButtonReleased()));
- }
- }
-
- connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
- connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
- connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed()));
-
- foreach(QWidget *widget, UBApplication::mainWindow->actionPages->associatedWidgets())
- {
- QAbstractButton *button = qobject_cast(widget);
- if (button)
- {
- connect(button, SIGNAL(pressed()), this, SLOT(pagePaletteButtonPressed()));
- connect(button, SIGNAL(released()), this, SLOT(pagePaletteButtonReleased()));
- }
- }
-
-}
-
-
-bool isFirstResized = true;
-void UBBoardPaletteManager::containerResized()
-{
- int innerMargin = UBSettings::boardMargin;
-
- int userLeft = innerMargin;
- int userWidth = mContainer->width() - (2 * innerMargin);
- int userTop = innerMargin;
- int userHeight = mContainer->height() - (2 * innerMargin);
-
- if(mStylusPalette)
- {
- mStylusPalette->move(userLeft, userTop);
- mStylusPalette->adjustSizeAndPosition();
- mStylusPalette->initPosition();
- }
-
- if(mZoomPalette)
- {
- mZoomPalette->move(userLeft + userWidth - mZoomPalette->width()
- , userTop + userHeight /*- mPageNumberPalette->height()*/ - innerMargin - mZoomPalette->height());
- mZoomPalette->adjustSizeAndPosition();
- }
-
- if (isFirstResized && mKeyboardPalette && mKeyboardPalette->parent() == UBApplication::boardController->controlContainer())
- {
- isFirstResized = false;
- mKeyboardPalette->move(userLeft + (userWidth - mKeyboardPalette->width())/2,
- userTop + (userHeight - mKeyboardPalette->height())/2);
- mKeyboardPalette->adjustSizeAndPosition();
- }
-
- if(mLeftPalette)
- {
- mLeftPalette->resize(mLeftPalette->width()-1, mContainer->height());
- mLeftPalette->resize(mLeftPalette->width(), mContainer->height());
- }
-
- if(mRightPalette)
- {
- mRightPalette->resize(mRightPalette->width()-1, mContainer->height());
- mRightPalette->resize(mRightPalette->width(), mContainer->height());
- }
-}
-
-
-void UBBoardPaletteManager::changeBackground()
-{
- if (UBApplication::mainWindow->actionCrossedLightBackground->isChecked())
- UBApplication::boardController->changeBackground(false, true);
- else if (UBApplication::mainWindow->actionPlainDarkBackground->isChecked())
- UBApplication::boardController->changeBackground(true, false);
- else if (UBApplication::mainWindow->actionCrossedDarkBackground->isChecked())
- UBApplication::boardController->changeBackground(true, true);
- else
- UBApplication::boardController->changeBackground(false, false);
-
- UBApplication::mainWindow->actionBackgrounds->setChecked(false);
-}
-
-
-void UBBoardPaletteManager::activeSceneChanged()
-{
- UBGraphicsScene *activeScene = UBApplication::boardController->activeScene();
- int pageIndex = UBApplication::boardController->activeSceneIndex();
-
- if (mStylusPalette)
- connect(mStylusPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
-
- if (mpPageNavigWidget)
- {
- mpPageNavigWidget->setPageNumber(UBDocumentContainer::pageFromSceneIndex(pageIndex), activeScene->document()->pageCount());
- }
-
- if (mZoomPalette)
- connect(mZoomPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
-
- if (mBackgroundsPalette)
- connect(mBackgroundsPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
-}
-
-
-void UBBoardPaletteManager::toggleBackgroundPalette(bool checked)
-{
- mBackgroundsPalette->setVisible(checked);
-
- if (checked)
- {
- UBApplication::mainWindow->actionErase->setChecked(false);
- UBApplication::mainWindow->actionNewPage->setChecked(false);
-
- mBackgroundsPalette->adjustSizeAndPosition();
- mBackgroundsPalette->move((mContainer->width() - mBackgroundsPalette->width()) / 2,
- (mContainer->height() - mBackgroundsPalette->height()) / 5);
- }
-}
-
-
-void UBBoardPaletteManager::backgroundPaletteClosed()
-{
- UBApplication::mainWindow->actionBackgrounds->setChecked(false);
-}
-
-
-void UBBoardPaletteManager::toggleStylusPalette(bool checked)
-{
- mStylusPalette->setVisible(checked);
-}
-
-
-void UBBoardPaletteManager::toggleErasePalette(bool checked)
-{
- mErasePalette->setVisible(checked);
- if (checked)
- {
- UBApplication::mainWindow->actionBackgrounds->setChecked(false);
- UBApplication::mainWindow->actionNewPage->setChecked(false);
-
- mErasePalette->adjustSizeAndPosition();
- mErasePalette->move((mContainer->width() - mErasePalette->width()) / 2,
- (mContainer->height() - mErasePalette->height()) / 5);
- }
-}
-
-
-void UBBoardPaletteManager::erasePaletteClosed()
-{
- UBApplication::mainWindow->actionErase->setChecked(false);
-}
-
-
-void UBBoardPaletteManager::togglePagePalette(bool checked)
-{
- mPagePalette->setVisible(checked);
- if (checked)
- {
- UBApplication::mainWindow->actionBackgrounds->setChecked(false);
- UBApplication::mainWindow->actionErase->setChecked(false);
-
- mPagePalette->adjustSizeAndPosition();
- mPagePalette->move((mContainer->width() - mPagePalette->width()) / 2,
- (mContainer->height() - mPagePalette->height()) / 5);
- }
-}
-
-
-void UBBoardPaletteManager::pagePaletteClosed()
-{
- UBApplication::mainWindow->actionPages->setChecked(false);
-}
-
-
-void UBBoardPaletteManager::tooglePodcastPalette(bool checked)
-{
- UBPodcastController::instance()->toggleRecordingPalette(checked);
-}
-
-
-void UBBoardPaletteManager::addItem(const QUrl& pUrl)
-{
- mItemUrl = pUrl;
- mPixmap = QPixmap();
- mPos = QPointF(0, 0);
- mScaleFactor = 1.;
-
- mAddItemPalette->show();
- mAddItemPalette->adjustSizeAndPosition();
-
- mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2,
- (mContainer->height() - mAddItemPalette->height()) / 5);
-}
-
-void UBBoardPaletteManager::changeMode(eUBDockPaletteWidgetMode newMode, bool isInit)
-{
- bool rightPaletteVisible = mRightPalette->switchMode(newMode);
- bool leftPaletteVisible = mLeftPalette->switchMode(newMode);
-
- switch( newMode )
- {
- case eUBDockPaletteWidget_BOARD:
- {
- // On Application start up the mAddItemPalette isn't initialized yet
- if(mAddItemPalette){
- mAddItemPalette->setParent(UBApplication::boardController->controlContainer());
- }
- mLeftPalette->assignParent(mContainer);
- mRightPalette->assignParent(mContainer);
- mRightPalette->stackUnder(mStylusPalette);
- mLeftPalette->stackUnder(mStylusPalette);
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- {
-
- if(mKeyboardPalette->m_isVisible)
- {
- mKeyboardPalette->hide();
- mKeyboardPalette->setParent(UBApplication::boardController->controlContainer());
- mKeyboardPalette->show();
- }
- else
- mKeyboardPalette->setParent(UBApplication::boardController->controlContainer());
- }
-
- mLeftPalette->setVisible(leftPaletteVisible);
- mRightPalette->setVisible(rightPaletteVisible);
-#ifdef Q_WS_WIN
- if (rightPaletteVisible)
- mRightPalette->setAdditionalVOffset(0);
-#endif
-
- if( !isInit )
- containerResized();
- if (mWebToolsCurrentPalette)
- mWebToolsCurrentPalette->hide();
- }
- break;
-
- case eUBDockPaletteWidget_DESKTOP:
- {
- mAddItemPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
- mLeftPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
- mRightPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
- mStylusPalette->raise();
-
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- {
-
- if(mKeyboardPalette->m_isVisible)
- {
- mKeyboardPalette->hide();
-#ifndef Q_WS_X11
- mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
-#else
- mKeyboardPalette->setParent(0);
-#endif
-#ifdef Q_WS_MAC
- mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint);
-#endif
- mKeyboardPalette->show();
- }
- else
-// In linux keyboard in desktop mode have to allways be with null parent
-#ifdef Q_WS_X11
- mKeyboardPalette->setParent(0);
-#else
- mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
-#endif //Q_WS_X11
-#ifdef Q_WS_MAC
- mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint);
-#endif
-
- }
-
- mLeftPalette->setVisible(leftPaletteVisible);
- mRightPalette->setVisible(rightPaletteVisible);
-#ifdef Q_WS_WIN
- if (rightPaletteVisible && UBSettings::settings()->appToolBarPositionedAtTop->get().toBool())
- mRightPalette->setAdditionalVOffset(30);
-#endif
-
- if(!isInit)
- UBApplication::applicationController->uninotesController()->TransparentWidgetResized();
-
- if (mWebToolsCurrentPalette)
- mWebToolsCurrentPalette->hide();
- }
- break;
-
- case eUBDockPaletteWidget_WEB:
- {
- mAddItemPalette->setParent(UBApplication::mainWindow);
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- {
-// tmp variable?
-// WBBrowserWindow* brWnd = UBApplication::webController->GetCurrentWebBrowser();
-
- if(mKeyboardPalette->m_isVisible)
- {
- mKeyboardPalette->hide();
- mKeyboardPalette->setParent(UBApplication::mainWindow);
- mKeyboardPalette->show();
- }
- else
- mKeyboardPalette->setParent(UBApplication::mainWindow);
- }
-
- }
- break;
-
- case eUBDockPaletteWidget_DOCUMENT:
- {
- mLeftPalette->setVisible(leftPaletteVisible);
- mRightPalette->setVisible(rightPaletteVisible);
- mLeftPalette->assignParent(UBApplication::documentController->controlView());
- mRightPalette->assignParent(UBApplication::documentController->controlView());
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- {
-
- if(mKeyboardPalette->m_isVisible)
- {
- mKeyboardPalette->hide();
- mKeyboardPalette->setParent(UBApplication::documentController->controlView());
- mKeyboardPalette->show();
- }
- else
- mKeyboardPalette->setParent(UBApplication::documentController->controlView());
- }
- if (mWebToolsCurrentPalette)
- mWebToolsCurrentPalette->hide();
- }
- break;
-
- default:
- {
- mLeftPalette->setVisible(leftPaletteVisible);
- mRightPalette->setVisible(rightPaletteVisible);
- mLeftPalette->assignParent(0);
- mRightPalette->assignParent(0);
- if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
- {
-
- if(mKeyboardPalette->m_isVisible)
- {
- mKeyboardPalette->hide();
- mKeyboardPalette->setParent(0);
- mKeyboardPalette->show();
- }
- else
- mKeyboardPalette->setParent(0);
- }
- }
- break;
- }
-
- if( !isInit )
- UBApplication::boardController->notifyPageChanged();
-
- emit signal_changeMode(newMode);
-}
-
-void UBBoardPaletteManager::addItem(const QPixmap& pPixmap, const QPointF& pos, qreal scaleFactor, const QUrl& sourceUrl)
-{
- mItemUrl = sourceUrl;
- mPixmap = pPixmap;
- mPos = pos;
- mScaleFactor = scaleFactor;
-
- mAddItemPalette->show();
- mAddItemPalette->adjustSizeAndPosition();
-
- mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2,
- (mContainer->height() - mAddItemPalette->height()) / 5);
-}
-
-
-void UBBoardPaletteManager::addItemToCurrentPage()
-{
- UBApplication::applicationController->showBoard();
- mAddItemPalette->hide();
- if(mPixmap.isNull())
- UBApplication::boardController->downloadURL(mItemUrl);
- else
- {
- UBGraphicsPixmapItem* item = UBApplication::boardController->activeScene()->addPixmap(mPixmap, NULL, mPos, mScaleFactor);
-
- item->setSourceUrl(mItemUrl);
- item->setSelected(true);
-
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
- }
-}
-
-
-void UBBoardPaletteManager::addItemToNewPage()
-{
- UBApplication::boardController->addScene();
- addItemToCurrentPage();
-}
-
-
-void UBBoardPaletteManager::addItemToLibrary()
-{
- if(mPixmap.isNull())
- {
- mPixmap = QPixmap(mItemUrl.toLocalFile());
- }
-
- if(!mPixmap.isNull())
- {
- if(mScaleFactor != 1.)
- {
- mPixmap = mPixmap.scaled(mScaleFactor * mPixmap.width(), mScaleFactor* mPixmap.height()
- , Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- QImage image = mPixmap.toImage();
-
- QDateTime now = QDateTime::currentDateTime();
- QString capturedName = tr("CapturedImage") + "-" + now.toString("dd-MM-yyyy hh-mm-ss") + ".png";
- mpFeaturesWidget->importImage(image, capturedName);
- }
- else
- {
- UBApplication::showMessage(tr("Error Adding Image to Library"));
- }
-
- mAddItemPalette->hide();
-}
-
-void UBBoardPaletteManager::zoomButtonPressed()
-{
- mZoomButtonPressedTime = QTime::currentTime();
-
- mPendingZoomButtonPressed = true;
- QTimer::singleShot(1000, this, SLOT(zoomButtonReleased()));
-}
-
-
-void UBBoardPaletteManager::zoomButtonReleased()
-{
- if (mPendingZoomButtonPressed)
- {
- if(mZoomButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
- {
- mBoardControler->zoomRestore();
- }
-
- mPendingZoomButtonPressed = false;
- }
-}
-
-void UBBoardPaletteManager::panButtonPressed()
-{
- mPanButtonPressedTime = QTime::currentTime();
-
- mPendingPanButtonPressed = true;
- QTimer::singleShot(1000, this, SLOT(panButtonReleased()));
-}
-
-
-void UBBoardPaletteManager::panButtonReleased()
-{
- if (mPendingPanButtonPressed)
- {
- if(mPanButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
- {
- mBoardControler->centerRestore();
- }
-
- mPendingPanButtonPressed = false;
- }
-}
-
-void UBBoardPaletteManager::showVirtualKeyboard(bool show)
-{
- if (mKeyboardPalette)
- mKeyboardPalette->setVisible(show);
-}
-
-void UBBoardPaletteManager::changeStylusPaletteOrientation(QVariant var)
-{
- bool bVertical = var.toBool();
- bool bVisible = mStylusPalette->isVisible();
-
- // Clean the old palette
- if(NULL != mStylusPalette)
- {
- delete mStylusPalette;
- mStylusPalette = NULL;
- }
-
- // Create the new palette
- if(bVertical)
- {
- mStylusPalette = new UBStylusPalette(mContainer, Qt::Vertical);
- }
- else
- {
- mStylusPalette = new UBStylusPalette(mContainer, Qt::Horizontal);
- }
-
- connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int)));
- mStylusPalette->setVisible(bVisible); // always show stylus palette at startup
-}
-
-
-void UBBoardPaletteManager::connectToDocumentController()
-{
- emit connectToDocController();
-}
-
-void UBBoardPaletteManager::refreshPalettes()
-{
- mRightPalette->update();
- mLeftPalette->update();
-}
-
-void UBBoardPaletteManager::startDownloads()
-{
- if(!mDownloadInProgress)
- {
- mDownloadInProgress = true;
- mpDownloadWidget->setVisibleState(true);
- mRightPalette->addTab(mpDownloadWidget);
- }
-}
-
-void UBBoardPaletteManager::stopDownloads()
-{
- if(mDownloadInProgress)
- {
- mDownloadInProgress = false;
- mpDownloadWidget->setVisibleState(false);
- mRightPalette->removeTab(mpDownloadWidget);
- }
-}
+
+
+#include "UBBoardPaletteManager.h"
+
+#include "frameworks/UBPlatformUtils.h"
+#include "frameworks/UBFileSystemUtils.h"
+
+#include "core/UBApplication.h"
+#include "core/UBApplicationController.h"
+#include "core/UBSettings.h"
+#include "core/UBSetting.h"
+#include "core/UBDisplayManager.h"
+
+#include "gui/UBMainWindow.h"
+#include "gui/UBStylusPalette.h"
+#include "gui/UBKeyboardPalette.h"
+#include "gui/UBToolWidget.h"
+#include "gui/UBZoomPalette.h"
+#include "gui/UBWebToolsPalette.h"
+#include "gui/UBActionPalette.h"
+#include "gui/UBFavoriteToolPalette.h"
+#include "gui/UBDockTeacherGuideWidget.h"
+
+
+#include "web/UBWebPage.h"
+#include "web/UBWebController.h"
+#include "web/browser/WBBrowserWindow.h"
+#include "web/browser/WBTabWidget.h"
+#include "web/browser/WBWebView.h"
+
+#include "desktop/UBDesktopAnnotationController.h"
+
+
+#include "network/UBNetworkAccessManager.h"
+#include "network/UBServerXMLHttpRequest.h"
+
+#include "domain/UBGraphicsScene.h"
+#include "domain/UBGraphicsPixmapItem.h"
+
+#include "document/UBDocumentProxy.h"
+#include "podcast/UBPodcastController.h"
+#include "board/UBDrawingController.h"
+
+#include "tools/UBToolsManager.h"
+
+#include "UBBoardController.h"
+
+#include "document/UBDocumentController.h"
+
+#include "core/memcheck.h"
+
+UBBoardPaletteManager::UBBoardPaletteManager(QWidget* container, UBBoardController* pBoardController)
+ : QObject(container)
+ , mKeyboardPalette(0)
+ , mWebToolsCurrentPalette(0)
+ , mContainer(container)
+ , mBoardControler(pBoardController)
+ , mStylusPalette(0)
+ , mZoomPalette(0)
+ , mLeftPalette(NULL)
+ , mRightPalette(NULL)
+ , mBackgroundsPalette(0)
+ , mToolsPalette(0)
+ , mAddItemPalette(0)
+ , mErasePalette(NULL)
+ , mPagePalette(NULL)
+ , mPendingPageButtonPressed(false)
+ , mPendingZoomButtonPressed(false)
+ , mPendingPanButtonPressed(false)
+ , mPendingEraseButtonPressed(false)
+ , mpPageNavigWidget(NULL)
+ , mpCachePropWidget(NULL)
+ , mpDownloadWidget(NULL)
+ , mpTeacherGuideWidget(NULL)
+ , mDownloadInProgress(false)
+{
+ setupPalettes();
+ connectPalettes();
+}
+
+
+UBBoardPaletteManager::~UBBoardPaletteManager()
+{
+
+// mAddedItemPalette is delete automatically because of is parent
+// that changes depending on the mode
+
+// mMainWindow->centralWidget is the parent of mStylusPalette
+// do not delete this here.
+}
+
+void UBBoardPaletteManager::initPalettesPosAtStartup()
+{
+ mStylusPalette->initPosition();
+}
+
+void UBBoardPaletteManager::setupLayout()
+{
+
+}
+
+/**
+ * \brief Set up the dock palette widgets
+ */
+void UBBoardPaletteManager::setupDockPaletteWidgets()
+{
+
+ //------------------------------------------------//
+ // Create the widgets for the dock palettes
+
+ mpPageNavigWidget = new UBPageNavigationWidget();
+
+ mpCachePropWidget = new UBCachePropertiesWidget();
+
+ mpDownloadWidget = new UBDockDownloadWidget();
+
+ // Add the dock palettes
+ mLeftPalette = new UBLeftPalette(mContainer);
+
+ // LEFT palette widgets
+ mpPageNavigWidget = new UBPageNavigationWidget();
+ mLeftPalette->registerWidget(mpPageNavigWidget);
+ mLeftPalette->addTab(mpPageNavigWidget);
+
+ if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool() || UBSettings::settings()->teacherGuideLessonPagesActivated->get().toBool()){
+ mpTeacherGuideWidget = new UBDockTeacherGuideWidget();
+ mLeftPalette->registerWidget(mpTeacherGuideWidget);
+ mLeftPalette->addTab(mpTeacherGuideWidget);
+ }
+
+ mLeftPalette->connectSignals();
+ mLeftPalette->showTabWidget(0);
+
+ mRightPalette = new UBRightPalette(mContainer);
+ // RIGHT palette widgets
+ mpFeaturesWidget = new UBFeaturesWidget();
+ mRightPalette->registerWidget(mpFeaturesWidget);
+ mRightPalette->addTab(mpFeaturesWidget);
+
+ // The cache widget will be visible only if a cache is put on the page
+ mRightPalette->registerWidget(mpCachePropWidget);
+
+ // The download widget will be part of the right palette but
+ // will become visible only when the first download starts
+ mRightPalette->registerWidget(mpDownloadWidget);
+ mRightPalette->connectSignals();
+ changeMode(eUBDockPaletteWidget_BOARD, true);
+
+ // Hide the tabs that must be hidden
+ mRightPalette->removeTab(mpDownloadWidget);
+ mRightPalette->removeTab(mpCachePropWidget);
+
+}
+
+void UBBoardPaletteManager::slot_changeMainMode(UBApplicationController::MainMode mainMode)
+{
+// Board = 0, Internet, Document, Tutorial, ParaschoolEditor, WebDocument
+
+ switch( mainMode )
+ {
+ case UBApplicationController::Board:
+ {
+ // call changeMode only when switch NOT from desktop mode
+ if(!UBApplication::applicationController->isShowingDesktop())
+ changeMode(eUBDockPaletteWidget_BOARD);
+ }
+ break;
+
+ case UBApplicationController::Tutorial:
+ {
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ mKeyboardPalette->hide();
+ }
+ break;
+
+ case UBApplicationController::Internet:
+ changeMode(eUBDockPaletteWidget_WEB);
+ break;
+
+ case UBApplicationController::Document:
+ changeMode(eUBDockPaletteWidget_DOCUMENT);
+ break;
+
+ default:
+ {
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ mKeyboardPalette->hide();
+ }
+ break;
+ }
+}
+
+void UBBoardPaletteManager::slot_changeDesktopMode(bool isDesktop)
+{
+ UBApplicationController::MainMode currMode = UBApplication::applicationController->displayMode();
+ if(!isDesktop)
+ {
+ switch( currMode )
+ {
+ case UBApplicationController::Board:
+ changeMode(eUBDockPaletteWidget_BOARD);
+ break;
+
+ default:
+ break;
+ }
+ }
+ else
+ changeMode(eUBDockPaletteWidget_DESKTOP);
+}
+
+void UBBoardPaletteManager::setupPalettes()
+{
+
+ if (UBPlatformUtils::hasVirtualKeyboard())
+ {
+ mKeyboardPalette = new UBKeyboardPalette(0);
+#ifndef Q_WS_WIN
+ connect(mKeyboardPalette, SIGNAL(closed()), mKeyboardPalette, SLOT(onDeactivated()));
+#endif
+ }
+
+
+ setupDockPaletteWidgets();
+
+
+ // Add the other palettes
+ mStylusPalette = new UBStylusPalette(mContainer, UBSettings::settings()->appToolBarOrientationVertical->get().toBool() ? Qt::Vertical : Qt::Horizontal);
+ connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int)));
+ mStylusPalette->show(); // always show stylus palette at startup
+
+ mZoomPalette = new UBZoomPalette(mContainer);
+
+ mStylusPalette->stackUnder(mZoomPalette);
+
+ QList backgroundsActions;
+
+ backgroundsActions << UBApplication::mainWindow->actionPlainLightBackground;
+ backgroundsActions << UBApplication::mainWindow->actionCrossedLightBackground;
+ backgroundsActions << UBApplication::mainWindow->actionPlainDarkBackground;
+ backgroundsActions << UBApplication::mainWindow->actionCrossedDarkBackground;
+
+ mBackgroundsPalette = new UBActionPalette(backgroundsActions, Qt::Horizontal , mContainer);
+ mBackgroundsPalette->setButtonIconSize(QSize(128, 128));
+ mBackgroundsPalette->groupActions();
+ mBackgroundsPalette->setClosable(true);
+ mBackgroundsPalette->setAutoClose(true);
+ mBackgroundsPalette->adjustSizeAndPosition();
+ mBackgroundsPalette->hide();
+
+ QList addItemActions;
+
+ addItemActions << UBApplication::mainWindow->actionAddItemToCurrentPage;
+ addItemActions << UBApplication::mainWindow->actionAddItemToNewPage;
+ addItemActions << UBApplication::mainWindow->actionAddItemToLibrary;
+
+ mAddItemPalette = new UBActionPalette(addItemActions, Qt::Horizontal, mContainer);
+ mAddItemPalette->setButtonIconSize(QSize(128, 128));
+ mAddItemPalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
+ mAddItemPalette->groupActions();
+ mAddItemPalette->setClosable(true);
+ mAddItemPalette->adjustSizeAndPosition();
+ mAddItemPalette->hide();
+
+ QList eraseActions;
+
+ eraseActions << UBApplication::mainWindow->actionEraseAnnotations;
+ eraseActions << UBApplication::mainWindow->actionEraseItems;
+ eraseActions << UBApplication::mainWindow->actionClearPage;
+ eraseActions << UBApplication::mainWindow->actionEraseBackground;
+
+ mErasePalette = new UBActionPalette(eraseActions, Qt::Horizontal , mContainer);
+ mErasePalette->setButtonIconSize(QSize(128, 128));
+ mErasePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
+ mErasePalette->groupActions();
+ mErasePalette->setClosable(true);
+ mErasePalette->adjustSizeAndPosition();
+ mErasePalette->hide();
+
+ QList pageActions;
+
+ pageActions << UBApplication::mainWindow->actionNewPage;
+ pageActions << UBApplication::mainWindow->actionDuplicatePage;
+ pageActions << UBApplication::mainWindow->actionImportPage;
+
+ mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer);
+ mPagePalette->setButtonIconSize(QSize(128, 128));
+ mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
+ mPagePalette->groupActions();
+ mPagePalette->setClosable(true);
+ mPagePalette->adjustSizeAndPosition();
+ mPagePalette->hide();
+
+ connect(UBSettings::settings()->appToolBarOrientationVertical, SIGNAL(changed(QVariant)), this, SLOT(changeStylusPaletteOrientation(QVariant)));
+}
+
+void UBBoardPaletteManager::pagePaletteButtonPressed()
+{
+ mPageButtonPressedTime = QTime::currentTime();
+
+ mPendingPageButtonPressed = true;
+ QTimer::singleShot(1000, this, SLOT(pagePaletteButtonReleased()));
+}
+
+
+void UBBoardPaletteManager::pagePaletteButtonReleased()
+{
+ if (mPendingPageButtonPressed)
+ {
+ if( mPageButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
+ {
+ // The palette is reinstanciated because the duplication depends on the current scene
+ delete(mPagePalette);
+ mPagePalette = 0;
+ QListpageActions;
+ pageActions << UBApplication::mainWindow->actionNewPage;
+ UBBoardController* boardController = UBApplication::boardController;
+ if(UBApplication::documentController->pageCanBeDuplicated(UBDocumentContainer::pageFromSceneIndex(boardController->activeSceneIndex()))){
+ pageActions << UBApplication::mainWindow->actionDuplicatePage;
+ }
+ pageActions << UBApplication::mainWindow->actionImportPage;
+
+ mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer);
+ mPagePalette->setButtonIconSize(QSize(128, 128));
+ mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
+ mPagePalette->groupActions();
+ mPagePalette->setClosable(true);
+
+ // As we recreate the pagePalette every time, we must reconnect the slots
+ connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
+ connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed()));
+
+ togglePagePalette(true);
+ }
+ else
+ {
+ UBApplication::mainWindow->actionNewPage->trigger();
+ }
+
+ mPendingPageButtonPressed = false;
+ }
+}
+
+void UBBoardPaletteManager::erasePaletteButtonPressed()
+{
+ mEraseButtonPressedTime = QTime::currentTime();
+
+ mPendingEraseButtonPressed = true;
+ QTimer::singleShot(1000, this, SLOT(erasePaletteButtonReleased()));
+}
+
+
+void UBBoardPaletteManager::erasePaletteButtonReleased()
+{
+ if (mPendingEraseButtonPressed)
+ {
+ if( mEraseButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
+ {
+ toggleErasePalette(true);
+ }
+ else
+ {
+ UBApplication::mainWindow->actionClearPage->trigger();
+ }
+
+ mPendingEraseButtonPressed = false;
+ }
+}
+
+
+
+void UBBoardPaletteManager::linkClicked(const QUrl& url)
+{
+ UBApplication::applicationController->showInternet();
+ UBApplication::webController->loadUrl(url);
+}
+
+
+void UBBoardPaletteManager::purchaseLinkActivated(const QString& link)
+{
+ UBApplication::applicationController->showInternet();
+ UBApplication::webController->loadUrl(QUrl(link));
+}
+
+void UBBoardPaletteManager::connectPalettes()
+{
+ connect(UBApplication::mainWindow->actionStylus, SIGNAL(toggled(bool)), this, SLOT(toggleStylusPalette(bool)));
+
+ foreach(QWidget *widget, UBApplication::mainWindow->actionZoomIn->associatedWidgets())
+ {
+ QAbstractButton *button = qobject_cast(widget);
+ if (button)
+ {
+ connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed()));
+ connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased()));
+ }
+ }
+
+ foreach(QWidget *widget, UBApplication::mainWindow->actionZoomOut->associatedWidgets())
+ {
+ QAbstractButton *button = qobject_cast(widget);
+ if (button)
+ {
+ connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed()));
+ connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased()));
+ }
+ }
+
+ foreach(QWidget *widget, UBApplication::mainWindow->actionHand->associatedWidgets())
+ {
+ QAbstractButton *button = qobject_cast(widget);
+ if (button)
+ {
+ connect(button, SIGNAL(pressed()), this, SLOT(panButtonPressed()));
+ connect(button, SIGNAL(released()), this, SLOT(panButtonReleased()));
+ }
+ }
+
+ connect(UBApplication::mainWindow->actionBackgrounds, SIGNAL(toggled(bool)), this, SLOT(toggleBackgroundPalette(bool)));
+ connect(mBackgroundsPalette, SIGNAL(closed()), this, SLOT(backgroundPaletteClosed()));
+
+ connect(UBApplication::mainWindow->actionPlainLightBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
+ connect(UBApplication::mainWindow->actionCrossedLightBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
+ connect(UBApplication::mainWindow->actionPlainDarkBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
+ connect(UBApplication::mainWindow->actionCrossedDarkBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
+ connect(UBApplication::mainWindow->actionPodcast, SIGNAL(triggered(bool)), this, SLOT(tooglePodcastPalette(bool)));
+
+ connect(UBApplication::mainWindow->actionAddItemToCurrentPage, SIGNAL(triggered()), this, SLOT(addItemToCurrentPage()));
+ connect(UBApplication::mainWindow->actionAddItemToNewPage, SIGNAL(triggered()), this, SLOT(addItemToNewPage()));
+ connect(UBApplication::mainWindow->actionAddItemToLibrary, SIGNAL(triggered()), this, SLOT(addItemToLibrary()));
+
+ connect(UBApplication::mainWindow->actionEraseItems, SIGNAL(triggered()), mErasePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionEraseAnnotations, SIGNAL(triggered()), mErasePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionClearPage, SIGNAL(triggered()), mErasePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionEraseBackground,SIGNAL(triggered()),mErasePalette,SLOT(close()));
+ connect(mErasePalette, SIGNAL(closed()), this, SLOT(erasePaletteClosed()));
+
+ foreach(QWidget *widget, UBApplication::mainWindow->actionErase->associatedWidgets())
+ {
+ QAbstractButton *button = qobject_cast(widget);
+ if (button)
+ {
+ connect(button, SIGNAL(pressed()), this, SLOT(erasePaletteButtonPressed()));
+ connect(button, SIGNAL(released()), this, SLOT(erasePaletteButtonReleased()));
+ }
+ }
+
+ connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
+ connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
+ connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed()));
+
+ foreach(QWidget *widget, UBApplication::mainWindow->actionPages->associatedWidgets())
+ {
+ QAbstractButton *button = qobject_cast(widget);
+ if (button)
+ {
+ connect(button, SIGNAL(pressed()), this, SLOT(pagePaletteButtonPressed()));
+ connect(button, SIGNAL(released()), this, SLOT(pagePaletteButtonReleased()));
+ }
+ }
+
+}
+
+
+bool isFirstResized = true;
+void UBBoardPaletteManager::containerResized()
+{
+ int innerMargin = UBSettings::boardMargin;
+
+ int userLeft = innerMargin;
+ int userWidth = mContainer->width() - (2 * innerMargin);
+ int userTop = innerMargin;
+ int userHeight = mContainer->height() - (2 * innerMargin);
+
+ if(mStylusPalette)
+ {
+ mStylusPalette->move(userLeft, userTop);
+ mStylusPalette->adjustSizeAndPosition();
+ mStylusPalette->initPosition();
+ }
+
+ if(mZoomPalette)
+ {
+ mZoomPalette->move(userLeft + userWidth - mZoomPalette->width()
+ , userTop + userHeight /*- mPageNumberPalette->height()*/ - innerMargin - mZoomPalette->height());
+ mZoomPalette->adjustSizeAndPosition();
+ }
+
+ if (isFirstResized && mKeyboardPalette && mKeyboardPalette->parent() == UBApplication::boardController->controlContainer())
+ {
+ isFirstResized = false;
+ mKeyboardPalette->move(userLeft + (userWidth - mKeyboardPalette->width())/2,
+ userTop + (userHeight - mKeyboardPalette->height())/2);
+ mKeyboardPalette->adjustSizeAndPosition();
+ }
+
+ if(mLeftPalette)
+ {
+ mLeftPalette->resize(mLeftPalette->width()-1, mContainer->height());
+ mLeftPalette->resize(mLeftPalette->width(), mContainer->height());
+ }
+
+ if(mRightPalette)
+ {
+ mRightPalette->resize(mRightPalette->width()-1, mContainer->height());
+ mRightPalette->resize(mRightPalette->width(), mContainer->height());
+ }
+}
+
+
+void UBBoardPaletteManager::changeBackground()
+{
+ if (UBApplication::mainWindow->actionCrossedLightBackground->isChecked())
+ UBApplication::boardController->changeBackground(false, true);
+ else if (UBApplication::mainWindow->actionPlainDarkBackground->isChecked())
+ UBApplication::boardController->changeBackground(true, false);
+ else if (UBApplication::mainWindow->actionCrossedDarkBackground->isChecked())
+ UBApplication::boardController->changeBackground(true, true);
+ else
+ UBApplication::boardController->changeBackground(false, false);
+
+ UBApplication::mainWindow->actionBackgrounds->setChecked(false);
+}
+
+
+void UBBoardPaletteManager::activeSceneChanged()
+{
+ UBGraphicsScene *activeScene = UBApplication::boardController->activeScene();
+ int pageIndex = UBApplication::boardController->activeSceneIndex();
+
+ if (mStylusPalette)
+ connect(mStylusPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
+
+ if (mpPageNavigWidget)
+ {
+ mpPageNavigWidget->setPageNumber(UBDocumentContainer::pageFromSceneIndex(pageIndex), activeScene->document()->pageCount());
+ }
+
+ if (mZoomPalette)
+ connect(mZoomPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
+
+ if (mBackgroundsPalette)
+ connect(mBackgroundsPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
+}
+
+
+void UBBoardPaletteManager::toggleBackgroundPalette(bool checked)
+{
+ mBackgroundsPalette->setVisible(checked);
+
+ if (checked)
+ {
+ UBApplication::mainWindow->actionErase->setChecked(false);
+ UBApplication::mainWindow->actionNewPage->setChecked(false);
+
+ mBackgroundsPalette->adjustSizeAndPosition();
+ mBackgroundsPalette->move((mContainer->width() - mBackgroundsPalette->width()) / 2,
+ (mContainer->height() - mBackgroundsPalette->height()) / 5);
+ }
+}
+
+
+void UBBoardPaletteManager::backgroundPaletteClosed()
+{
+ UBApplication::mainWindow->actionBackgrounds->setChecked(false);
+}
+
+
+void UBBoardPaletteManager::toggleStylusPalette(bool checked)
+{
+ mStylusPalette->setVisible(checked);
+}
+
+
+void UBBoardPaletteManager::toggleErasePalette(bool checked)
+{
+ mErasePalette->setVisible(checked);
+ if (checked)
+ {
+ UBApplication::mainWindow->actionBackgrounds->setChecked(false);
+ UBApplication::mainWindow->actionNewPage->setChecked(false);
+
+ mErasePalette->adjustSizeAndPosition();
+ mErasePalette->move((mContainer->width() - mErasePalette->width()) / 2,
+ (mContainer->height() - mErasePalette->height()) / 5);
+ }
+}
+
+
+void UBBoardPaletteManager::erasePaletteClosed()
+{
+ UBApplication::mainWindow->actionErase->setChecked(false);
+}
+
+
+void UBBoardPaletteManager::togglePagePalette(bool checked)
+{
+ mPagePalette->setVisible(checked);
+ if (checked)
+ {
+ UBApplication::mainWindow->actionBackgrounds->setChecked(false);
+ UBApplication::mainWindow->actionErase->setChecked(false);
+
+ mPagePalette->adjustSizeAndPosition();
+ mPagePalette->move((mContainer->width() - mPagePalette->width()) / 2,
+ (mContainer->height() - mPagePalette->height()) / 5);
+ }
+}
+
+
+void UBBoardPaletteManager::pagePaletteClosed()
+{
+ UBApplication::mainWindow->actionPages->setChecked(false);
+}
+
+
+void UBBoardPaletteManager::tooglePodcastPalette(bool checked)
+{
+ UBPodcastController::instance()->toggleRecordingPalette(checked);
+}
+
+
+void UBBoardPaletteManager::addItem(const QUrl& pUrl)
+{
+ mItemUrl = pUrl;
+ mPixmap = QPixmap();
+ mPos = QPointF(0, 0);
+ mScaleFactor = 1.;
+
+ mAddItemPalette->show();
+ mAddItemPalette->adjustSizeAndPosition();
+
+ mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2,
+ (mContainer->height() - mAddItemPalette->height()) / 5);
+}
+
+void UBBoardPaletteManager::changeMode(eUBDockPaletteWidgetMode newMode, bool isInit)
+{
+ bool rightPaletteVisible = mRightPalette->switchMode(newMode);
+ bool leftPaletteVisible = mLeftPalette->switchMode(newMode);
+
+ switch( newMode )
+ {
+ case eUBDockPaletteWidget_BOARD:
+ {
+ // On Application start up the mAddItemPalette isn't initialized yet
+ if(mAddItemPalette){
+ mAddItemPalette->setParent(UBApplication::boardController->controlContainer());
+ }
+ mLeftPalette->assignParent(mContainer);
+ mRightPalette->assignParent(mContainer);
+ mRightPalette->stackUnder(mStylusPalette);
+ mLeftPalette->stackUnder(mStylusPalette);
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ {
+
+ if(mKeyboardPalette->m_isVisible)
+ {
+ mKeyboardPalette->hide();
+ mKeyboardPalette->setParent(UBApplication::boardController->controlContainer());
+ mKeyboardPalette->show();
+ }
+ else
+ mKeyboardPalette->setParent(UBApplication::boardController->controlContainer());
+ }
+
+ mLeftPalette->setVisible(leftPaletteVisible);
+ mRightPalette->setVisible(rightPaletteVisible);
+#ifdef Q_WS_WIN
+ if (rightPaletteVisible)
+ mRightPalette->setAdditionalVOffset(0);
+#endif
+
+ if( !isInit )
+ containerResized();
+ if (mWebToolsCurrentPalette)
+ mWebToolsCurrentPalette->hide();
+ }
+ break;
+
+ case eUBDockPaletteWidget_DESKTOP:
+ {
+ mAddItemPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
+ mLeftPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
+ mRightPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
+ mStylusPalette->raise();
+
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ {
+
+ if(mKeyboardPalette->m_isVisible)
+ {
+ mKeyboardPalette->hide();
+#ifndef Q_WS_X11
+ mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
+#else
+ mKeyboardPalette->setParent(0);
+#endif
+#ifdef Q_WS_MAC
+ mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint);
+#endif
+ mKeyboardPalette->show();
+ }
+ else
+// In linux keyboard in desktop mode have to allways be with null parent
+#ifdef Q_WS_X11
+ mKeyboardPalette->setParent(0);
+#else
+ mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
+#endif //Q_WS_X11
+#ifdef Q_WS_MAC
+ mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint);
+#endif
+
+ }
+
+ mLeftPalette->setVisible(leftPaletteVisible);
+ mRightPalette->setVisible(rightPaletteVisible);
+#ifdef Q_WS_WIN
+ if (rightPaletteVisible && UBSettings::settings()->appToolBarPositionedAtTop->get().toBool())
+ mRightPalette->setAdditionalVOffset(30);
+#endif
+
+ if(!isInit)
+ UBApplication::applicationController->uninotesController()->TransparentWidgetResized();
+
+ if (mWebToolsCurrentPalette)
+ mWebToolsCurrentPalette->hide();
+ }
+ break;
+
+ case eUBDockPaletteWidget_WEB:
+ {
+ mAddItemPalette->setParent(UBApplication::mainWindow);
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ {
+// tmp variable?
+// WBBrowserWindow* brWnd = UBApplication::webController->GetCurrentWebBrowser();
+
+ if(mKeyboardPalette->m_isVisible)
+ {
+ mKeyboardPalette->hide();
+ mKeyboardPalette->setParent(UBApplication::mainWindow);
+ mKeyboardPalette->show();
+ }
+ else
+ mKeyboardPalette->setParent(UBApplication::mainWindow);
+ }
+
+ }
+ break;
+
+ case eUBDockPaletteWidget_DOCUMENT:
+ {
+ mLeftPalette->setVisible(leftPaletteVisible);
+ mRightPalette->setVisible(rightPaletteVisible);
+ mLeftPalette->assignParent(UBApplication::documentController->controlView());
+ mRightPalette->assignParent(UBApplication::documentController->controlView());
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ {
+
+ if(mKeyboardPalette->m_isVisible)
+ {
+ mKeyboardPalette->hide();
+ mKeyboardPalette->setParent(UBApplication::documentController->controlView());
+ mKeyboardPalette->show();
+ }
+ else
+ mKeyboardPalette->setParent(UBApplication::documentController->controlView());
+ }
+ if (mWebToolsCurrentPalette)
+ mWebToolsCurrentPalette->hide();
+ }
+ break;
+
+ default:
+ {
+ mLeftPalette->setVisible(leftPaletteVisible);
+ mRightPalette->setVisible(rightPaletteVisible);
+ mLeftPalette->assignParent(0);
+ mRightPalette->assignParent(0);
+ if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
+ {
+
+ if(mKeyboardPalette->m_isVisible)
+ {
+ mKeyboardPalette->hide();
+ mKeyboardPalette->setParent(0);
+ mKeyboardPalette->show();
+ }
+ else
+ mKeyboardPalette->setParent(0);
+ }
+ }
+ break;
+ }
+
+ if( !isInit )
+ UBApplication::boardController->notifyPageChanged();
+
+ emit signal_changeMode(newMode);
+}
+
+void UBBoardPaletteManager::addItem(const QPixmap& pPixmap, const QPointF& pos, qreal scaleFactor, const QUrl& sourceUrl)
+{
+ mItemUrl = sourceUrl;
+ mPixmap = pPixmap;
+ mPos = pos;
+ mScaleFactor = scaleFactor;
+
+ mAddItemPalette->show();
+ mAddItemPalette->adjustSizeAndPosition();
+
+ mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2,
+ (mContainer->height() - mAddItemPalette->height()) / 5);
+}
+
+
+void UBBoardPaletteManager::addItemToCurrentPage()
+{
+ UBApplication::applicationController->showBoard();
+ mAddItemPalette->hide();
+ if(mPixmap.isNull())
+ UBApplication::boardController->downloadURL(mItemUrl);
+ else
+ {
+ UBGraphicsPixmapItem* item = UBApplication::boardController->activeScene()->addPixmap(mPixmap, NULL, mPos, mScaleFactor);
+
+ item->setSourceUrl(mItemUrl);
+ item->setSelected(true);
+
+ UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
+ }
+}
+
+
+void UBBoardPaletteManager::addItemToNewPage()
+{
+ UBApplication::boardController->addScene();
+ addItemToCurrentPage();
+}
+
+
+void UBBoardPaletteManager::addItemToLibrary()
+{
+ if(mPixmap.isNull())
+ {
+ mPixmap = QPixmap(mItemUrl.toLocalFile());
+ }
+
+ if(!mPixmap.isNull())
+ {
+ if(mScaleFactor != 1.)
+ {
+ mPixmap = mPixmap.scaled(mScaleFactor * mPixmap.width(), mScaleFactor* mPixmap.height()
+ , Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ QImage image = mPixmap.toImage();
+
+ QDateTime now = QDateTime::currentDateTime();
+ QString capturedName = tr("CapturedImage") + "-" + now.toString("dd-MM-yyyy hh-mm-ss") + ".png";
+ mpFeaturesWidget->importImage(image, capturedName);
+ }
+ else
+ {
+ UBApplication::showMessage(tr("Error Adding Image to Library"));
+ }
+
+ mAddItemPalette->hide();
+}
+
+void UBBoardPaletteManager::zoomButtonPressed()
+{
+ mZoomButtonPressedTime = QTime::currentTime();
+
+ mPendingZoomButtonPressed = true;
+ QTimer::singleShot(1000, this, SLOT(zoomButtonReleased()));
+}
+
+
+void UBBoardPaletteManager::zoomButtonReleased()
+{
+ if (mPendingZoomButtonPressed)
+ {
+ if(mZoomButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
+ {
+ mBoardControler->zoomRestore();
+ }
+
+ mPendingZoomButtonPressed = false;
+ }
+}
+
+void UBBoardPaletteManager::panButtonPressed()
+{
+ mPanButtonPressedTime = QTime::currentTime();
+
+ mPendingPanButtonPressed = true;
+ QTimer::singleShot(1000, this, SLOT(panButtonReleased()));
+}
+
+
+void UBBoardPaletteManager::panButtonReleased()
+{
+ if (mPendingPanButtonPressed)
+ {
+ if(mPanButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
+ {
+ mBoardControler->centerRestore();
+ }
+
+ mPendingPanButtonPressed = false;
+ }
+}
+
+void UBBoardPaletteManager::showVirtualKeyboard(bool show)
+{
+ if (mKeyboardPalette)
+ mKeyboardPalette->setVisible(show);
+}
+
+void UBBoardPaletteManager::changeStylusPaletteOrientation(QVariant var)
+{
+ bool bVertical = var.toBool();
+ bool bVisible = mStylusPalette->isVisible();
+
+ // Clean the old palette
+ if(NULL != mStylusPalette)
+ {
+ delete mStylusPalette;
+ mStylusPalette = NULL;
+ }
+
+ // Create the new palette
+ if(bVertical)
+ {
+ mStylusPalette = new UBStylusPalette(mContainer, Qt::Vertical);
+ }
+ else
+ {
+ mStylusPalette = new UBStylusPalette(mContainer, Qt::Horizontal);
+ }
+
+ connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int)));
+ mStylusPalette->setVisible(bVisible); // always show stylus palette at startup
+}
+
+
+void UBBoardPaletteManager::connectToDocumentController()
+{
+ emit connectToDocController();
+}
+
+void UBBoardPaletteManager::refreshPalettes()
+{
+ mRightPalette->update();
+ mLeftPalette->update();
+}
+
+void UBBoardPaletteManager::startDownloads()
+{
+ if(!mDownloadInProgress)
+ {
+ mDownloadInProgress = true;
+ mpDownloadWidget->setVisibleState(true);
+ mRightPalette->addTab(mpDownloadWidget);
+ }
+}
+
+void UBBoardPaletteManager::stopDownloads()
+{
+ if(mDownloadInProgress)
+ {
+ mDownloadInProgress = false;
+ mpDownloadWidget->setVisibleState(false);
+ mRightPalette->removeTab(mpDownloadWidget);
+ }
+}
diff --git a/src/board/UBBoardPaletteManager.h b/src/board/UBBoardPaletteManager.h
index cb38459f..7526e081 100644
--- a/src/board/UBBoardPaletteManager.h
+++ b/src/board/UBBoardPaletteManager.h
@@ -19,173 +19,173 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBBOARDPALETTEMANAGER_H_
-#define UBBOARDPALETTEMANAGER_H_
-
-#include
-#include
-
-#include "gui/UBLeftPalette.h"
-#include "gui/UBRightPalette.h"
-#include "gui/UBPageNavigationWidget.h"
-#include "gui/UBCachePropertiesWidget.h"
-#include "gui/UBDockDownloadWidget.h"
-#include "core/UBApplicationController.h"
-#include "gui/UBFeaturesWidget.h"
-
-
-class UBWebToolsPalette;
-class UBStylusPalette;
-class UBClockPalette;
-class UBPageNumberPalette;
-class UBZoomPalette;
-class UBActionPalette;
-class UBBoardController;
-class UBServerXMLHttpRequest;
-class UBKeyboardPalette;
-class UBMainWindow;
-class UBApplicationController;
-class UBDockTeacherGuideWidget;
-
-class UBBoardPaletteManager : public QObject
-{
- Q_OBJECT
-
- public:
- UBBoardPaletteManager(QWidget* container, UBBoardController* controller);
- virtual ~UBBoardPaletteManager();
-
- void setupLayout();
- UBLeftPalette* leftPalette(){return mLeftPalette;}
- UBRightPalette* rightPalette(){return mRightPalette;}
- UBStylusPalette* stylusPalette(){return mStylusPalette;}
- UBActionPalette *addItemPalette() {return mAddItemPalette;}
- void showVirtualKeyboard(bool show = true);
- void initPalettesPosAtStartup();
- void connectToDocumentController();
- void refreshPalettes();
-
- UBKeyboardPalette *mKeyboardPalette;
-
- void setCurrentWebToolsPalette(UBWebToolsPalette *palette) {mWebToolsCurrentPalette = palette;}
- UBWebToolsPalette* mWebToolsCurrentPalette;
-
- UBDockTeacherGuideWidget* teacherGuideDockWidget() { return mpTeacherGuideWidget;}
-
- void processPalettersWidget(UBDockPalette *paletter, eUBDockPaletteWidgetMode mode);
- void changeMode(eUBDockPaletteWidgetMode newMode, bool isInit = false);
- void startDownloads();
- void stopDownloads();
-
- signals:
- void connectToDocController();
- void signal_changeMode(eUBDockPaletteWidgetMode newMode);
-
- public slots:
-
- void activeSceneChanged();
- void containerResized();
- void addItem(const QUrl& pUrl);
- void addItem(const QPixmap& pPixmap, const QPointF& p = QPointF(0.0, 0.0), qreal scale = 1.0, const QUrl& sourceUrl = QUrl());
-
- void slot_changeMainMode(UBApplicationController::MainMode);
- void slot_changeDesktopMode(bool);
-
- void toggleErasePalette(bool ckecked);
-
- private:
-
- void setupPalettes();
- void connectPalettes();
- void positionFreeDisplayPalette();
- void setupDockPaletteWidgets();
-
- QWidget* mContainer;
- UBBoardController *mBoardControler;
-
- UBStylusPalette *mStylusPalette;
-
- UBZoomPalette *mZoomPalette;
-
- /** The left dock palette */
- UBLeftPalette* mLeftPalette;
- /** The right dock palette */
- UBRightPalette* mRightPalette;
-
- UBActionPalette *mBackgroundsPalette;
- UBActionPalette *mToolsPalette;
- UBActionPalette* mAddItemPalette;
- UBActionPalette* mErasePalette;
- UBActionPalette* mPagePalette;
-
- QUrl mItemUrl;
- QPixmap mPixmap;
- QPointF mPos;
- qreal mScaleFactor;
-
- QTime mPageButtonPressedTime;
- bool mPendingPageButtonPressed;
-
- QTime mZoomButtonPressedTime;
- bool mPendingZoomButtonPressed;
-
- QTime mPanButtonPressedTime;
- bool mPendingPanButtonPressed;
-
- QTime mEraseButtonPressedTime;
- bool mPendingEraseButtonPressed;
-
- /** The page navigator widget */
- UBPageNavigationWidget* mpPageNavigWidget;
-
- /** The cache properties widget */
- UBCachePropertiesWidget* mpCachePropWidget;
-
- UBFeaturesWidget *mpFeaturesWidget;
-
- /** The download widget */
- UBDockDownloadWidget* mpDownloadWidget;
- UBDockTeacherGuideWidget* mpTeacherGuideWidget;
-
- bool mDownloadInProgress;
-
- private slots:
-
- void changeBackground();
-
- void toggleBackgroundPalette(bool checked);
- void backgroundPaletteClosed();
-
- void toggleStylusPalette(bool checked);
- void tooglePodcastPalette(bool checked);
-
- void erasePaletteButtonPressed();
- void erasePaletteButtonReleased();
-
- void erasePaletteClosed();
-
- void togglePagePalette(bool ckecked);
- void pagePaletteClosed();
-
- void pagePaletteButtonPressed();
- void pagePaletteButtonReleased();
-
- void addItemToCurrentPage();
- void addItemToNewPage();
- void addItemToLibrary();
-
- void purchaseLinkActivated(const QString&);
-
- void linkClicked(const QUrl& url);
-
- void zoomButtonPressed();
- void zoomButtonReleased();
- void panButtonPressed();
- void panButtonReleased();
-
- void changeStylusPaletteOrientation(QVariant var);
-};
-
-#endif /* UBBOARDPALETTEMANAGER_H_ */
+
+
+#ifndef UBBOARDPALETTEMANAGER_H_
+#define UBBOARDPALETTEMANAGER_H_
+
+#include
+#include
+
+#include "gui/UBLeftPalette.h"
+#include "gui/UBRightPalette.h"
+#include "gui/UBPageNavigationWidget.h"
+#include "gui/UBCachePropertiesWidget.h"
+#include "gui/UBDockDownloadWidget.h"
+#include "core/UBApplicationController.h"
+#include "gui/UBFeaturesWidget.h"
+
+
+class UBWebToolsPalette;
+class UBStylusPalette;
+class UBClockPalette;
+class UBPageNumberPalette;
+class UBZoomPalette;
+class UBActionPalette;
+class UBBoardController;
+class UBServerXMLHttpRequest;
+class UBKeyboardPalette;
+class UBMainWindow;
+class UBApplicationController;
+class UBDockTeacherGuideWidget;
+
+class UBBoardPaletteManager : public QObject
+{
+ Q_OBJECT
+
+ public:
+ UBBoardPaletteManager(QWidget* container, UBBoardController* controller);
+ virtual ~UBBoardPaletteManager();
+
+ void setupLayout();
+ UBLeftPalette* leftPalette(){return mLeftPalette;}
+ UBRightPalette* rightPalette(){return mRightPalette;}
+ UBStylusPalette* stylusPalette(){return mStylusPalette;}
+ UBActionPalette *addItemPalette() {return mAddItemPalette;}
+ void showVirtualKeyboard(bool show = true);
+ void initPalettesPosAtStartup();
+ void connectToDocumentController();
+ void refreshPalettes();
+
+ UBKeyboardPalette *mKeyboardPalette;
+
+ void setCurrentWebToolsPalette(UBWebToolsPalette *palette) {mWebToolsCurrentPalette = palette;}
+ UBWebToolsPalette* mWebToolsCurrentPalette;
+
+ UBDockTeacherGuideWidget* teacherGuideDockWidget() { return mpTeacherGuideWidget;}
+
+ void processPalettersWidget(UBDockPalette *paletter, eUBDockPaletteWidgetMode mode);
+ void changeMode(eUBDockPaletteWidgetMode newMode, bool isInit = false);
+ void startDownloads();
+ void stopDownloads();
+
+ signals:
+ void connectToDocController();
+ void signal_changeMode(eUBDockPaletteWidgetMode newMode);
+
+ public slots:
+
+ void activeSceneChanged();
+ void containerResized();
+ void addItem(const QUrl& pUrl);
+ void addItem(const QPixmap& pPixmap, const QPointF& p = QPointF(0.0, 0.0), qreal scale = 1.0, const QUrl& sourceUrl = QUrl());
+
+ void slot_changeMainMode(UBApplicationController::MainMode);
+ void slot_changeDesktopMode(bool);
+
+ void toggleErasePalette(bool ckecked);
+
+ private:
+
+ void setupPalettes();
+ void connectPalettes();
+ void positionFreeDisplayPalette();
+ void setupDockPaletteWidgets();
+
+ QWidget* mContainer;
+ UBBoardController *mBoardControler;
+
+ UBStylusPalette *mStylusPalette;
+
+ UBZoomPalette *mZoomPalette;
+
+ /** The left dock palette */
+ UBLeftPalette* mLeftPalette;
+ /** The right dock palette */
+ UBRightPalette* mRightPalette;
+
+ UBActionPalette *mBackgroundsPalette;
+ UBActionPalette *mToolsPalette;
+ UBActionPalette* mAddItemPalette;
+ UBActionPalette* mErasePalette;
+ UBActionPalette* mPagePalette;
+
+ QUrl mItemUrl;
+ QPixmap mPixmap;
+ QPointF mPos;
+ qreal mScaleFactor;
+
+ QTime mPageButtonPressedTime;
+ bool mPendingPageButtonPressed;
+
+ QTime mZoomButtonPressedTime;
+ bool mPendingZoomButtonPressed;
+
+ QTime mPanButtonPressedTime;
+ bool mPendingPanButtonPressed;
+
+ QTime mEraseButtonPressedTime;
+ bool mPendingEraseButtonPressed;
+
+ /** The page navigator widget */
+ UBPageNavigationWidget* mpPageNavigWidget;
+
+ /** The cache properties widget */
+ UBCachePropertiesWidget* mpCachePropWidget;
+
+ UBFeaturesWidget *mpFeaturesWidget;
+
+ /** The download widget */
+ UBDockDownloadWidget* mpDownloadWidget;
+ UBDockTeacherGuideWidget* mpTeacherGuideWidget;
+
+ bool mDownloadInProgress;
+
+ private slots:
+
+ void changeBackground();
+
+ void toggleBackgroundPalette(bool checked);
+ void backgroundPaletteClosed();
+
+ void toggleStylusPalette(bool checked);
+ void tooglePodcastPalette(bool checked);
+
+ void erasePaletteButtonPressed();
+ void erasePaletteButtonReleased();
+
+ void erasePaletteClosed();
+
+ void togglePagePalette(bool ckecked);
+ void pagePaletteClosed();
+
+ void pagePaletteButtonPressed();
+ void pagePaletteButtonReleased();
+
+ void addItemToCurrentPage();
+ void addItemToNewPage();
+ void addItemToLibrary();
+
+ void purchaseLinkActivated(const QString&);
+
+ void linkClicked(const QUrl& url);
+
+ void zoomButtonPressed();
+ void zoomButtonReleased();
+ void panButtonPressed();
+ void panButtonReleased();
+
+ void changeStylusPaletteOrientation(QVariant var);
+};
+
+#endif /* UBBOARDPALETTEMANAGER_H_ */
diff --git a/src/board/UBBoardView.h b/src/board/UBBoardView.h
index 01ee8ad9..fe709991 100644
--- a/src/board/UBBoardView.h
+++ b/src/board/UBBoardView.h
@@ -19,164 +19,164 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBBOARDVIEW_H_
-#define UBBOARDVIEW_H_
-
-#include
-#include "core/UB.h"
-#include "domain/UBGraphicsDelegateFrame.h"
-
-class UBBoardController;
-class UBGraphicsScene;
-class UBGraphicsWidgetItem;
-class UBRubberBand;
-
-class UBBoardView : public QGraphicsView
-{
- Q_OBJECT
-
- public:
-
- UBBoardView(UBBoardController* pController, QWidget* pParent = 0, bool isControl = false, bool isDesktop = false);
- UBBoardView(UBBoardController* pController, int pStartLayer, int pEndLayer, QWidget* pParent = 0, bool isControl = false, bool isDesktop = false);
- virtual ~UBBoardView();
-
- UBGraphicsScene* scene();
-
- void forcedTabletRelease();
-
- void setToolCursor(int tool);
-
- void rubberItems();
- void moveRubberedItems(QPointF movingVector);
-
- void setMultiselection(bool enable);
- bool isMultipleSelectionEnabled() { return mMultipleSelectionIsEnabled; }
-
- signals:
-
- void resized(QResizeEvent* event);
- void hidden();
- void shown();
- void clickOnBoard();
-
- protected:
-
- bool itemIsLocked(QGraphicsItem *item);
- bool isUBItem(QGraphicsItem *item); // we should to determine items who is not UB and use general scene behavior for them.
- bool isCppTool(QGraphicsItem *item);
- void handleItemsSelection(QGraphicsItem *item);
- bool itemShouldReceiveMousePressEvent(QGraphicsItem *item);
- bool itemShouldReceiveSuspendedMousePressEvent(QGraphicsItem *item);
- bool itemHaveParentWithType(QGraphicsItem *item, int type);
- bool itemShouldBeMoved(QGraphicsItem *item);
- QGraphicsItem* determineItemToPress(QGraphicsItem *item);
- QGraphicsItem* determineItemToMove(QGraphicsItem *item);
- void handleItemMousePress(QMouseEvent *event);
- void handleItemMouseMove(QMouseEvent *event);
-
- virtual bool event (QEvent * e);
-
- virtual void keyPressEvent(QKeyEvent *event);
- virtual void keyReleaseEvent(QKeyEvent *event);
- virtual void tabletEvent(QTabletEvent * event);
- virtual void mouseDoubleClickEvent(QMouseEvent *event);
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void mouseMoveEvent(QMouseEvent *event);
- virtual void mouseReleaseEvent(QMouseEvent *event);
- virtual void wheelEvent(QWheelEvent *event);
- virtual void leaveEvent ( QEvent * event);
-
- virtual void focusOutEvent ( QFocusEvent * event );
-
- virtual void drawItems(QPainter *painter, int numItems,
- QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[]);
-
-// virtual void dragEnterEvent(QDragEnterEvent * event);
- virtual void dropEvent(QDropEvent *event);
- virtual void dragMoveEvent(QDragMoveEvent *event);
-
- virtual void resizeEvent(QResizeEvent * event);
-
- virtual void drawBackground(QPainter *painter, const QRectF &rect);
-
- virtual void showEvent(QShowEvent * event);
- virtual void hideEvent(QHideEvent * event);
-
- private:
-
- void init();
-
- inline bool shouldDisplayItem(QGraphicsItem *item)
- {
- bool ok;
- int itemLayerType = item->data(UBGraphicsItemData::ItemLayerType).toInt(&ok);
- return (ok && (itemLayerType >= mStartLayer && itemLayerType <= mEndLayer));
- }
-
- QList processMimeData(const QMimeData* pMimeData);
-
- UBBoardController* mController;
-
- int mStartLayer, mEndLayer;
- bool mFilterZIndex;
-
- bool mTabletStylusIsPressed;
- bool mUsingTabletEraser;
-
- bool mPendingStylusReleaseEvent;
-
- bool mMouseButtonIsPressed;
- QPointF mPreviousPoint;
- QPoint mMouseDownPos;
-
- bool mPenPressureSensitive;
- bool mMarkerPressureSensitive;
- bool mUseHighResTabletEvent;
-
- QRubberBand *mRubberBand;
- bool mIsCreatingTextZone;
- bool mIsCreatingSceneGrabZone;
-
- bool isAbsurdPoint(QPoint point);
-
- bool mVirtualKeyboardActive;
- bool mOkOnWidget;
-
- bool mWidgetMoved;
- QPointF mLastPressedMousePos;
- QGraphicsItem *movingItem;
- QMouseEvent *suspendedMousePressEvent;
-
- bool moveRubberBand;
- UBRubberBand *mUBRubberBand;
-
- QList mRubberedItems;
- QSet mJustSelectedItems;
-
- int mLongPressInterval;
- QTimer mLongPressTimer;
-
- bool mIsDragInProgress;
- bool mMultipleSelectionIsEnabled;
- bool bIsControl;
- bool bIsDesktop;
- bool mRubberBandInPlayMode;
-
- static bool hasSelectedParents(QGraphicsItem * item);
-
- private slots:
-
- void settingChanged(QVariant newValue);
-
- public slots:
-
- void virtualKeyboardActivated(bool b);
- void longPressEvent();
-
-};
-
-#endif /* UBBOARDVIEW_H_ */
+
+
+#ifndef UBBOARDVIEW_H_
+#define UBBOARDVIEW_H_
+
+#include
+#include "core/UB.h"
+#include "domain/UBGraphicsDelegateFrame.h"
+
+class UBBoardController;
+class UBGraphicsScene;
+class UBGraphicsWidgetItem;
+class UBRubberBand;
+
+class UBBoardView : public QGraphicsView
+{
+ Q_OBJECT
+
+ public:
+
+ UBBoardView(UBBoardController* pController, QWidget* pParent = 0, bool isControl = false, bool isDesktop = false);
+ UBBoardView(UBBoardController* pController, int pStartLayer, int pEndLayer, QWidget* pParent = 0, bool isControl = false, bool isDesktop = false);
+ virtual ~UBBoardView();
+
+ UBGraphicsScene* scene();
+
+ void forcedTabletRelease();
+
+ void setToolCursor(int tool);
+
+ void rubberItems();
+ void moveRubberedItems(QPointF movingVector);
+
+ void setMultiselection(bool enable);
+ bool isMultipleSelectionEnabled() { return mMultipleSelectionIsEnabled; }
+
+ signals:
+
+ void resized(QResizeEvent* event);
+ void hidden();
+ void shown();
+ void clickOnBoard();
+
+ protected:
+
+ bool itemIsLocked(QGraphicsItem *item);
+ bool isUBItem(QGraphicsItem *item); // we should to determine items who is not UB and use general scene behavior for them.
+ bool isCppTool(QGraphicsItem *item);
+ void handleItemsSelection(QGraphicsItem *item);
+ bool itemShouldReceiveMousePressEvent(QGraphicsItem *item);
+ bool itemShouldReceiveSuspendedMousePressEvent(QGraphicsItem *item);
+ bool itemHaveParentWithType(QGraphicsItem *item, int type);
+ bool itemShouldBeMoved(QGraphicsItem *item);
+ QGraphicsItem* determineItemToPress(QGraphicsItem *item);
+ QGraphicsItem* determineItemToMove(QGraphicsItem *item);
+ void handleItemMousePress(QMouseEvent *event);
+ void handleItemMouseMove(QMouseEvent *event);
+
+ virtual bool event (QEvent * e);
+
+ virtual void keyPressEvent(QKeyEvent *event);
+ virtual void keyReleaseEvent(QKeyEvent *event);
+ virtual void tabletEvent(QTabletEvent * event);
+ virtual void mouseDoubleClickEvent(QMouseEvent *event);
+ virtual void mousePressEvent(QMouseEvent *event);
+ virtual void mouseMoveEvent(QMouseEvent *event);
+ virtual void mouseReleaseEvent(QMouseEvent *event);
+ virtual void wheelEvent(QWheelEvent *event);
+ virtual void leaveEvent ( QEvent * event);
+
+ virtual void focusOutEvent ( QFocusEvent * event );
+
+ virtual void drawItems(QPainter *painter, int numItems,
+ QGraphicsItem *items[],
+ const QStyleOptionGraphicsItem options[]);
+
+// virtual void dragEnterEvent(QDragEnterEvent * event);
+ virtual void dropEvent(QDropEvent *event);
+ virtual void dragMoveEvent(QDragMoveEvent *event);
+
+ virtual void resizeEvent(QResizeEvent * event);
+
+ virtual void drawBackground(QPainter *painter, const QRectF &rect);
+
+ virtual void showEvent(QShowEvent * event);
+ virtual void hideEvent(QHideEvent * event);
+
+ private:
+
+ void init();
+
+ inline bool shouldDisplayItem(QGraphicsItem *item)
+ {
+ bool ok;
+ int itemLayerType = item->data(UBGraphicsItemData::ItemLayerType).toInt(&ok);
+ return (ok && (itemLayerType >= mStartLayer && itemLayerType <= mEndLayer));
+ }
+
+ QList processMimeData(const QMimeData* pMimeData);
+
+ UBBoardController* mController;
+
+ int mStartLayer, mEndLayer;
+ bool mFilterZIndex;
+
+ bool mTabletStylusIsPressed;
+ bool mUsingTabletEraser;
+
+ bool mPendingStylusReleaseEvent;
+
+ bool mMouseButtonIsPressed;
+ QPointF mPreviousPoint;
+ QPoint mMouseDownPos;
+
+ bool mPenPressureSensitive;
+ bool mMarkerPressureSensitive;
+ bool mUseHighResTabletEvent;
+
+ QRubberBand *mRubberBand;
+ bool mIsCreatingTextZone;
+ bool mIsCreatingSceneGrabZone;
+
+ bool isAbsurdPoint(QPoint point);
+
+ bool mVirtualKeyboardActive;
+ bool mOkOnWidget;
+
+ bool mWidgetMoved;
+ QPointF mLastPressedMousePos;
+ QGraphicsItem *movingItem;
+ QMouseEvent *suspendedMousePressEvent;
+
+ bool moveRubberBand;
+ UBRubberBand *mUBRubberBand;
+
+ QList mRubberedItems;
+ QSet mJustSelectedItems;
+
+ int mLongPressInterval;
+ QTimer mLongPressTimer;
+
+ bool mIsDragInProgress;
+ bool mMultipleSelectionIsEnabled;
+ bool bIsControl;
+ bool bIsDesktop;
+ bool mRubberBandInPlayMode;
+
+ static bool hasSelectedParents(QGraphicsItem * item);
+
+ private slots:
+
+ void settingChanged(QVariant newValue);
+
+ public slots:
+
+ void virtualKeyboardActivated(bool b);
+ void longPressEvent();
+
+};
+
+#endif /* UBBOARDVIEW_H_ */
diff --git a/src/core/UBApplication.h b/src/core/UBApplication.h
index b98fe9ce..b3d6aa27 100644
--- a/src/core/UBApplication.h
+++ b/src/core/UBApplication.h
@@ -19,155 +19,155 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#ifndef UBAPPLICATION_H_
-#define UBAPPLICATION_H_
-
-#include
-
-#include "qtsingleapplication.h"
-
-#include "transition/UniboardSankoreTransition.h"
-
-namespace Ui
-{
- class MainWindow;
-}
-
-
-class UBBoardController;
-class UBWebController;
-class UBControlView;
-class UBPreferencesController;
-class UBResources;
-class UBSettings;
-class UBPersistenceManager;
-class UBApplicationController;
-class UBDocumentController;
-class UBMainWindow;
-
-class UBApplication : public QtSingleApplication
-{
- Q_OBJECT;
-
- public:
-
- UBApplication(const QString &id, int &argc, char **argv);
- virtual ~UBApplication();
-
- int exec(const QString& pFileToImport);
-
- void cleanup();
-
- static QPointer undoStack;
-
- static UBApplicationController *applicationController;
- static UBBoardController* boardController;
- static UBWebController* webController;
- static UBDocumentController* documentController;
- static UniboardSankoreTransition* mUniboardSankoreTransition;
-
- static UBMainWindow* mainWindow;
-
- static UBApplication* app()
- {
- return static_castqApp;
- }
-
- static const QString mimeTypeUniboardDocument;
- static const QString mimeTypeUniboardPage;
- static const QString mimeTypeUniboardPageItem;
- static const QString mimeTypeUniboardPageThumbnail;
-
- static void showMessage(const QString& message, bool showSpinningWheel = false);
- static void setDisabled(bool disable);
-
- static QObject* staticMemoryCleaner;
-
- void decorateActionMenu(QAction* action);
- void insertSpaceToToolbarBeforeAction(QToolBar* toolbar, QAction* action, int width = -1);
-
- int toolBarHeight();
- bool eventFilter(QObject *obj, QEvent *event);
-
- bool isVerbose() { return mIsVerbose;}
- void setVerbose(bool verbose){mIsVerbose = verbose;}
- static QString urlFromHtml(QString html);
- static bool isFromWeb(QString url);
-
- signals:
-
- public slots:
-
- void showBoard();
- void showInternet();
- void showDocument();
- void startScript();
- void stopScript();
-
- void toolBarPositionChanged(QVariant topOrBottom);
- void toolBarDisplayTextChanged(QVariant display);
-
- void closeEvent(QCloseEvent *event);
-
- /**
- * Used on Windows platform to open file in running application. On MacOS X opening file is done through the
- * FileOpen event that is handle in eventFilter method.
- */
- bool handleOpenMessage(const QString& pMessage);
-
- private slots:
-
- void closing();
-#ifdef Q_WS_MAC
- void showMinimized();
-#endif
- void importUniboardFiles();
-
- void onScreenCountChanged(int newCount);
-
- private:
- void updateProtoActionsState();
- void setupTranslators(QStringList args);
- QList mProtoMenus;
- bool mIsVerbose;
- QString checkLanguageAvailabilityForSankore(QString& language);
- protected:
-
-#if defined(Q_WS_MACX) && !defined(QT_MAC_USE_COCOA)
- bool macEventFilter(EventHandlerCallRef caller, EventRef event);
-#endif
-
- UBPreferencesController* mPreferencesController;
- QTranslator* mApplicationTranslator;
- QTranslator* mQtGuiTranslator;
-
-};
-
-
-class UBStyle : public QPlastiqueStyle
-{
- public:
-
- UBStyle()
- : QPlastiqueStyle()
- {
- // NOOP
- }
-
- virtual ~UBStyle()
- {
- // NOOP
- }
-
- /*
- * redefined to be more cocoa like on texts
- */
- virtual void drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const;
-
-
-};
-
-#endif /* UBAPPLICATION_H_ */
+
+
+#ifndef UBAPPLICATION_H_
+#define UBAPPLICATION_H_
+
+#include
+
+#include "qtsingleapplication.h"
+
+#include "transition/UniboardSankoreTransition.h"
+
+namespace Ui
+{
+ class MainWindow;
+}
+
+
+class UBBoardController;
+class UBWebController;
+class UBControlView;
+class UBPreferencesController;
+class UBResources;
+class UBSettings;
+class UBPersistenceManager;
+class UBApplicationController;
+class UBDocumentController;
+class UBMainWindow;
+
+class UBApplication : public QtSingleApplication
+{
+ Q_OBJECT;
+
+ public:
+
+ UBApplication(const QString &id, int &argc, char **argv);
+ virtual ~UBApplication();
+
+ int exec(const QString& pFileToImport);
+
+ void cleanup();
+
+ static QPointer undoStack;
+
+ static UBApplicationController *applicationController;
+ static UBBoardController* boardController;
+ static UBWebController* webController;
+ static UBDocumentController* documentController;
+ static UniboardSankoreTransition* mUniboardSankoreTransition;
+
+ static UBMainWindow* mainWindow;
+
+ static UBApplication* app()
+ {
+ return static_castqApp;
+ }
+
+ static const QString mimeTypeUniboardDocument;
+ static const QString mimeTypeUniboardPage;
+ static const QString mimeTypeUniboardPageItem;
+ static const QString mimeTypeUniboardPageThumbnail;
+
+ static void showMessage(const QString& message, bool showSpinningWheel = false);
+ static void setDisabled(bool disable);
+
+ static QObject* staticMemoryCleaner;
+
+ void decorateActionMenu(QAction* action);
+ void insertSpaceToToolbarBeforeAction(QToolBar* toolbar, QAction* action, int width = -1);
+
+ int toolBarHeight();
+ bool eventFilter(QObject *obj, QEvent *event);
+
+ bool isVerbose() { return mIsVerbose;}
+ void setVerbose(bool verbose){mIsVerbose = verbose;}
+ static QString urlFromHtml(QString html);
+ static bool isFromWeb(QString url);
+
+ signals:
+
+ public slots:
+
+ void showBoard();
+ void showInternet();
+ void showDocument();
+ void startScript();
+ void stopScript();
+
+ void toolBarPositionChanged(QVariant topOrBottom);
+ void toolBarDisplayTextChanged(QVariant display);
+
+ void closeEvent(QCloseEvent *event);
+
+ /**
+ * Used on Windows platform to open file in running application. On MacOS X opening file is done through the
+ * FileOpen event that is handle in eventFilter method.
+ */
+ bool handleOpenMessage(const QString& pMessage);
+
+ private slots:
+
+ void closing();
+#ifdef Q_WS_MAC
+ void showMinimized();
+#endif
+ void importUniboardFiles();
+
+ void onScreenCountChanged(int newCount);
+
+ private:
+ void updateProtoActionsState();
+ void setupTranslators(QStringList args);
+ QList mProtoMenus;
+ bool mIsVerbose;
+ QString checkLanguageAvailabilityForSankore(QString& language);
+ protected:
+
+#if defined(Q_WS_MACX) && !defined(QT_MAC_USE_COCOA)
+ bool macEventFilter(EventHandlerCallRef caller, EventRef event);
+#endif
+
+ UBPreferencesController* mPreferencesController;
+ QTranslator* mApplicationTranslator;
+ QTranslator* mQtGuiTranslator;
+
+};
+
+
+class UBStyle : public QPlastiqueStyle
+{
+ public:
+
+ UBStyle()
+ : QPlastiqueStyle()
+ {
+ // NOOP
+ }
+
+ virtual ~UBStyle()
+ {
+ // NOOP
+ }
+
+ /*
+ * redefined to be more cocoa like on texts
+ */
+ virtual void drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
+ bool enabled, const QString& text, QPalette::ColorRole textRole) const;
+
+
+};
+
+#endif /* UBAPPLICATION_H_ */
diff --git a/src/core/UBApplicationController.cpp b/src/core/UBApplicationController.cpp
index 865fca76..3922a385 100644
--- a/src/core/UBApplicationController.cpp
+++ b/src/core/UBApplicationController.cpp
@@ -19,820 +19,820 @@
* along with Open-Sankoré. If not, see .
*/
-
-
-#include "UBApplicationController.h"
-
-#include "frameworks/UBPlatformUtils.h"
-#include "frameworks/UBVersion.h"
-
-#include "core/UBApplication.h"
-#include "core/UBPersistenceManager.h"
-#include "core/UBSettings.h"
-#include "core/UBSetting.h"
-#include "core/UBDocumentManager.h"
-#include "core/UBDisplayManager.h"
-
-#include "board/UBBoardView.h"
-#include "board/UBBoardController.h"
-#include "board/UBBoardPaletteManager.h"
-#include "board/UBDrawingController.h"
-
-
-#include "document/UBDocumentProxy.h"
-#include "document/UBDocumentController.h"
-
-#include "domain/UBGraphicsWidgetItem.h"
-
-#include "desktop/UBDesktopPalette.h"
-#include "desktop/UBDesktopAnnotationController.h"
-
-#include "web/UBWebController.h"
-
-#include "gui/UBScreenMirror.h"
-#include "gui/UBMainWindow.h"
-#include "gui/UBDockTeacherGuideWidget.h"
-#include "gui/UBTeacherGuideWidget.h"
-
-#include "domain/UBGraphicsPixmapItem.h"
-
-#include "podcast/UBPodcastController.h"
-
-#include "network/UBNetworkAccessManager.h"
-
-#include "ui_mainWindow.h"
-
-#ifdef Q_WS_MAC
-#include
-#endif
-
-#include "core/memcheck.h"
-
-UBApplicationController::UBApplicationController(UBBoardView *pControlView,
- UBBoardView *pDisplayView,
- UBMainWindow* pMainWindow,
- QObject* parent,
- UBRightPalette* rightPalette)
- : QObject(parent)
- , mMainWindow(pMainWindow)
- , mControlView(pControlView)
- , mDisplayView(pDisplayView)
- , mMirror(0)
- , mMainMode(Board)
- , mDisplayManager(0)
- , mAutomaticCheckForUpdates(false)
- , mCheckingForUpdates(false)
- , mIsShowingDesktop(false)
- , mHttp(0)
-{
- mDisplayManager = new UBDisplayManager(this);
-
- mUninoteController = new UBDesktopAnnotationController(this, rightPalette);
-
- connect(mDisplayManager, SIGNAL(screenLayoutChanged()), this, SLOT(screenLayoutChanged()));
- connect(mDisplayManager, SIGNAL(screenLayoutChanged()), mUninoteController, SLOT(screenLayoutChanged()));
- connect(mDisplayManager, SIGNAL(screenLayoutChanged()), UBApplication::webController, SLOT(screenLayoutChanged()));
-
- connect(mUninoteController, SIGNAL(imageCaptured(const QPixmap &, bool)), this, SLOT(addCapturedPixmap(const QPixmap &, bool)));
- connect(mUninoteController, SIGNAL(restoreUniboard()), this, SLOT(hideDesktop()));
-
- for(int i = 0; i < mDisplayManager->numPreviousViews(); i++)
- {
- UBBoardView *previousView = new UBBoardView(UBApplication::boardController, UBItemLayerType::FixedBackground, UBItemLayerType::Tool, 0);
- previousView->setInteractive(false);
- mPreviousViews.append(previousView);
- }
-
- mBlackScene = new UBGraphicsScene(0); // deleted by UBApplicationController::destructor
- mBlackScene->setBackground(true, false);
-
- if (mDisplayManager->numScreens() >= 2)
- {
- mMirror = new UBScreenMirror();
- }
-
- connect(UBApplication::webController, SIGNAL(imageCaptured(const QPixmap &, bool, const QUrl&))
- , this, SLOT(addCapturedPixmap(const QPixmap &, bool, const QUrl&)));
-
- networkAccessManager = new QNetworkAccessManager (this);
- QTimer::singleShot (1000, this, SLOT (checkUpdateAtLaunch()));
-
-#ifdef Q_WS_X11
- mMainWindow->setStyleSheet("QToolButton { font-size: 11px}");
-#endif
-
-}
-
-
-UBApplicationController::~UBApplicationController()
-{
- foreach(UBBoardView* view, mPreviousViews)
- {
- delete view;
- }
-
- delete mBlackScene;
- delete mMirror;
- if (mHttp) delete mHttp;
-}
-
-
-void UBApplicationController::initViewState(int horizontalPosition, int verticalPostition)
-{
- mInitialHScroll = horizontalPosition;
- mInitialVScroll = verticalPostition;
-}
-
-
-void UBApplicationController::initScreenLayout(bool useMultiscreen)
-{
- mDisplayManager->setControlWidget(mMainWindow);
- mDisplayManager->setDisplayWidget(mDisplayView);
-
- mDisplayManager->setPreviousDisplaysWidgets(mPreviousViews);
- mDisplayManager->setDesktopWidget(mUninoteController->drawingView());
-
- mDisplayManager->setUseMultiScreen(useMultiscreen);
- mDisplayManager->adjustScreens(-1);
-}
-
-
-void UBApplicationController::screenLayoutChanged()
-{
- initViewState(mControlView->horizontalScrollBar()->value(),
- mControlView->verticalScrollBar()->value());
-
- adaptToolBar();
-
- adjustDisplayView();
-
- if (mDisplayManager->hasDisplay())
- {
- UBApplication::boardController->setBoxing(mDisplayView->geometry());
- }
- else
- {
- UBApplication::boardController->setBoxing(QRect());
- }
-
- adjustPreviousViews(0, 0);
-}
-
-
-void UBApplicationController::adaptToolBar()
-{
- bool highResolution = mMainWindow->width() > 1024;
-
- mMainWindow->actionClearPage->setVisible(Board == mMainMode && highResolution);
- mMainWindow->actionBoard->setVisible(Board != mMainMode || highResolution);
- mMainWindow->actionDocument->setVisible(Document != mMainMode || highResolution);
- mMainWindow->actionWeb->setVisible(Internet != mMainMode || highResolution);
- mMainWindow->boardToolBar->setIconSize(QSize(highResolution ? 48 : 42, mMainWindow->boardToolBar->iconSize().height()));
-
- mMainWindow->actionBoard->setEnabled(mMainMode != Board);
- mMainWindow->actionWeb->setEnabled(mMainMode != Internet);
- mMainWindow->actionDocument->setEnabled(mMainMode != Document);
-
- if (Document == mMainMode)
- {
- connect(UBApplication::instance(), SIGNAL(focusChanged(QWidget *, QWidget *)), UBApplication::documentController, SLOT(focusChanged(QWidget *, QWidget *)));
- }
- else
- {
- disconnect(UBApplication::instance(), SIGNAL(focusChanged(QWidget *, QWidget *)), UBApplication::documentController, SLOT(focusChanged(QWidget *, QWidget *)));
- if (Board == mMainMode)
- mMainWindow->actionDuplicate->setEnabled(true);
- }
-
- UBApplication::boardController->setToolbarTexts();
-
- UBApplication::webController->adaptToolBar();
-
-}
-
-
-void UBApplicationController::adjustDisplayView()
-{
- if (mDisplayView)
- {
- qreal systemDisplayViewScaleFactor = 1.0;
-
- QSize pageSize = UBApplication::boardController->activeScene()->nominalSize();
- QSize displaySize = mDisplayView->size();
-
- qreal hFactor = ((qreal)displaySize.width()) / ((qreal)pageSize.width());
- qreal vFactor = ((qreal)displaySize.height()) / ((qreal)pageSize.height());
-
- systemDisplayViewScaleFactor = qMin(hFactor, vFactor);
-
- QTransform tr;
- qreal scaleFactor = systemDisplayViewScaleFactor * UBApplication::boardController->currentZoom();
-
- tr.scale(scaleFactor, scaleFactor);
-
- QRect rect = mControlView->rect();
- QPoint center(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2);
-
- QTransform recentTransform = mDisplayView->transform();
-
- if (recentTransform != tr)
- mDisplayView->setTransform(tr);
-
- mDisplayView->centerOn(mControlView->mapToScene(center));
- }
-}
-
-
-void UBApplicationController::adjustPreviousViews(int pActiveSceneIndex, UBDocumentProxy *pActiveDocument)
-{
- int viewIndex = pActiveSceneIndex;
-
- foreach(UBBoardView* previousView, mPreviousViews)
- {
- if (viewIndex > 0)
- {
- viewIndex--;
-
- UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pActiveDocument, viewIndex);
-
- if (scene)
- {
- previousView->setScene(scene);
-
- qreal ratio = ((qreal)previousView->geometry().width()) / ((qreal)previousView->geometry().height());
- QRectF sceneRect = scene->normalizedSceneRect(ratio);
- qreal scaleRatio = previousView->geometry().width() / sceneRect.width();
-
- previousView->resetTransform();
-
- previousView->scale(scaleRatio, scaleRatio);
-
- previousView->centerOn(sceneRect.center());
- }
- }
- else
- {
- previousView->setScene(mBlackScene);
- }
- }
-}
-
-
-void UBApplicationController::blackout()
-{
- mDisplayManager->blackout();
-}
-
-
-void UBApplicationController::addCapturedPixmap(const QPixmap &pPixmap, bool pageMode, const QUrl& sourceUrl)
-{
- if (!pPixmap.isNull())
- {
- qreal sf = UBApplication::boardController->systemScaleFactor();
- qreal scaledWidth = ((qreal)pPixmap.width()) / sf;
- qreal scaledHeight = ((qreal)pPixmap.height()) / sf;
-
- QSize pageNominalSize = UBApplication::boardController->activeScene()->nominalSize();
-
- int newWidth = qMin((int)scaledWidth, pageNominalSize.width());
- int newHeight = qMin((int)scaledHeight, pageNominalSize.height());
-
- if (pageMode)
- {
- newHeight = pPixmap.height();
- }
-
- QSizeF scaledSize(scaledWidth, scaledHeight);
- scaledSize.scale(newWidth, newHeight, Qt::KeepAspectRatio);
-
- qreal scaleFactor = qMin(scaledSize.width() / (qreal)pPixmap.width(), scaledSize.height() / (qreal)pPixmap.height());
-
- QPointF pos(0.0, 0.0);
-
- if (pageMode)
- {
- pos.setY(pageNominalSize.height() / -2 + scaledSize.height() / 2);
- }
-
- UBApplication::boardController->paletteManager()->addItem(pPixmap, pos, scaleFactor, sourceUrl);
- }
-}
-
-
-void UBApplicationController::addCapturedEmbedCode(const QString& embedCode)
-{
- if (!embedCode.isEmpty())
- {
- showBoard();
-
- const QString userWidgetPath = UBSettings::settings()->userInteractiveDirectory() + "/" + tr("Web"); // TODO UB 4.x synch with w3cWidget
- QDir userWidgetDir(userWidgetPath);
-
- int width = 300;
- int height = 150;
-
- QString widgetPath = UBGraphicsW3CWidgetItem::createHtmlWrapperInDir(embedCode, userWidgetDir,
- QSize(width, height), UBStringUtils::toCanonicalUuid(QUuid::createUuid()));
-
- if (widgetPath.length() > 0)
- UBApplication::boardController->downloadURL(QUrl::fromLocalFile(widgetPath));
- }
-}
-
-
-void UBApplicationController::showBoard()
-{
- mMainWindow->webToolBar->hide();
- mMainWindow->documentToolBar->hide();
- mMainWindow->tutorialToolBar->hide();
- mMainWindow->boardToolBar->show();
-
- if (mMainMode == Document)
- {
- int selectedSceneIndex = UBApplication::documentController->getSelectedItemIndex();
- if (selectedSceneIndex != -1)
- {
- UBApplication::boardController->setActiveDocumentScene(UBApplication::documentController->selectedDocument(), selectedSceneIndex, true);
- }
- }
-
- mMainMode = Board;
-
- adaptToolBar();
-
- mirroringEnabled(false);
-
- mMainWindow->switchToBoardWidget();
-
- if (UBApplication::boardController)
- UBApplication::boardController->show();
-
- mIsShowingDesktop = false;
- UBPlatformUtils::setDesktopMode(false);
-
- mUninoteController->hideWindow();
-
- mMainWindow->show();
-
- emit mainModeChanged(Board);
-
- UBApplication::boardController->freezeW3CWidgets(false);
- UBApplication::boardController->activeScene()->updateGroupButtonState();
-}
-
-
-void UBApplicationController::showInternet()
-{
-
- if (UBApplication::boardController)
- {
- UBApplication::boardController->persistCurrentScene();
- UBApplication::boardController->hide();
- }
-
- if (UBSettings::settings()->webUseExternalBrowser->get().toBool())
- {
- showDesktop(true);
- UBApplication::webController->show(UBWebController::WebBrowser);
- // really no have emit mainModeChanged here ? potential problem with virtual keyboard ?
- }
- else
- {
- mMainWindow->boardToolBar->hide();
- mMainWindow->documentToolBar->hide();
- mMainWindow->tutorialToolBar->hide();
- mMainWindow->webToolBar->show();
-
- mMainMode = Internet;
-
- adaptToolBar();
-
- mMainWindow->show();
- mUninoteController->hideWindow();
-
- UBApplication::webController->show(UBWebController::WebBrowser);
-
- emit mainModeChanged(Internet);
- }
-}
-
-
-void UBApplicationController::showDocument()
-{
- mMainWindow->webToolBar->hide();
- mMainWindow->boardToolBar->hide();
- mMainWindow->tutorialToolBar->hide();
- mMainWindow->documentToolBar->show();
-
- mMainMode = Document;
-
- adaptToolBar();
-
- mirroringEnabled(false);
-
- mMainWindow->switchToDocumentsWidget();
-
- if (UBApplication::boardController)
- {
- if (UBApplication::boardController->activeScene()->isModified() || (UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()))
- UBApplication::boardController->persistCurrentScene();
- UBApplication::boardController->hide();
- }
-
- if (UBApplication::documentController)
- UBApplication::documentController->show();
-
- mMainWindow->show();
-
- mUninoteController->hideWindow();
-
- emit mainModeChanged(Document);
-}
-
-void UBApplicationController::showDesktop(bool dontSwitchFrontProcess)
-{
- int desktopWidgetIndex = qApp->desktop()->screenNumber(mMainWindow);
-
- if (UBApplication::boardController)
- UBApplication::boardController->hide();
-
- mMainWindow->hide();
- mUninoteController->showWindow();
-
- if (mMirror)
- {
- QRect rect = qApp->desktop()->screenGeometry(desktopWidgetIndex);
- mMirror->setSourceRect(rect);
- }
-
- mIsShowingDesktop = true;
- emit desktopMode(true);
-
- if (!dontSwitchFrontProcess) {
- UBPlatformUtils::bringPreviousProcessToFront();
- }
-
- UBDrawingController::drawingController()->setInDestopMode(true);
- UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
-}
-
-
-void UBApplicationController::showTutorial()
-{
-
- if (UBApplication::boardController)
- {
- UBApplication::boardController->persistCurrentScene();
- UBApplication::boardController->hide();
- }
-
- if (UBSettings::settings()->webUseExternalBrowser->get().toBool())
- {
- showDesktop(true);
- UBApplication::webController->show(UBWebController::Tutorial);
-
- }
- else{
- mMainWindow->webToolBar->hide();
- mMainWindow->boardToolBar->hide();
- mMainWindow->documentToolBar->hide();
- mMainWindow->tutorialToolBar->show();
-
-
- mMainMode = Tutorial;
-
- adaptToolBar();
-
- mUninoteController->hideWindow();
-
- UBApplication::webController->show(UBWebController::Tutorial);
-
- mirroringEnabled(false);
- emit mainModeChanged(mMainMode);
- }
-}
-
-
-void UBApplicationController::showSankoreEditor()
-{
-
- if (UBApplication::boardController)
- {
- UBApplication::boardController->persistCurrentScene();
- UBApplication::boardController->hide();
- }
-
-// it's needed not to duplicate webbrowser search in web mode. If I've breaked smbd's code let Ivan know
- UBApplication::webController->show(UBWebController::Paraschool);
-
- mMainWindow->webToolBar->hide();
- mMainWindow->boardToolBar->hide();
- mMainWindow->documentToolBar->hide();
- mMainWindow->tutorialToolBar->show();
-
-
- mMainMode = ParaschoolEditor;
-
- adaptToolBar();
-
- mUninoteController->hideWindow();
-
- mirroringEnabled(false);
- emit mainModeChanged(mMainMode);
-}
-
-void UBApplicationController::checkUpdate()
-{
- if(mHttp)
- delete mHttp;
- QUrl url("http://ftp.open-sankore.org/update.json");
- mHttp = new QHttp(url.host());
- connect(mHttp, SIGNAL(requestFinished(int,bool)), this, SLOT(updateRequestFinished(int,bool)));
- mHttp->get(url.path());
-}
-
-void UBApplicationController::updateRequestFinished(int id, bool error)
-{
- if (error){
- qWarning() << "http command id" << id << "return the error: " << mHttp->errorString();
- mHttp->close();
- }
- else{
- QString responseString = QString(mHttp->readAll());
- if (!responseString.isEmpty() && responseString.contains("version") && responseString.contains("url")){
- mHttp->close();
- downloadJsonFinished(responseString);
- }
- }
-}
-
-
-
-void UBApplicationController::downloadJsonFinished(QString currentJson)
-{
- QScriptValue scriptValue;
- QScriptEngine scriptEngine;
- scriptValue = scriptEngine.evaluate ("(" + currentJson + ")");
-
- UBVersion installedVersion (qApp->applicationVersion().left(4));
- UBVersion jsonVersion (scriptValue.property("version").toString().left(4));
-
- if (installedVersion.isValid() && jsonVersion.isValid() && jsonVersion > installedVersion) {
- if (UBApplication::mainWindow->yesNoQuestion(tr("Update available"), tr ("New update available, would you go to the web page ?"))){
- QUrl url(scriptValue.property ("url").toString());
- QDesktopServices::openUrl (url);
- }
- }
- else {
- if (isNoUpdateDisplayed) {
- mMainWindow->information(tr("Update"), tr("No update available"));
- }
- }
-}
-
-void UBApplicationController::checkUpdateAtLaunch()
-{
- if(UBSettings::settings()->appEnableAutomaticSoftwareUpdates->get().toBool()){
- isNoUpdateDisplayed = false;
- checkUpdate ();
- }
-}
-
-void UBApplicationController::checkUpdateRequest()
-{
- isNoUpdateDisplayed = true;
- checkUpdate ();
-}
-
-void UBApplicationController::hideDesktop()
-{
- if (mMainMode == Board)
- {
- showBoard();
- }
- else if (mMainMode == Internet)
- {
- showInternet();
- }
- else if (mMainMode == Document)
- {
- showDocument();
- }
- else if (mMainMode == Tutorial)
- {
- showTutorial();
- }
- else if (mMainMode == ParaschoolEditor)
- {
- showSankoreEditor();
- }
-
- mIsShowingDesktop = false;
-
- mDisplayManager->adjustScreens(-1);
-
- emit desktopMode(false);
-}
-
-void UBApplicationController::setMirrorSourceWidget(QWidget* pWidget)
-{
- if (mMirror)
- {
- mMirror->setSourceWidget(pWidget);
- }
-}
-
-
-void UBApplicationController::mirroringEnabled(bool enabled)
-{
- if (mMirror)
- {
- if (enabled)
- {
- mMirror->start();
- mDisplayManager->setDisplayWidget(mMirror);
-
- }
- else
- {
- mDisplayManager->setDisplayWidget(mDisplayView);
- mMirror->stop();
- }
-
- mMirror->setVisible(enabled && mDisplayManager->numScreens() > 1);
- mUninoteController->updateShowHideState(enabled);
- UBApplication::mainWindow->actionWebShowHideOnDisplay->setChecked(enabled);
- }
- else
- {
- mDisplayManager->setDisplayWidget(mDisplayView);
- }
-}
-
-
-void UBApplicationController::closing()
-{
- if (mMirror)
- mMirror->stop();
-
- if (mUninoteController)
- {
- mUninoteController->hideWindow();
- mUninoteController->close();
- }
-
- if (UBApplication::documentController)
- UBApplication::documentController->closing();
-}
-
-
-void UBApplicationController::showMessage(const QString& message, bool showSpinningWheel)
-{
- if (!UBApplication::closingDown())
- {
- if (mMainMode == Document)
- {
- UBApplication::boardController->hideMessage();
- UBApplication::documentController->showMessage(message, showSpinningWheel);
- }
- else
- {
- UBApplication::documentController->hideMessage();
- UBApplication::boardController->showMessage(message, showSpinningWheel);
- }
- }
-}
-
-
-void UBApplicationController::importFile(const QString& pFilePath)
-{
- const QFile fileToOpen(pFilePath);
-
- if (!fileToOpen.exists())
- return;
-
- UBDocumentProxy* document = 0;
-
- bool success = false;
-
- document = UBDocumentManager::documentManager()->importFile(fileToOpen, "");
-
- success = (document != 0);
-
- if (success && document)
- {
- if (mMainMode == Board || mMainMode == Internet)
- {
- if (UBApplication::boardController)
- {
- UBApplication::boardController->setActiveDocumentScene(document, 0);
- showBoard();
- }
- }
- else if (mMainMode == Document)
- {
- if (UBApplication::documentController)
- UBApplication::documentController->selectDocument(document);
- }
- }
-}
-
-void UBApplicationController::useMultiScreen(bool use)
-{
- mDisplayManager->setUseMultiScreen(use);
- mDisplayManager->adjustScreens(0);
- UBSettings::settings()->appUseMultiscreen->set(use);
-
-}
-
-
-QStringList UBApplicationController::widgetInlineJavaScripts()
-{
- QString scriptDirPath = UBPlatformUtils::applicationResourcesDirectory() + "/widget-inline-js";
- QDir scriptDir(scriptDirPath);
-
- QStringList scripts;
-
- if (scriptDir.exists())
- {
- QStringList files = scriptDir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
-
- foreach(QString file, files)
- {
- QFile scriptFile(scriptDirPath + "/" + file);
- if (file.endsWith(".js") && scriptFile.open(QIODevice::ReadOnly))
- {
- QString s = QString::fromUtf8(scriptFile.readAll());
-
- if (s.length() > 0)
- scripts << s;
-
- }
- }
- }
-
- qSort(scripts);
-
- return scripts;
-}
-
-
-
-void UBApplicationController::actionCut()
-{
- if (!UBApplication::closingDown())
- {
- if (mMainMode == Board)
- {
- UBApplication::boardController->cut();
- }
- else if(mMainMode == Document)
- {
- UBApplication::documentController->cut();
- }
- else if(mMainMode == Internet)
- {
- UBApplication::webController->cut();
- }
- }
-}
-
-
-void UBApplicationController::actionCopy()
-{
- if (!UBApplication::closingDown())
- {
- if (mMainMode == Board)
- {
- UBApplication::boardController->copy();
- }
- else if(mMainMode == Document)
- {
- UBApplication::documentController->copy();
- }
- else if(mMainMode == Internet)
- {
- UBApplication::webController->copy();
- }
- }
-}
-
-
-void UBApplicationController::actionPaste()
-{
- if (!UBApplication::closingDown())
- {
- if (mMainMode == Board)
- {
- UBApplication::boardController->paste();
- }
- else if (mMainMode == Document)
- {
- UBApplication::documentController->paste();
- }
- else if(mMainMode == Internet)
- {
- UBApplication::webController->paste();
- }
- }
-}
+
+
+#include "UBApplicationController.h"
+
+#include "frameworks/UBPlatformUtils.h"
+#include "frameworks/UBVersion.h"
+
+#include "core/UBApplication.h"
+#include "core/UBPersistenceManager.h"
+#include "core/UBSettings.h"
+#include "core/UBSetting.h"
+#include "core/UBDocumentManager.h"
+#include "core/UBDisplayManager.h"
+
+#include "board/UBBoardView.h"
+#include "board/UBBoardController.h"
+#include "board/UBBoardPaletteManager.h"
+#include "board/UBDrawingController.h"
+
+
+#include "document/UBDocumentProxy.h"
+#include "document/UBDocumentController.h"
+
+#include "domain/UBGraphicsWidgetItem.h"
+
+#include "desktop/UBDesktopPalette.h"
+#include "desktop/UBDesktopAnnotationController.h"
+
+#include "web/UBWebController.h"
+
+#include "gui/UBScreenMirror.h"
+#include "gui/UBMainWindow.h"
+#include "gui/UBDockTeacherGuideWidget.h"
+#include "gui/UBTeacherGuideWidget.h"
+
+#include "domain/UBGraphicsPixmapItem.h"
+
+#include "podcast/UBPodcastController.h"
+
+#include "network/UBNetworkAccessManager.h"
+
+#include "ui_mainWindow.h"
+
+#ifdef Q_WS_MAC
+#include